Fixture.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /*
  2. * Farseer Physics Engine based on Box2D.XNA port:
  3. * Copyright (c) 2010 Ian Qvist
  4. *
  5. * Box2D.XNA port of Box2D:
  6. * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
  7. *
  8. * Original source Box2D:
  9. * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
  10. *
  11. * This software is provided 'as-is', without any express or implied
  12. * warranty. In no event will the authors be held liable for any damages
  13. * arising from the use of this software.
  14. * Permission is granted to anyone to use this software for any purpose,
  15. * including commercial applications, and to alter it and redistribute it
  16. * freely, subject to the following restrictions:
  17. * 1. The origin of this software must not be misrepresented; you must not
  18. * claim that you wrote the original software. If you use this software
  19. * in a product, an acknowledgment in the product documentation would be
  20. * appreciated but is not required.
  21. * 2. Altered source versions must be plainly marked as such, and must not be
  22. * misrepresented as being the original software.
  23. * 3. This notice may not be removed or altered from any source distribution.
  24. */
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Diagnostics;
  28. using FarseerPhysics.Collision;
  29. using FarseerPhysics.Collision.Shapes;
  30. using FarseerPhysics.Common;
  31. using FarseerPhysics.Dynamics.Contacts;
  32. using Microsoft.Xna.Framework;
  33. namespace FarseerPhysics.Dynamics
  34. {
  35. [Flags]
  36. public enum Category
  37. {
  38. None = 0,
  39. All = int.MaxValue,
  40. Cat1 = 1,
  41. Cat2 = 2,
  42. Cat3 = 4,
  43. Cat4 = 8,
  44. Cat5 = 16,
  45. Cat6 = 32,
  46. Cat7 = 64,
  47. Cat8 = 128,
  48. Cat9 = 256,
  49. Cat10 = 512,
  50. Cat11 = 1024,
  51. Cat12 = 2048,
  52. Cat13 = 4096,
  53. Cat14 = 8192,
  54. Cat15 = 16384,
  55. Cat16 = 32768,
  56. Cat17 = 65536,
  57. Cat18 = 131072,
  58. Cat19 = 262144,
  59. Cat20 = 524288,
  60. Cat21 = 1048576,
  61. Cat22 = 2097152,
  62. Cat23 = 4194304,
  63. Cat24 = 8388608,
  64. Cat25 = 16777216,
  65. Cat26 = 33554432,
  66. Cat27 = 67108864,
  67. Cat28 = 134217728,
  68. Cat29 = 268435456,
  69. Cat30 = 536870912,
  70. Cat31 = 1073741824
  71. }
  72. /// <summary>
  73. /// This proxy is used internally to connect fixtures to the broad-phase.
  74. /// </summary>
  75. public struct FixtureProxy
  76. {
  77. public AABB AABB;
  78. public int ChildIndex;
  79. public Fixture Fixture;
  80. public int ProxyId;
  81. }
  82. /// <summary>
  83. /// A fixture is used to attach a Shape to a body for collision detection. A fixture
  84. /// inherits its transform from its parent. Fixtures hold additional non-geometric data
  85. /// such as friction, collision filters, etc.
  86. /// Fixtures are created via Body.CreateFixture.
  87. /// Warning: You cannot reuse fixtures.
  88. /// </summary>
  89. public class Fixture : IDisposable
  90. {
  91. private static int _fixtureIdCounter;
  92. /// <summary>
  93. /// Fires after two shapes has collided and are solved. This gives you a chance to get the impact force.
  94. /// </summary>
  95. public AfterCollisionEventHandler AfterCollision;
  96. /// <summary>
  97. /// Fires when two fixtures are close to each other.
  98. /// Due to how the broadphase works, this can be quite inaccurate as shapes are approximated using AABBs.
  99. /// </summary>
  100. public BeforeCollisionEventHandler BeforeCollision;
  101. /// <summary>
  102. /// Fires when two shapes collide and a contact is created between them.
  103. /// Note that the first fixture argument is always the fixture that the delegate is subscribed to.
  104. /// </summary>
  105. public OnCollisionEventHandler OnCollision;
  106. /// <summary>
  107. /// Fires when two shapes separate and a contact is removed between them.
  108. /// Note that the first fixture argument is always the fixture that the delegate is subscribed to.
  109. /// </summary>
  110. public OnSeparationEventHandler OnSeparation;
  111. public FixtureProxy[] Proxies;
  112. public int ProxyCount;
  113. internal Category _collidesWith;
  114. internal Category _collisionCategories;
  115. internal short _collisionGroup;
  116. internal Dictionary<int, bool> _collisionIgnores;
  117. private float _friction;
  118. private float _restitution;
  119. internal Fixture()
  120. {
  121. }
  122. public Fixture(Body body, Shape shape)
  123. : this(body, shape, null)
  124. {
  125. }
  126. public Fixture(Body body, Shape shape, object userData)
  127. {
  128. if (Settings.UseFPECollisionCategories)
  129. _collisionCategories = Category.All;
  130. else
  131. _collisionCategories = Category.Cat1;
  132. _collidesWith = Category.All;
  133. _collisionGroup = 0;
  134. //Fixture defaults
  135. Friction = 0.2f;
  136. Restitution = 0;
  137. IsSensor = false;
  138. Body = body;
  139. UserData = userData;
  140. if (Settings.ConserveMemory)
  141. Shape = shape;
  142. else
  143. Shape = shape.Clone();
  144. RegisterFixture();
  145. }
  146. /// <summary>
  147. /// Defaults to 0
  148. ///
  149. /// If Settings.UseFPECollisionCategories is set to false:
  150. /// Collision groups allow a certain group of objects to never collide (negative)
  151. /// or always collide (positive). Zero means no collision group. Non-zero group
  152. /// filtering always wins against the mask bits.
  153. ///
  154. /// If Settings.UseFPECollisionCategories is set to true:
  155. /// If 2 fixtures are in the same collision group, they will not collide.
  156. /// </summary>
  157. public short CollisionGroup
  158. {
  159. set
  160. {
  161. if (_collisionGroup == value)
  162. return;
  163. _collisionGroup = value;
  164. Refilter();
  165. }
  166. get { return _collisionGroup; }
  167. }
  168. /// <summary>
  169. /// Defaults to Category.All
  170. ///
  171. /// The collision mask bits. This states the categories that this
  172. /// fixture would accept for collision.
  173. /// Use Settings.UseFPECollisionCategories to change the behavior.
  174. /// </summary>
  175. public Category CollidesWith
  176. {
  177. get { return _collidesWith; }
  178. set
  179. {
  180. if (_collidesWith == value)
  181. return;
  182. _collidesWith = value;
  183. Refilter();
  184. }
  185. }
  186. /// <summary>
  187. /// The collision categories this fixture is a part of.
  188. ///
  189. /// If Settings.UseFPECollisionCategories is set to false:
  190. /// Defaults to Category.Cat1
  191. ///
  192. /// If Settings.UseFPECollisionCategories is set to true:
  193. /// Defaults to Category.All
  194. /// </summary>
  195. public Category CollisionCategories
  196. {
  197. get { return _collisionCategories; }
  198. set
  199. {
  200. if (_collisionCategories == value)
  201. return;
  202. _collisionCategories = value;
  203. Refilter();
  204. }
  205. }
  206. /// <summary>
  207. /// Get the type of the child Shape. You can use this to down cast to the concrete Shape.
  208. /// </summary>
  209. /// <value>The type of the shape.</value>
  210. public ShapeType ShapeType
  211. {
  212. get { return Shape.ShapeType; }
  213. }
  214. /// <summary>
  215. /// Get the child Shape. You can modify the child Shape, however you should not change the
  216. /// number of vertices because this will crash some collision caching mechanisms.
  217. /// </summary>
  218. /// <value>The shape.</value>
  219. public Shape Shape { get; internal set; }
  220. /// <summary>
  221. /// Gets or sets a value indicating whether this fixture is a sensor.
  222. /// </summary>
  223. /// <value><c>true</c> if this instance is a sensor; otherwise, <c>false</c>.</value>
  224. public bool IsSensor { get; set; }
  225. /// <summary>
  226. /// Get the parent body of this fixture. This is null if the fixture is not attached.
  227. /// </summary>
  228. /// <value>The body.</value>
  229. public Body Body { get; internal set; }
  230. /// <summary>
  231. /// Set the user data. Use this to store your application specific data.
  232. /// </summary>
  233. /// <value>The user data.</value>
  234. public object UserData { get; set; }
  235. /// <summary>
  236. /// Get or set the coefficient of friction.
  237. /// </summary>
  238. /// <value>The friction.</value>
  239. public float Friction
  240. {
  241. get { return _friction; }
  242. set
  243. {
  244. Debug.Assert(!float.IsNaN(value));
  245. _friction = value;
  246. }
  247. }
  248. /// <summary>
  249. /// Get or set the coefficient of restitution.
  250. /// </summary>
  251. /// <value>The restitution.</value>
  252. public float Restitution
  253. {
  254. get { return _restitution; }
  255. set
  256. {
  257. Debug.Assert(!float.IsNaN(value));
  258. _restitution = value;
  259. }
  260. }
  261. /// <summary>
  262. /// Gets a unique ID for this fixture.
  263. /// </summary>
  264. /// <value>The fixture id.</value>
  265. public int FixtureId { get; private set; }
  266. #region IDisposable Members
  267. public bool IsDisposed { get; set; }
  268. public void Dispose()
  269. {
  270. if (!IsDisposed)
  271. {
  272. Body.DestroyFixture(this);
  273. IsDisposed = true;
  274. GC.SuppressFinalize(this);
  275. }
  276. }
  277. #endregion
  278. /// <summary>
  279. /// Restores collisions between this fixture and the provided fixture.
  280. /// </summary>
  281. /// <param name="fixture">The fixture.</param>
  282. public void RestoreCollisionWith(Fixture fixture)
  283. {
  284. if (_collisionIgnores == null)
  285. return;
  286. if (_collisionIgnores.ContainsKey(fixture.FixtureId))
  287. {
  288. _collisionIgnores[fixture.FixtureId] = false;
  289. Refilter();
  290. }
  291. }
  292. /// <summary>
  293. /// Ignores collisions between this fixture and the provided fixture.
  294. /// </summary>
  295. /// <param name="fixture">The fixture.</param>
  296. public void IgnoreCollisionWith(Fixture fixture)
  297. {
  298. if (_collisionIgnores == null)
  299. _collisionIgnores = new Dictionary<int, bool>();
  300. if (_collisionIgnores.ContainsKey(fixture.FixtureId))
  301. _collisionIgnores[fixture.FixtureId] = true;
  302. else
  303. _collisionIgnores.Add(fixture.FixtureId, true);
  304. Refilter();
  305. }
  306. /// <summary>
  307. /// Determines whether collisions are ignored between this fixture and the provided fixture.
  308. /// </summary>
  309. /// <param name="fixture">The fixture.</param>
  310. /// <returns>
  311. /// <c>true</c> if the fixture is ignored; otherwise, <c>false</c>.
  312. /// </returns>
  313. public bool IsFixtureIgnored(Fixture fixture)
  314. {
  315. if (_collisionIgnores == null)
  316. return false;
  317. if (_collisionIgnores.ContainsKey(fixture.FixtureId))
  318. return _collisionIgnores[fixture.FixtureId];
  319. return false;
  320. }
  321. /// <summary>
  322. /// Contacts are persistant and will keep being persistant unless they are
  323. /// flagged for filtering.
  324. /// This methods flags all contacts associated with the body for filtering.
  325. /// </summary>
  326. internal void Refilter()
  327. {
  328. // Flag associated contacts for filtering.
  329. ContactEdge edge = Body.ContactList;
  330. while (edge != null)
  331. {
  332. Contact contact = edge.Contact;
  333. Fixture fixtureA = contact.FixtureA;
  334. Fixture fixtureB = contact.FixtureB;
  335. if (fixtureA == this || fixtureB == this)
  336. {
  337. contact.FlagForFiltering();
  338. }
  339. edge = edge.Next;
  340. }
  341. World world = Body.World;
  342. if (world == null)
  343. {
  344. return;
  345. }
  346. // Touch each proxy so that new pairs may be created
  347. IBroadPhase broadPhase = world.ContactManager.BroadPhase;
  348. for (int i = 0; i < ProxyCount; ++i)
  349. {
  350. broadPhase.TouchProxy(Proxies[i].ProxyId);
  351. }
  352. }
  353. private void RegisterFixture()
  354. {
  355. // Reserve proxy space
  356. Proxies = new FixtureProxy[Shape.ChildCount];
  357. ProxyCount = 0;
  358. FixtureId = _fixtureIdCounter++;
  359. if ((Body.Flags & BodyFlags.Enabled) == BodyFlags.Enabled)
  360. {
  361. IBroadPhase broadPhase = Body.World.ContactManager.BroadPhase;
  362. CreateProxies(broadPhase, ref Body.Xf);
  363. }
  364. Body.FixtureList.Add(this);
  365. // Adjust mass properties if needed.
  366. if (Shape._density > 0.0f)
  367. {
  368. Body.ResetMassData();
  369. }
  370. // Let the world know we have a new fixture. This will cause new contacts
  371. // to be created at the beginning of the next time step.
  372. Body.World.Flags |= WorldFlags.NewFixture;
  373. if (Body.World.FixtureAdded != null)
  374. {
  375. Body.World.FixtureAdded(this);
  376. }
  377. }
  378. /// <summary>
  379. /// Test a point for containment in this fixture.
  380. /// </summary>
  381. /// <param name="point">A point in world coordinates.</param>
  382. /// <returns></returns>
  383. public bool TestPoint(ref Vector2 point)
  384. {
  385. return Shape.TestPoint(ref Body.Xf, ref point);
  386. }
  387. /// <summary>
  388. /// Cast a ray against this Shape.
  389. /// </summary>
  390. /// <param name="output">The ray-cast results.</param>
  391. /// <param name="input">The ray-cast input parameters.</param>
  392. /// <param name="childIndex">Index of the child.</param>
  393. /// <returns></returns>
  394. public bool RayCast(out RayCastOutput output, ref RayCastInput input, int childIndex)
  395. {
  396. return Shape.RayCast(out output, ref input, ref Body.Xf, childIndex);
  397. }
  398. /// <summary>
  399. /// Get the fixture's AABB. This AABB may be enlarge and/or stale.
  400. /// If you need a more accurate AABB, compute it using the Shape and
  401. /// the body transform.
  402. /// </summary>
  403. /// <param name="aabb">The aabb.</param>
  404. /// <param name="childIndex">Index of the child.</param>
  405. public void GetAABB(out AABB aabb, int childIndex)
  406. {
  407. Debug.Assert(0 <= childIndex && childIndex < ProxyCount);
  408. aabb = Proxies[childIndex].AABB;
  409. }
  410. public Fixture Clone(Body body)
  411. {
  412. Fixture fixture = new Fixture();
  413. fixture.Body = body;
  414. if (Settings.ConserveMemory)
  415. fixture.Shape = Shape;
  416. else
  417. fixture.Shape = Shape.Clone();
  418. fixture.UserData = UserData;
  419. fixture.Restitution = Restitution;
  420. fixture.Friction = Friction;
  421. fixture.IsSensor = IsSensor;
  422. fixture._collisionGroup = CollisionGroup;
  423. fixture._collisionCategories = CollisionCategories;
  424. fixture._collidesWith = CollidesWith;
  425. if (_collisionIgnores != null)
  426. {
  427. fixture._collisionIgnores = new Dictionary<int, bool>();
  428. foreach (KeyValuePair<int, bool> pair in _collisionIgnores)
  429. {
  430. fixture._collisionIgnores.Add(pair.Key, pair.Value);
  431. }
  432. }
  433. fixture.RegisterFixture();
  434. return fixture;
  435. }
  436. public Fixture DeepClone()
  437. {
  438. Fixture fix = Clone(Body.Clone());
  439. return fix;
  440. }
  441. internal void Destroy()
  442. {
  443. // The proxies must be destroyed before calling this.
  444. Debug.Assert(ProxyCount == 0);
  445. // Free the proxy array.
  446. Proxies = null;
  447. Shape = null;
  448. BeforeCollision = null;
  449. OnCollision = null;
  450. OnSeparation = null;
  451. AfterCollision = null;
  452. if (Body.World.FixtureRemoved != null)
  453. {
  454. Body.World.FixtureRemoved(this);
  455. }
  456. Body.World.FixtureAdded = null;
  457. Body.World.FixtureRemoved = null;
  458. OnSeparation = null;
  459. OnCollision = null;
  460. }
  461. // These support body activation/deactivation.
  462. internal void CreateProxies(IBroadPhase broadPhase, ref Transform xf)
  463. {
  464. Debug.Assert(ProxyCount == 0);
  465. // Create proxies in the broad-phase.
  466. ProxyCount = Shape.ChildCount;
  467. for (int i = 0; i < ProxyCount; ++i)
  468. {
  469. FixtureProxy proxy = new FixtureProxy();
  470. Shape.ComputeAABB(out proxy.AABB, ref xf, i);
  471. proxy.Fixture = this;
  472. proxy.ChildIndex = i;
  473. proxy.ProxyId = broadPhase.AddProxy(ref proxy);
  474. Proxies[i] = proxy;
  475. }
  476. }
  477. internal void DestroyProxies(IBroadPhase broadPhase)
  478. {
  479. // Destroy proxies in the broad-phase.
  480. for (int i = 0; i < ProxyCount; ++i)
  481. {
  482. broadPhase.RemoveProxy(Proxies[i].ProxyId);
  483. Proxies[i].ProxyId = -1;
  484. }
  485. ProxyCount = 0;
  486. }
  487. internal void Synchronize(IBroadPhase broadPhase, ref Transform transform1, ref Transform transform2)
  488. {
  489. if (ProxyCount == 0)
  490. {
  491. return;
  492. }
  493. for (int i = 0; i < ProxyCount; ++i)
  494. {
  495. FixtureProxy proxy = Proxies[i];
  496. // Compute an AABB that covers the swept Shape (may miss some rotation effect).
  497. AABB aabb1, aabb2;
  498. Shape.ComputeAABB(out aabb1, ref transform1, proxy.ChildIndex);
  499. Shape.ComputeAABB(out aabb2, ref transform2, proxy.ChildIndex);
  500. proxy.AABB.Combine(ref aabb1, ref aabb2);
  501. Vector2 displacement = transform2.Position - transform1.Position;
  502. broadPhase.MoveProxy(proxy.ProxyId, ref proxy.AABB, displacement);
  503. }
  504. }
  505. internal bool CompareTo(Fixture fixture)
  506. {
  507. return (
  508. CollidesWith == fixture.CollidesWith &&
  509. CollisionCategories == fixture.CollisionCategories &&
  510. CollisionGroup == fixture.CollisionGroup &&
  511. Friction == fixture.Friction &&
  512. IsSensor == fixture.IsSensor &&
  513. Restitution == fixture.Restitution &&
  514. Shape.CompareTo(fixture.Shape) &&
  515. UserData == fixture.UserData);
  516. }
  517. }
  518. }