<|start_filename|>PhysX.Net/Test/Math/TransformTests.cs<|end_filename|>
﻿using System;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class TransformTests
	{
		[TestMethod]
		public void ToMatrix_Position()
		{
			var a = new Transform(new Vector3(1, 2, 3));
			Assert.AreEqual(Matrix4x4.CreateTranslation(1, 2, 3), a.ToMatrix());
		}

		[TestMethod]
		public void ToMatrix_PositionAndQuat()
		{
			var a = new Transform(Quaternion.CreateFromYawPitchRoll(4, 5, 6), new Vector3(1, 2, 3));
			Assert.AreEqual(Matrix4x4.CreateFromYawPitchRoll(4, 5, 6) * Matrix4x4.CreateTranslation(1, 2, 3), a.ToMatrix());
		}

		[TestMethod]
		public void CastToMatrix4x4()
		{
			var a = new Transform(Quaternion.CreateFromYawPitchRoll(4, 5, 6), new Vector3(1, 2, 3));
			Assert.AreEqual(Matrix4x4.CreateFromYawPitchRoll(4, 5, 6) * Matrix4x4.CreateTranslation(1, 2, 3), (Matrix4x4)a);
		}

		[TestMethod]
		public void EqualsOperator_WithSelf()
		{
			var a = new Transform(new Vector3(1, 2, 3));

			Assert.IsTrue(a == a);
		}

		[TestMethod]
		public void EqualsOperator()
		{
			var a = new Transform(new Vector3(1, 2, 3));
			var b = new Transform(new Vector3(1, 2, 3));

			Assert.IsTrue(a == b);
		}

		[TestMethod]
		public void NotEqualsOperator()
		{
			var a = new Transform(new Vector3(1, 2, 3));
			var b = new Transform(new Vector3(4, 5, 6));

			Assert.IsTrue(a != b);
		}

		[TestMethod]
		public void GetHashCode_Differs()
		{
			var a = new Transform(new Vector3(1, 2, 3));
			var b = new Transform(new Vector3(4, 5, 6));

			Assert.AreNotEqual(a.GetHashCode(), b.GetHashCode());
		}
	}
}


<|start_filename|>PhysX.Net/Samples/Engine/Extensions/RigidActorExtensions.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PhysX.Samples
{
	public static class RigidActorExtensions
	{
		/// <summary>
		/// A convenience/backwards-compatability method.
		/// </summary>
		public static Shape CreateShape(this RigidActor actor, Geometry geometry, Material material)
		{
			return RigidActorExt.CreateExclusiveShape(actor, geometry, material);
		}
	}
}


<|start_filename|>PhysX.Net/Test/Material/MaterialCreationAndDisposalTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class MaterialCreationAndDisposalTest : Test
	{
		[TestMethod]
		public void CreateAndDisposeMaterial()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(5, 6, 7);

				Assert.IsFalse(material.Disposed);

				material.Dispose();

				Assert.IsTrue(material.Disposed);
			}
		}

		[TestMethod]
		public void CreateMultipleMaterials()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				for (int i = 0; i < 10; i++)
				{
					var materialN = physics.Physics.CreateMaterial(5, 6, 7);
				}
			}
		}

		[TestMethod]
		public void MultipleDisposalCallsAreValid()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(5, 6, 7);

				Assert.IsFalse(material.Disposed);

				material.Dispose();

				Assert.IsTrue(material.Disposed);

				material.Dispose();

				Assert.IsTrue(material.Disposed);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Test/TestDependantFiles.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	public static class TestDependantFiles
	{
		// Copy out the dependant DLL files needed for each test run
		internal static void CopyDependantFiles(TestContext ctx)
		{
			const string platform = "x64";

#if DEBUG
			const string config = "Debug";
#elif RELEASE
			const string config = "Release";
#endif

			string dir = $@"..\..\Assemblies\{platform}\{config}";
			dir = Path.Combine(ctx.TestRunDirectory, dir);
			dir = Path.GetFullPath(dir);

			var files = Directory.GetFiles(dir);

			foreach (var file in files)
			{
				string dst = Path.Combine(ctx.TestDeploymentDir, Path.GetFileName(file));

				File.Copy(file, dst);
			}
		}
	}
}


<|start_filename|>PhysX.Net/Samples/CharacterSample/ControllerHitReport.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PhysX.Samples.CharacterSample
{
	public class ControllerHitReport : UserControllerHitReport
	{
		public override void OnControllerHit(ControllersHit hit)
		{
			Console.WriteLine("Hit controller at " + hit.WorldPosition);
		}

		public override void OnObstacleHit(ControllerObstacleHit hit)
		{
			
		}

		public override void OnShapeHit(ControllerShapeHit hit)
		{
			
		}
	}
}

<|start_filename|>PhysX.Net/Test/Util/ColladaLoader.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Globalization;
using System.Numerics;

namespace PhysX.Test.Util
{
	/// <summary>A very basic COLLADA loader.</summary>
	/// <remarks>
	/// This basically loads the torus DAE file for use as a convex mesh.
	/// </remarks>
	public class ColladaLoader
	{
		public Model Load(string xml)
		{
			XmlDocument document = new XmlDocument();
			document.LoadXml(xml);

			XmlNamespaceManager ns = new XmlNamespaceManager(document.NameTable);
			ns.AddNamespace("c", "http://www.collada.org/2005/11/COLLADASchema");

			// Read vertex positions
			var positionsNode = document.SelectSingleNode("/c:COLLADA/c:library_geometries/c:geometry/c:mesh/c:source/c:float_array", ns);
			var indicesNode = document.SelectSingleNode("/c:COLLADA/c:library_geometries/c:geometry/c:mesh/c:triangles/c:p", ns);

			var positions = ParseVector3s(positionsNode.InnerText).ToArray();
			var indices = ParseInts(indicesNode.InnerText).ToArray();

			var model = new Model()
			{
				Vertices = positions,
				Indices = indices
			};

			return model;
		}

		private IEnumerable<Vector3> ParseVector3s(string positionsText)
		{
			var positions = positionsText.Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

			for (int i = 0; i < positions.Length; i += 3)
			{
				float x = float.Parse(positions[i + 0], CultureInfo.InvariantCulture);
				float y = float.Parse(positions[i + 1], CultureInfo.InvariantCulture);
				float z = float.Parse(positions[i + 2], CultureInfo.InvariantCulture);

				yield return new Vector3(x, y, z);
			}
		}
		private IEnumerable<int> ParseInts(string indicesText)
		{
			var indices = indicesText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

			for (int i = 0; i < indices.Length; i++)
			{
				yield return int.Parse(indices[i], CultureInfo.InvariantCulture);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/EventsSample/Program.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PhysX.Samples.EventsSample
{
	public class Program
	{
		[STAThread]
		static void Main(string[] args)
		{
			new EventsSample();
		}
	}
}

<|start_filename|>PhysX.Net/Test/Actor/RigidActorTests.cs<|end_filename|>
﻿using System;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class RigidActorTests : Test
	{
		[TestMethod]
		public void CloneDynamic()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(0.2f, 0.1f, 0.2f);

				var rigid = physics.Physics.CreateRigidDynamic();
				var box = rigid.CreateShape(new BoxGeometry(2, 3, 4), material);

				//

				var rigidClone = rigid.CloneDynamic(Matrix4x4.Identity, physics.Physics);

				//

				Assert.IsNotNull(rigidClone);
				Assert.AreEqual(1, rigidClone.Shapes.Count);
				Assert.AreEqual(GeometryType.Box, rigidClone.Shapes[0].GeometryType);
				Assert.AreEqual(material, rigidClone.Shapes[0].Materials[0]);
				Assert.AreNotEqual(box, rigidClone.Shapes[0]);
				Assert.AreEqual(new Vector3(2, 3, 4), rigidClone.Shapes[0].GetBoxGeometry().HalfExtents);
			}
		}

		[TestMethod]
		public void CreateShape_IsInActorsShapesProperty()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(0.2f, 0.1f, 0.2f);
				var rigid = physics.Physics.CreateRigidDynamic();
				var box = rigid.CreateShape(new BoxGeometry(2, 3, 4), material);

				Assert.AreEqual(1, rigid.Shapes.Count);
			}
		}

		[TestMethod]
		public void CreateShape_DisposingOfShapeRemovesItFromActorsShapesProperty()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(0.2f, 0.1f, 0.2f);
				var rigid = physics.Physics.CreateRigidDynamic();
				var box = rigid.CreateShape(new BoxGeometry(2, 3, 4), material);

				Assert.AreEqual(1, rigid.Shapes.Count);

				box.Dispose();

				Assert.AreEqual(0, rigid.Shapes.Count);
			}
		}

		[TestMethod]
		public void Shapes_CanReturnEmpty()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(0.2f, 0.1f, 0.2f);
				var rigid = physics.Physics.CreateRigidDynamic();

				Assert.AreEqual(0, rigid.Shapes.Count);
			}
		}
	}
}


<|start_filename|>PhysX.Net/Test/Joint/FixedJointTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class FixedJointTest : Test
	{
		[TestMethod]
		public void CreateAndDisposeFixedJoint()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var box = CreateBoxActor(core.Scene, 5, 5, 5);

				using (var fixedJoint = core.Scene.CreateJoint<FixedJoint>(box, Matrix4x4.Identity, null, Matrix4x4.Identity))
				{

				}
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/CollisionDisabledSample/CollisionDisabledSample.cs<|end_filename|>
﻿using System;
using System.Numerics;

namespace PhysX.Samples.CollisionDisabledSample
{
	public class CollisionDisabledSample : Sample
	{
		private Scene _scene;
		private Material _material;

		public CollisionDisabledSample()
			: base(SetupFilters)
		{
			Run();
		}

		private static void SetupFilters(SceneDesc sceneDesc)
		{
			sceneDesc.SimulationFilterCallback = new CollisionDisabledSimulationFilterCallback();
			sceneDesc.FilterShader = new CollisionDisabledFilterShader();
		}

		protected override void LoadContent()
		{

		}

		protected override void LoadPhysics(Scene scene)
		{
			_scene = scene;
			_material = scene.Physics.CreateMaterial(0.7f, 0.7f, 0.1f);

			// Create some boxes that are above each other
			var a = CreateBox(new Vector3(0, 10, 0));
			var b = CreateBox(new Vector3(0, 20, 0));
			var c = CreateBox(new Vector3(0, 30, 0));

			// Pass boxes B and C to our filter callback
			var filter = scene.FilterCallback as CollisionDisabledSimulationFilterCallback;
			filter.DisableCollisionBetweenActors.Add(new Tuple<RigidActor, RigidActor>(b, c));
		}

		private RigidDynamic CreateBox(Vector3 position)
		{
			var actor = _scene.Physics.CreateRigidDynamic();

			var boxGeom = new BoxGeometry(2, 2, 2);
			var boxShape = actor.CreateShape(boxGeom, _material);

			actor.GlobalPose = Matrix4x4.CreateTranslation(position);
			actor.SetMassAndUpdateInertia(10);

			_scene.AddActor(actor);

			return actor;
		}

		protected override void Update(TimeSpan elapsed)
		{

		}

		protected override void Draw()
		{

		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Engine/SampleFilterShader.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PhysX.Samples.Engine
{
	public class SampleFilterShader : SimulationFilterShader
	{
		public override FilterResult Filter(int attributes0, FilterData filterData0, int attributes1, FilterData filterData1)
		{
			return new FilterResult
			{
				FilterFlag = FilterFlag.Default,
				// Cause PhysX to report any contact of two shapes as a touch and call SimulationEventCallback.OnContact
				PairFlags = PairFlag.ContactDefault | PairFlag.NotifyTouchFound | PairFlag.NotifyTouchLost
			};
		}
	}
}


<|start_filename|>PhysX.Net/Test/Joint/PrismaticJointTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class PrismaticJointTest : Test
	{
		[TestMethod]
		public void CreateAndDisposePrismaticJoint()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var box = CreateBoxActor(core.Scene, 5, 5, 5);

				var prismaticJoint = core.Scene.CreateJoint<PrismaticJoint>(box, Matrix4x4.Identity, null, Matrix4x4.Identity);

				prismaticJoint.Dispose();
			}
		}

		[TestMethod]
		public void DisposeOfOnlyAttachedActor()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var box = CreateBoxActor(core.Scene, 5, 5, 5);

				var prismaticJoint = core.Scene.CreateJoint<PrismaticJoint>(box, Matrix4x4.Identity, null, Matrix4x4.Identity);

				Assert.IsNotNull(prismaticJoint.Actor0);

				box.Dispose();

				Assert.IsNull(prismaticJoint.Actor0);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/VehicleSample/TyreType.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PhysX.Samples.VehicleSample
{
	public enum TyreType
	{
		Wets = 0,
		Slicks,
		Ice,
		Mud
	}
}

<|start_filename|>PhysX.Net/Test/Scene/SweepTests.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class SweepTests : Test
	{
		[TestMethod]
		public void Box_Box_Sweep()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				// Create a 10x10x10 box and place it to the right and on the ground
				var box = CreateBoxActor(physics.Scene, 5, 5, 5);
				box.GlobalPose = Matrix4x4.CreateTranslation(20, 5, 0);

				var sweepGeom = new BoxGeometry(2, 2, 2);

				//

				var hitActors = new List<RigidActor>();

				// Sweep the small box to the right 50units, it should hit our bigger box
				physics.Scene.Sweep(sweepGeom, Matrix4x4.CreateTranslation(0, 2, 0), new Vector3(1, 0, 0), 50, 10, (hits) =>
				{
					// Record all the hits to make sure we only end up with one
					hitActors.AddRange(hits.Select(h => h.Actor));

					return true;
				});

				Assert.AreEqual(1, hitActors.Count);
				Assert.AreEqual(box, hitActors[0]);
			}
		}
	}
}


<|start_filename|>PhysX.Net/Package.bat<|end_filename|>

cd C:\Development\PhysX.Net\PhysX.Net
C:

md Package
cd Package
rd Working /S /Q
md Working
cd Working
md "PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1"
cd "PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1"
md "Assemblies"
md "Assemblies\x64"
md "Assemblies\x64\Debug"
md "Assemblies\x64\Release"
cd ..\..\..

msbuild PhysX.Net.sln /p:Configuration=Debug;Platform=x64 /t:Clean,Build
msbuild PhysX.Net.sln /p:Configuration=Release;Platform=x64 /t:Clean,Build

Rem Samples
md "Package\Working\PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1\Samples"
robocopy Samples "Package\Working\PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1\Samples" /E /XF *.suo *.vssscc *.cachefile *.user *.vspscc *.pdb *.vshost.exe* /XD obj Release
md "Package\Working\PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1\Assemblies"
robocopy Assemblies "Package\Working\PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1\Assemblies" /E

xcopy "PhysX.Net\bin\x64\Debug\PhysX.Net.dll" "Package\Working\PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1\Assemblies\x64\Debug"
xcopy "PhysX.Net\bin\x64\Debug\PhysX.Net.pdb" "Package\Working\PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1\Assemblies\x64\Debug"
xcopy "PhysX.Net\bin\x64\Release\PhysX.Net.dll" "Package\Working\PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1\Assemblies\x64\Release"

cd "Package\Working"

attrib * -R /S /D

..\..\..\Tools\7-Zip\7z.exe a "PhysX.Net 3.0.0 for NVIDIA PhysX 4.1.1.zip" .

cd ..\..


<|start_filename|>PhysX.Net/Samples/Engine/Keyboard.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;

namespace PhysX.Samples.Engine
{
	public class Keyboard
	{
		public event KeyEventHandler OnKeyDown, OnKeyUp;

		private List<Key> _pressedKeys;

		public Keyboard(Engine engine)
		{
			_pressedKeys = new List<Key>();

			engine.Window.KeyDown += window_KeyDown;
			engine.Window.KeyUp += window_KeyUp;
		}

		public bool IsKeyDown(Key key)
		{
			return PressedKeys.Contains(key);
		}

		private void window_KeyDown(object sender, KeyEventArgs e)
		{
			if (!_pressedKeys.Contains(e.Key))
				_pressedKeys.Add(e.Key);

			if (OnKeyDown != null)
				OnKeyDown(this, e);
		}
		private void window_KeyUp(object sender, KeyEventArgs e)
		{
			_pressedKeys.Remove(e.Key);

			if (OnKeyUp != null)
				OnKeyUp(this, e);
		}

		public IEnumerable<Key> PressedKeys
		{
			get
			{
				return _pressedKeys;
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Cooking/CookingTests.cs<|end_filename|>
﻿using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Cooking
{
	[TestClass]
	public class CookingTests : Test
	{
		[TestMethod]
		public void CreateAndDisposeCooking()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				using (var cooking = physics.Physics.CreateCooking())
				{
					
				}
			}
		}

		[TestMethod]
		public void MidphaseType33()
		{
			var midphase33 = new MidphaseDesc
			{
				Bvh33Desc = new Bvh33MidphaseDesc()
			};

			Assert.AreEqual(MeshMidPhase.BoundingVolumeHierarchy33, midphase33.Type);
		}

		[TestMethod]
		public void MidphaseType34()
		{
			var midphase34 = new MidphaseDesc
			{
				Bvh34Desc = new Bvh34MidphaseDesc()
			};

			Assert.AreEqual(MeshMidPhase.BoundingVolumeHierarchy34, midphase34.Type);
		}
	}
}


<|start_filename|>PhysX.Net/PhysX.Net/Source/SceneEnum.h<|end_filename|>
#pragma once


namespace PhysX
{
	[Flags]
	public enum class SceneFlag
	{
		EnableActiveActors = PxSceneFlag::eENABLE_ACTIVE_ACTORS,

		/// <summary>
		/// Enables a second broad phase check after integration that makes it possible to prevent objects
		/// from tunneling through eachother. eSWEPT_INTEGRATION_LINEAR requires this flag to be specified.
		/// Note: For this feature to be effective for shapes that can move at a significant velocity, the
		/// user should raise the flag PxShapeFlag::eUSE_SWEPT_BOUNDS for them.
		/// </summary>
		EnableCcd = PxSceneFlag::eENABLE_CCD,

		DisableCcdResweep = PxSceneFlag::eDISABLE_CCD_RESWEEP,

		/// <summary>
		/// Enable adaptive forces to accelerate convergence of the solver.
		/// Note that this flag is not mutable, and must be set in PxSceneDesc at scene creation.
		/// Default: true 
		/// </summary>
		AdaptiveForce = PxSceneFlag::eADAPTIVE_FORCE,

		/// <summary>
		/// Enable GJK-based distance collision detection system.
		/// Note that this flag is not mutable, and must be set in PxSceneDesc at scene creation.
		/// In order to use this system, we need to register the system in the PxCreatePhysics
		/// Default: false 
		/// </summary>
		EnablePcm = PxSceneFlag::eENABLE_PCM,

		/// <summary>
		/// Disable contact report buffer resize. Once the contact buffer is full, the rest of
		/// the contact reports will not be buffered and sent. 
		/// Note that this flag is not mutable, and must be set in PxSceneDesc at scene creation.
		/// Default: false 
		/// </summary>
		DisableContactReportBufferSize = PxSceneFlag::eDISABLE_CONTACT_REPORT_BUFFER_RESIZE,

		DisableContactCache = PxSceneFlag::eDISABLE_CONTACT_CACHE,

		RequireReadWriteLock = PxSceneFlag::eREQUIRE_RW_LOCK,

		EnableStabilization = PxSceneFlag::eENABLE_STABILIZATION,
		EnableAveragePoint = PxSceneFlag::eENABLE_AVERAGE_POINT,
		ExcludeKinematicsFromActiveActors = PxSceneFlag::eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS,
		EnableGpuDynamics = PxSceneFlag::eENABLE_GPU_DYNAMICS,
		EnableEnhancedDeterminism = PxSceneFlag::eENABLE_ENHANCED_DETERMINISM,

		MutableFlags = PxSceneFlag::eMUTABLE_FLAGS
	};

	public enum class VisualizationParameter
	{
		/// <summary>
		/// This overall visualization scale gets multiplied with the individual scales.
		/// Setting to zero turns ignores all visualizations. Default is 0.
		/// </summary>
		Scale = PxVisualizationParameter::eSCALE,
		/// <summary>
		/// Visualize the world axes.
		/// </summary>
		WorldAxes = PxVisualizationParameter::eWORLD_AXES,
		/// <summary>
		/// Visualize a bodies axes.
		/// </summary>
		BodyAxes = PxVisualizationParameter::eBODY_AXES,
		/// <summary>
		/// Visualize a body's mass axes. 
		/// This visualization is also useful for visualizing the sleep state of bodies. Sleeping bodies are drawn in black, while
		/// awake bodies are drawn in white. If the body is sleeping and part of a sleeping group, it is drawn in red.
		/// </summary>
		BodyMassAxes = PxVisualizationParameter::eBODY_MASS_AXES,
		/// <summary>
		/// Visualize the bodies linear velocity.
		/// </summary>
		LinearVelocity = PxVisualizationParameter::eBODY_LIN_VELOCITY,
		/// <summary>
		/// Visualize the bodies angular velocity.
		/// </summary>
		AngularVelocity = PxVisualizationParameter::eBODY_ANG_VELOCITY,
		/// <summary>
		/// Visualize contact points. Will enable contact information.
		/// </summary>
		ContactPoint = PxVisualizationParameter::eCONTACT_POINT,
		/// <summary>
		/// Visualize contact normals. Will enable contact information.
		/// </summary>
		ContactNormal = PxVisualizationParameter::eCONTACT_NORMAL,
		/// <summary>
		/// Visualize contact errors. Will enable contact information.
		/// </summary>
		ContactError = PxVisualizationParameter::eCONTACT_ERROR,
		/// <summary>
		/// Visualize Contact forces. Will enable contact information.
		/// </summary>
		ContactForce = PxVisualizationParameter::eCONTACT_FORCE,
		/// <summary>
		/// Visualize actor axes.
		/// </summary>
		ActorAxes = PxVisualizationParameter::eACTOR_AXES,
		/// <summary>
		/// Visualize bounds (AABBs in world space).
		/// </summary>
		CollisionAABB = PxVisualizationParameter::eCOLLISION_AABBS,
		/// <summary>
		/// Shape visualization.
		/// </summary>
		CollisionShapes = PxVisualizationParameter::eCOLLISION_SHAPES,
		/// <summary>
		/// Shape axis visualization.
		/// </summary>
		CollisionAxes = PxVisualizationParameter::eCOLLISION_AXES,
		/// <summary>
		/// Compound visualization (compound AABBs in world space).
		/// </summary>
		CollisionCompounds = PxVisualizationParameter::eCOLLISION_COMPOUNDS,
		/// <summary>
		/// Mesh & convex face normals.
		/// </summary>
		CollisionFaceNormals = PxVisualizationParameter::eCOLLISION_FNORMALS,
		/// <summary>
		/// Active edges for meshes.
		/// </summary>
		CollisionEdges = PxVisualizationParameter::eCOLLISION_EDGES,
		/// <summary>
		/// Static pruning structures.
		/// </summary>
		CollisionStatic = PxVisualizationParameter::eCOLLISION_STATIC,
		/// <summary>
		/// Dynamic pruning structures.
		/// </summary>
		CollisionDynamic = PxVisualizationParameter::eCOLLISION_DYNAMIC,
		///// <summary>
		///// Convex decomposition of triangle meshes.
		///// </summary>
		//CollisionConvexParts = PxVisualizationParameter::eCOLLISION_CONVEX_PARTS,
		/// <summary>
		/// Visualizes pairwise state.
		/// </summary>
		DeprecatedCollisionPairs = PxVisualizationParameter::eDEPRECATED_COLLISION_PAIRS,
		/// <summary>
		/// Joint local axes.
		/// </summary>
		JointLocalFrames = PxVisualizationParameter::eJOINT_LOCAL_FRAMES,
		/// <summary>
		/// Joint limits.
		/// </summary>
		JointLimits = PxVisualizationParameter::eJOINT_LIMITS,
		/// <summary>
		/// Debug visualization culling.
		/// </summary>
		CullBox = PxVisualizationParameter::eCULL_BOX,
		/// <summary>
		/// MBP regions.
		/// </summary>
		MBPRegions = PxVisualizationParameter::eMBP_REGIONS
	};

	public enum class HitFlag
	{
		/// <summary>
		/// "position" member of PxQueryHit is valid.
		/// </summary>
		Position = PxHitFlag::ePOSITION,

		/// <summary>
		/// "normal" member of PxQueryHit is valid.
		/// </summary>
		Normal = PxHitFlag::eNORMAL,

		/// <summary>
		/// "u" and "v" barycentric coordinates of PxQueryHit are valid. Not applicable to sweep queries.
		/// </summary>
		UV = PxHitFlag::eUV,

		/// <summary>
		/// Performance hint flag for sweeps when it is known upfront there's no initial overlap. NOTE: using this flag may cause undefined results if shapes are initially overlapping.
		/// </summary>
		AssumeInitialOverlapDisabled = PxHitFlag::eASSUME_NO_INITIAL_OVERLAP,

		/// <summary>
		/// Report all hits for meshes rather than just the first. On SPU the number of reported hits per mesh is limited to 16 in no specific order.
		/// </summary>
		MeshMultiple = PxHitFlag::eMESH_MULTIPLE,

		/// <summary>
		/// Report any first hit for meshes. If neither eMESH_MULTIPLE or eMESH_ANY is specified, a single closest hit will be reported for meshes.
		/// </summary>
		MeshAny = PxHitFlag::eMESH_ANY,

		/// <summary>
		/// Report hits with back faces of triangles. Also report hits for raycast originating on mesh surface and facing away from the surface normal.
		/// </summary>
		MeshBothSides = PxHitFlag::eMESH_BOTH_SIDES,

		/// <summary>
		/// Use more accurate but slower narrow phase sweep tests. May provide better compatibility with PhysX 3.2 sweep behavior. Ignored on SPU.
		/// </summary>
		PreciseSweep = PxHitFlag::ePRECISE_SWEEP,

		/// <summary>
		/// Report the minimum translation depth, normal and contact point. Ignored on SPU.
		/// </summary>
		MinimumTranslationDirection = PxHitFlag::eMTD,

		/// <summary>
		/// 
		/// </summary>
		Default = PxHitFlag::eDEFAULT,

		/// <summary>
		/// Only this subset of flags can be modified by pre-filter. Other modifications will be discarded.
		/// </summary>
		ModifiableFlags = PxHitFlag::eMODIFIABLE_FLAGS
	};

	/// <summary>
	/// Filtering flags for scene queries.
	/// </summary>
	public enum class QueryFlag
	{
		/// <summary>
		/// Traverse static shapes.
		/// </summary>
		Static = PxQueryFlag::eSTATIC,
		/// <summary>
		/// Traverse dynamic shapes.
		/// </summary>
		Dynamic = PxQueryFlag::eDYNAMIC,
		/// <summary>
		/// Run the pre-intersection-test filter (see <see cref="SceneQueryFilterCallback.PreFilter" />). 
		/// </summary>
		Prefilter = PxQueryFlag::ePREFILTER,
		/// <summary>
		/// Run the post-intersection-test filter (see <see cref="SceneQueryFilterCallback.PostFilter" />).
		/// </summary>
		PostFilter = PxQueryFlag::ePOSTFILTER,
		AnyHit = PxQueryFlag::eANY_HIT,
		NoBlock = PxQueryFlag::eNO_BLOCK
	};

	public enum class QueryHitType
	{
		None = PxQueryHitType::eNONE,
		Block = PxQueryHitType::eBLOCK,
		Touch = PxQueryHitType::eTOUCH
	};

	public enum class SceneQueryUpdateMode
	{
		/// <summary>
		/// Both scene query build and commit are executed.
		/// </summary>
		EnabledCommitEnabled = PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED,
		/// <summary>
		/// Scene query build only is executed.
		/// </summary>
		EnabledCommitDisabled = PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED,
		/// <summary>
		/// No work is done, no update of scene queries.
		/// </summary>
		DisabledCommitDisabled = PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED,
	};

	/// <summary>
	/// Enum for selecting the type of solver used for the simulation.
	/// </summary>
	public enum class SolverType
	{
		/// <summary>
		/// Selects the default iterative sequential impulse solver. This is the same kind of solver
		/// used in PhysX 3.4 and earlier releases.
		/// </summary>
		PGS = PxSolverType::ePGS,

		/// <summary>
		/// Selects a non linear iterative solver. This kind of solver can lead to improved convergence
		/// and handle large mass ratios, long chains and jointed systems better. It is slightly more expensive 
		/// than the default solver and can introduce more energy to correct joint and contact errors.
		/// </summary>
		TGS = PxSolverType::eTGS
	};
};

<|start_filename|>PhysX.Net/Test/Stream/DefaultMemoryOutputStreamTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Stream
{
	[TestClass]
	public class DefaultMemoryOutputStreamTest : Test
	{
		[TestMethod]
		public void InitalizeAndGetData()
		{
			using (var foundation = new Foundation())
			{
				var buffer = new byte[] { 1, 2, 3, 4, 5 };

				using (var stream = new DefaultMemoryOutputStream(buffer))
				{
					var bufferOut = stream.GetData();

					Assert.IsNotNull(bufferOut);
					Assert.AreEqual(5, bufferOut.Length);
				}
			}
		}

		[TestMethod]
		public void InitalizeWithEmptyBuffer()
		{
			using (var foundation = new Foundation())
			{
				using (var stream = new DefaultMemoryOutputStream(new byte[] { }))
				{

				}
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/HeightField/HeightFieldTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class HeightFieldTest : Test
	{
		[TestMethod]
		public void CreateAndDisposeHeightField()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				const int rows = 25, columns = 25;
				var samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

				var heightFieldDesc = new HeightFieldDesc
				{
					NumberOfRows = rows,
					NumberOfColumns = columns,
					Samples = samples
				};

				var cooking = physics.Physics.CreateCooking();

				var stream = new MemoryStream();
				bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

				stream.Position = 0;

				HeightField heightField;
				using (heightField = physics.Physics.CreateHeightField(stream))
				{
					Assert.IsNotNull(heightField);
					Assert.IsFalse(heightField.Disposed);
				}

				Assert.IsTrue(heightField.Disposed);
			}
		}

		[TestMethod]
		public void MultipleDisposeCallsDoNotCauseAnException()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				const int rows = 25, columns = 25;
				var samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

				var heightFieldDesc = new HeightFieldDesc()
				{
					NumberOfRows = rows,
					NumberOfColumns = columns,
					Samples = samples
				};

				var cooking = physics.Physics.CreateCooking();

				var stream = new MemoryStream();
				bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

				stream.Position = 0;

				HeightField heightField = physics.Physics.CreateHeightField(stream);

				Assert.IsFalse(heightField.Disposed);

				// Dispose
				heightField.Dispose();
				Assert.IsTrue(heightField.Disposed);

				// Dispose again
				heightField.Dispose();
				Assert.IsTrue(heightField.Disposed);
			}
		}

		[TestMethod]
		public void MultipleInstancesAreValid()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				// A
				{
					const int rows = 25, columns = 25;
					var samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

					var heightFieldDesc = new HeightFieldDesc()
					{
						NumberOfRows = rows,
						NumberOfColumns = columns,
						Samples = samples
					};

					var cooking = physics.Physics.CreateCooking();

					var stream = new MemoryStream();
					bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

					stream.Position = 0;

					HeightField heightField = physics.Physics.CreateHeightField(stream);
				}

				// B
				{
					const int rows = 25, columns = 25;
					var samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

					var heightFieldDesc = new HeightFieldDesc()
					{
						NumberOfRows = rows,
						NumberOfColumns = columns,
						Samples = samples
					};

					var cooking = physics.Physics.CreateCooking();

					var stream = new MemoryStream();
					bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

					stream.Position = 0;

					HeightField heightField = physics.Physics.CreateHeightField(stream);
				}
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Geometry/Model.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Buffer = SharpDX.Direct3D11.Buffer;

namespace PhysX.Samples.Engine
{
	public class Model
	{
		public Buffer VertexBuffer { get; set; }
		public Buffer IndexBuffer { get; set; }
		public int IndexCount { get; set; }

		public Vector3[] VertexPositions { get; set; }
		public int[] Indices { get; set; }
	}
}

<|start_filename|>PhysX.Net/Test/Test/PhysicsAndSceneTestUnit.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PhysX.Test
{
	public class PhysicsAndSceneTestUnit : System.IDisposable
	{
		public Foundation Foundation { get; set; }
		public Physics Physics { get; set; }
		public Scene Scene { get; set; }
		public ErrorLog ErrorOutput { get; set; }

		#region IDisposable Members

		public void Dispose()
		{
			if (Foundation != null && !Foundation.Disposed)
				Foundation.Dispose();

			Foundation = null;
			Physics = null;
			Scene = null;
			ErrorOutput = null;
		}

		#endregion
	}
}

<|start_filename|>PhysX.Net/Test/Cooking/CookingTriangleMeshTests.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PhysX.Test.Util;

namespace PhysX.Test.Cooking
{
	[TestClass]
	public class CookingTriangleMeshTests : Test
	{
		[TestMethod]
		public void CookTriangleMesh()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				// Create a grid of triangles to be our triangle-mesh
				var clothGrid = new VertexGrid(25, 25);

				using (var cooking = physics.Physics.CreateCooking())
				{
					var desc = new TriangleMeshDesc()
					{
						Points = clothGrid.Points,
						Triangles = clothGrid.Indices
					};

					var stream = new MemoryStream();

					var result = cooking.CookTriangleMesh(desc, stream);

					Assert.AreEqual(TriangleMeshCookingResult.Success, result);
				}
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/CharacterSample/CharacterSample.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Windows.Input;
using PhysX.Samples.Engine;

namespace PhysX.Samples.CharacterSample
{
    public class CharacterSample : Sample
    {
        private CapsuleController _controller;
        private float _rotation;
        private const float _cameraDistance = 15;
        private const float _controllerSpeed = 0.1f;

        public CharacterSample()
        {
            Run();

            _rotation = 0;
        }

        protected override void LoadContent()
        {

        }

        protected override void LoadPhysics(Scene scene)
        {
            var material = scene.Physics.CreateMaterial(0.1f, 0.1f, 0.1f);

            var controllerManager = scene.CreateControllerManager();

            // User controllable character
            {
                var desc = new CapsuleControllerDesc()
                {
                    Height = 4,
                    Radius = 1,
                    Material = material,
                    UpDirection = new Vector3(0, 1, 0),
                    Position = new Vector3(0, 3, 0),
                    ReportCallback = new ControllerHitReport()
                };

                _controller = controllerManager.CreateController<CapsuleController>(desc);
            }

            // Another controller to walk into
            {
                var desc = new CapsuleControllerDesc()
                {
                    Height = 4,
                    Radius = 1,
                    Material = material,
                    UpDirection = new Vector3(0, 1, 0),
                    Position = new Vector3(15, 3, 15)
                };

                controllerManager.CreateController<CapsuleController>(desc);
            }
        }

        protected override void Update(TimeSpan elapsed)
        {
            // Controllers don't have gravity by default, so we'll need to calculate this acceleration ourselves.
            ProcessGravity();

            //

            // Camera
            Vector3 controllerPosition = _controller.Position.As<Vector3>();

            // Create a rotation matrix around the y-axis
            var rotation = Matrix4x4.CreateFromAxisAngle(Vector3.UnitY, _rotation);
            // Rotate the 'fowards' vector by the rotation matrix, then stretch it out a distance
            Vector3 cameraOffset = Vector3.Transform(-Vector3.UnitZ, rotation) * _cameraDistance;

            // Start at the controllers position, move the camera backwards, move the camera up slightly
            Vector3 p = controllerPosition
                + cameraOffset
                + new Vector3(0, 3, 0);

            // Recreate the cameras view matrix from our computed position, target (and static up direction)
            this.Engine.Camera.View = SharpDX.Matrix.LookAtLH(
                p.As<SharpDX.Vector3>(),
                controllerPosition.As<SharpDX.Vector3>(),
                SharpDX.Vector3.UnitY);
        }

        private void ProcessGravity()
        {
            //// Gravity
            //float dt = (float)this.FrameTime.TotalSeconds;

            //if (dt == 0 || dt > 0.5)
            //    return;

            //if (_previousControllerPosition == null)
            //    _previousControllerPosition = _controller.Position;


            //var v = (_controller.Position - _previousControllerPosition.Value) * (1.0f / dt) + this.Scene.Gravity;

            //_previousControllerPosition = _controller.Position;

            //_controller.Move(new PhysX.Math.Vector3(0, (v * dt).Y, 0));

            //Console.WriteLine((v * dt).Y);

            //_controller.ControllerManager.UpdateControllers();
        }

        protected override void ProcessKeyboard(Key[] pressedKeys)
        {
            // Create a rotation matrix around the y-axis
            var rotation = Matrix4x4.CreateFromAxisAngle(Vector3.UnitY, _rotation);

            // Compute the forwards and right movement vectors
            // The controller will move in its own space, so rotate the usual forwards and right vectors
            Vector3 forward = Vector3.TransformNormal(Vector3.UnitZ, rotation);
            Vector3 right = Vector3.TransformNormal(Vector3.UnitX, rotation);

            Vector3 moveDelta = Vector3.Zero;

            if (pressedKeys.Contains(Key.W))
                moveDelta += forward;
            if (pressedKeys.Contains(Key.S))
                moveDelta += -forward;
            if (pressedKeys.Contains(Key.A))
                moveDelta += -right;
            if (pressedKeys.Contains(Key.D))
                moveDelta += right;

            // Normalize the distance vector (as we may of added two or more components together)
            Vector3 d = moveDelta.LengthSquared() == 0 ?
                Vector3.Zero :
                Vector3.Normalize(moveDelta);

            // Move the controller in the intended direction * a speed multiplier
            _controller.Move(d * _controllerSpeed, this.Engine.FrameTime);
        }
        protected override void ProcessMouse(float deltaX, float deltaY)
        {
            // Add on (either positive or negative) a rotation amount based on the mouse movement
            // This value will be used to create rotation matrices in the above function
            _rotation += deltaX * 0.001f;
        }

        protected override void Draw()
        {

        }
    }
}

<|start_filename|>PhysX.Net/Test/Serialization/SerializationTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Serialization
{
	[TestClass]
	public class SerializationTest : Test
	{
		[TestMethod]
		public void BasicSingleCubeSerialization()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var box = CreateBoxActor(core.Scene, 5, 5, 5);

				var collection = core.Physics.CreateCollection();
				collection.Add(box);

				var sr = PhysX.Serialization.CreateSerializationRegistry(core.Physics);

				using (var serializeStream = new MemoryStream())
				{
					bool result = PhysX.Serialization.SerializeCollectionToXml(serializeStream, collection, sr);

					Assert.IsTrue(result);

					serializeStream.Flush();

					Assert.IsTrue(serializeStream.Length > 0);

					string xml;
					using (StreamReader reader = new StreamReader(serializeStream))
					{
						xml = reader.ReadToEnd();
					}
				}
			}
		}

		//[TestMethod]
		//public void DeserializeCollection()
		//{
		//    byte[] serialzedScene;

		//    // Serialize
		//    using (var core = CreatePhysicsAndScene())
		//    {
		//        CreateBoxActor(core.Scene, 5, 5, 5);

		//        var collection = core.Physics.CreateCollection();

		//        using (var serializeStream = new MemoryStream())
		//        {
		//            collection.CollectPhysicsForExport(core.Physics);

		//            collection.Serialize(serializeStream);
		//            serializeStream.Flush();
		//            serializeStream.Position = 0;

		//            serialzedScene = serializeStream.ToArray();
		//        }
		//    }

		//    // Deserialize
		//    using (var core = CreatePhysicsAndScene())
		//    {
		//        var collection = core.Physics.CreateCollection();

		//        using (var serializeStream = new MemoryStream())
		//        {
		//            serializeStream.Write(serialzedScene, 0, serialzedScene.Length);
		//            serializeStream.Position = 0;

		//            bool result = collection.Deserialize(serializeStream);

		//            Assert.IsTrue(result);
		//        }
		//    }
		//}
	}
}

<|start_filename|>PhysX.Net/Test/Scene/SceneTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PhysX;
using PhysX.Test.Util;

namespace PhysX.Test
{
	[TestClass]
	public class SceneTest : Test
	{
		[TestMethod]
		public void CreateAndDisposeSceneInstance()
		{
			using (var foundation = new Foundation())
			{
				using (var physics = new Physics(foundation))
				{
					var sceneDesc = new SceneDesc();

					Scene scene;
					using (scene = physics.CreateScene(sceneDesc))
					{
						GC.Collect();

						Assert.IsFalse(scene.Disposed);
					}

					Assert.IsFalse(physics.Disposed);
					Assert.IsTrue(scene.Disposed);
				}
			}
		}

		[TestMethod]
		public void SetGravity()
		{
			using (var core = CreatePhysicsAndScene())
			{
				core.Scene.Gravity = new Vector3(0, -9.81f, 0);

				Assert.AreEqual(new Vector3(0, -9.81f, 0), core.Scene.Gravity);
			}
		}

		[TestMethod]
		public void Raycast()
		{
			using (var core = CreatePhysicsAndScene())
			{
				// Just up from the ground, 20 units ahead
				var box1 = CreateBoxActor(core.Scene, 0, 2, 20);
				var box2 = CreateBoxActor(core.Scene, 0, 2, 40);

				Vector3 origin = new Vector3(0, 2, 0);
				Vector3 direction = new Vector3(0, 0, 1);

				RaycastHit[] hits = null;

				bool hadHit = core.Scene.Raycast
				(
					origin,
					direction,
					distance: 10000,
					maximumHits: 2,
					hitCall: h =>
					{
						hits = h;

						// Return hit again (PxAgain)
						return true;
					},
					hitFlag: HitFlag.Normal | HitFlag.Position
				);

				Assert.IsNotNull(hits);

				var hit = hits[0];

				Assert.IsNotNull(hit);
				Assert.AreEqual(17.5f, hit.Distance);
				Assert.AreEqual(new Vector3(0, 0, -1), hit.Normal);
				Assert.AreEqual(new Vector3(0, 2, 17.5f), hit.Position);
				Assert.IsNotNull(hit.Shape);
				Assert.AreEqual(box1.Shapes.First(), hit.Shape);
				Assert.AreEqual(box1, hit.Shape.Actor);
			}
		}

		[TestMethod]
		public void Overlap()
		{
			using (var core = CreatePhysicsAndScene())
			{
				// Just up from the ground, 20 units ahead
				var box1 = CreateBoxActor(core.Scene, 0, 2, 20);
				var box2 = CreateBoxActor(core.Scene, 0, 2, 40);

				box1.Name = "Box1";
				box2.Name = "Box2";

				BoxGeometry overlappingBox = new BoxGeometry(100, 100, 100);

				OverlapHit[] hits = null;

				bool result = core.Scene.Overlap
				(
					geometry: overlappingBox,
					pose: Matrix4x4.Identity,
					maximumOverlaps: 2,
					hitCall: hit =>
					{
						hits = hit;

						return true;
					}
				);

				Assert.IsNotNull(hits);
				Assert.AreEqual(2, hits.Length);

				var hitActors = hits.Select(h => h.Actor).ToArray();
				CollectionAssert.Contains(hitActors, box1);
				CollectionAssert.Contains(hitActors, box2);
			}
		}

		//[TestMethod]
		//public void SweepAny()
		//{
		//	using (var core = CreatePhysicsAndScene())
		//	{
		//		// Just up from the ground, 20 units ahead
		//		var box1 = CreateBoxActor(core.Scene, 0, 2, 20);
		//		var box2 = CreateBoxActor(core.Scene, 0, 2, 40);

		//		box1.Name = "Box1";
		//		box2.Name = "Box2";

		//		// Use a box of 10x10x10 to sweep with
		//		BoxGeometry sweepBox = new BoxGeometry(10, 10, 10);

		//		// Sweep the box forwards 25 units to hit box1
		//		var sweep = core.Scene.SweepAny
		//		(
		//			sweepBox, 
		//			Matrix4x4.CreateTranslation(0, 2, 0),
		//			new Vector3(0, 0, 1),
		//			25,
		//			SceneQueryFlags.All
		//		);

		//		Assert.IsNotNull(sweep);
		//		Assert.AreEqual(box1, sweep.Shape.Actor);
		//	}
		//}

		//[TestMethod]
		//[Ignore]
		//// This test throws an 'attempted to write to protected memory' exception, which causes
		//// the using/dispose method to be NOT called, and everything fails from there...
		//public void SweepMultiple()
		//{
		//	using (var core = CreatePhysicsAndScene())
		//	{
		//		// Just up from the ground, 20 units ahead
		//		var box1 = CreateBoxActor(core.Scene, 0, 2, 20);
		//		var box2 = CreateBoxActor(core.Scene, 0, 2, 40);

		//		box1.Name = "Box1";
		//		box2.Name = "Box2";

		//		// Use a box of 10x10x10 to sweep with
		//		BoxGeometry sweepBox = new BoxGeometry(10, 10, 10);

		//		// Sweep the box forwards 25 units to hit box1
		//		var sweep = core.Scene.SweepMultiple
		//		(
		//			sweepBox,
		//			Matrix4x4.CreateTranslation(0, 2, 0),
		//			null,
		//			new Vector3(0, 0, 1),
		//			25,
		//			SceneQueryFlags.All,
		//			2,
		//			null
		//		);

		//		Assert.IsNotNull(sweep);
		//		Assert.AreEqual(1, sweep.Count());

		//		var hit = sweep.ElementAt(0);
		//		Assert.IsNotNull(hit);
		//		Assert.IsNotNull(hit.Shape);
		//		Assert.AreEqual(box1, hit.Shape.Actor);
		//	}
		//}

		[TestMethod]
		public void GetSimulationStatisticValues()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				CreateBoxActor(physics.Scene, 2, 3, 4);

				var stats = physics.Scene.GetSimulationStatistics();

				Assert.AreEqual(1, stats.Shapes[GeometryType.Box]);
				Assert.AreEqual(1, stats.DynamicBodies);
			}
		}

		[TestMethod]
		public void GetSetSceneLimits()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				physics.Scene.SceneLimits = new SceneLimits()
				{
					MaxActors = 1,
					MaxBodies = 2,
					MaxConstraints = 3,
					MaxDynamicShapes = 4,
					MaxRegions = 5,
					MaxStaticShapes = 6,
					MaxAggregates = 7,
					MaxBroadPhaseOverlaps = 8
				};

				var limits = physics.Scene.SceneLimits;

				Assert.AreEqual(1, limits.MaxActors);
				Assert.AreEqual(2, limits.MaxBodies);
				Assert.AreEqual(3, limits.MaxConstraints);
				Assert.AreEqual(4, limits.MaxDynamicShapes);
				Assert.AreEqual(5, limits.MaxRegions);
				Assert.AreEqual(6, limits.MaxStaticShapes);
				Assert.AreEqual(7, limits.MaxAggregates);
				Assert.AreEqual(8, limits.MaxBroadPhaseOverlaps);
			}
		}

		[TestMethod]
		public void SceneDescFlagsAreMaintained()
		{
			using (var physics = new Physics(new Foundation()))
			{
				var sceneDesc = new SceneDesc
				{
					Flags = SceneFlag.EnableGpuDynamics | SceneFlag.EnableStabilization
				};

				var scene = physics.CreateScene(sceneDesc);

				Assert.IsTrue(scene.Flags.HasFlag(SceneFlag.EnableGpuDynamics));
				Assert.IsTrue(scene.Flags.HasFlag(SceneFlag.EnableStabilization));
			}
		}

		[TestMethod]
		public void GetActors_RigidDynamic()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var dynamicActor = CreateBoxActor(physics.Scene, 3, 3, 3);

				//

				var actors = physics.Scene.GetActors(ActorTypeFlag.RigidDynamic);

				Assert.AreEqual(1, actors.Count);
				Assert.AreEqual(dynamicActor, actors[0]);
			}
		}
		[TestMethod]
		public void GetActors_RigidStatic()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Scene.Physics.CreateMaterial(0.5f, 0.5f, 0.1f);
				var staticActor = physics.Scene.Physics.CreateRigidStatic();
				var shape = staticActor.CreateShape(new BoxGeometry(5, 5, 5), material);
				physics.Scene.AddActor(staticActor);

				//

				var actors = physics.Scene.GetActors(ActorTypeFlag.RigidStatic);

				Assert.AreEqual(1, actors.Count);
				Assert.AreEqual(staticActor, actors[0]);
			}
		}

		[TestMethod]
		public void CreateSceneWithTemporalGaussSeidelSolver()
		{
			using (var physics = CreatePhysics())
			{
				var sceneDesc = new SceneDesc
				{
					SolverType = SolverType.TGS
				};

				using (var scene = physics.CreateScene(sceneDesc))
				{
					
				}
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/CollisionDisabledSample/CollisionDisabledFilterShader.cs<|end_filename|>
﻿using System;

namespace PhysX.Samples.CollisionDisabledSample
{
	public class CollisionDisabledFilterShader : SimulationFilterShader
	{
		public override FilterResult Filter(int attributes0, FilterData filterData0, int attributes1, FilterData filterData1)
		{
			return new FilterResult
			{
				// Set FilterFlag to Callback to enable CollisionDisabledSimulationFilterCallback to be used
				FilterFlag = FilterFlag.Callback,
				PairFlags = PairFlag.ContactDefault
			};
		}
	}
}


<|start_filename|>PhysX.Net/Test/Geometry/GeometryQueryTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Geometry
{
	[TestClass]
	public class GeometryQueryTest
	{
		[TestMethod]
		public void Sweep()
		{
			var sweeper = new SphereGeometry(5);
			var obstacle = new SphereGeometry(3);

			var hit = GeometryQuery.Sweep
			(
				new Vector3(0, 0, 1),
				100,
				sweeper,
				Matrix4x4.CreateTranslation(0, 5, 0),
				obstacle,
				Matrix4x4.CreateTranslation(0, 5, 10)
			);

			Assert.IsNotNull(hit);
			Assert.AreEqual(2.0f, hit.Distance);
		}

		[TestMethod]
		public void GetWorldBounds()
		{
			var sphere = new SphereGeometry(5);

			var bounds = GeometryQuery.GetWorldBounds(sphere, Matrix4x4.Identity);

			// We started with a sphere of radius 5,
			// the bounding size + inflation value (3rd optional arg) results
			// in a box of size 10.1 whd
			Assert.AreEqual(new Bounds3(new Vector3(10.1f, 10.1f, 10.1f)), bounds);
		}
	}
}

<|start_filename|>PhysX.Net/Test/Joint/SphericalJointTest.cs<|end_filename|>
﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Numerics;

namespace PhysX.Test.Joint
{
	[TestClass]
	public class SphericalJointTest : Test
	{
		/// <summary>
		/// Create a joint limit cone and assign it to the spherical joint, then make sure
		/// the values have been assigned.
		/// </summary>
		[TestMethod]
		public void SetLimitCone()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var box1 = CreateBoxActor(core.Scene, new Vector3(5, 5, 5), new Vector3(0, 10, 0));
				var box2 = CreateBoxActor(core.Scene, new Vector3(5, 5, 5), new Vector3(0, 20, 0));

				SphericalJoint joint = core.Scene.CreateJoint<SphericalJoint>(box1, Matrix4x4.Identity, box2, Matrix4x4.Identity);

				// Set the limit cone
				var limit = new JointLimitCone()
				{
					YLimitAngle = 0.5f, // [0 - PI/2]
					ZLimitAngle = 0.6f, // [0 - PI/2]
					Stiffness = 3,
					Damping = 4,
					Restitution = 0.7f // [0 - 1]
				};

				joint.SetLimitCone(limit);

				// Get the limit cone back and compare the values to make sure they've been stored
				var retrievedLimitCone = joint.GetLimitCone();

				Assert.AreEqual(0.5f, retrievedLimitCone.YLimitAngle);
				Assert.AreEqual(0.6f, retrievedLimitCone.ZLimitAngle);
				Assert.AreEqual(3, retrievedLimitCone.Stiffness);
				Assert.AreEqual(4, retrievedLimitCone.Damping);
				Assert.AreEqual(0.7f, retrievedLimitCone.Restitution);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Util/ArrayUtil.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace PhysX.Test.Util
{
	public static class ArrayUtil
	{
		public static byte[] ToByteArray<T>(T[] array)
			where T : struct
		{
			int t = Marshal.SizeOf(typeof(T));

			GCHandle pinSrc = GCHandle.Alloc(array, GCHandleType.Pinned);

			var bytes = new byte[t * array.Length];

			Marshal.Copy(pinSrc.AddrOfPinnedObject(), bytes, 0, t * array.Length);

			pinSrc.Free();

			return bytes;
		}
	}
}

<|start_filename|>PhysX.Net/Test/HeightField/HeightFieldTestUtil.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PhysX.Test
{
	public static class HeightFieldTestUtil
	{
		public static HeightFieldSample[] CreateSampleGrid(int rows, int columns, short height = 100)
		{
			var samples = new HeightFieldSample[rows * columns];

			for (int r = 0; r < rows; r++)
			{
				for (int c = 0; c < columns; c++)
				{
					// Put a z and x curve together
					double h = System.Math.Sin(c) * System.Math.Cos(r) * height;

					var sample = new HeightFieldSample()
					{
						Height = (short)h
					};

					samples[r * columns + c] = sample;
				}
			}

			return samples;
		}
	}
}

<|start_filename|>PhysX.Net/Test/Controller/CapsuleControllerDescTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Controller
{
	[TestClass]
	public class CapsuleControllerDescTest : Test
	{
		[TestMethod]
		public void SetToDefault()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(1, 2, 3);

				// Change all the properties of a CapsuleControllerDesc
				var c = new CapsuleControllerDesc()
				{
					ClimbingMode = CapsuleClimbingMode.Easy,
					ContactOffset = 99,
					Density = 100,
					Height = 101,
					Material = material,
					NonWalkableMode = ControllerNonWalkableMode.PreventClimbing,
					Position = new Vector3(1, 2, 3),
					Radius = 104,
					ScaleCoefficient = 105,
					SlopeLimit = 106,
					StepOffset = 107,
					UpDirection = new Vector3(0, 0, 1),
				};

				// Set the description to default
				c.SetToDefault();

				// Capsule
				Assert.AreEqual(CapsuleClimbingMode.Easy, c.ClimbingMode);
				Assert.AreEqual(0, c.Radius);
				Assert.AreEqual(0, c.Height);

				// ControllerDesc
				Assert.AreEqual(0.1f, c.ContactOffset);
				Assert.AreEqual(0.5f, c.StepOffset);
				Assert.AreEqual(10.0f, c.Density);
				Assert.AreEqual(0.8f, c.ScaleCoefficient);
				Assert.AreEqual(new Vector3(0, 0, 0), c.Position);
				Assert.IsNull(c.Material);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Extensions/MathExtensions.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PhysX.Samples.Engine
{
	public static class MathExtensions
	{
		public static SharpDX.Vector3 AsSharpDX(this System.Numerics.Vector3 vector3)
		{
			return new SharpDX.Vector3(vector3.X, vector3.Y, vector3.Z);
		}

		public static System.Numerics.Vector3 AsPhysX(this SharpDX.Vector3 vector3)
		{
			return new System.Numerics.Vector3(vector3.X, vector3.Y, vector3.Z);
		}

		//public static System.Numerics.Matrix4x4 AsPhysX(this SharpDX.Matrix m)
		//{
		//	return new System.Numerics.Matrix4x4
		//	(
		//		m.M11, m.M12, m.M13, m.M14,
		//		m.M21, m.M22, m.M23, m.M24,
		//		m.M31, m.M32, m.M33, m.M34,
		//		m.M41, m.M42, m.M43, m.M44
		//	);
		//}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Math/Math.cs<|end_filename|>
using System;
using System.Collections.Generic;
using SharpDX;

namespace PhysX.Samples
{
	public static class Mathematics
	{
		public static Vector3 DirectionFromViewMatrix(Matrix viewMatrix)
		{
			return Vector3.Normalize(new Vector3(viewMatrix.M13, viewMatrix.M23, viewMatrix.M33));
		}
	}
}

<|start_filename|>PhysX.Net/Test/ObservableTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class ObservableTest : Test
	{
		//[TestMethod]
		//public void GetObservableType()
		//{
		//	using (var core = CreatePhysicsAndScene())
		//	{
		//		var actor = core.Physics.CreateRigidDynamic();

		//		Assert.AreEqual(ObservableType.Actor, actor.GetObservableType());
		//	}
		//}

		//[TestMethod]
		//public void GetNumberOfObservers_InitiallyZero()
		//{
		//	using (var core = CreatePhysicsAndScene())
		//	{
		//		var actor = core.Physics.CreateRigidDynamic();

		//		Assert.AreEqual(0, actor.GetNumberOfObservers());
		//	}
		//}

		//[TestMethod]
		//public void GetObservers_InitiallyZero()
		//{
		//	using (var core = CreatePhysicsAndScene())
		//	{
		//		var actor = core.Physics.CreateRigidDynamic();

		//		Assert.IsNotNull(actor.GetObservers());
		//		Assert.AreEqual(0, actor.GetObservers().Length);
		//	}
		//}
	}
}

<|start_filename|>PhysX.Net/PhysX.Net/Source/MathUtil.cpp<|end_filename|>
#include "StdAfx.h"
#include "MathUtil.h"

using namespace PhysX;

Matrix MathUtil::PxTransformToMatrix(PxTransform* transform)
{
	// TODO: This looks less than efficient
	Quaternion q = Quaternion(transform->q.x, transform->q.y, transform->q.z, transform->q.w);
	Matrix m = 
		Matrix::CreateFromQuaternion(q) *
		Matrix::CreateTranslation(transform->p.x, transform->p.y, transform->p.z);
	
	return m;
}
PxTransform MathUtil::MatrixToPxTransform(Matrix matrix)
{
	// TODO: This looks less than efficient
	Quaternion q = Quaternion::CreateFromRotationMatrix(matrix);

	PxTransform t;
		t.p = PxVec3(matrix.M41, matrix.M42, matrix.M43);
		t.q = PxQuat(q.X, q.Y, q.Z, q.W);

	return t;
}

Matrix MathUtil::PxMat33ToMatrix(PxMat33* matrix)
{
	// TODO: memcpy?
	Matrix m = Matrix::Identity;

	m.M11 = matrix->column0.x;
	m.M21 = matrix->column0.y;
	m.M31 = matrix->column0.z;
	
	m.M12 = matrix->column1.x;
	m.M22 = matrix->column1.y;
	m.M32 = matrix->column1.z;
			
	m.M13 = matrix->column2.x;
	m.M23 = matrix->column2.y;
	m.M33 = matrix->column2.z;

	return m;
}
PxMat33 MathUtil::MatrixToPxMat33(Matrix matrix)
{
	PxMat33 mat33;

	mat33.column0.x = matrix.M11;
	mat33.column0.y = matrix.M21;
	mat33.column0.z = matrix.M31;

	mat33.column1.x = matrix.M12;
	mat33.column1.y = matrix.M22;
	mat33.column1.z = matrix.M32;

	mat33.column2.x = matrix.M13;
	mat33.column2.y = matrix.M23;
	mat33.column2.z = matrix.M33;

	return mat33;
}

Matrix MathUtil::PxMat44ToMatrix(PxMat44* mat44)
{
	Matrix m;

	pin_ptr<Matrix> m_pin = &m;

	memcpy(m_pin, mat44, sizeof(PxMat44));

	return m;
}
PxMat44 MathUtil::MatrixToPxMat44(Matrix matrix)
{
	pin_ptr<Matrix> m_pin = &matrix;

	PxMat44 mat44;

	memcpy(&mat44, m_pin, sizeof(PxMat44));

	return mat44;
}

Vector3 MathUtil::PxVec3ToVector3(PxVec3 vector)
{
	return Vector3(vector.x, vector.y, vector.z);
}
PxVec3 MathUtil::Vector3ToPxVec3(Vector3 vector)
{
	return PxVec3(vector.X, vector.Y, vector.Z);
}

Vector3 MathUtil::PxExtendedVec3ToVector3(PxExtendedVec3 vector)
{
	return Vector3((float)vector.x, (float)vector.y, (float)vector.z);
}
PxExtendedVec3 MathUtil::Vector3ToPxExtendedVec3(Vector3 vector)
{
	return PxExtendedVec3(vector.X, vector.Y, vector.Z);
}

Vector2 MathUtil::PxVec2ToVector2(PxVec2 vector)
{
	return Vector2(vector.x, vector.y);
}
PxVec2 MathUtil::Vector2ToPxVec2(Vector2 vector)
{
	return PxVec2(vector.X, vector.Y);
}

Quaternion MathUtil::PxQuatToQuaternion(PxQuat quat)
{
	return Quaternion(quat.x, quat.y, quat.z, quat.w);
}
PxQuat MathUtil::QuaternionToPxQuat(Quaternion quat)
{
	return PxQuat(quat.X, quat.Y, quat.Z, quat.W);
}

bool MathUtil::IsMultipleOf(int num, int divisor)
{
	return (num % divisor) == 0;
}

<|start_filename|>PhysX.Net/Test/Controller/ControllerTest.cs<|end_filename|>
﻿using System;
using System.Linq;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Controller
{
	[TestClass]
	public class ControllerTest : Test
	{
		[TestMethod]
		public void ControllerStateIsValid()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var controllerManager = core.Scene.CreateControllerManager();

				var material = core.Physics.CreateMaterial(0.1f, 0.1f, 0.1f);

				var desc = new CapsuleControllerDesc()
				{
					Height = 12,
					Radius = 7,
					Material = material,
					Position = new Vector3(0, 25, 0)
				};

				// Create a capsule controller
				var capsuleController = controllerManager.CreateController<CapsuleController>(desc);

				// A box for it to fall on to
				var box = CreateBoxActor(core.Scene, new Vector3(10, 1, 10), new Vector3(0, 0.5f, 0));

				// Make it fall
				for (int i = 0; i < 200; i++)
				{
					capsuleController.Move(new Vector3(0, -0.3f, 0), TimeSpan.FromMilliseconds(0.1));

					core.Scene.Simulate(0.1f);
					core.Scene.FetchResults(block: true);
				}

				//

				var controllerState = capsuleController.GetState();

				Assert.IsNotNull(controllerState);
				Assert.AreEqual(box.Shapes.First(), controllerState.TouchedShape);
				Assert.AreEqual(box, controllerState.TouchedActor);
				Assert.AreEqual(ControllerCollisionFlag.Down, controllerState.CollisionFlags);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Cooking/CookConvexMeshTests.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PhysX.Test.Util;

namespace PhysX.Test.Cooking
{
	[TestClass]
	public class CookTest : Test
	{
		/// <summary>
		/// Cook a convex mesh (a teapot).
		/// </summary>
		[TestMethod]
		public void CookConvexMesh()
		{
			string teapotXml;
			using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PhysX.Test.Resources.Teapot.DAE"))
			{
				var streamReader = new StreamReader(stream);

				teapotXml = streamReader.ReadToEnd();
			}

			using (var physics = CreatePhysicsAndScene())
			{
				var colladaLoader = new ColladaLoader();

				// Read the vertices and indices from the Teapot.DAE collada file
				// This file is copied out to the TestResults folder using the DeploymentItem attribute on this class
				var teapot = colladaLoader.Load(teapotXml);

				using (var cooking = physics.Physics.CreateCooking())
				{
					var desc = new ConvexMeshDesc();
					desc.SetTriangles(teapot.Indices);
					desc.SetPositions(teapot.Vertices);
					desc.Flags = ConvexFlag.ComputeConvex;

					var stream = new MemoryStream();

					var result = cooking.CookConvexMesh(desc, stream);

					Assert.IsFalse(physics.ErrorOutput.HasErrors, physics.ErrorOutput.LastError);
					Assert.AreEqual(ConvexMeshCookingResult.Success, result);
				}
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/ObjectTable/ObjectTableTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class ObjectTableTest : Test
	{
		[TestInitialize]
		public void InitalizeTest()
		{
			// Make sure the object table is completely empty at the beginning of each test
			// TODO: This need should be elimited once the object table class is changed to be a singleton pattern instead
			// of a static class
			ObjectTable.Instance.Clear();
		}

		[TestMethod]
		public void OwnershipDisposale()
		{
			// Create a hierarchy of objects -
			// Physics is the root
			//	Scene
			//		Actor1
			//		Actor2
			//	Material1
			//	Material2
			var physics = new MockPhysics();
			var scene = new MockScene();
			var mat1 = new MockMaterial();
			var mat2 = new MockMaterial();
			var actor1 = new MockActor();
			var actor2 = new MockActor();

			ObjectTable.Instance.Add(1, physics, null);
			ObjectTable.Instance.Add(2, mat1, physics);
			ObjectTable.Instance.Add(3, mat2, physics);
			ObjectTable.Instance.Add(4, scene, physics);
			ObjectTable.Instance.Add(5, actor1, scene);
			ObjectTable.Instance.Add(6, actor2, scene);

			//

			// Dispose of the root object. This should dispose all object beneath it recursively
			physics.Dispose();

			Assert.IsTrue(physics.Disposed);
			Assert.IsTrue(mat1.Disposed);
			Assert.IsTrue(mat2.Disposed);
			Assert.IsTrue(scene.Disposed);
			Assert.IsTrue(actor1.Disposed);
			Assert.IsTrue(actor2.Disposed);
		}

		[TestMethod]
		public void EnsureUnmanagedObjectIsOnlyWrappedOnce()
		{
			var obj0 = new MockPhysics();
			var obj1 = new MockPhysics();

			// Add the object at address '5'
			ObjectTable.Instance.Add(5, obj0, null);

			// We should not be able to add the same unmanaged address
			try
			{
				ObjectTable.Instance.Add(5, obj1, null);

				Assert.Fail("The unmanaged object/address has already been wrapped and added to the ObjectTable, it can not be added again, instead it should be retrieved");
			}
			catch (InvalidOperationException)
			{

			}
		}

		[TestMethod]
		public void GetObjectsOfOwnerAndType()
		{
			var physics = new MockPhysics();

			// Create 2 material
			var material1 = new MockMaterial();
			var material2 = new MockMaterial();

			// Add them to the object table with the physics parent
			ObjectTable.Instance.Add(5, material1, physics);
			ObjectTable.Instance.Add(6, material2, physics);

			// Ask for the 2 material owned by the physics
			var materialsOfPhysics = ObjectTable.Instance.GetObjectsOfOwnerAndType<MockMaterial>(physics);

			Assert.IsNotNull(materialsOfPhysics);
			Assert.AreEqual(2, materialsOfPhysics.Count());
		}

		[TestMethod]
		public void GetObjectsOfOwnerAndType_MultipleEnumerationsYieldTheSameObjects()
		{
			var physics = new MockPhysics();

			// Create 2 material
			var material1 = new MockMaterial();
			var material2 = new MockMaterial();

			// Add them to the object table with the physics parent
			ObjectTable.Instance.Add(5, material1, physics);
			ObjectTable.Instance.Add(6, material2, physics);

			// Ask for the 2 material owned by the physics
			var materialsOfPhysics = ObjectTable.Instance.GetObjectsOfOwnerAndType<MockMaterial>(physics);

			Assert.IsNotNull(materialsOfPhysics);

			// Enumerate the objects once
			Assert.AreEqual(2, materialsOfPhysics.Count());

			// Enumerate the object again
			Assert.AreEqual(2, materialsOfPhysics.Count());
		}

		[TestMethod]
		public void Disposing_RemovedFromObjectTableDictionary()
		{
			var physics = new MockPhysics();

			var material1 = new MockMaterial();
			var material2 = new MockMaterial();

			ObjectTable.Instance.Add(5, material1, physics);
			ObjectTable.Instance.Add(6, material2, physics);

			// Make sure the objects are present to begin with
			Assert.IsTrue(ObjectTable.Instance.Objects.ContainsValue(material1));
			Assert.IsTrue(ObjectTable.Instance.Objects.ContainsValue(material2));

			material2.Dispose();

			Assert.IsTrue(ObjectTable.Instance.Objects.ContainsValue(material1));
			Assert.IsFalse(ObjectTable.Instance.Objects.ContainsValue(material2));
		}

		[TestMethod]
		public void Disposing_RemovedFromOwnershipDictionary()
		{
			var physics = new MockPhysics();

			var material1 = new MockMaterial();
			var material2 = new MockMaterial();

			ObjectTable.Instance.Add(5, material1, physics);
			ObjectTable.Instance.Add(6, material2, physics);

			// Make sure the objects are present to begin with
			Assert.IsTrue(ObjectTable.Instance.Ownership.ContainsKey(material1));
			Assert.IsTrue(ObjectTable.Instance.Ownership.ContainsKey(material2));

			material2.Dispose();

			Assert.IsTrue(ObjectTable.Instance.Ownership.ContainsKey(material1));
			Assert.IsFalse(ObjectTable.Instance.Ownership.ContainsKey(material2));
		}

		[TestMethod]
		public void Disposing_RemovedFromOwnerTypeDictionary()
		{
			var physics = new MockPhysics();

			var material1 = new MockMaterial();
			var material2 = new MockMaterial();

			ObjectTable.Instance.Add(5, material1, physics);
			ObjectTable.Instance.Add(6, material2, physics);

			// Make sure the objects are present to begin with
			{
				var materialKey = new ObjectTableOwnershipType(physics, typeof(MockMaterial));

				Assert.IsTrue(ObjectTable.Instance.OwnerTypeLookup.ContainsKey(materialKey));

				var materialsOwnedByPhysics = ObjectTable.Instance.GetObjectsOfOwnerAndType<MockMaterial>(physics);

				Assert.IsNotNull(materialsOwnedByPhysics);
				Assert.AreEqual(2, materialsOwnedByPhysics.Count());
				Assert.AreEqual(material1, materialsOwnedByPhysics.ElementAt(0));
				Assert.AreEqual(material2, materialsOwnedByPhysics.ElementAt(1));
			}

			material1.Dispose();

			{
				var materialKey = new ObjectTableOwnershipType(physics, typeof(MockMaterial));

				Assert.IsTrue(ObjectTable.Instance.OwnerTypeLookup.ContainsKey(materialKey));

				var materialsOwnedByPhysics = ObjectTable.Instance.GetObjectsOfOwnerAndType<MockMaterial>(physics);

				Assert.IsNotNull(materialsOwnedByPhysics);
				Assert.AreEqual(1, materialsOwnedByPhysics.Count());
				Assert.AreEqual(material2, materialsOwnedByPhysics.ElementAt(0));
			}
		}

		[TestMethod]
		public void Disposing_OwnerTypeListIsRemovedWhenEmpty()
		{
			var physics = new MockPhysics();

			var material1 = new MockMaterial();
			var material2 = new MockMaterial();

			ObjectTable.Instance.Add(5, material1, physics);
			ObjectTable.Instance.Add(6, material2, physics);

			// Make sure the objects are present to begin with
			{
				var materialKey = new ObjectTableOwnershipType(physics, typeof(MockMaterial));

				Assert.IsTrue(ObjectTable.Instance.OwnerTypeLookup.ContainsKey(materialKey));
				Assert.IsNotNull(ObjectTable.Instance.OwnerTypeLookup[materialKey]);
			}

			material1.Dispose();
			material2.Dispose();

			{
				var materialKey = new ObjectTableOwnershipType(physics, typeof(MockMaterial));

				// As we have disposed both materials; the entry in the dictionary for Physics-MockMaterial should
				// be removed
				Assert.IsFalse(ObjectTable.Instance.OwnerTypeLookup.ContainsKey(materialKey));
			}
		}

		[TestMethod]
		public void GetObjectHandlesNull()
		{
			RigidActor actor = ObjectTable.Instance.GetObject<RigidActor>(0);

			Assert.IsNull(actor);
		}

		[TestMethod]
		[ExpectedException(typeof(PhysXException))]
		public void NullKeyIsNotAllowed()
		{
			ObjectTable.Instance.Add(0, new MockMaterial(), null);
		}

		//

		public abstract class MockDisposableObject : IDisposable
		{
			protected MockDisposableObject()
			{
				Disposed = false;
			}

			#region IDisposable Members

			public bool Disposed { get; set; }

			public event EventHandler OnDisposed;

			public event EventHandler OnDisposing;

			#endregion

			#region IDisposable Members

			public void Dispose()
			{
				if (Disposed)
					Assert.Fail("Object is already disposed");

				if (OnDisposing != null)
					OnDisposing(this, null);

				Disposed = true;

				if (OnDisposed != null)
					OnDisposed(this, null);
			}

			#endregion
		}

		public class MockPhysics : MockDisposableObject
		{
			
		}

		public class MockMaterial : MockDisposableObject
		{
			
		}

		public class MockScene : MockDisposableObject
		{
			
		}

		public class MockActor : MockDisposableObject
		{

		}
	}
}

<|start_filename|>PhysX.Net/Test/Shape/ShapeTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class ShapeTest : Test
	{
		[TestMethod]
		public void GetAndSetMaterialOfShape()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				// New material to set
				var newMaterial = physics.Physics.CreateMaterial(0.2f, 0.1f, 0.2f);

				var actor = CreateBoxActor(physics.Scene, new Vector3(5, 5, 5), new Vector3(0, 0, 0));
				var boxShape = actor.Shapes.First();

				physics.Scene.AddActor(actor);

				// Assign the new material (can only be 1, given the shape setup)
				boxShape.Materials = new[] { newMaterial };

				Assert.AreEqual(1, boxShape.Materials.Length);
				Assert.AreEqual(newMaterial, boxShape.Materials[0]);
			}
		}

		[TestMethod]
		public void DisposingShapeRemovesItFromItsActor()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				// Create an actor with a box shape
				var actor = CreateBoxActor(physics.Scene, new Vector3(5, 5, 5), new Vector3(0, 0, 0));

				Assert.AreEqual(1, actor.Shapes.Count());

				var boxShape = actor.Shapes.First();

				// Dispose that shape
				boxShape.Dispose();

				// Make sure the shape was removed from its parent actor because of the Dispose call
				Assert.AreEqual(0, actor.Shapes.Count());
				Assert.IsTrue(boxShape.Disposed);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Geometry/Model.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

namespace PhysX.Test
{
	public class Model
	{
		public int[] Indices { get; set; }
		public Vector3[] Vertices { get; set; }
	}
}

<|start_filename|>PhysX.Net/Test/Stream/StreamExtensionsTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PhysX;

namespace PhysX.Test
{
	[TestClass]
	public class StreamExtensionsTest : Test
	{
		[TestMethod]
		public void GetData_ReturnArrayOfStructs()
		{
			unsafe
			{
				short[] @in = new short[50];
				for (int i = 0; i < 50; i++)
				{
					@in[i] = (short)i;
				}

				int inSize = 100; // 50 x 2 bytes per short

				// Allocate a block of unmanaged memory and return an IntPtr object.	
				IntPtr memIntPtr = Marshal.AllocHGlobal(inSize);

				// Get a byte pointer from the IntPtr object. 
				byte* memBytePtr = (byte*)memIntPtr.ToPointer();

				var stream = new UnmanagedMemoryStream(memBytePtr, inSize);

				// Set the data
				stream.SetData(@in);

				// Get the data back out
				short[] @out = stream.GetData<short>();

				Assert.AreEqual(@in.Length, @out.Length);

				for (int i = 0; i < 50; i++)
				{
					Assert.AreEqual(@in[i], @out[i]);
				}
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Actor/RigidActorExtTests.cs<|end_filename|>
﻿using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Actor
{
	[TestClass]
	public class RigidActorExtTests : Test
	{
		[TestMethod]
		public void CreateExclusiveShape_IsInActorsShapesProperty()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(0.2f, 0.1f, 0.2f);
				var rigid = physics.Physics.CreateRigidDynamic();

				Assert.AreEqual(0, rigid.Shapes.Count);

				var box = RigidActorExt.CreateExclusiveShape(rigid, new BoxGeometry(2, 3, 4), material);

				Assert.AreEqual(1, rigid.Shapes.Count);
			}
		}
	}
}


<|start_filename|>PhysX.Net/Test/Controller/BoxControllerTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class BoxControllerTest : Test
	{
		[TestMethod]
		public void CreateAndDisposeBoxController()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var controllerManager = core.Scene.CreateControllerManager();

				var material = core.Physics.CreateMaterial(0.1f, 0.1f, 0.1f);

				var desc = new CapsuleControllerDesc()
				{
					Height = 12,
					Radius = 7,
					Material = material
				};

				Assert.IsTrue(desc.IsValid());

				CapsuleController capsuleController;
				using (capsuleController = controllerManager.CreateController<CapsuleController>(desc))
				{
					Assert.IsNotNull(capsuleController);
					Assert.IsFalse(capsuleController.Disposed);
				}

				Assert.IsTrue(capsuleController.Disposed);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Joint/JointTest.cs<|end_filename|>
﻿using System;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Joint
{
	[TestClass]
	public class JointTest : Test
	{
		[TestMethod]
		public void SetActors()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var box1 = CreateBoxActor(core.Scene, 0, 10, 0);
				var box2 = CreateBoxActor(core.Scene, 0, 20, 0);

				var box3 = CreateBoxActor(core.Scene, 10, 10, 0);
				var box4 = CreateBoxActor(core.Scene, 10, 20, 0);

				var joint = core.Scene.CreateJoint<RevoluteJoint>(box1, Matrix4x4.Identity, box2, Matrix4x4.Identity);

				Assert.AreEqual(box1, joint.Actor0);
				Assert.AreEqual(box2, joint.Actor1);

				joint.SetActors(box3, box4);

				Assert.AreEqual(box3, joint.Actor0);
				Assert.AreEqual(box4, joint.Actor1);
			}
		}
	}
}


<|start_filename|>PhysX.Net/Test/Extensions/RigidActorExtensions.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PhysX.Test
{
	public static class RigidActorExtensions
	{
		/// <summary>
		/// A convenience/backwards-compatability method.
		/// </summary>
		public static Shape CreateShape(this RigidActor actor, PhysX.Geometry geometry, Material material)
		{
			return RigidActorExt.CreateExclusiveShape(actor, geometry, material);
		}
	}
}


<|start_filename|>PhysX.Net/Samples/Engine/Engine/Engine.cs<|end_filename|>
using System;
using System.Diagnostics;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;

namespace PhysX.Samples.Engine
{
	public delegate void UpdateEventHandler(TimeSpan elapsed);

	public class Engine
	{
		public event UpdateEventHandler OnUpdate;
		public event EventHandler OnDraw;

		private Action<SceneDesc> _sceneDescCallback;

		private Keyboard _keyboard;
		private VisualizationEffect _visualizationEffect;

		private RenderTargetView _backBuffer;
		private DepthStencilView _depthBuffer;
		private SwapChain _swapChain;

		private SharpDX.Direct3D11.Buffer _userPrimitivesBuffer;
		private InputLayout _inputLayout;

		// TODO: Clean up this class
		public Engine(Action<SceneDesc> sceneDescCallback = null)
		{
			_sceneDescCallback = sceneDescCallback;

			Window = new SampleWindow();
			Window.Show();

			_keyboard = new Keyboard(this);
			_keyboard.OnKeyDown += _keyboard_OnKeyDown;

			InitalizeGraphics();

			InitalizePhysics();

			Mouse.SetCursor(Cursors.None);
		}

		private void _keyboard_OnKeyDown(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Space)
			{
				ShootSphere();
			}
		}

		private void ShootSphere()
		{
			const float force = 5000;

			var cameraPos = Camera.Position.AsPhysX();
			var cameraDir = Camera.Direction.AsPhysX();

			var material = this.Scene.Physics.CreateMaterial(0.1f, 0.5f, 0.5f);

			var rigidActor = this.Scene.Physics.CreateRigidDynamic();

			var sphereGeom = new SphereGeometry(2);
			var boxShape = RigidActorExt.CreateExclusiveShape(rigidActor, sphereGeom, material, null);

			rigidActor.GlobalPose = Matrix4x4.CreateTranslation(cameraPos);
			rigidActor.SetMassAndUpdateInertia(100);

			this.Scene.AddActor(rigidActor);

			rigidActor.AddForceAtLocalPosition(cameraDir * force, new System.Numerics.Vector3(0, 0, 0), ForceMode.Impulse, true);
		}

		private void InitalizeGraphics()
		{
			if (Window.RenderCanvasHandle == IntPtr.Zero)
				throw new InvalidOperationException();

			var swapChainDesc = new SwapChainDescription()
			{
				BufferCount = 1,
				IsWindowed = true,
				OutputHandle = Window.RenderCanvasHandle,
				SwapEffect = SwapEffect.Discard,
				Usage = Usage.RenderTargetOutput,
				ModeDescription = new ModeDescription()
				{
					Format = Format.R8G8B8A8_UNorm,
					Width = (int)Window.RenderCanvasSize.Width,
					Height = (int)Window.RenderCanvasSize.Height,
					RefreshRate = new Rational(60, 1)
				},
				SampleDescription = new SampleDescription(1, 0)
			};

			SharpDX.Direct3D11.Device device;
			try
			{
				SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Warp, DeviceCreationFlags.None, swapChainDesc, out device, out _swapChain);
				GraphicsDevice = device;
			}
			catch
			{
				throw new Exception("Failed to create graphics device. Do you have DirectX 11?");
			}

			// Create a view of our render target, which is the 'back buffer' of the swap chain we just created
			{
				using (var resource = SharpDX.Direct3D11.Resource.FromSwapChain<Texture2D>(_swapChain, 0))
				{
					_backBuffer = new RenderTargetView(device, resource);
				}

				// Use it
				device.ImmediateContext.OutputMerger.SetTargets(_backBuffer);
			}

			CreateDepthStencil();
			LoadVisualizationEffect();

			// Allocate a large buffer to write the PhysX visualization vertices into
			// There's more optimized ways of doing this, but for this sample a large buffer will do
			_userPrimitivesBuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice, VertexPositionColor.SizeInBytes * 50000, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, VertexPositionColor.SizeInBytes);
		}
		private void CreateDepthStencil()
		{
			var stencilDesc = new Texture2DDescription()
			{
				Width = (int)Window.RenderCanvasSize.Width,
				Height = (int)Window.RenderCanvasSize.Height,
				MipLevels = 1,
				ArraySize = 1,
				Format = Format.D32_Float,
				SampleDescription = new SampleDescription() { Count = 1, Quality = 0 },
				Usage = ResourceUsage.Default,
				BindFlags = BindFlags.DepthStencil,
				CpuAccessFlags = CpuAccessFlags.None,
				OptionFlags = ResourceOptionFlags.None
			};

			var depthBufferTexture = new Texture2D(GraphicsDevice, stencilDesc);

			_depthBuffer = new DepthStencilView(this.GraphicsDevice, depthBufferTexture);
		}
		private void LoadVisualizationEffect()
		{
			string engineDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

			string visEffectFile = Path.Combine(engineDir, @"Shaders\VisualizationEffect.fx");

			var shaderByteCode = ShaderBytecode.CompileFromFile(visEffectFile, "fx_5_0", ShaderFlags.Debug);

			var effect = new Effect(this.GraphicsDevice, shaderByteCode);

			_visualizationEffect = new VisualizationEffect()
			{
				Effect = effect,
				World = effect.GetVariableByName("World").AsMatrix(),
				View = effect.GetVariableByName("View").AsMatrix(),
				Projection = effect.GetVariableByName("Projection").AsMatrix(),
				RenderScenePass0 = effect.GetTechniqueByName("RenderScene").GetPassByIndex(0)
			};

			// Vertex structure the shader is expecting - very basic sample, just Position and Color.
			var elements = new[]
			{
				new InputElement("Position", 0, Format.R32G32B32A32_Float, 0, 0),
				new InputElement("Color", 0, Format.R32G32B32A32_Float, 16, 0)
			};
			_inputLayout = new InputLayout(this.GraphicsDevice, _visualizationEffect.RenderScenePass0.Description.Signature, elements);
		}

		public void InitalizePhysics()
		{
			// Construct engine objects
			this.Camera = new Camera(this);

			// Construct physics objects
			ErrorOutput errorOutput = new ErrorOutput();

			Foundation foundation = new Foundation(errorOutput);

			var pvd = new VisualDebugger.Pvd(foundation);

			this.Physics = new Physics(foundation, true, pvd);

			this.Scene = this.Physics.CreateScene(CreateSceneDesc(foundation));

			this.Scene.SetVisualizationParameter(VisualizationParameter.Scale, 2.0f);
			this.Scene.SetVisualizationParameter(VisualizationParameter.CollisionShapes, true);
			this.Scene.SetVisualizationParameter(VisualizationParameter.JointLocalFrames, true);
			this.Scene.SetVisualizationParameter(VisualizationParameter.JointLimits, true);
			this.Scene.SetVisualizationParameter(VisualizationParameter.ActorAxes, true);

			// Connect to the PhysX Visual Debugger (if the PVD application is running)
			this.Physics.Pvd.Connect("localhost");

			CreateGroundPlane();
		}
		protected virtual SceneDesc CreateSceneDesc(Foundation foundation)
		{
#if GPU
			var cudaContext = new CudaContextManager(foundation);
#endif

			var sceneDesc = new SceneDesc
			{
				Gravity = new Vector3(0, -9.81f, 0),
#if GPU
				GpuDispatcher = cudaContext.GpuDispatcher,
#endif
				FilterShader = new SampleFilterShader()
			};

#if GPU
			sceneDesc.Flags |= SceneFlag.EnableGpuDynamics;
			sceneDesc.BroadPhaseType |= BroadPhaseType.Gpu;
#endif

			_sceneDescCallback?.Invoke(sceneDesc);

			return sceneDesc;
		}
		private void CreateGroundPlane()
		{
			var groundPlaneMaterial = this.Scene.Physics.CreateMaterial(0.1f, 0.1f, 0.1f);

			var groundPlane = this.Scene.Physics.CreateRigidStatic();
			groundPlane.Name = "Ground Plane";
			groundPlane.GlobalPose = Matrix4x4.CreateFromAxisAngle(new System.Numerics.Vector3(0, 0, 1), (float)System.Math.PI / 2);

			var planeGeom = new PlaneGeometry();

			RigidActorExt.CreateExclusiveShape(groundPlane, planeGeom, groundPlaneMaterial, null);

			this.Scene.AddActor(groundPlane);
		}

		public void Run()
		{
			Window.Show();
			Window.Focus();

			var frameTimer = Stopwatch.StartNew();

			// Not an ideal render loop, but it will do for this sample
			while (true)
			{
				if (!Window.IsActive)
				{
					System.Windows.Forms.Application.DoEvents();
					System.Threading.Thread.Sleep(50);
					continue;
				}

				Draw();

				// 60fps = 1/60 = 16.67 ms/frame
				if (frameTimer.Elapsed >= TimeSpan.FromMilliseconds(16.67))
				{
					Update(frameTimer.Elapsed);

					frameTimer.Restart();
					System.Windows.Forms.Application.DoEvents();
				}
			}
		}

		private void Update(TimeSpan elapsed)
		{
			this.FrameTime = elapsed;

			// Update Physics
			this.Scene.Simulate((float)elapsed.TotalSeconds);
			this.Scene.FetchResults(block: true);

			this.Camera.Update(elapsed);

			if (OnUpdate != null)
				OnUpdate(elapsed);
		}

		private void Draw()
		{
			this.GraphicsDevice.ImmediateContext.OutputMerger.SetTargets(_depthBuffer, _backBuffer);

			// Clear to a nice blue colour :)
			this.GraphicsDevice.ImmediateContext.ClearRenderTargetView(_backBuffer, new SharpDX.Color4(0.27f, 0.51f, 0.71f, 1));
			this.GraphicsDevice.ImmediateContext.ClearDepthStencilView(_depthBuffer, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0);
			this.GraphicsDevice.ImmediateContext.Rasterizer.SetViewports(new[] { (SharpDX.Mathematics.Interop.RawViewportF)this.Camera.Viewport }, 1);

			DrawDebug(this.Scene.GetRenderBuffer());

			if (OnDraw != null)
				OnDraw(this, null);

			_swapChain.Present(0, PresentFlags.None);
		}
		private void DrawDebug(RenderBuffer data)
		{
			var pass = _visualizationEffect.RenderScenePass0;

			_visualizationEffect.World.SetMatrix(SharpDX.Matrix.Identity);
			_visualizationEffect.View.SetMatrix(this.Camera.View);
			_visualizationEffect.Projection.SetMatrix(this.Camera.Projection);

			this.GraphicsDevice.ImmediateContext.InputAssembler.InputLayout = _inputLayout;

			pass.Apply(this.GraphicsDevice.ImmediateContext);

			if (data.NumberOfPoints > 0)
			{
				var vertices = new VertexPositionColor[data.Points.Length];
				for (int i = 0; i < data.Points.Length; i++)
				{
					var point = data.Points[i];

					vertices[i * 2 + 0] = new VertexPositionColor(point.Point.As<SharpDX.Vector3>(), Color.FromArgb(point.Color));
				}

				DrawVertices(vertices, PrimitiveTopology.PointList);
			}

			if (data.NumberOfLines > 0)
			{
				var vertices = new VertexPositionColor[data.Lines.Length * 2];
				for (int x = 0; x < data.Lines.Length; x++)
				{
					DebugLine line = data.Lines[x];

					vertices[x * 2 + 0] = new VertexPositionColor(line.Point0.As<SharpDX.Vector3>(), Color.FromArgb(line.Color0));
					vertices[x * 2 + 1] = new VertexPositionColor(line.Point1.As<SharpDX.Vector3>(), Color.FromArgb(line.Color1));
				}

				DrawVertices(vertices, PrimitiveTopology.LineList);
			}

			if (data.NumberOfTriangles > 0)
			{
				var vertices = new VertexPositionColor[data.Triangles.Length * 3];
				for (int x = 0; x < data.Triangles.Length; x++)
				{
					DebugTriangle triangle = data.Triangles[x];

					vertices[x * 3 + 0] = new VertexPositionColor(triangle.Point0.As<SharpDX.Vector3>(), Color.FromArgb(triangle.Color0));
					vertices[x * 3 + 1] = new VertexPositionColor(triangle.Point1.As<SharpDX.Vector3>(), Color.FromArgb(triangle.Color1));
					vertices[x * 3 + 2] = new VertexPositionColor(triangle.Point2.As<SharpDX.Vector3>(), Color.FromArgb(triangle.Color2));
				}

				DrawVertices(vertices, PrimitiveTopology.TriangleList);
			}
		}

		private void PopulatePrimitivesBuffer(VertexPositionColor[] vertices)
		{
			var dataBox = this.GraphicsDevice.ImmediateContext.MapSubresource(_userPrimitivesBuffer, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);
			SharpDX.Utilities.Write(IntPtr.Add(dataBox.DataPointer, 0), vertices, 0, vertices.Length);
			this.GraphicsDevice.ImmediateContext.UnmapSubresource(_userPrimitivesBuffer, 0);
		}
		private void DrawVertices(VertexPositionColor[] vertices, PrimitiveTopology top)
		{
			PopulatePrimitivesBuffer(vertices);

			this.GraphicsDevice.ImmediateContext.InputAssembler.PrimitiveTopology = top;
			this.GraphicsDevice.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_userPrimitivesBuffer, VertexPositionColor.SizeInBytes, 0));
			this.GraphicsDevice.ImmediateContext.Draw(vertices.Length, 0);
		}
		public void DrawSimple(SharpDX.Direct3D11.Buffer vertexBuffer, SharpDX.Direct3D11.Buffer indexBuffer, int indexCount)
		{
			this.GraphicsDevice.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 0, 0));
			this.GraphicsDevice.ImmediateContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);
			this.GraphicsDevice.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineList;

			this.GraphicsDevice.ImmediateContext.DrawIndexed(indexCount, 0, 0);
		}

		//

		public Camera Camera { get; private set; }

		public Physics Physics { get; private set; }
		public Scene Scene { get; private set; }

		public SharpDX.Direct3D11.Device GraphicsDevice { get; private set; }

		public SampleWindow Window { get; private set; }

		public Keyboard Keyboard => _keyboard;

		public TimeSpan FrameTime { get; private set; }
	}
}

<|start_filename|>PhysX.Net/PhysX.Net/Source/TriangleMeshDesc.cpp<|end_filename|>
#include "StdAfx.h"
#include "TriangleMeshDesc.h"

TriangleMeshDesc::TriangleMeshDesc()
{
	
}

TriangleMeshDesc^ TriangleMeshDesc::ToManaged(PxTriangleMeshDesc desc)
{
	auto d = gcnew TriangleMeshDesc();

	d->MaterialIndices = Util::AsManagedArray<short>(desc.materialIndices.data, desc.triangles.count);

	return d;
}
PxTriangleMeshDesc TriangleMeshDesc::ToUnmanaged(TriangleMeshDesc^ desc)
{
	PxTriangleMeshDesc d;

	desc->PopulateUnmanaged(d);

	if (desc->MaterialIndices != nullptr)
	{
		auto i = PxTypedStridedData<PxMaterialTableIndex>();
		i.data = new PxMaterialTableIndex[desc->MaterialIndices->Length];
		
		d.materialIndices = i;
		Util::AsUnmanagedArray<short>(desc->MaterialIndices, (void*)i.data, desc->MaterialIndices->Length);
	}
	
	return d;
}

void TriangleMeshDesc::SetToDefault()
{
	SimpleTriangleMesh::SetToDefault();
}
bool TriangleMeshDesc::IsValid()
{
	if(Points->Length < 3) 	//at least 1 trig's worth of points
		return false;
	if ((!Triangles) && (Points->Length%3))		// Non-indexed mesh => we must ensure the geometry defines an implicit number of triangles // i.e. numVertices can't be divided by 3
		return false;
	//add more validity checks here
	//if (MaterialIndices.data && MaterialIndices.stride < sizeof(PxMaterialTableIndex))
	//	return false;

	return SimpleTriangleMesh::IsValid();
}

<|start_filename|>PhysX.Net/Test/BroadPhase/BroadPhaseTests.cs<|end_filename|>
﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.BroadPhase
{
	[TestClass]
	public class BroadPhaseTests : Test
	{
		[TestMethod]
		public void FromSceneDescToScene()
		{
			if (Physics.Instantiated)
				Assert.Fail("Physics is still created");

			using (var foundation = new Foundation())
			{
				var physics = new Physics(foundation, checkRuntimeFiles: true);

				var bpc = new TestBroadPhaseCallback();

				var sceneDesc = new SceneDesc
				{
					BroadPhaseCallback = bpc
				};

				var scene = physics.CreateScene(sceneDesc);

				Assert.AreEqual(bpc, scene.BroadPhaseCallback);
			}
		}

		//

		public class TestBroadPhaseCallback : BroadPhaseCallback
		{
			public override void OnObjectOutOfBounds(PhysX.Aggregate aggregate)
			{
				
			}

			public override void OnObjectOutOfBounds(Shape shape, PhysX.Actor actor)
			{
				
			}
		}
	}
}


<|start_filename|>PhysX.Net/PhysX.Net/Source/Cooking.h<|end_filename|>
#pragma once

#include "CookingEnum.h"
#include "CookingParams.h"

namespace PhysX
{
	ref class Foundation;
	ref class TriangleMeshDesc;
	ref class ConvexMeshDesc;
	ref class ClothMeshDesc;
	ref class HeightFieldDesc;

	public ref class Cooking : IDisposable
	{
		public:
			virtual event EventHandler^ OnDisposing;
			virtual event EventHandler^ OnDisposed;

		private:
			PxCooking* _cooking;

		internal:
			Cooking(PxCooking* cooking, PhysX::Foundation^ owner);
		public:
			~Cooking();
		protected:
			!Cooking();

		public:
			property bool Disposed
			{
				virtual bool get();
			}

			bool CookHeightField(HeightFieldDesc^ desc, System::IO::Stream^ stream);

			/// <summary>
			/// Cooks a triangle mesh. The results are written to the stream.
			/// To create a triangle mesh object it is necessary to first 'cook' the mesh data into a form which allows the
			/// SDK to perform efficient collision detection.
			/// CookTriangleMesh() allows a mesh description to be cooked into a binary stream suitable for loading and
			/// performing collision detection at runtime.
			/// </summary>
			/// <param name="desc">The triangle mesh descriptor to read the mesh from.</param>
			/// <param name="stream">User stream to output the cooked data.</param>
			TriangleMeshCookingResult CookTriangleMesh(TriangleMeshDesc^ desc, System::IO::Stream^ stream);

			/// <summary>
			/// Cooks a convex mesh. The results are written to the stream.
			/// To create a triangle mesh object it is necessary to first 'cook' the mesh data into a form which allows the
			/// SDK to perform efficient collision detection.
			/// CookConvexMesh() allows a mesh description to be cooked into a binary stream suitable for loading and
			/// performing collision detection at runtime.
			/// </summary>
			/// <param name="desc">The convex mesh descriptor to read the mesh from.</param>
			/// <param name="stream">User stream to output the cooked data.</param>
			ConvexMeshCookingResult CookConvexMesh(ConvexMeshDesc^ desc, System::IO::Stream^ stream);

			//

			/// <summary>
			/// Gets or sets options for controlling the operation.
			/// </summary>
			property CookingParams^ Parameters
			{
				CookingParams^ get();
				void set(CookingParams^ value);
			}

			property bool PlatformMismatch
			{
				bool get();
			}

		internal:
			property PxCooking* UnmanagedPointer
			{
				PxCooking* get();
			}
	};
};

<|start_filename|>PhysX.Net/Samples/Engine/Util/ArrayUtil.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PhysX.Samples.Engine.Util
{
	public static class ArrayUtil
	{
		public static byte[] ToByteArray(int[] array)
		{
			byte[] bytes = new byte[sizeof(int) * array.Length];

			for (int i = 0; i < array.Length; i++)
			{
				byte[] k = BitConverter.GetBytes(array[i]);

				for (int j = 0; j < k.Length; j++)
				{
					bytes[i * sizeof(int) + j] = k[j];
				}
			}

			return bytes;
		}

		//public static byte[] ToByteArray<T>(T[] array)
		//	where T : struct
		//{
		//	int t = Marshal.SizeOf(typeof(T));

		//	GCHandle pinSrc = GCHandle.Alloc(array[0], GCHandleType.Pinned);

		//	var bytes = new byte[t * array.Length];

		//	Marshal.Copy(pinSrc.AddrOfPinnedObject(), bytes, 0, t * array.Length);

		//	pinSrc.Free();

		//	return bytes;
		//}
	}
}

<|start_filename|>PhysX.Net/Test/Test/Test.cs<|end_filename|>
﻿using System;
using System.Diagnostics;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	[DeploymentItem("PhysX_64.dll")]
	[DeploymentItem("PhysXCommon_64.dll")]
	[DeploymentItem("PhysXCooking_64.dll")]
	[DeploymentItem("PhysXDevice64.dll")]
	[DeploymentItem("PhysXFoundation_64.dll")]
	[DeploymentItem("PhysXGpu_64.dll")]
	public abstract class Test
	{
		private ErrorLog _errorLog;

		private static PhysX.Foundation _foundation;
		private static PhysX.Physics _physics;

		[TestCleanup]
		public void CleanUp()
		{
			if (Physics.Instantiated)
			{
				_foundation?.Dispose();
				_foundation = null;

				throw new Exception("After a test has run, the Physics singleton should have been disposed");
			}

			ObjectTable.Instance.Clear();

			if (_errorLog != null && _errorLog.HasErrors)
			{
				Trace.TraceError("There were errors, check the error log");
			}

			_errorLog = null;
		}

		[TestInitialize]
		public void TestInitialize()
		{
			if (Physics.Instantiated)
				throw new Exception("Before a test run, the Physics singleton should not be initalized. Probably spill over from a previous test.");
		}

		protected Physics CreatePhysics(ErrorCallback errorCallback = null)
		{
			if (Physics.Instantiated)
				Assert.Fail("Physics is still created");

			if (errorCallback == null)
				errorCallback = _errorLog = new ErrorLog();

			if (_physics != null)
			{
				_physics.Dispose();
				_physics = null;
			}
			if (_foundation != null)
			{
				_foundation.Dispose();
				_foundation = null;
			}

			_foundation = new Foundation(errorCallback);

			_physics = new Physics(_foundation, checkRuntimeFiles: true);

			return _physics;
		}
		protected PhysicsAndSceneTestUnit CreatePhysicsAndScene()
		{
			_errorLog = new ErrorLog();

			var physics = CreatePhysics(_errorLog);

			var scene = physics.CreateScene();

			return new PhysicsAndSceneTestUnit()
			{
				Foundation = physics.Foundation,
				Physics = scene.Physics,
				Scene = scene,
				ErrorOutput = _errorLog
			};
		}

		protected RigidDynamic CreateBoxActor(Scene scene, float x, float y, float z)
		{
			return CreateBoxActor(scene, new Vector3(5, 5, 5), new Vector3(x, y, z));
		}
		protected RigidDynamic CreateBoxActor(Scene scene, Vector3 size, Vector3 position)
		{
			var material = scene.Physics.CreateMaterial(0.5f, 0.5f, 0.1f);

			var rigid = scene.Physics.CreateRigidDynamic();

			var shape = rigid.CreateShape(new BoxGeometry(size / 2), material);

			rigid.GlobalPose = Matrix4x4.CreateTranslation(position);

			scene.AddActor(rigid);

			return rigid;
		}

		protected void AssertNoPhysXErrors(PhysicsAndSceneTestUnit physics)
		{
			Assert.IsFalse(physics.ErrorOutput.HasErrors, physics.ErrorOutput.LastError);
		}
	}
}

<|start_filename|>PhysX.Net/Samples/JointsSample/JointsSample.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

namespace PhysX.Samples.JointsSample
{
	public class JointsSample : Sample
	{
		public JointsSample()
		{
			Run();
		}

		protected override void LoadContent()
		{

		}

		protected override void LoadPhysics(Scene scene)
		{
			var material = scene.Physics.CreateMaterial(0.7f, 0.7f, 0.1f);

			// Spherical Joint
			{
				var box = scene.Physics.CreateRigidDynamic();
				box.CreateShape(new BoxGeometry(2, 2, 2), material);
				box.GlobalPose = Matrix4x4.CreateTranslation(0, 10, 0);
				box.SetMassAndUpdateInertia(10);

				//

				var sphericalJoint = scene.CreateJoint<SphericalJoint>(box, Matrix4x4.CreateTranslation(0, 4, 0), null, Matrix4x4.CreateTranslation(0, 15, 0));
				sphericalJoint.ConstraintFlags = ConstraintFlag.Visualization;

				scene.AddActor(box);
			}

			// Revolute Joint
			{
				var box = scene.Physics.CreateRigidDynamic();
				box.CreateShape(new BoxGeometry(2, 2, 2), material);
				box.GlobalPose = Matrix4x4.CreateTranslation(-10, 10, 0);
				box.SetMassAndUpdateInertia(10);

				//

				var revoluteJoint = scene.CreateJoint<RevoluteJoint>(box, Matrix4x4.CreateTranslation(0, 4, 0), null, Matrix4x4.CreateTranslation(-10, 15, 0));
				revoluteJoint.ConstraintFlags = ConstraintFlag.Visualization;

				scene.AddActor(box);
			}

			// Breakable Revolute Joint
			{
				var box = scene.Physics.CreateRigidDynamic();
				box.CreateShape(new BoxGeometry(2, 2, 2), material);
				box.GlobalPose = Matrix4x4.CreateTranslation(10, 10, 0);
				box.SetMassAndUpdateInertia(10);

				//

				var revoluteJoint = scene.CreateJoint<RevoluteJoint>(box, Matrix4x4.CreateTranslation(0, 4, 0), null, Matrix4x4.CreateTranslation(10, 15, 0));
				revoluteJoint.ConstraintFlags = ConstraintFlag.Visualization;
				revoluteJoint.BreakForce = 0.001f;

				scene.AddActor(box);
			}

			// Distance Joint
			{
				var box = scene.Physics.CreateRigidDynamic();
				box.CreateShape(new BoxGeometry(2, 2, 2), material);
				box.GlobalPose = Matrix4x4.CreateTranslation(-20, 10, 0);
				box.SetMassAndUpdateInertia(10);

				//

				var distanceJoint = scene.CreateJoint<DistanceJoint>(box, Matrix4x4.CreateTranslation(0, 4, 0), null, Matrix4x4.CreateTranslation(-20, 15, 0));
				distanceJoint.ConstraintFlags = ConstraintFlag.Visualization;
				distanceJoint.MinimumDistance = 1;
				distanceJoint.MaximumDistance = 3;

				scene.AddActor(box);
			}

			// Fixed Joint
			{
				var box = scene.Physics.CreateRigidDynamic();
				box.CreateShape(new BoxGeometry(2, 2, 2), material);
				box.GlobalPose = Matrix4x4.CreateTranslation(-30, 15, 0);
				box.SetMassAndUpdateInertia(10);

				//

				var fixedJoint = scene.CreateJoint<FixedJoint>(box, Matrix4x4.Identity, null, Matrix4x4.CreateTranslation(-30, 15, 0));
				fixedJoint.ConstraintFlags = ConstraintFlag.Visualization;

				scene.AddActor(box);
			}

			// Prismatic Joint
			{
				var box = scene.Physics.CreateRigidDynamic();
				box.CreateShape(new BoxGeometry(2, 2, 2), material);
				box.GlobalPose = Matrix4x4.CreateTranslation(-40, 15, 0);
				box.SetMassAndUpdateInertia(10);

				//

				var prismaticJoint = scene.CreateJoint<PrismaticJoint>(box, Matrix4x4.Identity, null, Matrix4x4.CreateTranslation(-40, 15, 0));
				prismaticJoint.ConstraintFlags = ConstraintFlag.Visualization;

				scene.AddActor(box);
			}

			// D6 Joint
			{
				var box = scene.Physics.CreateRigidDynamic();
				box.CreateShape(new BoxGeometry(2, 2, 2), material);
				box.GlobalPose = Matrix4x4.CreateTranslation(20, 15, 0);
				box.SetMassAndUpdateInertia(10);

				//

				var d6Joint = scene.CreateJoint<D6Joint>(box, Matrix4x4.Identity, null, Matrix4x4.CreateTranslation(20, 15, 0));
				d6Joint.ConstraintFlags = ConstraintFlag.Visualization;
				d6Joint.SetMotion(D6Axis.Twist, D6Motion.Free); // Spin on the X axis

				scene.AddActor(box);
			}
		}

		protected override void Update(TimeSpan elapsed)
		{

		}

		protected override void Draw()
		{

		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Color.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using SharpDX;

namespace PhysX.Samples
{
	[StructLayout(LayoutKind.Sequential)]
	public struct Color
	{
		public const int SizeInBytes = 16; // 4 bytes x RGBA

		public Color(float r, float g, float b, float a = 1.0f)
			: this()
		{
			this.Alpha = a;
			this.Red = r;
			this.Green = g;
			this.Blue = b;
		}

		public int ToArgb()
		{
			int a = (int)(this.Alpha * byte.MaxValue);
			int r = (int)(this.Red * byte.MaxValue);
			int g = (int)(this.Green * byte.MaxValue);
			int b = (int)(this.Blue * byte.MaxValue);

			return (a << 24) | (r << 16) | (g << 8) | (b << 0);
		}

		/// <summary>Returns a color structure based on the color input</summary>
		/// <param name="color">The color to use (AARRGGBB)</param>
		public static Color FromArgb(int color)
		{
			byte a = (byte)((color & 0xFF000000) >> 24);
			byte r = (byte)((color & 0x00FF0000) >> 16);
			byte g = (byte)((color & 0x0000FF00) >> 8);
			byte b = (byte)((color & 0x000000FF) >> 0);

			return Color.FromArgb(r, g, b, a);
		}
		public static Color FromArgb(byte r, byte g, byte b, byte a = 255)
		{
			return new Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
		}
		//public static Color FromArgb( byte r, byte g, byte b, byte a )
		//{
		//    int ia = ( (int)a << 24 );
		//    int ir = ( (int)r << 16 );
		//    int ig = ( (int)g << 8 );
		//    int ib = ( (int)b << 0 );

		//    int color = ia | ir | ig | ib;

		//    return Color.FromArgb( color );
		//}

		/// <summary>Converts a Vector4 to a Color object.</summary>
		/// <param name="vector">A vector where each component in the vector maps to a color component; X: Red, Y: Green, Z: Blue, W: Alpha.</param>
		public static Color FromVector4(Vector4 vector)
		{
			return new Color(vector.X, vector.Y, vector.Z, vector.W);
		}

		public static Color? TryParse(string hexColor)
		{
			try
			{
				return Parse(hexColor);
			}
			catch
			{
				return null;
			}
		}
		/// <summary>Parse a string based hex representation of a 32 bit color value.</summary>
		/// <param name="hexColor">A hex string representing the color. Acceptable inputs are: [#]RGB, [#]RGBA, [#]RRGGBBAA</param>
		public static Color Parse(string hexColor)
		{
			if (hexColor == null)
				throw new ArgumentNullException("hexColor");
			if (string.IsNullOrWhiteSpace(hexColor))
				throw new ArgumentException("Hex color string is empty", "hexColor");

			if (hexColor[0] == '#')
				hexColor = hexColor.Substring(1);

			hexColor = ExpandHexStringInternal(hexColor);

			byte r, g, b, a;

			if (hexColor.Length == 6)
			{
				r = ParseAsByte(hexColor, 0, 2);
				g = ParseAsByte(hexColor, 2, 2);
				b = ParseAsByte(hexColor, 4, 2);
				a = 0xFF;
			}
			else if (hexColor.Length == 8)
			{
				r = ParseAsByte(hexColor, 0, 2);
				g = ParseAsByte(hexColor, 2, 2);
				b = ParseAsByte(hexColor, 4, 2);
				a = ParseAsByte(hexColor, 6, 2);
			}
			else
			{
				throw new ArgumentException("Hex color string must be of length 3, 4, 6 or 8 (excluding the leading hash character)", "hexColor");
			}

			return Color.FromArgb(r, g, b, a);
		}
		private static byte ParseAsByte(string hexNumber, int charIndex, int length)
		{
			try
			{
				return Convert.ToByte(hexNumber.Substring(charIndex, length), 16);
			}
			catch
			{
				throw new ArgumentException(String.Format("Unable to parse hex color string component. From: {0} To: {1} In: {2}", charIndex, length, hexNumber));
			}
		}

		/// <summary>Expands the hex string to 2 bytes per component.</summary>
		/// <param name="hexColor">A hex representation of a 32 bit color value. Values can be [#]RGB or [#]RGBA</param>
		public static string ExpandHexString(string hexColor)
		{
			if (string.IsNullOrWhiteSpace(hexColor))
				throw new ArgumentException("Hex color string is empty", "hexColor");

			bool leadingHash = false;
			if (hexColor[0] == '#')
			{
				hexColor = hexColor.Substring(1);
				leadingHash = true;
			}

			if (hexColor.Length == 3)
			{
				// RGB = RRGGBB
				hexColor = String.Format("{0}{0}{1}{1}{2}{2}", hexColor[0], hexColor[1], hexColor[2]);
			}
			else if (hexColor.Length == 4)
			{
				// RGBA = RRGGBBAA
				hexColor = String.Format("{0}{0}{1}{1}{2}{2}{3}{3}", hexColor[0], hexColor[1], hexColor[2], hexColor[3]);
			}
			else
			{
				throw new FormatException("Hex must of length 3 or 4");
			}

			if (leadingHash)
				return "#" + hexColor;
			else
				return hexColor;
		}
		private static string ExpandHexStringInternal(string hexColor)
		{
			// Leading # is stripped off by caller

			// Expand the short hand versions (RGB and RGBA) into full 2 byte representations
			if (hexColor.Length == 3)
			{
				return ExpandHexString(hexColor);
			}
			else if (hexColor.Length == 4)
			{
				return ExpandHexString(hexColor);
			}
			else
			{
				return hexColor;
			}
		}

		public override string ToString()
		{
			return String.Format("R: {0:0.00} G: {1:0.00} B: {2:0.00}, A: {3:0.00}", this.Red, this.Green, this.Blue, this.Alpha);
		}
		/// <summary>Produces a 32 bit hex string representation of this color. Format is #RRGGBBAA</summary>
		public string ToHexString()
		{
			int r = (int)(this.Red * byte.MaxValue);
			int g = (int)(this.Green * byte.MaxValue);
			int b = (int)(this.Blue * byte.MaxValue);
			int a = (int)(this.Alpha * byte.MaxValue);

			return String.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", r, g, b, a);
		}

		/// <summary>Converts the color to a vector (RGBA).</summary>
		/// <returns></returns>
		public Vector4 ToVector4()
		{
			return new Vector4(this.Red, this.Green, this.Blue, this.Alpha);
		}
		/// <summary>Converts the Color struct to a SharpDX Color4 struct.</summary>
		/// <returns></returns>
		public Color4 ToColor4()
		{
			return new Color4(this.Alpha, this.Red, this.Green, this.Blue);
		}

		public override bool Equals(object obj)
		{
			return obj != null && obj is Color && (Color)obj == this;
		}
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		public static bool operator ==(Color x, Color y)
		{
			return
				x.Alpha == y.Alpha &&
				x.Red == y.Red &&
				x.Green == y.Green &&
				x.Blue == y.Blue;
		}
		public static bool operator !=(Color x, Color y)
		{
			return !(x == y);
		}

		//

		public float Red { get; set; }
		public float Green { get; set; }
		public float Blue { get; set; }
		public float Alpha { get; set; }
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Sample/Sample.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;

namespace PhysX.Samples
{
	public abstract class Sample
	{
		// TODO: Refactor how the physics objects are created, they're too hidden away from the individual samples
		protected Sample(Action<SceneDesc> sceneDescCallback = null)
		{
			Engine = new PhysX.Samples.Engine.Engine(sceneDescCallback);
			Engine.OnUpdate += UpdateEngine;
			Engine.OnDraw += (s, e) => DrawEngine();

			LoadContent();
			LoadPhysics(Engine.Scene);
		}

		private void UpdateEngine(TimeSpan elapsed)
		{
			if (Engine.Keyboard.IsKeyDown(Key.Escape))
			{
				Shutdown();
				return;
			}

			UpdateSample(elapsed);
		}
		protected void DrawEngine()
		{
			Draw();
		}

		protected abstract void LoadContent();
		protected abstract void LoadPhysics(Scene scene);
		private void UpdateSample(TimeSpan elapsed)
		{
			ProcessKeyboard(Engine.Keyboard.PressedKeys.ToArray());

			ProcessMouse(Engine.Camera.MouseDelta.X, Engine.Camera.MouseDelta.Y);

			Update(elapsed);
		}
		protected abstract void Update(TimeSpan elapsed);
		protected abstract void Draw();
		protected virtual void ProcessKeyboard(Key[] pressedKeys)
		{

		}
		protected virtual void ProcessMouse(float deltaX, float deltaY)
		{

		}

		protected void Run()
		{
			Engine.Run();
		}
		protected void Shutdown()
		{
			if (Engine.Physics != null && !Engine.Physics.Disposed)
				Engine.Physics.Dispose();

			Environment.Exit(0);
		}

		//

		protected PhysX.Samples.Engine.Engine Engine { get; private set; }

		public TimeSpan FrameTime => Engine.FrameTime;

		public Scene Scene => Engine.Scene;
	}
}

<|start_filename|>PhysX.Net/Test/Actor/ActorTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Actor
{
	[TestClass]
	public class ActorTest : Test
	{
		[TestMethod]
		public void ActorCollectionOfScene()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(0.2f, 0.3f, 0.1f);

				Assert.AreEqual(0, physics.Scene.RigidDynamicActors.Count());

				var rigidActor1 = physics.Scene.Physics.CreateRigidDynamic();

				Assert.AreEqual(1, physics.Scene.RigidDynamicActors.Count());

				var rigidActor2 = physics.Scene.Physics.CreateRigidDynamic();

				Assert.AreEqual(2, physics.Scene.RigidDynamicActors.Count());
			}
		}

		// https://github.com/stilldesign/PhysX.Net/issues/27
		[TestMethod]
		public void CreateAndDisposeRigidDynamicActor_EnsureItsRemovedFromTheObjectTable()
		{
			unsafe
			{
				using (var physics = CreatePhysicsAndScene())
				{
					var material = physics.Physics.CreateMaterial(0.2f, 0.3f, 0.1f);

					// Create
					// And assert things are setup
					Assert.AreEqual(0, physics.Scene.RigidDynamicActors.Length);

					var rigidActor1 = physics.Scene.Physics.CreateRigidDynamic();

					Assert.AreEqual(1, physics.Scene.RigidDynamicActors.Length);

					physx.PxRigidDynamic* rigidActor1Ptr = rigidActor1.UnmanagedPointer;

					Assert.AreEqual(rigidActor1, ObjectTable.Instance.Objects[(long)rigidActor1Ptr]);
					Assert.AreEqual(physics.Physics, ObjectTable.Instance.Ownership[rigidActor1]);
					Assert.AreEqual(rigidActor1, ObjectTable.Instance.OwnerTypeLookup[new ObjectTableOwnershipType
					{
						Owner = physics.Physics,
						Type = typeof(RigidDynamic)
					}].Single());

					//

					rigidActor1.Dispose();

					//

					// Actor should no longer be in RigidDynamicActors
					Assert.AreEqual(0, physics.Scene.RigidDynamicActors.Length);
					// Removed from the list of objects
					Assert.IsFalse(ObjectTable.Instance.Objects.ContainsKey((long)rigidActor1Ptr));
					// Nor in the ObjectTable's list of object owners
					Assert.IsFalse(ObjectTable.Instance.Ownership.ContainsKey(rigidActor1));
					// Nor in the ObjectTable's 'owner type lookup'
					Assert.IsFalse(ObjectTable.Instance.OwnerTypeLookup.ContainsKey(new ObjectTableOwnershipType
					{
						Owner = physics.Physics,
						Type = typeof(RigidDynamic)
					}));
				}
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Sample/SampleWindow.xaml.cs<|end_filename|>
﻿using System;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Input;

namespace PhysX.Samples
{
	/// <summary>
	/// Interaction logic for SampleWindow.xaml
	/// </summary>
	public partial class SampleWindow : Window
	{
		public SampleWindow()
		{
			InitializeComponent();

			Loaded += Window_Loaded;
			Closed += SampleWindow_Closed;
		}

		private void SampleWindow_Closed(object sender, EventArgs e)
		{
			Environment.Exit(0);
		}

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			this.Width = (int)(SystemParameters.PrimaryScreenWidth * 0.85);
			this.Height = (int)(SystemParameters.PrimaryScreenHeight * 0.85);

			this.Left = (SystemParameters.PrimaryScreenWidth / 2) - (this.Width / 2);
			this.Top = (SystemParameters.PrimaryScreenHeight / 2) - (this.Height / 2);
		}

		private void Window_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Escape)
				Close();
		}

		//

		public IntPtr RenderCanvasHandle
		{
			get
			{
				return new WindowInteropHelper(this).Handle;
			}
		}

		public Size RenderCanvasSize
		{
			get
			{
				return new Size(uxRenderCanvas.ActualWidth, uxRenderCanvas.ActualHeight);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Articulation/ArticulationTests.cs<|end_filename|>
﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Articulation
{
	[TestClass]
	public class ArticulationTests : Test
	{
		[TestMethod]
		public void CreateAndDispose()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var a = physics.Physics.CreateArticulation();

				a.Dispose();
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Engine/VertexPositionColor.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using SharpDX;

namespace PhysX.Samples
{
	public struct VertexPosition
	{
		public Vector3 Position;

		public VertexPosition(Vector3 position)
		{
			this.Position = position;
		}
		public VertexPosition(float x, float y, float z)
		{
			this.Position = new Vector3(x, y, z);
		}

		public static int SizeInBytes
		{
			get
			{
				return Vector3.SizeInBytes;
			}
		}
	}

	public struct VertexPosition4
	{
		public Vector4 Position;

		public VertexPosition4(Vector3 position)
		{
			this.Position = new Vector4(position, 1.0f);
		}
		public VertexPosition4(float x, float y, float z)
			: this(new Vector3(x, y, z))
		{

		}

		public static int SizeInBytes
		{
			get
			{
				return Vector4.SizeInBytes;
			}
		}
	}

	public struct VertexPositionNormal
	{
		public Vector3 Position;
		public Vector3 Normal;

		public VertexPositionNormal(Vector3 position, Vector3 normal)
		{
			this.Position = position;
			this.Normal = normal;
		}

		public static int SizeInBytes
		{
			get
			{
				return Vector3.SizeInBytes + Vector3.SizeInBytes;
			}
		}
	}

	public struct VertexPositionTextured
	{
		public Vector3 Position;
		public float U, V;

		public VertexPositionTextured(Vector3 position, float u, float v)
		{
			this.Position = position;
			this.U = u;
			this.V = v;
		}
		public VertexPositionTextured(float x, float y, float z, float u, float v)
		{
			this.Position = new Vector3(x, y, z);
			this.U = u;
			this.V = v;
		}

		public static int SizeInBytes
		{
			get
			{
				return Vector3.SizeInBytes + sizeof(float) + sizeof(float);
			}
		}
	}

	public struct VertexPositionNormalTextured
	{
		public float X, Y, Z;
		public Vector3 Normal;
		public float U, V;

		public VertexPositionNormalTextured(Vector3 position, Vector3 normal, float u, float v)
			: this()
		{
			this.Position = position;
			this.Normal = normal;
			this.U = u;
			this.V = v;
		}

		public Vector3 Position
		{
			get
			{
				return new Vector3(X, Y, Z);
			}
			set
			{
				X = value.X;
				Y = value.Y;
				Z = value.Z;
			}
		}

		public static int SizeInBytes
		{
			get
			{
				return
					Vector3.SizeInBytes +  // Position
					Vector3.SizeInBytes + // Normal
					Vector2.SizeInBytes; // Tex UV
			}
		}
	}
	public struct VertexPositionNormalTextured3
	{
		public float X, Y, Z;
		public Vector3 Normal;
		public float U, V, P;

		public VertexPositionNormalTextured3(Vector3 position, Vector3 normal, float u, float v, float p)
			: this()
		{
			this.Position = position;
			this.Normal = normal;
			this.U = u;
			this.V = v;
			this.P = p;
		}

		public Vector3 Position
		{
			get
			{
				return new Vector3(X, Y, Z);
			}
			set
			{
				X = value.X;
				Y = value.Y;
				Z = value.Z;
			}
		}

		public static int SizeInBytes
		{
			get
			{
				return
					Vector3.SizeInBytes +  // Position
					Vector3.SizeInBytes + // Normal
					Vector3.SizeInBytes; // Tex UVP
			}
		}
	}

	public struct VertexPositionNormalColored
	{
		public Vector3 Position;
		public Vector3 Normal;
		public int Color;

		public VertexPositionNormalColored(Vector3 position, Vector3 normal, int color)
		{
			this.Position = position;
			this.Normal = normal;
			this.Color = color;
		}

		public static int SizeInBytes
		{
			get
			{
				return Vector3.SizeInBytes + Vector3.SizeInBytes + sizeof(int);
			}
		}
	}

	public struct VertexPositionColor
	{
		public Vector4 Position;
		public Color Color;

		public VertexPositionColor(float x, float y, float z)
			: this(new Vector3(x, y, z), new Color())
		{

		}
		public VertexPositionColor(Vector3 position, int color)
			: this(position, Color.FromArgb(color))
		{

		}
		public VertexPositionColor(float x, float y, float z, int color)
			: this(new Vector3(x, y, z), Color.FromArgb(color))
		{

		}
		public VertexPositionColor(float x, float y, float z, Color color)
			: this(new Vector3(x, y, z), color)
		{

		}

		public VertexPositionColor(Vector3 position, Color color)
		{
			this.Position = new Vector4(position, 1);
			this.Color = color;
		}

		public static int SizeInBytes
		{
			get
			{
				return Vector4.SizeInBytes + Color.SizeInBytes;
			}
		}
	}

	public struct VertexTransformedTextured
	{
		public Vector4 Position;
		public float U, V;

		public VertexTransformedTextured(Vector4 position, float u, float v)
		{
			this.Position = position;
			this.U = u;
			this.V = v;
		}
		public VertexTransformedTextured(float x, float y, float z, float w, float u, float v)
		{
			this.Position = new Vector4(x, y, z, w);
			this.U = u;
			this.V = v;
		}

		public override string ToString()
		{
			return String.Format("Position: ({0:0.00}, {1:0.00}, {2:0.00}) UV: ({3:0.00}, {4:0.00})", Position.X, Position.Y, Position.Z, U, V);
		}

		public static int SizeInBytes
		{
			get
			{
				return Vector4.SizeInBytes + sizeof(float) + sizeof(float);
			}
		}
	}

	public struct VertexPositionPointSizeDiffuse
	{
		public Vector3 Position;
		private float Size;
		private int Color;

		public VertexPositionPointSizeDiffuse(Vector3 position, float size, int color)
		{
			Position = position;
			Color = color;
			Size = size;
		}
		public VertexPositionPointSizeDiffuse(float x, float y, float z, int color, float size)
		{
			Position = new Vector3(x, y, z);
			Color = color;
			Size = size;
		}

		public static int SizeInBytes
		{
			get
			{
				return Vector3.SizeInBytes + sizeof(float) + sizeof(int);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Physics/ContactModifyCallbackTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class ContactModifyCallbackTest : Test
	{
		[Ignore] // Not finished yet
		[TestMethod]
		public void GetContactData()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				// A box that will fall
				var box = CreateBoxActor(physics.Scene, new Vector3(5, 5, 5), new Vector3(0, 10, 0));

				// The ground
				var ground = CreateBoxActor(physics.Scene, new Vector3(100, 1, 100), new Vector3(0, 0, 0));
				ground.RigidBodyFlags = RigidBodyFlag.Kinematic; // Grounds don't move silly :P

				// Tell PhysX that the box and ground should raise collision callbacks
				DefaultSimulationFilterShader.SetGroup(box, 1);
				DefaultSimulationFilterShader.SetGroup(ground, 1);

				bool didTheBoxHitTheGround = false;

				physics.Scene.ContactModifyCallback = new TestContactModifyCallback(pairs =>
				{
					didTheBoxHitTheGround |= pairs.Any(p =>
						(p.ActorA == box && p.ActorB == ground) || 
						(p.ActorA == ground && p.ActorB == box));
				});

				// Wait for the cube to hit the ground and trigger the ContactModifyCallback. 3 seconds.
				for (int i = 0; i < 300; i++)
				{
					physics.Scene.Simulate(10);
				}

				Assert.IsTrue(didTheBoxHitTheGround);
			}
		}
	}

	public class TestContactModifyCallback : ContactModifyCallback
	{
		private Action<ContactModifyPair[]> _onContactModify;

		public TestContactModifyCallback(Action<ContactModifyPair[]> onContactModify)
		{
			_onContactModify = onContactModify;
		}

		public override void OnContactModify(ContactModifyPair[] pairs)
		{
			// Call the callback so our tests can assert the details
			_onContactModify(pairs);
		}
	}
}

<|start_filename|>PhysX.Net/Test/Vehicle/VehicleEngineDataTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Vehicle
{
	[TestClass]
	public class VehicleEngineDataTest : Test
	{
		[TestMethod]
		public void ManagedUnmanagedConversion()
		{
			var engineData = new VehicleEngineData()
			{
				DampingRateFullThrottle = 1,
				DampingRateZeroThrottleClutchDisengaged = 2,
				DampingRateZeroThrottleClutchEngaged = 3,
				MaxOmega = 4,
				PeakTorque = 5
			};

			var conversion = VehicleEngineData.TestManagedUnmanagedConversion(engineData);

			Assert.AreEqual(1, conversion.DampingRateFullThrottle);
			Assert.AreEqual(2, conversion.DampingRateZeroThrottleClutchDisengaged);
			Assert.AreEqual(3, conversion.DampingRateZeroThrottleClutchEngaged);
			Assert.AreEqual(4, conversion.MaxOmega);
			Assert.AreEqual(5, conversion.PeakTorque);
		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Engine/VertexGrid.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using SharpDX;

namespace PhysX.Samples
{
	public class VertexGrid
	{
		private VertexGrid(Vector3[] points, int[] indices)
		{
			this.Points = points;
			this.Indices = indices;
		}

		public static VertexGrid CreateGrid(int rows, int columns)
		{
			int numVertsX = rows + 1;
			int numVertsZ = columns + 1;

			VertexGrid grid = new VertexGrid(new Vector3[numVertsX * numVertsZ], new int[rows * columns * 2 * 3]);

			{
				for (int r = 0; r < numVertsX; r++)
				{
					for (int c = 0; c < numVertsZ; c++)
					{
						grid.Points[r * numVertsZ + c] = new Vector3(r, 0, c);
					}
				}
			}

			{
				int count = 0;
				int vi = 0;
				for (int z = 0; z < columns; z++)
				{
					for (int x = 0; x < rows; x++)
					{
						// First triangle
						grid.Indices[count++] = vi;
						grid.Indices[count++] = vi + 1;
						grid.Indices[count++] = vi + numVertsX;

						// Second triangle
						grid.Indices[count++] = vi + numVertsX;
						grid.Indices[count++] = vi + 1;
						grid.Indices[count++] = vi + numVertsX + 1;

						vi++;
					}
					vi++;
				}
			}

			return grid;
		}

		public Vector3[] Points { get; private set; }
		public int[] Indices { get; private set; }
	}
}

<|start_filename|>PhysX.Net/Samples/DoublePendulumSample/DoublePendulumSample.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using PhysX;
using PhysX.Samples;

namespace DoublePendulumSample
{
	public class DoublePendulumSample : Sample
	{
		private RigidDynamic _sphereC;

		public DoublePendulumSample()
		{
			Run();
		}

		protected override void LoadContent()
		{

		}

		protected override void LoadPhysics(PhysX.Scene scene)
		{
			var material = scene.Physics.CreateMaterial(0.7f, 0.7f, 0.1f);

			var sphereA = scene.Physics.CreateRigidDynamic();
			sphereA.CreateShape(new SphereGeometry(1), material);
			sphereA.GlobalPose = Matrix4x4.CreateTranslation(0, 30, 0);

			scene.AddActor(sphereA);

			//

			var sphereB = scene.Physics.CreateRigidDynamic();
			sphereB.CreateShape(new SphereGeometry(1), material);
			sphereB.GlobalPose = Matrix4x4.CreateTranslation(0, 40, 0);

			scene.AddActor(sphereB);

			//

			var sphereC = scene.Physics.CreateRigidDynamic();
			sphereC.CreateShape(new SphereGeometry(1), material);
			sphereC.GlobalPose = Matrix4x4.CreateTranslation(0, 50, 0);

			scene.AddActor(sphereC);

			_sphereC = sphereC;

			//

			var revoluteABJoint = scene.CreateJoint<RevoluteJoint>(sphereA, Matrix4x4.Identity, sphereB, Matrix4x4.Identity);
			revoluteABJoint.SetGlobalFrame(new Vector3(0, 35, 0), new Vector3(0, 0, 1));
			revoluteABJoint.ConstraintFlags = ConstraintFlag.Visualization;

			var revoluteBCJoint = scene.CreateJoint<RevoluteJoint>(sphereB, Matrix4x4.Identity, sphereC, Matrix4x4.Identity);
			revoluteBCJoint.SetGlobalFrame(new Vector3(0, 45, 0), new Vector3(0, 0, 1));
			revoluteBCJoint.ConstraintFlags = ConstraintFlag.Visualization;

			var revoluteAJoint = scene.CreateJoint<RevoluteJoint>(sphereA, Matrix4x4.Identity, null, Matrix4x4.Identity);
			revoluteAJoint.SetGlobalFrame(new Vector3(0, 30, 0), new Vector3(0, 0, 1));
			revoluteAJoint.ConstraintFlags = ConstraintFlag.Visualization;
		}

		protected override void Update(TimeSpan elapsed)
		{
			
		}

		protected override void Draw()
		{
		}

		protected override void ProcessKeyboard(Key[] pressedKeys)
		{
			if (pressedKeys.Contains(Key.P))
			{
				_sphereC.AddForceAtLocalPosition(new Vector3(25, 0, 0), new Vector3(0, 0, 0));
			}

			base.ProcessKeyboard(pressedKeys);
		}
	}
}


<|start_filename|>PhysX.Net/PhysX.Net/Source/MathUtil.h<|end_filename|>
#pragma once

namespace PhysX
{
	public ref class MathUtil
	{
	internal:
		static Matrix4x4 PxTransformToMatrix(PxTransform* transform);
		static PxTransform MatrixToPxTransform(Matrix4x4 transform);

		static Matrix4x4 PxMat33ToMatrix(PxMat33* matrix);
		static PxMat33 MatrixToPxMat33(Matrix4x4 matrix);

		static Matrix4x4 PxMat44ToMatrix(PxMat44* mat44);
		static PxMat44 MatrixToPxMat44(Matrix4x4 matrix);

		static Vector3 PxVec3ToVector3(PxVec3 vector);
		static PxVec3 Vector3ToPxVec3(Vector3 vector);

		static Vector3 PxExtendedVec3ToVector3(PxExtendedVec3 vector);
		static PxExtendedVec3 Vector3ToPxExtendedVec3(Vector3 vector);

		static Vector2 PxVec2ToVector2(PxVec2 vector);
		static PxVec2 Vector2ToPxVec2(Vector2 vector);

		static Quaternion PxQuatToQuaternion(PxQuat quat);
		static PxQuat QuaternionToPxQuat(Quaternion quat);

	public:
		static bool IsMultipleOf(int num, int divisor);

		const static float Pi = 3.1415926535897932384626433832795f;
		const static float PiOver2 = Pi / 2.0f;

		static int Vector3SizeInBytes = 12;
	};
};

<|start_filename|>PhysX.Net/Test/Shape/ShapeCreationAndDisposalTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class ShapeCreationAndDisposalTest : Test
	{
		[TestMethod]
		public void CreateAndDisposeShape()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(0.5f, 0.5f, 0.1f);

				var actor = physics.Physics.CreateRigidDynamic();

				var shape = actor.CreateShape(new BoxGeometry(5, 5, 5), material);

				physics.Scene.AddActor(actor);

				Assert.IsFalse(shape.Disposed);

				shape.Dispose();

				Assert.IsTrue(shape.Disposed);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Constraint/ConstraintTest.cs<|end_filename|>
﻿using System;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Constraint
{
	[TestClass]
	public class ConstraintTest : Test
	{
		[TestMethod]
		public void GetConstraintOfJoint()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var boxA = CreateBoxActor(core.Scene, new Vector3(1, 1, 1), new Vector3(-10, 10, 0));
				var boxB = CreateBoxActor(core.Scene, new Vector3(1, 1, 1), new Vector3(10, 10, 0));

				var joint = core.Scene.CreateJoint<SphericalJoint>(boxA, Matrix4x4.Identity, boxB, Matrix4x4.Identity);

				// Make sure its been wrapped when the joint was created
				Assert.IsNotNull(joint.Constraint);

				// Sanity checks
				Assert.AreEqual(boxA, joint.Constraint.Actor0);
				Assert.AreEqual(boxB, joint.Constraint.Actor1);
				Assert.AreEqual(core.Scene, joint.Constraint.Scene);
			}
		}

		[TestMethod]
		public void DisposingOfAJointDisposesItsChildConstraint()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var boxA = CreateBoxActor(core.Scene, new Vector3(1, 1, 1), new Vector3(-10, 10, 0));
				var boxB = CreateBoxActor(core.Scene, new Vector3(1, 1, 1), new Vector3(10, 10, 0));

				var joint = core.Scene.CreateJoint<SphericalJoint>(boxA, Matrix4x4.Identity, boxB, Matrix4x4.Identity);

				Assert.IsNotNull(joint.Constraint);
				Assert.IsFalse(joint.Constraint.Disposed);

				bool constraintOfJointDisposed = false;
				joint.Constraint.OnDisposed += (s, e) =>
				{
					constraintOfJointDisposed = true;
				};

				joint.Dispose();

				Assert.IsTrue(constraintOfJointDisposed);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/HeightField/HeightFieldSimpleTests.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class HeightFieldSimpleTests : Test
	{
		private HeightField _heightField;
		private PhysicsAndSceneTestUnit _physics;

		[TestInitialize]
		public void SetupHeightField()
		{
			_physics = CreatePhysicsAndScene();

			const int rows = 25, columns = 40;
			var samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

			var heightFieldDesc = new HeightFieldDesc()
			{
				NumberOfRows = rows,
				NumberOfColumns = columns,
				Samples = samples,
				Thickness = 4.2f,
				ConvexEdgeThreshold = 6.6f,
				Flags = HeightFieldFlag.NoBoundaryEdges
			};

			var cooking = _physics.Physics.CreateCooking();

			var stream = new MemoryStream();
			bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

			stream.Position = 0;

			_heightField = _physics.Physics.CreateHeightField(stream);

			Assert.IsNotNull(_heightField);
			Assert.IsFalse(_heightField.Disposed);
		}
		[TestCleanup]
		public void Cleanup()
		{
			_heightField.Dispose();
			_heightField = null;

			_physics.Dispose();
			_physics = null;
		}

		[TestMethod]
		public void GetNumberOfRows()
		{
			Assert.AreEqual(25, _heightField.NumberOfRows);
		}

		[TestMethod]
		public void GetNumberOfColumns()
		{
			Assert.AreEqual(40, _heightField.NumberOfColumns);
		}

		[TestMethod]
		public void GetFormat()
		{
			Assert.AreEqual(HeightFieldFormat.Signed16BitIntegersWithTriangleMaterials, _heightField.Format);
		}

		[TestMethod]
		public void GetConvexEdgeThreshold()
		{
			Assert.AreEqual(6.6f, _heightField.ConvexEdgeThreshold);
		}

		[TestMethod]
		public void GetFlags()
		{
			Assert.AreEqual(HeightFieldFlag.NoBoundaryEdges, _heightField.Flags);
		}

		[TestMethod]
		public void GetHeight()
		{
			Assert.AreEqual(-5, _heightField.GetHeight(2.0f, 3.0f));
		}

		[TestMethod]
		public void GetConcreteTypeName()
		{
			Assert.AreEqual("PxHeightField", _heightField.AsSerializable().ConcreteTypeName);
		}
	}
}

<|start_filename|>PhysX.Net/Samples/CollisionDisabledSample/CollisionDisabledSimulationFilterCallback.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PhysX.Samples.CollisionDisabledSample
{
	public class CollisionDisabledSimulationFilterCallback : PhysX.SimulationFilterCallback
	{
		public List<Tuple<RigidActor, RigidActor>> DisableCollisionBetweenActors { get; } = new List<Tuple<RigidActor, RigidActor>>();

		public override PairFoundResult PairFound(int pairId,
			int attributes0, FilterData filterData0, Actor a0, Shape s0,
			int attributes1, FilterData filterData1, Actor a1, Shape s1,
			PairFlag pairFlags)
		{
			// Check if the two colliding actors are ones we want to disable collision on
			// a0 and a1 can be in either order, so we need to check [a0, a1] and [a1, a0]
			bool disableCollision = this.DisableCollisionBetweenActors.Any(d => (d.Item1 == a0 || d.Item2 == a0) && (d.Item1 == a1 || d.Item2 == a1));

			return new PairFoundResult
			{
				FilterFlags = disableCollision ? FilterFlag.Suppress : FilterFlag.Default,
				PairFlags = PairFlag.ContactDefault
			};
		}

		public override void PairLost(int pairId, int attributes0, FilterData filterData0, int attributes1, FilterData filterData1, bool objectRemoved)
		{
		}

		public override StatusChangeResult? StatusChange(int pairId, PairFlag pairFlags, FilterFlag filterFlags)
		{
			return null;
		}
	}
}


<|start_filename|>PhysX.Net/Samples/JointsSample/Program.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PhysX.Samples.JointsSample
{
	public class Program
	{
		[STAThread]
		static void Main(string[] args)
		{
			new JointsSample();
		}
	}
}

<|start_filename|>PhysX.Net/PhysX.Net/Source/GeometryQuery.cpp<|end_filename|>
#include "StdAfx.h"
#include "GeometryQuery.h"
#include "SweepHit.h"

SweepHit^ GeometryQuery::Sweep(Vector3 unitDirection, float distance, Geometry^ geom0, Matrix pose0, Geometry^ geom1, Matrix pose1, [Optional] Nullable<HitFlag> hitFlags, [Optional] Nullable<float> inflation)
{
	if (geom0 == nullptr)
		throw gcnew ArgumentNullException("geom0");
	if (geom1 == nullptr)
		throw gcnew ArgumentNullException("geom1");

	PxSweepHit sh;

	PxGeometry* g0 = geom0->ToUnmanaged();
	PxGeometry* g1 = geom1->ToUnmanaged();

	bool result = PxGeometryQuery::sweep
	(
		UV(unitDirection),
		distance,
		*g0,
		UM(pose0),
		*g1,
		UM(pose1),
		sh,
		ToUnmanagedEnum(PxHitFlag, hitFlags.GetValueOrDefault(HitFlag::Default)),
		inflation.GetValueOrDefault(0)
	);

	delete g0, g1;

	if (!result)
		return nullptr;

	return SweepHit::ToManaged(sh);
}

Bounds3 GeometryQuery::GetWorldBounds(Geometry^ geometry, Matrix pose, [Optional] Nullable<float> inflation)
{
	if (geometry == nullptr)
		throw gcnew ArgumentNullException("geometry");

	PxGeometry* g = geometry->ToUnmanaged();

	PxTransform t = UM(pose);

	PxBounds3 bounds = PxGeometryQuery::getWorldBounds
	(
		*g,
		t,
		inflation.GetValueOrDefault(1.01f)
	);

	delete g;

	return Bounds3::ToManaged(bounds);
}

<|start_filename|>PhysX.Net/Test/ErrorOutput.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

namespace PhysX.Test
{
	public class ErrorLog : PhysX.ErrorCallback
	{
		private List<string> _errors;

		public ErrorLog()
		{
			_errors = new List<string>();
		}

		public override void ReportError(ErrorCode errorCode, string message, string file, int lineNumber)
		{
			string e = string.Format("Code: {0}, Message: {1}", errorCode, message);

			_errors.Add(e);

			Trace.WriteLine(e);
		}

		public override string ToString()
		{
			if (_errors.Count == 0)
				return "No errors";
			else
				return string.Format("{0} errors. Last error: {1}", _errors.Count, _errors[_errors.Count - 1]);
		}

		public int ErrorCount
		{
			get
			{
				return _errors.Count;
			}
		}

		public bool HasErrors
		{
			get
			{
				return _errors.Any();
			}
		}

		public string LastError
		{
			get
			{
				return _errors.LastOrDefault() ?? String.Empty;
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Material/MaterialTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class MaterialTest : Test
	{
		[TestMethod]
		public void GetDynamicFriction()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(5, 6, 7);

				Assert.AreEqual(6, material.DynamicFriction);
			}
		}

		[TestMethod]
		public void GetStaticFriction()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(5, 6, 7);

				Assert.AreEqual(5, material.StaticFriction);
			}
		}

		[TestMethod]
		public void GetRestitution()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(5, 6, 7);

				Assert.AreEqual(7, material.Restitution);
			}
		}

		[TestMethod]
		public void GetFlags()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(5, 6, 7);

				material.Flags = MaterialFlags.DisableFriction | MaterialFlags.DisableStrongFriction;

				Assert.IsTrue(material.Flags.HasFlag(MaterialFlags.DisableFriction));
				Assert.IsTrue(material.Flags.HasFlag(MaterialFlags.DisableStrongFriction));
			}
		}

		[TestMethod]
		public void GetFrictionCombineMode()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(5, 6, 7);

				material.FrictionCombineMode = CombineMode.Max;
				Assert.AreEqual(CombineMode.Max, material.FrictionCombineMode);

				material.FrictionCombineMode = CombineMode.Multiply;
				Assert.AreEqual(CombineMode.Multiply, material.FrictionCombineMode);
			}
		}

		[TestMethod]
		public void GetRestitutionCombineMode()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(5, 6, 7);

				material.RestitutionCombineMode = CombineMode.Max;
				Assert.AreEqual(CombineMode.Max, material.RestitutionCombineMode);

				material.RestitutionCombineMode = CombineMode.Multiply;
				Assert.AreEqual(CombineMode.Multiply, material.RestitutionCombineMode);
			}
		}

		[TestMethod]
		public void GetConcreteTypeName()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(5, 6, 7);

				Assert.AreEqual("PxMaterial", material.ConcreteTypeName);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Engine/Camera.cs<|end_filename|>
﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Input;
using SharpDX;
using SharpDX.Direct3D11;

namespace PhysX.Samples.Engine
{
	public class Camera
	{
		private Engine _engine;
		private float _cameraPitch, _cameraYaw;

		internal Camera(Engine engine)
		{
			_engine = engine;

			this.Viewport = new Viewport(0, 0, (int)_engine.Window.Width, (int)_engine.Window.Height);
			this.View = Matrix.LookAtLH(new Vector3(0, 20, -90), new Vector3(0, 20, 0), new Vector3(0, 1, 0));
			this.Projection = Matrix.PerspectiveFovLH((float)(System.Math.PI / 4.0), Viewport.AspectRatio(), 0.5f, 10000);

			CenterCursor();
		}

		public void Update(TimeSpan elapsedTime)
		{
			Vector2 delta = GetMouseDelta();
			Vector2 deltaDampened = delta * 0.0005f;
			CenterCursor();

			this.MouseDelta = delta;

			// Should perhaps extract the yaw and pitch from the current direction of the camera
			_cameraYaw += deltaDampened.X;
			_cameraPitch += deltaDampened.Y;

			//

			Vector3 forward = Mathematics.DirectionFromViewMatrix(Matrix.Invert(this.View));
			Vector3 position = Matrix.Invert(this.View).TranslationVector;

			Matrix cameraRotation = Matrix.RotationYawPitchRoll(_cameraYaw, _cameraPitch, 0);
			Vector3 newForward = Vector3.TransformNormal(Vector3.UnitZ, cameraRotation);

			double elapsed = elapsedTime.TotalSeconds; // Elapsed time since last frame in seconds
			double speedMultiplier = (_engine.Keyboard.IsKeyDown(Key.LeftShift) ? 2 : 1);
			double speed = 40.0 * speedMultiplier; // 40 distance units per second
			float distance = (float)(speed * elapsed); // d = vt

			// The amount of movement * the direction of movement, then rotate that along the direction we are looking
			Vector3 translateDirection = Vector3.Zero;

			if (_engine.Keyboard.IsKeyDown(Key.W)) // Forwards
				translateDirection += Vector3.TransformNormal(Vector3.UnitZ, cameraRotation);

			if (_engine.Keyboard.IsKeyDown(Key.S)) // Backwards
				translateDirection += Vector3.TransformNormal(-Vector3.UnitZ, cameraRotation);

			if (_engine.Keyboard.IsKeyDown(Key.A)) // Left
				translateDirection += Vector3.TransformNormal(-Vector3.UnitX, cameraRotation);

			if (_engine.Keyboard.IsKeyDown(Key.D)) // Right
				translateDirection += Vector3.TransformNormal(Vector3.UnitX, cameraRotation);

			Vector3 newPosition = position;

			if (translateDirection.LengthSquared() > 0)
				newPosition += Vector3.Normalize(translateDirection) * distance;

			this.View = Matrix.LookAtLH(newPosition, newPosition + newForward, Vector3.UnitY);
		}

		private Vector2 GetMouseDelta()
		{
			System.Drawing.Point p;
			GetCursorPos(out p);

			var mousePos = p - new Size((int)_engine.Window.Left, (int)_engine.Window.Top);

			Vector2 cursorPosition = new Vector2(mousePos.X, mousePos.Y);
			Vector2 mouseCenter = new Vector2((float)_engine.Window.Width / 2, (float)_engine.Window.Height / 2);

			return cursorPosition - mouseCenter;
		}

		private void CenterCursor()
		{
			var l = new System.Drawing.Point((int)_engine.Window.Left, (int)_engine.Window.Top);
			var s = new Size((int)_engine.Window.Width, (int)_engine.Window.Height);

			SetCursorPos(l.X + s.Width / 2, l.Y + s.Height / 2);
		}

		//

		public Matrix View { get; set; }
		public Matrix Projection { get; private set; }

		public Viewport Viewport { get; set; }

		public Vector3 Position
		{
			get
			{
				Matrix viewI = Matrix.Invert(this.View);

				return new Vector3(viewI.M41, viewI.M42, viewI.M43);
			}
		}
		public Vector3 Direction
		{
			get
			{
				return Vector3.Normalize(new Vector3(View.M13, View.M23, View.M33));
			}
		}

		/// <summary>
		/// Gets the change in mouse position (in pixels).
		/// This value is updated each frame.
		/// </summary>
		public Vector2 MouseDelta { get; private set; }

		//

		[DllImport("user32.dll")]
		static extern bool SetCursorPos(int X, int Y);
		[DllImport("user32.dll")]
		public static extern bool GetCursorPos(out System.Drawing.Point pt);
	}
}

<|start_filename|>PhysX.Net/Test/Physics/PhysicsTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PhysX;

namespace PhysX.Test
{
	[TestClass]
	public class PhysicsTest : Test
	{
		[TestMethod]
		public void CreateAndDisposePhysicsInstance()
		{
			using (var foundation = new Foundation(new ConsoleErrorCallback()))
			{
				Physics physics;
				using (physics = new Physics(foundation))
				{
					GC.Collect();

					Assert.IsFalse(physics.Disposed);
				}

				Assert.IsTrue(physics.Disposed);
			}
		}

		[TestMethod]
		public void ThrowsExceptionOnDuplicateInstantiation()
		{
			using (var foundation = new Foundation(new ConsoleErrorCallback()))
			{
				try
				{
					using (var physics = new Physics(foundation))
					{
						using (var physics2 = new Physics(foundation))
						{

						}
					}
					Assert.Fail("Creating multiple physics instances should throw an exception");
				}
				catch (PhysicsAlreadyInstantiatedException)
				{

				}
			}
		}

		/// <summary>
		/// This tests creating 10 materials and getting them back from Physics.Materials property.
		/// </summary>
		[TestMethod]
		public void CreateAndRetrieve10Materials()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var materials = new List<Material>();

				for (int i = 0; i < 10; i++)
				{
					var material = physics.Physics.CreateMaterial(10, 5, 0.5f);

					materials.Add(material);
				}

				foreach (var material in materials)
				{
					bool exists = physics.Physics.Materials.Contains(material);

					Assert.IsTrue(exists);
				}
			}
		}

		[TestMethod]
		public void VehicleSDKIsInitalized()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				Assert.IsNotNull(physics.Physics.VehicleSDK);
			}
		}

		[TestMethod]
		public void OnMaterialAdded()
		{
			bool onMaterialAddedCalled = false;

			using (var physics = CreatePhysicsAndScene())
			{
				physics.Physics.OnMaterialAdded += mat =>
				{
					onMaterialAddedCalled = true;
				};

				var material = physics.Physics.CreateMaterial(10, 5, 0.5f);
			}

			Assert.IsTrue(onMaterialAddedCalled);
		}

		[TestMethod]
		public void OnMaterialRemoved()
		{
			bool onMaterialRemovedCalled = false;

			using (var physics = CreatePhysicsAndScene())
			{
				physics.Physics.OnMaterialRemoved += mat =>
				{
					onMaterialRemovedCalled = true;
				};

				var material = physics.Physics.CreateMaterial(10, 5, 0.5f);

				// Dispose a material should raise OnMaterialRemoved event
				material.Dispose();
			}

			Assert.IsTrue(onMaterialRemovedCalled);
		}

		/// <summary>
		/// Test getting all the created <see cref="PhysX.Joint"/> objects.
		/// </summary>
		[TestMethod]
		public void GetJoints()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var material = physics.Physics.CreateMaterial(0.2f, 0.1f, 0.2f);
				var rigid = physics.Physics.CreateRigidDynamic();

				var sphericalJoint = physics.Scene.CreateJoint<SphericalJoint>(rigid, Matrix4x4.Identity, null, Matrix4x4.Identity);

				var joints = physics.Physics.Joints;

				Assert.AreEqual(1, joints.Length);
				Assert.AreEqual(sphericalJoint, joints[0]);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Joint/DistanceJointTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class DistanceJointTest : Test
	{
		[TestMethod]
		public void CreateAndDisposeDistanceJoint()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var box = CreateBoxActor(core.Scene, 5, 5, 5);

				var lf0 = Matrix4x4.CreateTranslation(1, 2, 3);
				var lf1 = Matrix4x4.CreateTranslation(3, 2, 1);

				using (var distance = core.Scene.CreateJoint<DistanceJoint>(box, lf0, null, lf1))
				{

				}
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Actor/ActorSerialization.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class ActorSerialization : Test
	{
		[TestMethod]
		public void Actor_GetConcreteTypeName()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var box = CreateBoxActor(physics.Scene, 5, 5, 5);

				var serializableActor = box.AsSerializable();

				string concreteTypeName = serializableActor.ConcreteTypeName;

				Assert.AreEqual("PxRigidDynamic", concreteTypeName);
			}
		}

		[TestMethod]
		public void Actor_GetConcreteType()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var box = CreateBoxActor(physics.Scene, 5, 5, 5);

				var serializableActor = box.AsSerializable();

				ConcreteType concreteType = serializableActor.ConcreteType;

				Assert.AreEqual(ConcreteType.RigidDynamic, concreteType);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/ErrorOutput.cs<|end_filename|>
using System;
using System.Collections.Generic;

namespace PhysX.Samples
{
	public class ErrorOutput : ErrorCallback
	{
		public override void ReportError(ErrorCode errorCode, string message, string file, int lineNumber)
		{
			Console.WriteLine("PhysX: " + message);
		}
	}
}

<|start_filename|>PhysX.Net/Samples/VehicleSample/VehicleSample.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

namespace PhysX.Samples.VehicleSample
{
	public class VehicleSample : Sample
	{
		protected override void LoadContent()
		{
			
		}

		protected override void LoadPhysics(Scene scene)
		{
			var wheelCenters = new[]
			{
				new Vector3(-10, -3, -15),
				new Vector3(10, -3, -15),
				new Vector3(-10, -3, 15),
				new Vector3(10, -3, 15)
			};

			var wheels = new VehicleWheelsSimData(4);
			var drive = new VehicleDriveSimData4W();
			var chassis = new VehicleChassisData();

			CreateVehicle4WSimulationData(1000, null, 3, null, wheelCenters, wheels, drive, chassis);
		}

		private void CreateVehicle4WSimulationData(
			float chassisMass,
			ConvexMesh chassisConvexMesh,
			float wheelMass, 
			ConvexMesh[] wheelConvexMeshes, 
			Vector3[] wheelCentreOffsets,
			VehicleWheelsSimData wheelsData, 
			VehicleDriveSimData4W driveData, 
			VehicleChassisData chassisData)
		{
			const int TIRE_TYPE_SLICKS = 0;

			//Extract the chassis AABB dimensions from the chassis convex mesh.
			//Vector3 chassisDims = computeChassisAABBDimensions(chassisConvexMesh);
			Vector3 chassisDims = new Vector3(10, 10, 10);

			//The origin is at the center of the chassis mesh.
			//Set the center of mass to be below this point and a little towards the front.
			Vector3 chassisCMOffset = new Vector3(0.0f, -chassisDims.Y * 0.5f + 0.65f, 0.25f);

			//Now compute the chassis mass and moment of inertia.
			//Use the moment of inertia of a cuboid as an approximate value for the chassis moi.
			Vector3 chassisMOI = new Vector3
			(
				(chassisDims.Y * chassisDims.Y + chassisDims.Z * chassisDims.Z) * chassisMass / 12.0f,
				(chassisDims.X * chassisDims.X + chassisDims.Z * chassisDims.Z) * chassisMass / 12.0f,
				(chassisDims.X * chassisDims.X + chassisDims.Y * chassisDims.Y) * chassisMass / 12.0f
			);

			//A bit of tweaking here.  The car will have more responsive turning if we reduce the
			//y-component of the chassis moment of inertia.
			chassisMOI.Y *= 0.8f;

			//Let's set up the chassis data structure now.
			chassisData.Mass = chassisMass;
			chassisData.MomentOfInertia = chassisMOI;
			chassisData.CenterOfMassOffset = chassisCMOffset;

			//Work out the front/rear mass split from the cm offset.
			//This is a very approximate calculation with lots of assumptions.
			//massRear*zRear + massFront*zFront = mass*cm           (1)
			//massRear       + massFront        = mass                      (2)
			//Rearrange (2)
			//massFront = mass - massRear                                           (3)
			//Substitute (3) into (1)
			//massRear(zRear - zFront) + mass*zFront = mass*cm      (4)
			//Solve (4) for massRear
			//massRear = mass(cm - zFront)/(zRear-zFront)           (5)
			//Now we also have
			//zFront = (z-cm)/2                                                                     (6a)
			//zRear = (-z-cm)/2                                                                     (6b)
			//Substituting (6a-b) into (5) gives
			//massRear = 0.5*mass*(z-3cm)/z                                         (7)
			float massRear = 0.5f * chassisMass * (chassisDims.Z - 3 * chassisCMOffset.Z) / chassisDims.Z;
			float massFront = chassisMass - massRear;

			//Extract the wheel radius and width from the wheel convex meshes.
			float[] wheelWidths = new float[4];
			float[] wheelRadii = new float[4];
			//ComputeWheelWidthsAndRadii(wheelConvexMeshes, wheelWidths, wheelRadii);
			wheelWidths = new[] { 3f, 3, 3, 3 };
			wheelRadii = new[] { 1f, 1, 1, 1 };

			//Now compute the wheel masses and inertias components around the axle's axis.
			//http://en.wikipedia.org/wiki/List_of_moments_of_inertia
			float[] wheelMOIs = new float[4];
			for (int i = 0; i < 4; i++)
			{
				wheelMOIs[i] = 0.5f * wheelMass * wheelRadii[i] * wheelRadii[i];
			}
			//Let's set up the wheel data structures now with radius, mass, and moi.
			VehicleWheelData[] wheels = new VehicleWheelData[4]
			{
				new VehicleWheelData(),
				new VehicleWheelData(),
				new VehicleWheelData(),
				new VehicleWheelData()
			};
			for (int i = 0; i < 4; i++)
			{
				wheels[i].Radius = wheelRadii[i];
				wheels[i].Mass = wheelMass;
				wheels[i].MomentOfInertia = wheelMOIs[i];
				wheels[i].Width = wheelWidths[i];
			}
			//Disable the handbrake from the front wheels and enable for the rear wheels
			wheels[(int)VehicleWheelOrdering.FrontLeft].MaxHandBrakeTorque = 0.0f;
			wheels[(int)VehicleWheelOrdering.FrontRight].MaxHandBrakeTorque = 0.0f;
			wheels[(int)VehicleWheelOrdering.RearLeft].MaxHandBrakeTorque = 4000.0f;
			wheels[(int)VehicleWheelOrdering.RearRight].MaxHandBrakeTorque = 4000.0f;
			//Enable steering for the front wheels and disable for the front wheels.
			wheels[(int)VehicleWheelOrdering.FrontLeft].MaxSteer = (float)System.Math.PI * 0.3333f;
			wheels[(int)VehicleWheelOrdering.FrontRight].MaxSteer = (float)System.Math.PI * 0.3333f;
			wheels[(int)VehicleWheelOrdering.RearLeft].MaxSteer = 0.0f;
			wheels[(int)VehicleWheelOrdering.RearRight].MaxSteer = 0.0f;

			//Let's set up the tire data structures now.
			//Put slicks on the front tires and wets on the rear tires.
			VehicleTireData[] tires = new VehicleTireData[4]
			{
				new VehicleTireData(),
				new VehicleTireData(),
				new VehicleTireData(),
				new VehicleTireData()
			};
			tires[(int)VehicleWheelOrdering.FrontLeft].Type = TIRE_TYPE_SLICKS;
			tires[(int)VehicleWheelOrdering.FrontRight].Type = TIRE_TYPE_SLICKS;
			tires[(int)VehicleWheelOrdering.RearLeft].Type = TIRE_TYPE_SLICKS;
			tires[(int)VehicleWheelOrdering.RearRight].Type = TIRE_TYPE_SLICKS;

			//Let's set up the suspension data structures now.
			VehicleSuspensionData[] susps = new VehicleSuspensionData[4]
			{
				new VehicleSuspensionData(),
				new VehicleSuspensionData(),
				new VehicleSuspensionData(),
				new VehicleSuspensionData()
			};
			for (int i = 0; i < 4; i++)
			{
				susps[i].MaxCompression = 0.3f;
				susps[i].MaxDroop = 0.1f;
				susps[i].SpringStrength = 35000.0f;
				susps[i].SpringDamperRate = 4500.0f;
			}
			susps[(int)VehicleWheelOrdering.FrontLeft].SprungMass = massFront * 0.5f;
			susps[(int)VehicleWheelOrdering.FrontRight].SprungMass = massFront * 0.5f;
			susps[(int)VehicleWheelOrdering.RearLeft].SprungMass = massRear * 0.5f;
			susps[(int)VehicleWheelOrdering.RearRight].SprungMass = massRear * 0.5f;

			//We need to set up geometry data for the suspension, wheels, and tires.
			//We already know the wheel centers described as offsets from the rigid body centre of mass.
			//From here we can approximate application points for the tire and suspension forces.
			//Lets assume that the suspension travel directions are absolutely vertical.
			//Also assume that we apply the tire and suspension forces 30cm below the centre of mass.
			Vector3[] suspTravelDirections = new Vector3[] { new Vector3(0, -1, 0), new Vector3(0, -1, 0), new Vector3(0, -1, 0), new Vector3(0, -1, 0) };
			Vector3[] wheelCentreCMOffsets = new Vector3[4];
			Vector3[] suspForceAppCMOffsets = new Vector3[4];
			Vector3[] tireForceAppCMOffsets = new Vector3[4];
			for (int i = 0; i < 4; i++)
			{
				wheelCentreCMOffsets[i] = wheelCentreOffsets[i] - chassisCMOffset;
				suspForceAppCMOffsets[i] = new Vector3(wheelCentreCMOffsets[i].X, -0.3f, wheelCentreCMOffsets[i].Z);
				tireForceAppCMOffsets[i] = new Vector3(wheelCentreCMOffsets[i].X, -0.3f, wheelCentreCMOffsets[i].Z);
			}

			//Now add the wheel, tire and suspension data.
			for (int i = 0; i < 4; i++)
			{
				wheelsData.SetWheelData(i, wheels[i]);
				wheelsData.SetTireData(i, tires[i]);
				wheelsData.SetSuspensionData(i, susps[i]);
				wheelsData.SetSuspensionTravelDirection(i, suspTravelDirections[i]);
				wheelsData.SetWheelCentreOffset(i, wheelCentreCMOffsets[i]);
				wheelsData.SetSuspensionForceApplicationPointOffset(i, suspForceAppCMOffsets[i]);
				wheelsData.SetTireForceApplicationPointOffset(i, tireForceAppCMOffsets[i]);
			}

			//Now set up the differential, engine, gears, clutch, and ackermann steering.

			//Diff
			VehicleDifferential4WData diff = new VehicleDifferential4WData();
			diff.Type = VehicleDifferentialType.LimitedSlip4WheelDrive;
			driveData.SetDifferentialData(diff);

			//Engine
			VehicleEngineData engine = new VehicleEngineData()
			{
				PeakTorque = 500.0f,
				MaxOmega = 600.0f//approx 6000 rpm
			};
			driveData.SetEngineData(engine);

			//Gears
			VehicleGearsData gears = new VehicleGearsData()
			{
				SwitchTime = 0.5f
			};
			driveData.SetGearsData(gears);

			//Clutch
			VehicleClutchData clutch = new VehicleClutchData()
			{
				Strength = 10.0f
			};
			driveData.SetClutchData(clutch);

			//Ackermann steer accuracy
			var ackermann = new VehicleAckermannGeometryData()
			{
				Accuracy = 1.0f,
				AxleSeparation = wheelCentreOffsets[(int)VehicleWheelOrdering.FrontLeft].Z - wheelCentreOffsets[(int)VehicleWheelOrdering.RearLeft].Z,
				FrontWidth = wheelCentreOffsets[(int)VehicleWheelOrdering.FrontRight].X - wheelCentreOffsets[(int)VehicleWheelOrdering.FrontLeft].X,
				RearWidth = wheelCentreOffsets[(int)VehicleWheelOrdering.RearRight].X - wheelCentreOffsets[(int)VehicleWheelOrdering.RearLeft].X
			};
			driveData.SetAckermannGeometryData(ackermann);
		}

		protected override void Update(TimeSpan elapsed)
		{

		}

		protected override void Draw()
		{

		}
	}
}

<|start_filename|>PhysX.Net/Test/SequentialLayoutStructTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	/// <summary>
	/// Tests for structs which are tagged with the StructLayout Sequential attribute, which are thus intended
	/// to have the exact same signature as their unmanaged counterpart.
	/// </summary>
	[TestClass]
	public class SequentialLayoutStructTest
	{
		
	}
}

<|start_filename|>PhysX.Net/Test/FoundationTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class FoundationTest : Test
	{
		[TestMethod]
		public void CreateAndCleanlyDisposeOfFoundation()
		{
			var error = new ExceptionErrorCallback()
			{
				BadMessages = new[] { "" }
			};

			using (var foundation = new Foundation(error))
			{

			}
		}

		/// <summary>
		/// Releasing a PxFoundation can report an error and not close down successfully. Actions such as
		/// calling PxCloseVehicleSDK() when no corrisponding PxInitVehicleSDK call has been made can cause this.
		/// </summary>
		[TestMethod]
		public void CreateAndCleanlyDisposeOfFoundationWithPhysics()
		{
			var error = new ExceptionErrorCallback()
			{
				BadMessages = new[] { "" }
			};

			using (var foundation = new Foundation(error))
			{
				using (var physics = new Physics(foundation))
				{

				}
			}
		}

		[TestMethod]
		public void OnlyOneInstanceOfFoundationCanExist()
		{
			using (var foundation = new Foundation())
			{
				try
				{
					using (var foundation2 = new Foundation())
					{
						Assert.Fail("Only one instance of Foundation can exist at a time");
					}
				}
				catch (FoundationAlreadyInitalizedException)
				{

				}
				catch
				{
					Assert.Fail("Initalizing a second foundation should throw an error of type " + typeof(FoundationAlreadyInitalizedException).Name);
				}
			}
		}

		private class ExceptionErrorCallback : ErrorCallback
		{
			public string[] BadMessages { get; set; }

			public override void ReportError(ErrorCode errorCode, string message, string file, int lineNumber)
			{
				if (BadMessages.Any(m => message.Contains(m)))
					throw new Exception(message);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Extensions/ViewportExtensions.cs<|end_filename|>
﻿using System;
using SharpDX;

namespace PhysX.Samples
{
	public static class ViewportExtensions
	{
		public static float AspectRatio(this Viewport viewport)
		{
			return (float)viewport.Width / (float)viewport.Height;
		}
	}
}

<|start_filename|>PhysX.Net/Samples/Engine/Engine/VisualizationEffect.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using SharpDX.Direct3D11;

namespace PhysX.Samples
{
	public class VisualizationEffect
	{
		public Effect Effect { get; set; }

		public EffectMatrixVariable World { get; set; }
		public EffectMatrixVariable View { get; set; }
		public EffectMatrixVariable Projection { get; set; }

		public EffectPass RenderScenePass0 { get; set; }
	}
}

<|start_filename|>PhysX.Net/PhysX.Net/Source/GeometryQuery.h<|end_filename|>
#pragma once

#include "Geometry.h"
#include "SceneEnum.h"
#include "Bounds3.h"

namespace PhysX
{
	ref class SweepHit;

	public ref class GeometryQuery
	{
	public:
		static SweepHit^ Sweep(Vector3 unitDirection, float distance, Geometry^ geom0, Matrix pose0, Geometry^ geom1, Matrix pose1, [Optional] Nullable<HitFlag> hitFlags, [Optional] Nullable<float> inflation);

		// TODO: Overlap
		// TODO: Raycast
		// TODO: ComputePenetration
		// TODO: PointDistance

		static Bounds3 GetWorldBounds(Geometry^ geometry, Matrix pose, [Optional] Nullable<float> inflation);
	};
}

<|start_filename|>PhysX.Net/Test/BroadPhase/BroadPhaseExtTests.cs<|end_filename|>
﻿using System;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test
{
	[TestClass]
	public class BroadPhaseExtTests
	{
		[TestMethod]
		public void CreateRegionsFromWorldBounds()
		{
			var bounds = BroadPhaseExt.CreateRegionsFromWorldBounds(new Bounds3(new Vector3(10)), 3);

			Assert.IsNotNull(bounds);
			Assert.AreEqual(9, bounds.Length);
		}
	}
}


<|start_filename|>PhysX.Net/Samples/DoublePendulumSample/Program.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DoublePendulumSample
{
	public class Program
	{
		[STAThread]
		static void Main(string[] args)
		{
			new DoublePendulumSample();
		}
	}
}


<|start_filename|>PhysX.Net/Test/Aggregate/AggregateTests.cs<|end_filename|>
﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Aggregate
{
	[TestClass]
	public class AggregateTests : Test
	{
		[TestMethod]
		public void CreateAndDispose()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var agg = physics.Physics.CreateAggregate(100, true);

				agg.Dispose();

				Assert.IsFalse(ObjectTable.Instance.Contains(agg));
			}
		}

		[TestMethod]
		public void GetActor()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var agg = physics.Physics.CreateAggregate(100, true);

				var actor = physics.Physics.CreateRigidDynamic();

				bool added = agg.AddActor(actor);

				Assert.IsTrue(added);
				Assert.AreEqual(actor, agg.GetActor(0));
			}
		}

		[TestMethod]
		public void GetActors()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var agg = physics.Physics.CreateAggregate(100, true);

				var actor1 = physics.Physics.CreateRigidDynamic();
				var actor2 = physics.Physics.CreateRigidDynamic();

				agg.AddActor(actor1);
				agg.AddActor(actor2);

				var actors = agg.GetActors();

				Assert.AreEqual(actor1, actors[0]);
				Assert.AreEqual(actor2, actors[1]);
			}
		}
	}
}

<|start_filename|>PhysX.Net/Test/Controller/ObstacleTest.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Controller
{
	[TestClass]
	public class ObstacleTest : Test
	{
		[TestMethod]
		public void CreateAndDisposeObstacleContext()
		{
			using (var physics = CreatePhysicsAndScene())
			{
				var controllerManager = physics.Scene.CreateControllerManager();

				var obstacleContext = controllerManager.CreateObstacleContext();

				Assert.IsFalse(obstacleContext.Disposed);

				obstacleContext.Dispose();

				Assert.IsTrue(obstacleContext.Disposed);
			}
		}
	}
}