code:
/*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;

namespace Box2D.XNA
{
    [Flags]
    public enum WorldFlags
    {
        NewFixture  = (1 << 0),
        Locked      = (1 << 1),
        ClearForces = (1 << 2),
    };

    /// The world class manages all physics entities, dynamic simulation,
    /// and asynchronous queries. The world also contains efficient memory
    /// management facilities.
    public class World
    {
        /// ruct a world object.
        /// @param gravity the world gravity vector.
        /// @param doSleep improve performance by not simulating inactive bodies.
        public World(Vector2 gravity, bool doSleep)
        {
            WarmStarting = true;
            ContinuousPhysics = true;

            _allowSleep = doSleep;
            Gravity = gravity;

            _flags = WorldFlags.ClearForces;

            _queryAABBCallbackWrapper = QueryAABBCallbackWrapper;
            _rayCastCallbackWrapper = RayCastCallbackWrapper;
        }

	    /// Register a destruction listener.
	    public IDestructionListener DestructionListener { get; set; }

	    /// Register a contact filter to provide specific control over collision.
	    /// Otherwise the default filter is used (Settings.b2_defaultFilter).
	    public IContactFilter ContactFilter
        {
            get
            {
                return _contactManager.ContactFilter;
            }
            set
            {
                _contactManager.ContactFilter = value;
            }
        }

	    /// Register a contact event listener
	    public IContactListener ContactListener
        {
            get
            {
                return _contactManager.ContactListener;
            }
            set
            {
                _contactManager.ContactListener = value;
            }
        }

	    /// Register a routine for debug drawing. The debug draw functions are called
	    /// inside the World.Step method, so make sure your renderer is ready to
	    /// consume draw commands when you call Step().
	    public DebugDraw DebugDraw { get; set; }

	    /// Create a rigid body given a definition. No reference to the definition
	    /// is retained.
	    /// @warning This function is locked during callbacks.
	    public Body CreateBody(BodyDef def)
        {
            Debug.Assert(!IsLocked);
	        if (IsLocked)
	        {
		        return null;
	        }

	        var b = new Body(def, this);

	        // Add to world doubly linked list.
	        b._prev = null;
	        b._next = _bodyList;
	        if (_bodyList != null)
	        {
		        _bodyList._prev = b;
	        }
	        _bodyList = b;
	        ++_bodyCount;

	        return b;
        }

	    /// Destroy a rigid body given a definition. No reference to the definition
	    /// is retained. This function is locked during callbacks.
	    /// @warning This automatically deletes all associated shapes and joints.
	    /// @warning This function is locked during callbacks.
	    public void DestroyBody(Body b)
        {
            Debug.Assert(_bodyCount > 0);
	        Debug.Assert(!IsLocked);
	        if (IsLocked)
	        {
		        return;
	        }

	        // Delete the attached joints.
	        JointEdge je = b._jointList;
	        while (je != null)
	        {
		        JointEdge je0 = je;
		        je = je.Next;

		        if (DestructionListener != null)
		        {
			        DestructionListener.SayGoodbye(je0.Joint);
		        }

		        DestroyJoint(je0.Joint);
	        }
	        b._jointList = null;

	        // Delete the attached contacts.
	        ContactEdge ce = b._contactList;
	        while (ce != null)
	        {
		        ContactEdge ce0 = ce;
		        ce = ce.Next;
		        _contactManager.Destroy(ce0.Contact);
	        }
	        b._contactList = null;

	        // Delete the attached fixtures. This destroys broad-phase proxies.
	        Fixture f = b._fixtureList;
	        while (f != null)
	        {
		        Fixture f0 = f;
		        f = f._next;

		        if (DestructionListener != null)
		        {
			        DestructionListener.SayGoodbye(f0);
		        }

                f0.DestroyProxies(_contactManager._broadPhase);
		        f0.Destroy();
	        }
	        b._fixtureList = null;
	        b._fixtureCount = 0;

	        // Remove world body list.
	        if (b._prev != null)
	        {
		        b._prev._next = b._next;
	        }

            if (b._next != null)
	        {
		        b._next._prev = b._prev;
	        }

	        if (b == _bodyList)
	        {
		        _bodyList = b._next;
	        }

	        --_bodyCount;
        }

	    /// Create a joint to rain bodies together. No reference to the definition
	    /// is retained. This may cause the connected bodies to cease colliding.
	    /// @warning This function is locked during callbacks.
	    public Joint CreateJoint(JointDef def)
        {
	        Debug.Assert(!IsLocked);
	        if (IsLocked)
	        {
		        return null;
	        }

	        Joint j = Joint.Create(def);

	        // Connect to the world list.
	        j._prev = null;
	        j._next = _jointList;
	        if (_jointList != null)
	        {
		        _jointList._prev = j;
	        }
	        _jointList = j;
	        ++_jointCount;

	        // Connect to the bodies' doubly linked lists.
	        j._edgeA.Joint = j;
	        j._edgeA.Other = j._bodyB;
	        j._edgeA.Prev = null;
	        j._edgeA.Next = j._bodyA._jointList;

	        if (j._bodyA._jointList != null)
                j._bodyA._jointList.Prev = j._edgeA;

	        j._bodyA._jointList = j._edgeA;

	        j._edgeB.Joint = j;
	        j._edgeB.Other = j._bodyA;
	        j._edgeB.Prev = null;
	        j._edgeB.Next = j._bodyB._jointList;

	        if (j._bodyB._jointList != null)
                j._bodyB._jointList.Prev = j._edgeB;

	        j._bodyB._jointList = j._edgeB;

	        Body bodyA = def.bodyA;
	        Body bodyB = def.bodyB;

	        bool staticA = bodyA.GetType() == BodyType.Static;
	        bool staticB = bodyB.GetType() == BodyType.Static;

	        // If the joint prevents collisions, then flag any contacts for filtering.
	        if (def.collideConnected == false)
	        {
		        ContactEdge edge = bodyB.GetContactList();
		        while (edge != null)
		        {
			        if (edge.Other == bodyA)
			        {
				        // Flag the contact for filtering at the next time step (where either
				        // body is awake).
				        edge.Contact.FlagForFiltering();
			        }

			        edge = edge.Next;
		        }
	        }

	        // Note: creating a joint doesn't wake the bodies.

	        return j;
        }

	    /// Destroy a joint. This may cause the connected bodies to begin colliding.
	    /// @warning This function is locked during callbacks.
	    public void DestroyJoint(Joint j)
        {
	        Debug.Assert(!IsLocked);
	        if (IsLocked)
	        {
		        return;
	        }

	        bool collideConnected = j._collideConnected;

	        // Remove from the doubly linked list.
	        if (j._prev != null)
	        {
		        j._prev._next = j._next;
	        }

	        if (j._next != null)
	        {
		        j._next._prev = j._prev;
	        }

	        if (j == _jointList)
	        {
		        _jointList = j._next;
	        }

	        // Disconnect from island graph.
	        Body bodyA = j._bodyA;
	        Body bodyB = j._bodyB;

	        // Wake up connected bodies.
	        bodyA.SetAwake(true);
	        bodyB.SetAwake(true);

	        // Remove from body 1.
	        if (j._edgeA.Prev != null)
	        {
		        j._edgeA.Prev.Next = j._edgeA.Next;
	        }

	        if (j._edgeA.Next != null)
	        {
		        j._edgeA.Next.Prev = j._edgeA.Prev;
	        }

	        if (j._edgeA == bodyA._jointList)
	        {
		        bodyA._jointList = j._edgeA.Next;
	        }

	        j._edgeA.Prev = null;
	        j._edgeA.Next = null;

	        // Remove from body 2
	        if (j._edgeB.Prev != null)
	        {
		        j._edgeB.Prev.Next = j._edgeB.Next;
	        }

	        if (j._edgeB.Next != null)
	        {
		        j._edgeB.Next.Prev = j._edgeB.Prev;
	        }

	        if (j._edgeB == bodyB._jointList)
	        {
		        bodyB._jointList = j._edgeB.Next;
	        }

	        j._edgeB.Prev = null;
	        j._edgeB.Next = null;

	        Debug.Assert(_jointCount > 0);
	        --_jointCount;

	        // If the joint prevents collisions, then flag any contacts for filtering.
	        if (collideConnected == false)
	        {
		        ContactEdge edge = bodyB.GetContactList();
		        while (edge != null)
		        {
			        if (edge.Other == bodyA)
			        {
				        // Flag the contact for filtering at the next time step (where either
				        // body is awake).
				        edge.Contact.FlagForFiltering();
			        }

			        edge = edge.Next;
		        }
	        }
        }

	    /// Take a time step. This performs collision detection, integration,
	    /// and raint solution.
	    /// @param timeStep the amount of time to simulate, this should not vary.
	    /// @param velocityIterations for the velocity raint solver.
	    /// @param positionIterations for the position raint solver.
	    public void Step(float dt, int velocityIterations, int positionIterations)
        {
	        // If new fixtures were added, we need to find the new contacts.
	        if ((_flags & WorldFlags.NewFixture) == WorldFlags.NewFixture)
	        {
		        _contactManager.FindNewContacts();
		        _flags &= ~WorldFlags.NewFixture;
	        }

	        _flags |= WorldFlags.Locked;

	        TimeStep step;
	        step.dt = dt;
	        step.velocityIterations	= velocityIterations;
	        step.positionIterations = positionIterations;
	        if (dt > 0.0f)
	        {
		        step.inv_dt = 1.0f / dt;
	        }
	        else
	        {
		        step.inv_dt = 0.0f;
	        }

	        step.dtRatio = _inv_dt0 * dt;

	        step.warmStarting = WarmStarting;

	        // Update contacts. This is where some contacts are destroyed.
	        _contactManager.Collide();

	        // Integrate velocities, solve velocity raints, and integrate positions.
	        if (step.dt > 0.0f)
	        {
		        Solve(ref step);
	        }

	        // Handle TOI events.
	        if (ContinuousPhysics && step.dt > 0.0f)
	        {
		        SolveTOI();
	        }

	        if (step.dt > 0.0f)
	        {
		        _inv_dt0 = step.inv_dt;
	        }

            if ((_flags & WorldFlags.ClearForces) != 0)
            {
                ClearForces();
            }

	        _flags &= ~WorldFlags.Locked;
        }

        /// Call this after you are done with time steps to clear the forces. You normally
	    /// call this after each call to Step, unless you are performing sub-steps. By default,
	    /// forces will be automatically cleared, so you don't need to call this function.
	    /// @see SetAutoClearForces
        public void ClearForces()
        {
            for (Body body = _bodyList; body != null; body = body.GetNext())
            {
                body._force = Vector2.Zero;
                body._torque = 0.0f;
            }
        }

        /// Set flag to control automatic clearing of forces after each time step.
	    void SetAutoClearForces(bool flag)
        {
            if (flag)
            {
                _flags |= WorldFlags.ClearForces;
            }
            else
            {
                _flags &= ~WorldFlags.ClearForces;
            }
        }

	    /// Get the flag that controls automatic clearing of forces after each time step.
        bool GetAutoClearForces()
        {
            return (_flags & WorldFlags.ClearForces) == WorldFlags.ClearForces;
        }

        /// Get the contact manager for testing.
        public ContactManager GetContactManager()
        {
            return _contactManager;
        }

	    /// Call this to draw shapes and other debug draw data.
	    public void DrawDebugData()
        {
	        if (DebugDraw == null)
	        {
		        return;
	        }

	        DebugDrawFlags flags = DebugDraw.Flags;

	        if ((flags & DebugDrawFlags.Shape) == DebugDrawFlags.Shape)
	        {
		        for (Body b = _bodyList; b != null; b = b.GetNext())
		        {
                    Transform xf;
                    b.GetTransform(out xf);
			        for (Fixture f = b.GetFixtureList(); f != null; f = f.GetNext())
			        {
                        if (b.IsActive() == false)
                        {
                            DrawShape(f, xf, new Color(0.5f, 0.5f, 0.3f));
                        }
                        else if (b.GetType() == BodyType.Static)
                        {
                            DrawShape(f, xf, new Color(0.5f, 0.9f, 0.5f));
                        }
                        else if (b.GetType() == BodyType.Kinematic)
                        {
                            DrawShape(f, xf, new Color(0.5f, 0.5f, 0.9f));
                        }
				        else if (b.IsAwake() == false)
				        {
					        DrawShape(f, xf, new Color(0.6f, 0.6f, 0.6f));
				        }
				        else
				        {
					        DrawShape(f, xf, new Color(0.9f, 0.7f, 0.7f));
				        }
			        }
		        }
	        }

	        if ((flags & DebugDrawFlags.Joint) == DebugDrawFlags.Joint)
	        {
		        for (Joint j = _jointList; j != null; j = j.GetNext())
		        {
				    DrawJoint(j);
		        }
	        }

	        if ((flags & DebugDrawFlags.Pair) == DebugDrawFlags.Pair)
	        {
		        Color color = new Color(0.3f, 0.9f, 0.9f);
		        for (Contact c = _contactManager._contactList; c != null; c = c.GetNext())
		        {
			      /*
                   Fixture fixtureA = c.GetFixtureA();
			       Fixture fixtureB = c.GetFixtureB();

                   AABB aabbA;
                   AABB aabbB;
                   fixtureA.GetAABB(out aabbA);
                   fixtureB.GetAABB(out aabbB);

                   Vector2 cA = aabbA.GetCenter();
                   Vector2 cB = aabbB.GetCenter();

                   DebugDraw.DrawSegment(cA, cB, color);
                  */
		        }
	        }

	        if ((flags & DebugDrawFlags.AABB) == DebugDrawFlags.AABB)
	        {
		        Color color = new Color(0.9f, 0.3f, 0.9f);
		        BroadPhase bp = _contactManager._broadPhase;

		        for (Body b = _bodyList; b != null; b = b.GetNext())
		        {
                    if (b.IsActive() == false)
			        {
				        continue;
			        }

			        for (Fixture f = b.GetFixtureList(); f != null; f = f.GetNext())
			        {
                        for (int i = 0; i < f._proxyCount; ++i)
				        {
					        FixtureProxy proxy = f._proxies[i];
					        AABB aabb;
                            bp.GetFatAABB(proxy.proxyId, out aabb);
                            FixedArray8<Vector2> vs = new FixedArray8<Vector2>();
					        vs[0] = new Vector2(aabb.lowerBound.X, aabb.lowerBound.Y);
					        vs[1] = new Vector2(aabb.upperBound.X, aabb.lowerBound.Y);
					        vs[2] = new Vector2(aabb.upperBound.X, aabb.upperBound.Y);
					        vs[3] = new Vector2(aabb.lowerBound.X, aabb.upperBound.Y);

					        DebugDraw.DrawPolygon(ref vs, 4, color);
				        }
			        }
		        }
	        }

	        if ((flags & DebugDrawFlags.CenterOfMass) == DebugDrawFlags.CenterOfMass)
	        {
		        for (Body b = _bodyList; b != null; b = b.GetNext())
		        {
                    Transform xf;
                    b.GetTransform(out xf);
			        xf.Position = b.GetWorldCenter();
			        DebugDraw.DrawTransform(ref xf);
		        }
	        }
        }

	    /// Query the world for all fixtures that potentially overlap the
	    /// provided AABB.
	    /// @param callback a user implemented callback class.
	    /// @param aabb the query box.
	    public void QueryAABB(Func<FixtureProxy, bool> callback, ref AABB aabb)
        {
            _queryAABBCallback = callback;
            _contactManager._broadPhase.Query(_queryAABBCallbackWrapper, ref aabb);
            _queryAABBCallback = null;
        }

        Func<FixtureProxy, bool> _queryAABBCallback;
        Func<int, bool> _queryAABBCallbackWrapper;

        bool QueryAABBCallbackWrapper(int proxyId)
        {
            FixtureProxy proxy = (FixtureProxy)_contactManager._broadPhase.GetUserData(proxyId);
            return _queryAABBCallback(proxy);
        }

        /// Ray-cast the world for all fixtures in the path of the ray. Your callback
	    /// controls whether you get the closest point, any point, or n-points.
	    /// The ray-cast ignores shapes that contain the starting point.
	    /// @param callback a user implemented callback class.
	    /// @param point1 the ray starting point
	    /// @param point2 the ray ending point
        public void RayCast(RayCastCallback callback, Vector2 point1, Vector2 point2)
        {
            RayCastInput input = new RayCastInput();
            input.maxFraction = 1.0f;
            input.p1 = point1;
            input.p2 = point2;

            _rayCastCallback = callback;
            _contactManager._broadPhase.RayCast(_rayCastCallbackWrapper, ref input);
            _rayCastCallback = null;
        }

        RayCastCallback _rayCastCallback;
        RayCastCallbackInternal _rayCastCallbackWrapper;

        float RayCastCallbackWrapper(ref RayCastInput input, int proxyId)
	    {
		    object userData = _contactManager._broadPhase.GetUserData(proxyId);
            FixtureProxy proxy = (FixtureProxy)userData;
            Fixture fixture = proxy.fixture;
            int index = proxy.childIndex;
		    RayCastOutput output;
		    bool hit = fixture.RayCast(out output, ref input, index);

		    if (hit)
		    {
			    float fraction = output.fraction;
			    Vector2 point = (1.0f - fraction) * input.p1 + fraction * input.p2;
                return _rayCastCallback(fixture, point, output.normal, fraction);
		    }

		    return input.maxFraction;
	    }

	    /// Get the world body list. With the returned body, use Body.GetNext to get
	    /// the next body in the world list. A null body indicates the end of the list.
	    /// @return the head of the world body list.
	    public Body GetBodyList()
        {
            return _bodyList;
        }

	    /// Get the world joint list. With the returned joint, use Joint.GetNext to get
	    /// the next joint in the world list. A null joint indicates the end of the list.
	    /// @return the head of the world joint list.
	    public Joint GetJointList()
        {
            return _jointList;
        }

	    /// Get the world contact list. With the returned contact, use Contact.GetNext to get
	    /// the next contact in the world list. A null contact indicates the end of the list.
	    /// @return the head of the world contact list.
	    /// @warning contacts are
	    public Contact GetContactList()
        {
            return _contactManager._contactList;
        }

	    /// Enable/disable warm starting. For testing.
	    public bool WarmStarting { get; set; }

	    /// Enable/disable continuous physics. For testing.
	    public bool ContinuousPhysics { get; set; }

	    /// Get the number of broad-phase proxies.
	    public int ProxyCount
        {
            get
            {
                return _contactManager._broadPhase.ProxyCount;
            }
        }

	    /// Get the number of bodies.
	    public int BodyCount
        {
            get
            {
                return _bodyCount;
            }
        }

	    /// Get the number of joints.
	    public int JointCount
        {
            get
            {
                return _jointCount;
            }
        }
	    /// Get the number of contacts (each may have 0 or more contact points).
	    public int ContactCount
        {
            get
            {
                return _contactManager._contactCount;
            }
        }

	    /// Change the global gravity vector.
	    public Vector2 Gravity { get; set; }

	    /// Is the world locked (in the middle of a time step).
	    public bool IsLocked
        {
            get
            {
                return (_flags & WorldFlags.Locked) == WorldFlags.Locked;
            }
            set
            {
                if (value)
                {
                    _flags |= WorldFlags.Locked;
                }
                else
                {
                    _flags &= ~WorldFlags.Locked;
                }
            }
        }

	    void Solve(ref TimeStep step)
        {
	        // Size the island for the worst case.
            _island.Reset(_bodyCount,
	                      _contactManager._contactCount,
	                      _jointCount,
	                      _contactManager.ContactListener);

	        // Clear all the island flags.
	        for (Body b = _bodyList; b != null; b = b._next)
	        {
		        b._flags &= ~BodyFlags.Island;
	        }
	        for (Contact c = _contactManager._contactList; c != null; c = c._next)
	        {
		        c._flags &= ~ContactFlags.Island;
	        }
	        for (Joint j = _jointList; j != null; j = j._next)
	        {
		        j._islandFlag = false;
	        }

	        // Build and simulate all awake islands.
            int stackSize = _bodyCount;
	        if (stackSize > stack.Length)
                stack = new Body[Math.Max(stack.Length * 2, stackSize)];

	        for (Body seed = _bodyList; seed != null; seed = seed._next)
	        {
		        if ((seed._flags & (BodyFlags.Island)) != BodyFlags.None)
		        {
			        continue;
		        }

		        if (seed.IsAwake() == false || seed.IsActive() == false)
		        {
			        continue;
		        }

                // The seed can be dynamic or kinematic.
                if (seed.GetType() == BodyType.Static)
                {
                    continue;
                }

		        // Reset island and stack.
		        _island.Clear();
		        int stackCount = 0;
		        stack[stackCount++] = seed;
		        seed._flags |= BodyFlags.Island;

		        // Perform a depth first search (DFS) on the raint graph.
		        while (stackCount > 0)
		        {
			        // Grab the next body off the stack and add it to the island.
			        Body b = stack[--stackCount];
                    Debug.Assert(b.IsActive() == true);
			        _island.Add(b);

			        // Make sure the body is awake.
                    b.SetAwake(true);

			        // To keep islands as small as possible, we don't
			        // propagate islands across static bodies.
			        if (b.GetType() == BodyType.Static)
			        {
				        continue;
			        }

			        // Search all contacts connected to this body.
			        for (ContactEdge ce = b._contactList; ce != null; ce = ce.Next)
			        {
                        Contact contact = ce.Contact;

				        // Has this contact already been added to an island?
                        if ((contact._flags & ContactFlags.Island) != ContactFlags.None)
				        {
					        continue;
				        }

                        // Is this contact solid and touching?
                        if (!ce.Contact.IsEnabled() || !ce.Contact.IsTouching())
				        {
					        continue;
				        }

                        // Skip sensors.
                        bool sensorA = contact._fixtureA._isSensor;
                        bool sensorB = contact._fixtureB._isSensor;
                        if (sensorA || sensorB)
                        {
                            continue;
                        }

                        _island.Add(contact);
        				contact._flags |= ContactFlags.Island;

				        Body other = ce.Other;

				        // Was the other body already added to this island?
				        if ((other._flags & BodyFlags.Island) != BodyFlags.None)
				        {
					        continue;
				        }

				        Debug.Assert(stackCount < stackSize);
				        stack[stackCount++] = other;
				        other._flags |= BodyFlags.Island;
			        }

			        // Search all joints connect to this body.
			        for (JointEdge je = b._jointList; je != null; je = je.Next)
			        {
				        if (je.Joint._islandFlag == true)
				        {
					        continue;
				        }

				        Body other = je.Other;

                        // Don't simulate joints connected to inactive bodies.
                        if (other.IsActive() == false)
                        {
                            continue;
                        }

                        _island.Add(je.Joint);
                        je.Joint._islandFlag = true;

				        if ((other._flags & BodyFlags.Island) != BodyFlags.None)
				        {
					        continue;
				        }

				        Debug.Assert(stackCount < stackSize);
				        stack[stackCount++] = other;
				        other._flags |= BodyFlags.Island;
			        }
		        }

		        _island.Solve(ref step, Gravity, _allowSleep);

		        // Post solve cleanup.
		        for (int i = 0; i < _island._bodyCount; ++i)
		        {
			        // Allow static bodies to participate in other islands.
			        Body b = _island._bodies[i];
			        if (b.GetType() == BodyType.Static)
			        {
				        b._flags &= ~BodyFlags.Island;
			        }
		        }
	        }

	        // Synchronize fixtures, check for out of range bodies.
	        for (Body b = _bodyList; b != null; b = b.GetNext())
	        {
		        // If a body was not in an island then it did not move.
                if ((b._flags & BodyFlags.Island) != BodyFlags.Island)
		        {
			        continue;
		        }

                if (b.GetType() == BodyType.Static)
		        {
			        continue;
		        }

		        // Update fixtures (for broad-phase).
		        b.SynchronizeFixtures();
	        }

	        // Look for new contacts.
	        _contactManager.FindNewContacts();
        }

        // Advance a dynamic body to its first time of contact
        // and adjust the position to ensure clearance.
        void SolveTOI(Body body)
        {
	        // Find the minimum contact.
	        Contact toiContact = null;
	        float toi = 1.0f;
            Body toiOther = null;
	        bool found;
	        int count;
	        int iter = 0;

	        bool bullet = body.IsBullet;

	        // Iterate until all contacts agree on the minimum TOI. We have
	        // to iterate because the TOI algorithm may skip some intermediate
	        // collisions when objects rotate through each other.
	        do
	        {
		        count = 0;
		        found = false;
		        for (ContactEdge ce = body._contactList; ce != null; ce = ce.Next)
		        {
                    if (ce.Contact == toiContact)
                    {
                        continue;
                    }

			        Body other = ce.Other;
			        BodyType type = other.GetType();

			        // Only bullets perform TOI with dynamic bodies.
			        if (bullet == true)
			        {
				        // Bullets only perform TOI with bodies that have their TOI resolved.
				        if ((other._flags & BodyFlags.Toi) == 0)
				        {
					        continue;
				        }

                        // No repeated hits on non-static bodies
				        if (type != BodyType.Static && (ce.Contact._flags & ContactFlags.BulletHit) != 0)
				        {
						    continue;
				        }
			        }
			        else if (type == BodyType.Dynamic)
			        {
				        continue;
			        }

			        // Check for a disabled contact.
			        Contact contact = ce.Contact;
			        if (contact.IsEnabled() == false)
			        {
				        continue;
			        }

			        // Prevent infinite looping.
			        if (contact._toiCount > 10)
			        {
				        continue;
			        }

			        Fixture fixtureA = contact._fixtureA;
			        Fixture fixtureB = contact._fixtureB;
                    int indexA = contact._indexA;
			        int indexB = contact._indexB;

			        // Cull sensors.
			        if (fixtureA.IsSensor() || fixtureB.IsSensor())
			        {
				        continue;
			        }

			        Body bodyA = fixtureA._body;
			        Body bodyB = fixtureB._body;

			        // Compute the time of impact in interval [0, minTOI]
			        TOIInput input = new TOIInput();
			        input.proxyA.Set(fixtureA.GetShape(), indexA);
			        input.proxyB.Set(fixtureB.GetShape(), indexB);
			        input.sweepA = bodyA._sweep;
			        input.sweepB = bodyB._sweep;
			        input.tMax = toi;

			        TOIOutput output;
			        TimeOfImpact.CalculateTimeOfImpact(out output, ref input);

			        if (output.State == TOIOutputState.Touching && output.t < toi)
			        {
				        toiContact = contact;
				        toi = output.t;
                        toiOther = other;
				        found = true;
			        }

			        ++count;
		        }

		        ++iter;
	        } while (found && count > 1 && iter < 50);

	        if (toiContact == null)
	        {
                body.Advance(1.0f);
		        return;
	        }

	        Sweep backup = body._sweep;
	        body.Advance(toi);
            toiContact.Update(_contactManager.ContactListener);
	        if (toiContact.IsEnabled() == false)
	        {
		        // Contact disabled. Backup and recurse.
		        body._sweep = backup;
		        SolveTOI(body);
	        }

	        ++toiContact._toiCount;

	        // Update all the valid contacts on this body and build a contact island.
	        count = 0;
	        for (ContactEdge ce = body._contactList; (ce != null) && (count < Settings.b2_maxTOIContacts); ce = ce.Next)
	        {
		        Body other = ce.Other;
		        BodyType type = other.GetType();

                // Only perform correction with static bodies, so the
                // body won't get pushed out of the world.
		        if (type == BodyType.Dynamic)
		        {
			        continue;
		        }

		        // Check for a disabled contact.
		        Contact contact = ce.Contact;
		        if (contact.IsEnabled() == false)
		        {
			        continue;
		        }

		        Fixture fixtureA = contact._fixtureA;
		        Fixture fixtureB = contact._fixtureB;

		        // Cull sensors.
		        if (fixtureA.IsSensor() || fixtureB.IsSensor())
		        {
			        continue;
		        }

		        // The contact likely has some new contact points. The listener
		        // gives the user a chance to disable the contact.
		        if (contact != toiContact)
		        {
			        contact.Update(_contactManager.ContactListener);
		        }

		        // Did the user disable the contact?
		        if (contact.IsEnabled() == false)
		        {
			        // Skip this contact.
			        continue;
		        }

		        if (contact.IsTouching() == false)
		        {
			        continue;
		        }

		        _toiContacts[count] = contact;
		        ++count;
	        }

	        // Reduce the TOI body's overlap with the contact island.
	        _toiSolver.Initialize(_toiContacts, count, body);

	        float k_toiBaumgarte = 0.75f;
	        //bool solved = false;
	        for (int i = 0; i < 20; ++i)
	        {
		        bool contactsOkay = _toiSolver.Solve(k_toiBaumgarte);
		        if (contactsOkay)
		        {
			        //solved = true;
			        break;
		        }
	        }

            if (toiOther.GetType() != BodyType.Static)
	        {
		        toiContact._flags |= ContactFlags.BulletHit;
	        }
        }

        // Sequentially solve TOIs for each body. We bring each
        // body to the time of contact and perform some position correction.
        // Time is not conserved.
        void SolveTOI()
        {
	        // Prepare all contacts.
	        for (Contact c = _contactManager._contactList; c != null; c = c._next)
	        {
		        // Enable the contact
		        c._flags |= ContactFlags.Enabled;

		        // Set the number of TOI events for this contact to zero.
		        c._toiCount = 0;
	        }

	        // Initialize the TOI flag.
	        for (Body body = _bodyList; body != null; body = body._next)
	        {
		        // Kinematic, and static bodies will not be affected by the TOI event.
		        // If a body was not in an island then it did not move.
		        if ((body._flags & BodyFlags.Island) == 0 || body.GetType() == BodyType.Kinematic || body.GetType() == BodyType.Static)
		        {
			        body._flags |= BodyFlags.Toi;
		        }
		        else
		        {
			        body._flags &= ~BodyFlags.Toi;
		        }
	        }

	        // Collide non-bullets.
	        for (Body body = _bodyList; body != null; body = body._next)
	        {
		        if ((body._flags & BodyFlags.Toi) != BodyFlags.None)
		        {
			        continue;
		        }

		        if (body.IsBullet == true)
		        {
			        continue;
		        }

		        SolveTOI(body);

		        body._flags |= BodyFlags.Toi;
	        }

	        // Collide bullets.
	        for (Body body = _bodyList; body != null; body = body._next)
	        {
                if ((body._flags & BodyFlags.Toi) != BodyFlags.None)
		        {
			        continue;
		        }

		        if (body.IsBullet == false)
		        {
			        continue;
		        }

		        SolveTOI(body);

		        body._flags |= BodyFlags.Toi;
	        }
        }

	    void DrawJoint(Joint joint)
        {
	        Body b1 = joint.GetBodyA();
	        Body b2 = joint.GetBodyB();
            Transform xf1, xf2;
            b1.GetTransform(out xf1);
	        b2.GetTransform(out xf2);
	        Vector2 x1 = xf1.Position;
	        Vector2 x2 = xf2.Position;
	        Vector2 p1 = joint.GetAnchorA();
	        Vector2 p2 = joint.GetAnchorB();

	        Color color = new Color(0.5f, 0.8f, 0.8f);

	        switch (joint.JointType)
	        {
	        case JointType.Distance:
		        DebugDraw.DrawSegment(p1, p2, color);
		        break;

	        case JointType.Pulley:
		        {
			        PulleyJoint pulley = (PulleyJoint)joint;
			        Vector2 s1 = pulley.GetGroundAnchorA();
			        Vector2 s2 = pulley.GetGroundAnchorB();
			        DebugDraw.DrawSegment(s1, p1, color);
			        DebugDraw.DrawSegment(s2, p2, color);
			        DebugDraw.DrawSegment(s1, s2, color);
		        }
		        break;

	        case JointType.Mouse:
		        // don't draw this
		        break;

	        default:
		        DebugDraw.DrawSegment(x1, p1, color);
		        DebugDraw.DrawSegment(p1, p2, color);
		        DebugDraw.DrawSegment(x2, p2, color);
                break;
	        }
        }

	    void DrawShape(Fixture fixture, Transform xf, Color color)
        {
	        switch (fixture.ShapeType)
	        {
	        case ShapeType.Circle:
		        {
			        CircleShape circle = (CircleShape)fixture.GetShape();

			        Vector2 center = MathUtils.Multiply(ref xf, circle._p);
			        float radius = circle._radius;
			        Vector2 axis = xf.R.col1;

			        DebugDraw.DrawSolidCircle(center, radius, axis, color);
		        }
		        break;

	        case ShapeType.Polygon:
		        {
			        PolygonShape poly = (PolygonShape)fixture.GetShape();
			        int vertexCount = poly._vertexCount;
			        Debug.Assert(vertexCount <= Settings.b2_maxPolygonVertices);
			        FixedArray8<Vector2> vertices = new FixedArray8<Vector2>();

			        for (int i = 0; i < vertexCount; ++i)
			        {
				        vertices[i] = MathUtils.Multiply(ref xf, poly._vertices[i]);
			        }

			        DebugDraw.DrawSolidPolygon(ref vertices, vertexCount, color);
		        }
		        break;

            case ShapeType.Edge:
		        {
			        EdgeShape edge = (EdgeShape)fixture.GetShape();
			        Vector2 v1 = MathUtils.Multiply(ref xf, edge._vertex1);
			        Vector2 v2 = MathUtils.Multiply(ref xf, edge._vertex2);
			        DebugDraw.DrawSegment(v1, v2, color);
		        }
		        break;

	        case ShapeType.Loop:
		        {
			        LoopShape loop = (LoopShape)fixture.GetShape();
			        int count = loop._count;

			        Vector2 v1 = MathUtils.Multiply(ref xf, loop._vertices[count - 1]);
			        for (int i = 0; i < count; ++i)
			        {
				        Vector2 v2 = MathUtils.Multiply(ref xf, loop._vertices[i]);
				        DebugDraw.DrawSegment(v1, v2, color);
				        v1 = v2;
			        }
		        }
		        break;
	        }
        }

        TOISolver _toiSolver = new TOISolver();
        Contact[] _toiContacts = new Contact[Settings.b2_maxTOIContacts];
        internal Island _island = new Island();
        internal WorldFlags _flags;

	    internal ContactManager _contactManager = new ContactManager();
        internal Queue<Contact> _contactPool = new Queue<Contact>(256);

        internal Body _bodyList;
        internal Joint _jointList;

        internal int _bodyCount;
        internal int _jointCount;

        internal bool _allowSleep;

        internal Body _groundBody;

	    // This is used to compute the time step ratio to
	    // support a variable time step.
        internal float _inv_dt0;

        Body[] stack = new Body[64];
    }
}


code:
/*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Box2D.XNA
{
    /// Called for each fixture found in the query. You control how the ray cast
    /// proceeds by returning a float:
    /// return -1: ignore this fixture and continue
    /// return 0: terminate the ray cast
    /// return fraction: clip the ray to this point
    /// return 1: don't clip the ray and continue
    /// @param fixture the fixture hit by the ray
    /// @param point the point of initial intersection
    /// @param normal the normal vector at the point of intersection
    /// @return -1 to filter, 0 to terminate, fraction to clip the ray for
    /// closest hit, 1 to continue
    public delegate float RayCastCallback(Fixture fixture, Vector2 point, Vector2 normal, float fraction);

    public interface IDestructionListener
    {
        void SayGoodbye(Joint joint);
        void SayGoodbye(Fixture fixture);
    }

    public interface IContactFilter
    {
        bool ShouldCollide(Fixture fixtureA, Fixture fixtureB);
    }

    public class DefaultContactFilter : IContactFilter
    {
        public bool ShouldCollide(Fixture fixtureA, Fixture fixtureB)
        {
            Filter filterA;
            fixtureA.GetFilterData(out filterA);

            Filter filterB;
            fixtureB.GetFilterData(out filterB);

	        if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0)
	        {
		        return filterA.groupIndex > 0;
	        }

	        bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0;

            return collide;
        }
    }

    public struct ContactImpulse
    {
        public FixedArray2<float> normalImpulses;
        public FixedArray2<float> tangentImpulses;
    }

    public interface IContactListener
    {
        void BeginContact(Contact contact);
        void EndContact(Contact contact);
        void PreSolve(Contact contact, ref Manifold oldManifold);
        void PostSolve(Contact contact, ref ContactImpulse impulse);
    }

    public class DefaultContactListener : IContactListener
    {
        public void BeginContact(Contact contact) { }
        public void EndContact(Contact contact) { }
        public void PreSolve(Contact contact, ref Manifold oldManifold) { }
        public void PostSolve(Contact contact, ref ContactImpulse impulse) { }
    }

    [Flags]
    public enum DebugDrawFlags
    {
	    Shape			= (1 << 0), ///< draw shapes
	    Joint			= (1 << 1), ///< draw joint connections
	    AABB			= (1 << 2), ///< draw axis aligned bounding boxes
	    Pair			= (1 << 3), ///< draw broad-phase pairs
	    CenterOfMass	= (1 << 4), ///< draw center of mass frame
    };

    /// Implement and register this class with a World to provide debug drawing of physics
    /// entities in your game.
    public abstract class DebugDraw
    {
	    public DebugDrawFlags Flags { get; set; }

	    /// Append flags to the current flags.
	    public void AppendFlags(DebugDrawFlags flags)
        {
            Flags |= flags;
        }

	    /// Clear flags from the current flags.
	    public  void ClearFlags(DebugDrawFlags flags)
        {
            Flags &= ~flags;
        }

	    /// Draw a closed polygon provided in CCW order.
	    public abstract void DrawPolygon(ref FixedArray8<Vector2> vertices, int count, Color color);

	    /// Draw a solid closed polygon provided in CCW order.
        public abstract void DrawSolidPolygon(ref FixedArray8<Vector2> vertices, int count, Color color);

	    /// Draw a circle.
        public abstract void DrawCircle(Vector2 center, float radius, Color color);

	    /// Draw a solid circle.
        public abstract void DrawSolidCircle(Vector2 center, float radius, Vector2 axis, Color color);

	    /// Draw a line segment.
        public abstract void DrawSegment(Vector2 p1, Vector2 p2, Color color);

	    /// Draw a transform. Choose your own length scale.
	    /// @param xf a transform.
        public abstract void DrawTransform(ref Transform xf);
    }
}

repo_name: snapshot/xnamototrialracer

license: unknown


code:
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
    <Deployment.Parts>
    </Deployment.Parts>
</Deployment>


code:
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Box2D.XNA")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Box2D.XNA")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: InternalsVisibleTo("Box2D.XNA.TestBed")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ed667df3-0a02-4276-b93e-d4cc50476d6e")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]


code:
<?xml version="1.0" encoding="utf-8" ?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
  <App xmlns="" ProductID="{066846be-aaea-4eb6-baa8-2d6b60b3bdb3}" Title="Box2D.XNA" RuntimeType="XNA" Version="1.0.0.0" Genre="Apps.Normal" Author="" Description="" Publisher="">
    <IconPath IsRelative="true" IsResource="false"></IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_LOCATION" />
      <Capability Name="ID_CAP_SENSORS" />
      <Capability Name="ID_CAP_MICROPHONE" />
      <Capability Name="ID_CAP_MEDIALIB" />
      <Capability Name="ID_CAP_GAMERSERVICES" />
      <Capability Name="ID_CAP_PHONEDIALER" />
      <Capability Name="ID_CAP_PUSH_NOTIFICATION" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
      <Capability Name="ID_CAP_IDENTITY_USER" />
      <Capability Name="ID_CAP_IDENTITY_DEVICE" />
    </Capabilities>
    <Tasks>
      <DefaultTask Name="_default"/>
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="Box2D.XNAToken" TaskName="_default">
        <TemplateType5>
          <BackgroundImageURI IsRelative="true" IsResource="false"></BackgroundImageURI>
          <Count>0</Count>
          <Title></Title>
        </TemplateType5>
      </PrimaryToken>
    </Tokens>
  </App>
</Deployment>


code:
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010 Express for Windows Phone
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotoTrialRacer", "MotoTrialRacer\MotoTrialRacer\MotoTrialRacer.csproj", "{AA22069A-4109-4E67-BFA1-473BECB8C98F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotoTrialRacerContent", "MotoTrialRacer\MotoTrialRacerContent\MotoTrialRacerContent.contentproj", "{0515B61A-F0EA-468A-8D35-0DF3A043A158}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Box2D.XNA - wp7", "Box2D.XNA\Box2D.XNA - wp7.csproj", "{066846BE-AAEA-4EB6-BAA8-2D6B60B3BDB3}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Windows Phone = Debug|Windows Phone
		Release|Windows Phone = Release|Windows Phone
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{AA22069A-4109-4E67-BFA1-473BECB8C98F}.Debug|Windows Phone.ActiveCfg = Debug|Windows Phone
		{AA22069A-4109-4E67-BFA1-473BECB8C98F}.Debug|Windows Phone.Build.0 = Debug|Windows Phone
		{AA22069A-4109-4E67-BFA1-473BECB8C98F}.Debug|Windows Phone.Deploy.0 = Debug|Windows Phone
		{AA22069A-4109-4E67-BFA1-473BECB8C98F}.Release|Windows Phone.ActiveCfg = Release|Windows Phone
		{AA22069A-4109-4E67-BFA1-473BECB8C98F}.Release|Windows Phone.Build.0 = Release|Windows Phone
		{AA22069A-4109-4E67-BFA1-473BECB8C98F}.Release|Windows Phone.Deploy.0 = Release|Windows Phone
		{0515B61A-F0EA-468A-8D35-0DF3A043A158}.Debug|Windows Phone.ActiveCfg = Debug|Windows Phone
		{0515B61A-F0EA-468A-8D35-0DF3A043A158}.Release|Windows Phone.ActiveCfg = Release|Windows Phone
		{066846BE-AAEA-4EB6-BAA8-2D6B60B3BDB3}.Debug|Windows Phone.ActiveCfg = Debug|Windows Phone
		{066846BE-AAEA-4EB6-BAA8-2D6B60B3BDB3}.Debug|Windows Phone.Build.0 = Debug|Windows Phone
		{066846BE-AAEA-4EB6-BAA8-2D6B60B3BDB3}.Release|Windows Phone.ActiveCfg = Release|Windows Phone
		{066846BE-AAEA-4EB6-BAA8-2D6B60B3BDB3}.Release|Windows Phone.Build.0 = Release|Windows Phone
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Audio;

namespace MotoTrialRacer
{
    /// <summary>
    /// The class for handling all the audio
    /// </summary>
    public class AudioPlayer
    {
        private SoundEffect music;
        private SoundEffect motor;
        private SoundEffect ouch;
        private SoundEffect blast;
        private SoundEffect fanfare;
        private SoundEffectInstance musicInstance;
        private SoundEffectInstance motorInstance;
        private SoundEffectInstance fanfareInstance;

        /// <summary>
        /// Loads all the audio files and creates the needed instances
        /// </summary>
        /// <param name="content"></param>
        public AudioPlayer(ContentManager content)
        {
            music = content.Load<SoundEffect>("Sounds/music");
            motor = content.Load<SoundEffect>("Sounds/motor2");
            ouch = content.Load<SoundEffect>("Sounds/ouch");
            blast = content.Load<SoundEffect>("Sounds/blast");
            fanfare = content.Load<SoundEffect>("Sounds/fanfare");
            musicInstance = music.CreateInstance();
            musicInstance.IsLooped = true;
            musicInstance.Volume = 0.6f;
            musicInstance.Play();
            motorInstance = motor.CreateInstance();
            motorInstance.IsLooped = true;
            motorInstance.Pitch = -0.5f;
            fanfareInstance = fanfare.CreateInstance();
        }

        /// <summary>
        /// Stops the music
        /// </summary>
        public void StopMusic()
        {
            musicInstance.Stop();
        }

        /// <summary>
        /// Starts the music
        /// </summary>
        public void PlayMusic()
        {
            musicInstance.Play();
        }

        /// <summary>
        /// Stops the motor sound
        /// </summary>
        public void StopMotor()
        {
            motorInstance.Stop();
        }

        /// <summary>
        /// Starts the motor sound
        /// </summary>
        public void PlayMotor()
        {
            motorInstance.Play();
        }

        /// <summary>
        /// Stops the tire blast sound
        /// </summary>
        public void PlayBlast()
        {
            blast.Play();
        }

        /// <summary>
        /// Starts the tire blast sound
        /// </summary>
        public void PlayFanfare()
        {
            fanfareInstance.Play();
        }

        /// <summary>
        /// Stops the fanfare sound
        /// </summary>
        public void StopFanfare()
        {
            fanfareInstance.Stop();
        }

        /// <summary>
        /// Starts the fanfare sound
        /// </summary>
        public void PlayOuch()
        {
            ouch.Play();
        }

        /// <summary>
        /// Changes the pitch of the motor sound
        /// </summary>
        /// <param name="pitch"></param>
        public void SetMotorPitch(float pitch)
        {
            if (pitch > -1)
                if (pitch < 1)
                    motorInstance.Pitch = pitch;
                else
                    motorInstance.Pitch = 1.0f;
            else
                motorInstance.Pitch = -1.0f;
        }
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Box2D.XNA;

namespace MotoTrialRacer
{
    /// <summary>
    /// The class for defining the motorcycle and the driver and their behaviour
    /// </summary>
    public class Bike : IDrawable
    {
		public RotationData RotationData { get; private set; }
		public bool OffTheBike { get; private set; }

        private World world;
        private ContentManager content;
        private List<Body> parts = new List<Body>();
        private float[] camPos;
        private Vector2 origin = new Vector2(0, 0);
        private RevoluteJoint motor;

        // The bike
        private Body frontWheel;
        private Body frontFork;
        private Body rearWheel;
        private Body rearFork;
        private Body bikeBody;

        // The driver
        private Body humanBody;
        private Body head;
        private Body arm;
        private Body hand;

        private Vector2 frontWheelInitPos = new Vector2(358, 250);
        private Vector2 frontForkInitPos = new Vector2(358, 240);
        private Vector2 rearWheelInitPos = new Vector2(229.0f, 178.0f);
        private Vector2 rearForkInitPos = new Vector2(254.0f, 186.0f);
        private float rearForkInitRot = 10.0f;
        private Vector2 bikeBodyInitPos = new Vector2(250, 80);
        private float bikeBodyInitRot = 27.0f;

        private Vector2 headInitPos = new Vector2(335, 78);
        private float headInitRot = 35;
        private Vector2 humanBodyInitPos = new Vector2(300, 114);
        private Vector2 handInitPos = new Vector2(344, 132);
        private float handInitRot = 45.0f;
        private Vector2 armInitPos = new Vector2(320, 105);
        private float armInitRot = 45.0f;
        private float[] bikeSpeed;

        private Joint handToBike;
        private Joint humanToBike;
        private Joint armToBike;

        /// <summary>
        /// Creates a new motorcycle and a driver into the given Box2D world.
        /// Creates all the parts of the motorcycle and driver and joints them together.
        /// </summary>
        /// <param name="pBikeSpeed">A pointer to the variable that describes the speed of the
        ///                          motorcycle</param>
        /// <param name="pRotationData">RotationData to provide the information of the rotation
        ///                             of the device</param>
        /// <param name="pWorld">The Box2D world where the bike is created into</param>
        /// <param name="pCamPos">A pointer to the variable that describes the position of the
        ///                       camera</param>
        /// <param name="pContent">The used ContentManager instance</param>
        /// <param name="pSpriteBatch">The used SpriteBatch instance</param>
        public Bike(float []pBikeSpeed, RotationData pRotationData, World pWorld, float[] pCamPos,
                    ContentManager pContent)
        {
			OffTheBike = false;
            camPos = pCamPos;
            world = pWorld;
            content = pContent;
            RotationData = pRotationData;

            bikeSpeed = pBikeSpeed;

            frontWheel = CreateCirclePart("wheel", frontWheelInitPos, 35.0f, 0, 0.1f, 0.9f, 0.2f);
            frontFork = CreateBoxPart("susp_lower_long", frontForkInitPos, 20.53f, 21.33f, 0, 0.8f,
                                      1.0f, 0.2f);
            rearWheel = CreateCirclePart("rearWheel", rearWheelInitPos, 32.0f, 0, 0.4f, 1.0f,
                                         0.2f);
            rearFork = CreateBoxPart("rearFork", rearForkInitPos, 64.0f, 17.0f, rearForkInitRot,
                                     0.5f, 1.0f, 0.2f);
            bikeBody = CreateBikeBody(bikeBodyInitPos, bikeBodyInitRot, 0.5f, 1.0f, 0.2f);

            RevoluteJointDef motorDef = new RevoluteJointDef();
            motorDef.Initialize(rearWheel, rearFork, rearWheel.GetWorldCenter());
            motorDef.maxMotorTorque = 2.0f;
            motorDef.enableMotor = true;
            motor = (RevoluteJoint)world.CreateJoint(motorDef);

            RevoluteJointDef rearForkBodyDef = new RevoluteJointDef();
            Vector2 anchor = rearFork.GetWorldCenter();
            anchor.X += (32.0f / Level.FACTOR);
            anchor.Y += (13.5f / Level.FACTOR);
            rearForkBodyDef.Initialize(rearFork, bikeBody, anchor);
            rearForkBodyDef.bodyA = rearFork;
            rearForkBodyDef.bodyB = bikeBody;
            rearForkBodyDef.maxMotorTorque = 300.0f;
            world.CreateJoint(rearForkBodyDef);

            RevoluteJointDef frontWheelJointDef = new RevoluteJointDef();
            frontWheelJointDef.Initialize(frontWheel, frontFork, frontWheel.GetWorldCenter());
            frontWheelJointDef.maxMotorTorque = 300.0f;
            world.CreateJoint(frontWheelJointDef);

            DistanceJointDef frontSuspToBikeDef = new DistanceJointDef();
            frontSuspToBikeDef.Initialize(bikeBody, frontFork,
                                          frontFork.GetWorldCenter() + new Vector2(0, 0.4f),
                                          frontFork.GetWorldCenter());
            frontSuspToBikeDef.frequencyHz = 4.0f;
            frontSuspToBikeDef.dampingRatio = 0.1f;
            frontSuspToBikeDef.collideConnected = true;
            world.CreateJoint(frontSuspToBikeDef);

            DistanceJointDef rearForkDistanceDef = new DistanceJointDef();
            rearForkDistanceDef.Initialize(bikeBody, rearFork,
                                           rearFork.GetWorldCenter() + new Vector2(0, 0.4f),
                                           rearFork.GetWorldCenter());
            rearForkDistanceDef.frequencyHz = 7.0f;
            rearForkDistanceDef.dampingRatio = 0.1f;
            rearForkDistanceDef.collideConnected = true;
            world.CreateJoint(rearForkDistanceDef);

            PrismaticJointDef fSuspBikePrismaticDef = new PrismaticJointDef();
            fSuspBikePrismaticDef.Initialize(bikeBody, frontFork, bikeBody.GetWorldCenter(),
                                             new Vector2(0, 1));
            fSuspBikePrismaticDef.enableLimit = true;
            fSuspBikePrismaticDef.lowerTranslation = -0.2f;
            fSuspBikePrismaticDef.upperTranslation = 0.2f;
            fSuspBikePrismaticDef.collideConnected = true;
            world.CreateJoint(fSuspBikePrismaticDef);

            humanBody = CreateBoxPart("human", humanBodyInitPos, 17.0f, 64.0f, 0, 0.1f, 1.0f,
                                      0.2f);
            head = CreateBoxPart("head", headInitPos, 38.4f, 29.9f, headInitRot, 0.1f, 1.0f,
                                 0.2f);
            hand = CreateBoxPart("hand", handInitPos, 34.13f, 8.53f, handInitRot, 0.1f, 1.0f,
                                 0.2f);
            arm = CreateBoxPart("arm", armInitPos, 42.67f, 8.53f, armInitRot, 0.1f, 1.0f, 0.2f);

            WeldJointDef headToHumanDef = new WeldJointDef();
            headToHumanDef.Initialize(head, humanBody, head.GetWorldCenter());
            world.CreateJoint(headToHumanDef);

            RevoluteJointDef humanToBikeDef = new RevoluteJointDef();
            anchor = humanBody.GetWorldCenter();
            anchor.Y += (30.0f / Level.FACTOR);
            humanToBikeDef.Initialize(humanBody, bikeBody, anchor);
            humanToBikeDef.maxMotorTorque = 300.0f;
            humanToBike = world.CreateJoint(humanToBikeDef);

            RevoluteJointDef humanToArmDef = new RevoluteJointDef();
            anchor = arm.GetWorldPoint(new Vector2(-21.33f / Level.FACTOR, 4.26f / Level.FACTOR));
            humanToArmDef.Initialize(humanBody, arm, anchor);
            humanToArmDef.maxMotorTorque = 300.0f;
            world.CreateJoint(humanToArmDef);

            RevoluteJointDef armToHandDef = new RevoluteJointDef();
            anchor = arm.GetWorldPoint(new Vector2(21.33f / Level.FACTOR, 4.26f / Level.FACTOR));
            armToHandDef.Initialize(arm, hand, anchor);
            armToHandDef.maxMotorTorque = 300.0f;
            world.CreateJoint(armToHandDef);

            RevoluteJointDef handToBikeDef = new RevoluteJointDef();
            anchor = hand.GetWorldPoint(new Vector2(17.06f / Level.FACTOR, 4.26f / Level.FACTOR));
            handToBikeDef.Initialize(hand, bikeBody, anchor);
            handToBikeDef.maxMotorTorque = 300.0f;
            handToBike = world.CreateJoint(handToBikeDef);

            DistanceJointDef armToBikeDef = new DistanceJointDef();
            armToBikeDef.Initialize(hand, bikeBody,
                                    hand.GetWorldPoint(new Vector2(-17.00f / Level.FACTOR,
                                                       4.26f / Level.FACTOR)),
                                    bikeBody.GetWorldCenter());
            armToBikeDef.length = 40.0f / Level.FACTOR;
            armToBikeDef.frequencyHz = 10.0f;
            armToBikeDef.dampingRatio = 1.0f;
            armToBikeDef.collideConnected = true;
            armToBike = world.CreateJoint(armToBikeDef);
        }

        /// <summary>
        /// Create a Box2D body and loads the texture for it
        /// </summary>
        /// <param name="name">Body's textures Content name</param>
        /// <param name="pos">Body's position</param>
        /// <param name="angle">Body's rotation angle</param>
        /// <returns></returns>
        private Body CreateBody(String name, Vector2 pos, float angle)
        {
            BodyDef bodyDef = new BodyDef();
            bodyDef.type = BodyType.Dynamic;
            bodyDef.position = pos;
            bodyDef.position.X /= Level.FACTOR;
            bodyDef.position.Y /= Level.FACTOR;
            bodyDef.angle = angle * Level.DEG_TO_RAD;

            Body body = world.CreateBody(bodyDef);
            Texture2D texture = content.Load<Texture2D>("Images/" + name);
            body.SetUserData(new UserData(name, texture));

            return body;
        }

        /// <summary>
        /// Creates one part of the motorcycle or driver
        /// </summary>
        /// <param name="shape">The shape of the part</param>
        /// <param name="name">The Content name of the texture that belongs to this part</param>
        /// <param name="pos">The position of the part</param>
        /// <param name="angle">The rotation angle of the part</param>
        /// <param name="density">The density of the part</param>
        /// <param name="friction">The friction of the part</param>
        /// <param name="restitution">The restitution of the part</param>
        /// <returns></returns>
        private Body CreatePart(Shape shape, String name, Vector2 pos, float angle, float density,
                                float friction, float restitution)
        {

            Body body = CreateBody(name, pos, angle);

            FixtureDef fixtureDef = new FixtureDef();
            fixtureDef.shape = shape;
            fixtureDef.density = density;
            fixtureDef.friction = friction;
            fixtureDef.restitution = restitution;

            body.CreateFixture(fixtureDef);

            parts.Add(body);
            return body;
        }

        /// <summary>
        /// Creates a circle shaped part of the motocycle
        /// </summary>
        /// <param name="name">The Content name of the texture that belongs to this part</param>
        /// <param name="pos">The position of the part</param>
        /// <param name="radius">The radius of the circle shape</param>
        /// <param name="angle">The rotation angle of the part</param>
        /// <param name="density">The density of the part</param>
        /// <param name="friction">The friction of the part</param>
        /// <param name="restitution">The restitution of the part</param>
        /// <returns></returns>
        private Body CreateCirclePart(String name, Vector2 pos, float radius, float angle,
                                      float density, float friction, float restitution)
        {
            CircleShape shape = new CircleShape();
            shape._radius = radius / Level.FACTOR;
            return CreatePart(shape, name, pos, angle, density, friction, restitution);
        }

        /// <summary>
        /// Creates a rectangle shaped part of the motorcycle or driver
        /// </summary>
        /// <param name="name">The Content name of the texture that belongs to this part</param>
        /// <param name="pos">The position of the part</param>
        /// <param name="width">The width of the rectangle shape</param>
        /// <param name="height">The height of the rectangle shape</param>
        /// <param name="angle">The rotation angle of the part</param>
        /// <param name="density">The density of the part</param>
        /// <param name="friction">The friction of the part</param>
        /// <param name="restitution">The restitution of the part</param>
        /// <returns></returns>
        private Body CreateBoxPart(String name, Vector2 pos, float width, float height,
                                   float angle, float density, float friction, float restitution)
        {
            PolygonShape shape = new PolygonShape();
            shape.SetAsBox(width * 0.5f / Level.FACTOR, height * 0.5f / Level.FACTOR);

            Body body = CreatePart(shape, name, pos, angle, density, friction, restitution);
            ((UserData)body.GetUserData()).Width = width;
            ((UserData)body.GetUserData()).Height = height;
            return body;
        }

        /// <summary>
        /// Adds a polygon to a body
        /// </summary>
        /// <param name="body">The body where the polygon should be added</param>
        /// <param name="vertices">The vertices of the polygon</param>
        /// <param name="density">The density of the polygon</param>
        /// <param name="friction">The friction of the polygon</param>
        /// <param name="restitution">The restitution of the polygon</param>
        private void AddPolygonToBody(Body body, Vector2[] vertices, float density, float friction,
                                      float restitution)
        {
            PolygonShape shape = new PolygonShape();
            shape.Set(vertices, vertices.Length);

            FixtureDef fixtureDef = new FixtureDef();
            fixtureDef.shape = shape;
            fixtureDef.density = density;
            fixtureDef.friction = friction;
            fixtureDef.restitution = restitution;

            body.CreateFixture(fixtureDef);
        }

        /// <summary>
        /// Creates the body of the motorcycle
        /// </summary>
        /// <param name="pos">The position of the motorcycle body</param>
        /// <param name="angle">The rotation angle of the motorcycle body</param>
        /// <param name="density">The density of the motorcycle body</param>
        /// <param name="friction">The friction of the motorcycle body</param>
        /// <param name="restitution">The restitution of the motorcycle body</param>
        /// <returns></returns>
        private Body CreateBikeBody(Vector2 pos, float angle, float density, float friction,
                                    float restitution)
        {
            Body body = CreateBody("bikeBody", pos, angle);

            Vector2[] tailVertices = {new Vector2(0, 22.0f/Level.FACTOR),
                                      new Vector2(32.0f/Level.FACTOR, 26.0f/Level.FACTOR),
                                      new Vector2(32.0f/Level.FACTOR, 32.0f/Level.FACTOR)};
            AddPolygonToBody(body, tailVertices, density, friction, restitution);

            Vector2[] rearVertices = {new Vector2(32.0f/Level.FACTOR, 26.0f/Level.FACTOR),
                                      new Vector2(120.0f*0.64f/Level.FACTOR,
                                                  45.0f*0.64f/Level.FACTOR),
                                      new Vector2(120.0f*0.64f/Level.FACTOR,
                                                  100.0f*0.64f/Level.FACTOR),
                                      new Vector2(90.0f*0.64f/Level.FACTOR,
                                                  100.0f*0.64f/Level.FACTOR),
                                      new Vector2(50.0f*0.64f/Level.FACTOR,
                                                  50.0f*0.64f/Level.FACTOR)};
            AddPolygonToBody(body, rearVertices, density, friction, restitution);

            Vector2[] frontVertices = {new Vector2(120.0f*0.64f/Level.FACTOR,
                                                   45.0f*0.64f/Level.FACTOR),
                                       new Vector2(180.0f*0.64f/Level.FACTOR,
                                                   35.0f*0.64f/Level.FACTOR),
                                       new Vector2(180.0f*0.64f/Level.FACTOR,
                                                   140.0f*0.64f/Level.FACTOR),
                                       new Vector2(120.0f*0.64f/Level.FACTOR,
                                                   140.0f*0.64f/Level.FACTOR)};
            AddPolygonToBody(body, frontVertices, density, friction, restitution);

            Vector2[] noseVertices = {new Vector2(180.0f*0.64f/Level.FACTOR, 0),
                                      new Vector2(210.0f*0.64f/Level.FACTOR, 0),
                                      new Vector2(230.0f*0.64f/Level.FACTOR,
                                                  60.0f*0.64f/Level.FACTOR),
                                      new Vector2(180.0f*0.64f/Level.FACTOR,
                                                  135.0f*0.64f/Level.FACTOR)};
            AddPolygonToBody(body, noseVertices, density, friction, restitution);

            parts.Add(body);
            return body;
        }

        /// <summary>
        /// Sets the initial position for the motorcycle and driver
        /// </summary>
        /// <param name="pX">x coordinate of the new initial position</param>
        /// <param name="pY">y coordinate of the new initial position</param>
        public void SetInitPos(float pX, float pY)
        {
            float x = pX - 250;
            float y = pY - 80;
            frontWheelInitPos = new Vector2(358+x, 250+y);
            frontForkInitPos = new Vector2(358+x, 240+y);
            rearWheelInitPos = new Vector2(229+x, 178+y);
            rearForkInitPos = new Vector2(254+x, 186+y);
            bikeBodyInitPos = new Vector2(250+x, 80+y);

            headInitPos = new Vector2(335+x, 78+y);
            humanBodyInitPos = new Vector2(300+x, 114+y);
            handInitPos = new Vector2(344+x, 132+y);
            armInitPos = new Vector2(320+x, 105+y);
        }

        /// <summary>
        /// Resets the bike and the driver to their initial positions
        /// Resets all angular and linear speeds
        /// Recreates the joints if they were destroyed
        /// </summary>
        public void Reset()
        {
            foreach (var part in parts)
            {
                part.SetAngularVelocity(0);
				part.SetLinearVelocity(Vector2.Zero);
            }

			frontWheel.SetTransform(frontWheelInitPos / Level.FACTOR, 0);
            frontFork.SetTransform(frontForkInitPos / Level.FACTOR, 0);
            rearWheel.SetTransform(rearWheelInitPos / Level.FACTOR, 0);
            rearFork.SetTransform(rearForkInitPos / Level.FACTOR,
                                  rearForkInitRot * Level.DEG_TO_RAD);
            bikeBody.SetTransform(bikeBodyInitPos / Level.FACTOR,
                                  bikeBodyInitRot * Level.DEG_TO_RAD);

            head.SetTransform(headInitPos / Level.FACTOR, headInitRot * Level.DEG_TO_RAD);
            humanBody.SetTransform(humanBodyInitPos / Level.FACTOR, 0);
            hand.SetTransform(handInitPos / Level.FACTOR, handInitRot * Level.DEG_TO_RAD);
            arm.SetTransform(armInitPos / Level.FACTOR, armInitRot * Level.DEG_TO_RAD);

            if (OffTheBike)
            {
                RevoluteJointDef handToBikeDef = new RevoluteJointDef();
                Vector2 anchor = hand.GetWorldPoint(new Vector2(17.06f / Level.FACTOR,
                                                                4.26f / Level.FACTOR));
                handToBikeDef.Initialize(hand, bikeBody, anchor);
                handToBikeDef.maxMotorTorque = 300.0f;
                handToBike = world.CreateJoint(handToBikeDef);

                RevoluteJointDef humanToBikeDef = new RevoluteJointDef();
                anchor = humanBody.GetWorldCenter();
                anchor.Y += (30.0f / Level.FACTOR);
                humanToBikeDef.Initialize(humanBody, bikeBody, anchor);
                humanToBikeDef.maxMotorTorque = 300.0f;
                humanToBike = world.CreateJoint(humanToBikeDef);

                DistanceJointDef armToBikeDef = new DistanceJointDef();
                armToBikeDef.Initialize(hand, bikeBody,
                                        hand.GetWorldPoint(new Vector2(-17.00f / Level.FACTOR,
                                                                       4.26f / Level.FACTOR)),
                                        bikeBody.GetWorldCenter());
                armToBikeDef.length = 40.0f / Level.FACTOR;
                armToBikeDef.frequencyHz = 10.0f;
                armToBikeDef.dampingRatio = 1.0f;
                armToBikeDef.collideConnected = true;
                armToBike = world.CreateJoint(armToBikeDef);

                OffTheBike = false;
            }

			if (!bikeBody.IsAwake())
				bikeBody.SetAwake(true);

			if (RotationData.device)
                motor._enableMotor = true;
        }

        /// <summary>
        /// Destroys the joints between the driver and the motorcycle
        /// </summary>
        public void Release()
        {
            OffTheBike = true;
            world.DestroyJoint(handToBike);
            handToBike = null;
            world.DestroyJoint(humanToBike);
            humanToBike = null;
            world.DestroyJoint(armToBike);
            armToBike = null;
        }

        /// <summary>
        /// Makes the motorcycle to ignore the user inputs
        /// </summary>
        public void disableControls()
        {
            motor._enableMotor = false;
            world.ClearForces();
        }

        /// <summary>
        /// Updates the positions of the parts and camera, the motorcycle speed and user inputs
        /// </summary>
        public void Update()
        {
            Vector2 pos = parts[0].GetPosition();
            Vector2 pos2 = parts[2].GetPosition();
            camPos[0] = Math.Min(pos.X, pos2.X) * Level.FACTOR;
            camPos[1] = Math.Max(pos.Y, pos2.Y) * Level.FACTOR;
            bikeSpeed[0] = parts[0].GetLinearVelocity().Length();
            bikeSpeed[1] = parts[2].GetAngularVelocity();

            if (!RotationData.device)
            {
                KeyboardState keyboardState = Keyboard.GetState();
                if (keyboardState.IsKeyDown(Keys.Up))
                {
                    motor._enableMotor = true;
                    RotationData.xRot = -30;
                }

                if (keyboardState.IsKeyDown(Keys.Down))
                {
                    motor._enableMotor = true;
                    RotationData.xRot = 0;
                }

				if (keyboardState.IsKeyDown(Keys.Left))
                    leanBackwards();

				if (keyboardState.IsKeyDown(Keys.Right))
                    leanForwards();

				if (keyboardState.IsKeyUp(Keys.Up) && keyboardState.IsKeyUp(Keys.Down))
                {
                    motor._enableMotor = false;
                    RotationData.xRot = 0;
                }
            }
            motor._motorSpeed = RotationData.xRot;
        }

        /// <summary>
        /// Rotates the motorcycle counterclockwise
        /// </summary>
        public void leanBackwards()
        {
            humanBody.ApplyTorque(-5);
            bikeBody.ApplyTorque(-50);
        }

        /// <summary>
        /// Rotates the motorcycle clockwise
        /// </summary>
        public void leanForwards()
        {
            humanBody.ApplyTorque(5);
            bikeBody.ApplyTorque(50);
        }

        /// <summary>
        /// Stops the rotation of the rear wheel
        /// </summary>
        public void StopMotor()
        {
            motor._motorSpeed = 0;
        }

        /// <summary>
        /// Stops the rotation of the rear wheel
        /// </summary>
        public void RearBreak()
        {
            motor._enableMotor = true;
            motor._motorSpeed = 0;
        }

        public void FrontBreak()
        {
        }

        /// <summary>
        /// Draw all the parts of the motorcycle and driver
        /// </summary>
		public void Draw(SpriteBatch spriteBatch)
        {
            foreach (Body body in parts)
            {
                Vector2 pos = body.GetPosition();
                UserData userData = (UserData)body.GetUserData();
                Texture2D texture = userData.Texture;
                pos *= Level.FACTOR;
                if (userData.Name == "susp_lower_long")
                {
                    origin.X = texture.Width * 0.5f;
                    origin.Y = texture.Height - 10.0f;
                }
                else if (userData.Name == "bikeBody")
                {
                    origin.X = 0;
                    origin.Y = 0;
                }
                else if (userData.Name == "rearFork")
                {
                    origin.X = texture.Width * 0.5f;
                    origin.Y = texture.Height * 0.75f;
                }
                else if (userData.Name == "human")
                {
                    origin.X = texture.Width - userData.Width*2.0f;
                    origin.Y = userData.Height * 0.5f;
                }
                else
                {
                    origin.X = texture.Width * 0.5f;
                    origin.Y = texture.Height * 0.5f;
                }
                spriteBatch.Draw(texture,
                                 pos,
                                 null,
                                 Color.White,
                                 body.GetAngle(),
                                 origin,
                                 1.0f,
                                 SpriteEffects.None,
                                 0.0f);
            }
        }
	}
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Box2D.XNA;

namespace MotoTrialRacer.Components
{
    /// <summary>
    /// The class that defines a level component for the finish line.
    /// A level is completed when the player contacts with this component.
    /// Derives from LevelComponent.
    /// </summary>
    class Finish : LevelComponent
    {
        /// <summary>
        /// Creates a new Finish component
        /// </summary>
        /// <param name="world">The Box2D world that will hold this component</param>
        /// <param name="content">Used ContentManager</param>
        /// <param name="pos">The position of the component</param>
        /// <param name="angle">The rotation angle of the component</param>
        /// <param name="width">The width of the component</param>
        /// <param name="height">The height of the component</param>
        public Finish(World world, ContentManager content, Vector2 pos,
                      float angle, float width, float height) :
            base(world, content, pos, angle, width, height)
        {
            Name = "finish";
            texture = content.Load<Texture2D>("Images/" + Name);
            PolygonShape shape = new PolygonShape();
            shape.SetAsBox(width * 0.5f / Level.FACTOR, height * 0.5f / Level.FACTOR);
            body.CreateFixture(shape, 1.0f).SetFriction(1.0f);
            body.SetUserData(new UserData(Name, null));
            origin = new Vector2(screenPos.Width * 0.5f, texture.Height * 0.5f);
            sourceRect = new Rectangle(0, 0, (int)width, texture.Height);
        }
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Box2D.XNA;

namespace MotoTrialRacer.Components
{
    /// <summary>
    /// This class defines the level component for the ground.
    /// Derives from LevelComponent.
    /// </summary>
    class Ground : LevelComponent
    {
        /// <summary>
        /// Creates a new ground component
        /// </summary>
        /// <param name="world">The Box2D world that will hold this component</param>
        /// <param name="content">Used ContentManager</param>
        /// <param name="pos">The position of this component</param>
        /// <param name="angle">The rotation angle of this component</param>
        /// <param name="width">The width of this component</param>
        /// <param name="height">The height of this component</param>
        public Ground(World world, ContentManager content, Vector2 pos,
                      float angle, float width, float height) :
            base(world, content, pos, angle, width, height)
        {
            Name = "grass";
            texture = content.Load<Texture2D>("Images/" + Name);
            PolygonShape shape = new PolygonShape();
            shape.SetAsBox(width * 0.5f / Level.FACTOR, height * 0.5f / Level.FACTOR);
            body.CreateFixture(shape, 1.0f).SetFriction(1.0f);
            origin = new Vector2(screenPos.Width * 0.5f, texture.Height * 0.5f);
            sourceRect = new Rectangle(0, 0, (int)width, texture.Height);
        }
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Box2D.XNA;

namespace MotoTrialRacer.Components
{
    /// <summary>
    /// This class defines the level component for the jump.
    /// Derives from LevelComponent.
    /// </summary>
    class Jump : LevelComponent
    {
        /// <summary>
        /// Creates a new jump component
        /// </summary>
        /// <param name="world">The Box2D world that will hold this component</param>
        /// <param name="content">Used ContentManager</param>
        /// <param name="pos">The position of this component</param>
        /// <param name="angle">The rotation angle of this component</param>
        /// <param name="width">The width of this component</param>
        /// <param name="height">The height of this component</param>
        public Jump(World world, ContentManager content, Vector2 pos,
                    float angle, float width, float height) :
            base(world, content, pos, angle, width, height)

        {
            Name = "jump";
            texture = content.Load<Texture2D>("Images/" + Name);
            origin = new Vector2(texture.Width * 0.5f, texture.Height * 0.5f);
            sourceRect = new Rectangle(1, 1, texture.Width, texture.Height);
            PolygonShape shape = new PolygonShape();
            Vector2[] vertices = {new Vector2(-width*0.5f/ Level.FACTOR,
                                              height*0.5f/ Level.FACTOR),
                                  new Vector2(width*0.5f/ Level.FACTOR,
                                              -height*0.5f/ Level.FACTOR),
                                  new Vector2(width*0.5f/ Level.FACTOR,
                                              height*0.5f/ Level.FACTOR)};
            shape.Set(vertices, 3);
            body.CreateFixture(shape, 1.0f);
        }
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Box2D.XNA;

namespace MotoTrialRacer.Components
{
    /// <summary>
    /// An enumeration to describe the type of a level component
    /// </summary>
    public enum LevelComponentType
    {
        grass,
        jump,
        nail,
        finish
    }

    /// <summary>
    /// The base class for all level components
    /// </summary>
    public class LevelComponent : IDrawable
    {
        protected Texture2D texture;
        protected Rectangle screenPos;
        protected Color unActiveColor = Color.White;
        protected Color activeColor = new Color(0.5f, 1.0f, 0.5f, 1.0f);
        protected Color color = Color.White;
        protected float x, y, width, height;
        protected Body body;
        protected float[] camPos = new float[2];
        protected bool pressed = false;
        protected Rectangle sourceRect;
        protected Vector2 origin;

		public String Name { get; protected set; }
		public Vector2 Pos { get; set; }

        public float X
		{
            get
            {
                return x;
            }
            set
            {
                screenPos.X = (int)value;
            }
        }

		public float Y
        {
            get
            {
                return y;
            }
            set
            {
                screenPos.Y = (int)value;
            }
        }

		public float Width
        {
            get
            {
                return width;
            }
            set
            {
                screenPos.Width = (int)value;
            }
        }

		public float Height
        {
            get
            {
                return height;
            }
            set
            {
                screenPos.Height = (int)value;
            }
        }

		public float Angle
        {
            get
            {
                return body.GetAngle();
            }
        }

        /// <summary>
        /// Creates a new level component
        /// </summary>
        /// <param name="world">The Box2D world that will hold this component</param>
        /// <param name="content">Used ContentManager</param>
        /// <param name="pSpriteBatch">Used SpriteBatch</param>
        /// <param name="pos">The position of the component</param>
        /// <param name="angle">The angle of the component</param>
        /// <param name="pWidth">The width of the component</param>
        /// <param name="pHeight">The height of the component</param>
        public LevelComponent(World world, ContentManager content,
                              Vector2 pos, float angle, float pWidth, float pHeight)
        {
			Pos = new Vector2();
            x = pos.X;
            y = pos.Y;
            width = pWidth;
            height = pHeight;
            sourceRect = new Rectangle(0, 0, (int)width, (int)height);
            screenPos = new Rectangle(0, 0, (int)width, (int)height);
            origin = new Vector2(sourceRect.Width * 0.5f, sourceRect.Height * 0.5f);

            BodyDef bodyDef = new BodyDef();
            bodyDef.type = BodyType.Static;
            bodyDef.position = pos;
            bodyDef.position.X /= Level.FACTOR;
            bodyDef.position.Y /= Level.FACTOR;
            bodyDef.angle = angle * Level.DEG_TO_RAD;

            body = world.CreateBody(bodyDef);
        }

        /// <summary>
        /// Sets the position of the camera
        /// </summary>
        /// <param name="pCamPos">The position of the camera</param>
        public void SetCamPos(float[] pCamPos)
        {
            camPos = pCamPos;
        }

        /// <summary>
        /// Updates the level component if it's wanted to react to the user touch inputs
        /// </summary>
        /// <param name="touchLocation">The location of the touch</param>
        /// <returns>Returns true if the component asumes that the touch was dedicated to it,
        ///          false otherwise</returns>
        public virtual bool Update(TouchLocation touchLocation)
        {
            Vector2 touch = new Vector2(touchLocation.Position.X + camPos[0] - Pos.X,
                                        touchLocation.Position.Y + camPos[1] - Pos.Y);
            touch = Vector2.Transform(touch, Matrix.CreateRotationZ(-body.GetAngle()));
            if (screenPos.Contains(new Point((int)(touch.X + Pos.X + width * 0.5),
                                             (int)(touch.Y + Pos.Y + height * 0.5))))
            {
                if (touchLocation.State == TouchLocationState.Pressed)
                {
                    color = activeColor;
                    pressed = true;
                }
                else if (touchLocation.State == TouchLocationState.Released)
                {
                    color = unActiveColor;
                    pressed = false;
                    return true;
                }
            }

            if (touchLocation.State == TouchLocationState.Released)
            {
                color = unActiveColor;
                pressed = false;
                return false;
            }

            if (pressed)
            {
                Pos = new Vector2(touchLocation.Position.X + camPos[0], touchLocation.Position.Y + camPos[1]);
                body.SetTransform(Pos / Level.FACTOR, body.GetAngle());
                return true;
            }

            return false;
        }

        /// <summary>
        /// Sets the angle of the component
        /// </summary>
        /// <param name="angle">The angle of the component</param>
        public void SetAngle(float angle)
        {
            body.SetTransform(Pos / Level.FACTOR, angle);
        }

		public void Draw(SpriteBatch spriteBatch)
		{
			screenPos.X = (int)(body.GetPosition().X * Level.FACTOR);
			screenPos.Y = (int)(body.GetPosition().Y * Level.FACTOR);
			spriteBatch.Draw(texture,
							 screenPos,
							 sourceRect,
							 color,
							 body.GetAngle(),
							 origin,
							 SpriteEffects.None,
							 0.0f);
		}
	}
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Box2D.XNA;

namespace MotoTrialRacer.Components
{
    /// <summary>
    /// This class defines the level component for the spike mat.
    /// Derives from LevelComponent.
    /// </summary>
    class SpikeMat : LevelComponent
    {
        /// <summary>
        /// Creates a new spike mat component
        /// </summary>
        /// <param name="world">The Box2D world that will hold this component</param>
        /// <param name="content">Used ContentManager</param>
        /// <param name="pSpriteBatch">Used SpriteBatch</param>
        /// <param name="pos">The position of this component</param>
        /// <param name="angle">The rotation angle of this component</param>
        /// <param name="width">The width of this component</param>
        /// <param name="height">The height of this component</param>
        public SpikeMat(World world, ContentManager content,
                        Vector2 pos, float angle, float width, float height) :
            base(world, content, pos, angle, width, height)
        {
            Name = "nail";
            texture = content.Load<Texture2D>("Images/" + Name);
            PolygonShape shape = new PolygonShape();
            shape.SetAsBox(width * 0.5f / Level.FACTOR, height * 0.5f / Level.FACTOR);
            body.CreateFixture(shape, 1.0f).SetFriction(1.0f);
            body.SetUserData(new UserData(Name, null));
            origin = new Vector2(screenPos.Width * 0.5f, texture.Height * 0.5f);
            sourceRect = new Rectangle(0, 0, (int)width, texture.Height);
        }
    }
}