From 01c5c700647feba596e02cb7a2e672f5301504ff Mon Sep 17 00:00:00 2001 From: Jakob Odersky Date: Mon, 29 Jun 2015 12:32:00 +0200 Subject: Port to scala 2.11 --- build.sbt | 10 ++ src/graphyx/Graphyx.scala | 64 -------- src/graphyx/actors/GUIActor.scala | 31 ---- src/graphyx/actors/PhysicsActor.scala | 73 --------- src/graphyx/graphics/Drawable.scala | 118 -------------- src/graphyx/graphics/GraphicalAABB.scala | 18 --- src/graphyx/graphics/GraphicalBody.scala | 42 ----- src/graphyx/graphics/GraphicalCircle.scala | 22 --- src/graphyx/graphics/GraphicalCollision.scala | 18 --- src/graphyx/graphics/GraphicalDistanceJoint.scala | 19 --- src/graphyx/graphics/GraphicalJoint.scala | 12 -- src/graphyx/graphics/GraphicalObject.scala | 15 -- src/graphyx/graphics/GraphicalPair.scala | 18 --- src/graphyx/graphics/GraphicalRectangle.scala | 18 --- src/graphyx/graphics/GraphicalRegularPolygon.scala | 19 --- src/graphyx/graphics/GraphicalRevoluteJoint.scala | 20 --- src/graphyx/graphics/GraphicalShape.scala | 15 -- src/graphyx/graphics/GraphicalSpringJoint.scala | 18 --- src/graphyx/graphics/GraphicalWorld.scala | 28 ---- src/graphyx/graphics/Parser.scala | 35 ---- src/graphyx/graphics/Scene.scala | 24 --- src/graphyx/gui/AboutHelpFrame.scala | 24 --- src/graphyx/gui/BodyPopup.scala | 41 ----- src/graphyx/gui/Container.scala | 37 ----- src/graphyx/gui/ControlPanel.scala | 40 ----- src/graphyx/gui/GravityPanel.scala | 83 ---------- src/graphyx/gui/InfoPanel.scala | 30 ---- src/graphyx/gui/MainFrame.scala | 25 --- src/graphyx/gui/MainPanel.scala | 77 --------- src/graphyx/gui/MenuHelp.scala | 19 --- src/graphyx/gui/MenuPanel.scala | 12 -- src/graphyx/gui/OptionsPanel.scala | 128 --------------- src/graphyx/gui/PopupMenu.scala | 20 --- src/graphyx/gui/ShapeInfoPanel.scala | 35 ---- src/graphyx/gui/WorldPanel.scala | 179 --------------------- src/graphyx/tests/Atom.scala | 36 ----- src/graphyx/tests/BallStack.scala | 25 --- src/graphyx/tests/Cannon.scala | 59 ------- src/graphyx/tests/Carriage.scala | 55 ------- src/graphyx/tests/Chain.scala | 26 --- src/graphyx/tests/CompositeShape.scala | 36 ----- src/graphyx/tests/Cup.scala | 31 ---- src/graphyx/tests/EmptyTest.scala | 15 -- src/graphyx/tests/Friction.scala | 57 ------- src/graphyx/tests/Friction2.scala | 33 ---- src/graphyx/tests/General1.scala | 126 --------------- src/graphyx/tests/General2.scala | 28 ---- src/graphyx/tests/Joints1.scala | 24 --- src/graphyx/tests/Joints2.scala | 29 ---- src/graphyx/tests/Net.scala | 22 --- src/graphyx/tests/RagdollTest.scala | 26 --- src/graphyx/tests/Restitution.scala | 21 --- src/graphyx/tests/Spring.scala | 23 --- src/graphyx/tests/Stacking.scala | 24 --- src/graphyx/tests/Test.scala | 17 -- src/graphyx/tests/Wave.scala | 34 ---- src/main/scala/graphyx/Graphyx.scala | 61 +++++++ src/main/scala/graphyx/actors/GUIActor.scala | 36 +++++ src/main/scala/graphyx/actors/PhysicsActor.scala | 88 ++++++++++ src/main/scala/graphyx/graphics/Drawable.scala | 118 ++++++++++++++ .../scala/graphyx/graphics/GraphicalAABB.scala | 18 +++ .../scala/graphyx/graphics/GraphicalBody.scala | 42 +++++ .../scala/graphyx/graphics/GraphicalCircle.scala | 22 +++ .../graphyx/graphics/GraphicalCollision.scala | 18 +++ .../graphyx/graphics/GraphicalDistanceJoint.scala | 19 +++ .../scala/graphyx/graphics/GraphicalJoint.scala | 12 ++ .../scala/graphyx/graphics/GraphicalObject.scala | 15 ++ .../scala/graphyx/graphics/GraphicalPair.scala | 18 +++ .../graphyx/graphics/GraphicalRectangle.scala | 18 +++ .../graphyx/graphics/GraphicalRegularPolygon.scala | 19 +++ .../graphyx/graphics/GraphicalRevoluteJoint.scala | 20 +++ .../scala/graphyx/graphics/GraphicalShape.scala | 15 ++ .../graphyx/graphics/GraphicalSpringJoint.scala | 18 +++ .../scala/graphyx/graphics/GraphicalWorld.scala | 28 ++++ src/main/scala/graphyx/graphics/Parser.scala | 35 ++++ src/main/scala/graphyx/graphics/Scene.scala | 24 +++ src/main/scala/graphyx/gui/AboutHelpFrame.scala | 24 +++ src/main/scala/graphyx/gui/BodyPopup.scala | 41 +++++ src/main/scala/graphyx/gui/Container.scala | 37 +++++ src/main/scala/graphyx/gui/ControlPanel.scala | 40 +++++ src/main/scala/graphyx/gui/GravityPanel.scala | 83 ++++++++++ src/main/scala/graphyx/gui/InfoPanel.scala | 30 ++++ src/main/scala/graphyx/gui/MainFrame.scala | 25 +++ src/main/scala/graphyx/gui/MainPanel.scala | 77 +++++++++ src/main/scala/graphyx/gui/MenuHelp.scala | 19 +++ src/main/scala/graphyx/gui/MenuPanel.scala | 12 ++ src/main/scala/graphyx/gui/OptionsPanel.scala | 128 +++++++++++++++ src/main/scala/graphyx/gui/PopupMenu.scala | 20 +++ src/main/scala/graphyx/gui/ShapeInfoPanel.scala | 35 ++++ src/main/scala/graphyx/gui/WorldPanel.scala | 179 +++++++++++++++++++++ src/main/scala/graphyx/tests/Atom.scala | 36 +++++ src/main/scala/graphyx/tests/BallStack.scala | 25 +++ src/main/scala/graphyx/tests/Cannon.scala | 59 +++++++ src/main/scala/graphyx/tests/Carriage.scala | 55 +++++++ src/main/scala/graphyx/tests/Chain.scala | 26 +++ src/main/scala/graphyx/tests/CompositeShape.scala | 36 +++++ src/main/scala/graphyx/tests/Cup.scala | 31 ++++ src/main/scala/graphyx/tests/EmptyTest.scala | 15 ++ src/main/scala/graphyx/tests/Friction.scala | 57 +++++++ src/main/scala/graphyx/tests/Friction2.scala | 33 ++++ src/main/scala/graphyx/tests/General1.scala | 126 +++++++++++++++ src/main/scala/graphyx/tests/General2.scala | 28 ++++ src/main/scala/graphyx/tests/Joints1.scala | 24 +++ src/main/scala/graphyx/tests/Joints2.scala | 29 ++++ src/main/scala/graphyx/tests/Net.scala | 22 +++ src/main/scala/graphyx/tests/RagdollTest.scala | 26 +++ src/main/scala/graphyx/tests/Restitution.scala | 21 +++ src/main/scala/graphyx/tests/Spring.scala | 23 +++ src/main/scala/graphyx/tests/Stacking.scala | 24 +++ src/main/scala/graphyx/tests/Test.scala | 17 ++ src/main/scala/graphyx/tests/Wave.scala | 34 ++++ src/main/scala/sims/collision/AABB.scala | 28 ++++ .../scala/sims/collision/CircleCollision.scala | 22 +++ src/main/scala/sims/collision/Collision.scala | 108 +++++++++++++ src/main/scala/sims/collision/Detector.scala | 21 +++ src/main/scala/sims/collision/GridDetector.scala | 123 ++++++++++++++ src/main/scala/sims/collision/Overlap.scala | 11 ++ src/main/scala/sims/collision/Pair.scala | 24 +++ .../scala/sims/collision/PolyCircleCollision.scala | 36 +++++ src/main/scala/sims/collision/PolyCollision.scala | 53 ++++++ src/main/scala/sims/dynamics/Body.scala | 141 ++++++++++++++++ src/main/scala/sims/dynamics/Circle.scala | 34 ++++ src/main/scala/sims/dynamics/Constraint.scala | 21 +++ src/main/scala/sims/dynamics/Rectangle.scala | 38 +++++ src/main/scala/sims/dynamics/RegularPolygon.scala | 35 ++++ src/main/scala/sims/dynamics/Shape.scala | 97 +++++++++++ src/main/scala/sims/dynamics/World.scala | 164 +++++++++++++++++++ .../scala/sims/dynamics/joints/DistanceJoint.scala | 77 +++++++++ .../scala/sims/dynamics/joints/ForceJoint.scala | 14 ++ src/main/scala/sims/dynamics/joints/Joint.scala | 27 ++++ .../scala/sims/dynamics/joints/RevoluteJoint.scala | 57 +++++++ .../scala/sims/dynamics/joints/SpringJoint.scala | 85 ++++++++++ .../sims/dynamics/joints/test/PrismaticJoint.scala | 84 ++++++++++ .../dynamics/joints/test/UnitCircleJoint.scala | 46 ++++++ src/main/scala/sims/geometry/ConvexPolygon.scala | 56 +++++++ src/main/scala/sims/geometry/Projection.scala | 35 ++++ src/main/scala/sims/geometry/Ray.scala | 49 ++++++ src/main/scala/sims/geometry/Segment.scala | 72 +++++++++ src/main/scala/sims/geometry/Vector2D.scala | 83 ++++++++++ src/main/scala/sims/materials/Material.scala | 7 + src/main/scala/sims/materials/Rubber.scala | 5 + src/main/scala/sims/materials/Steel.scala | 5 + src/main/scala/sims/math/Matrix22.scala | 55 +++++++ src/main/scala/sims/prefabs/Net.scala | 47 ++++++ src/main/scala/sims/prefabs/Prefab.scala | 15 ++ src/main/scala/sims/prefabs/Pylon.scala | 47 ++++++ src/main/scala/sims/prefabs/Ragdoll.scala | 43 +++++ src/main/scala/sims/util/Polar.scala | 17 ++ src/main/scala/sims/util/Positioning.scala | 24 +++ src/main/scala/sims/util/RelativeVector.scala | 24 +++ src/sims/collision/AABB.scala | 28 ---- src/sims/collision/CircleCollision.scala | 22 --- src/sims/collision/Collision.scala | 108 ------------- src/sims/collision/Detector.scala | 21 --- src/sims/collision/GridDetector.scala | 123 -------------- src/sims/collision/Overlap.scala | 11 -- src/sims/collision/Pair.scala | 24 --- src/sims/collision/PolyCircleCollision.scala | 36 ----- src/sims/collision/PolyCollision.scala | 53 ------ src/sims/dynamics/Body.scala | 141 ---------------- src/sims/dynamics/Circle.scala | 34 ---- src/sims/dynamics/Constraint.scala | 21 --- src/sims/dynamics/Rectangle.scala | 38 ----- src/sims/dynamics/RegularPolygon.scala | 35 ---- src/sims/dynamics/Shape.scala | 97 ----------- src/sims/dynamics/World.scala | 164 ------------------- src/sims/dynamics/joints/DistanceJoint.scala | 77 --------- src/sims/dynamics/joints/ForceJoint.scala | 14 -- src/sims/dynamics/joints/Joint.scala | 27 ---- src/sims/dynamics/joints/RevoluteJoint.scala | 57 ------- src/sims/dynamics/joints/SpringJoint.scala | 85 ---------- src/sims/dynamics/joints/test/PrismaticJoint.scala | 84 ---------- .../dynamics/joints/test/UnitCircleJoint.scala | 46 ------ src/sims/geometry/ConvexPolygon.scala | 56 ------- src/sims/geometry/Projection.scala | 35 ---- src/sims/geometry/Ray.scala | 49 ------ src/sims/geometry/Segment.scala | 72 --------- src/sims/geometry/Vector2D.scala | 83 ---------- src/sims/materials/Material.scala | 7 - src/sims/materials/Rubber.scala | 5 - src/sims/materials/Steel.scala | 5 - src/sims/math/Matrix22.scala | 55 ------- src/sims/prefabs/Net.scala | 47 ------ src/sims/prefabs/Prefab.scala | 15 -- src/sims/prefabs/Pylon.scala | 47 ------ src/sims/prefabs/Ragdoll.scala | 43 ----- src/sims/util/Polar.scala | 17 -- src/sims/util/Positioning.scala | 24 --- src/sims/util/RelativeVector.scala | 24 --- 189 files changed, 4081 insertions(+), 4054 deletions(-) create mode 100644 build.sbt delete mode 100644 src/graphyx/Graphyx.scala delete mode 100644 src/graphyx/actors/GUIActor.scala delete mode 100644 src/graphyx/actors/PhysicsActor.scala delete mode 100644 src/graphyx/graphics/Drawable.scala delete mode 100644 src/graphyx/graphics/GraphicalAABB.scala delete mode 100644 src/graphyx/graphics/GraphicalBody.scala delete mode 100644 src/graphyx/graphics/GraphicalCircle.scala delete mode 100644 src/graphyx/graphics/GraphicalCollision.scala delete mode 100644 src/graphyx/graphics/GraphicalDistanceJoint.scala delete mode 100644 src/graphyx/graphics/GraphicalJoint.scala delete mode 100644 src/graphyx/graphics/GraphicalObject.scala delete mode 100644 src/graphyx/graphics/GraphicalPair.scala delete mode 100644 src/graphyx/graphics/GraphicalRectangle.scala delete mode 100644 src/graphyx/graphics/GraphicalRegularPolygon.scala delete mode 100644 src/graphyx/graphics/GraphicalRevoluteJoint.scala delete mode 100644 src/graphyx/graphics/GraphicalShape.scala delete mode 100644 src/graphyx/graphics/GraphicalSpringJoint.scala delete mode 100644 src/graphyx/graphics/GraphicalWorld.scala delete mode 100644 src/graphyx/graphics/Parser.scala delete mode 100644 src/graphyx/graphics/Scene.scala delete mode 100644 src/graphyx/gui/AboutHelpFrame.scala delete mode 100644 src/graphyx/gui/BodyPopup.scala delete mode 100644 src/graphyx/gui/Container.scala delete mode 100644 src/graphyx/gui/ControlPanel.scala delete mode 100644 src/graphyx/gui/GravityPanel.scala delete mode 100644 src/graphyx/gui/InfoPanel.scala delete mode 100644 src/graphyx/gui/MainFrame.scala delete mode 100644 src/graphyx/gui/MainPanel.scala delete mode 100644 src/graphyx/gui/MenuHelp.scala delete mode 100644 src/graphyx/gui/MenuPanel.scala delete mode 100644 src/graphyx/gui/OptionsPanel.scala delete mode 100644 src/graphyx/gui/PopupMenu.scala delete mode 100644 src/graphyx/gui/ShapeInfoPanel.scala delete mode 100644 src/graphyx/gui/WorldPanel.scala delete mode 100644 src/graphyx/tests/Atom.scala delete mode 100644 src/graphyx/tests/BallStack.scala delete mode 100644 src/graphyx/tests/Cannon.scala delete mode 100644 src/graphyx/tests/Carriage.scala delete mode 100644 src/graphyx/tests/Chain.scala delete mode 100644 src/graphyx/tests/CompositeShape.scala delete mode 100644 src/graphyx/tests/Cup.scala delete mode 100644 src/graphyx/tests/EmptyTest.scala delete mode 100644 src/graphyx/tests/Friction.scala delete mode 100644 src/graphyx/tests/Friction2.scala delete mode 100644 src/graphyx/tests/General1.scala delete mode 100644 src/graphyx/tests/General2.scala delete mode 100644 src/graphyx/tests/Joints1.scala delete mode 100644 src/graphyx/tests/Joints2.scala delete mode 100644 src/graphyx/tests/Net.scala delete mode 100644 src/graphyx/tests/RagdollTest.scala delete mode 100644 src/graphyx/tests/Restitution.scala delete mode 100644 src/graphyx/tests/Spring.scala delete mode 100644 src/graphyx/tests/Stacking.scala delete mode 100644 src/graphyx/tests/Test.scala delete mode 100644 src/graphyx/tests/Wave.scala create mode 100644 src/main/scala/graphyx/Graphyx.scala create mode 100644 src/main/scala/graphyx/actors/GUIActor.scala create mode 100644 src/main/scala/graphyx/actors/PhysicsActor.scala create mode 100644 src/main/scala/graphyx/graphics/Drawable.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalAABB.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalBody.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalCircle.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalCollision.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalDistanceJoint.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalJoint.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalObject.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalPair.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalRectangle.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalRegularPolygon.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalRevoluteJoint.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalShape.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalSpringJoint.scala create mode 100644 src/main/scala/graphyx/graphics/GraphicalWorld.scala create mode 100644 src/main/scala/graphyx/graphics/Parser.scala create mode 100644 src/main/scala/graphyx/graphics/Scene.scala create mode 100644 src/main/scala/graphyx/gui/AboutHelpFrame.scala create mode 100644 src/main/scala/graphyx/gui/BodyPopup.scala create mode 100644 src/main/scala/graphyx/gui/Container.scala create mode 100644 src/main/scala/graphyx/gui/ControlPanel.scala create mode 100644 src/main/scala/graphyx/gui/GravityPanel.scala create mode 100644 src/main/scala/graphyx/gui/InfoPanel.scala create mode 100644 src/main/scala/graphyx/gui/MainFrame.scala create mode 100644 src/main/scala/graphyx/gui/MainPanel.scala create mode 100644 src/main/scala/graphyx/gui/MenuHelp.scala create mode 100644 src/main/scala/graphyx/gui/MenuPanel.scala create mode 100644 src/main/scala/graphyx/gui/OptionsPanel.scala create mode 100644 src/main/scala/graphyx/gui/PopupMenu.scala create mode 100644 src/main/scala/graphyx/gui/ShapeInfoPanel.scala create mode 100644 src/main/scala/graphyx/gui/WorldPanel.scala create mode 100644 src/main/scala/graphyx/tests/Atom.scala create mode 100644 src/main/scala/graphyx/tests/BallStack.scala create mode 100644 src/main/scala/graphyx/tests/Cannon.scala create mode 100644 src/main/scala/graphyx/tests/Carriage.scala create mode 100644 src/main/scala/graphyx/tests/Chain.scala create mode 100644 src/main/scala/graphyx/tests/CompositeShape.scala create mode 100644 src/main/scala/graphyx/tests/Cup.scala create mode 100644 src/main/scala/graphyx/tests/EmptyTest.scala create mode 100644 src/main/scala/graphyx/tests/Friction.scala create mode 100644 src/main/scala/graphyx/tests/Friction2.scala create mode 100644 src/main/scala/graphyx/tests/General1.scala create mode 100644 src/main/scala/graphyx/tests/General2.scala create mode 100644 src/main/scala/graphyx/tests/Joints1.scala create mode 100644 src/main/scala/graphyx/tests/Joints2.scala create mode 100644 src/main/scala/graphyx/tests/Net.scala create mode 100644 src/main/scala/graphyx/tests/RagdollTest.scala create mode 100644 src/main/scala/graphyx/tests/Restitution.scala create mode 100644 src/main/scala/graphyx/tests/Spring.scala create mode 100644 src/main/scala/graphyx/tests/Stacking.scala create mode 100644 src/main/scala/graphyx/tests/Test.scala create mode 100644 src/main/scala/graphyx/tests/Wave.scala create mode 100644 src/main/scala/sims/collision/AABB.scala create mode 100644 src/main/scala/sims/collision/CircleCollision.scala create mode 100644 src/main/scala/sims/collision/Collision.scala create mode 100644 src/main/scala/sims/collision/Detector.scala create mode 100644 src/main/scala/sims/collision/GridDetector.scala create mode 100644 src/main/scala/sims/collision/Overlap.scala create mode 100644 src/main/scala/sims/collision/Pair.scala create mode 100644 src/main/scala/sims/collision/PolyCircleCollision.scala create mode 100644 src/main/scala/sims/collision/PolyCollision.scala create mode 100644 src/main/scala/sims/dynamics/Body.scala create mode 100644 src/main/scala/sims/dynamics/Circle.scala create mode 100644 src/main/scala/sims/dynamics/Constraint.scala create mode 100644 src/main/scala/sims/dynamics/Rectangle.scala create mode 100644 src/main/scala/sims/dynamics/RegularPolygon.scala create mode 100644 src/main/scala/sims/dynamics/Shape.scala create mode 100644 src/main/scala/sims/dynamics/World.scala create mode 100644 src/main/scala/sims/dynamics/joints/DistanceJoint.scala create mode 100644 src/main/scala/sims/dynamics/joints/ForceJoint.scala create mode 100644 src/main/scala/sims/dynamics/joints/Joint.scala create mode 100644 src/main/scala/sims/dynamics/joints/RevoluteJoint.scala create mode 100644 src/main/scala/sims/dynamics/joints/SpringJoint.scala create mode 100644 src/main/scala/sims/dynamics/joints/test/PrismaticJoint.scala create mode 100644 src/main/scala/sims/dynamics/joints/test/UnitCircleJoint.scala create mode 100644 src/main/scala/sims/geometry/ConvexPolygon.scala create mode 100644 src/main/scala/sims/geometry/Projection.scala create mode 100644 src/main/scala/sims/geometry/Ray.scala create mode 100644 src/main/scala/sims/geometry/Segment.scala create mode 100644 src/main/scala/sims/geometry/Vector2D.scala create mode 100644 src/main/scala/sims/materials/Material.scala create mode 100644 src/main/scala/sims/materials/Rubber.scala create mode 100644 src/main/scala/sims/materials/Steel.scala create mode 100644 src/main/scala/sims/math/Matrix22.scala create mode 100644 src/main/scala/sims/prefabs/Net.scala create mode 100644 src/main/scala/sims/prefabs/Prefab.scala create mode 100644 src/main/scala/sims/prefabs/Pylon.scala create mode 100644 src/main/scala/sims/prefabs/Ragdoll.scala create mode 100644 src/main/scala/sims/util/Polar.scala create mode 100644 src/main/scala/sims/util/Positioning.scala create mode 100644 src/main/scala/sims/util/RelativeVector.scala delete mode 100644 src/sims/collision/AABB.scala delete mode 100644 src/sims/collision/CircleCollision.scala delete mode 100644 src/sims/collision/Collision.scala delete mode 100644 src/sims/collision/Detector.scala delete mode 100644 src/sims/collision/GridDetector.scala delete mode 100644 src/sims/collision/Overlap.scala delete mode 100644 src/sims/collision/Pair.scala delete mode 100644 src/sims/collision/PolyCircleCollision.scala delete mode 100644 src/sims/collision/PolyCollision.scala delete mode 100644 src/sims/dynamics/Body.scala delete mode 100644 src/sims/dynamics/Circle.scala delete mode 100644 src/sims/dynamics/Constraint.scala delete mode 100644 src/sims/dynamics/Rectangle.scala delete mode 100644 src/sims/dynamics/RegularPolygon.scala delete mode 100644 src/sims/dynamics/Shape.scala delete mode 100644 src/sims/dynamics/World.scala delete mode 100644 src/sims/dynamics/joints/DistanceJoint.scala delete mode 100644 src/sims/dynamics/joints/ForceJoint.scala delete mode 100644 src/sims/dynamics/joints/Joint.scala delete mode 100644 src/sims/dynamics/joints/RevoluteJoint.scala delete mode 100644 src/sims/dynamics/joints/SpringJoint.scala delete mode 100644 src/sims/dynamics/joints/test/PrismaticJoint.scala delete mode 100644 src/sims/dynamics/joints/test/UnitCircleJoint.scala delete mode 100644 src/sims/geometry/ConvexPolygon.scala delete mode 100644 src/sims/geometry/Projection.scala delete mode 100644 src/sims/geometry/Ray.scala delete mode 100644 src/sims/geometry/Segment.scala delete mode 100644 src/sims/geometry/Vector2D.scala delete mode 100644 src/sims/materials/Material.scala delete mode 100644 src/sims/materials/Rubber.scala delete mode 100644 src/sims/materials/Steel.scala delete mode 100644 src/sims/math/Matrix22.scala delete mode 100644 src/sims/prefabs/Net.scala delete mode 100644 src/sims/prefabs/Prefab.scala delete mode 100644 src/sims/prefabs/Pylon.scala delete mode 100644 src/sims/prefabs/Ragdoll.scala delete mode 100644 src/sims/util/Polar.scala delete mode 100644 src/sims/util/Positioning.scala delete mode 100644 src/sims/util/RelativeVector.scala diff --git a/build.sbt b/build.sbt new file mode 100644 index 0000000..24c097a --- /dev/null +++ b/build.sbt @@ -0,0 +1,10 @@ +name := "sims" + +version := "1.1" + +scalaVersion := "2.11.7" + +libraryDependencies ++= Seq( + "org.scala-lang.modules" %% "scala-swing" % "2.0.0-M2", + "com.typesafe.akka" %% "akka-actor" % "2.3.11" +) diff --git a/src/graphyx/Graphyx.scala b/src/graphyx/Graphyx.scala deleted file mode 100644 index 5720566..0000000 --- a/src/graphyx/Graphyx.scala +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx - -import graphyx.actors._ -import graphyx.graphics._ -import graphyx.tests._ -import sims.geometry._ -import sims.dynamics._ - -object Graphyx{ - val tests: List[graphyx.tests.Test] = List( - CompositeShape, - Joints1, - Joints2, - Spring, - Atom, - Chain, - Wave, - Net, - Stacking, - BallStack, - Cup, - Friction, - Friction2, - Restitution, - RagdollTest, - Carriage, - General1, - General2, - Cannon, - EmptyTest - ) - - private var _test: graphyx.tests.Test = tests(0) - def test = _test - def test_=(t: graphyx.tests.Test) = { - t.world.time = 0 - t.world.clear() - t.init() - physicsActor ! SetWorld(t.world) - _test = t - } - - val physicsActor = new PhysicsActor - val guiActor = new GUIActor - - def main(args: Array[String]): Unit = { - test.init() - physicsActor.world = test.world - guiActor.start() - physicsActor.start() - } - - def exit() = { - guiActor.container.exitGUI - guiActor ! Exit - physicsActor ! Exit - } -} diff --git a/src/graphyx/actors/GUIActor.scala b/src/graphyx/actors/GUIActor.scala deleted file mode 100644 index 0116551..0000000 --- a/src/graphyx/actors/GUIActor.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.actors - -import graphyx.graphics._ -import scala.actors._ - -class GUIActor extends Actor{ - val container = new graphyx.gui.Container - - var continue = true - - def act() = { - container.show() - println("GUI actor started.") - while (continue) { - receive { - case Exit => { - continue = false - } - case s @ Scene(_) => container.update(s) - case other => println("Engine received unknown command: " + other) - } - } - println("GUI actor exited.") - } -} diff --git a/src/graphyx/actors/PhysicsActor.scala b/src/graphyx/actors/PhysicsActor.scala deleted file mode 100644 index 0bc7faf..0000000 --- a/src/graphyx/actors/PhysicsActor.scala +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.actors - -import graphyx._ -import graphyx.graphics._ -import sims.dynamics._ -import scala.actors._ -class PhysicsActor extends Actor{ - var world = new World - - var continue = true - var simulate = false - - private var _fps = 0 - def fps = _fps - - def act{ - println("Physics actor started.") - while (continue) { - - var t0 = System.nanoTime - - if (simulate) { - world.step() - } - - Graphyx.guiActor ! new Scene(world) {override val fps = _fps} - - receiveWithin(0) { - case TIMEOUT => () - - case Stop => { - simulate = false - println("Simulation stopped.") - } - case Start => { - simulate = true - println("Simulation started.") - } - case Exit => { - continue = false - } - case sw @ SetWorld(w: World) => world = w - - case FireEvent => Graphyx.test.fireEvent() - - case other => println("Engine received unknown command: '" + other + "'") - } - - val h = (System.nanoTime - t0) / 1000000 - val f = 60 - val T = (1.0/f) * 1000 - if (T-h > 0) - Thread.sleep((T-h).toLong) - _fps = (1.0/((System.nanoTime - t0) / 1000000000.0)).toInt - //println((1.0/((System.nanoTime - t0) / 1000000000.0)).toInt) - } - println("Physics actor exited.") - } -} - -case object Start -case object Stop -case object Exit -case class SetWorld(world: World) -case object FireEvent - - diff --git a/src/graphyx/graphics/Drawable.scala b/src/graphyx/graphics/Drawable.scala deleted file mode 100644 index 07f3491..0000000 --- a/src/graphyx/graphics/Drawable.scala +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.geometry._ - -/**Enthaelt Methoden und Felder fuer graphische Darstellungen. - * Alle Klassen die dieses Trait implementieren koennen graphisch dargestellt werden.*/ -trait Drawable { - - /**Java Graphics Objekt zur graphischen Darstellung*/ - var g: java.awt.Graphics2D = _ - - /**Anzahl von Pixeln pro Meter.*/ - var ppm: Double = 39.37007874015748 * 96 //ppm = i/m * p/i - - /**Skala in der die graphischen Objekte gezeichnet werden.*/ - var scale: Double = 1.0/100.0 - - /**Hoehe des Fensters in Pixeln.*/ - var windowHeight = 0 - - /**Korrigiert einen Y-Wert in Bildschirmkoordinaten zu seinem kartesischen Aequivalent. - * @param y zu korrigierender Wert*/ - def correctY(y: Double) = windowHeight - y - - /**Malt eine Linie auf g. - * @param startPoint Startpunkt in Weltkoordinaten - * @param endPoint Endpunkt in Weltkoordinaten*/ - def drawLine(startPoint: Vector2D, endPoint: Vector2D) = { - val x1 = startPoint.x * scale * ppm - val y1 = correctY(startPoint.y * scale * ppm) - val x2 = endPoint.x * scale * ppm - val y2 = correctY(endPoint.y * scale * ppm) - g.drawLine(x1.toInt, y1.toInt, x2.toInt, y2.toInt) - } - - /**Malt ein massives Polygon auf g. - * @param points Eckpunkte des Polygons in Weltkoordinaten*/ - def fillPolygon(points: Seq[Vector2D]) = { - val xs = points map ((v: Vector2D) => (v.x * scale * ppm).toInt) - val ys = points map ((v: Vector2D) => correctY((v.y) * scale * ppm).toInt) - g.fillPolygon(xs.toArray, ys.toArray, points.length) - } - - /**Malt ein Polygon auf g. - * @param points Eckpunkte des Polygons in Weltkoordinaten*/ - def drawPolygon(points: Seq[Vector2D]) = { - val xs = points map ((v: Vector2D) => (v.x * scale * ppm).toInt) - val ys = points map ((v: Vector2D) => correctY((v.y) * scale * ppm).toInt) - g.drawPolygon(xs.toArray, ys.toArray, points.length) - } - - /**Malt einen massiven Kreis auf g. - * @param center Mitte des Kreises in Weltkoordinaten - * @param radius Radius des Kreises*/ - def fillCircle(center: Vector2D, radius: Double) = { - g.fillOval(((center.x - radius) * scale * ppm).toInt, - correctY((center.y + radius) * scale * ppm).toInt, - (radius * scale * ppm * 2).toInt, - (radius * scale * ppm * 2).toInt) - } - - /**Malt einen Kreis auf g. - * @param center Mitte des Kreises in Weltkoordinaten - * @param radius Radius des Kreises*/ - def drawCircle(center: Vector2D, radius: Double) = { - g.drawOval(((center.x - radius) * scale * ppm).toInt, - correctY((center.y + radius) * scale * ppm).toInt, - (radius * scale * ppm * 2).toInt, - (radius * scale * ppm * 2).toInt) - } - - /**Malt einen Punkt auf g. - *

- * Der Punkt wird von einem Kreis umgeben. - * @param point Punkt in Weltkoordinaten*/ - def drawPoint(point: Vector2D) = { - val radius = 4 //in pixel - g.drawLine((point.x * scale * ppm).toInt, - correctY(point.y * scale * ppm).toInt - radius, - (point.x * scale * ppm).toInt, - correctY(point.y * scale * ppm).toInt + radius) - g.drawLine((point.x * scale * ppm).toInt - radius, - correctY(point.y * scale * ppm).toInt, - (point.x * scale * ppm).toInt + radius, - correctY(point.y * scale * ppm).toInt) - g.drawOval((point.x * scale * ppm).toInt - radius, - correctY(point.y * scale * ppm).toInt - radius, - (radius * 2).toInt, - (radius * 2).toInt) - - } - - - /**Malt einen Vektor auf g. - * @param v Vektor in Weltkoordinaten - * @param p Ursprungspunkt in Weltkoordinaten - */ - def drawVector(v: Vector2D, p: Vector2D) = { - if (!v.isNull) { - val ep = p + v - val a1 = ep - ((v.unit rotate (Math.Pi / 6)) * 0.08) - val a2 = ep - ((v.unit rotate (-Math.Pi / 6)) * 0.08) - - g.drawLine((p.x * scale * ppm).toInt, correctY(p.y * scale * ppm).toInt, (ep.x * scale * ppm).toInt, correctY(ep.y * scale * ppm).toInt) - g.drawLine((a1.x * scale * ppm).toInt, correctY(a1.y * scale * ppm).toInt, (ep.x * scale * ppm).toInt, correctY(ep.y * scale * ppm).toInt) - g.drawLine((a2.x * scale * ppm).toInt, correctY(a2.y * scale * ppm).toInt, (ep.x * scale * ppm).toInt, correctY(ep.y * scale * ppm).toInt) - } - } - - /**Stellt das graphische Objekt dar.*/ - def draw(): Unit -} \ No newline at end of file diff --git a/src/graphyx/graphics/GraphicalAABB.scala b/src/graphyx/graphics/GraphicalAABB.scala deleted file mode 100644 index cb3694b..0000000 --- a/src/graphyx/graphics/GraphicalAABB.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.collision._ -class GraphicalAABB(val real: AABB) extends AABB(real.minVertex, real.maxVertex) with GraphicalObject { - override def draw() = { - g.setColor(java.awt.Color.BLACK) - g.drawRect((minVertex.x * scale * ppm).toInt, - correctY(maxVertex.y * scale * ppm).toInt, - ((maxVertex - minVertex).x * scale * ppm).toInt, - ((maxVertex - minVertex).y * scale * ppm).toInt) - } -} diff --git a/src/graphyx/graphics/GraphicalBody.scala b/src/graphyx/graphics/GraphicalBody.scala deleted file mode 100644 index c78ea51..0000000 --- a/src/graphyx/graphics/GraphicalBody.scala +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.dynamics._ - -case class GraphicalBody(real: Body) extends GraphicalObject { - val pos = real.pos - val fixed = real.fixed - val monitor = real.monitor - def draw() = { - val radius = 4 - val posX = (pos.x * scale * ppm).toInt - val posY = correctY(pos.y * scale * ppm).toInt - g.setColor(java.awt.Color.yellow) - g.fillArc(posX - radius, - posY - radius, - (radius * 2).toInt, - (radius * 2).toInt, - 0, 90) - g.fillArc(posX - radius, - posY - radius, - (radius * 2).toInt, - (radius * 2).toInt, - 180, 90) - g.setColor(java.awt.Color.black) - g.fillArc(posX - radius, - posY - radius, - (radius * 2).toInt, - (radius * 2).toInt, - 90, 90) - g.fillArc(posX - radius, - posY - radius, - (radius * 2).toInt, - (radius * 2).toInt, - 270, 90) - } -} diff --git a/src/graphyx/graphics/GraphicalCircle.scala b/src/graphyx/graphics/GraphicalCircle.scala deleted file mode 100644 index ffbd7a6..0000000 --- a/src/graphyx/graphics/GraphicalCircle.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims._ -import geometry._ -import dynamics._ -class GraphicalCircle(val real: Circle) extends Circle(real.radius, real.density) with GraphicalShape{ - override def draw() = { - //val b = Math.min(density / 100 * 255, 255) - //g.setColor(new java.awt.Color(0,0,255, b.toInt)) - g.setColor(java.awt.Color.blue) - fillCircle(pos, real.radius) - g.setColor(java.awt.Color.BLACK) - drawCircle(pos, real.radius) - this.drawLine(pos, pos + (Vector2D.i rotate rotation) * real.radius) - } -} diff --git a/src/graphyx/graphics/GraphicalCollision.scala b/src/graphyx/graphics/GraphicalCollision.scala deleted file mode 100644 index 5589f8c..0000000 --- a/src/graphyx/graphics/GraphicalCollision.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.collision._ - -case class GraphicalCollision(real: Collision) extends GraphicalObject{ - val points = real.points - val normal = real.normal - def draw() = { - g.setColor(java.awt.Color.GREEN) - for (p <- points) {drawPoint(p); drawVector(normal, p)} - } -} \ No newline at end of file diff --git a/src/graphyx/graphics/GraphicalDistanceJoint.scala b/src/graphyx/graphics/GraphicalDistanceJoint.scala deleted file mode 100644 index 4a6e49d..0000000 --- a/src/graphyx/graphics/GraphicalDistanceJoint.scala +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.dynamics.joints._ - -case class GraphicalDistanceJoint(real: DistanceJoint) extends GraphicalJoint { - val connection1 = real.connection1 - val connection2 = real.connection2 - - def draw() = { - g.setColor(java.awt.Color.BLACK) - drawLine(connection1, connection2) - } -} diff --git a/src/graphyx/graphics/GraphicalJoint.scala b/src/graphyx/graphics/GraphicalJoint.scala deleted file mode 100644 index 27d4f83..0000000 --- a/src/graphyx/graphics/GraphicalJoint.scala +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.dynamics.joints._ -trait GraphicalJoint extends GraphicalObject{ - val real: Joint -} diff --git a/src/graphyx/graphics/GraphicalObject.scala b/src/graphyx/graphics/GraphicalObject.scala deleted file mode 100644 index 3c56de6..0000000 --- a/src/graphyx/graphics/GraphicalObject.scala +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -/**Only copies functional info! (e.g. Graphical world does not include shapes, bodies).*/ -trait GraphicalObject extends Drawable{ - - /**Pointer to real object.*/ - val real: AnyRef - def draw(): Unit -} diff --git a/src/graphyx/graphics/GraphicalPair.scala b/src/graphyx/graphics/GraphicalPair.scala deleted file mode 100644 index 72e72ae..0000000 --- a/src/graphyx/graphics/GraphicalPair.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.collision._ -case class GraphicalPair(real: Pair) extends GraphicalObject{ - val pos1 = real.s1.pos - val pos2 = real.s2.pos - - def draw() = { - g.setColor(java.awt.Color.ORANGE) - drawLine(pos1, pos2) - } -} diff --git a/src/graphyx/graphics/GraphicalRectangle.scala b/src/graphyx/graphics/GraphicalRectangle.scala deleted file mode 100644 index 05dfa76..0000000 --- a/src/graphyx/graphics/GraphicalRectangle.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims._ -import sims.dynamics._ -class GraphicalRectangle(val real: Rectangle) extends Rectangle(real.halfWidth, real.halfHeight, real.density) with GraphicalShape { - override def draw() = { - g.setColor(java.awt.Color.red) - fillPolygon(vertices) - g.setColor(java.awt.Color.BLACK) - drawPolygon(vertices) - } -} \ No newline at end of file diff --git a/src/graphyx/graphics/GraphicalRegularPolygon.scala b/src/graphyx/graphics/GraphicalRegularPolygon.scala deleted file mode 100644 index fff8a9e..0000000 --- a/src/graphyx/graphics/GraphicalRegularPolygon.scala +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims._ -import geometry._ -import dynamics._ -class GraphicalRegularPolygon(val real: RegularPolygon) extends RegularPolygon(real.n, real.radius, real.density) with GraphicalShape{ - override def draw() = { - g.setColor(java.awt.Color.orange) - fillPolygon(vertices) - g.setColor(java.awt.Color.BLACK) - drawPolygon(vertices) - } -} \ No newline at end of file diff --git a/src/graphyx/graphics/GraphicalRevoluteJoint.scala b/src/graphyx/graphics/GraphicalRevoluteJoint.scala deleted file mode 100644 index 940a862..0000000 --- a/src/graphyx/graphics/GraphicalRevoluteJoint.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.geometry._ -import sims.dynamics.joints._ - -case class GraphicalRevoluteJoint(real: RevoluteJoint) extends GraphicalJoint { - val connection1 = real.connection1 - - def draw(): Unit = { - g.setColor(java.awt.Color.darkGray) - drawPoint(connection1) - } - -} diff --git a/src/graphyx/graphics/GraphicalShape.scala b/src/graphyx/graphics/GraphicalShape.scala deleted file mode 100644 index 256c041..0000000 --- a/src/graphyx/graphics/GraphicalShape.scala +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.dynamics._ -trait GraphicalShape extends Shape with GraphicalObject{ - val real: Shape - override val uid: Int = real.uid - pos = real.pos - rotation = real.rotation -} \ No newline at end of file diff --git a/src/graphyx/graphics/GraphicalSpringJoint.scala b/src/graphyx/graphics/GraphicalSpringJoint.scala deleted file mode 100644 index dbd9d5f..0000000 --- a/src/graphyx/graphics/GraphicalSpringJoint.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.dynamics.joints._ - -case class GraphicalSpringJoint(real: SpringJoint) extends GraphicalJoint { - val connection1 = real.connection1 - val connection2 = real.connection2 - def draw(): Unit = { - g.setColor(java.awt.Color.GRAY) - drawLine(connection1, connection2) - } -} diff --git a/src/graphyx/graphics/GraphicalWorld.scala b/src/graphyx/graphics/GraphicalWorld.scala deleted file mode 100644 index abc9cbb..0000000 --- a/src/graphyx/graphics/GraphicalWorld.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.dynamics._ -case class GraphicalWorld(real: World){ - val time = real.time - val timeStep = real.timeStep - val iterations = real.iterations - val overCWarning = real.overCWarning - val gravity = real.gravity - val monitorResults = for (m <- real.monitors) yield - new MonitorResult(m, - for (b <- real.bodies.toList; if (b.monitor)) yield (b.uid, m._1, m._2(b)) - ) - val monitorFlatResults = for (b <- real.bodies; m <- real.monitors; if (b.monitor)) yield (b.uid, m._1, m._2(b)) - val enableCollisionDetection = real.enableCollisionDetection - val enablePositionCorrection = real.enablePositionCorrection -} - -class MonitorResult ( - val monitor: (String, Body => Any), - val results: List[(Int, String, Any)] -) diff --git a/src/graphyx/graphics/Parser.scala b/src/graphyx/graphics/Parser.scala deleted file mode 100644 index 785d985..0000000 --- a/src/graphyx/graphics/Parser.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.collision._ -import sims.dynamics._ -import sims.dynamics.joints._ -object Parser { - - val throwOnUnknown = false - - def toGraphical(real: Shape) = real match { - case c: Circle => new GraphicalCircle(c) - case r: Rectangle => new GraphicalRectangle(r) - case p: RegularPolygon => new GraphicalRegularPolygon(p) - case _ => throw new IllegalArgumentException("Cannot cast '" + real.getClass + "' to a graphical object.") - } - - def toGraphical(real: Joint) = real match { - case j: DistanceJoint => new GraphicalDistanceJoint(j) - case j: SpringJoint => new GraphicalSpringJoint(j) - case j: RevoluteJoint => new GraphicalRevoluteJoint(j) - case j: Joint => if (!throwOnUnknown) new GraphicalJoint{override val real = j; def draw = ()} - else throw new IllegalArgumentException("Cannot cast '" + real.getClass + "' to a graphical object.") - } - - def toGraphical(real: Collision) = new GraphicalCollision(real) - def toGraphical(real: Pair) = new GraphicalPair(real) - def toGraphical(real: AABB) = new GraphicalAABB(real) - def toGraphical(real: Body) = new GraphicalBody(real) -} diff --git a/src/graphyx/graphics/Scene.scala b/src/graphyx/graphics/Scene.scala deleted file mode 100644 index bb1fd9e..0000000 --- a/src/graphyx/graphics/Scene.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.graphics - -import sims.geometry._ -import sims.collision._ -import sims.dynamics._ -import sims.dynamics.joints._ -import collection.mutable._ - -case class Scene(real: World) { - val world: GraphicalWorld = GraphicalWorld(real) - val shapes = for (s: Shape <- real.shapes) yield Parser.toGraphical(s) - val joints = for (j: Joint <- real.joints) yield Parser.toGraphical(j) - val bodies = for (b: Body <- real.bodies) yield Parser.toGraphical(b) - val collisions = for (c: Collision <- real.detector.collisions) yield Parser.toGraphical(c) - val pairs = for (p: Pair <- real.detector.asInstanceOf[GridDetector].pairs) yield Parser.toGraphical(p) - val aabbs = for (s: Shape <- real.shapes) yield Parser.toGraphical(s.AABB) - val fps = 0 -} diff --git a/src/graphyx/gui/AboutHelpFrame.scala b/src/graphyx/gui/AboutHelpFrame.scala deleted file mode 100644 index 52bfb73..0000000 --- a/src/graphyx/gui/AboutHelpFrame.scala +++ /dev/null @@ -1,24 +0,0 @@ -package graphyx.gui - -import graphyx.actors._ -import graphyx.gui._ -import scala.swing._ -import scala.swing.event._ - -class AboutHelpFrame extends Frame { - title = "About" - contents = new TextArea( - """|Graphyx, testing and visualization tool for SiMS. - | - |copyright (c) 2009 Jakob Odersky - |SiMS and Graphyx are made available under the MIT License - | - |http://sourceforge.net/projects/simplemechanics/ - | - |Version 1.1""".stripMargin - ) {editable = false} -} - -object AboutHelpFrame { - val frame = new AboutHelpFrame -} diff --git a/src/graphyx/gui/BodyPopup.scala b/src/graphyx/gui/BodyPopup.scala deleted file mode 100644 index 998a440..0000000 --- a/src/graphyx/gui/BodyPopup.scala +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import scala.swing._ -import scala.swing.event._ -import sims.dynamics._ -import graphyx.graphics._ - -class BodyPopup extends PopupMenu { - private var b: Body = _ - def body = b - def body_=(newBody: Body) = { - b = newBody - chckFixed.selected = b.fixed - chckMonitor.selected = b.monitor - } - - val chckMonitor = new CheckMenuItem("Monitor") - val chckFixed = new CheckMenuItem("Fixed") - val btnClose = new MenuItem("Close") - - add(chckMonitor) - add(chckFixed) - add(btnClose) - listenTo(chckMonitor, chckFixed, btnClose) - reactions += { - case ButtonClicked(b) => {setVisible(false) - b match { - case `chckMonitor` => body.monitor = chckMonitor.selected - case `chckFixed` => body.fixed = chckFixed.selected - case `btnClose` => () - case _ => () - } - } - } -} \ No newline at end of file diff --git a/src/graphyx/gui/Container.scala b/src/graphyx/gui/Container.scala deleted file mode 100644 index 80886f8..0000000 --- a/src/graphyx/gui/Container.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import sims.dynamics._ -import graphyx.graphics._ -import java.io._ -class Container { - val mainFrame = new MainFrame(this) - - //val plotFrames = new ArrayBuffer[plot.PlotFrame[Body]] - - var scene: Scene = Scene(new World) - - def show() = { - mainFrame.visible = true - } - - def update(s: Scene) = { - scene = s - mainFrame.mainPanel.controlPanel.update() - mainFrame.mainPanel.worldPanel.update() - mainFrame.mainPanel.infoPanel.update() - mainFrame.mainPanel.optionsPanel.update() - mainFrame.mainPanel.gravityPanel.update() - } - - def exitGUI() = { - mainFrame.dispose - AboutHelpFrame.frame.dispose - //plotFrames.foreach(_.dispose) - } -} diff --git a/src/graphyx/gui/ControlPanel.scala b/src/graphyx/gui/ControlPanel.scala deleted file mode 100644 index 2cde7e6..0000000 --- a/src/graphyx/gui/ControlPanel.scala +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import graphyx._ -import graphyx.actors._ -import graphyx.gui._ -import scala.swing._ -import scala.swing.event._ - -class ControlPanel(container: Container) extends BoxPanel(Orientation.Horizontal) { - val btnStart = new Button {text = "Start"} //; icon = new javax.swing.ImageIcon("""play.png"""); tooltip = "Start"} - val btnStep = new Button {text = "Step"} - val btnStop = new Button {text = "Stop"} - val btnExit = new Button {text = "Exit"} - val btnFire = new Button {text = "Fire!"} - val btnReset = new Button {text = "Reset"} - val cboTest = new ComboBox(Graphyx.tests) - - contents ++= List(btnStart, btnStep, btnStop, btnExit, new Separator, btnFire, btnReset, cboTest) - - listenTo(btnStart, btnStep, btnStop, btnExit, btnFire, btnReset, cboTest.selection) - reactions += { - case ButtonClicked(`btnStart`) => Graphyx.physicsActor ! Start - case ButtonClicked(`btnStop`) => Graphyx.physicsActor ! Stop - case ButtonClicked(`btnStep`) => Graphyx.physicsActor.world.step() - case ButtonClicked(`btnExit`) => Graphyx.exit - case ButtonClicked(`btnFire`) => Graphyx.physicsActor ! FireEvent - case ButtonClicked(`btnReset`) => Graphyx.test = Graphyx.tests(cboTest.selection.index) - case SelectionChanged(`cboTest`) => Graphyx.test = Graphyx.tests(cboTest.selection.index) - } - - def update() { - btnFire.enabled = Graphyx.test.enableEvent - } -} diff --git a/src/graphyx/gui/GravityPanel.scala b/src/graphyx/gui/GravityPanel.scala deleted file mode 100644 index bdf5245..0000000 --- a/src/graphyx/gui/GravityPanel.scala +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import scala.swing._ -import scala.swing.event._ -import scala.swing.GridBagPanel._ -import sims.geometry._ - -class GravityPanel(container: Container) extends GridBagPanel{ - - val c = new Constraints - c.fill = Fill.Both - this.border = Swing.EmptyBorder(3,3,3,3) - - val sldX = new Slider {max = 500; min = -500; preferredSize = minimumSize} - val lblX = new Label("0.0") - val sldY = new Slider {max = 500; min = -500; preferredSize = minimumSize} - val lblY = new Label("-9.81") - - c.gridx = 0 - c.gridy = 0 - c.weightx = 1.0 - c.weighty = 0.0 - super.add(new Label("Gravity"), c) - - c.gridx = 0 - c.gridy = 1 - c.weightx = 1.0 - c.weighty = 0.0 - super.add(new Label("X: "), c) - - c.gridx = 1 - c.gridy = 1 - c.weightx = 1.0 - c.weighty = 0.0 - super.add(sldX, c) - - c.gridx = 2 - c.gridy = 1 - c.weightx = 0.0 - c.weighty = 0.0 - super.add(lblX, c) - - c.gridx = 0 - c.gridy = 2 - c.weightx = 1.0 - c.weighty = 0.0 - super.add(new Label("Y: "), c) - - c.gridx = 1 - c.gridy = 2 - c.weightx = 1.0 - c.weighty = 0.0 - super.add(sldY, c) - - c.gridx = 2 - c.gridy = 2 - c.weightx = 0.0 - c.weighty = 0.0 - super.add(lblY, c) - - - listenTo(sldX, sldY) - - reactions += { - case ValueChanged(s) if (s == sldX || s == sldY) => - container.scene.real.gravity = Vector2D(sldX.value / 10.0, sldY.value / 10.0) - } - - def update() = { - val g = container.scene.world.gravity - sldX.value = (g.x * 10).toInt - lblX.text = ((g.x * 10).toInt / 10.0).toString - sldY.value = (g.y * 10).toInt - lblY.text = ((g.y * 10).toInt / 10.0).toString - } - -} diff --git a/src/graphyx/gui/InfoPanel.scala b/src/graphyx/gui/InfoPanel.scala deleted file mode 100644 index d9dad43..0000000 --- a/src/graphyx/gui/InfoPanel.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import scala.swing._ -import scala.swing._ - -class InfoPanel(container: Container) extends BoxPanel(Orientation.Vertical){ - preferredSize = new java.awt.Dimension(200, 50) - - val out = new TextArea - out.editable = false - contents += out - border = Swing.EmptyBorder(3,3,3,3) - - def update() = { - out.text = "fps=" + container.scene.fps + "\n" + - "t=" + container.scene.world.time.formatted("%f") + "\n" - if (container.scene.world.overCWarning) { - out.foreground = java.awt.Color.red - out.text += "Warning: some bodies passed the speed of light! Simulation may be highly incorrect.\n" - } - else out.foreground = java.awt.Color.black - for (r <- container.scene.world.monitorFlatResults) out.text += "b" + r._1 + " " + r._2 + ": " + r._3 + "\n" - } -} diff --git a/src/graphyx/gui/MainFrame.scala b/src/graphyx/gui/MainFrame.scala deleted file mode 100644 index 4fdc9a2..0000000 --- a/src/graphyx/gui/MainFrame.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import graphyx._ -import sims._ -import scala.swing._ - -class MainFrame(container: Container) extends Frame{ - super.background = java.awt.Color.WHITE - title = "graphyx" - preferredSize = new java.awt.Dimension(1000,800) - - reactions += { - case event.WindowClosing(w) => Graphyx.exit() - } - - val mainPanel = new MainPanel(container) - contents = mainPanel - -} diff --git a/src/graphyx/gui/MainPanel.scala b/src/graphyx/gui/MainPanel.scala deleted file mode 100644 index e4989e8..0000000 --- a/src/graphyx/gui/MainPanel.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import graphyx.graphics._ -import sims._ -import scala.swing._ -import swing.event._ -import GridBagPanel._ -import java.awt.Insets - -class MainPanel(container: Container) extends scala.swing.GridBagPanel { - val c = new Constraints - - val menuPanel = new MenuPanel(container) - val worldPanel = new WorldPanel(container) - val controlPanel = new ControlPanel(container) - val infoPanel = new InfoPanel(container) - val optionsPanel = new OptionsPanel(container) - val shapeInfoPanel = new ShapeInfoPanel(container) - val gravityPanel = new GravityPanel(container) - - val splitter = new SplitPane { - orientation = Orientation.Vertical - continuousLayout = true - resizeWeight = 1 - dividerSize = 2 - leftComponent = worldPanel - rightComponent = new SplitPane { - orientation = Orientation.Horizontal - continuousLayout = true - resizeWeight = 1 - dividerSize = 2 - topComponent = new SplitPane{ - orientation = Orientation.Horizontal - continuousLayout = true - resizeWeight = 1 - dividerSize = 2 - topComponent = infoPanel - bottomComponent = gravityPanel - } - bottomComponent = optionsPanel - } - } - c.fill = Fill.Both - - c.gridx = 0 - c.gridy = 0 - c.weightx = 1.0 - c.weighty = 0.0 - super.add(menuPanel, c) - - c.gridx = 0 - c.gridy = 1 - c.weightx = 1.0 - c.weighty = 0.0 - super.add(controlPanel, c) - - - c.gridx = 0 - c.gridy = 2 - c.weightx = 1.0 - c.weighty = 1.0 - super.add(splitter, c) - - /* - c.gridx = 1 - c.gridy = 1 - c.weightx = 0.0 - c.weighty = 1.0 - super.add(infoPanel, c) - */ -} diff --git a/src/graphyx/gui/MenuHelp.scala b/src/graphyx/gui/MenuHelp.scala deleted file mode 100644 index 1c73d51..0000000 --- a/src/graphyx/gui/MenuHelp.scala +++ /dev/null @@ -1,19 +0,0 @@ -package graphyx.gui - -import graphyx.actors._ -import graphyx.gui._ -import scala.swing._ -import scala.swing.event._ - -class MenuHelp extends Menu("Help") { - val miAbout = new MenuItem("About...") - - val components = List(miAbout) - contents ++= components - - listenTo(components: _*) - reactions += { - case event.ButtonClicked(`miAbout`) => AboutHelpFrame.frame.visible = true - - } -} diff --git a/src/graphyx/gui/MenuPanel.scala b/src/graphyx/gui/MenuPanel.scala deleted file mode 100644 index d3196fe..0000000 --- a/src/graphyx/gui/MenuPanel.scala +++ /dev/null @@ -1,12 +0,0 @@ -package graphyx.gui - -import graphyx.actors._ -import graphyx.gui._ -import scala.swing._ -import scala.swing.event._ - -class MenuPanel(container: Container) extends BoxPanel(Orientation.Horizontal) { - val mnu = new MenuBar - mnu.contents += new MenuHelp - contents += mnu -} diff --git a/src/graphyx/gui/OptionsPanel.scala b/src/graphyx/gui/OptionsPanel.scala deleted file mode 100644 index 525f352..0000000 --- a/src/graphyx/gui/OptionsPanel.scala +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import graphyx.graphics._ -import sims.geometry._ -import sims.dynamics._ -import scala.swing._ -import scala.swing.event._ -import GridBagPanel._ - -class OptionsPanel(container: Container) extends GridPanel(12,2){ - /* - val c = new Constraints - c.anchor = Anchor.West - */ - - this.border = Swing.EmptyBorder(3,3,3,3) - this.hGap = 3 - this.vGap = 3 - - val lblTimeStep = new Label("h [Hz]") {tooltip = "Time Step"} - val txtTimeStep = new TextField - - val lblIterations = new Label("i [1]") {tooltip = "Iterations"} - val txtIterations = new TextField - - val lblCD = new Label("CD") {tooltip = "Collision Detection"} - val chckCD = new CheckBox("") - - val lblPC = new Label("PC") {tooltip = "Position Correction"} - val chckPC = new CheckBox("") - - val lblDraw = new Label("Draw") - - val lblDrawBodies = new Label("Bodies") - val chckDrawBodies = new CheckBox {selected = false} - - val lblDrawShapes = new Label("Shapes") - val chckDrawShapes = new CheckBox {selected = true} - - val lblDrawJoints = new Label("Joints") - val chckDrawJoints = new CheckBox {selected = true} - - val lblDrawAABBs = new Label("AABBs") - val chckDrawAABBs = new CheckBox {selected = false} - - val lblDrawPairs = new Label("Pairs") - val chckDrawPairs = new CheckBox {selected = false} - - val lblDrawCollisions = new Label("Collisions") - val chckDrawCollisions = new CheckBox {selected = false} - - val lblTrace = new Label("Trace") - val chckTrace = new CheckBox {selected = false} - - val components = List( - lblTimeStep, txtTimeStep, - lblIterations, txtIterations, - lblCD, chckCD, - lblPC, chckPC, - lblDraw, new Label(""), - lblDrawBodies, chckDrawBodies, - lblDrawShapes, chckDrawShapes, - lblDrawJoints, chckDrawJoints, - lblDrawAABBs, chckDrawAABBs, - lblDrawPairs, chckDrawPairs, - lblDrawCollisions, chckDrawCollisions, - lblTrace, chckTrace - ) - contents ++= components - listenTo(components: _*) - - reactions += { - case EditDone(`txtTimeStep`) => container.scene.world.real.timeStep = 1.0 / txtTimeStep.text.toInt - case EditDone(`txtIterations`) => container.scene.world.real.iterations = txtIterations.text.toInt - case ButtonClicked(`chckCD`) => container.scene.world.real.enableCollisionDetection = chckCD.selected - case ButtonClicked(`chckPC`) => container.scene.world.real.enablePositionCorrection = chckPC.selected - case ButtonClicked(`chckDrawBodies`) => container.mainFrame.mainPanel.worldPanel.drawBodies = chckDrawBodies.selected - case ButtonClicked(`chckDrawShapes`) => container.mainFrame.mainPanel.worldPanel.drawShapes = chckDrawShapes.selected - case ButtonClicked(`chckDrawJoints`) => container.mainFrame.mainPanel.worldPanel.drawJoints = chckDrawJoints.selected - case ButtonClicked(`chckDrawAABBs`) => container.mainFrame.mainPanel.worldPanel.drawAABBs = chckDrawAABBs.selected - case ButtonClicked(`chckDrawPairs`) => container.mainFrame.mainPanel.worldPanel.drawPairs = chckDrawPairs.selected - case ButtonClicked(`chckDrawCollisions`) => container.mainFrame.mainPanel.worldPanel.drawCollisions = chckDrawCollisions.selected - case ButtonClicked(`chckTrace`) => container.mainFrame.mainPanel.worldPanel.trace = chckTrace.selected - } - - def update() = { - if (!txtTimeStep.peer.hasFocus) - txtTimeStep.text = (1.0 / container.scene.world.timeStep).toString - if (!txtIterations.peer.hasFocus) - txtIterations.text = container.scene.world.iterations.toString - chckCD.selected = container.scene.world.enableCollisionDetection - chckPC.selected = container.scene.world.enablePositionCorrection - chckDrawBodies.selected = container.mainFrame.mainPanel.worldPanel.drawBodies - chckDrawShapes.selected = container.mainFrame.mainPanel.worldPanel.drawShapes - chckDrawJoints.selected = container.mainFrame.mainPanel.worldPanel.drawJoints - chckDrawAABBs.selected = container.mainFrame.mainPanel.worldPanel.drawAABBs - chckDrawPairs.selected = container.mainFrame.mainPanel.worldPanel.drawPairs - chckDrawCollisions.selected = container.mainFrame.mainPanel.worldPanel.drawCollisions - chckTrace.selected = container.mainFrame.mainPanel.worldPanel.trace - } - - - /* - def addCell(cm: Component)(x: Int, y: Int) = { - c.gridx = x - c.gridy = y - c.weightx = 0.5 - c.weighty = 0.0 - c. - if (cm.isInstanceOf[TextArea]) - c.fill = Fill.Horizontal - else - c.fill = Fill.None - super.add(cm, c) - } - - addCell(lblTimeStep)(0,0) - addCell(txtTimeStep)(1,0) - addCell(lblIterations)(0,1) - addCell(txtIterations)(1,1) - */ -} diff --git a/src/graphyx/gui/PopupMenu.scala b/src/graphyx/gui/PopupMenu.scala deleted file mode 100644 index 9679018..0000000 --- a/src/graphyx/gui/PopupMenu.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import scala.swing._ -import scala.swing.event._ -import javax.swing._ - -class PopupMenu extends Component -{ - override lazy val peer : JPopupMenu = new JPopupMenu - - def add(item: MenuItem) : Unit = { peer.add(item.peer) } - def setVisible(visible:Boolean) : Unit = { peer.setVisible(visible) } - /* Create any other peer methods here */ -} \ No newline at end of file diff --git a/src/graphyx/gui/ShapeInfoPanel.scala b/src/graphyx/gui/ShapeInfoPanel.scala deleted file mode 100644 index d94c0bd..0000000 --- a/src/graphyx/gui/ShapeInfoPanel.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import graphyx.graphics._ -import sims.geometry._ -import sims.dynamics._ -import scala.swing._ -import scala.swing.event._ -import GridBagPanel._ - -class ShapeInfoPanel(container: Container) extends GridPanel(2,2) { - - this.border = Swing.EmptyBorder(3,3,3,3) - this.hGap = 3 - this.vGap = 3 - - val lblBody = new Label("Body") - val lblValBody = new Label("0") - - val lblShape = new Label("Shape") - val lblValShape = new Label("0") - - val components = List( - lblBody, lblValBody, - lblShape, lblValShape - ) - - contents ++= components - -} diff --git a/src/graphyx/gui/WorldPanel.scala b/src/graphyx/gui/WorldPanel.scala deleted file mode 100644 index ad14726..0000000 --- a/src/graphyx/gui/WorldPanel.scala +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.gui - -import graphyx.graphics._ -import sims.geometry._ -import sims.dynamics._ -import scala.swing._ -import scala.swing.event._ -import scala.collection.mutable.Map -import scala.collection.mutable.Queue - -class WorldPanel(container: Container) extends BoxPanel(Orientation.Vertical){ - cursor = new java.awt.Cursor(java.awt.Cursor.CROSSHAIR_CURSOR) - val lblBody = new Label {text = "None @ (0, 0)"} - contents += lblBody - val popup = new BodyPopup - contents += popup - - implicit def point2Vector(p: java.awt.Point) = { - val x = p.x - val y = size.height - p.y - new Vector2D((x - offset.x) / scale / ppm, (y - offset.y) / scale / ppm) - } - - private val ppi = java.awt.Toolkit.getDefaultToolkit.getScreenResolution - val ppm = 39.37007874 * ppi - var scale = 0.02 - var offset = Vector2D(100, 100) //vector for point coordinates [px] - - def scene: Scene = container.scene - - def update() = { - repaint() - } - - var drawBodies = false - var drawShapes = true - var drawJoints = true - var drawAABBs = false - var drawPairs = false - var drawCollisions = false - var trace = false - - override def paintComponent(g: java.awt.Graphics2D) = { - var parts: Seq[Drawable] = Seq() - if (drawShapes) parts ++= scene.shapes - if (drawJoints) parts ++= scene.joints - if (drawAABBs) parts ++= scene.aabbs - if (drawPairs) parts ++= scene.pairs - if (drawCollisions) parts ++= scene.collisions - if (drawBodies) parts ++= scene.bodies - g.clearRect(0,0,size.width,size.height) - drawAxes(g) - g.translate(offset.x.toInt, -offset.y.toInt) - drawParts(parts, g) - if (trace) trace(scene.shapes, g) - g.translate(-offset.x.toInt, offset.y.toInt) - } - - def drawAxes(g: java.awt.Graphics2D): Unit = { - g.setColor(java.awt.Color.GRAY) - g.drawLine(0, size.height - offset.y.toInt, size.width, size.height - offset.y.toInt) - g.drawLine(offset.x.toInt, 0, offset.x.toInt, size.height) - /* - val md = scale * ppm - val hb = size.width / md - for (i <- 1 to hb.toInt) g.drawLine(offset.x.toInt + i * md.toInt, size.height - offset.y.toInt, - offset.x.toInt + i * md.toInt, size.height - offset.y.toInt + 10) - */ - } - - def drawParts(parts: Iterable[Drawable], g: java.awt.Graphics2D) = { - for (p <- parts){ - p.g = g - p.windowHeight = super.size.height - p.ppm = ppm - p.scale = this.scale - p.draw() - } - } - - val prevPos: Map[Int, Queue[Vector2D]] = Map() - def trace(shapes: Iterable[GraphicalShape], g: java.awt.Graphics2D) = { - for (s <- shapes) { - s.g = g - s.windowHeight = super.size.height - s.ppm = ppm - s.scale = this.scale - - - if (!prevPos.contains(s.uid)) prevPos += (s.uid -> new Queue[Vector2D]) - else { - prevPos(s.uid).enqueue(s.pos) - for(i <- 0 until prevPos(s.uid).length - 1) { - val sp = prevPos(s.uid)(i) - val ep = prevPos(s.uid)(i + 1) - s.g.setColor(java.awt.Color.cyan) - s.drawLine(sp, ep) - } - if (prevPos(s.uid).length == 50) prevPos(s.uid).dequeue - } - } - } - - def getBody(p: Vector2D): Option[Body] = { - val shape = scene.shapes.find(_.contains(p)) - if (shape != None) Some(shape.get.real.body) - else None - } - - var mousePressed: Boolean = false - var startPoint = new java.awt.Point(0,0) - var endPoint = new java.awt.Point(0,0) - var grabbedBody: Option[GrabbedBody] = None - def grab(b: Body, p: Vector2D) = { - grabbedBody = Some(new GrabbedBody(b, p)) - b.fixed = true - } - - def release() = { - if (grabbedBody != None && grabbedBody.get.wasFixed == false) - grabbedBody.get.body.fixed = false - grabbedBody = None - } - - listenTo(mouse.clicks, mouse.moves, mouse.wheel) - reactions += { - case MousePressed(c,p,x,y,b) => { - mousePressed = true; startPoint = p; endPoint = p - x match { - case 1024 if (getBody(p) != None) => grab(getBody(p).get, p) - case 1152 if (getBody(p) != None) => {grabbedBody = Some(new GrabbedBody(getBody(p).get, p)); popup.body = grabbedBody.get.body; popup.peer.setLocation(p); popup.visible = true} - case 4096 if (getBody(p) != None) => {grabbedBody = Some(new GrabbedBody(getBody(p).get, p)); popup.body = grabbedBody.get.body; popup.peer.setLocation(p); popup.visible = true} - case _ => () - } - } - - case MouseMoved(c,p,i) => { - lblBody.text = (if (getBody(p) != None) getBody(p).get.uid.toString else "None") + " @ (" + point2Vector(p).x.formatted("%f") + ", " + point2Vector(p).y.formatted("%f") + ")" - } - - case MouseDragged(c,p,1088) => {//drag with shift - offset += Vector2D((p.x - endPoint.x), -(p.y - endPoint.y)) - mousePressed = true - endPoint = p - cursor = new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR) - } - - case MouseDragged(c,p,x) => - if (grabbedBody != None) grabbedBody.get.body.pos = p - grabbedBody.get.r - - case MouseReleased(c,p,x,y,b) => { - mousePressed = false - endPoint = p - cursor = new java.awt.Cursor(java.awt.Cursor.CROSSHAIR_CURSOR) - release() - } - - case MouseWheelMoved(c,p,1024,y) => { //with left mouse button pressed - if (grabbedBody != None) grabbedBody.get.body.rotation += 0.05 * y - } - - case MouseWheelMoved(c,p,x,y) => { - scale -= scale * 0.02 * y - } - - } -} - -class GrabbedBody(b: Body, point: Vector2D){ - def body = b - val r: Vector2D = point - body.pos - val wasFixed = b.fixed -} diff --git a/src/graphyx/tests/Atom.scala b/src/graphyx/tests/Atom.scala deleted file mode 100644 index 31d03fc..0000000 --- a/src/graphyx/tests/Atom.scala +++ /dev/null @@ -1,36 +0,0 @@ -package graphyx.tests - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.geometry._ - -object Atom extends Test{ - val title = "Atom" - val world = new World - - var nucleus = new Body(Circle(0.05, 1000)) {fixed = true} - var electrons: List[Body] = Nil - var connections: List[SpringJoint] = Nil - - def init = { - world -= nucleus - nucleus = new Body(Circle(0.05, 10)) {fixed = true} - world += nucleus - world --= electrons - electrons = Nil - for (c <- connections) world -= c - connections = Nil - } - - enableEvent = true - override def fireEvent = { - val e = (new Circle(0.1, 10) {pos = Vector2D(0, -1)}).asBody - e.linearVelocity = Vector2D(-50,100) - electrons = e :: electrons - world += e - - val c = new SpringJoint(nucleus, e, 500) - connections = c :: connections - world += c - } -} diff --git a/src/graphyx/tests/BallStack.scala b/src/graphyx/tests/BallStack.scala deleted file mode 100644 index 8e45611..0000000 --- a/src/graphyx/tests/BallStack.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -import sims.geometry._ - -object BallStack extends Test{ - val world = new World - val title = "BallStack" - def init(): Unit = { - val ground = new Rectangle(1,0.1,1) {pos = Vector2D(1,0)} - val wallLeft = new Rectangle(0.1,1,1) {pos = Vector2D(0,1)} - val wallRight = new Rectangle(0.1,1,1) {pos = Vector2D(2,1)} - val box = new Body(ground, wallLeft, wallRight) {fixed = true} - world += box - world += (new Circle(0.1,1) {pos = Vector2D(1.1, 2.8)}).asBody - world ++= (for (i <- 0 to 50) yield (new Circle(0.1,1) {pos = Vector2D(1, 3 + 0.2 * i)}).asBody) - - } -} diff --git a/src/graphyx/tests/Cannon.scala b/src/graphyx/tests/Cannon.scala deleted file mode 100644 index 01ce4e5..0000000 --- a/src/graphyx/tests/Cannon.scala +++ /dev/null @@ -1,59 +0,0 @@ -package graphyx.tests - -import sims.dynamics._ -import sims.geometry._ -import sims.prefabs._ - -object Cannon extends Test{ - val title = "Cannon" - val world = new World - - def init = { - val cannon = new Prefab{ - val hull = new Body( - new Rectangle(0.1,0.5,1) {pos = Vector2D(0.1, 0.6); friction = 0.0}, - new Rectangle(0.1,0.5,1) {pos = Vector2D(0.5, 0.6); friction = 0.0}, - new Rectangle(0.1,0.1,1) {pos = Vector2D(0.3, 0.2); friction = 0.0} - ) - hull.fixed = true - hull.rotation -= Math.Pi / 2 - - val ball = new Body(new Circle(0.1,100) {pos = Vector2D(0.3, 0.56)}) - - override val bodies = List(hull, ball) - override val joints = Nil - } - val n = 10 - val r = 0.1 - val initialPos = Vector2D(5,0) - val stack = for (i <- (0 to n).toList) yield { - for (j <- (0 to n-i).toList) yield - new Body( - new Circle(r,10){ - pos = Vector2D(2 * j * r + i * r, 1.7 * i * r) + initialPos - } - ) {fixed = (i == 0)} - } - world += cannon - world ++= stack.flatten - - } - - enableEvent = true - override def fireEvent() = blastBomb - - def blastBomb() = { - val bombPos = Vector2D(0, 0.56) - val bombRadius = 1 - val bombImpulse = 200 - val region = new Circle(bombRadius, 0) {pos = bombPos} - val detector = world.detector.asInstanceOf[sims.collision.GridDetector] - val collisions = for (s <- world.shapes; if detector.colliding(sims.collision.Pair(region, s))) yield detector.collision(sims.collision.Pair(region, s)) - for (c <- collisions) { - if (c.shape1 != region) - for(p <- c.points) c.shape1.body.applyImpulse((p - bombPos).unit * bombImpulse, p) - if (c.shape2 != region) - for(p <- c.points) c.shape2.body.applyImpulse((p - bombPos).unit * bombImpulse, p) - } - } -} diff --git a/src/graphyx/tests/Carriage.scala b/src/graphyx/tests/Carriage.scala deleted file mode 100644 index 967c6e5..0000000 --- a/src/graphyx/tests/Carriage.scala +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.geometry._ - -object Carriage extends Test{ - val title = "Carriage" - val world = new World - - def init = { - val car = new Car - - val groundShapes = for (i <- (0 to 200).toList) yield (new Rectangle(0.2, 0.1, 1) { - pos = Vector2D(0.4 * i, 0) - transientShapes += car.chassis.shapes(0) - }) - val ground = new Body(groundShapes: _*) //Rectangle(100, 0.1, 1).asBody - ground.pos = Vector2D(0,0) - ground.fixed = true - ground.rotation = -0.2 - - - world += ground - world += car - - } - - class Car extends sims.prefabs.Prefab { - - val chassis = (new Rectangle(0.5, 0.05, 10) {pos = Vector2D(0, 1)}).asBody - val rightWheel = (new Circle(0.1, 10) {pos = Vector2D(0.4,0.8)}).asBody - val leftWheel = (new Circle(0.1, 10) {pos = Vector2D(-0.4,0.8)}).asBody - - override val bodies = List(chassis, rightWheel, leftWheel) - - val rightStabelizer = new DistanceJoint(chassis, rightWheel) - val rightDamper = new SpringJoint(chassis, chassis.pos + Vector2D(rightWheel.pos.x, 0), - rightWheel, rightWheel.pos, 500) {damping = 1} - - val leftStabelizer = new DistanceJoint(chassis, leftWheel) - val leftDamper = new SpringJoint(chassis, chassis.pos + Vector2D(leftWheel.pos.x, 0), - leftWheel, leftWheel.pos, 500) {damping = 1} - - override val joints = List(rightStabelizer, rightDamper, leftStabelizer, leftDamper) - - } - -} diff --git a/src/graphyx/tests/Chain.scala b/src/graphyx/tests/Chain.scala deleted file mode 100644 index 27511ca..0000000 --- a/src/graphyx/tests/Chain.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.prefabs._ -import sims.geometry._ - -object Chain extends Test{ - override val title = "Chain" - val world = new World - def init = { - val nodes = for (i <- (0 until 20).toList) yield (new Circle(0.02, 1) {pos = Vector2D(i * 0.2, 1)}).asBody - nodes(0).fixed = true - nodes(19).fixed = true - val connectors = for (i <- (0 until nodes.length - 1).toList) yield new DistanceJoint(nodes(i), nodes(i + 1)) - for (n <- nodes) world += n - for (c <- connectors) world += c - world += (new Circle(1,0.001) {pos = Vector2D(2,2)}).asBody - } -} diff --git a/src/graphyx/tests/CompositeShape.scala b/src/graphyx/tests/CompositeShape.scala deleted file mode 100644 index 51ffd0b..0000000 --- a/src/graphyx/tests/CompositeShape.scala +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.geometry._ -import sims.dynamics._ - -import sims.util._ -import sims.util.Positioning._ - -object CompositeShape extends Test{ - val title = "Composite Shape" - val world = new World - - def init = { - - val ground = new Body(Rectangle(1000,0.1,1)) {fixed = true} - world += ground - - val h2o = { - val h = new Circle(0.2,1) - val o1 = new Circle(0.05,1) - val o2 = new Circle(0.05,1) {rotation = 0.3} - position(o1) {0.25 above h} - o2.pos = (new Polar(0.25, Math.Pi / 3)) from h - new Body(h, o1, o2) {pos = Vector2D(0, 0.5)} - } - world += h2o - } - -} - \ No newline at end of file diff --git a/src/graphyx/tests/Cup.scala b/src/graphyx/tests/Cup.scala deleted file mode 100644 index 598a9be..0000000 --- a/src/graphyx/tests/Cup.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -import sims.geometry._ -object Cup extends Test { - val title = "Cup" - val world = new World - - def init = { - val ground = (new Rectangle(1000, 0.1, 1) {friction = 1}).asBody - ground.fixed = true - world += ground - - val cupShapes = for (i <- 0 to (10 * Math.Pi).toInt) yield new Circle(0.1,1) {pos = Vector2D(Math.cos(-i / 10.0), Math.sin(-i / 10.0)); restitution = 0.0; friction = 1.0} - val cup = new Body(cupShapes: _*) {fixed = true; pos = Vector2D(0, 1)} - world += cup - - val ball1 = (new Circle(0.2, 1) {pos = Vector2D(0, 2)}).asBody - val ball2 = (new Circle(0.2, 1) {pos = Vector2D(-0.4, 2)}).asBody - val ball3 = (new Circle(0.2, 1) {pos = Vector2D(0.4, 2)}).asBody - world += ball1 - world += ball2 - world += ball3 - } -} diff --git a/src/graphyx/tests/EmptyTest.scala b/src/graphyx/tests/EmptyTest.scala deleted file mode 100644 index 0e3bd84..0000000 --- a/src/graphyx/tests/EmptyTest.scala +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -import sims.geometry._ -object EmptyTest extends Test{ - override val title = "Empty Test" - val world = new World - def init = {} -} diff --git a/src/graphyx/tests/Friction.scala b/src/graphyx/tests/Friction.scala deleted file mode 100644 index ba9fb69..0000000 --- a/src/graphyx/tests/Friction.scala +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.geometry._ -import sims.dynamics._ -import sims.dynamics.joints._ - -object Friction extends Test{ - val title = "Friction" - val world = new World - - var r1: RevoluteJoint = _ - var r2: RevoluteJoint = _ - var r3: RevoluteJoint = _ - - def init = { - val ground = (new Rectangle(1000, 0.1, 1) {friction = 1}).asBody - ground.fixed = true - world += ground - - val ball1 = (new Circle(0.2, 1) {pos = Vector2D(0, 1); friction = 0.05}).asBody - ball1.angularVelocity = -80 - ball1.monitor = true - val ball2 = (new Circle(0.2, 1) {pos = Vector2D(1, 1); friction = 0.2}).asBody - ball2.angularVelocity = -80 - ball2.monitor = true - val ball3 = (new Circle(0.2, 1) {pos = Vector2D(2, 1); friction = 1}).asBody - ball3.angularVelocity = -80 - ball3.monitor = true - - world += ball1 - world += ball2 - world += ball3 - - world.monitors += ("", (b: Body) => "I=" + b.I + "\tw=" + b.angularVelocity + "\tEcin=" + 0.5 * b.I * b.angularVelocity * b.angularVelocity) - - r1 = RevoluteJoint(ground, ball1, ball1.pos) - r2 = RevoluteJoint(ground, ball2, ball2.pos) - r3 = RevoluteJoint(ground, ball3, ball3.pos) - world += r1 - world += r2 - world += r3 - } - - enableEvent = true - override def fireEvent = { - world -= r1 - world -= r2 - world -= r3 - } - -} diff --git a/src/graphyx/tests/Friction2.scala b/src/graphyx/tests/Friction2.scala deleted file mode 100644 index 9d03bd9..0000000 --- a/src/graphyx/tests/Friction2.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.geometry._ -import sims.dynamics._ -import sims.dynamics.joints._ - -object Friction2 extends Test{ - val title = "Friction2" - val world = new World {override val detector = new sims.collision.GridDetector(this) {gridSide = 0.2}} - - def init = { - val shapes = for (i <- (0 to 20).toList) yield (new Rectangle(0.2, 0.1, 1) { - pos = Vector2D(0.4 * i, 0) - friction = (i * 1.0 / 10) - restitution = 0 - }) - val ground = new Body(shapes: _*) - ground.pos = Vector2D(0,0) - ground.fixed = true - ground.rotation = -Math.Pi / 5 - world += ground - - val b: Body = (new Circle(0.1,10)) ~ (new Circle(0.1,10) {pos = Vector2D(0.2,0)}) ~ (new Circle(0.1,10) {pos = Vector2D(0.4,0)}) - b.pos = Vector2D(0.1,0.1) - world += b - } -} \ No newline at end of file diff --git a/src/graphyx/tests/General1.scala b/src/graphyx/tests/General1.scala deleted file mode 100644 index 71e041b..0000000 --- a/src/graphyx/tests/General1.scala +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims._ -import sims.geometry._ -import sims.collision._ -import sims.dynamics._ -import sims.dynamics.joints._ -object General1 extends Test{ - override val title = "General1" - val world = new World - - def init() = { - val b0 = new Circle(0.1,1).asBody - b0.fixed = true - val b1 = (new Circle(0.1,1) {pos = Vector2D(0,1)}).asBody - //b0.linearVelocity = Vector2D(0,0.4) - b0.monitor = true - b1.monitor = true - val circles = for (i <- (0 until 10).toList) yield (new Circle(0.1,1) {pos = Vector2D(0, 1.2 + 0.2 * i)}).asBody - //for (c <- circles) world += c - //world.gravity = Vector2D.Null - // world += b0 - //world += b1 - - world.monitors += ("Veclocity = ", _.linearVelocity.length.toString) - - val b2 = (new Rectangle(0.1,0.15,1) {pos = Vector2D(1,0)}).asBody - b2.fixed = true - b2.rotation = 2 - val b3 = (new Circle(0.1,1) {pos = Vector2D(1,1.1)}).asBody - //world += b2 - //world += b3 - - val b4 = (new Rectangle(0.1,0.15,1) {pos = Vector2D(2,0)}).asBody - b4.fixed = true - b4.rotation = 2 - val b5 = (new Rectangle(0.1,0.15,1) {pos = Vector2D(2,1.2)}).asBody - //world += b4 - //world += b5 - - val bn = (new RegularPolygon(5,0.1,1) {pos = Vector2D(3,0)}).asBody - //world += bn - - //Make cannon and balls - val hull = new Body( - new Rectangle(0.1,0.5,1) {pos = Vector2D(0.1, 0.5)}, - new Rectangle(0.1,0.5,1) {pos = Vector2D(0.5, 0.5)}, - new Rectangle(0.1,0.1,1) {pos = Vector2D(0.3, 0.1)} - ) - hull.fixed = true - hull.rotation -= Math.Pi / 4 - - val ball = new Body( - new Circle(0.1,20) {pos = Vector2D(0.3, 0.3)} - ) - val ball2 = new Body( - new Circle(0.1,20) {pos = Vector2D(0.3, 0.5)} - ) - world += hull - world += ball - world += ball2 - - //Swing - val anchor = (new Circle(0.05,1) {pos = Vector2D(25,10)}).asBody - anchor.fixed = true - val block = (new RegularPolygon(9,0.5,2) {pos = Vector2D(25,1)}).asBody - val joint = new DistanceJoint(anchor, block) - world += anchor - world += block - world += joint - - //Make stack - val stack = for (i <- (0 until 10).toList) yield (new Circle(0.1,1) {pos = Vector2D(30, 0.2 + 0.2 * i)}).asBody - for (e <- stack) world += e - - - /* - val springBoardHull = new Body( - new Rectangle(0.1,0.5,1) {pos = Vector2D(-1.1, 0.5)}, - new Rectangle(0.1,0.5,1) {pos = Vector2D(-1.5, 0.5)}, - new Rectangle(0.1,0.1,1) {pos = Vector2D(-1.3, 0.1)} - ) - springBoardHull.fixed = true - world += springBoardHull - - val springBoard = new Body( - new Circle(0.1,20) {pos = Vector2D(-1.3, 0.5)} - ) - world += springBoard - - val spring = new SpringJoint(springBoardHull, Vector2D(-1.3, 0.1), springBoard, springBoard.pos, 2000) - spring.damping = 10 - world += spring - */ - - val ground = (new Rectangle(1000,0.5,1) {pos = Vector2D(0, -0.4)}).asBody - ground.fixed = true - world += ground - - world += (new Circle(0.1,1) {pos = Vector2D(2,2)}) ~ (new Circle(0.1,1) {pos = Vector2D(2,2.2)}) - } - - enableEvent = true - override def fireEvent() = blastBomb - - def blastBomb() = { - val bombPos = Vector2D(0, 0) - val bombRadius = 1 - val bombImpulse = 10 - val region = new Circle(bombRadius, 0) {pos = bombPos} - val detector = world.detector.asInstanceOf[GridDetector] - val collisions = for (s <- world.shapes; if detector.colliding(collision.Pair(region, s))) yield detector.collision(collision.Pair(region, s)) - for (c <- collisions) { - if (c.shape1 != region) - for(p <- c.points) c.shape1.body.applyImpulse((p - bombPos).unit * bombImpulse, p) - if (c.shape2 != region) - for(p <- c.points) c.shape2.body.applyImpulse((p - bombPos).unit * bombImpulse, p) - } - } -} diff --git a/src/graphyx/tests/General2.scala b/src/graphyx/tests/General2.scala deleted file mode 100644 index 2006080..0000000 --- a/src/graphyx/tests/General2.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.geometry._ -import sims.dynamics._ - -object General2 extends Test{ - val title = "General2" - val world = new World - - def init = { - world += new Body(new Rectangle(100,0.5,1) {pos = Vector2D(0, -0.5)}) {fixed = true} - //new Body(new Circle(0.05,1) {pos = Vector2D(0, 0.05)}), - //new Body(new Rectangle(0.5,0.1,1) {pos = Vector2D(0, 0.2)}), - //new Body(new Circle(0.05,1) {pos = Vector2D(1, 0.05)})) - - world += new Body(new Circle(0.2,1) {pos = Vector2D(5, 0.2)}) - world += new Body(new Rectangle(1.5,0.1,1) {pos = Vector2D(4.5, 0.5)}, new Rectangle(0.05,0.1,1) {pos = Vector2D(3.05,0.7)}) - world += new Body(new Circle(0.1,1) {pos = Vector2D(3.2, 0.7)}) - world += new Body(new Circle(0.5,10) {pos = Vector2D(8, 0.5)}) - - } -} diff --git a/src/graphyx/tests/Joints1.scala b/src/graphyx/tests/Joints1.scala deleted file mode 100644 index ad143ec..0000000 --- a/src/graphyx/tests/Joints1.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.geometry._ - -object Joints1 extends Test{ - override val title = "Joints1" - val world = new World - def init = { - val anchor = new Body(new Circle(0.03, 1) {pos = Vector2D(1,5)}) {fixed = true} - val weight = (new Rectangle(0.1, 0.5, 1) {pos = Vector2D(1,0)}).asBody - val joint = new DistanceJoint(anchor, anchor.pos, weight, weight.pos + Vector2D(0.1,0.2)) - world += anchor - world += weight - world += joint - } -} diff --git a/src/graphyx/tests/Joints2.scala b/src/graphyx/tests/Joints2.scala deleted file mode 100644 index 9ff5df3..0000000 --- a/src/graphyx/tests/Joints2.scala +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.geometry._ -import sims.util._ -import sims.util.Positioning._ - -object Joints2 extends Test{ - override val title = "Joints2" - val world = new World - def init() = { - val length = 100 - val distance = 0.2 - val anchors = for (i <- (0 until length).toList) yield new Body(new Circle(0.03,1) {pos = Vector2D(i * distance,5)}) {fixed = true} - val balls = for (i <- (0 until length).toList) yield new Body(new Circle(0.1,1) {pos = Vector2D(i * distance,0); restitution = 1}) - balls(0).pos = Vector2D(0, 5) + Polar(5, -Math.Pi / 1.5).toCarthesian - val joints = for (i <- (0 until length).toList) yield new DistanceJoint(anchors(i), balls(i)) - for (a <- anchors) world += a - for (b <- balls) world += b - for (j <- joints) world += j - } -} diff --git a/src/graphyx/tests/Net.scala b/src/graphyx/tests/Net.scala deleted file mode 100644 index c340a80..0000000 --- a/src/graphyx/tests/Net.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims._ -import sims.geometry._ -import sims.dynamics._ - -object Net extends Test{ - val title = "Net" - val world = new World - - def init = { - val n = new prefabs.Net(10, 10, Vector2D(4,4)) - n.bodies(9).fixed = true - world += n - } -} diff --git a/src/graphyx/tests/RagdollTest.scala b/src/graphyx/tests/RagdollTest.scala deleted file mode 100644 index 63c9ce5..0000000 --- a/src/graphyx/tests/RagdollTest.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.geometry._ -import sims.prefabs._ - -object RagdollTest extends Test { - val title = "Ragdoll" - val world = new World - - def init = { - val ground = new Body((for (i <- 0 to 1000) yield new Circle(0.5,1) {pos = Vector2D(0.5 * (i - 500), 0)}): _*) - ground.fixed = true - world += ground - - world += new Ragdoll(Vector2D(0, 5)) - } - -} diff --git a/src/graphyx/tests/Restitution.scala b/src/graphyx/tests/Restitution.scala deleted file mode 100644 index 9501a36..0000000 --- a/src/graphyx/tests/Restitution.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.geometry._ -import sims.dynamics._ - -object Restitution extends Test{ - val title = "Restitution" - val world = new World - - def init = { - world += new Body(new Rectangle(1000,0.1,10) {restitution = 1}) {fixed = true} - world ++= (for (i <- 0 until 10) yield (new Circle(0.05, 10) {pos = Vector2D(i * 0.5, 1); restitution = i / 10.0}).asBody) - } - -} diff --git a/src/graphyx/tests/Spring.scala b/src/graphyx/tests/Spring.scala deleted file mode 100644 index e7fecb8..0000000 --- a/src/graphyx/tests/Spring.scala +++ /dev/null @@ -1,23 +0,0 @@ -package graphyx.tests - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.geometry._ -import java.io._ - -object Spring extends Test{ - val title = "Spring" - val world = new World - - def init = { - val anchor = Circle(0.05, 10).asBody - anchor.fixed = true - val particle = (new Circle(0.1, 20) {pos = Vector2D(0, -3)}).asBody - val spring = new SpringJoint(anchor, particle, 500, 2) - spring.damping = 0.5 - - world += anchor - world += particle - world += spring - } -} diff --git a/src/graphyx/tests/Stacking.scala b/src/graphyx/tests/Stacking.scala deleted file mode 100644 index 63734b6..0000000 --- a/src/graphyx/tests/Stacking.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -import sims.geometry._ - -object Stacking extends Test{ - val world = new World - val title = "Stacking" - def init(): Unit = { - val sideWidth = 0.3 - val sideHeight = 0.2 - val boxes = 5 - val distance = 0.1 - val stack = for (i <- (0 until boxes).toList) yield (new Rectangle(sideWidth / (2 + 0.3 * i), sideHeight / 2, 1) {pos = Vector2D(1, i * (sideHeight + distance))}).asBody - stack(0).fixed = true - for (box <- stack) world += box - } -} diff --git a/src/graphyx/tests/Test.scala b/src/graphyx/tests/Test.scala deleted file mode 100644 index ca0f8e8..0000000 --- a/src/graphyx/tests/Test.scala +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Graphyx - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package graphyx.tests - -import sims.dynamics._ -trait Test { - val world: World - val title: String - def init(): Unit - var enableEvent: Boolean = false - def fireEvent(): Unit = println("No custom event method defined.") - override def toString() = title -} diff --git a/src/graphyx/tests/Wave.scala b/src/graphyx/tests/Wave.scala deleted file mode 100644 index d3359c1..0000000 --- a/src/graphyx/tests/Wave.scala +++ /dev/null @@ -1,34 +0,0 @@ -package graphyx.tests - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.dynamics.joints.test._ -import sims.geometry._ - -object Wave extends Test{ - val title = "Wave" - val world = new World {gravity = Vector2D.Null} - - def init = { - val n = 50 - - val anchors = for (i <- (0 to n).toList) yield - new Body(new Circle(0.01,1) {pos = Vector2D(0.4 * i, 5)}) {fixed = true} - - val particles = for (i <- (0 to n).toList) yield - new Body(new Circle(0.1,10) {pos = Vector2D(0.4 * i, 0)}) - - val rails = for (i <- (0 to n).toList) yield - new PrismaticJoint(anchors(i), particles(i)) - - val springs = for (i <- (0 to n).toList) yield - new SpringJoint(anchors(i), particles(i), 5)// {damping = 0.00}) - - val lateralSprings = for (i <- (0 to (n - 1)).toList) yield - new SpringJoint(particles(i), particles(i + 1), 50.0) - - world ++= anchors - world ++= particles - for (j <- rails ++ springs ++ lateralSprings) world += j - } -} diff --git a/src/main/scala/graphyx/Graphyx.scala b/src/main/scala/graphyx/Graphyx.scala new file mode 100644 index 0000000..17341fb --- /dev/null +++ b/src/main/scala/graphyx/Graphyx.scala @@ -0,0 +1,61 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx + +import akka.actor._ +import graphyx.actors._ +import graphyx.graphics._ +import graphyx.tests._ +import sims.geometry._ +import sims.dynamics._ + +object Graphyx{ + val tests: List[graphyx.tests.Test] = List( + CompositeShape, + Joints1, + Joints2, + Spring, + Atom, + Chain, + Wave, + Net, + Stacking, + BallStack, + Cup, + Friction, + Friction2, + Restitution, + RagdollTest, + Carriage, + General1, + General2, + Cannon, + EmptyTest + ) + + private var _test: graphyx.tests.Test = tests(0) + def test = _test + def test_=(t: graphyx.tests.Test) = { + t.world.time = 0 + t.world.clear() + t.init() + physicsActor ! SetWorld(t.world) + _test = t + } + + val system = ActorSystem() + val physicsActor = system.actorOf(PhysicsActor(), "physics") + val guiActor = system.actorOf(GUIActor(), "gui") + + def main(args: Array[String]): Unit = { + test = tests(0) + } + + def exit() = { + system.shutdown() + } +} diff --git a/src/main/scala/graphyx/actors/GUIActor.scala b/src/main/scala/graphyx/actors/GUIActor.scala new file mode 100644 index 0000000..cbfb1c2 --- /dev/null +++ b/src/main/scala/graphyx/actors/GUIActor.scala @@ -0,0 +1,36 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.actors + +import akka.actor._ +import graphyx.graphics._ + +class GUIActor extends Actor{ + val container = new graphyx.gui.Container + + override def preStart() = { + container.show() + println("GUI actor started.") + } + + def receive = { + case s @ Scene(_) => container.update(s) + case other => println("Engine received unknown command: " + other) + } + + override def postStop() = { + container.exitGUI() + println("GUI actor exited.") + } + +} + +object GUIActor { + + def apply() = Props(classOf[GUIActor]) + +} diff --git a/src/main/scala/graphyx/actors/PhysicsActor.scala b/src/main/scala/graphyx/actors/PhysicsActor.scala new file mode 100644 index 0000000..7a7d2b9 --- /dev/null +++ b/src/main/scala/graphyx/actors/PhysicsActor.scala @@ -0,0 +1,88 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.actors + +import akka.actor._ +import graphyx._ +import graphyx.graphics._ +import scala.concurrent.duration._ +import sims.dynamics._ +class PhysicsActor extends Actor{ + import context._ + + var world = new World + + var simulate = false + + private var _fps = 0 + def fps = _fps + var t0 = System.nanoTime + + override def preStart() = { + println("Physics actor started.") + t0 = System.nanoTime + } + + def receive = { + case Tick => + t0 = System.nanoTime + if (simulate) { + world.step() + } + Graphyx.guiActor ! new Scene(world) {override val fps = _fps} + val h = (System.nanoTime - t0) / 1000000 + val f = 60 + val T = (1.0/f) * 1000 + _fps = (1.0/((System.nanoTime - t0) / 1000000000.0)).toInt + //println((1.0/((System.nanoTime - t0) / 1000000000.0)).toInt) + + val delay = if (T-h>0) (T-h).toLong else 0l + + if (simulate) { + system.scheduler.scheduleOnce(delay.milliseconds, self, Tick) + } + + case Step => + world.step() + Graphyx.guiActor ! new Scene(world) + + case Stop => { + simulate = false + println("Simulation stopped.") + } + case Start => { + simulate = true + self ! Tick + println("Simulation started.") + } + + case sw @ SetWorld(w: World) => world = w + + case FireEvent => Graphyx.test.fireEvent() + + case other => println("Engine received unknown command: '" + other + "'") + } + + override def postStop() = { + println("Physics actor exited.") + } +} + +object PhysicsActor { + + def apply() = Props(classOf[PhysicsActor]) + +} + +case object Tick +case object Start +case object Stop +case object Step +case class SetWorld(world: World) +case object FireEvent + + diff --git a/src/main/scala/graphyx/graphics/Drawable.scala b/src/main/scala/graphyx/graphics/Drawable.scala new file mode 100644 index 0000000..e1757f7 --- /dev/null +++ b/src/main/scala/graphyx/graphics/Drawable.scala @@ -0,0 +1,118 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.geometry._ + +/**Enthaelt Methoden und Felder fuer graphische Darstellungen. + * Alle Klassen die dieses Trait implementieren koennen graphisch dargestellt werden.*/ +trait Drawable { + + /**Java Graphics Objekt zur graphischen Darstellung*/ + var g: java.awt.Graphics2D = _ + + /**Anzahl von Pixeln pro Meter.*/ + var ppm: Double = 39.37007874015748 * 96 //ppm = i/m * p/i + + /**Skala in der die graphischen Objekte gezeichnet werden.*/ + var scale: Double = 1.0/100.0 + + /**Hoehe des Fensters in Pixeln.*/ + var windowHeight = 0 + + /**Korrigiert einen Y-Wert in Bildschirmkoordinaten zu seinem kartesischen Aequivalent. + * @param y zu korrigierender Wert*/ + def correctY(y: Double) = windowHeight - y + + /**Malt eine Linie auf g. + * @param startPoint Startpunkt in Weltkoordinaten + * @param endPoint Endpunkt in Weltkoordinaten*/ + def drawLine(startPoint: Vector2D, endPoint: Vector2D) = { + val x1 = startPoint.x * scale * ppm + val y1 = correctY(startPoint.y * scale * ppm) + val x2 = endPoint.x * scale * ppm + val y2 = correctY(endPoint.y * scale * ppm) + g.drawLine(x1.toInt, y1.toInt, x2.toInt, y2.toInt) + } + + /**Malt ein massives Polygon auf g. + * @param points Eckpunkte des Polygons in Weltkoordinaten*/ + def fillPolygon(points: Seq[Vector2D]) = { + val xs = points map ((v: Vector2D) => (v.x * scale * ppm).toInt) + val ys = points map ((v: Vector2D) => correctY((v.y) * scale * ppm).toInt) + g.fillPolygon(xs.toArray, ys.toArray, points.length) + } + + /**Malt ein Polygon auf g. + * @param points Eckpunkte des Polygons in Weltkoordinaten*/ + def drawPolygon(points: Seq[Vector2D]) = { + val xs = points map ((v: Vector2D) => (v.x * scale * ppm).toInt) + val ys = points map ((v: Vector2D) => correctY((v.y) * scale * ppm).toInt) + g.drawPolygon(xs.toArray, ys.toArray, points.length) + } + + /**Malt einen massiven Kreis auf g. + * @param center Mitte des Kreises in Weltkoordinaten + * @param radius Radius des Kreises*/ + def fillCircle(center: Vector2D, radius: Double) = { + g.fillOval(((center.x - radius) * scale * ppm).toInt, + correctY((center.y + radius) * scale * ppm).toInt, + (radius * scale * ppm * 2).toInt, + (radius * scale * ppm * 2).toInt) + } + + /**Malt einen Kreis auf g. + * @param center Mitte des Kreises in Weltkoordinaten + * @param radius Radius des Kreises*/ + def drawCircle(center: Vector2D, radius: Double) = { + g.drawOval(((center.x - radius) * scale * ppm).toInt, + correctY((center.y + radius) * scale * ppm).toInt, + (radius * scale * ppm * 2).toInt, + (radius * scale * ppm * 2).toInt) + } + + /**Malt einen Punkt auf g. + *

+ * Der Punkt wird von einem Kreis umgeben. + * @param point Punkt in Weltkoordinaten*/ + def drawPoint(point: Vector2D) = { + val radius = 4 //in pixel + g.drawLine((point.x * scale * ppm).toInt, + correctY(point.y * scale * ppm).toInt - radius, + (point.x * scale * ppm).toInt, + correctY(point.y * scale * ppm).toInt + radius) + g.drawLine((point.x * scale * ppm).toInt - radius, + correctY(point.y * scale * ppm).toInt, + (point.x * scale * ppm).toInt + radius, + correctY(point.y * scale * ppm).toInt) + g.drawOval((point.x * scale * ppm).toInt - radius, + correctY(point.y * scale * ppm).toInt - radius, + (radius * 2).toInt, + (radius * 2).toInt) + + } + + + /**Malt einen Vektor auf g. + * @param v Vektor in Weltkoordinaten + * @param p Ursprungspunkt in Weltkoordinaten + */ + def drawVector(v: Vector2D, p: Vector2D) = { + if (!v.isNull) { + val ep = p + v + val a1 = ep - ((v.unit rotate (math.Pi / 6)) * 0.08) + val a2 = ep - ((v.unit rotate (-math.Pi / 6)) * 0.08) + + g.drawLine((p.x * scale * ppm).toInt, correctY(p.y * scale * ppm).toInt, (ep.x * scale * ppm).toInt, correctY(ep.y * scale * ppm).toInt) + g.drawLine((a1.x * scale * ppm).toInt, correctY(a1.y * scale * ppm).toInt, (ep.x * scale * ppm).toInt, correctY(ep.y * scale * ppm).toInt) + g.drawLine((a2.x * scale * ppm).toInt, correctY(a2.y * scale * ppm).toInt, (ep.x * scale * ppm).toInt, correctY(ep.y * scale * ppm).toInt) + } + } + + /**Stellt das graphische Objekt dar.*/ + def draw(): Unit +} diff --git a/src/main/scala/graphyx/graphics/GraphicalAABB.scala b/src/main/scala/graphyx/graphics/GraphicalAABB.scala new file mode 100644 index 0000000..cb3694b --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalAABB.scala @@ -0,0 +1,18 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.collision._ +class GraphicalAABB(val real: AABB) extends AABB(real.minVertex, real.maxVertex) with GraphicalObject { + override def draw() = { + g.setColor(java.awt.Color.BLACK) + g.drawRect((minVertex.x * scale * ppm).toInt, + correctY(maxVertex.y * scale * ppm).toInt, + ((maxVertex - minVertex).x * scale * ppm).toInt, + ((maxVertex - minVertex).y * scale * ppm).toInt) + } +} diff --git a/src/main/scala/graphyx/graphics/GraphicalBody.scala b/src/main/scala/graphyx/graphics/GraphicalBody.scala new file mode 100644 index 0000000..c78ea51 --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalBody.scala @@ -0,0 +1,42 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.dynamics._ + +case class GraphicalBody(real: Body) extends GraphicalObject { + val pos = real.pos + val fixed = real.fixed + val monitor = real.monitor + def draw() = { + val radius = 4 + val posX = (pos.x * scale * ppm).toInt + val posY = correctY(pos.y * scale * ppm).toInt + g.setColor(java.awt.Color.yellow) + g.fillArc(posX - radius, + posY - radius, + (radius * 2).toInt, + (radius * 2).toInt, + 0, 90) + g.fillArc(posX - radius, + posY - radius, + (radius * 2).toInt, + (radius * 2).toInt, + 180, 90) + g.setColor(java.awt.Color.black) + g.fillArc(posX - radius, + posY - radius, + (radius * 2).toInt, + (radius * 2).toInt, + 90, 90) + g.fillArc(posX - radius, + posY - radius, + (radius * 2).toInt, + (radius * 2).toInt, + 270, 90) + } +} diff --git a/src/main/scala/graphyx/graphics/GraphicalCircle.scala b/src/main/scala/graphyx/graphics/GraphicalCircle.scala new file mode 100644 index 0000000..77b038c --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalCircle.scala @@ -0,0 +1,22 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims._ +import geometry._ +import dynamics._ +class GraphicalCircle(val real: Circle) extends Circle(real.radius, real.density) with GraphicalShape{ + override def draw() = { + //val b = math.min(density / 100 * 255, 255) + //g.setColor(new java.awt.Color(0,0,255, b.toInt)) + g.setColor(java.awt.Color.blue) + fillCircle(pos, real.radius) + g.setColor(java.awt.Color.BLACK) + drawCircle(pos, real.radius) + this.drawLine(pos, pos + (Vector2D.i rotate rotation) * real.radius) + } +} diff --git a/src/main/scala/graphyx/graphics/GraphicalCollision.scala b/src/main/scala/graphyx/graphics/GraphicalCollision.scala new file mode 100644 index 0000000..5589f8c --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalCollision.scala @@ -0,0 +1,18 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.collision._ + +case class GraphicalCollision(real: Collision) extends GraphicalObject{ + val points = real.points + val normal = real.normal + def draw() = { + g.setColor(java.awt.Color.GREEN) + for (p <- points) {drawPoint(p); drawVector(normal, p)} + } +} \ No newline at end of file diff --git a/src/main/scala/graphyx/graphics/GraphicalDistanceJoint.scala b/src/main/scala/graphyx/graphics/GraphicalDistanceJoint.scala new file mode 100644 index 0000000..4a6e49d --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalDistanceJoint.scala @@ -0,0 +1,19 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.dynamics.joints._ + +case class GraphicalDistanceJoint(real: DistanceJoint) extends GraphicalJoint { + val connection1 = real.connection1 + val connection2 = real.connection2 + + def draw() = { + g.setColor(java.awt.Color.BLACK) + drawLine(connection1, connection2) + } +} diff --git a/src/main/scala/graphyx/graphics/GraphicalJoint.scala b/src/main/scala/graphyx/graphics/GraphicalJoint.scala new file mode 100644 index 0000000..27d4f83 --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalJoint.scala @@ -0,0 +1,12 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.dynamics.joints._ +trait GraphicalJoint extends GraphicalObject{ + val real: Joint +} diff --git a/src/main/scala/graphyx/graphics/GraphicalObject.scala b/src/main/scala/graphyx/graphics/GraphicalObject.scala new file mode 100644 index 0000000..3c56de6 --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalObject.scala @@ -0,0 +1,15 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +/**Only copies functional info! (e.g. Graphical world does not include shapes, bodies).*/ +trait GraphicalObject extends Drawable{ + + /**Pointer to real object.*/ + val real: AnyRef + def draw(): Unit +} diff --git a/src/main/scala/graphyx/graphics/GraphicalPair.scala b/src/main/scala/graphyx/graphics/GraphicalPair.scala new file mode 100644 index 0000000..72e72ae --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalPair.scala @@ -0,0 +1,18 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.collision._ +case class GraphicalPair(real: Pair) extends GraphicalObject{ + val pos1 = real.s1.pos + val pos2 = real.s2.pos + + def draw() = { + g.setColor(java.awt.Color.ORANGE) + drawLine(pos1, pos2) + } +} diff --git a/src/main/scala/graphyx/graphics/GraphicalRectangle.scala b/src/main/scala/graphyx/graphics/GraphicalRectangle.scala new file mode 100644 index 0000000..05dfa76 --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalRectangle.scala @@ -0,0 +1,18 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims._ +import sims.dynamics._ +class GraphicalRectangle(val real: Rectangle) extends Rectangle(real.halfWidth, real.halfHeight, real.density) with GraphicalShape { + override def draw() = { + g.setColor(java.awt.Color.red) + fillPolygon(vertices) + g.setColor(java.awt.Color.BLACK) + drawPolygon(vertices) + } +} \ No newline at end of file diff --git a/src/main/scala/graphyx/graphics/GraphicalRegularPolygon.scala b/src/main/scala/graphyx/graphics/GraphicalRegularPolygon.scala new file mode 100644 index 0000000..fff8a9e --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalRegularPolygon.scala @@ -0,0 +1,19 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims._ +import geometry._ +import dynamics._ +class GraphicalRegularPolygon(val real: RegularPolygon) extends RegularPolygon(real.n, real.radius, real.density) with GraphicalShape{ + override def draw() = { + g.setColor(java.awt.Color.orange) + fillPolygon(vertices) + g.setColor(java.awt.Color.BLACK) + drawPolygon(vertices) + } +} \ No newline at end of file diff --git a/src/main/scala/graphyx/graphics/GraphicalRevoluteJoint.scala b/src/main/scala/graphyx/graphics/GraphicalRevoluteJoint.scala new file mode 100644 index 0000000..940a862 --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalRevoluteJoint.scala @@ -0,0 +1,20 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.geometry._ +import sims.dynamics.joints._ + +case class GraphicalRevoluteJoint(real: RevoluteJoint) extends GraphicalJoint { + val connection1 = real.connection1 + + def draw(): Unit = { + g.setColor(java.awt.Color.darkGray) + drawPoint(connection1) + } + +} diff --git a/src/main/scala/graphyx/graphics/GraphicalShape.scala b/src/main/scala/graphyx/graphics/GraphicalShape.scala new file mode 100644 index 0000000..256c041 --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalShape.scala @@ -0,0 +1,15 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.dynamics._ +trait GraphicalShape extends Shape with GraphicalObject{ + val real: Shape + override val uid: Int = real.uid + pos = real.pos + rotation = real.rotation +} \ No newline at end of file diff --git a/src/main/scala/graphyx/graphics/GraphicalSpringJoint.scala b/src/main/scala/graphyx/graphics/GraphicalSpringJoint.scala new file mode 100644 index 0000000..dbd9d5f --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalSpringJoint.scala @@ -0,0 +1,18 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.dynamics.joints._ + +case class GraphicalSpringJoint(real: SpringJoint) extends GraphicalJoint { + val connection1 = real.connection1 + val connection2 = real.connection2 + def draw(): Unit = { + g.setColor(java.awt.Color.GRAY) + drawLine(connection1, connection2) + } +} diff --git a/src/main/scala/graphyx/graphics/GraphicalWorld.scala b/src/main/scala/graphyx/graphics/GraphicalWorld.scala new file mode 100644 index 0000000..abc9cbb --- /dev/null +++ b/src/main/scala/graphyx/graphics/GraphicalWorld.scala @@ -0,0 +1,28 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.dynamics._ +case class GraphicalWorld(real: World){ + val time = real.time + val timeStep = real.timeStep + val iterations = real.iterations + val overCWarning = real.overCWarning + val gravity = real.gravity + val monitorResults = for (m <- real.monitors) yield + new MonitorResult(m, + for (b <- real.bodies.toList; if (b.monitor)) yield (b.uid, m._1, m._2(b)) + ) + val monitorFlatResults = for (b <- real.bodies; m <- real.monitors; if (b.monitor)) yield (b.uid, m._1, m._2(b)) + val enableCollisionDetection = real.enableCollisionDetection + val enablePositionCorrection = real.enablePositionCorrection +} + +class MonitorResult ( + val monitor: (String, Body => Any), + val results: List[(Int, String, Any)] +) diff --git a/src/main/scala/graphyx/graphics/Parser.scala b/src/main/scala/graphyx/graphics/Parser.scala new file mode 100644 index 0000000..785d985 --- /dev/null +++ b/src/main/scala/graphyx/graphics/Parser.scala @@ -0,0 +1,35 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.collision._ +import sims.dynamics._ +import sims.dynamics.joints._ +object Parser { + + val throwOnUnknown = false + + def toGraphical(real: Shape) = real match { + case c: Circle => new GraphicalCircle(c) + case r: Rectangle => new GraphicalRectangle(r) + case p: RegularPolygon => new GraphicalRegularPolygon(p) + case _ => throw new IllegalArgumentException("Cannot cast '" + real.getClass + "' to a graphical object.") + } + + def toGraphical(real: Joint) = real match { + case j: DistanceJoint => new GraphicalDistanceJoint(j) + case j: SpringJoint => new GraphicalSpringJoint(j) + case j: RevoluteJoint => new GraphicalRevoluteJoint(j) + case j: Joint => if (!throwOnUnknown) new GraphicalJoint{override val real = j; def draw = ()} + else throw new IllegalArgumentException("Cannot cast '" + real.getClass + "' to a graphical object.") + } + + def toGraphical(real: Collision) = new GraphicalCollision(real) + def toGraphical(real: Pair) = new GraphicalPair(real) + def toGraphical(real: AABB) = new GraphicalAABB(real) + def toGraphical(real: Body) = new GraphicalBody(real) +} diff --git a/src/main/scala/graphyx/graphics/Scene.scala b/src/main/scala/graphyx/graphics/Scene.scala new file mode 100644 index 0000000..bb1fd9e --- /dev/null +++ b/src/main/scala/graphyx/graphics/Scene.scala @@ -0,0 +1,24 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.graphics + +import sims.geometry._ +import sims.collision._ +import sims.dynamics._ +import sims.dynamics.joints._ +import collection.mutable._ + +case class Scene(real: World) { + val world: GraphicalWorld = GraphicalWorld(real) + val shapes = for (s: Shape <- real.shapes) yield Parser.toGraphical(s) + val joints = for (j: Joint <- real.joints) yield Parser.toGraphical(j) + val bodies = for (b: Body <- real.bodies) yield Parser.toGraphical(b) + val collisions = for (c: Collision <- real.detector.collisions) yield Parser.toGraphical(c) + val pairs = for (p: Pair <- real.detector.asInstanceOf[GridDetector].pairs) yield Parser.toGraphical(p) + val aabbs = for (s: Shape <- real.shapes) yield Parser.toGraphical(s.AABB) + val fps = 0 +} diff --git a/src/main/scala/graphyx/gui/AboutHelpFrame.scala b/src/main/scala/graphyx/gui/AboutHelpFrame.scala new file mode 100644 index 0000000..0bb3c36 --- /dev/null +++ b/src/main/scala/graphyx/gui/AboutHelpFrame.scala @@ -0,0 +1,24 @@ +package graphyx.gui + +import graphyx.actors._ +import graphyx.gui._ +import scala.swing._ +import scala.swing.event._ + +class AboutHelpFrame extends Frame { + title = "About" + contents = new TextArea( + """|Graphyx, testing and visualization tool for SiMS. + | + |copyright (c) 2009 Jakob Odersky + |SiMS and Graphyx are made available under the MIT License + | + |https://github.com/jodersky/sims + | + |Version 1.2""".stripMargin + ) {editable = false} +} + +object AboutHelpFrame { + val frame = new AboutHelpFrame +} diff --git a/src/main/scala/graphyx/gui/BodyPopup.scala b/src/main/scala/graphyx/gui/BodyPopup.scala new file mode 100644 index 0000000..998a440 --- /dev/null +++ b/src/main/scala/graphyx/gui/BodyPopup.scala @@ -0,0 +1,41 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import scala.swing._ +import scala.swing.event._ +import sims.dynamics._ +import graphyx.graphics._ + +class BodyPopup extends PopupMenu { + private var b: Body = _ + def body = b + def body_=(newBody: Body) = { + b = newBody + chckFixed.selected = b.fixed + chckMonitor.selected = b.monitor + } + + val chckMonitor = new CheckMenuItem("Monitor") + val chckFixed = new CheckMenuItem("Fixed") + val btnClose = new MenuItem("Close") + + add(chckMonitor) + add(chckFixed) + add(btnClose) + listenTo(chckMonitor, chckFixed, btnClose) + reactions += { + case ButtonClicked(b) => {setVisible(false) + b match { + case `chckMonitor` => body.monitor = chckMonitor.selected + case `chckFixed` => body.fixed = chckFixed.selected + case `btnClose` => () + case _ => () + } + } + } +} \ No newline at end of file diff --git a/src/main/scala/graphyx/gui/Container.scala b/src/main/scala/graphyx/gui/Container.scala new file mode 100644 index 0000000..80886f8 --- /dev/null +++ b/src/main/scala/graphyx/gui/Container.scala @@ -0,0 +1,37 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import sims.dynamics._ +import graphyx.graphics._ +import java.io._ +class Container { + val mainFrame = new MainFrame(this) + + //val plotFrames = new ArrayBuffer[plot.PlotFrame[Body]] + + var scene: Scene = Scene(new World) + + def show() = { + mainFrame.visible = true + } + + def update(s: Scene) = { + scene = s + mainFrame.mainPanel.controlPanel.update() + mainFrame.mainPanel.worldPanel.update() + mainFrame.mainPanel.infoPanel.update() + mainFrame.mainPanel.optionsPanel.update() + mainFrame.mainPanel.gravityPanel.update() + } + + def exitGUI() = { + mainFrame.dispose + AboutHelpFrame.frame.dispose + //plotFrames.foreach(_.dispose) + } +} diff --git a/src/main/scala/graphyx/gui/ControlPanel.scala b/src/main/scala/graphyx/gui/ControlPanel.scala new file mode 100644 index 0000000..43d7305 --- /dev/null +++ b/src/main/scala/graphyx/gui/ControlPanel.scala @@ -0,0 +1,40 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import graphyx._ +import graphyx.actors._ +import graphyx.gui._ +import scala.swing._ +import scala.swing.event._ + +class ControlPanel(container: Container) extends BoxPanel(Orientation.Horizontal) { + val btnStart = new Button {text = "Start"} //; icon = new javax.swing.ImageIcon("""play.png"""); tooltip = "Start"} + val btnStep = new Button {text = "Step"} + val btnStop = new Button {text = "Stop"} + val btnExit = new Button {text = "Exit"} + val btnFire = new Button {text = "Fire!"} + val btnReset = new Button {text = "Reset"} + val cboTest = new ComboBox(Graphyx.tests) + + contents ++= List(btnStart, btnStep, btnStop, btnExit, new Separator, btnFire, btnReset, cboTest) + + listenTo(btnStart, btnStep, btnStop, btnExit, btnFire, btnReset, cboTest.selection) + reactions += { + case ButtonClicked(`btnStart`) => Graphyx.physicsActor ! Start + case ButtonClicked(`btnStop`) => Graphyx.physicsActor ! Stop + case ButtonClicked(`btnStep`) => Graphyx.physicsActor ! Step + case ButtonClicked(`btnExit`) => Graphyx.exit + case ButtonClicked(`btnFire`) => Graphyx.physicsActor ! FireEvent + case ButtonClicked(`btnReset`) => Graphyx.test = Graphyx.tests(cboTest.selection.index) + case SelectionChanged(`cboTest`) => Graphyx.test = Graphyx.tests(cboTest.selection.index) + } + + def update() { + btnFire.enabled = Graphyx.test.enableEvent + } +} diff --git a/src/main/scala/graphyx/gui/GravityPanel.scala b/src/main/scala/graphyx/gui/GravityPanel.scala new file mode 100644 index 0000000..bdf5245 --- /dev/null +++ b/src/main/scala/graphyx/gui/GravityPanel.scala @@ -0,0 +1,83 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import scala.swing._ +import scala.swing.event._ +import scala.swing.GridBagPanel._ +import sims.geometry._ + +class GravityPanel(container: Container) extends GridBagPanel{ + + val c = new Constraints + c.fill = Fill.Both + this.border = Swing.EmptyBorder(3,3,3,3) + + val sldX = new Slider {max = 500; min = -500; preferredSize = minimumSize} + val lblX = new Label("0.0") + val sldY = new Slider {max = 500; min = -500; preferredSize = minimumSize} + val lblY = new Label("-9.81") + + c.gridx = 0 + c.gridy = 0 + c.weightx = 1.0 + c.weighty = 0.0 + super.add(new Label("Gravity"), c) + + c.gridx = 0 + c.gridy = 1 + c.weightx = 1.0 + c.weighty = 0.0 + super.add(new Label("X: "), c) + + c.gridx = 1 + c.gridy = 1 + c.weightx = 1.0 + c.weighty = 0.0 + super.add(sldX, c) + + c.gridx = 2 + c.gridy = 1 + c.weightx = 0.0 + c.weighty = 0.0 + super.add(lblX, c) + + c.gridx = 0 + c.gridy = 2 + c.weightx = 1.0 + c.weighty = 0.0 + super.add(new Label("Y: "), c) + + c.gridx = 1 + c.gridy = 2 + c.weightx = 1.0 + c.weighty = 0.0 + super.add(sldY, c) + + c.gridx = 2 + c.gridy = 2 + c.weightx = 0.0 + c.weighty = 0.0 + super.add(lblY, c) + + + listenTo(sldX, sldY) + + reactions += { + case ValueChanged(s) if (s == sldX || s == sldY) => + container.scene.real.gravity = Vector2D(sldX.value / 10.0, sldY.value / 10.0) + } + + def update() = { + val g = container.scene.world.gravity + sldX.value = (g.x * 10).toInt + lblX.text = ((g.x * 10).toInt / 10.0).toString + sldY.value = (g.y * 10).toInt + lblY.text = ((g.y * 10).toInt / 10.0).toString + } + +} diff --git a/src/main/scala/graphyx/gui/InfoPanel.scala b/src/main/scala/graphyx/gui/InfoPanel.scala new file mode 100644 index 0000000..d9dad43 --- /dev/null +++ b/src/main/scala/graphyx/gui/InfoPanel.scala @@ -0,0 +1,30 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import scala.swing._ +import scala.swing._ + +class InfoPanel(container: Container) extends BoxPanel(Orientation.Vertical){ + preferredSize = new java.awt.Dimension(200, 50) + + val out = new TextArea + out.editable = false + contents += out + border = Swing.EmptyBorder(3,3,3,3) + + def update() = { + out.text = "fps=" + container.scene.fps + "\n" + + "t=" + container.scene.world.time.formatted("%f") + "\n" + if (container.scene.world.overCWarning) { + out.foreground = java.awt.Color.red + out.text += "Warning: some bodies passed the speed of light! Simulation may be highly incorrect.\n" + } + else out.foreground = java.awt.Color.black + for (r <- container.scene.world.monitorFlatResults) out.text += "b" + r._1 + " " + r._2 + ": " + r._3 + "\n" + } +} diff --git a/src/main/scala/graphyx/gui/MainFrame.scala b/src/main/scala/graphyx/gui/MainFrame.scala new file mode 100644 index 0000000..4fdc9a2 --- /dev/null +++ b/src/main/scala/graphyx/gui/MainFrame.scala @@ -0,0 +1,25 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import graphyx._ +import sims._ +import scala.swing._ + +class MainFrame(container: Container) extends Frame{ + super.background = java.awt.Color.WHITE + title = "graphyx" + preferredSize = new java.awt.Dimension(1000,800) + + reactions += { + case event.WindowClosing(w) => Graphyx.exit() + } + + val mainPanel = new MainPanel(container) + contents = mainPanel + +} diff --git a/src/main/scala/graphyx/gui/MainPanel.scala b/src/main/scala/graphyx/gui/MainPanel.scala new file mode 100644 index 0000000..e4989e8 --- /dev/null +++ b/src/main/scala/graphyx/gui/MainPanel.scala @@ -0,0 +1,77 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import graphyx.graphics._ +import sims._ +import scala.swing._ +import swing.event._ +import GridBagPanel._ +import java.awt.Insets + +class MainPanel(container: Container) extends scala.swing.GridBagPanel { + val c = new Constraints + + val menuPanel = new MenuPanel(container) + val worldPanel = new WorldPanel(container) + val controlPanel = new ControlPanel(container) + val infoPanel = new InfoPanel(container) + val optionsPanel = new OptionsPanel(container) + val shapeInfoPanel = new ShapeInfoPanel(container) + val gravityPanel = new GravityPanel(container) + + val splitter = new SplitPane { + orientation = Orientation.Vertical + continuousLayout = true + resizeWeight = 1 + dividerSize = 2 + leftComponent = worldPanel + rightComponent = new SplitPane { + orientation = Orientation.Horizontal + continuousLayout = true + resizeWeight = 1 + dividerSize = 2 + topComponent = new SplitPane{ + orientation = Orientation.Horizontal + continuousLayout = true + resizeWeight = 1 + dividerSize = 2 + topComponent = infoPanel + bottomComponent = gravityPanel + } + bottomComponent = optionsPanel + } + } + c.fill = Fill.Both + + c.gridx = 0 + c.gridy = 0 + c.weightx = 1.0 + c.weighty = 0.0 + super.add(menuPanel, c) + + c.gridx = 0 + c.gridy = 1 + c.weightx = 1.0 + c.weighty = 0.0 + super.add(controlPanel, c) + + + c.gridx = 0 + c.gridy = 2 + c.weightx = 1.0 + c.weighty = 1.0 + super.add(splitter, c) + + /* + c.gridx = 1 + c.gridy = 1 + c.weightx = 0.0 + c.weighty = 1.0 + super.add(infoPanel, c) + */ +} diff --git a/src/main/scala/graphyx/gui/MenuHelp.scala b/src/main/scala/graphyx/gui/MenuHelp.scala new file mode 100644 index 0000000..1c73d51 --- /dev/null +++ b/src/main/scala/graphyx/gui/MenuHelp.scala @@ -0,0 +1,19 @@ +package graphyx.gui + +import graphyx.actors._ +import graphyx.gui._ +import scala.swing._ +import scala.swing.event._ + +class MenuHelp extends Menu("Help") { + val miAbout = new MenuItem("About...") + + val components = List(miAbout) + contents ++= components + + listenTo(components: _*) + reactions += { + case event.ButtonClicked(`miAbout`) => AboutHelpFrame.frame.visible = true + + } +} diff --git a/src/main/scala/graphyx/gui/MenuPanel.scala b/src/main/scala/graphyx/gui/MenuPanel.scala new file mode 100644 index 0000000..d3196fe --- /dev/null +++ b/src/main/scala/graphyx/gui/MenuPanel.scala @@ -0,0 +1,12 @@ +package graphyx.gui + +import graphyx.actors._ +import graphyx.gui._ +import scala.swing._ +import scala.swing.event._ + +class MenuPanel(container: Container) extends BoxPanel(Orientation.Horizontal) { + val mnu = new MenuBar + mnu.contents += new MenuHelp + contents += mnu +} diff --git a/src/main/scala/graphyx/gui/OptionsPanel.scala b/src/main/scala/graphyx/gui/OptionsPanel.scala new file mode 100644 index 0000000..525f352 --- /dev/null +++ b/src/main/scala/graphyx/gui/OptionsPanel.scala @@ -0,0 +1,128 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import graphyx.graphics._ +import sims.geometry._ +import sims.dynamics._ +import scala.swing._ +import scala.swing.event._ +import GridBagPanel._ + +class OptionsPanel(container: Container) extends GridPanel(12,2){ + /* + val c = new Constraints + c.anchor = Anchor.West + */ + + this.border = Swing.EmptyBorder(3,3,3,3) + this.hGap = 3 + this.vGap = 3 + + val lblTimeStep = new Label("h [Hz]") {tooltip = "Time Step"} + val txtTimeStep = new TextField + + val lblIterations = new Label("i [1]") {tooltip = "Iterations"} + val txtIterations = new TextField + + val lblCD = new Label("CD") {tooltip = "Collision Detection"} + val chckCD = new CheckBox("") + + val lblPC = new Label("PC") {tooltip = "Position Correction"} + val chckPC = new CheckBox("") + + val lblDraw = new Label("Draw") + + val lblDrawBodies = new Label("Bodies") + val chckDrawBodies = new CheckBox {selected = false} + + val lblDrawShapes = new Label("Shapes") + val chckDrawShapes = new CheckBox {selected = true} + + val lblDrawJoints = new Label("Joints") + val chckDrawJoints = new CheckBox {selected = true} + + val lblDrawAABBs = new Label("AABBs") + val chckDrawAABBs = new CheckBox {selected = false} + + val lblDrawPairs = new Label("Pairs") + val chckDrawPairs = new CheckBox {selected = false} + + val lblDrawCollisions = new Label("Collisions") + val chckDrawCollisions = new CheckBox {selected = false} + + val lblTrace = new Label("Trace") + val chckTrace = new CheckBox {selected = false} + + val components = List( + lblTimeStep, txtTimeStep, + lblIterations, txtIterations, + lblCD, chckCD, + lblPC, chckPC, + lblDraw, new Label(""), + lblDrawBodies, chckDrawBodies, + lblDrawShapes, chckDrawShapes, + lblDrawJoints, chckDrawJoints, + lblDrawAABBs, chckDrawAABBs, + lblDrawPairs, chckDrawPairs, + lblDrawCollisions, chckDrawCollisions, + lblTrace, chckTrace + ) + contents ++= components + listenTo(components: _*) + + reactions += { + case EditDone(`txtTimeStep`) => container.scene.world.real.timeStep = 1.0 / txtTimeStep.text.toInt + case EditDone(`txtIterations`) => container.scene.world.real.iterations = txtIterations.text.toInt + case ButtonClicked(`chckCD`) => container.scene.world.real.enableCollisionDetection = chckCD.selected + case ButtonClicked(`chckPC`) => container.scene.world.real.enablePositionCorrection = chckPC.selected + case ButtonClicked(`chckDrawBodies`) => container.mainFrame.mainPanel.worldPanel.drawBodies = chckDrawBodies.selected + case ButtonClicked(`chckDrawShapes`) => container.mainFrame.mainPanel.worldPanel.drawShapes = chckDrawShapes.selected + case ButtonClicked(`chckDrawJoints`) => container.mainFrame.mainPanel.worldPanel.drawJoints = chckDrawJoints.selected + case ButtonClicked(`chckDrawAABBs`) => container.mainFrame.mainPanel.worldPanel.drawAABBs = chckDrawAABBs.selected + case ButtonClicked(`chckDrawPairs`) => container.mainFrame.mainPanel.worldPanel.drawPairs = chckDrawPairs.selected + case ButtonClicked(`chckDrawCollisions`) => container.mainFrame.mainPanel.worldPanel.drawCollisions = chckDrawCollisions.selected + case ButtonClicked(`chckTrace`) => container.mainFrame.mainPanel.worldPanel.trace = chckTrace.selected + } + + def update() = { + if (!txtTimeStep.peer.hasFocus) + txtTimeStep.text = (1.0 / container.scene.world.timeStep).toString + if (!txtIterations.peer.hasFocus) + txtIterations.text = container.scene.world.iterations.toString + chckCD.selected = container.scene.world.enableCollisionDetection + chckPC.selected = container.scene.world.enablePositionCorrection + chckDrawBodies.selected = container.mainFrame.mainPanel.worldPanel.drawBodies + chckDrawShapes.selected = container.mainFrame.mainPanel.worldPanel.drawShapes + chckDrawJoints.selected = container.mainFrame.mainPanel.worldPanel.drawJoints + chckDrawAABBs.selected = container.mainFrame.mainPanel.worldPanel.drawAABBs + chckDrawPairs.selected = container.mainFrame.mainPanel.worldPanel.drawPairs + chckDrawCollisions.selected = container.mainFrame.mainPanel.worldPanel.drawCollisions + chckTrace.selected = container.mainFrame.mainPanel.worldPanel.trace + } + + + /* + def addCell(cm: Component)(x: Int, y: Int) = { + c.gridx = x + c.gridy = y + c.weightx = 0.5 + c.weighty = 0.0 + c. + if (cm.isInstanceOf[TextArea]) + c.fill = Fill.Horizontal + else + c.fill = Fill.None + super.add(cm, c) + } + + addCell(lblTimeStep)(0,0) + addCell(txtTimeStep)(1,0) + addCell(lblIterations)(0,1) + addCell(txtIterations)(1,1) + */ +} diff --git a/src/main/scala/graphyx/gui/PopupMenu.scala b/src/main/scala/graphyx/gui/PopupMenu.scala new file mode 100644 index 0000000..9679018 --- /dev/null +++ b/src/main/scala/graphyx/gui/PopupMenu.scala @@ -0,0 +1,20 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import scala.swing._ +import scala.swing.event._ +import javax.swing._ + +class PopupMenu extends Component +{ + override lazy val peer : JPopupMenu = new JPopupMenu + + def add(item: MenuItem) : Unit = { peer.add(item.peer) } + def setVisible(visible:Boolean) : Unit = { peer.setVisible(visible) } + /* Create any other peer methods here */ +} \ No newline at end of file diff --git a/src/main/scala/graphyx/gui/ShapeInfoPanel.scala b/src/main/scala/graphyx/gui/ShapeInfoPanel.scala new file mode 100644 index 0000000..d94c0bd --- /dev/null +++ b/src/main/scala/graphyx/gui/ShapeInfoPanel.scala @@ -0,0 +1,35 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import graphyx.graphics._ +import sims.geometry._ +import sims.dynamics._ +import scala.swing._ +import scala.swing.event._ +import GridBagPanel._ + +class ShapeInfoPanel(container: Container) extends GridPanel(2,2) { + + this.border = Swing.EmptyBorder(3,3,3,3) + this.hGap = 3 + this.vGap = 3 + + val lblBody = new Label("Body") + val lblValBody = new Label("0") + + val lblShape = new Label("Shape") + val lblValShape = new Label("0") + + val components = List( + lblBody, lblValBody, + lblShape, lblValShape + ) + + contents ++= components + +} diff --git a/src/main/scala/graphyx/gui/WorldPanel.scala b/src/main/scala/graphyx/gui/WorldPanel.scala new file mode 100644 index 0000000..ad14726 --- /dev/null +++ b/src/main/scala/graphyx/gui/WorldPanel.scala @@ -0,0 +1,179 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.gui + +import graphyx.graphics._ +import sims.geometry._ +import sims.dynamics._ +import scala.swing._ +import scala.swing.event._ +import scala.collection.mutable.Map +import scala.collection.mutable.Queue + +class WorldPanel(container: Container) extends BoxPanel(Orientation.Vertical){ + cursor = new java.awt.Cursor(java.awt.Cursor.CROSSHAIR_CURSOR) + val lblBody = new Label {text = "None @ (0, 0)"} + contents += lblBody + val popup = new BodyPopup + contents += popup + + implicit def point2Vector(p: java.awt.Point) = { + val x = p.x + val y = size.height - p.y + new Vector2D((x - offset.x) / scale / ppm, (y - offset.y) / scale / ppm) + } + + private val ppi = java.awt.Toolkit.getDefaultToolkit.getScreenResolution + val ppm = 39.37007874 * ppi + var scale = 0.02 + var offset = Vector2D(100, 100) //vector for point coordinates [px] + + def scene: Scene = container.scene + + def update() = { + repaint() + } + + var drawBodies = false + var drawShapes = true + var drawJoints = true + var drawAABBs = false + var drawPairs = false + var drawCollisions = false + var trace = false + + override def paintComponent(g: java.awt.Graphics2D) = { + var parts: Seq[Drawable] = Seq() + if (drawShapes) parts ++= scene.shapes + if (drawJoints) parts ++= scene.joints + if (drawAABBs) parts ++= scene.aabbs + if (drawPairs) parts ++= scene.pairs + if (drawCollisions) parts ++= scene.collisions + if (drawBodies) parts ++= scene.bodies + g.clearRect(0,0,size.width,size.height) + drawAxes(g) + g.translate(offset.x.toInt, -offset.y.toInt) + drawParts(parts, g) + if (trace) trace(scene.shapes, g) + g.translate(-offset.x.toInt, offset.y.toInt) + } + + def drawAxes(g: java.awt.Graphics2D): Unit = { + g.setColor(java.awt.Color.GRAY) + g.drawLine(0, size.height - offset.y.toInt, size.width, size.height - offset.y.toInt) + g.drawLine(offset.x.toInt, 0, offset.x.toInt, size.height) + /* + val md = scale * ppm + val hb = size.width / md + for (i <- 1 to hb.toInt) g.drawLine(offset.x.toInt + i * md.toInt, size.height - offset.y.toInt, + offset.x.toInt + i * md.toInt, size.height - offset.y.toInt + 10) + */ + } + + def drawParts(parts: Iterable[Drawable], g: java.awt.Graphics2D) = { + for (p <- parts){ + p.g = g + p.windowHeight = super.size.height + p.ppm = ppm + p.scale = this.scale + p.draw() + } + } + + val prevPos: Map[Int, Queue[Vector2D]] = Map() + def trace(shapes: Iterable[GraphicalShape], g: java.awt.Graphics2D) = { + for (s <- shapes) { + s.g = g + s.windowHeight = super.size.height + s.ppm = ppm + s.scale = this.scale + + + if (!prevPos.contains(s.uid)) prevPos += (s.uid -> new Queue[Vector2D]) + else { + prevPos(s.uid).enqueue(s.pos) + for(i <- 0 until prevPos(s.uid).length - 1) { + val sp = prevPos(s.uid)(i) + val ep = prevPos(s.uid)(i + 1) + s.g.setColor(java.awt.Color.cyan) + s.drawLine(sp, ep) + } + if (prevPos(s.uid).length == 50) prevPos(s.uid).dequeue + } + } + } + + def getBody(p: Vector2D): Option[Body] = { + val shape = scene.shapes.find(_.contains(p)) + if (shape != None) Some(shape.get.real.body) + else None + } + + var mousePressed: Boolean = false + var startPoint = new java.awt.Point(0,0) + var endPoint = new java.awt.Point(0,0) + var grabbedBody: Option[GrabbedBody] = None + def grab(b: Body, p: Vector2D) = { + grabbedBody = Some(new GrabbedBody(b, p)) + b.fixed = true + } + + def release() = { + if (grabbedBody != None && grabbedBody.get.wasFixed == false) + grabbedBody.get.body.fixed = false + grabbedBody = None + } + + listenTo(mouse.clicks, mouse.moves, mouse.wheel) + reactions += { + case MousePressed(c,p,x,y,b) => { + mousePressed = true; startPoint = p; endPoint = p + x match { + case 1024 if (getBody(p) != None) => grab(getBody(p).get, p) + case 1152 if (getBody(p) != None) => {grabbedBody = Some(new GrabbedBody(getBody(p).get, p)); popup.body = grabbedBody.get.body; popup.peer.setLocation(p); popup.visible = true} + case 4096 if (getBody(p) != None) => {grabbedBody = Some(new GrabbedBody(getBody(p).get, p)); popup.body = grabbedBody.get.body; popup.peer.setLocation(p); popup.visible = true} + case _ => () + } + } + + case MouseMoved(c,p,i) => { + lblBody.text = (if (getBody(p) != None) getBody(p).get.uid.toString else "None") + " @ (" + point2Vector(p).x.formatted("%f") + ", " + point2Vector(p).y.formatted("%f") + ")" + } + + case MouseDragged(c,p,1088) => {//drag with shift + offset += Vector2D((p.x - endPoint.x), -(p.y - endPoint.y)) + mousePressed = true + endPoint = p + cursor = new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR) + } + + case MouseDragged(c,p,x) => + if (grabbedBody != None) grabbedBody.get.body.pos = p - grabbedBody.get.r + + case MouseReleased(c,p,x,y,b) => { + mousePressed = false + endPoint = p + cursor = new java.awt.Cursor(java.awt.Cursor.CROSSHAIR_CURSOR) + release() + } + + case MouseWheelMoved(c,p,1024,y) => { //with left mouse button pressed + if (grabbedBody != None) grabbedBody.get.body.rotation += 0.05 * y + } + + case MouseWheelMoved(c,p,x,y) => { + scale -= scale * 0.02 * y + } + + } +} + +class GrabbedBody(b: Body, point: Vector2D){ + def body = b + val r: Vector2D = point - body.pos + val wasFixed = b.fixed +} diff --git a/src/main/scala/graphyx/tests/Atom.scala b/src/main/scala/graphyx/tests/Atom.scala new file mode 100644 index 0000000..31d03fc --- /dev/null +++ b/src/main/scala/graphyx/tests/Atom.scala @@ -0,0 +1,36 @@ +package graphyx.tests + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.geometry._ + +object Atom extends Test{ + val title = "Atom" + val world = new World + + var nucleus = new Body(Circle(0.05, 1000)) {fixed = true} + var electrons: List[Body] = Nil + var connections: List[SpringJoint] = Nil + + def init = { + world -= nucleus + nucleus = new Body(Circle(0.05, 10)) {fixed = true} + world += nucleus + world --= electrons + electrons = Nil + for (c <- connections) world -= c + connections = Nil + } + + enableEvent = true + override def fireEvent = { + val e = (new Circle(0.1, 10) {pos = Vector2D(0, -1)}).asBody + e.linearVelocity = Vector2D(-50,100) + electrons = e :: electrons + world += e + + val c = new SpringJoint(nucleus, e, 500) + connections = c :: connections + world += c + } +} diff --git a/src/main/scala/graphyx/tests/BallStack.scala b/src/main/scala/graphyx/tests/BallStack.scala new file mode 100644 index 0000000..8e45611 --- /dev/null +++ b/src/main/scala/graphyx/tests/BallStack.scala @@ -0,0 +1,25 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +import sims.geometry._ + +object BallStack extends Test{ + val world = new World + val title = "BallStack" + def init(): Unit = { + val ground = new Rectangle(1,0.1,1) {pos = Vector2D(1,0)} + val wallLeft = new Rectangle(0.1,1,1) {pos = Vector2D(0,1)} + val wallRight = new Rectangle(0.1,1,1) {pos = Vector2D(2,1)} + val box = new Body(ground, wallLeft, wallRight) {fixed = true} + world += box + world += (new Circle(0.1,1) {pos = Vector2D(1.1, 2.8)}).asBody + world ++= (for (i <- 0 to 50) yield (new Circle(0.1,1) {pos = Vector2D(1, 3 + 0.2 * i)}).asBody) + + } +} diff --git a/src/main/scala/graphyx/tests/Cannon.scala b/src/main/scala/graphyx/tests/Cannon.scala new file mode 100644 index 0000000..6c59d3f --- /dev/null +++ b/src/main/scala/graphyx/tests/Cannon.scala @@ -0,0 +1,59 @@ +package graphyx.tests + +import sims.dynamics._ +import sims.geometry._ +import sims.prefabs._ + +object Cannon extends Test{ + val title = "Cannon" + val world = new World + + def init = { + val cannon = new Prefab{ + val hull = new Body( + new Rectangle(0.1,0.5,1) {pos = Vector2D(0.1, 0.6); friction = 0.0}, + new Rectangle(0.1,0.5,1) {pos = Vector2D(0.5, 0.6); friction = 0.0}, + new Rectangle(0.1,0.1,1) {pos = Vector2D(0.3, 0.2); friction = 0.0} + ) + hull.fixed = true + hull.rotation -= math.Pi / 2 + + val ball = new Body(new Circle(0.1,100) {pos = Vector2D(0.3, 0.56)}) + + override val bodies = List(hull, ball) + override val joints = Nil + } + val n = 10 + val r = 0.1 + val initialPos = Vector2D(5,0) + val stack = for (i <- (0 to n).toList) yield { + for (j <- (0 to n-i).toList) yield + new Body( + new Circle(r,10){ + pos = Vector2D(2 * j * r + i * r, 1.7 * i * r) + initialPos + } + ) {fixed = (i == 0)} + } + world += cannon + world ++= stack.flatten + + } + + enableEvent = true + override def fireEvent() = blastBomb + + def blastBomb() = { + val bombPos = Vector2D(0, 0.56) + val bombRadius = 1 + val bombImpulse = 200 + val region = new Circle(bombRadius, 0) {pos = bombPos} + val detector = world.detector.asInstanceOf[sims.collision.GridDetector] + val collisions = for (s <- world.shapes; if detector.colliding(sims.collision.Pair(region, s))) yield detector.collision(sims.collision.Pair(region, s)) + for (c <- collisions) { + if (c.shape1 != region) + for(p <- c.points) c.shape1.body.applyImpulse((p - bombPos).unit * bombImpulse, p) + if (c.shape2 != region) + for(p <- c.points) c.shape2.body.applyImpulse((p - bombPos).unit * bombImpulse, p) + } + } +} diff --git a/src/main/scala/graphyx/tests/Carriage.scala b/src/main/scala/graphyx/tests/Carriage.scala new file mode 100644 index 0000000..967c6e5 --- /dev/null +++ b/src/main/scala/graphyx/tests/Carriage.scala @@ -0,0 +1,55 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.geometry._ + +object Carriage extends Test{ + val title = "Carriage" + val world = new World + + def init = { + val car = new Car + + val groundShapes = for (i <- (0 to 200).toList) yield (new Rectangle(0.2, 0.1, 1) { + pos = Vector2D(0.4 * i, 0) + transientShapes += car.chassis.shapes(0) + }) + val ground = new Body(groundShapes: _*) //Rectangle(100, 0.1, 1).asBody + ground.pos = Vector2D(0,0) + ground.fixed = true + ground.rotation = -0.2 + + + world += ground + world += car + + } + + class Car extends sims.prefabs.Prefab { + + val chassis = (new Rectangle(0.5, 0.05, 10) {pos = Vector2D(0, 1)}).asBody + val rightWheel = (new Circle(0.1, 10) {pos = Vector2D(0.4,0.8)}).asBody + val leftWheel = (new Circle(0.1, 10) {pos = Vector2D(-0.4,0.8)}).asBody + + override val bodies = List(chassis, rightWheel, leftWheel) + + val rightStabelizer = new DistanceJoint(chassis, rightWheel) + val rightDamper = new SpringJoint(chassis, chassis.pos + Vector2D(rightWheel.pos.x, 0), + rightWheel, rightWheel.pos, 500) {damping = 1} + + val leftStabelizer = new DistanceJoint(chassis, leftWheel) + val leftDamper = new SpringJoint(chassis, chassis.pos + Vector2D(leftWheel.pos.x, 0), + leftWheel, leftWheel.pos, 500) {damping = 1} + + override val joints = List(rightStabelizer, rightDamper, leftStabelizer, leftDamper) + + } + +} diff --git a/src/main/scala/graphyx/tests/Chain.scala b/src/main/scala/graphyx/tests/Chain.scala new file mode 100644 index 0000000..27511ca --- /dev/null +++ b/src/main/scala/graphyx/tests/Chain.scala @@ -0,0 +1,26 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.prefabs._ +import sims.geometry._ + +object Chain extends Test{ + override val title = "Chain" + val world = new World + def init = { + val nodes = for (i <- (0 until 20).toList) yield (new Circle(0.02, 1) {pos = Vector2D(i * 0.2, 1)}).asBody + nodes(0).fixed = true + nodes(19).fixed = true + val connectors = for (i <- (0 until nodes.length - 1).toList) yield new DistanceJoint(nodes(i), nodes(i + 1)) + for (n <- nodes) world += n + for (c <- connectors) world += c + world += (new Circle(1,0.001) {pos = Vector2D(2,2)}).asBody + } +} diff --git a/src/main/scala/graphyx/tests/CompositeShape.scala b/src/main/scala/graphyx/tests/CompositeShape.scala new file mode 100644 index 0000000..184bab9 --- /dev/null +++ b/src/main/scala/graphyx/tests/CompositeShape.scala @@ -0,0 +1,36 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.geometry._ +import sims.dynamics._ + +import sims.util._ +import sims.util.Positioning._ + +object CompositeShape extends Test{ + val title = "Composite Shape" + val world = new World + + def init = { + + val ground = new Body(Rectangle(1000,0.1,1)) {fixed = true} + world += ground + + val h2o = { + val h = new Circle(0.2,1) + val o1 = new Circle(0.05,1) + val o2 = new Circle(0.05,1) {rotation = 0.3} + position(o1) {0.25 above h} + o2.pos = (new Polar(0.25, math.Pi / 3)) from h + new Body(h, o1, o2) {pos = Vector2D(0, 0.5)} + } + world += h2o + } + +} + diff --git a/src/main/scala/graphyx/tests/Cup.scala b/src/main/scala/graphyx/tests/Cup.scala new file mode 100644 index 0000000..ad791f0 --- /dev/null +++ b/src/main/scala/graphyx/tests/Cup.scala @@ -0,0 +1,31 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +import sims.geometry._ +object Cup extends Test { + val title = "Cup" + val world = new World + + def init = { + val ground = (new Rectangle(1000, 0.1, 1) {friction = 1}).asBody + ground.fixed = true + world += ground + + val cupShapes = for (i <- 0 to (10 * math.Pi).toInt) yield new Circle(0.1,1) {pos = Vector2D(math.cos(-i / 10.0), math.sin(-i / 10.0)); restitution = 0.0; friction = 1.0} + val cup = new Body(cupShapes: _*) {fixed = true; pos = Vector2D(0, 1)} + world += cup + + val ball1 = (new Circle(0.2, 1) {pos = Vector2D(0, 2)}).asBody + val ball2 = (new Circle(0.2, 1) {pos = Vector2D(-0.4, 2)}).asBody + val ball3 = (new Circle(0.2, 1) {pos = Vector2D(0.4, 2)}).asBody + world += ball1 + world += ball2 + world += ball3 + } +} diff --git a/src/main/scala/graphyx/tests/EmptyTest.scala b/src/main/scala/graphyx/tests/EmptyTest.scala new file mode 100644 index 0000000..0e3bd84 --- /dev/null +++ b/src/main/scala/graphyx/tests/EmptyTest.scala @@ -0,0 +1,15 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +import sims.geometry._ +object EmptyTest extends Test{ + override val title = "Empty Test" + val world = new World + def init = {} +} diff --git a/src/main/scala/graphyx/tests/Friction.scala b/src/main/scala/graphyx/tests/Friction.scala new file mode 100644 index 0000000..ba9fb69 --- /dev/null +++ b/src/main/scala/graphyx/tests/Friction.scala @@ -0,0 +1,57 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.geometry._ +import sims.dynamics._ +import sims.dynamics.joints._ + +object Friction extends Test{ + val title = "Friction" + val world = new World + + var r1: RevoluteJoint = _ + var r2: RevoluteJoint = _ + var r3: RevoluteJoint = _ + + def init = { + val ground = (new Rectangle(1000, 0.1, 1) {friction = 1}).asBody + ground.fixed = true + world += ground + + val ball1 = (new Circle(0.2, 1) {pos = Vector2D(0, 1); friction = 0.05}).asBody + ball1.angularVelocity = -80 + ball1.monitor = true + val ball2 = (new Circle(0.2, 1) {pos = Vector2D(1, 1); friction = 0.2}).asBody + ball2.angularVelocity = -80 + ball2.monitor = true + val ball3 = (new Circle(0.2, 1) {pos = Vector2D(2, 1); friction = 1}).asBody + ball3.angularVelocity = -80 + ball3.monitor = true + + world += ball1 + world += ball2 + world += ball3 + + world.monitors += ("", (b: Body) => "I=" + b.I + "\tw=" + b.angularVelocity + "\tEcin=" + 0.5 * b.I * b.angularVelocity * b.angularVelocity) + + r1 = RevoluteJoint(ground, ball1, ball1.pos) + r2 = RevoluteJoint(ground, ball2, ball2.pos) + r3 = RevoluteJoint(ground, ball3, ball3.pos) + world += r1 + world += r2 + world += r3 + } + + enableEvent = true + override def fireEvent = { + world -= r1 + world -= r2 + world -= r3 + } + +} diff --git a/src/main/scala/graphyx/tests/Friction2.scala b/src/main/scala/graphyx/tests/Friction2.scala new file mode 100644 index 0000000..5204fcf --- /dev/null +++ b/src/main/scala/graphyx/tests/Friction2.scala @@ -0,0 +1,33 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.geometry._ +import sims.dynamics._ +import sims.dynamics.joints._ + +object Friction2 extends Test{ + val title = "Friction2" + val world = new World {override val detector = new sims.collision.GridDetector(this) {gridSide = 0.2}} + + def init = { + val shapes = for (i <- (0 to 20).toList) yield (new Rectangle(0.2, 0.1, 1) { + pos = Vector2D(0.4 * i, 0) + friction = (i * 1.0 / 10) + restitution = 0 + }) + val ground = new Body(shapes: _*) + ground.pos = Vector2D(0,0) + ground.fixed = true + ground.rotation = -math.Pi / 5 + world += ground + + val b: Body = (new Circle(0.1,10)) ~ (new Circle(0.1,10) {pos = Vector2D(0.2,0)}) ~ (new Circle(0.1,10) {pos = Vector2D(0.4,0)}) + b.pos = Vector2D(0.1,0.1) + world += b + } +} diff --git a/src/main/scala/graphyx/tests/General1.scala b/src/main/scala/graphyx/tests/General1.scala new file mode 100644 index 0000000..4ab401f --- /dev/null +++ b/src/main/scala/graphyx/tests/General1.scala @@ -0,0 +1,126 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims._ +import sims.geometry._ +import sims.collision._ +import sims.dynamics._ +import sims.dynamics.joints._ +object General1 extends Test{ + override val title = "General1" + val world = new World + + def init() = { + val b0 = new Circle(0.1,1).asBody + b0.fixed = true + val b1 = (new Circle(0.1,1) {pos = Vector2D(0,1)}).asBody + //b0.linearVelocity = Vector2D(0,0.4) + b0.monitor = true + b1.monitor = true + val circles = for (i <- (0 until 10).toList) yield (new Circle(0.1,1) {pos = Vector2D(0, 1.2 + 0.2 * i)}).asBody + //for (c <- circles) world += c + //world.gravity = Vector2D.Null + // world += b0 + //world += b1 + + world.monitors += ("Veclocity = ", _.linearVelocity.length.toString) + + val b2 = (new Rectangle(0.1,0.15,1) {pos = Vector2D(1,0)}).asBody + b2.fixed = true + b2.rotation = 2 + val b3 = (new Circle(0.1,1) {pos = Vector2D(1,1.1)}).asBody + //world += b2 + //world += b3 + + val b4 = (new Rectangle(0.1,0.15,1) {pos = Vector2D(2,0)}).asBody + b4.fixed = true + b4.rotation = 2 + val b5 = (new Rectangle(0.1,0.15,1) {pos = Vector2D(2,1.2)}).asBody + //world += b4 + //world += b5 + + val bn = (new RegularPolygon(5,0.1,1) {pos = Vector2D(3,0)}).asBody + //world += bn + + //Make cannon and balls + val hull = new Body( + new Rectangle(0.1,0.5,1) {pos = Vector2D(0.1, 0.5)}, + new Rectangle(0.1,0.5,1) {pos = Vector2D(0.5, 0.5)}, + new Rectangle(0.1,0.1,1) {pos = Vector2D(0.3, 0.1)} + ) + hull.fixed = true + hull.rotation -= scala.math.Pi / 4 + + val ball = new Body( + new Circle(0.1,20) {pos = Vector2D(0.3, 0.3)} + ) + val ball2 = new Body( + new Circle(0.1,20) {pos = Vector2D(0.3, 0.5)} + ) + world += hull + world += ball + world += ball2 + + //Swing + val anchor = (new Circle(0.05,1) {pos = Vector2D(25,10)}).asBody + anchor.fixed = true + val block = (new RegularPolygon(9,0.5,2) {pos = Vector2D(25,1)}).asBody + val joint = new DistanceJoint(anchor, block) + world += anchor + world += block + world += joint + + //Make stack + val stack = for (i <- (0 until 10).toList) yield (new Circle(0.1,1) {pos = Vector2D(30, 0.2 + 0.2 * i)}).asBody + for (e <- stack) world += e + + + /* + val springBoardHull = new Body( + new Rectangle(0.1,0.5,1) {pos = Vector2D(-1.1, 0.5)}, + new Rectangle(0.1,0.5,1) {pos = Vector2D(-1.5, 0.5)}, + new Rectangle(0.1,0.1,1) {pos = Vector2D(-1.3, 0.1)} + ) + springBoardHull.fixed = true + world += springBoardHull + + val springBoard = new Body( + new Circle(0.1,20) {pos = Vector2D(-1.3, 0.5)} + ) + world += springBoard + + val spring = new SpringJoint(springBoardHull, Vector2D(-1.3, 0.1), springBoard, springBoard.pos, 2000) + spring.damping = 10 + world += spring + */ + + val ground = (new Rectangle(1000,0.5,1) {pos = Vector2D(0, -0.4)}).asBody + ground.fixed = true + world += ground + + world += (new Circle(0.1,1) {pos = Vector2D(2,2)}) ~ (new Circle(0.1,1) {pos = Vector2D(2,2.2)}) + } + + enableEvent = true + override def fireEvent() = blastBomb + + def blastBomb() = { + val bombPos = Vector2D(0, 0) + val bombRadius = 1 + val bombImpulse = 10 + val region = new Circle(bombRadius, 0) {pos = bombPos} + val detector = world.detector.asInstanceOf[GridDetector] + val collisions = for (s <- world.shapes; if detector.colliding(collision.Pair(region, s))) yield detector.collision(collision.Pair(region, s)) + for (c <- collisions) { + if (c.shape1 != region) + for(p <- c.points) c.shape1.body.applyImpulse((p - bombPos).unit * bombImpulse, p) + if (c.shape2 != region) + for(p <- c.points) c.shape2.body.applyImpulse((p - bombPos).unit * bombImpulse, p) + } + } +} diff --git a/src/main/scala/graphyx/tests/General2.scala b/src/main/scala/graphyx/tests/General2.scala new file mode 100644 index 0000000..2006080 --- /dev/null +++ b/src/main/scala/graphyx/tests/General2.scala @@ -0,0 +1,28 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.geometry._ +import sims.dynamics._ + +object General2 extends Test{ + val title = "General2" + val world = new World + + def init = { + world += new Body(new Rectangle(100,0.5,1) {pos = Vector2D(0, -0.5)}) {fixed = true} + //new Body(new Circle(0.05,1) {pos = Vector2D(0, 0.05)}), + //new Body(new Rectangle(0.5,0.1,1) {pos = Vector2D(0, 0.2)}), + //new Body(new Circle(0.05,1) {pos = Vector2D(1, 0.05)})) + + world += new Body(new Circle(0.2,1) {pos = Vector2D(5, 0.2)}) + world += new Body(new Rectangle(1.5,0.1,1) {pos = Vector2D(4.5, 0.5)}, new Rectangle(0.05,0.1,1) {pos = Vector2D(3.05,0.7)}) + world += new Body(new Circle(0.1,1) {pos = Vector2D(3.2, 0.7)}) + world += new Body(new Circle(0.5,10) {pos = Vector2D(8, 0.5)}) + + } +} diff --git a/src/main/scala/graphyx/tests/Joints1.scala b/src/main/scala/graphyx/tests/Joints1.scala new file mode 100644 index 0000000..ad143ec --- /dev/null +++ b/src/main/scala/graphyx/tests/Joints1.scala @@ -0,0 +1,24 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.geometry._ + +object Joints1 extends Test{ + override val title = "Joints1" + val world = new World + def init = { + val anchor = new Body(new Circle(0.03, 1) {pos = Vector2D(1,5)}) {fixed = true} + val weight = (new Rectangle(0.1, 0.5, 1) {pos = Vector2D(1,0)}).asBody + val joint = new DistanceJoint(anchor, anchor.pos, weight, weight.pos + Vector2D(0.1,0.2)) + world += anchor + world += weight + world += joint + } +} diff --git a/src/main/scala/graphyx/tests/Joints2.scala b/src/main/scala/graphyx/tests/Joints2.scala new file mode 100644 index 0000000..c190bc9 --- /dev/null +++ b/src/main/scala/graphyx/tests/Joints2.scala @@ -0,0 +1,29 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.geometry._ +import sims.util._ +import sims.util.Positioning._ + +object Joints2 extends Test{ + override val title = "Joints2" + val world = new World + def init() = { + val length = 100 + val distance = 0.2 + val anchors = for (i <- (0 until length).toList) yield new Body(new Circle(0.03,1) {pos = Vector2D(i * distance,5)}) {fixed = true} + val balls = for (i <- (0 until length).toList) yield new Body(new Circle(0.1,1) {pos = Vector2D(i * distance,0); restitution = 1}) + balls(0).pos = Vector2D(0, 5) + Polar(5, -math.Pi / 1.5).toCarthesian + val joints = for (i <- (0 until length).toList) yield new DistanceJoint(anchors(i), balls(i)) + for (a <- anchors) world += a + for (b <- balls) world += b + for (j <- joints) world += j + } +} diff --git a/src/main/scala/graphyx/tests/Net.scala b/src/main/scala/graphyx/tests/Net.scala new file mode 100644 index 0000000..c340a80 --- /dev/null +++ b/src/main/scala/graphyx/tests/Net.scala @@ -0,0 +1,22 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims._ +import sims.geometry._ +import sims.dynamics._ + +object Net extends Test{ + val title = "Net" + val world = new World + + def init = { + val n = new prefabs.Net(10, 10, Vector2D(4,4)) + n.bodies(9).fixed = true + world += n + } +} diff --git a/src/main/scala/graphyx/tests/RagdollTest.scala b/src/main/scala/graphyx/tests/RagdollTest.scala new file mode 100644 index 0000000..63c9ce5 --- /dev/null +++ b/src/main/scala/graphyx/tests/RagdollTest.scala @@ -0,0 +1,26 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.geometry._ +import sims.prefabs._ + +object RagdollTest extends Test { + val title = "Ragdoll" + val world = new World + + def init = { + val ground = new Body((for (i <- 0 to 1000) yield new Circle(0.5,1) {pos = Vector2D(0.5 * (i - 500), 0)}): _*) + ground.fixed = true + world += ground + + world += new Ragdoll(Vector2D(0, 5)) + } + +} diff --git a/src/main/scala/graphyx/tests/Restitution.scala b/src/main/scala/graphyx/tests/Restitution.scala new file mode 100644 index 0000000..9501a36 --- /dev/null +++ b/src/main/scala/graphyx/tests/Restitution.scala @@ -0,0 +1,21 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.geometry._ +import sims.dynamics._ + +object Restitution extends Test{ + val title = "Restitution" + val world = new World + + def init = { + world += new Body(new Rectangle(1000,0.1,10) {restitution = 1}) {fixed = true} + world ++= (for (i <- 0 until 10) yield (new Circle(0.05, 10) {pos = Vector2D(i * 0.5, 1); restitution = i / 10.0}).asBody) + } + +} diff --git a/src/main/scala/graphyx/tests/Spring.scala b/src/main/scala/graphyx/tests/Spring.scala new file mode 100644 index 0000000..e7fecb8 --- /dev/null +++ b/src/main/scala/graphyx/tests/Spring.scala @@ -0,0 +1,23 @@ +package graphyx.tests + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.geometry._ +import java.io._ + +object Spring extends Test{ + val title = "Spring" + val world = new World + + def init = { + val anchor = Circle(0.05, 10).asBody + anchor.fixed = true + val particle = (new Circle(0.1, 20) {pos = Vector2D(0, -3)}).asBody + val spring = new SpringJoint(anchor, particle, 500, 2) + spring.damping = 0.5 + + world += anchor + world += particle + world += spring + } +} diff --git a/src/main/scala/graphyx/tests/Stacking.scala b/src/main/scala/graphyx/tests/Stacking.scala new file mode 100644 index 0000000..63734b6 --- /dev/null +++ b/src/main/scala/graphyx/tests/Stacking.scala @@ -0,0 +1,24 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +import sims.geometry._ + +object Stacking extends Test{ + val world = new World + val title = "Stacking" + def init(): Unit = { + val sideWidth = 0.3 + val sideHeight = 0.2 + val boxes = 5 + val distance = 0.1 + val stack = for (i <- (0 until boxes).toList) yield (new Rectangle(sideWidth / (2 + 0.3 * i), sideHeight / 2, 1) {pos = Vector2D(1, i * (sideHeight + distance))}).asBody + stack(0).fixed = true + for (box <- stack) world += box + } +} diff --git a/src/main/scala/graphyx/tests/Test.scala b/src/main/scala/graphyx/tests/Test.scala new file mode 100644 index 0000000..ca0f8e8 --- /dev/null +++ b/src/main/scala/graphyx/tests/Test.scala @@ -0,0 +1,17 @@ +/* + * Graphyx + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package graphyx.tests + +import sims.dynamics._ +trait Test { + val world: World + val title: String + def init(): Unit + var enableEvent: Boolean = false + def fireEvent(): Unit = println("No custom event method defined.") + override def toString() = title +} diff --git a/src/main/scala/graphyx/tests/Wave.scala b/src/main/scala/graphyx/tests/Wave.scala new file mode 100644 index 0000000..d3359c1 --- /dev/null +++ b/src/main/scala/graphyx/tests/Wave.scala @@ -0,0 +1,34 @@ +package graphyx.tests + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.dynamics.joints.test._ +import sims.geometry._ + +object Wave extends Test{ + val title = "Wave" + val world = new World {gravity = Vector2D.Null} + + def init = { + val n = 50 + + val anchors = for (i <- (0 to n).toList) yield + new Body(new Circle(0.01,1) {pos = Vector2D(0.4 * i, 5)}) {fixed = true} + + val particles = for (i <- (0 to n).toList) yield + new Body(new Circle(0.1,10) {pos = Vector2D(0.4 * i, 0)}) + + val rails = for (i <- (0 to n).toList) yield + new PrismaticJoint(anchors(i), particles(i)) + + val springs = for (i <- (0 to n).toList) yield + new SpringJoint(anchors(i), particles(i), 5)// {damping = 0.00}) + + val lateralSprings = for (i <- (0 to (n - 1)).toList) yield + new SpringJoint(particles(i), particles(i + 1), 50.0) + + world ++= anchors + world ++= particles + for (j <- rails ++ springs ++ lateralSprings) world += j + } +} diff --git a/src/main/scala/sims/collision/AABB.scala b/src/main/scala/sims/collision/AABB.scala new file mode 100644 index 0000000..f3a0b71 --- /dev/null +++ b/src/main/scala/sims/collision/AABB.scala @@ -0,0 +1,28 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.collision + +import sims.geometry._ + +/** + * Axis Aligned Bounding Boxes (AABBs) are rectangles that frame a shape. + * Their X-Axis and Y-Axis orientation makes it easy to test two AABBs for overlap. + * @param minVertex Position vector of the bottom-left vertex + * @param maxVertex Position vector of the upper-right vertex + */ +case class AABB(val minVertex: Vector2D, + val maxVertex: Vector2D) +{ + /** + * Checks this AABB with box for overlap. + * @param box AABB with which to check for overlap*/ + def overlaps(box: AABB): Boolean = { + val d1 = box.minVertex - maxVertex + val d2 = minVertex - box.maxVertex + !(d1.x > 0 || d1.y > 0 || d2.x > 0 || d2.y > 0) + } +} diff --git a/src/main/scala/sims/collision/CircleCollision.scala b/src/main/scala/sims/collision/CircleCollision.scala new file mode 100644 index 0000000..04cf2d7 --- /dev/null +++ b/src/main/scala/sims/collision/CircleCollision.scala @@ -0,0 +1,22 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.collision + +import sims.geometry._ +import sims.dynamics._ + +/**Collision between two circles.*/ +case class CircleCollision(c1: Circle, c2: Circle) extends Collision { + val shape1 = c1 + val shape2 = c2 + val normal = (c2.pos - c1.pos).unit + val points = { + val distance = (c2.pos - c1.pos).length + val p = shape1.pos + normal * (distance - c2.radius) + List(p) + } +} diff --git a/src/main/scala/sims/collision/Collision.scala b/src/main/scala/sims/collision/Collision.scala new file mode 100644 index 0000000..65111c6 --- /dev/null +++ b/src/main/scala/sims/collision/Collision.scala @@ -0,0 +1,108 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.collision + +import sims.dynamics._ +import sims.geometry._ + +/**Collision between two shapes. Contains methods to compute the collision response.*/ +abstract class Collision extends Constraint { + + /**First colliding shape (reference shape).*/ + val shape1: Shape + + /**Second colliding shape (incident shape).*/ + val shape2: Shape + + /**Collision points.*/ + val points: Iterable[Vector2D] + + /**Normal vector to the collision face.*/ + val normal: Vector2D + + /* C = delta + * Cdot = (vp2 - vp1) dot n + * = v2 + (w2 cross r2) - v2 - (w1 cross r1) + * = v2 + (w2 cross (p - x2)) - v2 - (w1 cross(p - x1)) + * J = [-n -((p-x1) cross n) n ((p-x2) cross n)]*/ + def correctVelocity(h: Double) = { + val coefficientOfRestitution = shape1.restitution * shape2.restitution + for (p <- points) { + val b1 = shape1.body + val b2 = shape2.body + val relativeNormalVelocity = (b2.velocityOfPoint(p) - b1.velocityOfPoint(p)) dot normal + val Cdot = relativeNormalVelocity + relativeNormalVelocity * coefficientOfRestitution + if (Cdot <= 0) { + val r1 = p - b1.pos + val r2 = p - b2.pos + val cr1 = r1 cross normal + val cr2 = r2 cross normal + val invMass = 1/b1.mass * (normal dot normal) + 1/b1.I * cr1 * cr1 + 1/b2.mass * (normal dot normal) + 1/b2.I * cr2 * cr2 + val m = if (invMass == 0.0) 0.0 else 1/invMass + val lambda = -m * Cdot + //wenn fixed, dann ist Masse unendlich => kein 'if (fixed != true)' + b1.linearVelocity += -normal * lambda / b1.mass + b1.angularVelocity += -(r1 cross normal) * lambda / b1.I + b2.linearVelocity += normal * lambda / b2.mass + b2.angularVelocity += (r2 cross normal) * lambda / b2.I + correctFriction(p, (-normal * lambda).length / h, h) + } + } + } + + /* Cdot = vt = [v2 + (w2 cross r2) - v1 - (w2 cross r2)] dot t + * J = [-t -(r2 cross t) t (r1 cross t)] + * 1/m = J * M * JT + * = 1/m1 * (t dot t) + 1/m2 * (t dot t) + 1/I1 * (r1 cross u)^2 + 1/I2 * (r2 cross u)^2*/ + def correctFriction(point: Vector2D, normalForce: Double, h: Double) = { + val b1 = shape1.body + val b2 = shape2.body + val tangent = normal.leftNormal + val Cdot = (b2.velocityOfPoint(point) - b1.velocityOfPoint(point)) dot tangent + val r1 = point - b1.pos + val r2 = point - b2.pos + val cr1 = r1 cross tangent + val cr2 = r2 cross tangent + val invMass = 1/b1.mass * (tangent dot tangent) + 1/b1.I * cr1 * cr1 + 1/b2.mass * (tangent dot tangent) + 1/b2.I * cr2 * cr2 + val m = if (invMass == 0.0) 0.0 else 1/invMass + val lambda = -m * Cdot + val cf = shape1.friction * shape2.friction + val cl = math.min(math.max(-normalForce * cf * h, lambda), normalForce * cf * h) + val impulse = tangent * cl + b1.applyImpulse(-impulse, point) + b2.applyImpulse(impulse, point) + } + + def correctPosition(h: Double) = { + val b1 = shape1.body + val b2 = shape2.body + + for (p <- points) { + val overlap = shape1.project(normal) overlap shape2.project(normal) + val C = Collision.ToleratedOverlap - overlap + if (C <= 0.0) { + val r1 = p - b1.pos + val r2 = p - b2.pos + val cr1 = r1 cross normal + val cr2 = r2 cross normal + val invMass = 1/b1.mass + 1/b1.I * cr1 * cr1 + 1/b2.mass + 1/b2.I * cr2 * cr2 + val m = if (invMass == 0.0) 0.0 else 1/invMass + val impulse = -normal.unit * m * C + b1.pos += -impulse / b1.mass + b1.rotation += -(r1 cross impulse) / b1.I + b2.pos += impulse / b2.mass + b2.rotation += (r2 cross impulse) / b2.I + } + } + } +} + +object Collision { + + /**Tolerated overlap. Collision response will only be applied if the overlap of two shapes exceeds the tolerated overlap.*/ + val ToleratedOverlap: Double = 0.01 +} diff --git a/src/main/scala/sims/collision/Detector.scala b/src/main/scala/sims/collision/Detector.scala new file mode 100644 index 0000000..96af5dc --- /dev/null +++ b/src/main/scala/sims/collision/Detector.scala @@ -0,0 +1,21 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.collision + + +import sims.geometry._ +import sims.dynamics._ + +/**A world detects its collisions through concrete implementations of this class.*/ +abstract class Detector { + + /**The world whose shapes are to be checked for collisions.*/ + val world: World + + /**Returns all collisions between shapes in the world world.*/ + def collisions: Seq[Collision] +} \ No newline at end of file diff --git a/src/main/scala/sims/collision/GridDetector.scala b/src/main/scala/sims/collision/GridDetector.scala new file mode 100644 index 0000000..2196195 --- /dev/null +++ b/src/main/scala/sims/collision/GridDetector.scala @@ -0,0 +1,123 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.collision + +import sims.dynamics._ +import sims.geometry._ +import scala.collection._ +import scala.collection.mutable.ArrayBuffer +import scala.collection.mutable.HashMap + +/**A concrete implementation of Detector. GridDetector divides the world into a grid + * for faster collision detection.*/ +class GridDetector(override val world: World) extends Detector { + + /**Array of collision detection methods. These methods return true if two shapes are colliding.*/ + val detectionMethods = new ArrayBuffer[PartialFunction[(Shape, Shape), Boolean]] + detectionMethods += { + case (c1: Circle, c2: Circle) => { //collision if distance <= sum of radiuses + val d = (c1.pos - c2.pos).length + val rSum = c1.radius + c2.radius + d - rSum <= 0 + } + + case (p1: ConvexPolygon, p2: ConvexPolygon) => { //SAT + val sides = p1.sides ++ p2.sides + val axes = sides map (_.n0) + axes.forall((a: Vector2D) => p1.project(a) overlaps p2.project(a)) + } + + case (p: ConvexPolygon, c: Circle) => { //distance form center to sides or vertices + val distances = for (s <- p.sides) yield (s distance c.pos) + distances.exists(_ - c.radius <= 0) || (p contains c.pos) + } + + case (c: Circle, p: ConvexPolygon) => { //distance form center to sides or vertices + val distances = for (s <- p.sides) yield (s distance c.pos) + distances.exists(_ - c.radius <= 0) || (p contains c.pos) + } + } + + /**Array of methods returning collisions. It is assumed that both shapes are colliding.*/ + val collisionMethods = new ArrayBuffer[PartialFunction[(Shape, Shape), Collision]] + collisionMethods += { + case (c1: Circle, c2: Circle) => CircleCollision(c1, c2) + case (p1: ConvexPolygon, p2: ConvexPolygon) => PolyCollision(p1, p2) + case (p: ConvexPolygon, c: Circle) => PolyCircleCollision(p, c) + case (c: Circle, p: ConvexPolygon) => PolyCircleCollision(p, c) + } + + /**Checks the pair of shapes p for collision. + * @param p Pair of shapes.*/ + def colliding(p: Pair) = { + if (detectionMethods.exists(_.isDefinedAt(p))) + detectionMethods.find(_.isDefinedAt(p)).get.apply(p) + else throw new IllegalArgumentException("No collision method for colliding pair!") + } + + /**Returns the collision between both shapes of the pair p. + * @param p Pair of shapes.*/ + def collision(p: Pair): Collision = { + if (collisionMethods.exists(_.isDefinedAt(p))) + collisionMethods.find(_.isDefinedAt(p)).get.apply(p) + else throw new IllegalArgumentException("No collision found in colliding pair!") + } + + /**Width and height of a grid cell.*/ + var gridSide: Double = 2 + + /**Returns potential colliding pairs of shapes of the world world. + *

+ * A potential colliding pair is a pair of two shapes that comply with the following criteria: + *

*/ + def getPairs = { + val grid = new HashMap[(Int, Int), List[Shape]] + def gridCoordinates(v: Vector2D) = ((v.x / gridSide).toInt, (v.y / gridSide).toInt) + def addToGrid(s: Shape) = { + val aabb = s.AABB + val minCell = gridCoordinates(aabb.minVertex) + val maxCell = gridCoordinates(aabb.maxVertex) + val coords = for(i <- (minCell._1 to maxCell._1); j <- (minCell._2 to maxCell._2)) yield (i, j) + for (c <- coords) { + if (grid.contains(c)) + {if (grid(c).forall(_ ne s)) grid(c) = s :: grid(c)} + else + grid += (c -> List(s)) + } + } + for(s <- world.shapes) addToGrid(s) + var ps: List[Pair] = Nil + for(cell <- grid.valuesIterator) { + ps = ps ::: (for (s1: Shape <- cell; s2: Shape <- cell; + if (s1 ne s2); + if (s1.body ne s2.body); + if (s1.collidable && s2.collidable); + if (s1.AABB overlaps s2.AABB); + if (!s1.transientShapes.contains(s2) && !s2.transientShapes.contains(s1))) yield Pair(s1, s2) + ).distinct + } + ps.toSeq + } + + private var cache = (world.time, getPairs) + + /**All potential colliding pairs of the world. + * @see getPairs*/ + def pairs = {if (world.time != cache._1) cache = (world.time, getPairs); cache._2} + + /**Returns all colliding pairs.*/ + def collidingPairs: Seq[Pair] = for(p <- pairs; if (colliding(p))) yield p + + /**Returns all collisions.*/ + def collisions: Seq[Collision] = for(p <- pairs; if (colliding(p))) yield collision(p) +} diff --git a/src/main/scala/sims/collision/Overlap.scala b/src/main/scala/sims/collision/Overlap.scala new file mode 100644 index 0000000..97ecdd6 --- /dev/null +++ b/src/main/scala/sims/collision/Overlap.scala @@ -0,0 +1,11 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.collision + +import sims.geometry._ + +case class Overlap(poly: ConvexPolygon, sideNum: Int, overlap: Double) diff --git a/src/main/scala/sims/collision/Pair.scala b/src/main/scala/sims/collision/Pair.scala new file mode 100644 index 0000000..a01fb00 --- /dev/null +++ b/src/main/scala/sims/collision/Pair.scala @@ -0,0 +1,24 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.collision + +import sims.dynamics._ + +/**Pair of shapes.*/ +case class Pair(s1: Shape, s2: Shape){ + + override def equals(other: Any) = { //overriden to prevent removal during "GridDetector.getPairs" + other match { + case Pair(a, b) => ((a eq this.s1) && (b eq this.s2)) || ((b eq this.s1) && (a eq this.s2)) + case _ => false + } + } +} + +object Pair { + implicit def pair2Tuple(x: Pair) = (x.s1, x.s2) +} diff --git a/src/main/scala/sims/collision/PolyCircleCollision.scala b/src/main/scala/sims/collision/PolyCircleCollision.scala new file mode 100644 index 0000000..20f1d49 --- /dev/null +++ b/src/main/scala/sims/collision/PolyCircleCollision.scala @@ -0,0 +1,36 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.collision + +import sims.dynamics._ +import sims.geometry._ + +/**Collision between a convex polygon and a circle.*/ +case class PolyCircleCollision(p: ConvexPolygon, c: Circle) extends Collision { + require(p.isInstanceOf[Shape]) + val shape1 = p.asInstanceOf[Shape] + val shape2 = c + + val normal = { + //minimum overlap + var min = (p.sides(0) distance c.pos) - c.radius + var axis = p.sides(0).n0 + for (s <- p.sides; val delta = (s distance c.pos) - c.radius) if (delta <= 0 && delta < min) { + min = delta + axis = s.n0 + } + for (v <- p.vertices; val delta = (v - c.pos).length - c.radius) if (delta <= 0 && delta <= min){ + min = delta + axis = (c.pos - v).unit + } + axis + } + + val points = List( + c.pos - normal * c.radius + ) +} diff --git a/src/main/scala/sims/collision/PolyCollision.scala b/src/main/scala/sims/collision/PolyCollision.scala new file mode 100644 index 0000000..5296f41 --- /dev/null +++ b/src/main/scala/sims/collision/PolyCollision.scala @@ -0,0 +1,53 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.collision + +import sims.geometry._ +import sims.dynamics._ +import scala.collection.mutable.Map + +/**Collision between two convex polygons.*/ +case class PolyCollision(p1: ConvexPolygon, p2: ConvexPolygon) extends Collision { + require(p1.isInstanceOf[Shape]) + require(p2.isInstanceOf[Shape]) + + def overlap(axis: Vector2D) = { + // println((p1.project(axis) overlap p2.project(axis)).toString + " to " + (p2.project(axis) overlap p1.project(axis))) + p1.project(axis) overlap p2.project(axis) + } + + lazy val overlaps = (for (i <- 0 until p2.sides.length) yield Overlap(p2, i, overlap(p2.sides(i).n0))) ++ + (for (i <- 0 until p1.sides.length) yield Overlap(p1, i, overlap(p1.sides(i).n0))) + + private var potMinOverlap = overlaps.find(_.overlap > 0.0) + require(potMinOverlap != None) + private var _minOverlap: Overlap = potMinOverlap.get + var minOverlap: Overlap = { + for (o <- overlaps) if ((o.overlap < _minOverlap.overlap) && (o.overlap > 0.0)) _minOverlap = o + _minOverlap + } + + + private lazy val refPoly = minOverlap.poly + private lazy val incPoly = if (minOverlap.poly eq p1) p2 else p1 + + lazy val shape1 = refPoly.asInstanceOf[Shape] + lazy val shape2 = incPoly.asInstanceOf[Shape] + + lazy val normal = refPoly.sides(minOverlap.sideNum).n0 + lazy val points = (for (v <- incPoly.vertices; if refPoly.contains(v)) yield v)++ + (for (v <- refPoly.vertices; if incPoly.contains(v)) yield v) + + /* ++ + (for (s <- incPoly.sides; + val clip = s.clipToSegment(refPoly.sides((refPoly.sides.length - (minOverlap.sideNum + 1)) % refPoly.sides.length)); + if (clip != None)) yield clip.get) ++ + (for (s <- incPoly.sides; + val clip = s.clipToSegment(refPoly.sides((refPoly.sides.length - (minOverlap.sideNum - 1)) % refPoly.sides.length)); + if (clip != None)) yield clip.get) + */ +} diff --git a/src/main/scala/sims/dynamics/Body.scala b/src/main/scala/sims/dynamics/Body.scala new file mode 100644 index 0000000..8c0e2ee --- /dev/null +++ b/src/main/scala/sims/dynamics/Body.scala @@ -0,0 +1,141 @@ + +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics + +import sims.geometry._ +import sims.dynamics.joints._ + +/**A two dimensional rigid body is made out of shapes. + * @param shps shapes that belong to this body.*/ +class Body(shps: Shape*){ + + /**Unique identification number.*/ + val uid = Body.nextUid + + /**Shapes that belong to this body.*/ + val shapes: List[Shape] = shps.toList + + //Shapes are added during initialisation. + for (s <- shapes) { + s.body = this + s.refLocalPos = s.pos - pos + s.rotation0 = s.rotation + } + + private var isFixed: Boolean = false + + /**Returns whether this body is fixed or not.*/ + def fixed = isFixed + + /**Fixes or frees this body. By fixing, linear and angular velocities are set to zero.*/ + def fixed_=(value: Boolean) = { + if (value) {linearVelocity = Vector2D.Null; angularVelocity = 0.0} + isFixed = value + } + + /**Flag for a world to monitor the properties of this body. + * @see World#monitors*/ + var monitor: Boolean = false + + /**Returns the position of this body. The position is equivalent to the center of mass. + * @return position of this body*/ + def pos: Vector2D = // COM = sum(pos*mass)/M + (Vector2D.Null /: shapes)((v: Vector2D, s: Shape) => v + s.pos * s.mass) / + (0.0 /: shapes)((i: Double, s: Shape) => i + s.mass) + + /**Sets the position of this body. By doing so all its shapes are translated. + * @param newPos new position*/ + def pos_=(newPos: Vector2D) = { + val stepPos = pos + shapes.foreach((s: Shape) => s.pos = s.pos - stepPos + newPos) + } + + /**Contains the current rotation of this body.*/ + private var _rotation: Double = 0.0 + + /**Returns the current rotation of this body.*/ + def rotation: Double = _rotation + + /**Sets the rotation of this body. Position and rotation of shapes are modified accordingly. + * @param r new rotation*/ + def rotation_=(newRotation: Double) = { + _rotation = newRotation + val stepPos = pos + for (s <- shapes) { + s.rotation = newRotation + s.rotation0 + s.pos = stepPos + (s.refLocalPos rotate (newRotation)) + } + } + + /**Linear velocity of this body.*/ + var linearVelocity: Vector2D = Vector2D.Null + + /**Angular velocity of this body.*/ + var angularVelocity: Double = 0 + + /**Linear velocity of the given point on this body (in world coordinates).*/ + def velocityOfPoint(point: Vector2D) = linearVelocity + ((point - pos).leftNormal * angularVelocity) + + /**Resulting force on the COM of this body.*/ + var force: Vector2D = Vector2D.Null + + /**Resulting torque on this body.*/ + var torque: Double = 0 + + /**Returns the mass of this body. If the body is free, its mass is the sum of the masses of its shapes. + * If the body is fixed, its mass is infinite (Double.PositiveInfinity). + * @return this body's mass*/ + def mass: Double = if (fixed) Double.PositiveInfinity else (0.0 /: shapes)((i: Double, s: Shape) => i + s.mass) + + /**Returns the moment of inertia for rotations about the COM of this body. + * It is calculated using the moments of inertia of this body's shapes and the parallel axis theorem. + * If the body is fixed, its moment of inertia is infinite (Double.PositiveInfinity). + * @return moment of inertia for rotations about the COM of this body*/ + def I: Double = if (fixed) Double.PositiveInfinity else + (0.0 /: (for (s <- shapes) yield (s.I + s.mass * ((s.pos - pos) dot (s.pos - pos)))))(_+_) + + /**Applies a force to the COM of this body. + * @param force applied force*/ + def applyForce(force: Vector2D) = if (!fixed) this.force += force + + /**Applies a force to a point on this body. Warning: the point is considered to be contained within this body. + * @param force applied force + * @param point position vector of the point (in world coordinates)*/ + def applyForce(force: Vector2D, point: Vector2D) = if (!fixed) {this.force += force; torque += (point - pos) cross force} + + /**Applies an impulse to the COM of this body. + * @param impulse applied impulse*/ + def applyImpulse(impulse: Vector2D) = if (!fixed) linearVelocity += impulse / mass + + /**Applies an impulse to a point on this body. Warning: the point is considered to be contained within this body. + * @param impulse applied impulse + * @param point position vector of the point (in world coordinates)*/ + def applyImpulse(impulse: Vector2D, point: Vector2D) = if (!fixed) {linearVelocity += impulse / mass; angularVelocity += ((point - pos) cross impulse) / I} + + /**Checks if the point point is contained in this body.*/ + def contains(point: Vector2D) = shapes.exists(_.contains(point)) + + override def toString: String = { + "Body" + uid + " " + shapes + " fixed=" + fixed + " m=" + mass + " I=" + I + " pos=" + pos + " rot=" + rotation + " v=" + linearVelocity + " w=" + angularVelocity + " F=" + force + " tau=" + torque + } + + /**Creates a new body containing this body's shapes and the shape s. + * @param s new shape + * @return new body*/ + def ~(s: Shape) = new Body((s :: shapes): _*) + + /**Creates a new body containing this body's shapes and the shapes of another body b. + * @param b body with extra shapes + * @return new body*/ + def ~(b: Body) = new Body((this.shapes ::: b.shapes): _*) +} + +object Body { + private var uidCounter = -1 + private def nextUid = {uidCounter += 1; uidCounter} +} \ No newline at end of file diff --git a/src/main/scala/sims/dynamics/Circle.scala b/src/main/scala/sims/dynamics/Circle.scala new file mode 100644 index 0000000..d6db07d --- /dev/null +++ b/src/main/scala/sims/dynamics/Circle.scala @@ -0,0 +1,34 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics + +import sims.geometry._ +import sims.collision._ + +/** + * A circle. + * @param radius radius of this circle + * @param density density of this circle + */ +case class Circle(radius: Double, density: Double) extends Shape{ + + val volume = math.Pi * radius * radius + + val I = mass * radius * radius / 2 + + def AABB = new AABB(pos - Vector2D(radius,radius), + pos + Vector2D(radius,radius)) + + def project(axis: Vector2D) = if (axis.x != 0) Projection(axis, + (pos.project(axis).x / axis.x) - radius, + (pos.project(axis).x / axis.x) + radius) + else Projection(axis, + (pos.project(axis).y / axis.y) - radius, + (pos.project(axis).y / axis.y) + radius) + + def contains(point: Vector2D) = (point - pos).length <= radius +} diff --git a/src/main/scala/sims/dynamics/Constraint.scala b/src/main/scala/sims/dynamics/Constraint.scala new file mode 100644 index 0000000..eaa6952 --- /dev/null +++ b/src/main/scala/sims/dynamics/Constraint.scala @@ -0,0 +1,21 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics + +/**All constraints in SiMS implement this trait. + * Position and velocity can be corrected for each constraint. + * The implementation of constraints was inspired by Erin Catto's box2d.*/ +trait Constraint { + + /**Corrects the velocities of bodies according to this constraint. + * @param h a time interval, used for converting forces and impulses*/ + def correctVelocity(h: Double): Unit + + /**Corrects the positions of bodies according to this constraint. + * @param h a time interval, used for converting forces and impulses*/ + def correctPosition(h: Double): Unit +} diff --git a/src/main/scala/sims/dynamics/Rectangle.scala b/src/main/scala/sims/dynamics/Rectangle.scala new file mode 100644 index 0000000..89ab4c0 --- /dev/null +++ b/src/main/scala/sims/dynamics/Rectangle.scala @@ -0,0 +1,38 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics + +import sims.geometry._ +import sims.collision._ + +/**A rectangle is a polygon. + * @param halfWidth this rectangle's half width + * @param halfHeight this rectangle's half height + * @param density density of this rectangle + */ +case class Rectangle(halfWidth: Double, + halfHeight : Double, + density: Double) extends Shape with ConvexPolygon{ + + val volume = halfWidth * halfHeight * 4 + + val I = 1.0 / 12.0 * mass * ((2 * halfWidth) * (2 * halfWidth) + (2 * halfHeight) * (2 * halfHeight)) + + /**Returns the vectors from the center to the vertices of this rectangle. + * The first vertex is the upper-right vertex at a rotation of 0. + * Vertices are ordered counter-clockwise.*/ + def halfDiags: Array[Vector2D] = Array(Vector2D(halfWidth, halfHeight), + Vector2D(-halfWidth, halfHeight), + Vector2D(-halfWidth, -halfHeight), + Vector2D(halfWidth, -halfHeight)) map (_ rotate rotation) + + /**Returns the position vectors of this rectangle's vertices. + * The first vertex is the upper-right vertex at a rotation of 0. + * Vertices are ordered counter-clockwise.*/ + def vertices = for (h <- halfDiags) yield pos + h + +} \ No newline at end of file diff --git a/src/main/scala/sims/dynamics/RegularPolygon.scala b/src/main/scala/sims/dynamics/RegularPolygon.scala new file mode 100644 index 0000000..6f08ca1 --- /dev/null +++ b/src/main/scala/sims/dynamics/RegularPolygon.scala @@ -0,0 +1,35 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics + +import math._ +import sims.geometry._ + +/**A regular polygon with n sides whose excircle has a radius radius. + * @param n nmber of sides. + * @param radius radius of the excircle + * @param density density of this regular polygon + * @throws IllegalArgumentException if n is smaller than 3 */ +case class RegularPolygon(n: Int, radius: Double, density: Double) extends Shape with ConvexPolygon{ + require(n >= 3, "A polygon must have at least 3 sides.") + + /**Height of one of the constituting triangles.*/ + private val h: Double = radius * cos(Pi / n) + /**Half width of one of the constituting triangles.*/ + private val b: Double = radius * sin(Pi / n) + + def halfDiags = (for (i: Int <- (0 until n).toArray) yield (Vector2D(0, radius) rotate (2 * Pi * i / n))) map (_ rotate rotation) + + def vertices = for (h <- halfDiags) yield pos + h + + val volume = n * h * b + + /**Moment of inertia of one of the constituting triangles about the center of this polygon.*/ + private val Ic: Double = density * b * (3 * b + 16) * h * h * h * h / 54 + + val I = n * Ic +} diff --git a/src/main/scala/sims/dynamics/Shape.scala b/src/main/scala/sims/dynamics/Shape.scala new file mode 100644 index 0000000..47a4199 --- /dev/null +++ b/src/main/scala/sims/dynamics/Shape.scala @@ -0,0 +1,97 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics + +import sims.geometry._ +import sims.collision._ + +/** +* An abstract shape. +*/ +abstract class Shape{ + + /**Unique identification number.*/ + val uid: Int = Shape.nextUid + + /**Flag determining this shapes ability to collide with other shapes.*/ + var collidable: Boolean = true + + /**Part of the coefficient of restitution for a collision between this shape and another. + * The coefficient of restitution is calculated out of the product of this part and the other shape's part.*/ + var restitution: Double = 0.7 + + /**Part of the coefficient of friction for a collision between this shape and another. + * The coefficient of friction is calculated out of the product of this part and the other shape's part.*/ + var friction: Double = 0.707 + + /**Position of this shape's COM (in world coordinates).*/ + var pos: Vector2D = Vector2D.Null + + /**Rotation of this shape about its COM.*/ + var rotation: Double = 0 + + /**Initial rotation. Rotation of this shape before it was added to a body.*/ + var rotation0 = 0.0 + + /**Local position of this shape's body COM to its COM at a body rotation of zero.*/ + var refLocalPos: Vector2D = Vector2D.Null + + /**Density. (Mass per area)*/ + val density: Double + + /**Volume. The volume is actually equivalent to this shape's area (SiMS is in 2D) + * and is used with this shape's density to calculate its mass.*/ + val volume: Double + + /**Returns the mass of this shape. The mass is given by volume times density. + @return mass of this shape*/ + def mass = volume * density + + /**Moment of inertia for a rotation about this shape's COM.*/ + val I: Double + + /**Containing body.*/ + private var _body: Body = _ + + /**Returns this shape's containing body.*/ + def body = _body + + /**Sets this shape's containing body.*/ + private[dynamics] def body_=(b: Body) = _body = b + + /**Returns this shape's axis aligned bounding box.*/ + def AABB: AABB + + /**Returns the projection of this shape onto the line given by the directional vector axis. + * @param axis directional vector of the line + * @return projection of this shape*/ + def project(axis: Vector2D): Projection + + /**Checks if the point point is contained in this shape.*/ + def contains(point: Vector2D): Boolean + + /**Creates a new body made out of tis shape. + @return a body made out of tis shape*/ + def asBody = new Body(this) + + /**Shapes with which this shape cannot collide.*/ + val transientShapes: collection.mutable.Set[Shape] = collection.mutable.Set() + + /**Creates a new body out of this shape and the shape s.*/ + def ~(s: Shape) = new Body(this, s) + + /**Creates a new body out of this shape and the shapes of body b.*/ + def ~(b: Body) = { + val shapes = this :: b.shapes + new Body(shapes: _*) + } +} + +object Shape { + private var uidCounter = -1 + private def nextUid = {uidCounter += 1; uidCounter} +} diff --git a/src/main/scala/sims/dynamics/World.scala b/src/main/scala/sims/dynamics/World.scala new file mode 100644 index 0000000..f24a3fd --- /dev/null +++ b/src/main/scala/sims/dynamics/World.scala @@ -0,0 +1,164 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics + +import sims.geometry._ +import sims.collision._ +import sims.dynamics.joints._ +import scala.collection.mutable.ArrayBuffer + +/**A world contains and simulates a system of rigid bodies and joints.*/ +class World { + + /**Time intervals in which this world simulates.*/ + var timeStep: Double = 1.0 / 60 + + /**Number of constraint corrections per time step.*/ + var iterations: Int = 10 + + /**Gravity in this world.*/ + var gravity = Vector2D(0, -9.81) + + /**Bodies contained in this world.*/ + val bodies = new ArrayBuffer[Body] + + /**Joints contained in this world.*/ + val joints = new ArrayBuffer[Joint] + + /**Monitoring methods for bodies. + *

+ * The first element of the tuple is the method's title and the second the method. + * Example usage: monitors += ("Y-Position", _.pos.y.toString) + * This will calculate all bodies - whose monitor field is set to + * true - second position components.*/ + val monitors = new ArrayBuffer[(String, Body => Any)] + + /**Collsion detector who manages collision detection in this world.*/ + val detector: Detector = new GridDetector(this) + + /**Warning if a body's velocity exceeds the speed of light.*/ + var overCWarning = false + + /**Flag to enable collision detection.*/ + var enableCollisionDetection = true + + /**Flag to enable position correction for constraints.*/ + var enablePositionCorrection = true + + /**Minimal, non-zero linear velocity.*/ + var minLinearVelocity: Double = 0.0001 + + /**Minimal, non-zero angular velocity.*/ + var minAngularVelocity: Double = 0.0001 + + /**Returns all shapes of all bodies in this world.*/ + def shapes = for (b <- bodies; s <- b.shapes) yield s + + /**Adds the given body to this world.*/ + def +=(body: Body) = bodies += body + + /**Adds the given joint to this world.*/ + def +=(joint: Joint): Unit = joints += joint + + /**Adds the given prefabricated system of bodies and joints to this world.*/ + def +=(p: sims.prefabs.Prefab): Unit = { + for (b <- p.bodies) this += b + for (j <- p.joints) this += j + } + + /**Adds the given sequence of bodies to this world.*/ + def ++=(bs: Seq[Body]): Unit = for(b <- bs) this += b + + /**Removes the given body from this world.*/ + def -=(body: Body): Unit = bodies -= body + + /**Removes the given joint from this world.*/ + def -=(joint: Joint): Unit = joints -= joint + + /**Removes the given prefabricated system of bodies and joints from this world.*/ + def -=(p: sims.prefabs.Prefab): Unit = { + for (b <- p.bodies) this -= b + for (j <- p.joints) this -= j + } + + /**Removes the given sequence of bodies from this world.*/ + def --=(bs: Seq[Body]) = for(b <- bs) this -= b + + /**Removes all bodies, joints and monitoring methods from this world.*/ + def clear() = {joints.clear(); bodies.clear(); monitors.clear()} + + /**Current time in this world.*/ + var time: Double = 0.0 + + /**Simulates a time step of the duration timeStep. + *

+ * The time step is simulated in the following phases: + *

    + *
  1. Forces are applied to bodies.
  2. + *
  3. Accelerations are integrated.
  4. + *
  5. Velocities are corrected.
  6. + *
  7. Velocities are integrated.
  8. + *
  9. Postions are corrected.
  10. + *
  11. The method postStep() is executed.
  12. + *
*/ + def step() = { + time += timeStep + + //force applying objects + for (j <- joints) j match {case f: ForceJoint => f.applyForce; case _ => ()} + + //integration of acclerations, yields velocities + for (b <- bodies) { + b.applyForce(gravity * b.mass) + b.linearVelocity = b.linearVelocity + (b.force / b.mass) * timeStep + b.angularVelocity = b.angularVelocity + (b.torque / b.I) * timeStep + } + + //correction of velocities + for (i <- 0 until iterations){ + for(c <- joints) c.correctVelocity(timeStep) + if (enableCollisionDetection) for (c <- detector.collisions) c.correctVelocity(timeStep) + } + + //integration of velocities, yields positions + for (b <- bodies) { + //warning when body gets faster than speed of light + if (b.linearVelocity.length >= 300000000) overCWarning = true + if (b.linearVelocity.length < minLinearVelocity) b.linearVelocity = Vector2D.Null + if (b.angularVelocity.abs < minAngularVelocity) b.angularVelocity = 0.0 + b.pos = b.pos + b.linearVelocity * timeStep + b.rotation = b.rotation + b.angularVelocity * timeStep + b.force = Vector2D.Null + b.torque = 0.0 + } + + //correction of positions + if (enablePositionCorrection) for (i <- 0 until iterations){ + for (c <- joints) c.correctPosition(timeStep) + if (enableCollisionDetection) for (c <- detector.collisions) c.correctPosition(timeStep) + } + + postStep() + } + + /**Initially empty method that is executed after each time step. This method + * may be overriden to create custom behaviour in a world.*/ + def postStep() = {} + + /**Returns information about this world.*/ + def info = { + "Bodies = " + bodies.length + "\n" + + "Shapes = " + shapes.length + "\n" + + "Joints = " + joints.length + "\n" + + "Collisions = " + detector.collisions.length + "\n" + + "Monitors = " + monitors.length + "\n" + + "Gravity = " + gravity + "m/s^2\n" + + "Timestep = " + timeStep + "s\n" + + "Time = " + time + "s\n" + + "Iterations = " + iterations + } +} diff --git a/src/main/scala/sims/dynamics/joints/DistanceJoint.scala b/src/main/scala/sims/dynamics/joints/DistanceJoint.scala new file mode 100644 index 0000000..1bf9b46 --- /dev/null +++ b/src/main/scala/sims/dynamics/joints/DistanceJoint.scala @@ -0,0 +1,77 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics.joints + +import sims.dynamics._ +import sims.geometry._ + +/** DistanceJoints keep their connection points at a constant distance. + * @param node1 first associated body + * @param anchor1 first connection point + * @param node2 second associated body + * @param anchor2 second connection point*/ +case class DistanceJoint(node1: Body, anchor1: Vector2D, node2: Body, anchor2: Vector2D) extends Joint{ + def this(node1: Body, node2: Body) = this(node1, node1.pos, node2, node2.pos) + + /**Distance between the two connection points at initialisation (the desired distance).*/ + val distance = (anchor2 - anchor1).length + + private val a1 = anchor1 - node1.pos + private val a2 = anchor2 - node2.pos + private val initRotation1 = node1.rotation + private val initRotation2 = node2.rotation + + /**Returns the connection point on body one (in world coordinates).*/ + def connection1 = (a1 rotate (node1.rotation - initRotation1)) + node1.pos + + /**Returns the connection point on body two (in world coordinates).*/ + def connection2 = (a2 rotate (node2.rotation - initRotation2)) + node2.pos + + /**Relative position of the connection points.*/ + def x = connection2 - connection1 + + /**Relative velocity of the connection points.*/ + def v = node2.velocityOfPoint(connection2) - node1.velocityOfPoint(connection1) + + /* x = connection2 - connection1 + * C = ||x|| - L + * u = x / ||x|| + * v = v2 + w2 cross r2 - v1 - w1 cross r1 + * Cdot = u dot v + * J = [-u -(r1 cross u) u (r2 cross u)] + * 1/m = J * M^-1 * JT + * = 1/m1 * u * u + 1/m2 * u * u + 1/I1 * (r1 cross u)^2 + 1/I2 * (r2 cross u)^2*/ + override def correctVelocity(h: Double) = { + val x = this.x //relative position + val v = this.v //relative velocity + val r1 = (connection1 - node1.pos) + val r2 = (connection2 - node2.pos) + val cr1 = r1 cross x.unit + val cr2 = r2 cross x.unit + val Cdot = x.unit dot v //velocity constraint + val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 //=J M^-1 JT + val m = if (invMass == 0.0) 0.0 else 1/invMass //avoid division by zero + val lambda = -m * Cdot //=-JV/JM^-1JT + val impulse = x.unit * lambda //P=J lambda + node1.applyImpulse(-impulse, connection1) + node2.applyImpulse(impulse, connection2) + } + + override def correctPosition(h: Double) = { + val C = x.length - distance + val cr1 = (connection1 - node1.pos) cross x.unit + val cr2 = (connection2 - node2.pos) cross x.unit + val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 + val m = if (invMass == 0.0) 0.0 else 1/invMass + val impulse = -x.unit * m * C + node1.pos -= impulse / node1.mass + node2.pos += impulse / node2.mass + node1.rotation -= ((connection1 - node1.pos) cross impulse) / node1.I + node2.rotation += ((connection2 - node2.pos) cross impulse) / node2.I + } + +} \ No newline at end of file diff --git a/src/main/scala/sims/dynamics/joints/ForceJoint.scala b/src/main/scala/sims/dynamics/joints/ForceJoint.scala new file mode 100644 index 0000000..2074ee4 --- /dev/null +++ b/src/main/scala/sims/dynamics/joints/ForceJoint.scala @@ -0,0 +1,14 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics.joints + +/**A joint which can apply a force to its anchor bodies, thus adding or removing energy to the system.*/ +trait ForceJoint { + + /**Applies a force on the anchor bodies.*/ + def applyForce(): Unit +} diff --git a/src/main/scala/sims/dynamics/joints/Joint.scala b/src/main/scala/sims/dynamics/joints/Joint.scala new file mode 100644 index 0000000..652df97 --- /dev/null +++ b/src/main/scala/sims/dynamics/joints/Joint.scala @@ -0,0 +1,27 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics.joints + +import sims.geometry._ +import sims.dynamics._ + +/**Joints constrain the movement of two bodies. + * Their implementation was inspired by Erin Catto's box2d.*/ +abstract class Joint extends Constraint{ + + /**First body of the joint.*/ + val node1: Body + + /**Second body of the joint.*/ + val node2: Body + + /**Corrects the velocities of this joint's associated bodies.*/ + def correctVelocity(h: Double): Unit + + /**Corrects the positions of this joint's associated bodies.*/ + def correctPosition(h: Double): Unit +} \ No newline at end of file diff --git a/src/main/scala/sims/dynamics/joints/RevoluteJoint.scala b/src/main/scala/sims/dynamics/joints/RevoluteJoint.scala new file mode 100644 index 0000000..bf6f05e --- /dev/null +++ b/src/main/scala/sims/dynamics/joints/RevoluteJoint.scala @@ -0,0 +1,57 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics.joints + +import sims.geometry._ +import sims.math._ +import sims.dynamics._ +import math._ + +/**A revolute joint that connects two bodies at a singe point. Inspired from JBox2D. + * Warning: there are still several bugs with revolute joints, if they are between two free + * bodies and not connected at their respective COMs.*/ +case class RevoluteJoint(node1: Body, node2: Body, anchor: Vector2D) extends Joint{ + private val a1 = anchor - node1.pos + private val a2 = anchor - node2.pos + private val initRotation1 = node1.rotation + private val initRotation2 = node2.rotation + def connection1 = (a1 rotate (node1.rotation - initRotation1)) + node1.pos + def connection2 = (a2 rotate (node2.rotation - initRotation2)) + node2.pos + + def x = connection2 - connection1 + def v = node2.velocityOfPoint(connection2) - node1.velocityOfPoint(connection1) + + /* x = connection2 - connection1 + * C = x + * Cdot = v = v2 - v1 = v2 + (w2 cross r2) - v1 - (w1 cross r1) + * J = [-I -r1_skew I r2_skew ] ????? + */ + def correctVelocity(h: Double) = { + val m1 = node1.mass + val m2 = node2.mass + val I1 = node1.I + val I2 = node2.I + val r1 = connection1 - node1.pos + val r2 = connection2 - node2.pos + + val K1 = new Matrix22(1/m1 + 1/m2, 0, + 0, 1/m1 + 1/m2) + val K2 = new Matrix22(1/I1 * r1.x * r1.x, -1/I1 * r1.x * r1.y, + -1/I1 * r1.x * r1.y, 1/I1 * r1.x * r1.x) + val K3 = new Matrix22(1/I2 * r2.x * r2.x, -1/I2 * r2.x * r2.y, + -1/I2 * r2.x * r2.y, 1/I2 * r2.x * r2.x) + val pivotMass = (K1 + K2 + K3).invert + val cdot = v + val p = pivotMass * cdot + node1.applyImpulse(p, connection1) + node2.applyImpulse(-p, connection2) + } + + def correctPosition(h: Double) = { + + } +} diff --git a/src/main/scala/sims/dynamics/joints/SpringJoint.scala b/src/main/scala/sims/dynamics/joints/SpringJoint.scala new file mode 100644 index 0000000..10d5afb --- /dev/null +++ b/src/main/scala/sims/dynamics/joints/SpringJoint.scala @@ -0,0 +1,85 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics.joints + +import sims.dynamics._ +import sims.geometry._ + +/**A spring obeying Hooke's law. + * @param node1 first associated body + * @param anchor1 first connection point + * @param node2 second associated body + * @param anchor2 second connection point + * @param springConstant spring constant + * @param initialLength initial length + */ +case class SpringJoint(node1: Body, anchor1: Vector2D, node2: Body, anchor2: Vector2D, springConstant: Double, initialLength: Double) extends Joint with ForceJoint{ + + def this(node1: Body, anchor1: Vector2D, node2: Body, anchor2: Vector2D, springConstant: Double) = { + this(node1: Body, anchor1, node2: Body, anchor2, springConstant: Double, (anchor2 - anchor1).length) + } + + def this(node1: Body, node2: Body, springConstant: Double, initialLength: Double) = { + this(node1: Body, node1.pos, node2: Body, node2.pos, springConstant: Double, initialLength: Double) + } + def this(node1: Body, node2: Body, springConstant: Double) = { + this(node1: Body, node1.pos, node2: Body, node2.pos, springConstant: Double, (node2.pos - node1.pos).length) + } + + private val a1 = anchor1 - node1.pos + private val a2 = anchor2 - node2.pos + private val initRotation1 = node1.rotation + private val initRotation2 = node2.rotation + + /**Returns the connection point on body one (in world coordinates).*/ + def connection1 = (a1 rotate (node1.rotation - initRotation1)) + node1.pos + + /**Returns the connection point on body two (in world coordinates).*/ + def connection2 = (a2 rotate (node2.rotation - initRotation2)) + node2.pos + + /**Damping.*/ + var damping = 0.0 + + /**Relative position of the connection points.*/ + def x = connection2 - connection1 + + /**Relative velocity of the connection points.*/ + def v = node2.velocityOfPoint(connection2) - node1.velocityOfPoint(connection1) + + /**Returns the spring force.*/ + def force = (x.length - initialLength) * springConstant + + /**Applies the spring force to the connection points.*/ + def applyForce() = { + node1.applyForce(x.unit * force - (v * damping) project x, connection1) + node2.applyForce(-x.unit * force - (v * damping) project x, connection2) + //println("this should not happen") + } + + def correctVelocity(h: Double) = { + /* + val x = this.x + val v = this.v + val r1 = (connection1 - node1.pos) + val r2 = (connection2 - node2.pos) + val cr1 = r1 cross x.unit + val cr2 = r2 cross x.unit + val Cdot = x.unit dot v + val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 //=J M^-1 JT + val m = if (invMass == 0.0) 0.0 else 1/invMass + val lambda = math.min(math.max(-this.force * h, (-m * Cdot)), this.force * h) + println (force * h, -m * Cdot) + val impulse = x.unit * lambda + node1.applyImpulse(-impulse, connection1) + node2.applyImpulse(impulse, connection2) + */ + } + + def correctPosition(h: Double) = { + + } +} diff --git a/src/main/scala/sims/dynamics/joints/test/PrismaticJoint.scala b/src/main/scala/sims/dynamics/joints/test/PrismaticJoint.scala new file mode 100644 index 0000000..040647d --- /dev/null +++ b/src/main/scala/sims/dynamics/joints/test/PrismaticJoint.scala @@ -0,0 +1,84 @@ +package sims.dynamics.joints.test + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.geometry._ + +case class PrismaticJoint(node1: Body, anchor1: Vector2D, node2: Body, anchor2: Vector2D) extends Joint{ + def this(node1: Body, node2: Body) = this(node1, node1.pos, node2, node2.pos) + + val angle = node2.rotation - node1.rotation + + private val a1 = anchor1 - node1.pos + private val a2 = anchor2 - node2.pos + private val initRotation1 = node1.rotation + private val initRotation2 = node2.rotation + + def connection1 = (a1 rotate (node1.rotation - initRotation1)) + node1.pos + def connection2 = (a2 rotate (node2.rotation - initRotation2)) + node2.pos + + def x = connection2 - connection1 + + def v = node2.velocityOfPoint(connection2) - node1.velocityOfPoint(connection1) + + + def correctVelocity(h: Double) = { + correctLinear(h) + //correctAngular(h) + } + + def correctLinear(h: Double) = { + val x = this.x.unit + val n0 = x.leftNormal + val v = this.v + val r1 = (connection1 - node1.pos) + val r2 = (connection2 - node2.pos) + val cr1 = r1 cross n0 + val cr2 = r2 cross n0 + val Cdot = n0 dot v + val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 + val m = if (invMass == 0.0) 0.0 else 1/invMass + val impulse = -n0 * m * Cdot + node1.applyImpulse(-impulse, connection1) + node2.applyImpulse(impulse, connection2) + } + + //J=[-1,1] + + def correctAngular(h: Double) = { + val w = node2.angularVelocity - node1.angularVelocity + val Cdot = w + val invMass = node1.I + node2.I + val m = 1 / invMass + val lambda = m * Cdot + node1.angularVelocity += lambda / node1.I + node2.angularVelocity += -lambda / node2.I + } + + def correctPosition(h: Double) = { + /* + val x = this.x.unit + val n0 = x.leftNormal + val v = this.v + val r1 = (connection1 - node1.pos) + val r2 = (connection2 - node2.pos) + val cr1 = r1 cross n0 + val cr2 = r2 cross n0 + val C = n0 dot x + val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 + val m = if (invMass == 0.0) 0.0 else 1/invMass + val impulse = -n0 * m * C + node1.pos += -impulse + node1.rotation += -impulse cross r1 + node2.pos += impulse + node2.rotation += impulse cross r2 + + val relOmega = node2.angularVelocity - node2.angularVelocity + val invMassOmega = node1.I + node2.I + val mOmega = if (invMassOmega == 0.0) 0.0 else 1/invMassOmega + val Crot = node2.rotation - node2.rotation + angle + node1.rotation += mOmega * Crot + node2.rotation += -mOmega * Crot + */ + } +} diff --git a/src/main/scala/sims/dynamics/joints/test/UnitCircleJoint.scala b/src/main/scala/sims/dynamics/joints/test/UnitCircleJoint.scala new file mode 100644 index 0000000..09e72d9 --- /dev/null +++ b/src/main/scala/sims/dynamics/joints/test/UnitCircleJoint.scala @@ -0,0 +1,46 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.dynamics.joints.test + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.geometry._ + +class UnitCircleJoint(body: Body, anchor: Vector2D) extends Joint{ + + val node1 = body + val node2 = body + + private val a = anchor - body.pos + private val initRotation = body.rotation + def connection = (a rotate (body.rotation - initRotation)) + body.pos + def x = connection + def v = body.velocityOfPoint(connection) + + /* + * C = ||x|| - 1 + * Cdot = x/||x|| dot v = u dot v + * J = [u (r cross u)] + */ + def correctVelocity(h: Double) = { + val r = connection - body.pos + val u = x.unit + val cr = r cross u + val mc = 1.0/(1/body.mass + 1/body.I * cr * cr) + val lambda = -mc * (u dot v) + val Pc = u * lambda + + val vupdate = u * lambda / body.mass + val wupdate = (r cross u) * lambda / body.I + + println("dv = " + vupdate + " dw = " + wupdate) + body.linearVelocity = body.linearVelocity + u * lambda / body.mass + body.angularVelocity = body.angularVelocity + (r cross u) * lambda / body.I + } + + def correctPosition(h: Double) = {} +} diff --git a/src/main/scala/sims/geometry/ConvexPolygon.scala b/src/main/scala/sims/geometry/ConvexPolygon.scala new file mode 100644 index 0000000..bfd17a1 --- /dev/null +++ b/src/main/scala/sims/geometry/ConvexPolygon.scala @@ -0,0 +1,56 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.geometry + +import sims.collision._ +import sims.geometry._ + +/**Common properties of all convex polygons.*/ +trait ConvexPolygon { + + /**Returns positions of all vertices of this Polygon. Vertices are ordered counter-clockwise. + * @return position vectors of the vertices*/ + def vertices: Seq[Vector2D] + + /**Returns all sides of this polygon. The sides are ordered counter-clockwise, the first vertex of the side + * giving the side index.*/ + def sides = (for (i <- 0 until vertices.length) yield (new Segment(vertices(i), vertices((i + 1) % vertices.length)))).toArray + + /**Returns the projection of this polygon onto the line given by the directional vector axis. + * @param axis directional vector of the line + * @return projection of this polygon*/ + def project(axis: Vector2D) = { + val points = for (v <- vertices) yield {v project axis} + val bounds = for (p <- points) yield {if (axis.x != 0) p.x / axis.x else p.y / axis.y} + Projection(axis, + (bounds(0) /: bounds)(math.min(_,_)), + (bounds(0) /: bounds)(math.max(_,_))) + } + + /**Returns this polygon's axis aligned bounding box. + * @see collision.AABB*/ + def AABB = { + val xs = vertices map (_.x) + val ys = vertices map (_.y) + new AABB(Vector2D(xs.min, ys.min), + Vector2D(xs.max, ys.max)) + } + + /**Checks if the point point is contained in this polygon. + *

+ * A ray is created, originating from the point and following an arbitrary direction (X-Axis was chosen). + * The number of intersections between the ray and this polygon's sides (including vertices) is counted. + * The amount of intersections with vertices is substracted form the previuos number. + * If the latter number is odd, the point is contained in the polygon.*/ + def contains(point: Vector2D) = { + val r = new Ray(point, Vector2D.i) + var intersections = 0 + for (s <- sides; if (r intersects s)) intersections += 1 + for (v <- vertices; if (r contains v)) intersections -= 1 + intersections % 2 != 0 + } +} diff --git a/src/main/scala/sims/geometry/Projection.scala b/src/main/scala/sims/geometry/Projection.scala new file mode 100644 index 0000000..9957c73 --- /dev/null +++ b/src/main/scala/sims/geometry/Projection.scala @@ -0,0 +1,35 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.geometry + +import sims.math._ + +/**Projection on an axis. + *

+ * Projections are commonly used in SiMS for collision detection. + * @param axis directional vector of the axis of the projection + * @param lower lower value of the projection + * @param upper upper value of the projection*/ +case class Projection(axis: Vector2D, + lower: Double, + upper: Double) { + require(axis != Vector2D.Null, "A projection's axis cannot be given by a null vector!") + + /**Checks this projection for overlap with another projection other. + * @throws IllegalArgumentExcepion if both projections axes aren't the same*/ + def overlaps(other: Projection): Boolean = { + require(axis == other.axis, "Cannot compare two projections on different axes!") + !((other.lower - this.upper) > 0 || (this.lower - other.upper) > 0) + } + + /**Returns the overlap between this projection and another projection other. + * @throws IllegalArgumentExcepion if both projections axes aren't the same*/ + def overlap(other: Projection): Double = { + require(axis == other.axis, "Cannot compare two projections on different axes!") + (math.max(lower, other.lower) - math.min(upper, other.upper)).abs + } +} diff --git a/src/main/scala/sims/geometry/Ray.scala b/src/main/scala/sims/geometry/Ray.scala new file mode 100644 index 0000000..1cca8d5 --- /dev/null +++ b/src/main/scala/sims/geometry/Ray.scala @@ -0,0 +1,49 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.geometry + +import sims.math._ +import scala.math._ + +/**A ray. + * @param point a point on the ray + * @param direction this ray's directional vector + * @throws IllegalArgumentException if the directional vector is the null vector*/ +case class Ray(point: Vector2D, direction: Vector2D) { + + require(direction != Vector2D.Null, "A ray's direction cannot be given by a null vector!") + + /**Checks this ray and the given segment for intersection. + * @param s the segment to test for intersection*/ + def intersects(s: Segment) = { + val p1 = point + val p2 = point + direction + val p3 = s.vertex1 + val p4 = s.vertex2 + val d = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y) + val na = (p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x) + val nb = (p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x) + if (d == 0 && na == 0 && nb == 0) + true //lines are coincident + else if (d == 0) + false //parallel + else { + val ua = na / d + val ub = nb / d + (ub >= 0) && (ub <= 1) && (ua >= 0) + } + } + + /**Checks if this ray contains the point p.*/ + def contains(p: Vector2D) = { + val v = p - point + p == point || + Matrix22(direction, v).det == 0 && + signum(direction.x) == signum(v.x) && + signum(direction.y) == signum(v.y) + } +} diff --git a/src/main/scala/sims/geometry/Segment.scala b/src/main/scala/sims/geometry/Segment.scala new file mode 100644 index 0000000..4aaec21 --- /dev/null +++ b/src/main/scala/sims/geometry/Segment.scala @@ -0,0 +1,72 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.geometry + +/**A segment is given by its vertices. + * @param vertex1 position vector of the first vertex + * @param vertex2 position vector of the second vertex + * @throws IllegalArgumentException if both vertices are equal + */ +case class Segment(vertex1: Vector2D, vertex2: Vector2D){ + require(vertex1 != vertex2, "A segment must have 2 distinct vertices!") + + /**Length of this segment.*/ + val length = (vertex2 - vertex1).length + + /**Vector from vertex1 to vertex2.*/ + val d = vertex2 - vertex1 + + /**Unit directional vector.*/ + val d0 = d.unit + + /**Right normal vector.*/ + val n = d.rightNormal + + /**Right normal unit vector.*/ + val n0 = n.unit + + /**Smallest distance between this segment and the point point.*/ + def distance(point: Vector2D): Double = { + val v = point - vertex1 //vector from vertex1 to point + val projection = v project d + val alpha = if (d.x != 0) d.x / projection.x else d.y / projection.y + if (alpha >= 0 && projection.length <= length) //point is closer to line between vertex1 and vertex2 + (v project n0).length + else if (alpha < 0) //point is closer to vertex1 + (point - vertex1).length + else if (alpha > 0) //point is closer to vertex2 + (point - vertex2).length + else + throw new IllegalArgumentException("Error occured trying to compute distance between segment and point.") + } + + def clipToSegment(s: Segment): Option[Vector2D] = { + + val distance1 = (vertex1 - s.vertex1) dot s.n0 + val distance2 = (vertex2 - s.vertex1) dot s.n0 + + if (distance1 * distance2 < 0) { //auf anderen Seiten + /* Geradengleichungen + * ================== + * Segment1: s1: x = a + alpha * r | alpha in [0,1] + * Segment2: s2: x = b + beta * s | beta in [0,1] + * + * alpha = [s2(a1-b1)-s1(a2-b2)] / [r2s1-r1s2] + * beta = [r2(b1-a1)-r1(b2-a2)] / [r1s2-r2s1] + * = [r1(b2-a2)]-r2(b1-a1) / [r2s1-r1s2] + * s1: vertex1 + alpha * d + * s2: s.vertex1 + beta * s.d + */ + val denom: Double = d.y * s.d.x - d.x * s.d.y + val alpha: Double = (s.d.y * (vertex1.x - s.vertex1.x) - s.d.x * (vertex1.y - s.vertex1.y)) / denom + val beta: Double = (d.x * (s.vertex1.y - vertex1.y) - d.y * (s.vertex1.x - vertex1.x)) / denom + if (0.0 <= alpha && alpha <= 1.0 && 0.0 <= beta && beta <= 1.0) Some(vertex1 + d * alpha) + else None + } + else None + } +} diff --git a/src/main/scala/sims/geometry/Vector2D.scala b/src/main/scala/sims/geometry/Vector2D.scala new file mode 100644 index 0000000..8d5205f --- /dev/null +++ b/src/main/scala/sims/geometry/Vector2D.scala @@ -0,0 +1,83 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.geometry + +import scala.math._ + +/**A 2D vector. + * @param x 1st component + * @param y 2nd component*/ +case class Vector2D(x: Double, y: Double) { + + /**Vector addition.*/ + def +(v: Vector2D): Vector2D = Vector2D(x + v.x, y + v.y) + + /**Vector substraction.*/ + def -(v: Vector2D): Vector2D = this + (v * -1) + + /**Scalar multiplication.*/ + def *(n: Double): Vector2D = Vector2D(x * n, y * n) + + /**Scalar division.*/ + def /(n: Double): Vector2D = this * (1/n) + + /**Unary minus.*/ + def unary_- : Vector2D = Vector2D(-x, -y) + + /**Dot product.*/ + def dot(v: Vector2D): Double = x * v.x + y * v.y + + /**Cross product. Length only because in 2D. The direction would be given by the x3-axis.*/ + def cross(v: Vector2D): Double = x * v.y - y * v.x + + /**Norm or length of this vector.*/ + val length: Double = math.sqrt(x * x + y * y) + + /**Unit vector.*/ + def unit: Vector2D = if (!(x == 0.0 && y == 0.0)) Vector2D(x / length, y / length) + else throw new IllegalArgumentException("Null vector does not have a unit vector.") + + /**Returns the projection of this vector onto the vector v.*/ + def project(v: Vector2D): Vector2D = { + if (v != Vector2D.Null) + v * ((this dot v) / (v dot v)) + else + Vector2D.Null + } + + /**Returns a rotation of this vector by angle radian.*/ + def rotate(angle: Double): Vector2D = { + Vector2D(cos(angle) * x - sin(angle) * y, + cos(angle) * y + sin(angle) * x) + } + + /**Left normal vector. (-y, x)*/ + def leftNormal: Vector2D = Vector2D(-y, x) + + /**Right normal vector. (y, -x)*/ + def rightNormal: Vector2D = Vector2D(y, -x) + + /**Checks if this vector is the null vector.*/ + def isNull: Boolean = this == Vector2D.Null + + /**Returns a list of this vector's components.*/ + def components = List(x, y) +} + +/**Contains special vectors.*/ +object Vector2D { + + /**Null vector.*/ + val Null = Vector2D(0,0) + + /**Horizontal unit vector. (1,0)*/ + val i = Vector2D(1,0) + + /**Vertical unit vector. (0,1)*/ + val j = Vector2D(0,1) +} + diff --git a/src/main/scala/sims/materials/Material.scala b/src/main/scala/sims/materials/Material.scala new file mode 100644 index 0000000..b05e082 --- /dev/null +++ b/src/main/scala/sims/materials/Material.scala @@ -0,0 +1,7 @@ +package sims.materials + +trait Material { + val density: Double + val restitution: Double + val friction: Double +} diff --git a/src/main/scala/sims/materials/Rubber.scala b/src/main/scala/sims/materials/Rubber.scala new file mode 100644 index 0000000..b408d2d --- /dev/null +++ b/src/main/scala/sims/materials/Rubber.scala @@ -0,0 +1,5 @@ +package sims.materials + +object Rubber { + +} diff --git a/src/main/scala/sims/materials/Steel.scala b/src/main/scala/sims/materials/Steel.scala new file mode 100644 index 0000000..1d14563 --- /dev/null +++ b/src/main/scala/sims/materials/Steel.scala @@ -0,0 +1,5 @@ +package sims.materials + +object Steel { + +} \ No newline at end of file diff --git a/src/main/scala/sims/math/Matrix22.scala b/src/main/scala/sims/math/Matrix22.scala new file mode 100644 index 0000000..54d24c7 --- /dev/null +++ b/src/main/scala/sims/math/Matrix22.scala @@ -0,0 +1,55 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.math + +import sims.geometry._ + +/**A 2x2 matrix. + * @param c11 component 1,1 + * @param c12 component 1,2 + * @param c21 component 2,1 + * @param c22 component 2,2 + */ +case class Matrix22(c11: Double, c12: Double, c21: Double, c22: Double) { + + /**A 2x2 matrix can be created with two 2D vectors. In this case, each column is represented by a vector. + * @param c1 first column + * @param c2 second column*/ + def this(c1: Vector2D, c2: Vector2D) = this(c1.x, c2.x, c1.y, c2.y) + + /**Determinant of this matrix.*/ + def det = c11 * c22 - c21 * c12 + + /**Addition.*/ + def +(m: Matrix22) = + new Matrix22(c11 + m.c11, c12 + m.c12, + c21 + m.c21, c22 + m.c22) + + /**Scalar multiplication.*/ + def *(n: Double) = + new Matrix22(c11 * n, c12 * n, + c21 * n, c22 * n) + + /**Matrix multiplication.*/ + def *(m: Matrix22) = + new Matrix22(c11 * m.c11 + c12 * m.c21, c11 * m.c12 + c12 * m.c22, + c21 * m.c11 + c22 * m.c21, c21 * m.c12 + c22 * m.c22) + + /**Multiplikation with a 2D vector.*/ + def *(v: Vector2D) = + new Vector2D(c11 * v.x + c12 * v.y, + c21 * v.x + c22 * v.y) + + /**Inverse.*/ + def invert = + new Matrix22(c22 / det, -c12 / det, + -c21 / det, c11 / det) + } + +object Matrix22 { + def apply(c1: Vector2D, c2: Vector2D) = new Matrix22(c1.x, c2.x, c1.y, c2.y) +} diff --git a/src/main/scala/sims/prefabs/Net.scala b/src/main/scala/sims/prefabs/Net.scala new file mode 100644 index 0000000..d3f4d57 --- /dev/null +++ b/src/main/scala/sims/prefabs/Net.scala @@ -0,0 +1,47 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.prefabs + +import sims.geometry._ +import sims.dynamics._ +import sims.dynamics.joints._ + +class Net(width: Int, height: Int, initPos: Vector2D) extends Prefab { + val nodeDistance: Double = 0.2 + val nodeRadius: Double = 0.05 + val nodeDensity: Double = 4 + + val springConstant: Double = 50 + val springDamping: Double = 0 + + private val connectors: Array[Array[Body]] = + makeConnectors(width, height) + + override val bodies: List[Body] = for (row <- connectors.toList; elem <- row) yield elem + override val joints = connect(connectors) + + private def makeConnectors(w: Int, h: Int): Array[Array[Body]] = { + for(i <- (0 until w).toArray[Int]) yield + for(j <- (0 until h).toArray[Int]) yield + new Body(new Circle(nodeRadius, nodeDensity) {pos = Vector2D(nodeDistance * i, nodeDistance * j) + initPos}) + } + + private def connect(connectors: Array[Array[Body]]): List[DistanceJoint] = { + var r: List[DistanceJoint] = Nil + for(i <- 0 to connectors.length - 1; j <- 0 to connectors(i).length - 1) { + if (i > 0) + r = connect(connectors(i-1)(j),connectors(i)(j)) :: r + if (j > 0) + r = connect(connectors(i)(j-1),connectors(i)(j)) :: r + } + r + } + + private def connect(s1: Body, s2: Body): DistanceJoint = + new DistanceJoint(s1, s1.pos, s2, s2.pos) + +} \ No newline at end of file diff --git a/src/main/scala/sims/prefabs/Prefab.scala b/src/main/scala/sims/prefabs/Prefab.scala new file mode 100644 index 0000000..84bb3b7 --- /dev/null +++ b/src/main/scala/sims/prefabs/Prefab.scala @@ -0,0 +1,15 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.prefabs + +import sims.dynamics._ +import sims.dynamics.joints._ + +trait Prefab { + val bodies: Iterable[Body] = Nil + val joints: Iterable[Joint] = Nil +} diff --git a/src/main/scala/sims/prefabs/Pylon.scala b/src/main/scala/sims/prefabs/Pylon.scala new file mode 100644 index 0000000..7f3211f --- /dev/null +++ b/src/main/scala/sims/prefabs/Pylon.scala @@ -0,0 +1,47 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.prefabs + +import sims.geometry._ +import sims.dynamics._ +import sims.dynamics.joints._ + +class Pylon extends Prefab{ + val position: Vector2D = Vector2D(2,1) + val nodeDensity: Double = 100 + val beamHeight: Double = 1 + val beamWidth: Double = 0.5 + val beamNumber: Int = 10 + + private val nodeRow1 = (for (i <- 0 to beamNumber) yield (new Circle(0.01, nodeDensity) { + pos = position + Vector2D(0, i * beamHeight)}).asBody).toList + private val nodeRow2 = (for (i <- 0 to beamNumber) yield (new Circle(0.01, nodeDensity) { + pos = position + Vector2D(beamWidth, i * beamHeight)}).asBody).toList + + private val beamRow1 = (for (i <- 0 until nodeRow1.length - 1) yield + new DistanceJoint(nodeRow1(i), nodeRow1(i).pos, nodeRow1(i+1), nodeRow1(i + 1).pos)).toList + private val beamRow2 = (for (i <- 0 until nodeRow1.length - 1) yield + new DistanceJoint(nodeRow2(i), nodeRow2(i).pos, nodeRow2(i+1), nodeRow2(i + 1).pos)).toList + + private val latBeams = (for (i <- 0 to beamNumber) yield + new DistanceJoint(nodeRow1(i), nodeRow2(i))).toList + private val diagBeams1 = (for (i <- 0 until beamNumber) yield + new DistanceJoint(nodeRow1(i), nodeRow2(i + 1))).toList + private val diagBeams2 = (for (i <- 0 until beamNumber) yield + new DistanceJoint(nodeRow2(i), nodeRow1(i + 1))).toList + + + + + lazy val nodes = nodeRow1 ++ nodeRow2 + lazy val beams = beamRow1 ++ beamRow2 ++ latBeams ++ diagBeams1 ++ diagBeams2 + + override val bodies = nodes + override val joints = beams + + +} diff --git a/src/main/scala/sims/prefabs/Ragdoll.scala b/src/main/scala/sims/prefabs/Ragdoll.scala new file mode 100644 index 0000000..00e4b8d --- /dev/null +++ b/src/main/scala/sims/prefabs/Ragdoll.scala @@ -0,0 +1,43 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.prefabs + +import sims.dynamics._ +import sims.dynamics.joints._ +import sims.geometry._ + +class Ragdoll(position: Vector2D) extends Prefab { + val headTorso = new Body(new Circle(0.1, 1) {pos = position}, + new Rectangle(0.09, 0.35, 1) {pos = position + Vector2D(0, -0.45)}) + val thigh1 = (new Rectangle(0.075, 0.17, 1) {pos = position + Vector2D(0, -0.97)}).asBody + val thigh2 = (new Rectangle(0.075, 0.17, 1) {pos = position + Vector2D(0, -0.97)}).asBody + val tibia1 = (new Rectangle(0.075, 0.25, 1) {pos = position + Vector2D(0, -1.39)}).asBody + val tibia2 = (new Rectangle(0.075, 0.25, 1) {pos = position + Vector2D(0, -1.39)}).asBody + val foot1 = (new Circle(0.08, 1) {pos = position + Vector2D(0, -1.72)}).asBody + val foot2 = (new Circle(0.08, 1) {pos = position + Vector2D(0, -1.72)}).asBody + val upperArm1 = (new Rectangle(0.17, 0.06, 1) {pos = position + Vector2D(0.17, -0.16)}).asBody + val upperArm2 = (new Rectangle(0.17, 0.06, 1) {pos = position + Vector2D(-0.17, -0.16)}).asBody + val forearm1 = (new Rectangle(0.15, 0.06, 1) {pos = position + Vector2D(0.49, -0.16)}).asBody + val forearm2 = (new Rectangle(0.15, 0.06, 1) {pos = position + Vector2D(-0.49, -0.16)}).asBody + val hand1 = (new Circle(0.07, 1) {pos = position + Vector2D(0.71, -0.16)}).asBody + val hand2 = (new Circle(0.07, 1) {pos = position + Vector2D(-0.71, -0.16)}).asBody + + override val bodies = List(headTorso, + thigh1, thigh2, + tibia1, tibia2, + foot1, foot2, + upperArm1, upperArm2, + forearm1, forearm2, + hand1, hand2) + private val shapes = bodies.flatMap(_.shapes) + for (s <- shapes) s.transientShapes ++= shapes + + val shoulder1 = RevoluteJoint(headTorso, upperArm1, position + Vector2D(0, -0.16)) + val shoulder2 = RevoluteJoint(headTorso, upperArm2, position + Vector2D(0, -0.16)) + override val joints = Nil //List(shoulder1, shoulder2) + +} diff --git a/src/main/scala/sims/util/Polar.scala b/src/main/scala/sims/util/Polar.scala new file mode 100644 index 0000000..494c984 --- /dev/null +++ b/src/main/scala/sims/util/Polar.scala @@ -0,0 +1,17 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.util + +import sims.geometry._ +import scala.math._ + +/**Polar coordinates.*/ +case class Polar(distance: Double, angle: Double) { + + /**Returns the vector representation of these polar coordinates.*/ + def toCarthesian = Vector2D(distance * sin(angle), distance * cos(angle)) +} diff --git a/src/main/scala/sims/util/Positioning.scala b/src/main/scala/sims/util/Positioning.scala new file mode 100644 index 0000000..cf72276 --- /dev/null +++ b/src/main/scala/sims/util/Positioning.scala @@ -0,0 +1,24 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.util + +import sims.geometry._ +import sims.dynamics._ + +/**Utility functions for comfortable positioning of bodies.*/ +object Positioning { + + implicit def int2RelativeVector(x: Int): RelativeVector = new RelativeVector(x, 0) + implicit def double2RelativeVector(x: Double): RelativeVector = new RelativeVector(x, 0) + implicit def vector2RelativeVector(v: Vector2D): RelativeVector = new RelativeVector(v.x, v.y) + implicit def polar2Carthesian(p: Polar): Vector2D = p.toCarthesian + implicit def polar2RelativeVector(p: Polar): RelativeVector = vector2RelativeVector(p.toCarthesian) + + def position(s: Shape)(a: Vector2D) = { + s.pos = a + } +} diff --git a/src/main/scala/sims/util/RelativeVector.scala b/src/main/scala/sims/util/RelativeVector.scala new file mode 100644 index 0000000..374f92c --- /dev/null +++ b/src/main/scala/sims/util/RelativeVector.scala @@ -0,0 +1,24 @@ +/* + * Simple Mechanics Simulator (SiMS) + * copyright (c) 2009 Jakob Odersky + * made available under the MIT License +*/ + +package sims.util + +import sims.geometry._ +import sims.dynamics._ + +class RelativeVector(val x: Double, val y: Double) { + def above(point: Vector2D): Vector2D = point + Vector2D(0, x) + def below(point: Vector2D): Vector2D = point - Vector2D(0, x) + def left(point: Vector2D): Vector2D = point - Vector2D(x, 0) + def right(point: Vector2D): Vector2D = point + Vector2D(x, 0) + def from(point: Vector2D): Vector2D = point + Vector2D(x, y) + + def above(s: Shape): Vector2D = this.above(s.pos) + def below(s: Shape): Vector2D = this.below(s.pos) + def left(s: Shape): Vector2D = this.left(s.pos) + def right(s: Shape): Vector2D = this.right(s.pos) + def from(s: Shape): Vector2D = this.from(s.pos) +} diff --git a/src/sims/collision/AABB.scala b/src/sims/collision/AABB.scala deleted file mode 100644 index f3a0b71..0000000 --- a/src/sims/collision/AABB.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.collision - -import sims.geometry._ - -/** - * Axis Aligned Bounding Boxes (AABBs) are rectangles that frame a shape. - * Their X-Axis and Y-Axis orientation makes it easy to test two AABBs for overlap. - * @param minVertex Position vector of the bottom-left vertex - * @param maxVertex Position vector of the upper-right vertex - */ -case class AABB(val minVertex: Vector2D, - val maxVertex: Vector2D) -{ - /** - * Checks this AABB with box for overlap. - * @param box AABB with which to check for overlap*/ - def overlaps(box: AABB): Boolean = { - val d1 = box.minVertex - maxVertex - val d2 = minVertex - box.maxVertex - !(d1.x > 0 || d1.y > 0 || d2.x > 0 || d2.y > 0) - } -} diff --git a/src/sims/collision/CircleCollision.scala b/src/sims/collision/CircleCollision.scala deleted file mode 100644 index 04cf2d7..0000000 --- a/src/sims/collision/CircleCollision.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.collision - -import sims.geometry._ -import sims.dynamics._ - -/**Collision between two circles.*/ -case class CircleCollision(c1: Circle, c2: Circle) extends Collision { - val shape1 = c1 - val shape2 = c2 - val normal = (c2.pos - c1.pos).unit - val points = { - val distance = (c2.pos - c1.pos).length - val p = shape1.pos + normal * (distance - c2.radius) - List(p) - } -} diff --git a/src/sims/collision/Collision.scala b/src/sims/collision/Collision.scala deleted file mode 100644 index 540081a..0000000 --- a/src/sims/collision/Collision.scala +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.collision - -import sims.dynamics._ -import sims.geometry._ - -/**Collision between two shapes. Contains methods to compute the collision response.*/ -abstract class Collision extends Constraint { - - /**First colliding shape (reference shape).*/ - val shape1: Shape - - /**Second colliding shape (incident shape).*/ - val shape2: Shape - - /**Collision points.*/ - val points: Iterable[Vector2D] - - /**Normal vector to the collision face.*/ - val normal: Vector2D - - /* C = delta - * Cdot = (vp2 - vp1) dot n - * = v2 + (w2 cross r2) - v2 - (w1 cross r1) - * = v2 + (w2 cross (p - x2)) - v2 - (w1 cross(p - x1)) - * J = [-n -((p-x1) cross n) n ((p-x2) cross n)]*/ - def correctVelocity(h: Double) = { - val coefficientOfRestitution = shape1.restitution * shape2.restitution - for (p <- points) { - val b1 = shape1.body - val b2 = shape2.body - val relativeNormalVelocity = (b2.velocityOfPoint(p) - b1.velocityOfPoint(p)) dot normal - val Cdot = relativeNormalVelocity + relativeNormalVelocity * coefficientOfRestitution - if (Cdot <= 0) { - val r1 = p - b1.pos - val r2 = p - b2.pos - val cr1 = r1 cross normal - val cr2 = r2 cross normal - val invMass = 1/b1.mass * (normal dot normal) + 1/b1.I * cr1 * cr1 + 1/b2.mass * (normal dot normal) + 1/b2.I * cr2 * cr2 - val m = if (invMass == 0.0) 0.0 else 1/invMass - val lambda = -m * Cdot - //wenn fixed, dann ist Masse unendlich => kein 'if (fixed != true)' - b1.linearVelocity += -normal * lambda / b1.mass - b1.angularVelocity += -(r1 cross normal) * lambda / b1.I - b2.linearVelocity += normal * lambda / b2.mass - b2.angularVelocity += (r2 cross normal) * lambda / b2.I - correctFriction(p, (-normal * lambda).length / h, h) - } - } - } - - /* Cdot = vt = [v2 + (w2 cross r2) - v1 - (w2 cross r2)] dot t - * J = [-t -(r2 cross t) t (r1 cross t)] - * 1/m = J * M * JT - * = 1/m1 * (t dot t) + 1/m2 * (t dot t) + 1/I1 * (r1 cross u)^2 + 1/I2 * (r2 cross u)^2*/ - def correctFriction(point: Vector2D, normalForce: Double, h: Double) = { - val b1 = shape1.body - val b2 = shape2.body - val tangent = normal.leftNormal - val Cdot = (b2.velocityOfPoint(point) - b1.velocityOfPoint(point)) dot tangent - val r1 = point - b1.pos - val r2 = point - b2.pos - val cr1 = r1 cross tangent - val cr2 = r2 cross tangent - val invMass = 1/b1.mass * (tangent dot tangent) + 1/b1.I * cr1 * cr1 + 1/b2.mass * (tangent dot tangent) + 1/b2.I * cr2 * cr2 - val m = if (invMass == 0.0) 0.0 else 1/invMass - val lambda = -m * Cdot - val cf = shape1.friction * shape2.friction - val cl = Math.min(Math.max(-normalForce * cf * h, lambda), normalForce * cf * h) - val impulse = tangent * cl - b1.applyImpulse(-impulse, point) - b2.applyImpulse(impulse, point) - } - - def correctPosition(h: Double) = { - val b1 = shape1.body - val b2 = shape2.body - - for (p <- points) { - val overlap = shape1.project(normal) overlap shape2.project(normal) - val C = Collision.ToleratedOverlap - overlap - if (C <= 0.0) { - val r1 = p - b1.pos - val r2 = p - b2.pos - val cr1 = r1 cross normal - val cr2 = r2 cross normal - val invMass = 1/b1.mass + 1/b1.I * cr1 * cr1 + 1/b2.mass + 1/b2.I * cr2 * cr2 - val m = if (invMass == 0.0) 0.0 else 1/invMass - val impulse = -normal.unit * m * C - b1.pos += -impulse / b1.mass - b1.rotation += -(r1 cross impulse) / b1.I - b2.pos += impulse / b2.mass - b2.rotation += (r2 cross impulse) / b2.I - } - } - } -} - -object Collision { - - /**Tolerated overlap. Collision response will only be applied if the overlap of two shapes exceeds the tolerated overlap.*/ - val ToleratedOverlap: Double = 0.01 -} diff --git a/src/sims/collision/Detector.scala b/src/sims/collision/Detector.scala deleted file mode 100644 index 96af5dc..0000000 --- a/src/sims/collision/Detector.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.collision - - -import sims.geometry._ -import sims.dynamics._ - -/**A world detects its collisions through concrete implementations of this class.*/ -abstract class Detector { - - /**The world whose shapes are to be checked for collisions.*/ - val world: World - - /**Returns all collisions between shapes in the world world.*/ - def collisions: Seq[Collision] -} \ No newline at end of file diff --git a/src/sims/collision/GridDetector.scala b/src/sims/collision/GridDetector.scala deleted file mode 100644 index 9a71c6d..0000000 --- a/src/sims/collision/GridDetector.scala +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.collision - -import sims.dynamics._ -import sims.geometry._ -import scala.collection._ -import scala.collection.mutable.ArrayBuffer -import scala.collection.mutable.HashMap - -/**A concrete implementation of Detector. GridDetector divides the world into a grid - * for faster collision detection.*/ -class GridDetector(override val world: World) extends Detector { - - /**Array of collision detection methods. These methods return true if two shapes are colliding.*/ - val detectionMethods = new ArrayBuffer[PartialFunction[(Shape, Shape), Boolean]] - detectionMethods += { - case (c1: Circle, c2: Circle) => { //collision if distance <= sum of radiuses - val d = (c1.pos - c2.pos).length - val rSum = c1.radius + c2.radius - d - rSum <= 0 - } - - case (p1: ConvexPolygon, p2: ConvexPolygon) => { //SAT - val sides = p1.sides ++ p2.sides - val axes = sides map (_.n0) - axes.forall((a: Vector2D) => p1.project(a) overlaps p2.project(a)) - } - - case (p: ConvexPolygon, c: Circle) => { //distance form center to sides or vertices - val distances = for (s <- p.sides) yield (s distance c.pos) - distances.exists(_ - c.radius <= 0) || (p contains c.pos) - } - - case (c: Circle, p: ConvexPolygon) => { //distance form center to sides or vertices - val distances = for (s <- p.sides) yield (s distance c.pos) - distances.exists(_ - c.radius <= 0) || (p contains c.pos) - } - } - - /**Array of methods returning collisions. It is assumed that both shapes are colliding.*/ - val collisionMethods = new ArrayBuffer[PartialFunction[(Shape, Shape), Collision]] - collisionMethods += { - case (c1: Circle, c2: Circle) => CircleCollision(c1, c2) - case (p1: ConvexPolygon, p2: ConvexPolygon) => PolyCollision(p1, p2) - case (p: ConvexPolygon, c: Circle) => PolyCircleCollision(p, c) - case (c: Circle, p: ConvexPolygon) => PolyCircleCollision(p, c) - } - - /**Checks the pair of shapes p for collision. - * @param p Pair of shapes.*/ - def colliding(p: Pair) = { - if (detectionMethods.exists(_.isDefinedAt(p))) - detectionMethods.find(_.isDefinedAt(p)).get.apply(p) - else throw new IllegalArgumentException("No collision method for colliding pair!") - } - - /**Returns the collision between both shapes of the pair p. - * @param p Pair of shapes.*/ - def collision(p: Pair): Collision = { - if (collisionMethods.exists(_.isDefinedAt(p))) - collisionMethods.find(_.isDefinedAt(p)).get.apply(p) - else throw new IllegalArgumentException("No collision found in colliding pair!") - } - - /**Width and height of a grid cell.*/ - var gridSide: Double = 2 - - /**Returns potential colliding pairs of shapes of the world world. - *

- * A potential colliding pair is a pair of two shapes that comply with the following criteria: - *

*/ - def getPairs = { - val grid = new HashMap[(Int, Int), List[Shape]] - def gridCoordinates(v: Vector2D) = ((v.x / gridSide).toInt, (v.y / gridSide).toInt) - def addToGrid(s: Shape) = { - val aabb = s.AABB - val minCell = gridCoordinates(aabb.minVertex) - val maxCell = gridCoordinates(aabb.maxVertex) - val coords = for(i <- (minCell._1 to maxCell._1); j <- (minCell._2 to maxCell._2)) yield (i, j) - for (c <- coords) { - if (grid.contains(c)) - {if (grid(c).forall(_ ne s)) grid(c) = s :: grid(c)} - else - grid += (c -> List(s)) - } - } - for(s <- world.shapes) addToGrid(s) - var ps: List[Pair] = Nil - for(cell <- grid.valuesIterator) { - ps = ps ::: (for (s1: Shape <- cell; s2: Shape <- cell; - if (s1 ne s2); - if (s1.body ne s2.body); - if (s1.collidable && s2.collidable); - if (s1.AABB overlaps s2.AABB); - if (!s1.transientShapes.contains(s2) && !s2.transientShapes.contains(s1))) yield Pair(s1, s2) - ).removeDuplicates - } - ps.toSeq - } - - private var cache = (world.time, getPairs) - - /**All potential colliding pairs of the world. - * @see getPairs*/ - def pairs = {if (world.time != cache._1) cache = (world.time, getPairs); cache._2} - - /**Returns all colliding pairs.*/ - def collidingPairs: Seq[Pair] = for(p <- pairs; if (colliding(p))) yield p - - /**Returns all collisions.*/ - def collisions: Seq[Collision] = for(p <- pairs; if (colliding(p))) yield collision(p) -} diff --git a/src/sims/collision/Overlap.scala b/src/sims/collision/Overlap.scala deleted file mode 100644 index 97ecdd6..0000000 --- a/src/sims/collision/Overlap.scala +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.collision - -import sims.geometry._ - -case class Overlap(poly: ConvexPolygon, sideNum: Int, overlap: Double) diff --git a/src/sims/collision/Pair.scala b/src/sims/collision/Pair.scala deleted file mode 100644 index a01fb00..0000000 --- a/src/sims/collision/Pair.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.collision - -import sims.dynamics._ - -/**Pair of shapes.*/ -case class Pair(s1: Shape, s2: Shape){ - - override def equals(other: Any) = { //overriden to prevent removal during "GridDetector.getPairs" - other match { - case Pair(a, b) => ((a eq this.s1) && (b eq this.s2)) || ((b eq this.s1) && (a eq this.s2)) - case _ => false - } - } -} - -object Pair { - implicit def pair2Tuple(x: Pair) = (x.s1, x.s2) -} diff --git a/src/sims/collision/PolyCircleCollision.scala b/src/sims/collision/PolyCircleCollision.scala deleted file mode 100644 index 20f1d49..0000000 --- a/src/sims/collision/PolyCircleCollision.scala +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.collision - -import sims.dynamics._ -import sims.geometry._ - -/**Collision between a convex polygon and a circle.*/ -case class PolyCircleCollision(p: ConvexPolygon, c: Circle) extends Collision { - require(p.isInstanceOf[Shape]) - val shape1 = p.asInstanceOf[Shape] - val shape2 = c - - val normal = { - //minimum overlap - var min = (p.sides(0) distance c.pos) - c.radius - var axis = p.sides(0).n0 - for (s <- p.sides; val delta = (s distance c.pos) - c.radius) if (delta <= 0 && delta < min) { - min = delta - axis = s.n0 - } - for (v <- p.vertices; val delta = (v - c.pos).length - c.radius) if (delta <= 0 && delta <= min){ - min = delta - axis = (c.pos - v).unit - } - axis - } - - val points = List( - c.pos - normal * c.radius - ) -} diff --git a/src/sims/collision/PolyCollision.scala b/src/sims/collision/PolyCollision.scala deleted file mode 100644 index 5296f41..0000000 --- a/src/sims/collision/PolyCollision.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.collision - -import sims.geometry._ -import sims.dynamics._ -import scala.collection.mutable.Map - -/**Collision between two convex polygons.*/ -case class PolyCollision(p1: ConvexPolygon, p2: ConvexPolygon) extends Collision { - require(p1.isInstanceOf[Shape]) - require(p2.isInstanceOf[Shape]) - - def overlap(axis: Vector2D) = { - // println((p1.project(axis) overlap p2.project(axis)).toString + " to " + (p2.project(axis) overlap p1.project(axis))) - p1.project(axis) overlap p2.project(axis) - } - - lazy val overlaps = (for (i <- 0 until p2.sides.length) yield Overlap(p2, i, overlap(p2.sides(i).n0))) ++ - (for (i <- 0 until p1.sides.length) yield Overlap(p1, i, overlap(p1.sides(i).n0))) - - private var potMinOverlap = overlaps.find(_.overlap > 0.0) - require(potMinOverlap != None) - private var _minOverlap: Overlap = potMinOverlap.get - var minOverlap: Overlap = { - for (o <- overlaps) if ((o.overlap < _minOverlap.overlap) && (o.overlap > 0.0)) _minOverlap = o - _minOverlap - } - - - private lazy val refPoly = minOverlap.poly - private lazy val incPoly = if (minOverlap.poly eq p1) p2 else p1 - - lazy val shape1 = refPoly.asInstanceOf[Shape] - lazy val shape2 = incPoly.asInstanceOf[Shape] - - lazy val normal = refPoly.sides(minOverlap.sideNum).n0 - lazy val points = (for (v <- incPoly.vertices; if refPoly.contains(v)) yield v)++ - (for (v <- refPoly.vertices; if incPoly.contains(v)) yield v) - - /* ++ - (for (s <- incPoly.sides; - val clip = s.clipToSegment(refPoly.sides((refPoly.sides.length - (minOverlap.sideNum + 1)) % refPoly.sides.length)); - if (clip != None)) yield clip.get) ++ - (for (s <- incPoly.sides; - val clip = s.clipToSegment(refPoly.sides((refPoly.sides.length - (minOverlap.sideNum - 1)) % refPoly.sides.length)); - if (clip != None)) yield clip.get) - */ -} diff --git a/src/sims/dynamics/Body.scala b/src/sims/dynamics/Body.scala deleted file mode 100644 index 8c0e2ee..0000000 --- a/src/sims/dynamics/Body.scala +++ /dev/null @@ -1,141 +0,0 @@ - -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics - -import sims.geometry._ -import sims.dynamics.joints._ - -/**A two dimensional rigid body is made out of shapes. - * @param shps shapes that belong to this body.*/ -class Body(shps: Shape*){ - - /**Unique identification number.*/ - val uid = Body.nextUid - - /**Shapes that belong to this body.*/ - val shapes: List[Shape] = shps.toList - - //Shapes are added during initialisation. - for (s <- shapes) { - s.body = this - s.refLocalPos = s.pos - pos - s.rotation0 = s.rotation - } - - private var isFixed: Boolean = false - - /**Returns whether this body is fixed or not.*/ - def fixed = isFixed - - /**Fixes or frees this body. By fixing, linear and angular velocities are set to zero.*/ - def fixed_=(value: Boolean) = { - if (value) {linearVelocity = Vector2D.Null; angularVelocity = 0.0} - isFixed = value - } - - /**Flag for a world to monitor the properties of this body. - * @see World#monitors*/ - var monitor: Boolean = false - - /**Returns the position of this body. The position is equivalent to the center of mass. - * @return position of this body*/ - def pos: Vector2D = // COM = sum(pos*mass)/M - (Vector2D.Null /: shapes)((v: Vector2D, s: Shape) => v + s.pos * s.mass) / - (0.0 /: shapes)((i: Double, s: Shape) => i + s.mass) - - /**Sets the position of this body. By doing so all its shapes are translated. - * @param newPos new position*/ - def pos_=(newPos: Vector2D) = { - val stepPos = pos - shapes.foreach((s: Shape) => s.pos = s.pos - stepPos + newPos) - } - - /**Contains the current rotation of this body.*/ - private var _rotation: Double = 0.0 - - /**Returns the current rotation of this body.*/ - def rotation: Double = _rotation - - /**Sets the rotation of this body. Position and rotation of shapes are modified accordingly. - * @param r new rotation*/ - def rotation_=(newRotation: Double) = { - _rotation = newRotation - val stepPos = pos - for (s <- shapes) { - s.rotation = newRotation + s.rotation0 - s.pos = stepPos + (s.refLocalPos rotate (newRotation)) - } - } - - /**Linear velocity of this body.*/ - var linearVelocity: Vector2D = Vector2D.Null - - /**Angular velocity of this body.*/ - var angularVelocity: Double = 0 - - /**Linear velocity of the given point on this body (in world coordinates).*/ - def velocityOfPoint(point: Vector2D) = linearVelocity + ((point - pos).leftNormal * angularVelocity) - - /**Resulting force on the COM of this body.*/ - var force: Vector2D = Vector2D.Null - - /**Resulting torque on this body.*/ - var torque: Double = 0 - - /**Returns the mass of this body. If the body is free, its mass is the sum of the masses of its shapes. - * If the body is fixed, its mass is infinite (Double.PositiveInfinity). - * @return this body's mass*/ - def mass: Double = if (fixed) Double.PositiveInfinity else (0.0 /: shapes)((i: Double, s: Shape) => i + s.mass) - - /**Returns the moment of inertia for rotations about the COM of this body. - * It is calculated using the moments of inertia of this body's shapes and the parallel axis theorem. - * If the body is fixed, its moment of inertia is infinite (Double.PositiveInfinity). - * @return moment of inertia for rotations about the COM of this body*/ - def I: Double = if (fixed) Double.PositiveInfinity else - (0.0 /: (for (s <- shapes) yield (s.I + s.mass * ((s.pos - pos) dot (s.pos - pos)))))(_+_) - - /**Applies a force to the COM of this body. - * @param force applied force*/ - def applyForce(force: Vector2D) = if (!fixed) this.force += force - - /**Applies a force to a point on this body. Warning: the point is considered to be contained within this body. - * @param force applied force - * @param point position vector of the point (in world coordinates)*/ - def applyForce(force: Vector2D, point: Vector2D) = if (!fixed) {this.force += force; torque += (point - pos) cross force} - - /**Applies an impulse to the COM of this body. - * @param impulse applied impulse*/ - def applyImpulse(impulse: Vector2D) = if (!fixed) linearVelocity += impulse / mass - - /**Applies an impulse to a point on this body. Warning: the point is considered to be contained within this body. - * @param impulse applied impulse - * @param point position vector of the point (in world coordinates)*/ - def applyImpulse(impulse: Vector2D, point: Vector2D) = if (!fixed) {linearVelocity += impulse / mass; angularVelocity += ((point - pos) cross impulse) / I} - - /**Checks if the point point is contained in this body.*/ - def contains(point: Vector2D) = shapes.exists(_.contains(point)) - - override def toString: String = { - "Body" + uid + " " + shapes + " fixed=" + fixed + " m=" + mass + " I=" + I + " pos=" + pos + " rot=" + rotation + " v=" + linearVelocity + " w=" + angularVelocity + " F=" + force + " tau=" + torque - } - - /**Creates a new body containing this body's shapes and the shape s. - * @param s new shape - * @return new body*/ - def ~(s: Shape) = new Body((s :: shapes): _*) - - /**Creates a new body containing this body's shapes and the shapes of another body b. - * @param b body with extra shapes - * @return new body*/ - def ~(b: Body) = new Body((this.shapes ::: b.shapes): _*) -} - -object Body { - private var uidCounter = -1 - private def nextUid = {uidCounter += 1; uidCounter} -} \ No newline at end of file diff --git a/src/sims/dynamics/Circle.scala b/src/sims/dynamics/Circle.scala deleted file mode 100644 index b1d3703..0000000 --- a/src/sims/dynamics/Circle.scala +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics - -import sims.geometry._ -import sims.collision._ - -/** - * A circle. - * @param radius radius of this circle - * @param density density of this circle - */ -case class Circle(radius: Double, density: Double) extends Shape{ - - val volume = Math.Pi * radius * radius - - val I = mass * radius * radius / 2 - - def AABB = new AABB(pos - Vector2D(radius,radius), - pos + Vector2D(radius,radius)) - - def project(axis: Vector2D) = if (axis.x != 0) Projection(axis, - (pos.project(axis).x / axis.x) - radius, - (pos.project(axis).x / axis.x) + radius) - else Projection(axis, - (pos.project(axis).y / axis.y) - radius, - (pos.project(axis).y / axis.y) + radius) - - def contains(point: Vector2D) = (point - pos).length <= radius -} diff --git a/src/sims/dynamics/Constraint.scala b/src/sims/dynamics/Constraint.scala deleted file mode 100644 index eaa6952..0000000 --- a/src/sims/dynamics/Constraint.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics - -/**All constraints in SiMS implement this trait. - * Position and velocity can be corrected for each constraint. - * The implementation of constraints was inspired by Erin Catto's box2d.*/ -trait Constraint { - - /**Corrects the velocities of bodies according to this constraint. - * @param h a time interval, used for converting forces and impulses*/ - def correctVelocity(h: Double): Unit - - /**Corrects the positions of bodies according to this constraint. - * @param h a time interval, used for converting forces and impulses*/ - def correctPosition(h: Double): Unit -} diff --git a/src/sims/dynamics/Rectangle.scala b/src/sims/dynamics/Rectangle.scala deleted file mode 100644 index 89ab4c0..0000000 --- a/src/sims/dynamics/Rectangle.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics - -import sims.geometry._ -import sims.collision._ - -/**A rectangle is a polygon. - * @param halfWidth this rectangle's half width - * @param halfHeight this rectangle's half height - * @param density density of this rectangle - */ -case class Rectangle(halfWidth: Double, - halfHeight : Double, - density: Double) extends Shape with ConvexPolygon{ - - val volume = halfWidth * halfHeight * 4 - - val I = 1.0 / 12.0 * mass * ((2 * halfWidth) * (2 * halfWidth) + (2 * halfHeight) * (2 * halfHeight)) - - /**Returns the vectors from the center to the vertices of this rectangle. - * The first vertex is the upper-right vertex at a rotation of 0. - * Vertices are ordered counter-clockwise.*/ - def halfDiags: Array[Vector2D] = Array(Vector2D(halfWidth, halfHeight), - Vector2D(-halfWidth, halfHeight), - Vector2D(-halfWidth, -halfHeight), - Vector2D(halfWidth, -halfHeight)) map (_ rotate rotation) - - /**Returns the position vectors of this rectangle's vertices. - * The first vertex is the upper-right vertex at a rotation of 0. - * Vertices are ordered counter-clockwise.*/ - def vertices = for (h <- halfDiags) yield pos + h - -} \ No newline at end of file diff --git a/src/sims/dynamics/RegularPolygon.scala b/src/sims/dynamics/RegularPolygon.scala deleted file mode 100644 index b49d100..0000000 --- a/src/sims/dynamics/RegularPolygon.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics - -import Math._ -import sims.geometry._ - -/**A regular polygon with n sides whose excircle has a radius radius. - * @param n nmber of sides. - * @param radius radius of the excircle - * @param density density of this regular polygon - * @throws IllegalArgumentException if n is smaller than 3 */ -case class RegularPolygon(n: Int, radius: Double, density: Double) extends Shape with ConvexPolygon{ - require(n >= 3, "A polygon must have at least 3 sides.") - - /**Height of one of the constituting triangles.*/ - private val h: Double = radius * cos(Pi / n) - /**Half width of one of the constituting triangles.*/ - private val b: Double = radius * sin(Pi / n) - - def halfDiags = (for (i: Int <- (0 until n).toArray) yield (Vector2D(0, radius) rotate (2 * Pi * i / n))) map (_ rotate rotation) - - def vertices = for (h <- halfDiags) yield pos + h - - val volume = n * h * b - - /**Moment of inertia of one of the constituting triangles about the center of this polygon.*/ - private val Ic: Double = density * b * (3 * b + 16) * h * h * h * h / 54 - - val I = n * Ic -} diff --git a/src/sims/dynamics/Shape.scala b/src/sims/dynamics/Shape.scala deleted file mode 100644 index 47a4199..0000000 --- a/src/sims/dynamics/Shape.scala +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics - -import sims.geometry._ -import sims.collision._ - -/** -* An abstract shape. -*/ -abstract class Shape{ - - /**Unique identification number.*/ - val uid: Int = Shape.nextUid - - /**Flag determining this shapes ability to collide with other shapes.*/ - var collidable: Boolean = true - - /**Part of the coefficient of restitution for a collision between this shape and another. - * The coefficient of restitution is calculated out of the product of this part and the other shape's part.*/ - var restitution: Double = 0.7 - - /**Part of the coefficient of friction for a collision between this shape and another. - * The coefficient of friction is calculated out of the product of this part and the other shape's part.*/ - var friction: Double = 0.707 - - /**Position of this shape's COM (in world coordinates).*/ - var pos: Vector2D = Vector2D.Null - - /**Rotation of this shape about its COM.*/ - var rotation: Double = 0 - - /**Initial rotation. Rotation of this shape before it was added to a body.*/ - var rotation0 = 0.0 - - /**Local position of this shape's body COM to its COM at a body rotation of zero.*/ - var refLocalPos: Vector2D = Vector2D.Null - - /**Density. (Mass per area)*/ - val density: Double - - /**Volume. The volume is actually equivalent to this shape's area (SiMS is in 2D) - * and is used with this shape's density to calculate its mass.*/ - val volume: Double - - /**Returns the mass of this shape. The mass is given by volume times density. - @return mass of this shape*/ - def mass = volume * density - - /**Moment of inertia for a rotation about this shape's COM.*/ - val I: Double - - /**Containing body.*/ - private var _body: Body = _ - - /**Returns this shape's containing body.*/ - def body = _body - - /**Sets this shape's containing body.*/ - private[dynamics] def body_=(b: Body) = _body = b - - /**Returns this shape's axis aligned bounding box.*/ - def AABB: AABB - - /**Returns the projection of this shape onto the line given by the directional vector axis. - * @param axis directional vector of the line - * @return projection of this shape*/ - def project(axis: Vector2D): Projection - - /**Checks if the point point is contained in this shape.*/ - def contains(point: Vector2D): Boolean - - /**Creates a new body made out of tis shape. - @return a body made out of tis shape*/ - def asBody = new Body(this) - - /**Shapes with which this shape cannot collide.*/ - val transientShapes: collection.mutable.Set[Shape] = collection.mutable.Set() - - /**Creates a new body out of this shape and the shape s.*/ - def ~(s: Shape) = new Body(this, s) - - /**Creates a new body out of this shape and the shapes of body b.*/ - def ~(b: Body) = { - val shapes = this :: b.shapes - new Body(shapes: _*) - } -} - -object Shape { - private var uidCounter = -1 - private def nextUid = {uidCounter += 1; uidCounter} -} diff --git a/src/sims/dynamics/World.scala b/src/sims/dynamics/World.scala deleted file mode 100644 index f24a3fd..0000000 --- a/src/sims/dynamics/World.scala +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics - -import sims.geometry._ -import sims.collision._ -import sims.dynamics.joints._ -import scala.collection.mutable.ArrayBuffer - -/**A world contains and simulates a system of rigid bodies and joints.*/ -class World { - - /**Time intervals in which this world simulates.*/ - var timeStep: Double = 1.0 / 60 - - /**Number of constraint corrections per time step.*/ - var iterations: Int = 10 - - /**Gravity in this world.*/ - var gravity = Vector2D(0, -9.81) - - /**Bodies contained in this world.*/ - val bodies = new ArrayBuffer[Body] - - /**Joints contained in this world.*/ - val joints = new ArrayBuffer[Joint] - - /**Monitoring methods for bodies. - *

- * The first element of the tuple is the method's title and the second the method. - * Example usage: monitors += ("Y-Position", _.pos.y.toString) - * This will calculate all bodies - whose monitor field is set to - * true - second position components.*/ - val monitors = new ArrayBuffer[(String, Body => Any)] - - /**Collsion detector who manages collision detection in this world.*/ - val detector: Detector = new GridDetector(this) - - /**Warning if a body's velocity exceeds the speed of light.*/ - var overCWarning = false - - /**Flag to enable collision detection.*/ - var enableCollisionDetection = true - - /**Flag to enable position correction for constraints.*/ - var enablePositionCorrection = true - - /**Minimal, non-zero linear velocity.*/ - var minLinearVelocity: Double = 0.0001 - - /**Minimal, non-zero angular velocity.*/ - var minAngularVelocity: Double = 0.0001 - - /**Returns all shapes of all bodies in this world.*/ - def shapes = for (b <- bodies; s <- b.shapes) yield s - - /**Adds the given body to this world.*/ - def +=(body: Body) = bodies += body - - /**Adds the given joint to this world.*/ - def +=(joint: Joint): Unit = joints += joint - - /**Adds the given prefabricated system of bodies and joints to this world.*/ - def +=(p: sims.prefabs.Prefab): Unit = { - for (b <- p.bodies) this += b - for (j <- p.joints) this += j - } - - /**Adds the given sequence of bodies to this world.*/ - def ++=(bs: Seq[Body]): Unit = for(b <- bs) this += b - - /**Removes the given body from this world.*/ - def -=(body: Body): Unit = bodies -= body - - /**Removes the given joint from this world.*/ - def -=(joint: Joint): Unit = joints -= joint - - /**Removes the given prefabricated system of bodies and joints from this world.*/ - def -=(p: sims.prefabs.Prefab): Unit = { - for (b <- p.bodies) this -= b - for (j <- p.joints) this -= j - } - - /**Removes the given sequence of bodies from this world.*/ - def --=(bs: Seq[Body]) = for(b <- bs) this -= b - - /**Removes all bodies, joints and monitoring methods from this world.*/ - def clear() = {joints.clear(); bodies.clear(); monitors.clear()} - - /**Current time in this world.*/ - var time: Double = 0.0 - - /**Simulates a time step of the duration timeStep. - *

- * The time step is simulated in the following phases: - *

    - *
  1. Forces are applied to bodies.
  2. - *
  3. Accelerations are integrated.
  4. - *
  5. Velocities are corrected.
  6. - *
  7. Velocities are integrated.
  8. - *
  9. Postions are corrected.
  10. - *
  11. The method postStep() is executed.
  12. - *
*/ - def step() = { - time += timeStep - - //force applying objects - for (j <- joints) j match {case f: ForceJoint => f.applyForce; case _ => ()} - - //integration of acclerations, yields velocities - for (b <- bodies) { - b.applyForce(gravity * b.mass) - b.linearVelocity = b.linearVelocity + (b.force / b.mass) * timeStep - b.angularVelocity = b.angularVelocity + (b.torque / b.I) * timeStep - } - - //correction of velocities - for (i <- 0 until iterations){ - for(c <- joints) c.correctVelocity(timeStep) - if (enableCollisionDetection) for (c <- detector.collisions) c.correctVelocity(timeStep) - } - - //integration of velocities, yields positions - for (b <- bodies) { - //warning when body gets faster than speed of light - if (b.linearVelocity.length >= 300000000) overCWarning = true - if (b.linearVelocity.length < minLinearVelocity) b.linearVelocity = Vector2D.Null - if (b.angularVelocity.abs < minAngularVelocity) b.angularVelocity = 0.0 - b.pos = b.pos + b.linearVelocity * timeStep - b.rotation = b.rotation + b.angularVelocity * timeStep - b.force = Vector2D.Null - b.torque = 0.0 - } - - //correction of positions - if (enablePositionCorrection) for (i <- 0 until iterations){ - for (c <- joints) c.correctPosition(timeStep) - if (enableCollisionDetection) for (c <- detector.collisions) c.correctPosition(timeStep) - } - - postStep() - } - - /**Initially empty method that is executed after each time step. This method - * may be overriden to create custom behaviour in a world.*/ - def postStep() = {} - - /**Returns information about this world.*/ - def info = { - "Bodies = " + bodies.length + "\n" + - "Shapes = " + shapes.length + "\n" + - "Joints = " + joints.length + "\n" + - "Collisions = " + detector.collisions.length + "\n" + - "Monitors = " + monitors.length + "\n" + - "Gravity = " + gravity + "m/s^2\n" + - "Timestep = " + timeStep + "s\n" + - "Time = " + time + "s\n" + - "Iterations = " + iterations - } -} diff --git a/src/sims/dynamics/joints/DistanceJoint.scala b/src/sims/dynamics/joints/DistanceJoint.scala deleted file mode 100644 index 1bf9b46..0000000 --- a/src/sims/dynamics/joints/DistanceJoint.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics.joints - -import sims.dynamics._ -import sims.geometry._ - -/** DistanceJoints keep their connection points at a constant distance. - * @param node1 first associated body - * @param anchor1 first connection point - * @param node2 second associated body - * @param anchor2 second connection point*/ -case class DistanceJoint(node1: Body, anchor1: Vector2D, node2: Body, anchor2: Vector2D) extends Joint{ - def this(node1: Body, node2: Body) = this(node1, node1.pos, node2, node2.pos) - - /**Distance between the two connection points at initialisation (the desired distance).*/ - val distance = (anchor2 - anchor1).length - - private val a1 = anchor1 - node1.pos - private val a2 = anchor2 - node2.pos - private val initRotation1 = node1.rotation - private val initRotation2 = node2.rotation - - /**Returns the connection point on body one (in world coordinates).*/ - def connection1 = (a1 rotate (node1.rotation - initRotation1)) + node1.pos - - /**Returns the connection point on body two (in world coordinates).*/ - def connection2 = (a2 rotate (node2.rotation - initRotation2)) + node2.pos - - /**Relative position of the connection points.*/ - def x = connection2 - connection1 - - /**Relative velocity of the connection points.*/ - def v = node2.velocityOfPoint(connection2) - node1.velocityOfPoint(connection1) - - /* x = connection2 - connection1 - * C = ||x|| - L - * u = x / ||x|| - * v = v2 + w2 cross r2 - v1 - w1 cross r1 - * Cdot = u dot v - * J = [-u -(r1 cross u) u (r2 cross u)] - * 1/m = J * M^-1 * JT - * = 1/m1 * u * u + 1/m2 * u * u + 1/I1 * (r1 cross u)^2 + 1/I2 * (r2 cross u)^2*/ - override def correctVelocity(h: Double) = { - val x = this.x //relative position - val v = this.v //relative velocity - val r1 = (connection1 - node1.pos) - val r2 = (connection2 - node2.pos) - val cr1 = r1 cross x.unit - val cr2 = r2 cross x.unit - val Cdot = x.unit dot v //velocity constraint - val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 //=J M^-1 JT - val m = if (invMass == 0.0) 0.0 else 1/invMass //avoid division by zero - val lambda = -m * Cdot //=-JV/JM^-1JT - val impulse = x.unit * lambda //P=J lambda - node1.applyImpulse(-impulse, connection1) - node2.applyImpulse(impulse, connection2) - } - - override def correctPosition(h: Double) = { - val C = x.length - distance - val cr1 = (connection1 - node1.pos) cross x.unit - val cr2 = (connection2 - node2.pos) cross x.unit - val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 - val m = if (invMass == 0.0) 0.0 else 1/invMass - val impulse = -x.unit * m * C - node1.pos -= impulse / node1.mass - node2.pos += impulse / node2.mass - node1.rotation -= ((connection1 - node1.pos) cross impulse) / node1.I - node2.rotation += ((connection2 - node2.pos) cross impulse) / node2.I - } - -} \ No newline at end of file diff --git a/src/sims/dynamics/joints/ForceJoint.scala b/src/sims/dynamics/joints/ForceJoint.scala deleted file mode 100644 index 2074ee4..0000000 --- a/src/sims/dynamics/joints/ForceJoint.scala +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics.joints - -/**A joint which can apply a force to its anchor bodies, thus adding or removing energy to the system.*/ -trait ForceJoint { - - /**Applies a force on the anchor bodies.*/ - def applyForce(): Unit -} diff --git a/src/sims/dynamics/joints/Joint.scala b/src/sims/dynamics/joints/Joint.scala deleted file mode 100644 index 652df97..0000000 --- a/src/sims/dynamics/joints/Joint.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics.joints - -import sims.geometry._ -import sims.dynamics._ - -/**Joints constrain the movement of two bodies. - * Their implementation was inspired by Erin Catto's box2d.*/ -abstract class Joint extends Constraint{ - - /**First body of the joint.*/ - val node1: Body - - /**Second body of the joint.*/ - val node2: Body - - /**Corrects the velocities of this joint's associated bodies.*/ - def correctVelocity(h: Double): Unit - - /**Corrects the positions of this joint's associated bodies.*/ - def correctPosition(h: Double): Unit -} \ No newline at end of file diff --git a/src/sims/dynamics/joints/RevoluteJoint.scala b/src/sims/dynamics/joints/RevoluteJoint.scala deleted file mode 100644 index 66a4c06..0000000 --- a/src/sims/dynamics/joints/RevoluteJoint.scala +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics.joints - -import sims.geometry._ -import sims.math._ -import sims.dynamics._ -import Math._ - -/**A revolute joint that connects two bodies at a singe point. Inspired from JBox2D. - * Warning: there are still several bugs with revolute joints, if they are between two free - * bodies and not connected at their respective COMs.*/ -case class RevoluteJoint(node1: Body, node2: Body, anchor: Vector2D) extends Joint{ - private val a1 = anchor - node1.pos - private val a2 = anchor - node2.pos - private val initRotation1 = node1.rotation - private val initRotation2 = node2.rotation - def connection1 = (a1 rotate (node1.rotation - initRotation1)) + node1.pos - def connection2 = (a2 rotate (node2.rotation - initRotation2)) + node2.pos - - def x = connection2 - connection1 - def v = node2.velocityOfPoint(connection2) - node1.velocityOfPoint(connection1) - - /* x = connection2 - connection1 - * C = x - * Cdot = v = v2 - v1 = v2 + (w2 cross r2) - v1 - (w1 cross r1) - * J = [-I -r1_skew I r2_skew ] ????? - */ - def correctVelocity(h: Double) = { - val m1 = node1.mass - val m2 = node2.mass - val I1 = node1.I - val I2 = node2.I - val r1 = connection1 - node1.pos - val r2 = connection2 - node2.pos - - val K1 = new Matrix22(1/m1 + 1/m2, 0, - 0, 1/m1 + 1/m2) - val K2 = new Matrix22(1/I1 * r1.x * r1.x, -1/I1 * r1.x * r1.y, - -1/I1 * r1.x * r1.y, 1/I1 * r1.x * r1.x) - val K3 = new Matrix22(1/I2 * r2.x * r2.x, -1/I2 * r2.x * r2.y, - -1/I2 * r2.x * r2.y, 1/I2 * r2.x * r2.x) - val pivotMass = (K1 + K2 + K3).invert - val cdot = v - val p = pivotMass * cdot - node1.applyImpulse(p, connection1) - node2.applyImpulse(-p, connection2) - } - - def correctPosition(h: Double) = { - - } -} diff --git a/src/sims/dynamics/joints/SpringJoint.scala b/src/sims/dynamics/joints/SpringJoint.scala deleted file mode 100644 index 4d44864..0000000 --- a/src/sims/dynamics/joints/SpringJoint.scala +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics.joints - -import sims.dynamics._ -import sims.geometry._ - -/**A spring obeying Hooke's law. - * @param node1 first associated body - * @param anchor1 first connection point - * @param node2 second associated body - * @param anchor2 second connection point - * @param springConstant spring constant - * @param initialLength initial length - */ -case class SpringJoint(node1: Body, anchor1: Vector2D, node2: Body, anchor2: Vector2D, springConstant: Double, initialLength: Double) extends Joint with ForceJoint{ - - def this(node1: Body, anchor1: Vector2D, node2: Body, anchor2: Vector2D, springConstant: Double) = { - this(node1: Body, anchor1, node2: Body, anchor2, springConstant: Double, (anchor2 - anchor1).length) - } - - def this(node1: Body, node2: Body, springConstant: Double, initialLength: Double) = { - this(node1: Body, node1.pos, node2: Body, node2.pos, springConstant: Double, initialLength: Double) - } - def this(node1: Body, node2: Body, springConstant: Double) = { - this(node1: Body, node1.pos, node2: Body, node2.pos, springConstant: Double, (node2.pos - node1.pos).length) - } - - private val a1 = anchor1 - node1.pos - private val a2 = anchor2 - node2.pos - private val initRotation1 = node1.rotation - private val initRotation2 = node2.rotation - - /**Returns the connection point on body one (in world coordinates).*/ - def connection1 = (a1 rotate (node1.rotation - initRotation1)) + node1.pos - - /**Returns the connection point on body two (in world coordinates).*/ - def connection2 = (a2 rotate (node2.rotation - initRotation2)) + node2.pos - - /**Damping.*/ - var damping = 0.0 - - /**Relative position of the connection points.*/ - def x = connection2 - connection1 - - /**Relative velocity of the connection points.*/ - def v = node2.velocityOfPoint(connection2) - node1.velocityOfPoint(connection1) - - /**Returns the spring force.*/ - def force = (x.length - initialLength) * springConstant - - /**Applies the spring force to the connection points.*/ - def applyForce() = { - node1.applyForce(x.unit * force - (v * damping) project x, connection1) - node2.applyForce(-x.unit * force - (v * damping) project x, connection2) - //println("this should not happen") - } - - def correctVelocity(h: Double) = { - /* - val x = this.x - val v = this.v - val r1 = (connection1 - node1.pos) - val r2 = (connection2 - node2.pos) - val cr1 = r1 cross x.unit - val cr2 = r2 cross x.unit - val Cdot = x.unit dot v - val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 //=J M^-1 JT - val m = if (invMass == 0.0) 0.0 else 1/invMass - val lambda = Math.min(Math.max(-this.force * h, (-m * Cdot)), this.force * h) - println (force * h, -m * Cdot) - val impulse = x.unit * lambda - node1.applyImpulse(-impulse, connection1) - node2.applyImpulse(impulse, connection2) - */ - } - - def correctPosition(h: Double) = { - - } -} \ No newline at end of file diff --git a/src/sims/dynamics/joints/test/PrismaticJoint.scala b/src/sims/dynamics/joints/test/PrismaticJoint.scala deleted file mode 100644 index 040647d..0000000 --- a/src/sims/dynamics/joints/test/PrismaticJoint.scala +++ /dev/null @@ -1,84 +0,0 @@ -package sims.dynamics.joints.test - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.geometry._ - -case class PrismaticJoint(node1: Body, anchor1: Vector2D, node2: Body, anchor2: Vector2D) extends Joint{ - def this(node1: Body, node2: Body) = this(node1, node1.pos, node2, node2.pos) - - val angle = node2.rotation - node1.rotation - - private val a1 = anchor1 - node1.pos - private val a2 = anchor2 - node2.pos - private val initRotation1 = node1.rotation - private val initRotation2 = node2.rotation - - def connection1 = (a1 rotate (node1.rotation - initRotation1)) + node1.pos - def connection2 = (a2 rotate (node2.rotation - initRotation2)) + node2.pos - - def x = connection2 - connection1 - - def v = node2.velocityOfPoint(connection2) - node1.velocityOfPoint(connection1) - - - def correctVelocity(h: Double) = { - correctLinear(h) - //correctAngular(h) - } - - def correctLinear(h: Double) = { - val x = this.x.unit - val n0 = x.leftNormal - val v = this.v - val r1 = (connection1 - node1.pos) - val r2 = (connection2 - node2.pos) - val cr1 = r1 cross n0 - val cr2 = r2 cross n0 - val Cdot = n0 dot v - val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 - val m = if (invMass == 0.0) 0.0 else 1/invMass - val impulse = -n0 * m * Cdot - node1.applyImpulse(-impulse, connection1) - node2.applyImpulse(impulse, connection2) - } - - //J=[-1,1] - - def correctAngular(h: Double) = { - val w = node2.angularVelocity - node1.angularVelocity - val Cdot = w - val invMass = node1.I + node2.I - val m = 1 / invMass - val lambda = m * Cdot - node1.angularVelocity += lambda / node1.I - node2.angularVelocity += -lambda / node2.I - } - - def correctPosition(h: Double) = { - /* - val x = this.x.unit - val n0 = x.leftNormal - val v = this.v - val r1 = (connection1 - node1.pos) - val r2 = (connection2 - node2.pos) - val cr1 = r1 cross n0 - val cr2 = r2 cross n0 - val C = n0 dot x - val invMass = 1/node1.mass + 1/node1.I * cr1 * cr1 + 1/node2.mass + 1/node2.I * cr2 * cr2 - val m = if (invMass == 0.0) 0.0 else 1/invMass - val impulse = -n0 * m * C - node1.pos += -impulse - node1.rotation += -impulse cross r1 - node2.pos += impulse - node2.rotation += impulse cross r2 - - val relOmega = node2.angularVelocity - node2.angularVelocity - val invMassOmega = node1.I + node2.I - val mOmega = if (invMassOmega == 0.0) 0.0 else 1/invMassOmega - val Crot = node2.rotation - node2.rotation + angle - node1.rotation += mOmega * Crot - node2.rotation += -mOmega * Crot - */ - } -} diff --git a/src/sims/dynamics/joints/test/UnitCircleJoint.scala b/src/sims/dynamics/joints/test/UnitCircleJoint.scala deleted file mode 100644 index 09e72d9..0000000 --- a/src/sims/dynamics/joints/test/UnitCircleJoint.scala +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.dynamics.joints.test - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.geometry._ - -class UnitCircleJoint(body: Body, anchor: Vector2D) extends Joint{ - - val node1 = body - val node2 = body - - private val a = anchor - body.pos - private val initRotation = body.rotation - def connection = (a rotate (body.rotation - initRotation)) + body.pos - def x = connection - def v = body.velocityOfPoint(connection) - - /* - * C = ||x|| - 1 - * Cdot = x/||x|| dot v = u dot v - * J = [u (r cross u)] - */ - def correctVelocity(h: Double) = { - val r = connection - body.pos - val u = x.unit - val cr = r cross u - val mc = 1.0/(1/body.mass + 1/body.I * cr * cr) - val lambda = -mc * (u dot v) - val Pc = u * lambda - - val vupdate = u * lambda / body.mass - val wupdate = (r cross u) * lambda / body.I - - println("dv = " + vupdate + " dw = " + wupdate) - body.linearVelocity = body.linearVelocity + u * lambda / body.mass - body.angularVelocity = body.angularVelocity + (r cross u) * lambda / body.I - } - - def correctPosition(h: Double) = {} -} diff --git a/src/sims/geometry/ConvexPolygon.scala b/src/sims/geometry/ConvexPolygon.scala deleted file mode 100644 index 0b05aaa..0000000 --- a/src/sims/geometry/ConvexPolygon.scala +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.geometry - -import sims.collision._ -import sims.geometry._ - -/**Common properties of all convex polygons.*/ -trait ConvexPolygon { - - /**Returns positions of all vertices of this Polygon. Vertices are ordered counter-clockwise. - * @return position vectors of the vertices*/ - def vertices: Seq[Vector2D] - - /**Returns all sides of this polygon. The sides are ordered counter-clockwise, the first vertex of the side - * giving the side index.*/ - def sides = (for (i <- 0 until vertices.length) yield (new Segment(vertices(i), vertices((i + 1) % vertices.length)))).toArray - - /**Returns the projection of this polygon onto the line given by the directional vector axis. - * @param axis directional vector of the line - * @return projection of this polygon*/ - def project(axis: Vector2D) = { - val points = for (v <- vertices) yield {v project axis} - val bounds = for (p <- points) yield {if (axis.x != 0) p.x / axis.x else p.y / axis.y} - Projection(axis, - (bounds(0) /: bounds)(Math.min(_,_)), - (bounds(0) /: bounds)(Math.max(_,_))) - } - - /**Returns this polygon's axis aligned bounding box. - * @see collision.AABB*/ - def AABB = { - val xs = vertices map (_.x) - val ys = vertices map (_.y) - new AABB(Vector2D(xs.min, ys.min), - Vector2D(xs.max, ys.max)) - } - - /**Checks if the point point is contained in this polygon. - *

- * A ray is created, originating from the point and following an arbitrary direction (X-Axis was chosen). - * The number of intersections between the ray and this polygon's sides (including vertices) is counted. - * The amount of intersections with vertices is substracted form the previuos number. - * If the latter number is odd, the point is contained in the polygon.*/ - def contains(point: Vector2D) = { - val r = new Ray(point, Vector2D.i) - var intersections = 0 - for (s <- sides; if (r intersects s)) intersections += 1 - for (v <- vertices; if (r contains v)) intersections -= 1 - intersections % 2 != 0 - } -} diff --git a/src/sims/geometry/Projection.scala b/src/sims/geometry/Projection.scala deleted file mode 100644 index 0c340f0..0000000 --- a/src/sims/geometry/Projection.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.geometry - -import sims.math._ - -/**Projection on an axis. - *

- * Projections are commonly used in SiMS for collision detection. - * @param axis directional vector of the axis of the projection - * @param lower lower value of the projection - * @param upper upper value of the projection*/ -case class Projection(axis: Vector2D, - lower: Double, - upper: Double) { - require(axis != Vector2D.Null, "A projection's axis cannot be given by a null vector!") - - /**Checks this projection for overlap with another projection other. - * @throws IllegalArgumentExcepion if both projections axes aren't the same*/ - def overlaps(other: Projection): Boolean = { - require(axis == other.axis, "Cannot compare two projections on different axes!") - !((other.lower - this.upper) > 0 || (this.lower - other.upper) > 0) - } - - /**Returns the overlap between this projection and another projection other. - * @throws IllegalArgumentExcepion if both projections axes aren't the same*/ - def overlap(other: Projection): Double = { - require(axis == other.axis, "Cannot compare two projections on different axes!") - (Math.max(lower, other.lower) - Math.min(upper, other.upper)).abs - } -} diff --git a/src/sims/geometry/Ray.scala b/src/sims/geometry/Ray.scala deleted file mode 100644 index feb18a9..0000000 --- a/src/sims/geometry/Ray.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.geometry - -import sims.math._ -import Math._ - -/**A ray. - * @param point a point on the ray - * @param direction this ray's directional vector - * @throws IllegalArgumentException if the directional vector is the null vector*/ -case class Ray(point: Vector2D, direction: Vector2D) { - - require(direction != Vector2D.Null, "A ray's direction cannot be given by a null vector!") - - /**Checks this ray and the given segment for intersection. - * @param s the segment to test for intersection*/ - def intersects(s: Segment) = { - val p1 = point - val p2 = point + direction - val p3 = s.vertex1 - val p4 = s.vertex2 - val d = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y) - val na = (p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x) - val nb = (p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x) - if (d == 0 && na == 0 && nb == 0) - true //lines are coincident - else if (d == 0) - false //parallel - else { - val ua = na / d - val ub = nb / d - (ub >= 0) && (ub <= 1) && (ua >= 0) - } - } - - /**Checks if this ray contains the point p.*/ - def contains(p: Vector2D) = { - val v = p - point - p == point || - Matrix22(direction, v).det == 0 && - signum(direction.x) == signum(v.x) && - signum(direction.y) == signum(v.y) - } -} diff --git a/src/sims/geometry/Segment.scala b/src/sims/geometry/Segment.scala deleted file mode 100644 index 4aaec21..0000000 --- a/src/sims/geometry/Segment.scala +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.geometry - -/**A segment is given by its vertices. - * @param vertex1 position vector of the first vertex - * @param vertex2 position vector of the second vertex - * @throws IllegalArgumentException if both vertices are equal - */ -case class Segment(vertex1: Vector2D, vertex2: Vector2D){ - require(vertex1 != vertex2, "A segment must have 2 distinct vertices!") - - /**Length of this segment.*/ - val length = (vertex2 - vertex1).length - - /**Vector from vertex1 to vertex2.*/ - val d = vertex2 - vertex1 - - /**Unit directional vector.*/ - val d0 = d.unit - - /**Right normal vector.*/ - val n = d.rightNormal - - /**Right normal unit vector.*/ - val n0 = n.unit - - /**Smallest distance between this segment and the point point.*/ - def distance(point: Vector2D): Double = { - val v = point - vertex1 //vector from vertex1 to point - val projection = v project d - val alpha = if (d.x != 0) d.x / projection.x else d.y / projection.y - if (alpha >= 0 && projection.length <= length) //point is closer to line between vertex1 and vertex2 - (v project n0).length - else if (alpha < 0) //point is closer to vertex1 - (point - vertex1).length - else if (alpha > 0) //point is closer to vertex2 - (point - vertex2).length - else - throw new IllegalArgumentException("Error occured trying to compute distance between segment and point.") - } - - def clipToSegment(s: Segment): Option[Vector2D] = { - - val distance1 = (vertex1 - s.vertex1) dot s.n0 - val distance2 = (vertex2 - s.vertex1) dot s.n0 - - if (distance1 * distance2 < 0) { //auf anderen Seiten - /* Geradengleichungen - * ================== - * Segment1: s1: x = a + alpha * r | alpha in [0,1] - * Segment2: s2: x = b + beta * s | beta in [0,1] - * - * alpha = [s2(a1-b1)-s1(a2-b2)] / [r2s1-r1s2] - * beta = [r2(b1-a1)-r1(b2-a2)] / [r1s2-r2s1] - * = [r1(b2-a2)]-r2(b1-a1) / [r2s1-r1s2] - * s1: vertex1 + alpha * d - * s2: s.vertex1 + beta * s.d - */ - val denom: Double = d.y * s.d.x - d.x * s.d.y - val alpha: Double = (s.d.y * (vertex1.x - s.vertex1.x) - s.d.x * (vertex1.y - s.vertex1.y)) / denom - val beta: Double = (d.x * (s.vertex1.y - vertex1.y) - d.y * (s.vertex1.x - vertex1.x)) / denom - if (0.0 <= alpha && alpha <= 1.0 && 0.0 <= beta && beta <= 1.0) Some(vertex1 + d * alpha) - else None - } - else None - } -} diff --git a/src/sims/geometry/Vector2D.scala b/src/sims/geometry/Vector2D.scala deleted file mode 100644 index 4468a90..0000000 --- a/src/sims/geometry/Vector2D.scala +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.geometry - -import scala.Math._ - -/**A 2D vector. - * @param x 1st component - * @param y 2nd component*/ -case class Vector2D(x: Double, y: Double) { - - /**Vector addition.*/ - def +(v: Vector2D): Vector2D = Vector2D(x + v.x, y + v.y) - - /**Vector substraction.*/ - def -(v: Vector2D): Vector2D = this + (v * -1) - - /**Scalar multiplication.*/ - def *(n: Double): Vector2D = Vector2D(x * n, y * n) - - /**Scalar division.*/ - def /(n: Double): Vector2D = this * (1/n) - - /**Unary minus.*/ - def unary_- : Vector2D = Vector2D(-x, -y) - - /**Dot product.*/ - def dot(v: Vector2D): Double = x * v.x + y * v.y - - /**Cross product. Length only because in 2D. The direction would be given by the x3-axis.*/ - def cross(v: Vector2D): Double = x * v.y - y * v.x - - /**Norm or length of this vector.*/ - val length: Double = Math.sqrt(x * x + y * y) - - /**Unit vector.*/ - def unit: Vector2D = if (!(x == 0.0 && y == 0.0)) Vector2D(x / length, y / length) - else throw new IllegalArgumentException("Null vector does not have a unit vector.") - - /**Returns the projection of this vector onto the vector v.*/ - def project(v: Vector2D): Vector2D = { - if (v != Vector2D.Null) - v * ((this dot v) / (v dot v)) - else - Vector2D.Null - } - - /**Returns a rotation of this vector by angle radian.*/ - def rotate(angle: Double): Vector2D = { - Vector2D(cos(angle) * x - sin(angle) * y, - cos(angle) * y + sin(angle) * x) - } - - /**Left normal vector. (-y, x)*/ - def leftNormal: Vector2D = Vector2D(-y, x) - - /**Right normal vector. (y, -x)*/ - def rightNormal: Vector2D = Vector2D(y, -x) - - /**Checks if this vector is the null vector.*/ - def isNull: Boolean = this == Vector2D.Null - - /**Returns a list of this vector's components.*/ - def components = List(x, y) -} - -/**Contains special vectors.*/ -object Vector2D { - - /**Null vector.*/ - val Null = Vector2D(0,0) - - /**Horizontal unit vector. (1,0)*/ - val i = Vector2D(1,0) - - /**Vertical unit vector. (0,1)*/ - val j = Vector2D(0,1) -} - diff --git a/src/sims/materials/Material.scala b/src/sims/materials/Material.scala deleted file mode 100644 index b05e082..0000000 --- a/src/sims/materials/Material.scala +++ /dev/null @@ -1,7 +0,0 @@ -package sims.materials - -trait Material { - val density: Double - val restitution: Double - val friction: Double -} diff --git a/src/sims/materials/Rubber.scala b/src/sims/materials/Rubber.scala deleted file mode 100644 index b408d2d..0000000 --- a/src/sims/materials/Rubber.scala +++ /dev/null @@ -1,5 +0,0 @@ -package sims.materials - -object Rubber { - -} diff --git a/src/sims/materials/Steel.scala b/src/sims/materials/Steel.scala deleted file mode 100644 index 1d14563..0000000 --- a/src/sims/materials/Steel.scala +++ /dev/null @@ -1,5 +0,0 @@ -package sims.materials - -object Steel { - -} \ No newline at end of file diff --git a/src/sims/math/Matrix22.scala b/src/sims/math/Matrix22.scala deleted file mode 100644 index 54d24c7..0000000 --- a/src/sims/math/Matrix22.scala +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.math - -import sims.geometry._ - -/**A 2x2 matrix. - * @param c11 component 1,1 - * @param c12 component 1,2 - * @param c21 component 2,1 - * @param c22 component 2,2 - */ -case class Matrix22(c11: Double, c12: Double, c21: Double, c22: Double) { - - /**A 2x2 matrix can be created with two 2D vectors. In this case, each column is represented by a vector. - * @param c1 first column - * @param c2 second column*/ - def this(c1: Vector2D, c2: Vector2D) = this(c1.x, c2.x, c1.y, c2.y) - - /**Determinant of this matrix.*/ - def det = c11 * c22 - c21 * c12 - - /**Addition.*/ - def +(m: Matrix22) = - new Matrix22(c11 + m.c11, c12 + m.c12, - c21 + m.c21, c22 + m.c22) - - /**Scalar multiplication.*/ - def *(n: Double) = - new Matrix22(c11 * n, c12 * n, - c21 * n, c22 * n) - - /**Matrix multiplication.*/ - def *(m: Matrix22) = - new Matrix22(c11 * m.c11 + c12 * m.c21, c11 * m.c12 + c12 * m.c22, - c21 * m.c11 + c22 * m.c21, c21 * m.c12 + c22 * m.c22) - - /**Multiplikation with a 2D vector.*/ - def *(v: Vector2D) = - new Vector2D(c11 * v.x + c12 * v.y, - c21 * v.x + c22 * v.y) - - /**Inverse.*/ - def invert = - new Matrix22(c22 / det, -c12 / det, - -c21 / det, c11 / det) - } - -object Matrix22 { - def apply(c1: Vector2D, c2: Vector2D) = new Matrix22(c1.x, c2.x, c1.y, c2.y) -} diff --git a/src/sims/prefabs/Net.scala b/src/sims/prefabs/Net.scala deleted file mode 100644 index d3f4d57..0000000 --- a/src/sims/prefabs/Net.scala +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.prefabs - -import sims.geometry._ -import sims.dynamics._ -import sims.dynamics.joints._ - -class Net(width: Int, height: Int, initPos: Vector2D) extends Prefab { - val nodeDistance: Double = 0.2 - val nodeRadius: Double = 0.05 - val nodeDensity: Double = 4 - - val springConstant: Double = 50 - val springDamping: Double = 0 - - private val connectors: Array[Array[Body]] = - makeConnectors(width, height) - - override val bodies: List[Body] = for (row <- connectors.toList; elem <- row) yield elem - override val joints = connect(connectors) - - private def makeConnectors(w: Int, h: Int): Array[Array[Body]] = { - for(i <- (0 until w).toArray[Int]) yield - for(j <- (0 until h).toArray[Int]) yield - new Body(new Circle(nodeRadius, nodeDensity) {pos = Vector2D(nodeDistance * i, nodeDistance * j) + initPos}) - } - - private def connect(connectors: Array[Array[Body]]): List[DistanceJoint] = { - var r: List[DistanceJoint] = Nil - for(i <- 0 to connectors.length - 1; j <- 0 to connectors(i).length - 1) { - if (i > 0) - r = connect(connectors(i-1)(j),connectors(i)(j)) :: r - if (j > 0) - r = connect(connectors(i)(j-1),connectors(i)(j)) :: r - } - r - } - - private def connect(s1: Body, s2: Body): DistanceJoint = - new DistanceJoint(s1, s1.pos, s2, s2.pos) - -} \ No newline at end of file diff --git a/src/sims/prefabs/Prefab.scala b/src/sims/prefabs/Prefab.scala deleted file mode 100644 index 84bb3b7..0000000 --- a/src/sims/prefabs/Prefab.scala +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.prefabs - -import sims.dynamics._ -import sims.dynamics.joints._ - -trait Prefab { - val bodies: Iterable[Body] = Nil - val joints: Iterable[Joint] = Nil -} diff --git a/src/sims/prefabs/Pylon.scala b/src/sims/prefabs/Pylon.scala deleted file mode 100644 index 7f3211f..0000000 --- a/src/sims/prefabs/Pylon.scala +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.prefabs - -import sims.geometry._ -import sims.dynamics._ -import sims.dynamics.joints._ - -class Pylon extends Prefab{ - val position: Vector2D = Vector2D(2,1) - val nodeDensity: Double = 100 - val beamHeight: Double = 1 - val beamWidth: Double = 0.5 - val beamNumber: Int = 10 - - private val nodeRow1 = (for (i <- 0 to beamNumber) yield (new Circle(0.01, nodeDensity) { - pos = position + Vector2D(0, i * beamHeight)}).asBody).toList - private val nodeRow2 = (for (i <- 0 to beamNumber) yield (new Circle(0.01, nodeDensity) { - pos = position + Vector2D(beamWidth, i * beamHeight)}).asBody).toList - - private val beamRow1 = (for (i <- 0 until nodeRow1.length - 1) yield - new DistanceJoint(nodeRow1(i), nodeRow1(i).pos, nodeRow1(i+1), nodeRow1(i + 1).pos)).toList - private val beamRow2 = (for (i <- 0 until nodeRow1.length - 1) yield - new DistanceJoint(nodeRow2(i), nodeRow2(i).pos, nodeRow2(i+1), nodeRow2(i + 1).pos)).toList - - private val latBeams = (for (i <- 0 to beamNumber) yield - new DistanceJoint(nodeRow1(i), nodeRow2(i))).toList - private val diagBeams1 = (for (i <- 0 until beamNumber) yield - new DistanceJoint(nodeRow1(i), nodeRow2(i + 1))).toList - private val diagBeams2 = (for (i <- 0 until beamNumber) yield - new DistanceJoint(nodeRow2(i), nodeRow1(i + 1))).toList - - - - - lazy val nodes = nodeRow1 ++ nodeRow2 - lazy val beams = beamRow1 ++ beamRow2 ++ latBeams ++ diagBeams1 ++ diagBeams2 - - override val bodies = nodes - override val joints = beams - - -} diff --git a/src/sims/prefabs/Ragdoll.scala b/src/sims/prefabs/Ragdoll.scala deleted file mode 100644 index 00e4b8d..0000000 --- a/src/sims/prefabs/Ragdoll.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.prefabs - -import sims.dynamics._ -import sims.dynamics.joints._ -import sims.geometry._ - -class Ragdoll(position: Vector2D) extends Prefab { - val headTorso = new Body(new Circle(0.1, 1) {pos = position}, - new Rectangle(0.09, 0.35, 1) {pos = position + Vector2D(0, -0.45)}) - val thigh1 = (new Rectangle(0.075, 0.17, 1) {pos = position + Vector2D(0, -0.97)}).asBody - val thigh2 = (new Rectangle(0.075, 0.17, 1) {pos = position + Vector2D(0, -0.97)}).asBody - val tibia1 = (new Rectangle(0.075, 0.25, 1) {pos = position + Vector2D(0, -1.39)}).asBody - val tibia2 = (new Rectangle(0.075, 0.25, 1) {pos = position + Vector2D(0, -1.39)}).asBody - val foot1 = (new Circle(0.08, 1) {pos = position + Vector2D(0, -1.72)}).asBody - val foot2 = (new Circle(0.08, 1) {pos = position + Vector2D(0, -1.72)}).asBody - val upperArm1 = (new Rectangle(0.17, 0.06, 1) {pos = position + Vector2D(0.17, -0.16)}).asBody - val upperArm2 = (new Rectangle(0.17, 0.06, 1) {pos = position + Vector2D(-0.17, -0.16)}).asBody - val forearm1 = (new Rectangle(0.15, 0.06, 1) {pos = position + Vector2D(0.49, -0.16)}).asBody - val forearm2 = (new Rectangle(0.15, 0.06, 1) {pos = position + Vector2D(-0.49, -0.16)}).asBody - val hand1 = (new Circle(0.07, 1) {pos = position + Vector2D(0.71, -0.16)}).asBody - val hand2 = (new Circle(0.07, 1) {pos = position + Vector2D(-0.71, -0.16)}).asBody - - override val bodies = List(headTorso, - thigh1, thigh2, - tibia1, tibia2, - foot1, foot2, - upperArm1, upperArm2, - forearm1, forearm2, - hand1, hand2) - private val shapes = bodies.flatMap(_.shapes) - for (s <- shapes) s.transientShapes ++= shapes - - val shoulder1 = RevoluteJoint(headTorso, upperArm1, position + Vector2D(0, -0.16)) - val shoulder2 = RevoluteJoint(headTorso, upperArm2, position + Vector2D(0, -0.16)) - override val joints = Nil //List(shoulder1, shoulder2) - -} diff --git a/src/sims/util/Polar.scala b/src/sims/util/Polar.scala deleted file mode 100644 index c4009b5..0000000 --- a/src/sims/util/Polar.scala +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.util - -import sims.geometry._ -import scala.Math._ - -/**Polar coordinates.*/ -case class Polar(distance: Double, angle: Double) { - - /**Returns the vector representation of these polar coordinates.*/ - def toCarthesian = Vector2D(distance * sin(angle), distance * cos(angle)) -} diff --git a/src/sims/util/Positioning.scala b/src/sims/util/Positioning.scala deleted file mode 100644 index cf72276..0000000 --- a/src/sims/util/Positioning.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.util - -import sims.geometry._ -import sims.dynamics._ - -/**Utility functions for comfortable positioning of bodies.*/ -object Positioning { - - implicit def int2RelativeVector(x: Int): RelativeVector = new RelativeVector(x, 0) - implicit def double2RelativeVector(x: Double): RelativeVector = new RelativeVector(x, 0) - implicit def vector2RelativeVector(v: Vector2D): RelativeVector = new RelativeVector(v.x, v.y) - implicit def polar2Carthesian(p: Polar): Vector2D = p.toCarthesian - implicit def polar2RelativeVector(p: Polar): RelativeVector = vector2RelativeVector(p.toCarthesian) - - def position(s: Shape)(a: Vector2D) = { - s.pos = a - } -} diff --git a/src/sims/util/RelativeVector.scala b/src/sims/util/RelativeVector.scala deleted file mode 100644 index 374f92c..0000000 --- a/src/sims/util/RelativeVector.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Simple Mechanics Simulator (SiMS) - * copyright (c) 2009 Jakob Odersky - * made available under the MIT License -*/ - -package sims.util - -import sims.geometry._ -import sims.dynamics._ - -class RelativeVector(val x: Double, val y: Double) { - def above(point: Vector2D): Vector2D = point + Vector2D(0, x) - def below(point: Vector2D): Vector2D = point - Vector2D(0, x) - def left(point: Vector2D): Vector2D = point - Vector2D(x, 0) - def right(point: Vector2D): Vector2D = point + Vector2D(x, 0) - def from(point: Vector2D): Vector2D = point + Vector2D(x, y) - - def above(s: Shape): Vector2D = this.above(s.pos) - def below(s: Shape): Vector2D = this.below(s.pos) - def left(s: Shape): Vector2D = this.left(s.pos) - def right(s: Shape): Vector2D = this.right(s.pos) - def from(s: Shape): Vector2D = this.from(s.pos) -} -- cgit v1.2.3