Adding initial files

This commit is contained in:
nathan@daedalus
2012-03-19 18:57:59 -05:00
commit 5bdc5db408
162 changed files with 43840 additions and 0 deletions

View File

@@ -0,0 +1,207 @@
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
public class CircleShape : Shape
{
internal Vector2 _position;
public CircleShape(float radius, float density)
: base(density)
{
ShapeType = ShapeType.Circle;
_radius = radius;
_position = Vector2.Zero;
ComputeProperties();
}
internal CircleShape()
: base(0)
{
ShapeType = ShapeType.Circle;
_radius = 0.0f;
_position = Vector2.Zero;
}
public override int ChildCount
{
get { return 1; }
}
public Vector2 Position
{
get { return _position; }
set
{
_position = value;
ComputeProperties();
}
}
public override Shape Clone()
{
CircleShape shape = new CircleShape();
shape._radius = Radius;
shape._density = _density;
shape._position = _position;
shape.ShapeType = ShapeType;
shape.MassData = MassData;
return shape;
}
/// <summary>
/// Test a point for containment in this shape. This only works for convex shapes.
/// </summary>
/// <param name="transform">The shape world transform.</param>
/// <param name="point">a point in world coordinates.</param>
/// <returns>True if the point is inside the shape</returns>
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
Vector2 center = transform.Position + MathUtils.Multiply(ref transform.R, Position);
Vector2 d = point - center;
return Vector2.Dot(d, d) <= Radius * Radius;
}
/// <summary>
/// Cast a ray against a child shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="transform">The transform to be applied to the shape.</param>
/// <param name="childIndex">The child shape index.</param>
/// <returns>True if the ray-cast hits the shape</returns>
public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform,
int childIndex)
{
// Collision Detection in Interactive 3D Environments by Gino van den Bergen
// From Section 3.1.2
// x = s + a * r
// norm(x) = radius
output = new RayCastOutput();
Vector2 position = transform.Position + MathUtils.Multiply(ref transform.R, Position);
Vector2 s = input.Point1 - position;
float b = Vector2.Dot(s, s) - Radius * Radius;
// Solve quadratic equation.
Vector2 r = input.Point2 - input.Point1;
float c = Vector2.Dot(s, r);
float rr = Vector2.Dot(r, r);
float sigma = c * c - rr * b;
// Check for negative discriminant and short segment.
if (sigma < 0.0f || rr < Settings.Epsilon)
{
return false;
}
// Find the point of intersection of the line with the circle.
float a = -(c + (float)Math.Sqrt(sigma));
// Is the intersection point on the segment?
if (0.0f <= a && a <= input.MaxFraction * rr)
{
a /= rr;
output.Fraction = a;
Vector2 norm = (s + a * r);
norm.Normalize();
output.Normal = norm;
return true;
}
return false;
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
Vector2 p = transform.Position + MathUtils.Multiply(ref transform.R, Position);
aabb.LowerBound = new Vector2(p.X - Radius, p.Y - Radius);
aabb.UpperBound = new Vector2(p.X + Radius, p.Y + Radius);
}
/// <summary>
/// Compute the mass properties of this shape using its dimensions and density.
/// The inertia tensor is computed about the local origin, not the centroid.
/// </summary>
public override sealed void ComputeProperties()
{
float area = Settings.Pi * Radius * Radius;
MassData.Area = area;
MassData.Mass = Density * area;
MassData.Centroid = Position;
// inertia about the local origin
MassData.Inertia = MassData.Mass * (0.5f * Radius * Radius + Vector2.Dot(Position, Position));
}
public bool CompareTo(CircleShape shape)
{
return (Radius == shape.Radius &&
Position == shape.Position);
}
public override float ComputeSubmergedArea(Vector2 normal, float offset, Transform xf, out Vector2 sc)
{
sc = Vector2.Zero;
Vector2 p = MathUtils.Multiply(ref xf, Position);
float l = -(Vector2.Dot(normal, p) - offset);
if (l < -Radius + Settings.Epsilon)
{
//Completely dry
return 0;
}
if (l > Radius)
{
//Completely wet
sc = p;
return Settings.Pi * Radius * Radius;
}
//Magic
float r2 = Radius * Radius;
float l2 = l * l;
float area = r2 * (float)((Math.Asin(l / Radius) + Settings.Pi / 2) + l * Math.Sqrt(r2 - l2));
float com = -2.0f / 3.0f * (float)Math.Pow(r2 - l2, 1.5f) / area;
sc.X = p.X + normal.X * com;
sc.Y = p.Y + normal.Y * com;
return area;
}
}
}

View File

@@ -0,0 +1,266 @@
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// A line segment (edge) Shape. These can be connected in chains or loops
/// to other edge Shapes. The connectivity information is used to ensure
/// correct contact normals.
/// </summary>
public class EdgeShape : Shape
{
public bool HasVertex0, HasVertex3;
/// <summary>
/// Optional adjacent vertices. These are used for smooth collision.
/// </summary>
public Vector2 Vertex0;
/// <summary>
/// Optional adjacent vertices. These are used for smooth collision.
/// </summary>
public Vector2 Vertex3;
/// <summary>
/// Edge start vertex
/// </summary>
private Vector2 _vertex1;
/// <summary>
/// Edge end vertex
/// </summary>
private Vector2 _vertex2;
internal EdgeShape()
: base(0)
{
ShapeType = ShapeType.Edge;
_radius = Settings.PolygonRadius;
}
public EdgeShape(Vector2 start, Vector2 end)
: base(0)
{
ShapeType = ShapeType.Edge;
_radius = Settings.PolygonRadius;
Set(start, end);
}
public override int ChildCount
{
get { return 1; }
}
/// <summary>
/// These are the edge vertices
/// </summary>
public Vector2 Vertex1
{
get { return _vertex1; }
set
{
_vertex1 = value;
ComputeProperties();
}
}
/// <summary>
/// These are the edge vertices
/// </summary>
public Vector2 Vertex2
{
get { return _vertex2; }
set
{
_vertex2 = value;
ComputeProperties();
}
}
/// <summary>
/// Set this as an isolated edge.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
public void Set(Vector2 start, Vector2 end)
{
_vertex1 = start;
_vertex2 = end;
HasVertex0 = false;
HasVertex3 = false;
ComputeProperties();
}
public override Shape Clone()
{
EdgeShape edge = new EdgeShape();
edge._radius = _radius;
edge._density = _density;
edge.HasVertex0 = HasVertex0;
edge.HasVertex3 = HasVertex3;
edge.Vertex0 = Vertex0;
edge._vertex1 = _vertex1;
edge._vertex2 = _vertex2;
edge.Vertex3 = Vertex3;
edge.MassData = MassData;
return edge;
}
/// <summary>
/// Test a point for containment in this shape. This only works for convex shapes.
/// </summary>
/// <param name="transform">The shape world transform.</param>
/// <param name="point">a point in world coordinates.</param>
/// <returns>True if the point is inside the shape</returns>
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
return false;
}
/// <summary>
/// Cast a ray against a child shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="transform">The transform to be applied to the shape.</param>
/// <param name="childIndex">The child shape index.</param>
/// <returns>True if the ray-cast hits the shape</returns>
public override bool RayCast(out RayCastOutput output, ref RayCastInput input,
ref Transform transform, int childIndex)
{
// p = p1 + t * d
// v = v1 + s * e
// p1 + t * d = v1 + s * e
// s * e - t * d = p1 - v1
output = new RayCastOutput();
// Put the ray into the edge's frame of reference.
Vector2 p1 = MathUtils.MultiplyT(ref transform.R, input.Point1 - transform.Position);
Vector2 p2 = MathUtils.MultiplyT(ref transform.R, input.Point2 - transform.Position);
Vector2 d = p2 - p1;
Vector2 v1 = _vertex1;
Vector2 v2 = _vertex2;
Vector2 e = v2 - v1;
Vector2 normal = new Vector2(e.Y, -e.X);
normal.Normalize();
// q = p1 + t * d
// dot(normal, q - v1) = 0
// dot(normal, p1 - v1) + t * dot(normal, d) = 0
float numerator = Vector2.Dot(normal, v1 - p1);
float denominator = Vector2.Dot(normal, d);
if (denominator == 0.0f)
{
return false;
}
float t = numerator / denominator;
if (t < 0.0f || 1.0f < t)
{
return false;
}
Vector2 q = p1 + t * d;
// q = v1 + s * r
// s = dot(q - v1, r) / dot(r, r)
Vector2 r = v2 - v1;
float rr = Vector2.Dot(r, r);
if (rr == 0.0f)
{
return false;
}
float s = Vector2.Dot(q - v1, r) / rr;
if (s < 0.0f || 1.0f < s)
{
return false;
}
output.Fraction = t;
if (numerator > 0.0f)
{
output.Normal = -normal;
}
else
{
output.Normal = normal;
}
return true;
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
Vector2 v1 = MathUtils.Multiply(ref transform, _vertex1);
Vector2 v2 = MathUtils.Multiply(ref transform, _vertex2);
Vector2 lower = Vector2.Min(v1, v2);
Vector2 upper = Vector2.Max(v1, v2);
Vector2 r = new Vector2(Radius, Radius);
aabb.LowerBound = lower - r;
aabb.UpperBound = upper + r;
}
/// <summary>
/// Compute the mass properties of this shape using its dimensions and density.
/// The inertia tensor is computed about the local origin, not the centroid.
/// </summary>
public override void ComputeProperties()
{
MassData.Centroid = 0.5f * (_vertex1 + _vertex2);
}
public override float ComputeSubmergedArea(Vector2 normal, float offset, Transform xf, out Vector2 sc)
{
sc = Vector2.Zero;
return 0;
}
public bool CompareTo(EdgeShape shape)
{
return (HasVertex0 == shape.HasVertex0 &&
HasVertex3 == shape.HasVertex3 &&
Vertex0 == shape.Vertex0 &&
Vertex1 == shape.Vertex1 &&
Vertex2 == shape.Vertex2 &&
Vertex3 == shape.Vertex3);
}
}
}

View File

@@ -0,0 +1,188 @@
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// A loop Shape is a free form sequence of line segments that form a circular list.
/// The loop may cross upon itself, but this is not recommended for smooth collision.
/// The loop has double sided collision, so you can use inside and outside collision.
/// Therefore, you may use any winding order.
/// </summary>
public class LoopShape : Shape
{
private static EdgeShape _edgeShape = new EdgeShape();
/// <summary>
/// The vertices. These are not owned/freed by the loop Shape.
/// </summary>
public Vertices Vertices;
private LoopShape()
: base(0)
{
ShapeType = ShapeType.Loop;
_radius = Settings.PolygonRadius;
}
public LoopShape(Vertices vertices)
: base(0)
{
ShapeType = ShapeType.Loop;
_radius = Settings.PolygonRadius;
#pragma warning disable 162
if (Settings.ConserveMemory)
Vertices = vertices;
else
// Copy vertices.
Vertices = new Vertices(vertices);
#pragma warning restore 162
}
public override int ChildCount
{
get { return Vertices.Count; }
}
public override Shape Clone()
{
LoopShape loop = new LoopShape();
loop._density = _density;
loop._radius = _radius;
loop.Vertices = Vertices;
loop.MassData = MassData;
return loop;
}
/// <summary>
/// Get a child edge.
/// </summary>
/// <param name="edge">The edge.</param>
/// <param name="index">The index.</param>
public void GetChildEdge(ref EdgeShape edge, int index)
{
Debug.Assert(2 <= Vertices.Count);
Debug.Assert(0 <= index && index < Vertices.Count);
edge.ShapeType = ShapeType.Edge;
edge._radius = _radius;
edge.HasVertex0 = true;
edge.HasVertex3 = true;
int i0 = index - 1 >= 0 ? index - 1 : Vertices.Count - 1;
int i1 = index;
int i2 = index + 1 < Vertices.Count ? index + 1 : 0;
int i3 = index + 2;
while (i3 >= Vertices.Count)
{
i3 -= Vertices.Count;
}
edge.Vertex0 = Vertices[i0];
edge.Vertex1 = Vertices[i1];
edge.Vertex2 = Vertices[i2];
edge.Vertex3 = Vertices[i3];
}
/// <summary>
/// Test a point for containment in this shape. This only works for convex shapes.
/// </summary>
/// <param name="transform">The shape world transform.</param>
/// <param name="point">a point in world coordinates.</param>
/// <returns>True if the point is inside the shape</returns>
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
return false;
}
/// <summary>
/// Cast a ray against a child shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="transform">The transform to be applied to the shape.</param>
/// <param name="childIndex">The child shape index.</param>
/// <returns>True if the ray-cast hits the shape</returns>
public override bool RayCast(out RayCastOutput output, ref RayCastInput input,
ref Transform transform, int childIndex)
{
Debug.Assert(childIndex < Vertices.Count);
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == Vertices.Count)
{
i2 = 0;
}
_edgeShape.Vertex1 = Vertices[i1];
_edgeShape.Vertex2 = Vertices[i2];
return _edgeShape.RayCast(out output, ref input, ref transform, 0);
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
Debug.Assert(childIndex < Vertices.Count);
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == Vertices.Count)
{
i2 = 0;
}
Vector2 v1 = MathUtils.Multiply(ref transform, Vertices[i1]);
Vector2 v2 = MathUtils.Multiply(ref transform, Vertices[i2]);
aabb.LowerBound = Vector2.Min(v1, v2);
aabb.UpperBound = Vector2.Max(v1, v2);
}
/// <summary>
/// Chains have zero mass.
/// </summary>
public override void ComputeProperties()
{
//Does nothing. Loop shapes don't have properties.
}
public override float ComputeSubmergedArea(Vector2 normal, float offset, Transform xf, out Vector2 sc)
{
sc = Vector2.Zero;
return 0;
}
}
}

View File

@@ -0,0 +1,556 @@
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using FarseerPhysics.Common.Decomposition;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// Represents a simple non-selfintersecting convex polygon.
/// If you want to have concave polygons, you will have to use the <see cref="BayazitDecomposer"/> or the <see cref="EarclipDecomposer"/>
/// to decompose the concave polygon into 2 or more convex polygons.
/// </summary>
public class PolygonShape : Shape
{
public Vertices Normals;
public Vertices Vertices;
/// <summary>
/// Initializes a new instance of the <see cref="PolygonShape"/> class.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="density">The density.</param>
public PolygonShape(Vertices vertices, float density)
: base(density)
{
ShapeType = ShapeType.Polygon;
_radius = Settings.PolygonRadius;
Set(vertices);
}
public PolygonShape(float density)
: base(density)
{
ShapeType = ShapeType.Polygon;
_radius = Settings.PolygonRadius;
Normals = new Vertices();
Vertices = new Vertices();
}
internal PolygonShape()
: base(0)
{
ShapeType = ShapeType.Polygon;
_radius = Settings.PolygonRadius;
Normals = new Vertices();
Vertices = new Vertices();
}
public override int ChildCount
{
get { return 1; }
}
public override Shape Clone()
{
PolygonShape clone = new PolygonShape();
clone.ShapeType = ShapeType;
clone._radius = _radius;
clone._density = _density;
if (Settings.ConserveMemory)
{
#pragma warning disable 162
clone.Vertices = Vertices;
clone.Normals = Normals;
#pragma warning restore 162
}
else
{
clone.Vertices = new Vertices(Vertices);
clone.Normals = new Vertices(Normals);
}
clone.MassData = MassData;
return clone;
}
/// <summary>
/// Copy vertices. This assumes the vertices define a convex polygon.
/// It is assumed that the exterior is the the right of each edge.
/// </summary>
/// <param name="vertices">The vertices.</param>
public void Set(Vertices vertices)
{
Debug.Assert(vertices.Count >= 3 && vertices.Count <= Settings.MaxPolygonVertices);
#pragma warning disable 162
if (Settings.ConserveMemory)
Vertices = vertices;
else
// Copy vertices.
Vertices = new Vertices(vertices);
#pragma warning restore 162
Normals = new Vertices(vertices.Count);
// Compute normals. Ensure the edges have non-zero length.
for (int i = 0; i < vertices.Count; ++i)
{
int i1 = i;
int i2 = i + 1 < vertices.Count ? i + 1 : 0;
Vector2 edge = Vertices[i2] - Vertices[i1];
Debug.Assert(edge.LengthSquared() > Settings.Epsilon * Settings.Epsilon);
Vector2 temp = new Vector2(edge.Y, -edge.X);
temp.Normalize();
Normals.Add(temp);
}
#if DEBUG
// Ensure the polygon is convex and the interior
// is to the left of each edge.
for (int i = 0; i < Vertices.Count; ++i)
{
int i1 = i;
int i2 = i + 1 < Vertices.Count ? i + 1 : 0;
Vector2 edge = Vertices[i2] - Vertices[i1];
for (int j = 0; j < vertices.Count; ++j)
{
// Don't check vertices on the current edge.
if (j == i1 || j == i2)
{
continue;
}
Vector2 r = Vertices[j] - Vertices[i1];
// Your polygon is non-convex (it has an indentation) or
// has colinear edges.
float s = edge.X * r.Y - edge.Y * r.X;
Debug.Assert(s > 0.0f);
}
}
#endif
// Compute the polygon mass data
ComputeProperties();
}
/// <summary>
/// Compute the mass properties of this shape using its dimensions and density.
/// The inertia tensor is computed about the local origin, not the centroid.
/// </summary>
public override void ComputeProperties()
{
// Polygon mass, centroid, and inertia.
// Let rho be the polygon density in mass per unit area.
// Then:
// mass = rho * int(dA)
// centroid.X = (1/mass) * rho * int(x * dA)
// centroid.Y = (1/mass) * rho * int(y * dA)
// I = rho * int((x*x + y*y) * dA)
//
// We can compute these integrals by summing all the integrals
// for each triangle of the polygon. To evaluate the integral
// for a single triangle, we make a change of variables to
// the (u,v) coordinates of the triangle:
// x = x0 + e1x * u + e2x * v
// y = y0 + e1y * u + e2y * v
// where 0 <= u && 0 <= v && u + v <= 1.
//
// We integrate u from [0,1-v] and then v from [0,1].
// We also need to use the Jacobian of the transformation:
// D = cross(e1, e2)
//
// Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
//
// The rest of the derivation is handled by computer algebra.
Debug.Assert(Vertices.Count >= 3);
if (_density <= 0)
return;
Vector2 center = Vector2.Zero;
float area = 0.0f;
float I = 0.0f;
// pRef is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
Vector2 pRef = Vector2.Zero;
#if false
// This code would put the reference point inside the polygon.
for (int i = 0; i < count; ++i)
{
pRef += vs[i];
}
pRef *= 1.0f / count;
#endif
const float inv3 = 1.0f / 3.0f;
for (int i = 0; i < Vertices.Count; ++i)
{
// Triangle vertices.
Vector2 p1 = pRef;
Vector2 p2 = Vertices[i];
Vector2 p3 = i + 1 < Vertices.Count ? Vertices[i + 1] : Vertices[0];
Vector2 e1 = p2 - p1;
Vector2 e2 = p3 - p1;
float d;
MathUtils.Cross(ref e1, ref e2, out d);
float triangleArea = 0.5f * d;
area += triangleArea;
// Area weighted centroid
center += triangleArea * inv3 * (p1 + p2 + p3);
float px = p1.X, py = p1.Y;
float ex1 = e1.X, ey1 = e1.Y;
float ex2 = e2.X, ey2 = e2.Y;
float intx2 = inv3 * (0.25f * (ex1 * ex1 + ex2 * ex1 + ex2 * ex2) + (px * ex1 + px * ex2)) +
0.5f * px * px;
float inty2 = inv3 * (0.25f * (ey1 * ey1 + ey2 * ey1 + ey2 * ey2) + (py * ey1 + py * ey2)) +
0.5f * py * py;
I += d * (intx2 + inty2);
}
//The area is too small for the engine to handle.
Debug.Assert(area > Settings.Epsilon);
// We save the area
MassData.Area = area;
// Total mass
MassData.Mass = _density * area;
// Center of mass
center *= 1.0f / area;
MassData.Centroid = center;
// Inertia tensor relative to the local origin.
MassData.Inertia = _density * I;
}
/// <summary>
/// Build vertices to represent an axis-aligned box.
/// </summary>
/// <param name="halfWidth">The half-width.</param>
/// <param name="halfHeight">The half-height.</param>
public void SetAsBox(float halfWidth, float halfHeight)
{
Set(PolygonTools.CreateRectangle(halfWidth, halfHeight));
}
/// <summary>
/// Build vertices to represent an oriented box.
/// </summary>
/// <param name="halfWidth">The half-width..</param>
/// <param name="halfHeight">The half-height.</param>
/// <param name="center">The center of the box in local coordinates.</param>
/// <param name="angle">The rotation of the box in local coordinates.</param>
public void SetAsBox(float halfWidth, float halfHeight, Vector2 center, float angle)
{
Set(PolygonTools.CreateRectangle(halfWidth, halfHeight, center, angle));
}
/// <summary>
/// Test a point for containment in this shape. This only works for convex shapes.
/// </summary>
/// <param name="transform">The shape world transform.</param>
/// <param name="point">a point in world coordinates.</param>
/// <returns>True if the point is inside the shape</returns>
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
Vector2 pLocal = MathUtils.MultiplyT(ref transform.R, point - transform.Position);
for (int i = 0; i < Vertices.Count; ++i)
{
float dot = Vector2.Dot(Normals[i], pLocal - Vertices[i]);
if (dot > 0.0f)
{
return false;
}
}
return true;
}
/// <summary>
/// Cast a ray against a child shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="transform">The transform to be applied to the shape.</param>
/// <param name="childIndex">The child shape index.</param>
/// <returns>True if the ray-cast hits the shape</returns>
public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform,
int childIndex)
{
output = new RayCastOutput();
// Put the ray into the polygon's frame of reference.
Vector2 p1 = MathUtils.MultiplyT(ref transform.R, input.Point1 - transform.Position);
Vector2 p2 = MathUtils.MultiplyT(ref transform.R, input.Point2 - transform.Position);
Vector2 d = p2 - p1;
float lower = 0.0f, upper = input.MaxFraction;
int index = -1;
for (int i = 0; i < Vertices.Count; ++i)
{
// p = p1 + a * d
// dot(normal, p - v) = 0
// dot(normal, p1 - v) + a * dot(normal, d) = 0
float numerator = Vector2.Dot(Normals[i], Vertices[i] - p1);
float denominator = Vector2.Dot(Normals[i], d);
if (denominator == 0.0f)
{
if (numerator < 0.0f)
{
return false;
}
}
else
{
// Note: we want this predicate without division:
// lower < numerator / denominator, where denominator < 0
// Since denominator < 0, we have to flip the inequality:
// lower < numerator / denominator <==> denominator * lower > numerator.
if (denominator < 0.0f && numerator < lower * denominator)
{
// Increase lower.
// The segment enters this half-space.
lower = numerator / denominator;
index = i;
}
else if (denominator > 0.0f && numerator < upper * denominator)
{
// Decrease upper.
// The segment exits this half-space.
upper = numerator / denominator;
}
}
// The use of epsilon here causes the assert on lower to trip
// in some cases. Apparently the use of epsilon was to make edge
// shapes work, but now those are handled separately.
//if (upper < lower - b2_epsilon)
if (upper < lower)
{
return false;
}
}
Debug.Assert(0.0f <= lower && lower <= input.MaxFraction);
if (index >= 0)
{
output.Fraction = lower;
output.Normal = MathUtils.Multiply(ref transform.R, Normals[index]);
return true;
}
return false;
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
Vector2 lower = MathUtils.Multiply(ref transform, Vertices[0]);
Vector2 upper = lower;
for (int i = 1; i < Vertices.Count; ++i)
{
Vector2 v = MathUtils.Multiply(ref transform, Vertices[i]);
lower = Vector2.Min(lower, v);
upper = Vector2.Max(upper, v);
}
Vector2 r = new Vector2(Radius, Radius);
aabb.LowerBound = lower - r;
aabb.UpperBound = upper + r;
}
public bool CompareTo(PolygonShape shape)
{
if (Vertices.Count != shape.Vertices.Count)
return false;
for (int i = 0; i < Vertices.Count; i++)
{
if (Vertices[i] != shape.Vertices[i])
return false;
}
return (Radius == shape.Radius &&
MassData == shape.MassData);
}
public override float ComputeSubmergedArea(Vector2 normal, float offset, Transform xf, out Vector2 sc)
{
sc = Vector2.Zero;
//Transform plane into shape co-ordinates
Vector2 normalL = MathUtils.MultiplyT(ref xf.R, normal);
float offsetL = offset - Vector2.Dot(normal, xf.Position);
float[] depths = new float[Settings.MaxPolygonVertices];
int diveCount = 0;
int intoIndex = -1;
int outoIndex = -1;
bool lastSubmerged = false;
int i;
for (i = 0; i < Vertices.Count; i++)
{
depths[i] = Vector2.Dot(normalL, Vertices[i]) - offsetL;
bool isSubmerged = depths[i] < -Settings.Epsilon;
if (i > 0)
{
if (isSubmerged)
{
if (!lastSubmerged)
{
intoIndex = i - 1;
diveCount++;
}
}
else
{
if (lastSubmerged)
{
outoIndex = i - 1;
diveCount++;
}
}
}
lastSubmerged = isSubmerged;
}
switch (diveCount)
{
case 0:
if (lastSubmerged)
{
//Completely submerged
sc = MathUtils.Multiply(ref xf, MassData.Centroid);
return MassData.Mass / Density;
}
else
{
//Completely dry
return 0;
}
#pragma warning disable 162
break;
#pragma warning restore 162
case 1:
if (intoIndex == -1)
{
intoIndex = Vertices.Count - 1;
}
else
{
outoIndex = Vertices.Count - 1;
}
break;
}
int intoIndex2 = (intoIndex + 1) % Vertices.Count;
int outoIndex2 = (outoIndex + 1) % Vertices.Count;
float intoLambda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]);
float outoLambda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]);
Vector2 intoVec = new Vector2(
Vertices[intoIndex].X * (1 - intoLambda) + Vertices[intoIndex2].X * intoLambda,
Vertices[intoIndex].Y * (1 - intoLambda) + Vertices[intoIndex2].Y * intoLambda);
Vector2 outoVec = new Vector2(
Vertices[outoIndex].X * (1 - outoLambda) + Vertices[outoIndex2].X * outoLambda,
Vertices[outoIndex].Y * (1 - outoLambda) + Vertices[outoIndex2].Y * outoLambda);
//Initialize accumulator
float area = 0;
Vector2 center = new Vector2(0, 0);
Vector2 p2 = Vertices[intoIndex2];
Vector2 p3;
float k_inv3 = 1.0f / 3.0f;
//An awkward loop from intoIndex2+1 to outIndex2
i = intoIndex2;
while (i != outoIndex2)
{
i = (i + 1) % Vertices.Count;
if (i == outoIndex2)
p3 = outoVec;
else
p3 = Vertices[i];
//Add the triangle formed by intoVec,p2,p3
{
Vector2 e1 = p2 - intoVec;
Vector2 e2 = p3 - intoVec;
float D = MathUtils.Cross(e1, e2);
float triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * (intoVec + p2 + p3);
}
//
p2 = p3;
}
//Normalize and transform centroid
center *= 1.0f / area;
sc = MathUtils.Multiply(ref xf, center);
return area;
}
}
}

View File

@@ -0,0 +1,222 @@
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// This holds the mass data computed for a shape.
/// </summary>
public struct MassData : IEquatable<MassData>
{
/// <summary>
/// The area of the shape
/// </summary>
public float Area;
/// <summary>
/// The position of the shape's centroid relative to the shape's origin.
/// </summary>
public Vector2 Centroid;
/// <summary>
/// The rotational inertia of the shape about the local origin.
/// </summary>
public float Inertia;
/// <summary>
/// The mass of the shape, usually in kilograms.
/// </summary>
public float Mass;
#region IEquatable<MassData> Members
public bool Equals(MassData other)
{
return this == other;
}
#endregion
public static bool operator ==(MassData left, MassData right)
{
return (left.Area == right.Area && left.Mass == right.Mass && left.Centroid == right.Centroid &&
left.Inertia == right.Inertia);
}
public static bool operator !=(MassData left, MassData right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(MassData)) return false;
return Equals((MassData)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = Area.GetHashCode();
result = (result * 397) ^ Centroid.GetHashCode();
result = (result * 397) ^ Inertia.GetHashCode();
result = (result * 397) ^ Mass.GetHashCode();
return result;
}
}
}
public enum ShapeType
{
Unknown = -1,
Circle = 0,
Edge = 1,
Polygon = 2,
Loop = 3,
TypeCount = 4,
}
/// <summary>
/// A shape is used for collision detection. You can create a shape however you like.
/// Shapes used for simulation in World are created automatically when a Fixture
/// is created. Shapes may encapsulate a one or more child shapes.
/// </summary>
public abstract class Shape
{
private static int _shapeIdCounter;
public MassData MassData;
public int ShapeId;
internal float _density;
internal float _radius;
protected Shape(float density)
{
_density = density;
ShapeType = ShapeType.Unknown;
ShapeId = _shapeIdCounter++;
}
/// <summary>
/// Get the type of this shape.
/// </summary>
/// <value>The type of the shape.</value>
public ShapeType ShapeType { get; internal set; }
/// <summary>
/// Get the number of child primitives.
/// </summary>
/// <value></value>
public abstract int ChildCount { get; }
/// <summary>
/// Gets or sets the density.
/// </summary>
/// <value>The density.</value>
public float Density
{
get { return _density; }
set
{
_density = value;
ComputeProperties();
}
}
/// <summary>
/// Radius of the Shape
/// </summary>
public float Radius
{
get { return _radius; }
set
{
_radius = value;
ComputeProperties();
}
}
/// <summary>
/// Clone the concrete shape
/// </summary>
/// <returns>A clone of the shape</returns>
public abstract Shape Clone();
/// <summary>
/// Test a point for containment in this shape. This only works for convex shapes.
/// </summary>
/// <param name="transform">The shape world transform.</param>
/// <param name="point">a point in world coordinates.</param>
/// <returns>True if the point is inside the shape</returns>
public abstract bool TestPoint(ref Transform transform, ref Vector2 point);
/// <summary>
/// Cast a ray against a child shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="transform">The transform to be applied to the shape.</param>
/// <param name="childIndex">The child shape index.</param>
/// <returns>True if the ray-cast hits the shape</returns>
public abstract bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform,
int childIndex);
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public abstract void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex);
/// <summary>
/// Compute the mass properties of this shape using its dimensions and density.
/// The inertia tensor is computed about the local origin, not the centroid.
/// </summary>
public abstract void ComputeProperties();
public bool CompareTo(Shape shape)
{
if (shape is PolygonShape && this is PolygonShape)
return ((PolygonShape)this).CompareTo((PolygonShape)shape);
if (shape is CircleShape && this is CircleShape)
return ((CircleShape)this).CompareTo((CircleShape)shape);
if (shape is EdgeShape && this is EdgeShape)
return ((EdgeShape)this).CompareTo((EdgeShape)shape);
return false;
}
public abstract float ComputeSubmergedArea(Vector2 normal, float offset, Transform xf, out Vector2 sc);
}
}