Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Initial commit

  • Loading branch information...
commit cc9570e968013932316fb211f94fe90dc9705d71 0 parents
Jonas Wagner authored
Showing with 29,881 additions and 0 deletions.
  1. +1 −0  README
  2. +347 −0 box2d.js
  3. +2 −0  build.sh
  4. +195 −0 changes.patch
  5. +232 −0 convert.py
  6. +217 −0 engine.js
  7. +5 −0 extend.js
  8. +33 −0 flash/Box2D/Collision/ClipVertex.as
  9. +69 −0 flash/Box2D/Collision/Features.as
  10. +40 −0 flash/Box2D/Collision/Shapes/b2CircleDef.as
  11. +190 −0 flash/Box2D/Collision/Shapes/b2CircleShape.as
  12. +50 −0 flash/Box2D/Collision/Shapes/b2FilterData.as
  13. +37 −0 flash/Box2D/Collision/Shapes/b2MassData.as
  14. +94 −0 flash/Box2D/Collision/Shapes/b2PolygonDef.as
  15. +700 −0 flash/Box2D/Collision/Shapes/b2PolygonShape.as
  16. +329 −0 flash/Box2D/Collision/Shapes/b2Shape.as
  17. +56 −0 flash/Box2D/Collision/Shapes/b2ShapeDef.as
  18. +42 −0 flash/Box2D/Collision/b2AABB.as
  19. +45 −0 flash/Box2D/Collision/b2Bound.as
  20. +28 −0 flash/Box2D/Collision/b2BoundValues.as
  21. +987 −0 flash/Box2D/Collision/b2BroadPhase.as
  22. +28 −0 flash/Box2D/Collision/b2BufferedPair.as
  23. +756 −0 flash/Box2D/Collision/b2Collision.as
  24. +53 −0 flash/Box2D/Collision/b2ContactID.as
  25. +40 −0 flash/Box2D/Collision/b2ContactPoint.as
  26. +548 −0 flash/Box2D/Collision/b2Distance.as
  27. +55 −0 flash/Box2D/Collision/b2Manifold.as
  28. +56 −0 flash/Box2D/Collision/b2ManifoldPoint.as
  29. +32 −0 flash/Box2D/Collision/b2OBB.as
  30. +64 −0 flash/Box2D/Collision/b2Pair.as
  31. +35 −0 flash/Box2D/Collision/b2PairCallback.as
  32. +406 −0 flash/Box2D/Collision/b2PairManager.as
  33. +41 −0 flash/Box2D/Collision/b2Point.as
  34. +37 −0 flash/Box2D/Collision/b2Proxy.as
  35. +103 −0 flash/Box2D/Collision/b2Segment.as
  36. +155 −0 flash/Box2D/Collision/b2TimeOfImpact.as
  37. +134 −0 flash/Box2D/Common/Math/b2Mat22.as
  38. +265 −0 flash/Box2D/Common/Math/b2Math.as
  39. +79 −0 flash/Box2D/Common/Math/b2Sweep.as
  40. +140 −0 flash/Box2D/Common/Math/b2Vec2.as
  41. +67 −0 flash/Box2D/Common/Math/b2XForm.as
  42. +67 −0 flash/Box2D/Common/b2Color.as
  43. +107 −0 flash/Box2D/Common/b2Settings.as
  44. +141 −0 flash/Box2D/Dynamics/Contacts/b2CircleContact.as
  45. +259 −0 flash/Box2D/Dynamics/Contacts/b2Contact.as
  46. +49 −0 flash/Box2D/Dynamics/Contacts/b2ContactConstraint.as
  47. +42 −0 flash/Box2D/Dynamics/Contacts/b2ContactConstraintPoint.as
  48. +40 −0 flash/Box2D/Dynamics/Contacts/b2ContactEdge.as
  49. +31 −0 flash/Box2D/Dynamics/Contacts/b2ContactRegister.as
  50. +38 −0 flash/Box2D/Dynamics/Contacts/b2ContactResult.as
  51. +483 −0 flash/Box2D/Dynamics/Contacts/b2ContactSolver.as
  52. +33 −0 flash/Box2D/Dynamics/Contacts/b2NullContact.as
  53. +182 −0 flash/Box2D/Dynamics/Contacts/b2PolyAndCircleContact.as
  54. +181 −0 flash/Box2D/Dynamics/Contacts/b2PolygonContact.as
  55. +313 −0 flash/Box2D/Dynamics/Joints/b2DistanceJoint.as
  56. +77 −0 flash/Box2D/Dynamics/Joints/b2DistanceJointDef.as
  57. +330 −0 flash/Box2D/Dynamics/Joints/b2GearJoint.as
  58. +49 −0 flash/Box2D/Dynamics/Joints/b2GearJointDef.as
  59. +48 −0 flash/Box2D/Dynamics/Joints/b2Jacobian.as
  60. +220 −0 flash/Box2D/Dynamics/Joints/b2Joint.as
  61. +52 −0 flash/Box2D/Dynamics/Joints/b2JointDef.as
  62. +42 −0 flash/Box2D/Dynamics/Joints/b2JointEdge.as
  63. +227 −0 flash/Box2D/Dynamics/Joints/b2MouseJoint.as
  64. +53 −0 flash/Box2D/Dynamics/Joints/b2MouseJointDef.as
  65. +701 −0 flash/Box2D/Dynamics/Joints/b2PrismaticJoint.as
  66. +84 −0 flash/Box2D/Dynamics/Joints/b2PrismaticJointDef.as
  67. +655 −0 flash/Box2D/Dynamics/Joints/b2PulleyJoint.as
  68. +107 −0 flash/Box2D/Dynamics/Joints/b2PulleyJointDef.as
  69. +534 −0 flash/Box2D/Dynamics/Joints/b2RevoluteJoint.as
  70. +95 −0 flash/Box2D/Dynamics/Joints/b2RevoluteJointDef.as
  71. +857 −0 flash/Box2D/Dynamics/b2Body.as
  72. +95 −0 flash/Box2D/Dynamics/b2BodyDef.as
  73. +40 −0 flash/Box2D/Dynamics/b2BoundaryListener.as
  74. +54 −0 flash/Box2D/Dynamics/b2ContactFilter.as
  75. +59 −0 flash/Box2D/Dynamics/b2ContactListener.as
  76. +267 −0 flash/Box2D/Dynamics/b2ContactManager.as
  77. +158 −0 flash/Box2D/Dynamics/b2DebugDraw.as
  78. +46 −0 flash/Box2D/Dynamics/b2DestructionListener.as
  79. +477 −0 flash/Box2D/Dynamics/b2Island.as
  80. +33 −0 flash/Box2D/Dynamics/b2TimeStep.as
  81. +1,274 −0 flash/Box2D/Dynamics/b2World.as
  82. BIN  flash/Box2DFlashAS3_2.0.2_.zip
  83. +49 −0 flash/General/FRateLimiter.as
  84. +132 −0 flash/General/FpsCounter.as
  85. +392 −0 flash/General/Input.as
  86. +140 −0 flash/HelloWorld.as
  87. BIN  flash/HelloWorld.fla
  88. BIN  flash/HelloWorld.swf
  89. +17 −0 flash/License.txt
  90. +167 −0 flash/Main.as
  91. BIN  flash/PhysTest.fla
  92. BIN  flash/PhysTest.swf
  93. +65 −0 flash/ReadMe.txt
  94. +459 −0 flash/TestBed/Test.as
  95. +166 −0 flash/TestBed/TestBridge.as
  96. +93 −0 flash/TestBed/TestCCD.as
  97. +161 −0 flash/TestBed/TestCompound.as
  98. +252 −0 flash/TestBed/TestCrankGearsPulley.as
  99. +273 −0 flash/TestBed/TestRagdoll.as
  100. +106 −0 flash/TestBed/TestStack.as
  101. +254 −0 flash/TestBed/TestTheoJansen.as
  102. +15 −0 javascript/Box2D/Collision/ClipVertex.js
  103. +45 −0 javascript/Box2D/Collision/Features.js
  104. +45 −0 javascript/Box2D/Collision/Features_edited.js
  105. +20 −0 javascript/Box2D/Collision/Shapes/b2CircleDef.js
  106. +147 −0 javascript/Box2D/Collision/Shapes/b2CircleShape.js
  107. +23 −0 javascript/Box2D/Collision/Shapes/b2FilterData.js
  108. +15 −0 javascript/Box2D/Collision/Shapes/b2MassData.js
  109. +61 −0 javascript/Box2D/Collision/Shapes/b2PolygonDef.js
  110. +576 −0 javascript/Box2D/Collision/Shapes/b2PolygonShape.js
  111. +191 −0 javascript/Box2D/Collision/Shapes/b2Shape.js
  112. +20 −0 javascript/Box2D/Collision/Shapes/b2ShapeDef.js
  113. +23 −0 javascript/Box2D/Collision/b2AABB.js
  114. +29 −0 javascript/Box2D/Collision/b2Bound.js
  115. +15 −0 javascript/Box2D/Collision/b2BoundValues.js
  116. +909 −0 javascript/Box2D/Collision/b2BroadPhase.js
  117. +13 −0 javascript/Box2D/Collision/b2BufferedPair.js
  118. +689 −0 javascript/Box2D/Collision/b2Collision.js
  119. +36 −0 javascript/Box2D/Collision/b2ContactID.js
  120. +24 −0 javascript/Box2D/Collision/b2ContactPoint.js
  121. +36 −0 javascript/Box2D/Collision/b2Contact_modified.js
  122. +488 −0 javascript/Box2D/Collision/b2Distance.js
  123. +34 −0 javascript/Box2D/Collision/b2Manifold.js
  124. +36 −0 javascript/Box2D/Collision/b2ManifoldPoint.js
  125. +17 −0 javascript/Box2D/Collision/b2OBB.js
  126. +31 −0 javascript/Box2D/Collision/b2Pair.js
  127. +13 −0 javascript/Box2D/Collision/b2PairCallback.js
  128. +334 −0 javascript/Box2D/Collision/b2PairManager.js
  129. +19 −0 javascript/Box2D/Collision/b2Point.js
  130. +21 −0 javascript/Box2D/Collision/b2Proxy.js
  131. +68 −0 javascript/Box2D/Collision/b2Segment.js
  132. +126 −0 javascript/Box2D/Collision/b2TimeOfImpact.js
  133. +92 −0 javascript/Box2D/Common/Math/b2Mat22.js
  134. +150 −0 javascript/Box2D/Common/Math/b2Math.js
  135. +55 −0 javascript/Box2D/Common/Math/b2Sweep.js
  136. +83 −0 javascript/Box2D/Common/Math/b2Vec2.js
  137. +89 −0 javascript/Box2D/Common/Math/b2Vec2_edited.js
  138. +36 −0 javascript/Box2D/Common/Math/b2XForm.js
  139. +35 −0 javascript/Box2D/Common/b2Color.js
  140. +38 −0 javascript/Box2D/Common/b2Settings.js
  141. +118 −0 javascript/Box2D/Dynamics/Contacts/b2CircleContact.js
  142. +192 −0 javascript/Box2D/Dynamics/Contacts/b2Contact.js
  143. +27 −0 javascript/Box2D/Dynamics/Contacts/b2ContactConstraint.js
  144. +27 −0 javascript/Box2D/Dynamics/Contacts/b2ContactConstraintPoint.js
  145. +15 −0 javascript/Box2D/Dynamics/Contacts/b2ContactEdge.js
  146. +14 −0 javascript/Box2D/Dynamics/Contacts/b2ContactRegister.js
  147. +21 −0 javascript/Box2D/Dynamics/Contacts/b2ContactResult.js
  148. +454 −0 javascript/Box2D/Dynamics/Contacts/b2ContactSolver.js
  149. +16 −0 javascript/Box2D/Dynamics/Contacts/b2NullContact.js
  150. +155 −0 javascript/Box2D/Dynamics/Contacts/b2PolyAndCircleContact.js
  151. +155 −0 javascript/Box2D/Dynamics/Contacts/b2PolygonContact.js
  152. +268 −0 javascript/Box2D/Dynamics/Joints/b2DistanceJoint.js
  153. +40 −0 javascript/Box2D/Dynamics/Joints/b2DistanceJointDef.js
  154. +281 −0 javascript/Box2D/Dynamics/Joints/b2GearJoint.js
  155. +22 −0 javascript/Box2D/Dynamics/Joints/b2GearJointDef.js
  156. +30 −0 javascript/Box2D/Dynamics/Joints/b2Jacobian.js
  157. +127 −0 javascript/Box2D/Dynamics/Joints/b2Joint.js
  158. +22 −0 javascript/Box2D/Dynamics/Joints/b2JointDef.js
  159. +15 −0 javascript/Box2D/Dynamics/Joints/b2JointEdge.js
  160. +188 −0 javascript/Box2D/Dynamics/Joints/b2MouseJoint.js
  161. +26 −0 javascript/Box2D/Dynamics/Joints/b2MouseJointDef.js
  162. +625 −0 javascript/Box2D/Dynamics/Joints/b2PrismaticJoint.js
  163. +47 −0 javascript/Box2D/Dynamics/Joints/b2PrismaticJointDef.js
  164. +598 −0 javascript/Box2D/Dynamics/Joints/b2PulleyJoint.js
  165. +67 −0 javascript/Box2D/Dynamics/Joints/b2PulleyJointDef.js
  166. +465 −0 javascript/Box2D/Dynamics/Joints/b2RevoluteJoint.js
  167. +43 −0 javascript/Box2D/Dynamics/Joints/b2RevoluteJointDef.js
  168. +663 −0 javascript/Box2D/Dynamics/b2Body.js
  169. +36 −0 javascript/Box2D/Dynamics/b2BodyDef.js
  170. +12 −0 javascript/Box2D/Dynamics/b2BoundaryListener.js
  171. +24 −0 javascript/Box2D/Dynamics/b2ContactFilter.js
  172. +15 −0 javascript/Box2D/Dynamics/b2ContactListener.js
  173. +227 −0 javascript/Box2D/Dynamics/b2ContactManager.js
  174. +96 −0 javascript/Box2D/Dynamics/b2DebugDraw.js
  175. +13 −0 javascript/Box2D/Dynamics/b2DestructionListener.js
  176. +350 −0 javascript/Box2D/Dynamics/b2Island.js
  177. +17 −0 javascript/Box2D/Dynamics/b2TimeStep.js
  178. +1,126 −0 javascript/Box2D/Dynamics/b2World.js
  179. +217 −0 javascript/Box2D/engine.js
  180. +74 −0 load.html
  181. +9 −0 test.html
  182. +128 −0 test.js
1  README
@@ -0,0 +1 @@
+See http://29a.ch/2010/4/17/box2d-2-flash-ported-javascript
347 box2d.js
347 additions, 0 deletions not shown
2  build.sh
@@ -0,0 +1,2 @@
+#!/bin/sh
+java -jar compiler.jar --js extend.js --js javascript/Box2D/Common/b2Settings.js --js javascript/Box2D/Common/Math/b2Vec2.js --js javascript/Box2D/Collision/b2BufferedPair.js --js javascript/Box2D/Collision/b2AABB.js --js javascript/Box2D/Collision/b2Pair.js --js javascript/Box2D/Dynamics/b2TimeStep.js --js javascript/Box2D/Collision/b2Manifold.js --js javascript/Box2D/Collision/b2Point.js --js javascript/Box2D/Collision/b2Bound.js --js javascript/Box2D/Common/Math/b2Mat22.js --js javascript/Box2D/Dynamics/b2BoundaryListener.js --js javascript/Box2D/Collision/Shapes/b2MassData.js --js javascript/Box2D/Dynamics/Joints/b2JointEdge.js --js javascript/Box2D/Collision/b2Collision.js --js javascript/Box2D/Dynamics/b2ContactListener.js --js javascript/Box2D/Collision/b2PairCallback.js --js javascript/Box2D/Dynamics/Joints/b2JointDef.js --js javascript/Box2D/Collision/b2Proxy.js --js javascript/Box2D/Common/b2Color.js --js javascript/Box2D/Collision/Shapes/b2FilterData.js --js javascript/Box2D/Collision/b2PairManager.js --js javascript/Box2D/Dynamics/Contacts/b2ContactSolver.js --js javascript/Box2D/Collision/b2BoundValues.js --js javascript/Box2D/Collision/b2Segment.js --js javascript/Box2D/Collision/Features.js --js javascript/Box2D/Dynamics/Joints/b2MouseJointDef.js --js javascript/Box2D/Dynamics/Contacts/b2ContactConstraintPoint.js --js javascript/Box2D/Dynamics/Contacts/b2ContactRegister.js --js javascript/Box2D/Dynamics/b2DestructionListener.js --js javascript/Box2D/Dynamics/Joints/b2PulleyJointDef.js --js javascript/Box2D/Dynamics/Joints/b2Jacobian.js --js javascript/Box2D/Dynamics/b2DebugDraw.js --js javascript/Box2D/Dynamics/Contacts/b2ContactEdge.js --js javascript/Box2D/Common/Math/b2Sweep.js --js javascript/Box2D/Dynamics/Contacts/b2ContactConstraint.js --js javascript/Box2D/Collision/b2Distance.js --js javascript/Box2D/Collision/Shapes/b2Shape.js --js javascript/Box2D/Common/Math/b2XForm.js --js javascript/Box2D/Dynamics/Joints/b2DistanceJointDef.js --js javascript/Box2D/Collision/b2OBB.js --js javascript/Box2D/Dynamics/b2BodyDef.js --js javascript/Box2D/Dynamics/Joints/b2PrismaticJointDef.js --js javascript/Box2D/Collision/b2ContactID.js --js javascript/Box2D/Dynamics/Joints/b2RevoluteJointDef.js --js javascript/Box2D/Collision/Shapes/b2CircleShape.js --js javascript/Box2D/Dynamics/Joints/b2Joint.js --js javascript/Box2D/Dynamics/Joints/b2GearJoint.js --js javascript/Box2D/Dynamics/Joints/b2GearJointDef.js --js javascript/Box2D/Collision/b2BroadPhase.js --js javascript/Box2D/Collision/b2TimeOfImpact.js --js javascript/Box2D/Collision/Shapes/b2ShapeDef.js --js javascript/Box2D/Collision/Shapes/b2PolygonDef.js --js javascript/Box2D/Dynamics/Contacts/b2Contact.js --js javascript/Box2D/Dynamics/Joints/b2DistanceJoint.js --js javascript/Box2D/Dynamics/b2Body.js --js javascript/Box2D/Dynamics/b2ContactFilter.js --js javascript/Box2D/Collision/Shapes/b2PolygonShape.js --js javascript/Box2D/Dynamics/Contacts/b2ContactResult.js --js javascript/Box2D/Dynamics/b2Island.js --js javascript/Box2D/Collision/b2ManifoldPoint.js --js javascript/Box2D/Common/Math/b2Math.js --js javascript/Box2D/Collision/Shapes/b2CircleDef.js --js javascript/Box2D/Collision/b2ContactPoint.js --js javascript/Box2D/Dynamics/Contacts/b2PolygonContact.js --js javascript/Box2D/Dynamics/Joints/b2MouseJoint.js --js javascript/Box2D/Dynamics/Contacts/b2CircleContact.js --js javascript/Box2D/Dynamics/Joints/b2PulleyJoint.js --js javascript/Box2D/Dynamics/Joints/b2RevoluteJoint.js --js javascript/Box2D/Dynamics/Joints/b2PrismaticJoint.js --js javascript/Box2D/Collision/ClipVertex.js --js javascript/Box2D/Dynamics/Contacts/b2NullContact.js --js javascript/Box2D/Dynamics/Contacts/b2PolyAndCircleContact.js --js javascript/Box2D/Dynamics/b2ContactManager.js --js javascript/Box2D/Dynamics/b2World.js --js_output_file box2d.js
195 changes.patch
@@ -0,0 +1,195 @@
+diff -r 91f57f867c94 Box2D/Collision/Features.js
+--- a/Box2D/Collision/Features.js Sun Apr 18 20:55:05 2010 +0200
++++ b/Box2D/Collision/Features.js Sun Apr 18 21:00:19 2010 +0200
+@@ -2,6 +2,36 @@
+ this.__varz();
+ this.__constructor.apply(this, arguments);
+ }
++Features.prototype = {
++ get referenceEdge() {
++ return this._referenceEdge;
++ },
++ set referenceEdge(value) {
++ this._referenceEdge = value;
++ this._m_id._key = (this._m_id._key & 0xffffff00) | (this._referenceEdge & 0x000000ff);
++ },
++ get incidentEdge() {
++ return this._incidentEdge;
++ },
++ set incidentEdge(value) {
++ this._incidentEdge = value;
++ this._m_id._key = (this._m_id._key & 0xffff00ff) | ((this._incidentEdge << 8) & 0x0000ff00);
++ },
++ set incidentVertex(value) {
++ this._incidentVertex = value;
++ this._m_id._key = (this._m_id._key & 0xff00ffff) | ((this._incidentVertex << 16) & 0x00ff0000);
++ },
++ get incidentVertex() {
++ return this._incidentVertex;
++ },
++ set flip(value) {
++ this._flip = value;
++ this._m_id._key = (this._m_id._key & 0x00ffffff) | ((this._flip << 24) & 0xff000000);
++ },
++ get flip() {
++ return this._flip;
++ }
++}
+ Features.prototype.__constructor = function(){}
+ Features.prototype.__varz = function(){
+ }
+@@ -13,32 +43,3 @@
+ Features.prototype._incidentVertex = 0;
+ Features.prototype._flip = 0;
+ Features.prototype._m_id = null;
+-// methods
+-Features.prototype.set = function (value) {
+- this._referenceEdge = value;
+- this._m_id._key = (this._m_id._key & 0xffffff00) | (this._referenceEdge & 0x000000ff);
+- }
+-Features.prototype.get = function () {
+- return this._referenceEdge;
+- }
+-Features.prototype.set = function (value) {
+- this._incidentEdge = value;
+- this._m_id._key = (this._m_id._key & 0xffff00ff) | ((this._incidentEdge << 8) & 0x0000ff00);
+- }
+-Features.prototype.get = function () {
+- return this._incidentEdge;
+- }
+-Features.prototype.set = function (value) {
+- this._incidentVertex = value;
+- this._m_id._key = (this._m_id._key & 0xff00ffff) | ((this._incidentVertex << 16) & 0x00ff0000);
+- }
+-Features.prototype.get = function () {
+- return this._incidentVertex;
+- }
+-Features.prototype.set = function (value) {
+- this._flip = value;
+- this._m_id._key = (this._m_id._key & 0x00ffffff) | ((this._flip << 24) & 0xff000000);
+- }
+-Features.prototype.get = function () {
+- return this._flip;
+- }
+\ No newline at end of file
+diff -r 91f57f867c94 Box2D/Collision/Shapes/b2PolygonShape.js
+--- a/Box2D/Collision/Shapes/b2PolygonShape.js Sun Apr 18 20:55:05 2010 +0200
++++ b/Box2D/Collision/Shapes/b2PolygonShape.js Sun Apr 18 21:00:19 2010 +0200
+@@ -102,7 +102,6 @@
+ b2PolygonShape.ComputeCentroid = function (vs, count) {
+
+
+-
+ var c = new b2Vec2();
+ var area = 0.0;
+
+@@ -574,4 +573,4 @@
+
+ if (dX > this.m_sweepRadius) this.m_sweepRadius = dX;
+ }
+- }
+\ No newline at end of file
++ }
+diff -r 91f57f867c94 Box2D/Collision/b2ContactID.js
+--- a/Box2D/Collision/b2ContactID.js Sun Apr 18 20:55:05 2010 +0200
++++ b/Box2D/Collision/b2ContactID.js Sun Apr 18 21:00:19 2010 +0200
+@@ -2,12 +2,23 @@
+ this.__varz();
+ this.__constructor.apply(this, arguments);
+ }
++b2ContactID.prototype = {
++ get key() {
++ return this._key;
++ },
++ set key(value) {
++ this._key = value;
++ this.features._referenceEdge = this._key & 0x000000ff;
++ this.features._incidentEdge = ((this._key & 0x0000ff00) >> 8) & 0x000000ff;
++ this.features._incidentVertex = ((this._key & 0x00ff0000) >> 16) & 0x000000ff;
++ this.features._flip = ((this._key & 0xff000000) >> 24) & 0x000000ff;
++ }
++}
+ b2ContactID.prototype.__constructor = function () {
+ this.features._m_id = this;
+-
+- }
++}
+ b2ContactID.prototype.__varz = function(){
+-this.features = new Features();
++ this.features = new Features();
+ }
+ // static attributes
+ // static methods
+@@ -16,20 +27,10 @@
+ b2ContactID.prototype._key = 0;
+ // methods
+ b2ContactID.prototype.Set = function (id) {
+- key = id._key;
+- }
++ this.key = id._key;
++}
+ b2ContactID.prototype.Copy = function () {
+- var id = new b2ContactID();
+- id.key = key;
+- return id;
+- }
+-b2ContactID.prototype.get = function () {
+- return this._key;
+- }
+-b2ContactID.prototype.set = function (value) {
+- this._key = value;
+- this.features._referenceEdge = this._key & 0x000000ff;
+- this.features._incidentEdge = ((this._key & 0x0000ff00) >> 8) & 0x000000ff;
+- this.features._incidentVertex = ((this._key & 0x00ff0000) >> 16) & 0x000000ff;
+- this.features._flip = ((this._key & 0xff000000) >> 24) & 0x000000ff;
+- }
+\ No newline at end of file
++ var id = new b2ContactID();
++ id.key = this._key;
++ return id;
++}
+diff -r 91f57f867c94 Box2D/Common/Math/b2Vec2.js
+--- a/Box2D/Common/Math/b2Vec2.js Sun Apr 18 20:55:05 2010 +0200
++++ b/Box2D/Common/Math/b2Vec2.js Sun Apr 18 21:00:19 2010 +0200
+@@ -1,9 +1,7 @@
+-var b2Vec2 = function() {
+-this.__varz();
+-this.__constructor.apply(this, arguments);
+-}
+-b2Vec2.prototype.__constructor = function (x_, y_) {this.x=x_; this.y=y_;}
+-b2Vec2.prototype.__varz = function(){
++var b2Vec2 = function(x_, y_) {
++ if(arguments.length == 2) {
++ this.x=x_; this.y=y_;
++ }
+ }
+ // static attributes
+ // static methods
+@@ -11,8 +9,8 @@
+ return new b2Vec2(x_, y_);
+ }
+ // attributes
+-b2Vec2.prototype.x = null;
+-b2Vec2.prototype.y = null;
++b2Vec2.prototype.x = 0;
++b2Vec2.prototype.y = 0;
+ // methods
+ b2Vec2.prototype.SetZero = function () { this.x = 0.0; this.y = 0.0; }
+ b2Vec2.prototype.Set = function (x_, y_) {this.x=x_; this.y=y_;}
+@@ -82,4 +80,4 @@
+ }
+ b2Vec2.prototype.IsValid = function () {
+ return b2Math.b2IsValid(this.x) && b2Math.b2IsValid(this.y);
+- }
+\ No newline at end of file
++ }
+diff -r 91f57f867c94 Box2D/Common/b2Settings.js
+--- a/Box2D/Common/b2Settings.js Sun Apr 18 20:55:05 2010 +0200
++++ b/Box2D/Common/b2Settings.js Sun Apr 18 21:00:19 2010 +0200
+@@ -35,4 +35,4 @@
+ }
+ }
+ // attributes
+-// methods
+\ No newline at end of file
++// methods
232 convert.py
@@ -0,0 +1,232 @@
+import os
+from collections import namedtuple
+
+Klass = namedtuple("Klass", "name extends constructor varz funcs svars sfuncs")
+Var = namedtuple("Var", "name value")
+
+source = "flash/Box2D"
+destination = "javascript/Box2D"
+import re
+
+def readblock(code, start="{", end="}"):
+ i = 0
+ code = code[code.index(start):]
+ block = []
+ for c in code:
+ block.append(c)
+ if c == start:
+ i += 1
+ elif c == end:
+ i -= 1
+ if i == 0:
+ return "".join(block)
+
+def translate(klass):
+ lines = ["var %s = function() {" % klass.name]
+ if klass.extends:
+ lines.append("%s.prototype.__varz.call(this)" % klass.extends)
+ lines.append("this.__varz();")
+ lines.append("this.__constructor.apply(this, arguments);")
+ lines.append("}")
+ if klass.extends:
+ lines.append("extend(%s.prototype, %s.prototype)" % (klass.name, klass.extends));
+ lines.append("%s.prototype._super = function(){ %s.prototype.__constructor.apply(this, arguments) }" % (klass.name, klass.extends))
+ lines.append("%s.prototype.__constructor = %s" % klass.constructor)
+ lines.append("%s.prototype.__varz = function(){" % klass.name)
+ for name, value in klass.varz:
+ if not re.match("^\s*(\d+(\.\d+)?|null|true|false)\s*;\s*$", value):
+ lines.append("this.%s = %s" % (name, value))
+ lines.append("}")
+ lines.append("// static attributes")
+ for name, value in klass.svars:
+ lines.append("%s.%s = %s" % (klass.name, name, value))
+ lines.append("// static methods")
+ for name, value in klass.sfuncs:
+ lines.append("%s.%s = %s" % (klass.name, name, value))
+ lines.append("// attributes")
+ for name, value in klass.varz:
+ lines.append("%s.prototype.%s = %s" % (klass.name, name, value))
+ lines.append("// methods")
+ for name, value in klass.funcs:
+ lines.append("%s.prototype.%s = %s" % (klass.name, name, value))
+ code = "\n".join(lines)
+ # remove type annotations
+ code = re.sub(r"([^ ]+)[ ]+as[ ]+\w+", "\\1", code)
+ return code
+
+def parse(code):
+ # strip comments
+ code = re.sub("(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//.*)", "", code)
+ # ints and uints are initialized with 0 not null
+ code = re.sub("(var\s+\w+:u?int)\s*;", "\\1 = 0;", code)
+ # int/uint -> parseInt
+ code = re.sub("([^a-zA-Z0-9]+)int\(", "\\1parseInt(", code)
+ code = re.sub("([^a-zA-Z0-9]+)uint\(", "\\1parseInt(", code)
+ # super -> this._super
+ code = re.sub("([^a-zA-Z0-9]+)super\(", "\\1this._super(", code)
+ # const -> var
+ code = re.sub(r"\bconst\b", "var", code)
+ #remove type anotations
+ code = re.sub("(\w+):[ ]*(\w+|\\*)", "\\1", code)
+ ## remove override and virtual
+ code = code.replace("override", "").replace("virtual", "").replace("\r", "")
+ # hack ...
+ code = code.replace("var mid = ((low + high) / 2);", "var mid = Math.round((low + high) / 2);")
+ code = code.replace("static public", "staticpublik")
+ code = code.replace("static private", "staticprivat")
+ # hack for uints used in proxy
+ code = code.replace("& 0x0000ffff", "% 65535")
+ while " " in code:
+ # normalize whitespace
+ code = code.replace(" ", " ")
+ lines = code.split("\n")
+ klass = None
+ extends = None
+ # remove packages and imports
+ lines = [l for l in lines if not
+ l.startswith("package ") and not l.startswith("import ")]
+
+ code = "\n".join(lines)
+
+ # find class
+ i = code.index("public class ")
+ aux = code[i+len("public class "):]
+ i = min(aux.index(" "), aux.index("\n"), aux.index("{"))
+ klass = aux[:i].strip()
+ extends = None
+ if "extends " in aux:
+ if aux.index("extends ") < aux.index("{"):
+ aux = aux[aux.index("extends ")+len("extends "):]
+ extends = aux[:min(aux.index(" "), aux.index("{"))].strip()
+ code = readblock(aux[aux.index("{"):])
+ pubf = getfunctions(code, "public function ")
+ try:
+ constructor = next(x for x in pubf if x[0] == klass)
+ pubf.remove(constructor)
+ except StopIteration:
+ constructor = Var(klass, "function(){}")
+ privf = getfunctions(code, "private function ")
+ statf = getfunctions(code, "static function ") + getfunctions(code,
+ "staticpublik function ") + getfunctions(code, "staticprivat function ")
+ privvar = getvars(code, "private var ")
+ pubvar = getvars(code, "public var ")
+ statvar = getvars(code, "staticpublik var ") + getvars(code, "static var") + getvars(code, "staticprivat var")
+
+ return Klass(klass, extends, constructor, privvar+pubvar, privf+pubf, statvar, statf)
+
+def getvars(code, prefix):
+ varz = []
+ while prefix in code:
+ code = code[code.index(prefix)+len(prefix):]
+ i = min(code.index(";"), code.index("\n"))
+ if "=" in code and code.index("=") < i:
+ name, code = code.split("=", 1)
+ name = name.strip()
+ i = min(code.index(";"), code.index("\n"))
+ body = code[:i] + ";"
+ else:
+ name = code[:i]
+ body = " null;"
+ # support var foo, bar = x;
+ if "," in name:
+ for subname in name.split(","):
+ varz.append(Var(subname.strip(), body))
+ else:
+ varz.append(Var(name, body))
+ return varz
+
+def getfunctions(code, prefix):
+ functions = []
+ while prefix in code:
+ code = code[code.index(prefix)+len(prefix):]
+ i = min(code.index(" "), code.index("("))
+ name = code[:i]
+ args = readblock(code, "(", ")")
+ #remove default parameters
+ args = re.sub("=[^,)]+", "", args)
+ body = readblock(code)
+ functions.append(Var(name, "function %s %s" % (args, body)))
+ return functions
+
+classes = {}
+files = []
+for dirpath, dirnames, filenames in os.walk(source):
+ target = dirpath.replace(source, destination, 1)
+ for dirname in dirnames:
+ try:
+ os.mkdir(os.path.join(target, dirname))
+ except OSError:
+ pass
+ for filename in filenames:
+ if not filename.endswith(".as"):
+ continue
+ src = os.path.join(dirpath, filename)
+ code = open(src, "r").read()
+ dest = os.path.join(target, filename.replace(".as", ".js"))
+ print "parsing", src
+ klass = parse(code)
+ print "translating", src
+ code = translate(klass)
+ # klass, path, dependencies (empty)
+ deps = klass.extends and [klass.extends] or []
+ classes[klass.name] = (klass, code, dest, deps)
+
+def resolve(code, klass):
+ for name, value in klass.svars + klass.sfuncs:
+ code = re.sub("([^a-zA-Z0-9_.])(%s)([^a-zA-Z0-9_])" % name, "\\1" +
+ klass.name + ".\\2\\3", code)
+ for name, value in klass.varz + klass.funcs:
+ code = re.sub("([^a-zA-Z0-9_.])(%s)([^a-zA-Z0-9_])" % name, "\\1this.\\2\\3", code)
+
+ if klass.extends:
+ return resolve(code, classes[klass.extends][0])
+ return code
+
+
+# resolve references
+for name in classes:
+ klass, code, dest, deps = classes[name]
+ with open(dest, "w") as f:
+ f.write(resolve(code, klass))
+
+# build deps
+for klass in classes:
+ klass, code, dest, deps = classes[klass]
+ for name, value in klass.varz + klass.svars:
+ for klass2 in classes:
+ if klass2 == klass.name:
+ continue
+ if klass2 in value and not klass2 in deps:
+ deps.append(klass2)
+
+# randomly breaking circular dependencies
+def breakCircle(klass, root, visited):
+ visited.append(klass)
+ deps = classes[klass][3]
+ if root in deps:
+ deps.remove(root)
+ print "found circle", root, klass
+ return True
+ return any(breakCircle(d, root, visited) for d in deps if not d in visited)
+
+# breaking all the circles
+while any(breakCircle(klass, klass, []) for klass in classes):
+ pass
+
+while classes:
+ for name in classes.keys():
+ klass, code, dest, deps = classes[name]
+ deps = [d for d in deps if d in classes]
+ if len(deps) == 0:
+ files.append(dest)
+ del classes[name]
+
+with open("build.sh", "w") as f:
+ f.write("#!/bin/sh\n")
+ f.write("java -jar compiler.jar --js extend.js --js ")
+ f.write(" --js ".join(files))
+ f.write(" --js_output_file box2d.js")
+with open("load.html", "w") as f:
+ for filename in files:
+ f.write('<script src="' + filename + '" type="text/javascript"></script>\r\n')
+print "\n".join(files)
217 engine.js
@@ -0,0 +1,217 @@
+(function(){
+var Engine = {};
+var $ = jQuery;
+
+Engine.log = function(arg) {
+return;
+ if(typeof(window.console) != 'undefined') {
+ console.log(arg);
+ }
+}
+var log = Engine.log;
+
+Engine.Helper = {};
+Engine.Helper.Canvas = function (w, h){
+ var c = document.createElement('canvas');
+ c.setAttribute('width', w);
+ c.setAttribute('height', h);
+ return c;
+}
+
+Engine.FPSCounter = function(ctx) {
+ this.t = new Date().getTime()/1000.0;
+ this.n = 0;
+ this.fps = 0.0;
+ this.draw = function() {
+ this.n ++;
+ if(this.n == 10) {
+ this.n = 0;
+ t = new Date().getTime()/1000.0;
+ this.fps = Math.round(10.0/(t-this.t));
+ this.t = t;
+ }
+ ctx.fillText('FPS: ' + this.fps, 1, 25);
+ }
+}
+
+Engine.Helper.fillTextMultiline = function(ctx, text, x, y, h) {
+ if(!$.isArray(text)) {
+ text = text.split('\n');
+ }
+ for(var i = 0; i < text.length; i ++){
+ ctx.fillText(text[i], x, y);
+ y += h;
+ }
+}
+
+Engine.Worker = function(script) {
+ var worker = new Worker(script);
+ this.output = null;
+ worker.onmessage = function(event) {
+ this.output = event.data;
+ }
+ worker.onerror = function(event) {
+ log('Worker Error ' + event.filename + ':' + event.lineno + ' ' + event.message);
+ }
+ this.tick = function(input) {
+ worker.postMessage(input);
+ return this.output;
+ }
+}
+
+Engine.FakeWorker = function(f) {
+ this.tick = f;
+}
+
+Engine.Scheduler = function(rate) {
+ this.ontick = function(){};
+ this.last = new Date().getTime()/1000.0;
+ var self = this;
+ this.tick = function () {
+ var current = new Date().getTime()/1000.0;
+ self.ontick(current-self.last);
+ self.last = current;
+ }
+ this.setRate = function(rate) {
+ this.rate = rate;
+ if(self.interval)
+ clearInterval(this.interval)
+ if(rate > 0) {
+ self.interval = setInterval(this.tick, 1000.0/rate)
+ }
+ }
+ this.setRate(rate);
+}
+
+var keyname = {
+ 32: 'SPACE',
+ 13: 'ENTER',
+ 9: 'TAB',
+ 8: 'BACKSPACE',
+ 16: 'SHIFT',
+ 17: 'CTRL',
+ 18: 'ALT',
+ 20: 'CAPS_LOCK',
+ 144: 'NUM_LOCK',
+ 145: 'SCROLL_LOCK',
+ 37: 'LEFT',
+ 38: 'UP',
+ 39: 'RIGHT',
+ 40: 'DOWN',
+ 33: 'PAGE_UP',
+ 34: 'PAGE_DOWN',
+ 36: 'HOME',
+ 35: 'END',
+ 45: 'INSERT',
+ 46: 'DELETE',
+ 27: 'ESCAPE',
+ 19: 'PAUSE',
+ 222: "'"
+};
+
+Engine.KeyTracker = function(obj) {
+ //TODO: focus is broken in chrome
+ this.focus = true;
+ this.onfocus = function() {}
+ this.onblur = function() {}
+
+ var self = this;
+
+ this.reset = function() {
+ var code;
+ for(code in keyname) {
+ this[keyname[code]] = false;
+ }
+ }
+
+ var keydown = $(document).keydown(function(e){
+ self[keyname[e.keyCode]] = true;
+ return !self.focus;
+ });
+
+ var keyup = $(document).keyup(function(evt){
+ self[keyname[evt.keyCode]] = false;
+ return !self.focus;
+ });
+
+ // keep track of focus
+ $(obj).click(function(e) {
+ self.focus = true;
+ $(obj).addClass('keytracked');
+ self.onfocus();
+ });
+
+ $(obj).addClass('keytracked');
+
+ $(window).click(function(e) {
+ if(e.originalEvent.target != obj) {
+ $(obj).removeClass('keytracked');
+ self.focus = false;
+ self.onblur();
+ }
+ });
+
+}
+
+Engine.MouseTracker = function(obj) {
+ this.x = 0;
+ this.y = 0;
+ this.onclick = function() {}
+ var self = this;
+ // this does assume that the object does not move
+ // to improve performance
+ var o = $(obj).offset();
+ // todo: add unregistration
+ $(obj).click(function(e){
+ var x = e.pageX-o.left;
+ var y = e.pageY-o.top;
+ self.onclick(e, x, y);
+ });
+ $(obj).mousemove(function(e){
+ self.x = e.pageX-o.left;
+ self.y = e.pageY-o.top;
+ });
+}
+
+
+
+html5av = document.createElement('video').load != undefined;
+Engine.ResourceLoader = function(resources, onready, onerror) {
+ this.total = 0;
+ this.loaded = 0;
+ var self = this;
+ this.load = function(type, name, url) {
+ var data = document.createElement(type);
+ this[name] = data;
+
+ // TODO: proper error handling
+ $(data).one('error', onerror);
+
+ var callback = function() {
+ self.loaded ++;
+ log('ready', url, self.loaded, self.total);
+ if(self.loaded == self.total) {
+ onready();
+ }
+ }
+
+ if(type == 'video' || type == 'audio') {
+ $(data).one('canplaythrough', callback);
+ data.setAttribute('autobuffer', 'autobuffer');
+ data.setAttribute('src', url);
+ data.load();
+ }
+ else {
+ data.setAttribute('src', url);
+ $(data).one('load', callback);
+ }
+ this.total ++;
+ }
+
+ for(var i = 0; i < resources.length; i++){
+ this.load(resources[i][0], resources[i][1], resources[i][2]);
+ }
+}
+
+window.Engine = Engine;
+})();
5 extend.js
@@ -0,0 +1,5 @@
+function extend(a, b) {
+ for(var c in b) {
+ a[c] = b[c];
+ }
+}
33 flash/Box2D/Collision/ClipVertex.as
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2006-2007 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.
+*/
+
+package Box2D.Collision{
+
+
+import Box2D.Common.Math.*;
+import Box2D.Collision.*;
+
+
+public class ClipVertex
+{
+ public var v:b2Vec2 = new b2Vec2();
+ public var id:b2ContactID = new b2ContactID();
+};
+
+
+}
69 flash/Box2D/Collision/Features.as
@@ -0,0 +1,69 @@
+/*
+* Copyright (c) 2006-2007 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.
+*/
+
+package Box2D.Collision{
+
+// We use contact ids to facilitate warm starting.
+public class Features
+{
+ ///< The edge that defines the outward contact normal.
+ public function set referenceEdge(value:int) : void{
+ _referenceEdge = value;
+ _m_id._key = (_m_id._key & 0xffffff00) | (_referenceEdge & 0x000000ff);
+ }
+ public function get referenceEdge():int{
+ return _referenceEdge;
+ }
+ public var _referenceEdge:int;
+
+ ///< The edge most anti-parallel to the reference edge.
+ public function set incidentEdge(value:int) : void{
+ _incidentEdge = value;
+ _m_id._key = (_m_id._key & 0xffff00ff) | ((_incidentEdge << 8) & 0x0000ff00);
+ }
+ public function get incidentEdge():int{
+ return _incidentEdge;
+ }
+ public var _incidentEdge:int;
+
+ ///< The vertex (0 or 1) on the incident edge that was clipped.
+ public function set incidentVertex(value:int) : void{
+ _incidentVertex = value;
+ _m_id._key = (_m_id._key & 0xff00ffff) | ((_incidentVertex << 16) & 0x00ff0000);
+ }
+ public function get incidentVertex():int{
+ return _incidentVertex;
+ }
+ public var _incidentVertex:int;
+
+ ///< A value of 1 indicates that the reference edge is on shape2.
+ public function set flip(value:int) : void{
+ _flip = value;
+ _m_id._key = (_m_id._key & 0x00ffffff) | ((_flip << 24) & 0xff000000);
+ }
+ public function get flip():int{
+ return _flip;
+ }
+ public var _flip:int;
+
+
+ public var _m_id:b2ContactID;
+};
+
+
+}
40 flash/Box2D/Collision/Shapes/b2CircleDef.as
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2006-2007 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.
+*/
+
+package Box2D.Collision.Shapes{
+
+
+
+import Box2D.Common.Math.*;
+import Box2D.Collision.Shapes.*;
+
+
+/// This structure is used to build circle shapes.
+public class b2CircleDef extends b2ShapeDef
+{
+ public function b2CircleDef()
+ {
+ type = b2Shape.e_circleShape;
+ radius = 1.0;
+ }
+
+ public var localPosition:b2Vec2 = new b2Vec2(0.0, 0.0);
+ public var radius:Number;
+};
+
+}
190 flash/Box2D/Collision/Shapes/b2CircleShape.as
@@ -0,0 +1,190 @@
+/*
+* Copyright (c) 2006-2007 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.
+*/
+
+package Box2D.Collision.Shapes{
+
+
+
+import Box2D.Common.Math.*;
+import Box2D.Common.*;
+import Box2D.Collision.Shapes.*;
+import Box2D.Dynamics.*;
+import Box2D.Collision.*;
+
+
+
+public class b2CircleShape extends b2Shape
+{
+ /// @see b2Shape::TestPoint
+ public override function TestPoint(transform:b2XForm, p:b2Vec2) : Boolean{
+ //b2Vec2 center = transform.position + b2Mul(transform.R, m_localPosition);
+ var tMat:b2Mat22 = transform.R;
+ var dX:Number = transform.position.x + (tMat.col1.x * m_localPosition.x + tMat.col2.x * m_localPosition.y);
+ var dY:Number = transform.position.y + (tMat.col1.y * m_localPosition.x + tMat.col2.y * m_localPosition.y);
+ //b2Vec2 d = p - center;
+ dX = p.x - dX;
+ dY = p.y - dY;
+ //return b2Dot(d, d) <= m_radius * m_radius;
+ return (dX*dX + dY*dY) <= m_radius * m_radius;
+ }
+
+ /// @see b2Shape::TestSegment
+ public override function TestSegment( transform:b2XForm,
+ lambda:Array, // float pointer
+ normal:b2Vec2, // pointer
+ segment:b2Segment,
+ maxLambda:Number) :Boolean
+ {
+ //b2Vec2 position = transform.position + b2Mul(transform.R, m_localPosition);
+ var tMat:b2Mat22 = transform.R;
+ var positionX:Number = transform.position.x + (tMat.col1.x * m_localPosition.x + tMat.col2.x * m_localPosition.y);
+ var positionY:Number = transform.position.y + (tMat.col1.y * m_localPosition.x + tMat.col2.y * m_localPosition.y);
+
+ //b2Vec2 s = segment.p1 - position;
+ var sX:Number = segment.p1.x - positionX;
+ var sY:Number = segment.p1.y - positionY;
+ //float32 b = b2Dot(s, s) - m_radius * m_radius;
+ var b:Number = (sX*sX + sY*sY) - m_radius * m_radius;
+
+ // Does the segment start inside the circle?
+ if (b < 0.0)
+ {
+ return false;
+ }
+
+ // Solve quadratic equation.
+ //b2Vec2 r = segment.p2 - segment.p1;
+ var rX:Number = segment.p2.x - segment.p1.x;
+ var rY:Number = segment.p2.y - segment.p1.y;
+ //float32 c = b2Dot(s, r);
+ var c:Number = (sX*rX + sY*rY);
+ //float32 rr = b2Dot(r, r);
+ var rr:Number = (rX*rX + rY*rY);
+ var sigma:Number = c * c - rr * b;
+
+ // Check for negative discriminant and short segment.
+ if (sigma < 0.0 || rr < Number.MIN_VALUE)
+ {
+ return false;
+ }
+
+ // Find the point of intersection of the line with the circle.
+ var a:Number = -(c + Math.sqrt(sigma));
+
+ // Is the intersection point on the segment?
+ if (0.0 <= a && a <= maxLambda * rr)
+ {
+ a /= rr;
+ //*lambda = a;
+ lambda[0] = a;
+ //*normal = s + a * r;
+ normal.x = sX + a * rX;
+ normal.y = sY + a * rY;
+ normal.Normalize();
+ return true;
+ }
+
+ return false;
+ }
+
+ /// @see b2Shape::ComputeAABB
+ public override function ComputeAABB(aabb:b2AABB, transform:b2XForm) : void{
+ //b2Vec2 p = transform.position + b2Mul(transform.R, m_localPosition);
+ var tMat:b2Mat22 = transform.R;
+ var pX:Number = transform.position.x + (tMat.col1.x * m_localPosition.x + tMat.col2.x * m_localPosition.y);
+ var pY:Number = transform.position.y + (tMat.col1.y * m_localPosition.x + tMat.col2.y * m_localPosition.y);
+ aabb.lowerBound.Set(pX - m_radius, pY - m_radius);
+ aabb.upperBound.Set(pX + m_radius, pY + m_radius);
+ }
+
+ /// @see b2Shape::ComputeSweptAABB
+ public override function ComputeSweptAABB( aabb:b2AABB,
+ transform1:b2XForm,
+ transform2:b2XForm) : void
+ {
+ var tMat:b2Mat22;
+ //b2Vec2 p1 = transform1.position + b2Mul(transform1.R, m_localPosition);
+ tMat = transform1.R;
+ var p1X:Number = transform1.position.x + (tMat.col1.x * m_localPosition.x + tMat.col2.x * m_localPosition.y);
+ var p1Y:Number = transform1.position.y + (tMat.col1.y * m_localPosition.x + tMat.col2.y * m_localPosition.y);
+ //b2Vec2 p2 = transform2.position + b2Mul(transform2.R, m_localPosition);
+ tMat = transform2.R;
+ var p2X:Number = transform2.position.x + (tMat.col1.x * m_localPosition.x + tMat.col2.x * m_localPosition.y);
+ var p2Y:Number = transform2.position.y + (tMat.col1.y * m_localPosition.x + tMat.col2.y * m_localPosition.y);
+
+ //b2Vec2 lower = b2Min(p1, p2);
+ //b2Vec2 upper = b2Max(p1, p2);
+
+ //aabb->lowerBound.Set(lower.x - m_radius, lower.y - m_radius);
+ aabb.lowerBound.Set((p1X < p2X ? p1X : p2X) - m_radius, (p1Y < p2Y ? p1Y : p2Y) - m_radius);
+ //aabb->upperBound.Set(upper.x + m_radius, upper.y + m_radius);
+ aabb.upperBound.Set((p1X > p2X ? p1X : p2X) + m_radius, (p1Y > p2Y ? p1Y : p2Y) + m_radius);
+ }
+
+ /// @see b2Shape::ComputeMass
+ public override function ComputeMass(massData:b2MassData) : void{
+ massData.mass = m_density * b2Settings.b2_pi * m_radius * m_radius;
+ massData.center.SetV(m_localPosition);
+
+ // inertia about the local origin
+ //massData.I = massData.mass * (0.5 * m_radius * m_radius + b2Dot(m_localPosition, m_localPosition));
+ massData.I = massData.mass * (0.5 * m_radius * m_radius + (m_localPosition.x*m_localPosition.x + m_localPosition.y*m_localPosition.y));
+ }
+
+ /// Get the local position of this circle in its parent body.
+ public function GetLocalPosition() : b2Vec2{
+ return m_localPosition;
+ }
+
+ /// Get the radius of this circle.
+ public function GetRadius() : Number{
+ return m_radius;
+ }
+
+ //--------------- Internals Below -------------------
+
+ public function b2CircleShape(def:b2ShapeDef){
+ super(def);
+
+ //b2Settings.b2Assert(def.type == e_circleShape);
+ var circleDef:b2CircleDef = def as b2CircleDef;
+
+ m_type = e_circleShape;
+ m_localPosition.SetV(circleDef.localPosition);
+ m_radius = circleDef.radius;
+
+ }
+
+ public override function UpdateSweepRadius(center:b2Vec2) : void{
+ // Update the sweep radius (maximum radius) as measured from
+ // a local center point.
+ //b2Vec2 d = m_localPosition - center;
+ var dX:Number = m_localPosition.x - center.x;
+ var dY:Number = m_localPosition.y - center.y;
+ dX = Math.sqrt(dX*dX + dY*dY); // length
+ //m_sweepRadius = d.Length() + m_radius - b2_toiSlop;
+ m_sweepRadius = dX + m_radius - b2Settings.b2_toiSlop;
+ }
+
+ // Local position in parent body
+ public var m_localPosition:b2Vec2 = new b2Vec2();
+ public var m_radius:Number;
+
+};
+
+}
50 flash/Box2D/Collision/Shapes/b2FilterData.as
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2006-2007 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.
+*/
+
+package Box2D.Collision.Shapes{
+
+
+
+import Box2D.Common.Math.*;
+
+
+/// This holds contact filtering data.
+public class b2FilterData
+{
+ public function Copy() : b2FilterData {
+ var copy: b2FilterData = new b2FilterData();
+ copy.categoryBits = categoryBits;
+ copy.maskBits = maskBits;
+ copy.groupIndex = groupIndex;
+ return copy;
+ }
+
+ /// The collision category bits. Normally you would just set one bit.
+ public var categoryBits: uint = 0x0001;
+
+ /// The collision mask bits. This states the categories that this
+ /// shape would accept for collision.
+ public var maskBits: uint = 0xFFFF;
+
+ /// Collision groups allow a certain group of objects to never collide (negative)
+ /// or always collide (positive). Zero means no collision group. Non-zero group
+ /// filtering always wins against the mask bits.
+ public var groupIndex: int = 0;
+}
+
+}
37 flash/Box2D/Collision/Shapes/b2MassData.as
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2006-2007 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.
+*/
+
+package Box2D.Collision.Shapes{
+
+
+
+import Box2D.Common.Math.*;
+
+
+/// This holds the mass data computed for a shape.
+public class b2MassData
+{
+ /// The mass of the shape, usually in kilograms.
+ public var mass:Number = 0.0;
+ /// The position of the shape's centroid relative to the shape's origin.
+ public var center:b2Vec2 = new b2Vec2(0,0);
+ /// The rotational inertia of the shape.
+ public var I:Number = 0.0;
+}
+
+}
94 flash/Box2D/Collision/Shapes/b2PolygonDef.as
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2006-2007 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.
+*/
+
+package Box2D.Collision.Shapes{
+
+
+
+import Box2D.Common.Math.*;
+import Box2D.Common.*;
+import Box2D.Collision.Shapes.*;
+
+
+
+public class b2PolygonDef extends b2ShapeDef
+{
+ public function b2PolygonDef()
+ {
+ type = b2Shape.e_polygonShape;
+ vertexCount = 0;
+
+ for (var i:int = 0; i < b2Settings.b2_maxPolygonVertices; i++){
+ vertices[i] = new b2Vec2();
+ }
+ }
+
+ /// Build vertices to represent an axis-aligned box.
+ /// @param hx the half-width.
+ /// @param hy the half-height.
+ public function SetAsBox(hx:Number, hy:Number) : void{
+ vertexCount = 4;
+ vertices[0].Set(-hx, -hy);
+ vertices[1].Set( hx, -hy);
+ vertices[2].Set( hx, hy);
+ vertices[3].Set(-hx, hy);
+ }
+
+ /// Build vertices to represent an oriented box.
+ /// @param hx the half-width.
+ /// @param hy the half-height.
+ /// @param center the center of the box in local coordinates.
+ /// @param angle the rotation of the box in local coordinates.
+ static private var s_mat:b2Mat22 = new b2Mat22();
+ public function SetAsOrientedBox(hx:Number, hy:Number, center:b2Vec2=null, angle:Number=0.0) : void{
+ //SetAsBox(hx, hy);
+ {
+ vertexCount = 4;
+ vertices[0].Set(-hx, -hy);
+ vertices[1].Set( hx, -hy);
+ vertices[2].Set( hx, hy);
+ vertices[3].Set(-hx, hy);
+ }
+
+ if (center){
+ //b2XForm xf;
+ //xf.position = center;
+ var xfPosition:b2Vec2 = center;
+ //xf.R.Set(angle);
+ var xfR:b2Mat22 = s_mat;
+ xfR.Set(angle);
+
+ for (var i:int = 0; i < vertexCount; ++i)
+ {
+ //vertices[i] = b2Mul(xf, vertices[i]);
+ //var a:b2Vec2 = b2MulMV(T.R, v);
+ center = vertices[i];
+ hx = xfPosition.x + (xfR.col1.x * center.x + xfR.col2.x * center.y)
+ center.y = xfPosition.y + (xfR.col1.y * center.x + xfR.col2.y * center.y)
+ center.x = hx;
+ }
+ }
+ }
+
+ /// The polygon vertices in local coordinates.
+ public var vertices:Array = new Array(b2Settings.b2_maxPolygonVertices);
+ /// The number of polygon vertices.
+ public var vertexCount:int;
+};
+
+}
700 flash/Box2D/Collision/Shapes/b2PolygonShape.as
@@ -0,0 +1,700 @@
+/*
+* Copyright (c) 2006-2007 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.
+*/
+
+package Box2D.Collision.Shapes{
+
+
+
+import Box2D.Common.Math.*;
+import Box2D.Common.*;
+import Box2D.Collision.Shapes.*;
+import Box2D.Dynamics.*;
+import Box2D.Collision.*;
+
+/// Convex polygon. The vertices must be in CCW order for a right-handed
+/// coordinate system with the z-axis coming out of the screen.
+
+public class b2PolygonShape extends b2Shape
+{
+ /// @see b2Shape::TestPoint
+ public override function TestPoint(xf:b2XForm, p:b2Vec2) : Boolean{
+ var tVec:b2Vec2;
+
+ //b2Vec2 pLocal = b2MulT(xf.R, p - xf.position);
+ var tMat:b2Mat22 = xf.R;
+ var tX:Number = p.x - xf.position.x;
+ var tY:Number = p.y - xf.position.y;
+ var pLocalX:Number = (tX*tMat.col1.x + tY*tMat.col1.y);
+ var pLocalY:Number = (tX*tMat.col2.x + tY*tMat.col2.y);
+
+ for (var i:int = 0; i < m_vertexCount; ++i)
+ {
+ //float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
+ tVec = m_vertices[i];
+ tX = pLocalX - tVec.x;
+ tY = pLocalY - tVec.y;
+ tVec = m_normals[i];
+ var dot:Number = (tVec.x * tX + tVec.y * tY);
+ if (dot > 0.0)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// @see b2Shape::TestSegment
+ public override function TestSegment( xf:b2XForm,
+ lambda:Array, // float ptr
+ normal:b2Vec2, // ptr
+ segment:b2Segment,
+ maxLambda:Number) : Boolean
+ {
+ var lower:Number = 0.0;
+ var upper:Number = maxLambda;
+
+ var tX:Number;
+ var tY:Number;
+ var tMat:b2Mat22;
+ var tVec:b2Vec2;
+
+ //b2Vec2 p1 = b2MulT(xf.R, segment.p1 - xf.position);
+ tX = segment.p1.x - xf.position.x;
+ tY = segment.p1.y - xf.position.y;
+ tMat = xf.R;
+ var p1X:Number = (tX * tMat.col1.x + tY * tMat.col1.y);
+ var p1Y:Number = (tX * tMat.col2.x + tY * tMat.col2.y);
+ //b2Vec2 p2 = b2MulT(xf.R, segment.p2 - xf.position);
+ tX = segment.p2.x - xf.position.x;
+ tY = segment.p2.y - xf.position.y;
+ tMat = xf.R;
+ var p2X:Number = (tX * tMat.col1.x + tY * tMat.col1.y);
+ var p2Y:Number = (tX * tMat.col2.x + tY * tMat.col2.y);
+ //b2Vec2 d = p2 - p1;
+ var dX:Number = p2X - p1X;
+ var dY:Number = p2Y - p1Y;
+ var index:int = -1;
+
+ for (var i:int = 0; i < m_vertexCount; ++i)
+ {
+ // p = p1 + a * d
+ // dot(normal, p - v) = 0
+ // dot(normal, p1 - v) + a * dot(normal, d) = 0
+
+ //float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
+ tVec = m_vertices[i];
+ tX = tVec.x - p1X;
+ tY = tVec.y - p1Y;
+ tVec = m_normals[i];
+ var numerator:Number = (tVec.x*tX + tVec.y*tY);
+ //float32 denominator = b2Dot(m_normals[i], d);
+ var denominator:Number = (tVec.x*dX + tVec.y*dY);
+
+ // 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.0 && numerator < lower * denominator)
+ {
+ // Increase lower.
+ // The segment enters this half-space.
+ lower = numerator / denominator;
+ index = i;
+ }
+ else if (denominator > 0.0 && numerator < upper * denominator)
+ {
+ // Decrease upper.
+ // The segment exits this half-space.
+ upper = numerator / denominator;
+ }
+
+ if (upper < lower)
+ {
+ return false;
+ }
+ }
+
+ //b2Settings.b2Assert(0.0 <= lower && lower <= maxLambda);
+
+ if (index >= 0)
+ {
+ //*lambda = lower;
+ lambda[0] = lower;
+ //*normal = b2Mul(xf.R, m_normals[index]);
+ tMat = xf.R;
+ tVec = m_normals[index];
+ normal.x = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ normal.y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ return true;
+ }
+
+ return false;
+ }
+
+ /// @see b2Shape::ComputeAABB
+ //
+ static private var s_computeMat:b2Mat22 = new b2Mat22();
+ //
+ public override function ComputeAABB(aabb:b2AABB, xf:b2XForm) : void{
+ var tMat:b2Mat22;
+ var tVec:b2Vec2;
+
+ var R:b2Mat22 = s_computeMat;
+ //b2Mat22 R = b2Mul(xf.R, m_obb.R);
+ tMat = xf.R;
+ tVec = m_obb.R.col1;
+ //R.col1 = b2MulMV(A, B.col1)
+ R.col1.x = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ R.col1.y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ //
+ tVec = m_obb.R.col2;
+ //R.col1 = b2MulMV(A, B.col2)
+ R.col2.x = (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ R.col2.y = (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+
+ //b2Mat22 absR = b2Abs(R);
+ R.Abs();
+ var absR:b2Mat22 = R;
+ //b2Vec2 h = b2Mul(absR, m_obb.extents);
+ tVec = m_obb.extents;
+ var hX:Number = (absR.col1.x * tVec.x + absR.col2.x * tVec.y);
+ var hY:Number = (absR.col1.y * tVec.x + absR.col2.y * tVec.y);
+ //b2Vec2 position = xf.position + b2Mul(xf.R, m_obb.center);
+ tMat = xf.R;
+ tVec = m_obb.center;
+ var positionX:Number = xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ var positionY:Number = xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ //aabb->lowerBound = position - h;
+ aabb.lowerBound.Set(positionX - hX, positionY - hY);
+ //aabb->upperBound = position + h;
+ aabb.upperBound.Set(positionX + hX, positionY + hY);
+ }
+
+ /// @see b2Shape::ComputeSweptAABB
+ //
+ static private var s_sweptAABB1:b2AABB = new b2AABB();
+ static private var s_sweptAABB2:b2AABB = new b2AABB();
+ //
+ public override function ComputeSweptAABB( aabb:b2AABB,
+ transform1:b2XForm,
+ transform2:b2XForm) : void
+ {
+ //b2AABB aabb1, aabb2;
+ var aabb1:b2AABB = s_sweptAABB1;
+ var aabb2:b2AABB = s_sweptAABB2;
+ ComputeAABB(aabb1, transform1);
+ ComputeAABB(aabb2, transform2);
+ //aabb.lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound);
+ aabb.lowerBound.Set((aabb1.lowerBound.x < aabb2.lowerBound.x ? aabb1.lowerBound.x : aabb2.lowerBound.x),
+ (aabb1.lowerBound.y < aabb2.lowerBound.y ? aabb1.lowerBound.y : aabb2.lowerBound.y));
+ //aabb.upperBound = b2Max(aabb1.upperBound, aabb2.upperBound);
+ aabb.upperBound.Set((aabb1.upperBound.x > aabb2.upperBound.x ? aabb1.upperBound.x : aabb2.upperBound.x),
+ (aabb1.upperBound.y > aabb2.upperBound.y ? aabb1.upperBound.y : aabb2.upperBound.y));
+ }
+
+ /// @see b2Shape::ComputeMass
+ //
+
+ //
+ public override function ComputeMass(massData:b2MassData) : void{
+ // 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.
+
+ //b2Settings.b2Assert(m_vertexCount >= 3);
+
+ //b2Vec2 center; center.Set(0.0f, 0.0f);
+ var centerX:Number = 0.0;
+ var centerY:Number = 0.0;
+ var area:Number = 0.0;
+ var I:Number = 0.0;
+
+ // pRef is the reference point for forming triangles.
+ // It's location doesn't change the result (except for rounding error).
+ //b2Vec2 pRef(0.0f, 0.0f);
+ var p1X:Number = 0.0;
+ var p1Y:Number = 0.0;
+ /*#if 0
+ // This code would put the reference point inside the polygon.
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ pRef += m_vertices[i];
+ }
+ pRef *= 1.0f / count;
+ #endif*/
+
+ var k_inv3:Number = 1.0 / 3.0;
+
+ for (var i:int = 0; i < m_vertexCount; ++i)
+ {
+ // Triangle vertices.
+ //b2Vec2 p1 = pRef;
+ //
+ //b2Vec2 p2 = m_vertices[i];
+ var p2:b2Vec2 = m_vertices[i];
+ //b2Vec2 p3 = i + 1 < m_vertexCount ? m_vertices[i+1] : m_vertices[0];
+ var p3:b2Vec2 = i + 1 < m_vertexCount ? m_vertices[int(i+1)] : m_vertices[0];
+
+ //b2Vec2 e1 = p2 - p1;
+ var e1X:Number = p2.x - p1X;
+ var e1Y:Number = p2.y - p1Y;
+ //b2Vec2 e2 = p3 - p1;
+ var e2X:Number = p3.x - p1X;
+ var e2Y:Number = p3.y - p1Y;
+
+ //float32 D = b2Cross(e1, e2);
+ var D:Number = e1X * e2Y - e1Y * e2X;
+
+ //float32 triangleArea = 0.5f * D;
+ var triangleArea:Number = 0.5 * D;
+ area += triangleArea;
+
+ // Area weighted centroid
+ //center += triangleArea * k_inv3 * (p1 + p2 + p3);
+ centerX += triangleArea * k_inv3 * (p1X + p2.x + p3.x);
+ centerY += triangleArea * k_inv3 * (p1Y + p2.y + p3.y);
+
+ //float32 px = p1.x, py = p1.y;
+ var px:Number = p1X;
+ var py:Number = p1Y;
+ //float32 ex1 = e1.x, ey1 = e1.y;
+ var ex1:Number = e1X;
+ var ey1:Number = e1Y;
+ //float32 ex2 = e2.x, ey2 = e2.y;
+ var ex2:Number = e2X;
+ var ey2:Number = e2Y;
+
+ //float32 intx2 = k_inv3 * (0.25f * (ex1*ex1 + ex2*ex1 + ex2*ex2) + (px*ex1 + px*ex2)) + 0.5f*px*px;
+ var intx2:Number = k_inv3 * (0.25 * (ex1*ex1 + ex2*ex1 + ex2*ex2) + (px*ex1 + px*ex2)) + 0.5*px*px;
+ //float32 inty2 = k_inv3 * (0.25f * (ey1*ey1 + ey2*ey1 + ey2*ey2) + (py*ey1 + py*ey2)) + 0.5f*py*py;
+ var inty2:Number = k_inv3 * (0.25 * (ey1*ey1 + ey2*ey1 + ey2*ey2) + (py*ey1 + py*ey2)) + 0.5*py*py;
+
+ I += D * (intx2 + inty2);
+ }
+
+ // Total mass
+ massData.mass = m_density * area;
+
+ // Center of mass
+ //b2Settings.b2Assert(area > Number.MIN_VALUE);
+ //center *= 1.0f / area;
+ centerX *= 1.0 / area;
+ centerY *= 1.0 / area;
+ //massData->center = center;
+ massData.center.Set(centerX, centerY);
+
+ // Inertia tensor relative to the local origin.
+ massData.I = m_density * I;
+ }
+
+ /// Get the oriented bounding box relative to the parent body.
+ public function GetOBB() : b2OBB{
+ return m_obb;
+ }
+
+ /// Get local centroid relative to the parent body.
+ public function GetCentroid() : b2Vec2{
+ return m_centroid;
+ }
+
+ /// Get the vertex count.
+ public function GetVertexCount() : int{
+ return m_vertexCount;
+ }
+
+ /// Get the vertices in local coordinates.
+ public function GetVertices() : Array{
+ return m_vertices;
+ }
+
+ /// Get the core vertices in local coordinates. These vertices
+ /// represent a smaller polygon that is used for time of impact
+ /// computations.
+ public function GetCoreVertices() : Array{
+ return m_coreVertices;
+ }
+
+ /// Get the edge normal vectors. There is one for each vertex.
+ public function GetNormals() : Array
+ {
+ return m_normals;
+ }
+
+ /// Get the first vertex and apply the supplied transform.
+ public function GetFirstVertex(xf:b2XForm) : b2Vec2{
+ return b2Math.b2MulX(xf, m_coreVertices[0]);
+ }
+
+ /// Get the centroid and apply the supplied transform.
+ public function Centroid(xf:b2XForm) : b2Vec2{
+ return b2Math.b2MulX(xf, m_centroid);
+ }
+
+ /// Get the support point in the given world direction.
+ /// Use the supplied transform.
+ private var s_supportVec:b2Vec2 = new b2Vec2();
+ public function Support(xf:b2XForm, dX:Number, dY:Number) : b2Vec2{
+ var tVec:b2Vec2;
+
+ var tMat:b2Mat22;
+ //b2Vec2 dLocal = b2MulT(xf.R, d);
+ tMat = xf.R;
+ var dLocalX:Number = (dX * tMat.col1.x + dY * tMat.col1.y);
+ var dLocalY:Number = (dX * tMat.col2.x + dY * tMat.col2.y);
+
+ var bestIndex:int = 0;
+ //var bestValue:Number = b2Dot(m_coreVertices[0], dLocal);
+ tVec = m_coreVertices[0];
+ var bestValue:Number = (tVec.x*dLocalX + tVec.y*dLocalY);
+ for (var i:int = 1; i < m_vertexCount; ++i)
+ {
+ //var value:Number = b2Dot(m_coreVertices[i], dLocal);
+ tVec = m_coreVertices[i];
+ var value:Number = (tVec.x*dLocalX + tVec.y*dLocalY);
+ if (value > bestValue)
+ {
+ bestIndex = i;
+ bestValue = value;
+ }
+ }
+
+ //return b2Math.b2MulX(xf, m_coreVertices[bestIndex]);
+ tMat = xf.R;
+ tVec = m_coreVertices[bestIndex];
+ s_supportVec.x = xf.position.x + (tMat.col1.x * tVec.x + tMat.col2.x * tVec.y);
+ s_supportVec.y = xf.position.y + (tMat.col1.y * tVec.x + tMat.col2.y * tVec.y);
+ return s_supportVec;
+
+ }
+
+ //--------------- Internals Below -------------------
+
+ public function b2PolygonShape(def:b2ShapeDef){
+ super(def);
+
+ //b2Settings.b2Assert(def.type == e_polygonShape);
+ m_type = e_polygonShape;
+ var poly:b2PolygonDef = def as b2PolygonDef;
+
+ // Get the vertices transformed into the body frame.
+ m_vertexCount = poly.vertexCount;
+ //b2Settings.b2Assert(3 <= m_vertexCount && m_vertexCount <= b2_maxPolygonVertices);
+
+ var i:int;
+ var i1:int = i;
+ var i2:int = i;
+
+ // Copy vertices.
+ for (i = 0; i < m_vertexCount; ++i)
+ {
+ m_vertices[i] = poly.vertices[i].Copy();
+ }
+
+ // Compute normals. Ensure the edges have non-zero length.
+ for (i = 0; i < m_vertexCount; ++i)
+ {
+ i1 = i;
+ i2 = i + 1 < m_vertexCount ? i + 1 : 0;
+ //b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
+ var edgeX:Number = m_vertices[i2].x - m_vertices[i1].x;
+ var edgeY:Number = m_vertices[i2].y - m_vertices[i1].y;
+ //b2Settings.b2Assert(edge.LengthSquared() > Number.MIN_VALUE * Number.MIN_VALUE);
+ //m_normals[i] = b2Cross(edge, 1.0f); ^^
+ var len:Number = Math.sqrt(edgeX*edgeX + edgeY*edgeY);
+ //m_normals[i].Normalize();
+ m_normals[i] = new b2Vec2(edgeY/len, -edgeX/len);
+ }
+
+ /*#ifdef _DEBUG
+ // Ensure the polygon is convex.
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ for (int32 j = 0; j < m_vertexCount; ++j)
+ {
+ // Don't check vertices on the current edge.
+ if (j == i || j == (i + 1) % m_vertexCount)
+ {
+ continue;
+ }
+
+ // Your polygon is non-convex (it has an indentation).
+ // Or your polygon is too skinny.
+ float32 s = b2Dot(m_normals[i], m_vertices[j] - m_vertices[i]);
+ b2Assert(s < -b2_linearSlop);
+ }
+ }
+
+ // Ensure the polygon is counter-clockwise.
+ for (i = 1; i < m_vertexCount; ++i)
+ {
+ var cross:Number = b2Math.b2CrossVV(m_normals[int(i-1)], m_normals[i]);
+
+ // Keep asinf happy.
+ cross = b2Math.b2Clamp(cross, -1.0, 1.0);
+
+ // You have consecutive edges that are almost parallel on your polygon.
+ var angle:Number = Math.asin(cross);
+ //b2Assert(angle > b2_angularSlop);
+ trace(angle > b2Settings.b2_angularSlop);
+ }
+ #endif*/
+
+ // Compute the polygon centroid.
+ m_centroid = ComputeCentroid(poly.vertices, poly.vertexCount);
+
+ // Compute the oriented bounding box.
+ ComputeOBB(m_obb, m_vertices, m_vertexCount);
+
+ // Create core polygon shape by shifting edges inward.
+ // Also compute the min/max radius for CCD.
+ for (i = 0; i < m_vertexCount; ++i)
+ {
+ i1 = i - 1 >= 0 ? i - 1 : m_vertexCount - 1;
+ i2 = i;
+
+ //b2Vec2 n1 = m_normals[i1];
+ var n1X:Number = m_normals[i1].x;
+ var n1Y:Number = m_normals[i1].y;
+ //b2Vec2 n2 = m_normals[i2];
+ var n2X:Number = m_normals[i2].x;
+ var n2Y:Number = m_normals[i2].y;
+ //b2Vec2 v = m_vertices[i] - m_centroid;
+ var vX:Number = m_vertices[i].x - m_centroid.x;
+ var vY:Number = m_vertices[i].y - m_centroid.y;
+
+ //b2Vec2 d;
+ var dX:Number = (n1X*vX + n1Y*vY) - b2Settings.b2_toiSlop;
+ var dY:Number = (n2X*vX + n2Y*vY) - b2Settings.b2_toiSlop;
+
+ // Shifting the edge inward by b2_toiSlop should
+ // not cause the plane to pass the centroid.
+
+ // Your shape has a radius/extent less than b2_toiSlop.
+ //b2Settings.b2Assert(d.x >= 0.0);
+ //b2Settings.b2Assert(d.y >= 0.0);
+ //var A:b2Mat22;
+ //A.col1.x = n1.x; A.col2.x = n1.y;
+ //A.col1.y = n2.x; A.col2.y = n2.y;
+ //m_coreVertices[i] = A.Solve(d) + m_centroid;
+ //float32 det = a11 * a22 - a12 * a21;
+ var det:Number = 1.0/(n1X * n2Y - n1Y * n2X);
+ //det = 1.0 / det;
+ m_coreVertices[i] = new b2Vec2( det * (n2Y * dX - n1Y * dY) + m_centroid.x,
+ det * (n1X * dY - n2X * dX) + m_centroid.y);
+ }
+ }
+
+ public override function UpdateSweepRadius(center:b2Vec2) : void{
+ var tVec:b2Vec2;
+
+ // Update the sweep radius (maximum radius) as measured from
+ // a local center point.
+ m_sweepRadius = 0.0;
+ for (var i:int = 0; i < m_vertexCount; ++i)
+ {
+ //b2Vec2 d = m_coreVertices[i] - center;
+ tVec = m_coreVertices[i];
+ var dX:Number = tVec.x - center.x;
+ var dY:Number = tVec.y - center.y;
+ dX = Math.sqrt(dX*dX + dY*dY);
+ //m_sweepRadius = b2Max(m_sweepRadius, d.Length());
+ if (dX > m_sweepRadius) m_sweepRadius = dX;
+ }
+ }
+
+ // Local position of the polygon centroid.
+ public var m_centroid:b2Vec2;
+
+ public var m_obb:b2OBB = new b2OBB();
+
+ public var m_vertices:Array = new Array(b2Settings.b2_maxPolygonVertices);
+ public var m_normals:Array = new Array(b2Settings.b2_maxPolygonVertices);
+ public var m_coreVertices:Array = new Array(b2Settings.b2_maxPolygonVertices);
+
+ public var m_vertexCount:int;
+
+
+
+
+ static public function ComputeCentroid(vs:Array, count:int) : b2Vec2
+ {
+ //b2Settings.b2Assert(count >= 3);
+
+ //b2Vec2 c; c.Set(0.0f, 0.0f);
+ var c:b2Vec2 = new b2Vec2();
+ var area:Number = 0.0;
+
+ // pRef is the reference point for forming triangles.
+ // It's location doesn't change the result (except for rounding error).
+ //b2Vec2 pRef(0.0f, 0.0f);
+ var p1X:Number = 0.0;
+ var p1Y:Number = 0.0;
+ /*#if 0
+ // This code would put the reference point inside the polygon.
+ for (int32 i = 0; i < count; ++i)
+ {
+ pRef += vs[i];
+ }
+ pRef *= 1.0f / count;
+ #endif*/
+
+ var inv3:Number = 1.0 / 3.0;
+
+ for (var i:int = 0; i < count; ++i)
+ {
+ // Triangle vertices.
+ //b2Vec2 p1 = pRef;
+ // 0.0, 0.0
+ //b2Vec2 p2 = vs[i];
+ var p2:b2Vec2 = vs[i];
+ //b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0];
+ var p3:b2Vec2 = i + 1 < count ? vs[int(i+1)] : vs[0];
+
+ //b2Vec2 e1 = p2 - p1;
+ var e1X:Number = p2.x - p1X;
+ var e1Y:Number = p2.y - p1Y;
+ //b2Vec2 e2 = p3 - p1;
+ var e2X:Number = p3.x - p1X;
+ var e2Y:Number = p3.y - p1Y;
+
+ //float32 D = b2Cross(e1, e2);
+ var D:Number = (e1X * e2Y - e1Y * e2X);
+
+ //float32 triangleArea = 0.5f * D;
+ var triangleArea:Number = 0.5 * D;
+ area += triangleArea;
+
+ // Area weighted centroid
+ //c += triangleArea * inv3 * (p1 + p2 + p3);
+ c.x += triangleArea * inv3 * (p1X + p2.x + p3.x);
+ c.y += triangleArea * inv3 * (p1Y + p2.y + p3.y);
+ }
+
+ // Centroid
+ //beSettings.b2Assert(area > Number.MIN_VALUE);
+ //c *= 1.0 / area;
+ c.x *= 1.0 / area;
+ c.y *= 1.0 / area;
+ return c;
+ }
+
+ // http://www.geometrictools.com/Documentation/MinimumAreaRectangle.pdf
+ static public function ComputeOBB(obb:b2OBB, vs:Array, count:int) : void
+ {
+ var i:int;
+ //b2Settings.b2Assert(count <= b2Settings.b2_maxPolygonVertices);
+ var p:Array = new Array(b2Settings.b2_maxPolygonVertices + 1);
+ for (i = 0; i < count; ++i)
+ {
+ p[i] = vs[i];
+ }
+ p[count] = p[0];
+
+ var minArea:Number = Number.MAX_VALUE;
+
+ for (i = 1; i <= count; ++i)
+ {
+ var root:b2Vec2 = p[int(i-1)];
+ //b2Vec2 ux = p[i] - root;
+ var uxX:Number = p[i].x - root.x;
+ var uxY:Number = p[i].y - root.y;
+ //var length:Number = ux.Normalize();
+ var length:Number = Math.sqrt(uxX*uxX + uxY*uxY);
+ uxX /= length;
+ uxY /= length;
+ //b2Settings.b2Assert(length > Number.MIN_VALUE);
+ //b2Vec2 uy(-ux.y, ux.x);
+ var uyX:Number = -uxY;
+ var uyY:Number = uxX;
+ //b2Vec2 lower(FLT_MAX, FLT_MAX);
+ var lowerX:Number = Number.MAX_VALUE;
+ var lowerY:Number = Number.MAX_VALUE;
+ //b2Vec2 upper(-FLT_MAX, -FLT_MAX);
+ var upperX:Number = -Number.MAX_VALUE;
+ var upperY:Number = -Number.MAX_VALUE;
+
+ for (var j:int = 0; j < count; ++j)
+ {
+ //b2Vec2 d = p[j] - root;
+ var dX:Number = p[j].x - root.x;
+ var dY:Number = p[j].y - root.y;
+ //b2Vec2 r;
+ //var rX:Number = b2Dot(ux, d);
+ var rX:Number = (uxX*dX + uxY*dY);
+ //var rY:Number = b2Dot(uy, d);
+ var rY:Number = (uyX*dX + uyY*dY);
+ //lower = b2Min(lower, r);
+ if (rX < lowerX) lowerX = rX;
+ if (rY < lowerY) lowerY = rY;
+ //upper = b2Max(upper, r);
+ if (rX > upperX) upperX = rX;
+ if (rY > upperY) upperY = rY;
+ }
+
+ var area:Number = (upperX - lowerX) * (upperY - lowerY);
+ if (area < 0.95 * minArea)
+ {
+ minArea = area;
+ //obb->R.col1 = ux;
+ obb.R.col1.x = uxX;
+ obb.R.col1.y = uxY;
+ //obb->R.col2 = uy;
+ obb.R.col2.x = uyX;
+ obb.R.col2.y = uyY;
+ //b2Vec2 center = 0.5f * (lower + upper);
+ var centerX:Number = 0.5 * (lowerX + upperX);
+ var centerY:Number = 0.5 * (lowerY + upperY);
+ //obb->center = root + b2Mul(obb->R, center);
+ var tMat:b2Mat22 = obb.R;
+ obb.center.x = root.x + (tMat.col1.x * centerX + tMat.col2.x * centerY);
+ obb.center.y = root.y + (tMat.col1.y * centerX + tMat.col2.y * centerY);
+ //obb->extents = 0.5f * (upper - lower);
+ obb.extents.x = 0.5 * (upperX - lowerX);
+ obb.extents.y = 0.5 * (upperY - lowerY);
+ }
+ }
+
+ //b2Settings.b2Assert(minArea < Number.MAX_VALUE);
+ }
+
+
+};
+
+}
329 flash/Box2D/Collision/Shapes/b2Shape.as
@@ -0,0 +1,329 @@
+/*
+* Copyright (c) 2006-2007 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.
+*/
+
+package Box2D.Collision.Shapes{
+
+
+
+
+import Box2D.Common.Math.*;
+import Box2D.Common.*;
+import Box2D.Dynamics.*;
+import Box2D.Collision.*;
+
+
+
+/// A shape is used for collision detection. Shapes are created in b2World.
+/// You can use shape for collision detection before they are attached to the world.
+/// @warning you cannot reuse shapes.
+public class b2Shape
+{
+ /// Get the type of this shape. You can use this to down cast to the concrete shape.
+ /// @return the shape type.
+ public function GetType() : int{
+ return m_type;
+ }
+
+ /// Is this shape a sensor (non-solid)?
+ /// @return the true if the shape is a sensor.
+ public function IsSensor() : Boolean{
+ return m_isSensor;
+ }
+
+ /// Set the contact filtering data. You must call b2World::Refilter to correct
+ /// existing contacts/non-contacts.
+ public function SetFilterData(filter:b2FilterData) : void
+ {
+ m_filter = filter.Copy();
+ }
+
+ /// Get the contact filtering data.
+ public function GetFilterData() : b2FilterData
+ {
+ return m_filter.Copy();
+ }
+
+ /// Get the parent body of this shape. This is NULL if the shape is not attached.
+ /// @return the parent body.
+ public function GetBody() : b2Body{
+ return m_body;
+ }
+
+ /// Get the next shape in the parent body's shape list.
+ /// @return the next shape.
+ public function GetNext() : b2Shape{
+ return m_next;
+ }
+
+ /// Get the user data that was assigned in the shape definition. Use this to
+ /// store your application specific data.
+ public function GetUserData() : *{
+ return m_userData;
+ }
+
+ /// Set the user data. Use this to store your application specific data.
+ public function SetUserData(data:*) : void
+ {
+ m_userData = data;
+ }
+
+ /// Test a point for containment in this shape. This only works for convex shapes.
+ /// @param xf the shape world transform.
+ /// @param p a point in world coordinates.
+ public virtual function TestPoint(xf:b2XForm, p:b2Vec2) : Boolean {return false};
+
+ /// Perform a ray cast against this shape.
+ /// @param xf the shape world transform.
+ /// @param lambda returns the hit fraction. You can use this to compute the contact point
+ /// p = (1 - lambda) * segment.p1 + lambda * segment.p2.
+ /// @param normal returns the normal at the contact point. If there is no intersection, the normal
+ /// is not set.
+ /// @param segment defines the begin and end point of the ray cast.
+ /// @param maxLambda a number typically in the range [0,1].
+ /// @return true if there was an intersection.
+ public virtual function TestSegment(xf:b2XForm,
+ lambda:Array, // float pointer
+ normal:b2Vec2, // pointer
+ segment:b2Segment,
+ maxLambda:Number) : Boolean {return false};
+
+ /// Given a transform, compute the associated axis aligned bounding box for this shape.
+ /// @param aabb returns the axis aligned box.
+ /// @param xf the world transform of the shape.
+ public virtual function ComputeAABB(aabb:b2AABB, xf:b2XForm) : void {};
+
+ /// Given two transforms, compute the associated swept axis aligned bounding box for this shape.