Просмотр исходного кода

Merge pull request #690 from fodinabor/Android

Android
Ivan Safrin 9 лет назад
Родитель
Сommit
bf98497601
100 измененных файлов с 10372 добавлено и 20 удалено
  1. 9 0
      assets/ide/Fonts/Lato-Black.ttf
  2. 1 0
      build/android/.idea/.name
  3. 22 0
      build/android/.idea/compiler.xml
  4. 3 0
      build/android/.idea/copyright/profiles_settings.xml
  5. 6 0
      build/android/.idea/encodings.xml
  6. 32 0
      build/android/.idea/gradle.xml
  7. 46 0
      build/android/.idea/misc.xml
  8. 13 0
      build/android/.idea/modules.xml
  9. 12 0
      build/android/.idea/runConfigurations.xml
  10. 6 0
      build/android/.idea/vcs.xml
  11. 1 0
      build/android/Polycode2DPhysics/.gitignore
  12. 31 0
      build/android/Polycode2DPhysics/AndroidManifest.xml
  13. 41 0
      build/android/Polycode2DPhysics/build.gradle
  14. 9 0
      build/android/Polycode2DPhysics/jni/Android.mk
  15. 5 0
      build/android/Polycode2DPhysics/jni/Application.mk
  16. 17 0
      build/android/Polycode2DPhysics/proguard-rules.pro
  17. 1 0
      build/android/Polycode3DPhysics/.gitignore
  18. 31 0
      build/android/Polycode3DPhysics/AndroidManifest.xml
  19. 41 0
      build/android/Polycode3DPhysics/build.gradle
  20. 9 0
      build/android/Polycode3DPhysics/jni/Android.mk
  21. 5 0
      build/android/Polycode3DPhysics/jni/Application.mk
  22. 17 0
      build/android/Polycode3DPhysics/proguard-rules.pro
  23. 1 0
      build/android/PolycodeUI/.gitignore
  24. 31 0
      build/android/PolycodeUI/AndroidManifest.xml
  25. 41 0
      build/android/PolycodeUI/build.gradle
  26. 9 0
      build/android/PolycodeUI/jni/Android.mk
  27. 5 0
      build/android/PolycodeUI/jni/Application.mk
  28. 17 0
      build/android/PolycodeUI/proguard-rules.pro
  29. 1 0
      build/android/Polycore/.gitignore
  30. 31 0
      build/android/Polycore/AndroidManifest.xml
  31. 45 0
      build/android/Polycore/build.gradle
  32. 7 0
      build/android/Polycore/jni/Android.mk
  33. 5 0
      build/android/Polycore/jni/Application.mk
  34. 17 0
      build/android/Polycore/proguard-rules.pro
  35. 2 0
      build/android/TemplateApp/.gitignore
  36. 27 0
      build/android/TemplateApp/AndroidManifest.xml
  37. 50 0
      build/android/TemplateApp/build.gradle
  38. 82 0
      build/android/TemplateApp/jni/Android.mk
  39. 5 0
      build/android/TemplateApp/jni/Application.mk
  40. 19 0
      build/android/TemplateApp/jni/PolycodeTemplate.cpp
  41. 153 0
      build/android/TemplateApp/jni/PolycodeTemplateApp.cpp
  42. 39 0
      build/android/TemplateApp/jni/PolycodeTemplateApp.h
  43. 17 0
      build/android/TemplateApp/proguard-rules.pro
  44. BIN
      build/android/TemplateApp/src/main/assets/main_icon.png
  45. 13 0
      build/android/TemplateApp/src/main/java/org/polycode/templateapp/PolycodeActivity.java
  46. 23 0
      build/android/build.gradle
  47. 18 0
      build/android/gradle.properties
  48. BIN
      build/android/gradle/wrapper/gradle-wrapper.jar
  49. 6 0
      build/android/gradle/wrapper/gradle-wrapper.properties
  50. 160 0
      build/android/gradlew
  51. 90 0
      build/android/gradlew.bat
  52. 1 0
      build/android/settings.gradle
  53. 0 0
      build/linux/Makefile
  54. 13 14
      build/linux/TemplateApp/PolycodeTemplateApp.cpp
  55. 62 0
      include/Box2D/Box2D.h
  56. 87 0
      include/Box2D/Collision/Shapes/b2CircleShape.h
  57. 131 0
      include/Box2D/Collision/Shapes/b2PolygonShape.h
  58. 95 0
      include/Box2D/Collision/Shapes/b2Shape.h
  59. 229 0
      include/Box2D/Collision/b2BroadPhase.h
  60. 240 0
      include/Box2D/Collision/b2Collision.h
  61. 141 0
      include/Box2D/Collision/b2Distance.h
  62. 286 0
      include/Box2D/Collision/b2DynamicTree.h
  63. 59 0
      include/Box2D/Collision/b2TimeOfImpact.h
  64. 59 0
      include/Box2D/Common/b2BlockAllocator.h
  65. 624 0
      include/Box2D/Common/b2Math.h
  66. 151 0
      include/Box2D/Common/b2Settings.h
  67. 60 0
      include/Box2D/Common/b2StackAllocator.h
  68. 38 0
      include/Box2D/Dynamics/Contacts/b2CircleContact.h
  69. 242 0
      include/Box2D/Dynamics/Contacts/b2Contact.h
  70. 78 0
      include/Box2D/Dynamics/Contacts/b2ContactSolver.h
  71. 38 0
      include/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h
  72. 38 0
      include/Box2D/Dynamics/Contacts/b2PolygonContact.h
  73. 51 0
      include/Box2D/Dynamics/Contacts/b2TOISolver.h
  74. 140 0
      include/Box2D/Dynamics/Joints/b2DistanceJoint.h
  75. 99 0
      include/Box2D/Dynamics/Joints/b2FrictionJoint.h
  76. 111 0
      include/Box2D/Dynamics/Joints/b2GearJoint.h
  77. 226 0
      include/Box2D/Dynamics/Joints/b2Joint.h
  78. 170 0
      include/Box2D/Dynamics/Joints/b2LineJoint.h
  79. 114 0
      include/Box2D/Dynamics/Joints/b2MouseJoint.h
  80. 175 0
      include/Box2D/Dynamics/Joints/b2PrismaticJoint.h
  81. 148 0
      include/Box2D/Dynamics/Joints/b2PulleyJoint.h
  82. 174 0
      include/Box2D/Dynamics/Joints/b2RevoluteJoint.h
  83. 82 0
      include/Box2D/Dynamics/Joints/b2WeldJoint.h
  84. 802 0
      include/Box2D/Dynamics/b2Body.h
  85. 52 0
      include/Box2D/Dynamics/b2ContactManager.h
  86. 326 0
      include/Box2D/Dynamics/b2Fixture.h
  87. 105 0
      include/Box2D/Dynamics/b2Island.h
  88. 35 0
      include/Box2D/Dynamics/b2TimeStep.h
  89. 285 0
      include/Box2D/Dynamics/b2World.h
  90. 217 0
      include/Box2D/Dynamics/b2WorldCallbacks.h
  91. 2 0
      include/Polycode.h
  92. 2774 0
      include/SLES/OpenSLES.h
  93. 47 0
      include/SLES/OpenSLES_Platform.h
  94. 58 0
      include/polycode/core/PolyAAssetFileProvider.h
  95. 160 0
      include/polycode/core/PolyAndroidCore.h
  96. 11 5
      include/polycode/core/PolyCore.h
  97. 5 0
      include/polycode/core/PolyGlobals.h
  98. 1 0
      include/polycode/core/PolyOpenGLGraphicsInterface.h
  99. 57 0
      include/polycode/core/PolyOpenSLAudioInterface.h
  100. 1 1
      include/polycode/core/PolySDLCore.h

+ 9 - 0
assets/ide/Fonts/Lato-Black.ttf

@@ -0,0 +1,9 @@
+*.iml
+.gradle
+/local.properties
+/.idea/workspace.xml
+/.idea/libraries
+.DS_Store
+/build
+/captures
+libs

+ 1 - 0
build/android/.idea/.name

@@ -0,0 +1 @@
+Polycore

+ 22 - 0
build/android/.idea/compiler.xml

@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="CompilerConfiguration">
+    <resourceExtensions />
+    <wildcardResourcePatterns>
+      <entry name="!?*.java" />
+      <entry name="!?*.form" />
+      <entry name="!?*.class" />
+      <entry name="!?*.groovy" />
+      <entry name="!?*.scala" />
+      <entry name="!?*.flex" />
+      <entry name="!?*.kt" />
+      <entry name="!?*.clj" />
+      <entry name="!?*.aj" />
+    </wildcardResourcePatterns>
+    <annotationProcessing>
+      <profile default="true" name="Default" enabled="false">
+        <processorPath useClasspath="true" />
+      </profile>
+    </annotationProcessing>
+  </component>
+</project>

+ 3 - 0
build/android/.idea/copyright/profiles_settings.xml

@@ -0,0 +1,3 @@
+<component name="CopyrightManager">
+  <settings default="" />
+</component>

+ 6 - 0
build/android/.idea/encodings.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="Encoding">
+    <file url="PROJECT" charset="UTF-8" />
+  </component>
+</project>

+ 32 - 0
build/android/.idea/gradle.xml

@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="GradleSettings">
+    <option name="linkedExternalProjectsSettings">
+      <GradleProjectSettings>
+        <option name="distributionType" value="LOCAL" />
+        <option name="externalProjectPath" value="$PROJECT_DIR$" />
+        <option name="gradleHome" value="$APPLICATION_HOME_DIR$/gradle/gradle-2.10" />
+        <option name="modules">
+          <set>
+            <option value="$PROJECT_DIR$" />
+            <option value="$PROJECT_DIR$/Polycode2DPhysics" />
+            <option value="$PROJECT_DIR$/Polycode3DPhysics" />
+            <option value="$PROJECT_DIR$/PolycodeUI" />
+            <option value="$PROJECT_DIR$/Polycore" />
+            <option value="$PROJECT_DIR$/TemplateApp" />
+          </set>
+        </option>
+        <option name="myModules">
+          <set>
+            <option value="$PROJECT_DIR$" />
+            <option value="$PROJECT_DIR$/Polycode2DPhysics" />
+            <option value="$PROJECT_DIR$/Polycode3DPhysics" />
+            <option value="$PROJECT_DIR$/PolycodeUI" />
+            <option value="$PROJECT_DIR$/Polycore" />
+            <option value="$PROJECT_DIR$/TemplateApp" />
+          </set>
+        </option>
+      </GradleProjectSettings>
+    </option>
+  </component>
+</project>

+ 46 - 0
build/android/.idea/misc.xml

@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="EntryPointsManager">
+    <entry_points version="2.0" />
+  </component>
+  <component name="NullableNotNullManager">
+    <option name="myDefaultNullable" value="android.support.annotation.Nullable" />
+    <option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
+    <option name="myNullables">
+      <value>
+        <list size="4">
+          <item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
+          <item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
+          <item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
+          <item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
+        </list>
+      </value>
+    </option>
+    <option name="myNotNulls">
+      <value>
+        <list size="4">
+          <item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
+          <item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
+          <item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
+          <item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
+        </list>
+      </value>
+    </option>
+  </component>
+  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
+    <OptionsSetting value="true" id="Add" />
+    <OptionsSetting value="true" id="Remove" />
+    <OptionsSetting value="true" id="Checkout" />
+    <OptionsSetting value="true" id="Update" />
+    <OptionsSetting value="true" id="Status" />
+    <OptionsSetting value="true" id="Edit" />
+    <ConfirmationsSetting value="0" id="Add" />
+    <ConfirmationsSetting value="0" id="Remove" />
+  </component>
+  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
+    <output url="file://$PROJECT_DIR$/build/classes" />
+  </component>
+  <component name="ProjectType">
+    <option name="id" value="Android" />
+  </component>
+</project>

+ 13 - 0
build/android/.idea/modules.xml

@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/Polycode2DPhysics/Polycode2DPhysics.iml" filepath="$PROJECT_DIR$/Polycode2DPhysics/Polycode2DPhysics.iml" />
+      <module fileurl="file://$PROJECT_DIR$/Polycode3DPhysics/Polycode3DPhysics.iml" filepath="$PROJECT_DIR$/Polycode3DPhysics/Polycode3DPhysics.iml" />
+      <module fileurl="file://$PROJECT_DIR$/PolycodeUI/PolycodeUI.iml" filepath="$PROJECT_DIR$/PolycodeUI/PolycodeUI.iml" />
+      <module fileurl="file://$PROJECT_DIR$/Polycore/Polycore.iml" filepath="$PROJECT_DIR$/Polycore/Polycore.iml" />
+      <module fileurl="file://$PROJECT_DIR$/TemplateApp/TemplateApp.iml" filepath="$PROJECT_DIR$/TemplateApp/TemplateApp.iml" />
+      <module fileurl="file://$PROJECT_DIR$/android.iml" filepath="$PROJECT_DIR$/android.iml" />
+    </modules>
+  </component>
+</project>

+ 12 - 0
build/android/.idea/runConfigurations.xml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="RunConfigurationProducerService">
+    <option name="ignoredProducers">
+      <set>
+        <option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
+        <option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
+        <option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
+      </set>
+    </option>
+  </component>
+</project>

+ 6 - 0
build/android/.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
+  </component>
+</project>

+ 1 - 0
build/android/Polycode2DPhysics/.gitignore

@@ -0,0 +1 @@
+/build

+ 31 - 0
build/android/Polycode2DPhysics/AndroidManifest.xml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- BEGIN_INCLUDE(manifest) -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.example.native_activity"
+        android:versionCode="1"
+        android:versionName="1.0">
+
+    <uses-sdk android:minSdkVersion="21" />
+
+    <!-- This .apk has no Java code itself, so set hasCode to false. -->
+    <application android:label="Polycore" android:hasCode="false">
+
+        <!-- Our activity is the built-in NativeActivity framework class.
+             This will take care of integrating with our NDK code. -->
+        <activity android:name="android.app.NativeActivity"
+                android:label="Polycode2DPhysics"
+                android:configChanges="orientation|keyboardHidden">
+            <!-- Tell NativeActivity the name of or .so -->
+            <meta-data android:name="android.app.lib_name"
+                    android:value="native-activity" />
+            <meta-data android:name="android.app.func_name"
+                    android:value="main" />
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest> 
+<!-- END_INCLUDE(manifest) -->

+ 41 - 0
build/android/Polycode2DPhysics/build.gradle

@@ -0,0 +1,41 @@
+import org.apache.tools.ant.taskdefs.condition.Os
+
+apply plugin: 'com.android.application'
+
+android {
+    compileSdkVersion 23
+    buildToolsVersion "23.0.2"
+
+    defaultConfig {
+    applicationId "org.polycode.polycode2dphysics"
+        minSdkVersion 21
+        targetSdkVersion 23
+        versionCode 1
+        versionName "1.0"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+    sourceSets.main {
+        manifest.srcFile 'AndroidManifest.xml'
+        //jniLibs.srcDir '../../../lib/android/' //set libs as .so's location instead of jniLibs
+        jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk
+    }
+    // call regular ndk-build(.cmd) script from app directory
+    task ndkBuild(type: Exec) {
+        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
+            commandLine 'ndk-build.cmd'
+        } else {
+            commandLine 'ndk-build'
+        }
+    }
+    tasks.withType(JavaCompile) {
+        compileTask -> compileTask.dependsOn ndkBuild
+    }
+}
+
+dependencies {
+}

+ 9 - 0
build/android/Polycode2DPhysics/jni/Android.mk

@@ -0,0 +1,9 @@
+LOCAL_PATH := $(call my-dir)
+SRCDIR := ../../../../src
+LIBDIR := ../../../../lib/linux/android
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Polycode2DPhysics
+LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../include
+LOCAL_SRC_FILES := $(SRCDIR)/modules/physics2D/PolyPhysicsScreen.cpp $(SRCDIR)/modules/physics2D/PolyPhysicsScreenEntity.cpp
+include $(BUILD_STATIC_LIBRARY)

+ 5 - 0
build/android/Polycode2DPhysics/jni/Application.mk

@@ -0,0 +1,5 @@
+APP_PLATFORM := android-21
+APP_ABI := armeabi x86
+APP_STL := gnustl_static
+APP_CPPFLAGS += -std=c++11
+APP_OPTIM := release

+ 17 - 0
build/android/Polycode2DPhysics/proguard-rules.pro

@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /home/joachim/Android/Sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}

+ 1 - 0
build/android/Polycode3DPhysics/.gitignore

@@ -0,0 +1 @@
+/build

+ 31 - 0
build/android/Polycode3DPhysics/AndroidManifest.xml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- BEGIN_INCLUDE(manifest) -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.example.native_activity"
+        android:versionCode="1"
+        android:versionName="1.0">
+
+    <uses-sdk android:minSdkVersion="21" />
+
+    <!-- This .apk has no Java code itself, so set hasCode to false. -->
+    <application android:label="Polycore" android:hasCode="false">
+
+        <!-- Our activity is the built-in NativeActivity framework class.
+             This will take care of integrating with our NDK code. -->
+        <activity android:name="android.app.NativeActivity"
+                android:label="Polycode3DPhysics"
+                android:configChanges="orientation|keyboardHidden">
+            <!-- Tell NativeActivity the name of or .so -->
+            <meta-data android:name="android.app.lib_name"
+                    android:value="native-activity" />
+            <meta-data android:name="android.app.func_name"
+                    android:value="main" />
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest> 
+<!-- END_INCLUDE(manifest) -->

+ 41 - 0
build/android/Polycode3DPhysics/build.gradle

@@ -0,0 +1,41 @@
+import org.apache.tools.ant.taskdefs.condition.Os
+
+apply plugin: 'com.android.application'
+
+android {
+    compileSdkVersion 23
+    buildToolsVersion "23.0.2"
+
+    defaultConfig {
+    applicationId "org.polycode.polycode3dphysics"
+        minSdkVersion 21
+        targetSdkVersion 23
+        versionCode 1
+        versionName "1.0"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+    sourceSets.main {
+        manifest.srcFile 'AndroidManifest.xml'
+        //jniLibs.srcDir '../../../lib/android/' //set libs as .so's location instead of jniLibs
+        jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk
+    }
+    // call regular ndk-build(.cmd) script from app directory
+    task ndkBuild(type: Exec) {
+        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
+            commandLine 'ndk-build.cmd'
+        } else {
+            commandLine 'ndk-build'
+        }
+    }
+    tasks.withType(JavaCompile) {
+        compileTask -> compileTask.dependsOn ndkBuild
+    }
+}
+
+dependencies {
+}

+ 9 - 0
build/android/Polycode3DPhysics/jni/Android.mk

@@ -0,0 +1,9 @@
+LOCAL_PATH := $(call my-dir)
+SRCDIR := ../../../../src
+LIBDIR := ../../../../lib/linux/android
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Polycode3DPhysics
+LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../include
+LOCAL_SRC_FILES := $(SRCDIR)/modules/physics3D/PolyPhysicsConstraint.cpp $(SRCDIR)/modules/physics3D/PolyPhysicsSceneEntity.cpp $(SRCDIR)/modules/physics3D/PolyPhysicsScene.cpp $(SRCDIR)/modules/physics3D/PolyCollisionSceneEntity.cpp $(SRCDIR)/modules/physics3D/PolyCollisionScene.cpp
+include $(BUILD_STATIC_LIBRARY)

+ 5 - 0
build/android/Polycode3DPhysics/jni/Application.mk

@@ -0,0 +1,5 @@
+APP_PLATFORM := android-21
+APP_ABI := armeabi x86
+APP_STL := gnustl_static
+APP_CPPFLAGS += -std=c++11
+APP_OPTIM := release

+ 17 - 0
build/android/Polycode3DPhysics/proguard-rules.pro

@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /home/joachim/Android/Sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}

+ 1 - 0
build/android/PolycodeUI/.gitignore

@@ -0,0 +1 @@
+/build

+ 31 - 0
build/android/PolycodeUI/AndroidManifest.xml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- BEGIN_INCLUDE(manifest) -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.example.native_activity"
+        android:versionCode="1"
+        android:versionName="1.0">
+
+    <uses-sdk android:minSdkVersion="21" />
+
+    <!-- This .apk has no Java code itself, so set hasCode to false. -->
+    <application android:label="Polycore" android:hasCode="false">
+
+        <!-- Our activity is the built-in NativeActivity framework class.
+             This will take care of integrating with our NDK code. -->
+        <activity android:name="android.app.NativeActivity"
+                android:label="PolycodeUI"
+                android:configChanges="orientation|keyboardHidden">
+            <!-- Tell NativeActivity the name of or .so -->
+            <meta-data android:name="android.app.lib_name"
+                    android:value="native-activity" />
+            <meta-data android:name="android.app.func_name"
+                    android:value="main" />
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest> 
+<!-- END_INCLUDE(manifest) -->

+ 41 - 0
build/android/PolycodeUI/build.gradle

@@ -0,0 +1,41 @@
+import org.apache.tools.ant.taskdefs.condition.Os
+
+apply plugin: 'com.android.application'
+
+android {
+    compileSdkVersion 23
+    buildToolsVersion "23.0.2"
+
+    defaultConfig {
+    applicationId "org.polycode.polycodeui"
+        minSdkVersion 21
+        targetSdkVersion 23
+        versionCode 1
+        versionName "1.0"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+    sourceSets.main {
+        manifest.srcFile 'AndroidManifest.xml'
+        //jniLibs.srcDir '../../../lib/android/' //set libs as .so's location instead of jniLibs
+        jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk
+    }
+    // call regular ndk-build(.cmd) script from app directory
+    task ndkBuild(type: Exec) {
+        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
+            commandLine 'ndk-build.cmd'
+        } else {
+            commandLine 'ndk-build'
+        }
+    }
+    tasks.withType(JavaCompile) {
+        compileTask -> compileTask.dependsOn ndkBuild
+    }
+}
+
+dependencies {
+}

+ 9 - 0
build/android/PolycodeUI/jni/Android.mk

@@ -0,0 +1,9 @@
+LOCAL_PATH := $(call my-dir)
+SRCDIR := ../../../../src
+LIBDIR := ../../../../lib/linux/android
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := PolycodeUI
+LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../include
+LOCAL_SRC_FILES := $(SRCDIR)/modules/ui/PolyUIBox.cpp $(SRCDIR)/modules/ui/PolyUIButton.cpp $(SRCDIR)/modules/ui/PolyUICheckBox.cpp $(SRCDIR)/modules/ui/PolyUIColorBox.cpp $(SRCDIR)/modules/ui/PolyUIComboBox.cpp $(SRCDIR)/modules/ui/PolyUIElement.cpp $(SRCDIR)/modules/ui/PolyUIEvent.cpp $(SRCDIR)/modules/ui/PolyUIFileDialog.cpp $(SRCDIR)/modules/ui/PolyUIHScrollBar.cpp $(SRCDIR)/modules/ui/PolyUIHSizer.cpp $(SRCDIR)/modules/ui/PolyUIHSlider.cpp $(SRCDIR)/modules/ui/PolyUIIconSelector.cpp $(SRCDIR)/modules/ui/PolyUIImageButton.cpp $(SRCDIR)/modules/ui/PolyUIMenu.cpp $(SRCDIR)/modules/ui/PolyUIMenuBar.cpp $(SRCDIR)/modules/ui/PolyUIScrollContainer.cpp $(SRCDIR)/modules/ui/PolyUITextInput.cpp $(SRCDIR)/modules/ui/PolyUITree.cpp $(SRCDIR)/modules/ui/PolyUITreeContainer.cpp $(SRCDIR)/modules/ui/PolyUITreeEvent.cpp $(SRCDIR)/modules/ui/PolyUIVScrollBar.cpp $(SRCDIR)/modules/ui/PolyUIVSizer.cpp $(SRCDIR)/modules/ui/PolyUIWindow.cpp
+include $(BUILD_STATIC_LIBRARY)

+ 5 - 0
build/android/PolycodeUI/jni/Application.mk

@@ -0,0 +1,5 @@
+APP_PLATFORM := android-21
+APP_ABI := armeabi x86
+APP_STL := gnustl_static
+APP_CPPFLAGS += -std=c++11
+APP_OPTIM := release

+ 17 - 0
build/android/PolycodeUI/proguard-rules.pro

@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /home/joachim/Android/Sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}

+ 1 - 0
build/android/Polycore/.gitignore

@@ -0,0 +1 @@
+/build

+ 31 - 0
build/android/Polycore/AndroidManifest.xml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- BEGIN_INCLUDE(manifest) -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.example.native_activity"
+        android:versionCode="1"
+        android:versionName="1.0">
+
+    <uses-sdk android:minSdkVersion="21" />
+
+    <!-- This .apk has no Java code itself, so set hasCode to false. -->
+    <application android:label="Polycore" android:hasCode="false">
+
+        <!-- Our activity is the built-in NativeActivity framework class.
+             This will take care of integrating with our NDK code. -->
+        <activity android:name="android.app.NativeActivity"
+                android:label="Polycore"
+                android:configChanges="orientation|keyboardHidden">
+            <!-- Tell NativeActivity the name of or .so -->
+            <meta-data android:name="android.app.lib_name"
+                    android:value="native-activity" />
+            <meta-data android:name="android.app.func_name"
+                    android:value="main" />
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest> 
+<!-- END_INCLUDE(manifest) -->

+ 45 - 0
build/android/Polycore/build.gradle

@@ -0,0 +1,45 @@
+import org.apache.tools.ant.taskdefs.condition.Os
+apply plugin: 'com.android.application'
+
+android {
+    compileSdkVersion 23
+    buildToolsVersion "23.0.2"
+    defaultConfig {
+        applicationId "org.polycode.polycore"
+        minSdkVersion 21
+        targetSdkVersion 23
+        versionCode 1
+        versionName "1.0"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+        debug {
+            debuggable true
+            jniDebuggable true
+        }
+    }
+    sourceSets.main {
+        manifest.srcFile 'AndroidManifest.xml'
+        //jniLibs.srcDir '../../../lib/android/' //set libs as .so's location instead of jniLibs
+        jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk
+    }
+    // call regular ndk-build(.cmd) script from app directory
+    task ndkBuild(type: Exec) {
+        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
+            commandLine 'ndk-build.cmd'
+        } else {
+            commandLine 'ndk-build'
+        }
+    }
+    tasks.withType(JavaCompile) {
+        compileTask -> compileTask.dependsOn ndkBuild
+    }
+    productFlavors {
+    }
+}
+
+dependencies {
+}

Разница между файлами не показана из-за своего большого размера
+ 7 - 0
build/android/Polycore/jni/Android.mk


+ 5 - 0
build/android/Polycore/jni/Application.mk

@@ -0,0 +1,5 @@
+APP_PLATFORM := android-21
+APP_ABI := armeabi x86
+APP_STL := gnustl_static
+APP_CPPFLAGS += -std=c++11
+APP_OPTIM := release

+ 17 - 0
build/android/Polycore/proguard-rules.pro

@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /home/joachim/Android/Sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}

+ 2 - 0
build/android/TemplateApp/.gitignore

@@ -0,0 +1,2 @@
+/build
+default

+ 27 - 0
build/android/TemplateApp/AndroidManifest.xml

@@ -0,0 +1,27 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="org.polycode.templateapp">
+
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.WAKE_LOCK" />
+
+    <application android:label="TemplateApp">
+        <activity
+            android:name="org.polycode.templateapp.PolycodeActivity"
+            android:configChanges="keyboardHidden|keyboard"
+            android:screenOrientation="landscape"
+            android:label="TemplateApp">
+
+            <!-- Tell NativeActivity the name of our .so -->
+            <meta-data
+                android:name="android.app.lib_name"
+                android:value="TemplateApp" />
+
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest> <!-- END_INCLUDE(manifest) -->

+ 50 - 0
build/android/TemplateApp/build.gradle

@@ -0,0 +1,50 @@
+import org.apache.tools.ant.taskdefs.condition.Os
+
+apply plugin: 'com.android.application'
+
+android {
+    compileSdkVersion 23
+    buildToolsVersion '23.0.2'
+    defaultConfig {
+        applicationId "org.polycode.templateapp"
+        minSdkVersion 21
+        targetSdkVersion 23
+        versionCode 1
+        versionName "1.0"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+        debug {
+            debuggable true
+            jniDebuggable false
+        }
+    }
+    sourceSets.main {
+        manifest.srcFile 'AndroidManifest.xml'
+        jniLibs.srcDir 'libs' //set libs as .so's location instead of jniLibs
+        jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk
+    }
+    // call regular ndk-build(.cmd) script from app directory
+    task ndkBuild(type: Exec) {
+        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
+            commandLine 'ndk-build.cmd'
+        } else {
+            commandLine 'ndk-build'
+        }
+    }
+    task copyAssets(type: Copy) {
+        from '../../../assets/default_mobile/default.pak'
+        into 'src/main/assets/extract/'
+    }
+    tasks.withType(JavaCompile) {
+        compileTask -> compileTask.dependsOn ndkBuild, copyAssets
+    }
+    productFlavors {
+    }
+}
+
+dependencies {
+}

+ 82 - 0
build/android/TemplateApp/jni/Android.mk

@@ -0,0 +1,82 @@
+LOCAL_PATH := $(call my-dir)
+SRCDIR := ../../../../src
+LIBDIR := ../../../../lib/android/$(TARGET_ARCH_ABI)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Polycore
+LOCAL_SRC_FILES := ../../Polycore/obj/local/$(TARGET_ARCH_ABI)/libPolycore.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := PolycodeUI
+LOCAL_SRC_FILES := ../../PolycodeUI/obj/local/$(TARGET_ARCH_ABI)/libPolycodeUI.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Polycode2DPhysics
+LOCAL_SRC_FILES := ../../Polycode2DPhysics/obj/local/$(TARGET_ARCH_ABI)/libPolycode2DPhysics.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Polycode3DPhysics
+LOCAL_SRC_FILES := ../../Polycode3DPhysics/obj/local/$(TARGET_ARCH_ABI)/libPolycode3DPhysics.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := freetype
+LOCAL_SRC_FILES := $(LIBDIR)/libfreetype.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := lua
+LOCAL_SRC_FILES := $(LIBDIR)/liblua.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := physfs
+LOCAL_SRC_FILES := $(LIBDIR)/libphysfs.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := BulletDynamics
+LOCAL_SRC_FILES := $(LIBDIR)/libBulletDynamics.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := BulletCollision
+LOCAL_SRC_FILES := $(LIBDIR)/libBulletCollision.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := LinearMath
+LOCAL_SRC_FILES := $(LIBDIR)/libLinearMath.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := BulletSoftBody
+LOCAL_SRC_FILES := $(LIBDIR)/libBulletSoftBody.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := box2d
+LOCAL_SRC_FILES := $(LIBDIR)/libbox2d.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := ogg
+LOCAL_SRC_FILES := $(LIBDIR)/libogg.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := vorbis
+LOCAL_SRC_FILES := $(LIBDIR)/libvorbis.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := TemplateApp
+LOCAL_LDLIBS := -landroid -lEGL -lGLESv2 -lOpenSLES -lz -llog
+LOCAL_STATIC_LIBRARIES := Polycore PolycodeUI Polycode3DPhysics freetype lua physfs box2d BulletDynamics BulletCollision BulletSoftBody LinearMath
+LOCAL_SHARED_LIBRARIES := ogg vorbis
+LOCAL_CFLAGS += -I$(LOCAL_PATH)/../../../../include -DUSE_EGL -DSTRICT_OPENGLES2
+LOCAL_SRC_FILES := PolycodeTemplate.cpp PolycodeTemplateApp.cpp
+include $(BUILD_SHARED_LIBRARY)

+ 5 - 0
build/android/TemplateApp/jni/Application.mk

@@ -0,0 +1,5 @@
+APP_PLATFORM := android-21
+APP_ABI := armeabi x86
+APP_STL := gnustl_static
+APP_CPPFLAGS += -std=c++11
+APP_OPTIM := release

+ 19 - 0
build/android/TemplateApp/jni/PolycodeTemplate.cpp

@@ -0,0 +1,19 @@
+#include "PolycodeTemplateApp.h"
+#include "polycode/view/android/PolycodeView.h"
+//#include <android_native_app_glue.h>
+
+void android_main(struct startHelper* helper){
+	LOGI("Starting");
+	PolycodeView *view = new PolycodeView(helper->activity, "TemplateApp");
+
+	PolycodeTemplateApp *app = new PolycodeTemplateApp(view);
+
+	pthread_mutex_lock(&helper->mutex);
+    helper->running = 1;
+    pthread_cond_broadcast(&helper->cond);
+    pthread_mutex_unlock(&helper->mutex);
+
+	while(app->Update()) {
+	}
+	return;
+}

+ 153 - 0
build/android/TemplateApp/jni/PolycodeTemplateApp.cpp

@@ -0,0 +1,153 @@
+//
+// Polycode template. Write your code here.
+// 
+
+#include "PolycodeTemplateApp.h"
+#include "polycode/view/android/PolycodeView.h"
+
+
+PolycodeTemplateApp::PolycodeTemplateApp(PolycodeView *view) {
+    core = new POLYCODE_CORE(view, 800,480,false,false, 0,0,60, -1, true);
+
+    core->addFileSource("archive", "default.pak");
+    core->addFileSource("folder", core->getDefaultWorkingDirectory());
+    ResourcePool *globalPool = Services()->getResourceManager()->getGlobalPool();
+    globalPool->loadResourcesFromFolder("default", true);
+
+    CoreServices::getInstance()->getConfig()->loadConfig("Polycode", "UIThemes/dark_retina/theme.xml");
+
+	// Write your code here!
+    srand(time(NULL));
+    scene = new Scene(Scene::SCENE_2D);
+    scene->useClearColor = true;
+    scene->clearColor.setColor(1.0f / (float)(rand() % 5),1.0f / (float)(rand()%5),1.0f / (float)(rand() % 5),1.0f);
+
+    test = new ScenePrimitive(ScenePrimitive::TYPE_VPLANE, 0.5, 0.5);
+    test->setPositionY(0.2);
+    test->setMaterialByName("Unlit");
+    test->getShaderPass(0).shaderBinding->loadTextureForParam("diffuse", "main_icon.png");
+
+    SceneLabel *testLabel = new SceneLabel("Hello Polycode!", 32, "sans", Label::ANTIALIAS_FULL, 0.2);
+	testLabel->setPositionY(-0.2);
+    scene->addChild(testLabel);
+
+    /*ScenePrimitive* box;
+    for(int i = 0; i < 1000; i++){
+        box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 0.2, 0.2,0.2);
+        box->setMaterialByName("UnlitUntextured");
+        //box->setColor(1.0, 0.0,0.0, 1.0);
+        //box->getShaderPass(0).shaderBinding->loadTextureForParam("diffuse", "default/default.png");
+        scene->addChild(box);
+    }*/
+
+    bgSound = new Sound("FightBG.wav");
+//    bgSound->Play();
+
+//    sound1 = new Sound("hit.wav");
+    //Logger::log("before Play");
+    //sound1->Play(true);
+    //Logger::log("after Play");
+    //sound1->setPitch(10);
+
+//    sound2 = new Sound("test.wav");
+//     sound3 = new Sound("curve_02_c.wav");
+
+    //sound2->Play(true);
+
+    running = 0;
+    rot = Vector3();
+    fps = new SceneLabel("0", 32, "sans", Label::ANTIALIAS_FULL, 0.1);
+    fps->setPosition(-0.6,0.3);
+    scene->addChild(fps);
+    scene->addChild(test);
+
+    /*game = new Scene(Scene::SCENE_2D_TOPLEFT);
+    //game->useClearColor = true;
+    //game->getActiveCamera()->setPosition(0, 0, 10);
+
+    /*box = new ScenePrimitive(ScenePrimitive::TYPE_BOX, 2, 2, 2);
+    box->setMaterialByName("UnlitUntextured");
+    box->setColor(0.1, 1.0, 1.0, 1.0);
+    game->addChild(box);
+
+    UILabel *uiLabel = new UILabel("Text");
+    game->addChild(uiLabel);
+
+    btn = new UIButton("Press me!", 80);
+    btn->setPosition(5, 70);
+    game->addChild(btn);
+    btn->addEventListener(this, UIEvent::CLICK_EVENT);
+
+    Services()->getInput()->simulateMouseWithTouch = true;
+
+    game->rootEntity.processInputEvents = true;*/
+
+    Services()->getInput()->addEventListener(this, InputEvent::EVENT_KEYDOWN);
+    Services()->getInput()->addEventListener(this, InputEvent::EVENT_TOUCHES_BEGAN);
+    Services()->getInput()->addEventListener(this, InputEvent::EVENT_TOUCHES_ENDED);
+    Services()->getInput()->addEventListener(this, InputEvent::EVENT_TOUCHES_MOVED);
+    Services()->getCore()->addEventListener(this, Core::EVENT_ACCELEROMETER_MOTION);
+    Services()->getCore()->addEventListener(this, Core::EVENT_GYRO_ROTATION);
+}
+
+void PolycodeTemplateApp::handleEvent(Event *event) {
+    if(event->getEventType()=="InputEvent"){
+        InputEvent *inputEvent = (InputEvent*) event;
+        if(inputEvent->getEventCode() == InputEvent::EVENT_KEYDOWN){
+        //Logger::log("keyevent %d", inputEvent->getKey());
+        switch(inputEvent->getKey()) {
+            case KEY_ESCAPE:
+                core->openOnScreenKeyboard(false);
+                break;
+            case KEY_z:
+                //sound1->Play(true);
+            break;
+            case KEY_x:
+                //sound2->Play();
+            break;
+            case KEY_c:
+                //sound3->Play();
+            break;
+            }
+        } else if (inputEvent->getEventCode() == InputEvent::EVENT_TOUCHES_BEGAN){
+            Ray r = scene->projectRayFromCameraAndViewportCoordinate(scene->getActiveCamera(),inputEvent->touch.position);
+            test->setPosition(r.origin.x, r.origin.y);
+        } else if(inputEvent->getEventCode() == InputEvent::EVENT_TOUCHES_ENDED){
+            Ray r = scene->projectRayFromCameraAndViewportCoordinate(scene->getActiveCamera(),inputEvent->touch.position);
+            test->setPosition(r.origin.x, r.origin.y);
+        } else if(inputEvent->getEventCode() == InputEvent::EVENT_TOUCHES_MOVED){
+            Ray r = scene->projectRayFromCameraAndViewportCoordinate(scene->getActiveCamera(),inputEvent->touch.position);
+            test->setPosition(r.origin.x, r.origin.y);
+        }
+    } else if(event->getEventType() == "CoreMotionEvent"){
+        CoreMotionEvent* motionEvent = (CoreMotionEvent*)event;
+        if(motionEvent->getEventCode() == Core::EVENT_ACCELEROMETER_MOTION){
+        } else if (motionEvent->getEventCode() == Core::EVENT_GYRO_ROTATION){
+            test->Translate(motionEvent->amount.x*0.01, motionEvent->amount.y*0.01);
+        }
+    } else if(event->getEventType()=="UIEvent"){
+        UIEvent* uiEvent = (UIEvent*)event;
+        if(uiEvent->getDispatcher() == btn){
+        Logger::log("hit");
+            core->openOnScreenKeyboard(true);
+        }
+    }
+}
+
+PolycodeTemplateApp::~PolycodeTemplateApp() {
+    
+}
+
+bool PolycodeTemplateApp::Update() {
+    if (!core->paused) {
+        running += core->getElapsed();
+        if(running >= 1){
+            fps->setText(String::NumberToString(core->getFPS(),0));
+            running = 0;
+        }
+        return core->updateAndRender();
+    } else {
+        usleep(200000);
+        return true;
+    }
+}

+ 39 - 0
build/android/TemplateApp/jni/PolycodeTemplateApp.h

@@ -0,0 +1,39 @@
+//
+// Polycode template. Write your code here.
+//
+
+#include "Polycode.h"
+#include "polycode/modules/ui/PolycodeUI.h"
+#include "polycode/modules/physics3D/Polycode3DPhysics.h"
+
+using namespace Polycode;
+
+class PolycodeTemplateApp : public EventHandler {
+public:
+    PolycodeTemplateApp(PolycodeView *view);
+    ~PolycodeTemplateApp();
+    
+    void handleEvent(Event *event);
+    
+    bool Update();
+    
+private:
+    
+    Sound *bgSound;
+    
+    Sound *sound1;
+    Sound *sound2;
+    Sound *sound3;
+
+    ScenePrimitive *test;
+    Scene *scene;
+
+    Core *core;
+    Vector3 rot;
+    Number running;
+    SceneLabel* fps;
+
+    Scene* game;
+    ScenePrimitive* box;
+    UIButton* btn;
+};

+ 17 - 0
build/android/TemplateApp/proguard-rules.pro

@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /home/joachim/Android/Sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}

BIN
build/android/TemplateApp/src/main/assets/main_icon.png


+ 13 - 0
build/android/TemplateApp/src/main/java/org/polycode/templateapp/PolycodeActivity.java

@@ -0,0 +1,13 @@
+package org.polycode.templateapp;
+
+import android.app.NativeActivity;
+
+/**
+ * Created by joachim on 29.02.16.
+ */
+public class PolycodeActivity extends NativeActivity {
+    static {
+        System.loadLibrary("ogg");
+        System.loadLibrary("vorbis");
+    }
+}

+ 23 - 0
build/android/build.gradle

@@ -0,0 +1,23 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+    repositories {
+        jcenter()
+    }
+    dependencies {
+        classpath 'com.android.tools.build:gradle:2.1.0'
+
+        // NOTE: Do not place your application dependencies here; they belong
+        // in the individual module build.gradle files
+    }
+}
+
+allprojects {
+    repositories {
+        jcenter()
+    }
+}
+
+task clean(type: Delete) {
+    delete rootProject.buildDir
+}

+ 18 - 0
build/android/gradle.properties

@@ -0,0 +1,18 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+# Default value: -Xmx10248m -XX:MaxPermSize=256m
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true

BIN
build/android/gradle/wrapper/gradle-wrapper.jar


+ 6 - 0
build/android/gradle/wrapper/gradle-wrapper.properties

@@ -0,0 +1,6 @@
+#Wed Mar 09 15:35:15 CET 2016
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

+ 160 - 0
build/android/gradlew

@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+    JAVACMD=`cygpath --unix "$JAVACMD"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

+ 90 - 0
build/android/gradlew.bat

@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem  Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega

+ 1 - 0
build/android/settings.gradle

@@ -0,0 +1 @@
+include ':Polycore', ':TemplateApp', ':PolycodeUI', ':Polycode2DPhysics', ':Polycode3DPhysics'

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
build/linux/Makefile


+ 13 - 14
build/linux/TemplateApp/PolycodeTemplateApp.cpp

@@ -27,39 +27,38 @@ PolycodeTemplateApp::PolycodeTemplateApp(PolycodeView *view) {
 	testLabel->setPositionY(-0.2);
     scene->addChild(testLabel);
     
-/*
-    bgSound = new Sound("bedlayer_main.wav");
+    bgSound = new Sound("FightBG.WAV");
     bgSound->Play();
 //    bgSound->setPitch(10.0);
     
     
-    sound1 = new Sound("marimba-lo.wav");
+    sound1 = new Sound("hit.wav");
     
     sound1->setPitch(2.3);
     
-    sound2 = new Sound("initial_touch_01.wav");
-    sound3 = new Sound("curve_02_c.wav");
+    sound2 = new Sound("test.wav");
+//     sound3 = new Sound("curve_02_c.wav");
     
     //sound2->Play(true);
-  */
+ 
     Services()->getInput()->addEventListener(this, InputEvent::EVENT_KEYDOWN);
 }
 
 void PolycodeTemplateApp::handleEvent(Event *event) {
     InputEvent *inputEvent = (InputEvent*) event;
     
-//     switch(inputEvent->getKey()) {
-//         case KEY_z:
-//             sound1->Play(true);
-//         break;
-//         case KEY_x:
-//             sound2->Play();
-//         break;
+    switch(inputEvent->getKey()) {
+        case KEY_z:
+            sound1->Play(true);
+        break;
+        case KEY_x:
+            sound2->Play();
+        break;
 //         case KEY_c:
 //             sound3->Play();
 //         break;
 //             
-//     }
+    }
 }
 
 PolycodeTemplateApp::~PolycodeTemplateApp() {

+ 62 - 0
include/Box2D/Box2D.h

@@ -0,0 +1,62 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef BOX2D_H
+#define BOX2D_H
+
+/**
+\mainpage Box2D API Documentation
+
+\section intro_sec Getting Started
+
+For documentation please see http://box2d.org/documentation.html
+
+For discussion please visit http://box2d.org/forum
+*/
+
+// These include files constitute the main Box2D API
+
+#include <Box2D/Common/b2Settings.h>
+
+#include <Box2D/Collision/Shapes/b2CircleShape.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+
+#include <Box2D/Collision/b2BroadPhase.h>
+#include <Box2D/Collision/b2Distance.h>
+#include <Box2D/Collision/b2DynamicTree.h>
+#include <Box2D/Collision/b2TimeOfImpact.h>
+
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2WorldCallbacks.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+#include <Box2D/Dynamics/b2World.h>
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
+#include <Box2D/Dynamics/Joints/b2FrictionJoint.h>
+#include <Box2D/Dynamics/Joints/b2GearJoint.h>
+#include <Box2D/Dynamics/Joints/b2LineJoint.h>
+#include <Box2D/Dynamics/Joints/b2MouseJoint.h>
+#include <Box2D/Dynamics/Joints/b2PrismaticJoint.h>
+#include <Box2D/Dynamics/Joints/b2PulleyJoint.h>
+#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
+#include <Box2D/Dynamics/Joints/b2WeldJoint.h>
+
+#endif

+ 87 - 0
include/Box2D/Collision/Shapes/b2CircleShape.h

@@ -0,0 +1,87 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CIRCLE_SHAPE_H
+#define B2_CIRCLE_SHAPE_H
+
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+/// A circle shape.
+class b2CircleShape : public b2Shape
+{
+public:
+	b2CircleShape();
+
+	/// Implement b2Shape.
+	b2Shape* Clone(b2BlockAllocator* allocator) const;
+
+	/// Implement b2Shape.
+	bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
+
+	/// Implement b2Shape.
+	bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const;
+
+	/// @see b2Shape::ComputeAABB
+	void ComputeAABB(b2AABB* aabb, const b2Transform& transform) const;
+
+	/// @see b2Shape::ComputeMass
+	void ComputeMass(b2MassData* massData, float32 density) const;
+
+	/// Get the supporting vertex index in the given direction.
+	int32 GetSupport(const b2Vec2& d) const;
+
+	/// Get the supporting vertex in the given direction.
+	const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
+
+	/// Get the vertex count.
+	int32 GetVertexCount() const { return 1; }
+
+	/// Get a vertex by index. Used by b2Distance.
+	const b2Vec2& GetVertex(int32 index) const;
+
+	/// Position
+	b2Vec2 m_p;
+};
+
+inline b2CircleShape::b2CircleShape()
+{
+	m_type = e_circle;
+	m_radius = 0.0f;
+	m_p.SetZero();
+}
+
+inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const
+{
+	B2_NOT_USED(d);
+	return 0;
+}
+
+inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const
+{
+	B2_NOT_USED(d);
+	return m_p;
+}
+
+inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const
+{
+	B2_NOT_USED(index);
+	b2Assert(index == 0);
+	return m_p;
+}
+
+#endif

+ 131 - 0
include/Box2D/Collision/Shapes/b2PolygonShape.h

@@ -0,0 +1,131 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_POLYGON_SHAPE_H
+#define B2_POLYGON_SHAPE_H
+
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+/// A convex polygon. It is assumed that the interior of the polygon is to
+/// the left of each edge.
+class b2PolygonShape : public b2Shape
+{
+public:
+	b2PolygonShape();
+
+	/// Implement b2Shape.
+	b2Shape* Clone(b2BlockAllocator* allocator) const;
+
+	/// Copy vertices. This assumes the vertices define a convex polygon.
+	/// It is assumed that the exterior is the the right of each edge.
+	void Set(const b2Vec2* vertices, int32 vertexCount);
+
+	/// Build vertices to represent an axis-aligned box.
+	/// @param hx the half-width.
+	/// @param hy the half-height.
+	void SetAsBox(float32 hx, float32 hy);
+
+	/// Build vertices to represent an oriented box.
+	/// @param hx the half-width.
+	/// @param hy the half-height.
+	/// @param center the center of the box in local coordinates.
+	/// @param angle the rotation of the box in local coordinates.
+	void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle);
+
+	/// Set this as a single edge.
+	void SetAsEdge(const b2Vec2& v1, const b2Vec2& v2);
+
+	/// @see b2Shape::TestPoint
+	bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
+
+	/// Implement b2Shape.
+	bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const;
+
+	/// @see b2Shape::ComputeAABB
+	void ComputeAABB(b2AABB* aabb, const b2Transform& transform) const;
+
+	/// @see b2Shape::ComputeMass
+	void ComputeMass(b2MassData* massData, float32 density) const;
+
+	/// Get the supporting vertex index in the given direction.
+	int32 GetSupport(const b2Vec2& d) const;
+
+	/// Get the supporting vertex in the given direction.
+	const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
+
+	/// Get the vertex count.
+	int32 GetVertexCount() const { return m_vertexCount; }
+
+	/// Get a vertex by index.
+	const b2Vec2& GetVertex(int32 index) const;
+
+	b2Vec2 m_centroid;
+	b2Vec2 m_vertices[b2_maxPolygonVertices];
+	b2Vec2 m_normals[b2_maxPolygonVertices];
+	int32 m_vertexCount;
+};
+
+inline b2PolygonShape::b2PolygonShape()
+{
+	m_type = e_polygon;
+	m_radius = b2_polygonRadius;
+	m_vertexCount = 0;
+	m_centroid.SetZero();
+}
+
+inline int32 b2PolygonShape::GetSupport(const b2Vec2& d) const
+{
+	int32 bestIndex = 0;
+	float32 bestValue = b2Dot(m_vertices[0], d);
+	for (int32 i = 1; i < m_vertexCount; ++i)
+	{
+		float32 value = b2Dot(m_vertices[i], d);
+		if (value > bestValue)
+		{
+			bestIndex = i;
+			bestValue = value;
+		}
+	}
+
+	return bestIndex;
+}
+
+inline const b2Vec2& b2PolygonShape::GetSupportVertex(const b2Vec2& d) const
+{
+	int32 bestIndex = 0;
+	float32 bestValue = b2Dot(m_vertices[0], d);
+	for (int32 i = 1; i < m_vertexCount; ++i)
+	{
+		float32 value = b2Dot(m_vertices[i], d);
+		if (value > bestValue)
+		{
+			bestIndex = i;
+			bestValue = value;
+		}
+	}
+
+	return m_vertices[bestIndex];
+}
+
+inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const
+{
+	b2Assert(0 <= index && index < m_vertexCount);
+	return m_vertices[index];
+}
+
+#endif

+ 95 - 0
include/Box2D/Collision/Shapes/b2Shape.h

@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_SHAPE_H
+#define B2_SHAPE_H
+
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Collision.h>
+
+/// This holds the mass data computed for a shape.
+struct b2MassData
+{
+	/// The mass of the shape, usually in kilograms.
+	float32 mass;
+
+	/// The position of the shape's centroid relative to the shape's origin.
+	b2Vec2 center;
+
+	/// The rotational inertia of the shape about the local origin.
+	float32 I;
+};
+
+/// A shape is used for collision detection. You can create a shape however you like.
+/// Shapes used for simulation in b2World are created automatically when a b2Fixture
+/// is created.
+class b2Shape
+{
+public:
+	
+	enum Type
+	{
+		e_unknown= -1,
+		e_circle = 0,
+		e_polygon = 1,
+		e_typeCount = 2,
+	};
+
+	b2Shape() { m_type = e_unknown; }
+	virtual ~b2Shape() {}
+
+	/// Clone the concrete shape using the provided allocator.
+	virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0;
+
+	/// Get the type of this shape. You can use this to down cast to the concrete shape.
+	/// @return the shape type.
+	Type GetType() const;
+
+	/// Test a point for containment in this shape. This only works for convex shapes.
+	/// @param xf the shape world transform.
+	/// @param p a point in world coordinates.
+	virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0;
+
+	/// Cast a ray against this shape.
+	/// @param output the ray-cast results.
+	/// @param input the ray-cast input parameters.
+	/// @param transform the transform to be applied to the shape.
+	virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const = 0;
+
+	/// Given a transform, compute the associated axis aligned bounding box for this shape.
+	/// @param aabb returns the axis aligned box.
+	/// @param xf the world transform of the shape.
+	virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf) const = 0;
+
+	/// Compute the mass properties of this shape using its dimensions and density.
+	/// The inertia tensor is computed about the local origin.
+	/// @param massData returns the mass data for this shape.
+	/// @param density the density in kilograms per meter squared.
+	virtual void ComputeMass(b2MassData* massData, float32 density) const = 0;
+
+	Type m_type;
+	float32 m_radius;
+};
+
+inline b2Shape::Type b2Shape::GetType() const
+{
+	return m_type;
+}
+
+#endif

+ 229 - 0
include/Box2D/Collision/b2BroadPhase.h

@@ -0,0 +1,229 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_BROAD_PHASE_H
+#define B2_BROAD_PHASE_H
+
+#include <Box2D/Common/b2Settings.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/b2DynamicTree.h>
+#include <algorithm>
+
+struct b2Pair
+{
+	int32 proxyIdA;
+	int32 proxyIdB;
+	int32 next;
+};
+
+/// The broad-phase is used for computing pairs and performing volume queries and ray casts.
+/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs.
+/// It is up to the client to consume the new pairs and to track subsequent overlap.
+class b2BroadPhase
+{
+public:
+
+	enum
+	{
+		e_nullProxy = -1,
+	};
+
+	b2BroadPhase();
+	~b2BroadPhase();
+
+	/// Create a proxy with an initial AABB. Pairs are not reported until
+	/// UpdatePairs is called.
+	int32 CreateProxy(const b2AABB& aabb, void* userData);
+
+	/// Destroy a proxy. It is up to the client to remove any pairs.
+	void DestroyProxy(int32 proxyId);
+
+	/// Call MoveProxy as many times as you like, then when you are done
+	/// call UpdatePairs to finalized the proxy pairs (for your time step).
+	void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement);
+
+	/// Get the fat AABB for a proxy.
+	const b2AABB& GetFatAABB(int32 proxyId) const;
+
+	/// Get user data from a proxy. Returns NULL if the id is invalid.
+	void* GetUserData(int32 proxyId) const;
+
+	/// Test overlap of fat AABBs.
+	bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const;
+
+	/// Get the number of proxies.
+	int32 GetProxyCount() const;
+
+	/// Update the pairs. This results in pair callbacks. This can only add pairs.
+	template <typename T>
+	void UpdatePairs(T* callback);
+
+	/// Query an AABB for overlapping proxies. The callback class
+	/// is called for each proxy that overlaps the supplied AABB.
+	template <typename T>
+	void Query(T* callback, const b2AABB& aabb) const;
+
+	/// Ray-cast against the proxies in the tree. This relies on the callback
+	/// to perform a exact ray-cast in the case were the proxy contains a shape.
+	/// The callback also performs the any collision filtering. This has performance
+	/// roughly equal to k * log(n), where k is the number of collisions and n is the
+	/// number of proxies in the tree.
+	/// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
+	/// @param callback a callback class that is called for each proxy that is hit by the ray.
+	template <typename T>
+	void RayCast(T* callback, const b2RayCastInput& input) const;
+
+	/// Compute the height of the embedded tree.
+	int32 ComputeHeight() const;
+
+private:
+
+	friend class b2DynamicTree;
+
+	void BufferMove(int32 proxyId);
+	void UnBufferMove(int32 proxyId);
+
+	bool QueryCallback(int32 proxyId);
+
+	b2DynamicTree m_tree;
+
+	int32 m_proxyCount;
+
+	int32* m_moveBuffer;
+	int32 m_moveCapacity;
+	int32 m_moveCount;
+
+	b2Pair* m_pairBuffer;
+	int32 m_pairCapacity;
+	int32 m_pairCount;
+
+	int32 m_queryProxyId;
+};
+
+/// This is used to sort pairs.
+inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2)
+{
+	if (pair1.proxyIdA < pair2.proxyIdA)
+	{
+		return true;
+	}
+
+	if (pair1.proxyIdA == pair2.proxyIdA)
+	{
+		return pair1.proxyIdB < pair2.proxyIdB;
+	}
+
+	return false;
+}
+
+inline void* b2BroadPhase::GetUserData(int32 proxyId) const
+{
+	return m_tree.GetUserData(proxyId);
+}
+
+inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const
+{
+	const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA);
+	const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB);
+	return b2TestOverlap(aabbA, aabbB);
+}
+
+inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const
+{
+	return m_tree.GetFatAABB(proxyId);
+}
+
+inline int32 b2BroadPhase::GetProxyCount() const
+{
+	return m_proxyCount;
+}
+
+inline int32 b2BroadPhase::ComputeHeight() const
+{
+	return m_tree.ComputeHeight();
+}
+
+template <typename T>
+void b2BroadPhase::UpdatePairs(T* callback)
+{
+	// Reset pair buffer
+	m_pairCount = 0;
+
+	// Perform tree queries for all moving proxies.
+	for (int32 i = 0; i < m_moveCount; ++i)
+	{
+		m_queryProxyId = m_moveBuffer[i];
+		if (m_queryProxyId == e_nullProxy)
+		{
+			continue;
+		}
+
+		// We have to query the tree with the fat AABB so that
+		// we don't fail to create a pair that may touch later.
+		const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId);
+
+		// Query tree, create pairs and add them pair buffer.
+		m_tree.Query(this, fatAABB);
+	}
+
+	// Reset move buffer
+	m_moveCount = 0;
+
+	// Sort the pair buffer to expose duplicates.
+	std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan);
+
+	// Send the pairs back to the client.
+	int32 i = 0;
+	while (i < m_pairCount)
+	{
+		b2Pair* primaryPair = m_pairBuffer + i;
+		void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA);
+		void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB);
+
+		callback->AddPair(userDataA, userDataB);
+		++i;
+
+		// Skip any duplicate pairs.
+		while (i < m_pairCount)
+		{
+			b2Pair* pair = m_pairBuffer + i;
+			if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB)
+			{
+				break;
+			}
+			++i;
+		}
+	}
+
+	// Try to keep the tree balanced.
+	m_tree.Rebalance(4);
+}
+
+template <typename T>
+inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const
+{
+	m_tree.Query(callback, aabb);
+}
+
+template <typename T>
+inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const
+{
+	m_tree.RayCast(callback, input);
+}
+
+#endif

+ 240 - 0
include/Box2D/Collision/b2Collision.h

@@ -0,0 +1,240 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_COLLISION_H
+#define B2_COLLISION_H
+
+#include <Box2D/Common/b2Math.h>
+#include <climits>
+
+/// @file
+/// Structures and functions used for computing contact points, distance
+/// queries, and TOI queries.
+
+class b2Shape;
+class b2CircleShape;
+class b2PolygonShape;
+
+const uint8 b2_nullFeature = UCHAR_MAX;
+
+/// Contact ids to facilitate warm starting.
+union b2ContactID
+{
+	/// The features that intersect to form the contact point
+	struct Features
+	{
+		uint8 referenceEdge;	///< The edge that defines the outward contact normal.
+		uint8 incidentEdge;		///< The edge most anti-parallel to the reference edge.
+		uint8 incidentVertex;	///< The vertex (0 or 1) on the incident edge that was clipped.
+		uint8 flip;				///< A value of 1 indicates that the reference edge is on shape2.
+	} features;
+	uint32 key;					///< Used to quickly compare contact ids.
+};
+
+/// A manifold point is a contact point belonging to a contact
+/// manifold. It holds details related to the geometry and dynamics
+/// of the contact points.
+/// The local point usage depends on the manifold type:
+/// -e_circles: the local center of circleB
+/// -e_faceA: the local center of cirlceB or the clip point of polygonB
+/// -e_faceB: the clip point of polygonA
+/// This structure is stored across time steps, so we keep it small.
+/// Note: the impulses are used for internal caching and may not
+/// provide reliable contact forces, especially for high speed collisions.
+struct b2ManifoldPoint
+{
+	b2Vec2 localPoint;		///< usage depends on manifold type
+	float32 normalImpulse;	///< the non-penetration impulse
+	float32 tangentImpulse;	///< the friction impulse
+	b2ContactID id;			///< uniquely identifies a contact point between two shapes
+};
+
+/// A manifold for two touching convex shapes.
+/// Box2D supports multiple types of contact:
+/// - clip point versus plane with radius
+/// - point versus point with radius (circles)
+/// The local point usage depends on the manifold type:
+/// -e_circles: the local center of circleA
+/// -e_faceA: the center of faceA
+/// -e_faceB: the center of faceB
+/// Similarly the local normal usage:
+/// -e_circles: not used
+/// -e_faceA: the normal on polygonA
+/// -e_faceB: the normal on polygonB
+/// We store contacts in this way so that position correction can
+/// account for movement, which is critical for continuous physics.
+/// All contact scenarios must be expressed in one of these types.
+/// This structure is stored across time steps, so we keep it small.
+struct b2Manifold
+{
+	enum Type
+	{
+		e_circles,
+		e_faceA,
+		e_faceB
+	};
+
+	b2ManifoldPoint points[b2_maxManifoldPoints];	///< the points of contact
+	b2Vec2 localNormal;								///< not use for Type::e_points
+	b2Vec2 localPoint;								///< usage depends on manifold type
+	Type type;
+	int32 pointCount;								///< the number of manifold points
+};
+
+/// This is used to compute the current state of a contact manifold.
+struct b2WorldManifold
+{
+	/// Evaluate the manifold with supplied transforms. This assumes
+	/// modest motion from the original state. This does not change the
+	/// point count, impulses, etc. The radii must come from the shapes
+	/// that generated the manifold.
+	void Initialize(const b2Manifold* manifold,
+					const b2Transform& xfA, float32 radiusA,
+					const b2Transform& xfB, float32 radiusB);
+
+	b2Vec2 normal;						///< world vector pointing from A to B
+	b2Vec2 points[b2_maxManifoldPoints];	///< world contact point (point of intersection)
+};
+
+/// This is used for determining the state of contact points.
+enum b2PointState
+{
+	b2_nullState,		///< point does not exist
+	b2_addState,		///< point was added in the update
+	b2_persistState,	///< point persisted across the update
+	b2_removeState		///< point was removed in the update
+};
+
+/// Compute the point states given two manifolds. The states pertain to the transition from manifold1
+/// to manifold2. So state1 is either persist or remove while state2 is either add or persist.
+void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints],
+					  const b2Manifold* manifold1, const b2Manifold* manifold2);
+
+/// Used for computing contact manifolds.
+struct b2ClipVertex
+{
+	b2Vec2 v;
+	b2ContactID id;
+};
+
+/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
+struct b2RayCastInput
+{
+	b2Vec2 p1, p2;
+	float32 maxFraction;
+};
+
+/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2
+/// come from b2RayCastInput.
+struct b2RayCastOutput
+{
+	b2Vec2 normal;
+	float32 fraction;
+};
+
+/// An axis aligned bounding box.
+struct b2AABB
+{
+	/// Verify that the bounds are sorted.
+	bool IsValid() const;
+
+	/// Get the center of the AABB.
+	b2Vec2 GetCenter() const
+	{
+		return 0.5f * (lowerBound + upperBound);
+	}
+
+	/// Get the extents of the AABB (half-widths).
+	b2Vec2 GetExtents() const
+	{
+		return 0.5f * (upperBound - lowerBound);
+	}
+
+	/// Combine two AABBs into this one.
+	void Combine(const b2AABB& aabb1, const b2AABB& aabb2)
+	{
+		lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound);
+		upperBound = b2Max(aabb1.upperBound, aabb2.upperBound);
+	}
+
+	/// Does this aabb contain the provided AABB.
+	bool Contains(const b2AABB& aabb) const
+	{
+		bool result = true;
+		result = result && lowerBound.x <= aabb.lowerBound.x;
+		result = result && lowerBound.y <= aabb.lowerBound.y;
+		result = result && aabb.upperBound.x <= upperBound.x;
+		result = result && aabb.upperBound.y <= upperBound.y;
+		return result;
+	}
+
+	bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const;
+
+	b2Vec2 lowerBound;	///< the lower vertex
+	b2Vec2 upperBound;	///< the upper vertex
+};
+
+/// Compute the collision manifold between two circles.
+void b2CollideCircles(b2Manifold* manifold,
+					  const b2CircleShape* circle1, const b2Transform& xf1,
+					  const b2CircleShape* circle2, const b2Transform& xf2);
+
+/// Compute the collision manifold between a polygon and a circle.
+void b2CollidePolygonAndCircle(b2Manifold* manifold,
+							   const b2PolygonShape* polygon, const b2Transform& xf1,
+							   const b2CircleShape* circle, const b2Transform& xf2);
+
+/// Compute the collision manifold between two polygons.
+void b2CollidePolygons(b2Manifold* manifold,
+					   const b2PolygonShape* polygon1, const b2Transform& xf1,
+					   const b2PolygonShape* polygon2, const b2Transform& xf2);
+
+/// Clipping for contact manifolds.
+int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2],
+							const b2Vec2& normal, float32 offset);
+
+/// Determine if two generic shapes overlap.
+bool b2TestOverlap(const b2Shape* shapeA, const b2Shape* shapeB,
+				   const b2Transform& xfA, const b2Transform& xfB);
+
+// ---------------- Inline Functions ------------------------------------------
+
+inline bool b2AABB::IsValid() const
+{
+	b2Vec2 d = upperBound - lowerBound;
+	bool valid = d.x >= 0.0f && d.y >= 0.0f;
+	valid = valid && lowerBound.IsValid() && upperBound.IsValid();
+	return valid;
+}
+
+inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b)
+{
+	b2Vec2 d1, d2;
+	d1 = b.lowerBound - a.upperBound;
+	d2 = a.lowerBound - b.upperBound;
+
+	if (d1.x > 0.0f || d1.y > 0.0f)
+		return false;
+
+	if (d2.x > 0.0f || d2.y > 0.0f)
+		return false;
+
+	return true;
+}
+
+#endif

+ 141 - 0
include/Box2D/Collision/b2Distance.h

@@ -0,0 +1,141 @@
+
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_DISTANCE_H
+#define B2_DISTANCE_H
+
+#include <Box2D/Common/b2Math.h>
+#include <climits>
+
+class b2Shape;
+
+/// A distance proxy is used by the GJK algorithm.
+/// It encapsulates any shape.
+struct b2DistanceProxy
+{
+	b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {}
+
+	/// Initialize the proxy using the given shape. The shape
+	/// must remain in scope while the proxy is in use.
+	void Set(const b2Shape* shape);
+
+	/// Get the supporting vertex index in the given direction.
+	int32 GetSupport(const b2Vec2& d) const;
+
+	/// Get the supporting vertex in the given direction.
+	const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
+
+	/// Get the vertex count.
+	int32 GetVertexCount() const;
+
+	/// Get a vertex by index. Used by b2Distance.
+	const b2Vec2& GetVertex(int32 index) const;
+
+	const b2Vec2* m_vertices;
+	int32 m_count;
+	float32 m_radius;
+};
+
+/// Used to warm start b2Distance.
+/// Set count to zero on first call.
+struct b2SimplexCache
+{
+	float32 metric;		///< length or area
+	uint16 count;
+	uint8 indexA[3];	///< vertices on shape A
+	uint8 indexB[3];	///< vertices on shape B
+};
+
+/// Input for b2Distance.
+/// You have to option to use the shape radii
+/// in the computation. Even 
+struct b2DistanceInput
+{
+	b2DistanceProxy proxyA;
+	b2DistanceProxy proxyB;
+	b2Transform transformA;
+	b2Transform transformB;
+	bool useRadii;
+};
+
+/// Output for b2Distance.
+struct b2DistanceOutput
+{
+	b2Vec2 pointA;		///< closest point on shapeA
+	b2Vec2 pointB;		///< closest point on shapeB
+	float32 distance;
+	int32 iterations;	///< number of GJK iterations used
+};
+
+/// Compute the closest points between two shapes. Supports any combination of:
+/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output.
+/// On the first call set b2SimplexCache.count to zero.
+void b2Distance(b2DistanceOutput* output,
+				b2SimplexCache* cache, 
+				const b2DistanceInput* input);
+
+
+//////////////////////////////////////////////////////////////////////////
+
+inline int32 b2DistanceProxy::GetVertexCount() const
+{
+	return m_count;
+}
+
+inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const
+{
+	b2Assert(0 <= index && index < m_count);
+	return m_vertices[index];
+}
+
+inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const
+{
+	int32 bestIndex = 0;
+	float32 bestValue = b2Dot(m_vertices[0], d);
+	for (int32 i = 1; i < m_count; ++i)
+	{
+		float32 value = b2Dot(m_vertices[i], d);
+		if (value > bestValue)
+		{
+			bestIndex = i;
+			bestValue = value;
+		}
+	}
+
+	return bestIndex;
+}
+
+inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const
+{
+	int32 bestIndex = 0;
+	float32 bestValue = b2Dot(m_vertices[0], d);
+	for (int32 i = 1; i < m_count; ++i)
+	{
+		float32 value = b2Dot(m_vertices[i], d);
+		if (value > bestValue)
+		{
+			bestIndex = i;
+			bestValue = value;
+		}
+	}
+
+	return m_vertices[bestIndex];
+}
+
+#endif

+ 286 - 0
include/Box2D/Collision/b2DynamicTree.h

@@ -0,0 +1,286 @@
+/*
+* Copyright (c) 2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_DYNAMIC_TREE_H
+#define B2_DYNAMIC_TREE_H
+
+#include <Box2D/Collision/b2Collision.h>
+
+/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt.
+
+#define b2_nullNode (-1)
+
+/// A node in the dynamic tree. The client does not interact with this directly.
+struct b2DynamicTreeNode
+{
+	bool IsLeaf() const
+	{
+		return child1 == b2_nullNode;
+	}
+
+	/// This is the fattened AABB.
+	b2AABB aabb;
+
+	//int32 userData;
+	void* userData;
+
+	union
+	{
+		int32 parent;
+		int32 next;
+	};
+
+	int32 child1;
+	int32 child2;
+};
+
+/// A dynamic tree arranges data in a binary tree to accelerate
+/// queries such as volume queries and ray casts. Leafs are proxies
+/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor
+/// so that the proxy AABB is bigger than the client object. This allows the client
+/// object to move by small amounts without triggering a tree update.
+///
+/// Nodes are pooled and relocatable, so we use node indices rather than pointers.
+class b2DynamicTree
+{
+public:
+
+	/// Constructing the tree initializes the node pool.
+	b2DynamicTree();
+
+	/// Destroy the tree, freeing the node pool.
+	~b2DynamicTree();
+
+	/// Create a proxy. Provide a tight fitting AABB and a userData pointer.
+	int32 CreateProxy(const b2AABB& aabb, void* userData);
+
+	/// Destroy a proxy. This asserts if the id is invalid.
+	void DestroyProxy(int32 proxyId);
+
+	/// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB,
+	/// then the proxy is removed from the tree and re-inserted. Otherwise
+	/// the function returns immediately.
+	/// @return true if the proxy was re-inserted.
+	bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement);
+
+	/// Perform some iterations to re-balance the tree.
+	void Rebalance(int32 iterations);
+
+	/// Get proxy user data.
+	/// @return the proxy user data or 0 if the id is invalid.
+	void* GetUserData(int32 proxyId) const;
+
+	/// Get the fat AABB for a proxy.
+	const b2AABB& GetFatAABB(int32 proxyId) const;
+
+	/// Compute the height of the tree.
+	int32 ComputeHeight() const;
+
+	/// Query an AABB for overlapping proxies. The callback class
+	/// is called for each proxy that overlaps the supplied AABB.
+	template <typename T>
+	void Query(T* callback, const b2AABB& aabb) const;
+
+	/// Ray-cast against the proxies in the tree. This relies on the callback
+	/// to perform a exact ray-cast in the case were the proxy contains a shape.
+	/// The callback also performs the any collision filtering. This has performance
+	/// roughly equal to k * log(n), where k is the number of collisions and n is the
+	/// number of proxies in the tree.
+	/// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
+	/// @param callback a callback class that is called for each proxy that is hit by the ray.
+	template <typename T>
+	void RayCast(T* callback, const b2RayCastInput& input) const;
+
+private:
+
+	int32 AllocateNode();
+	void FreeNode(int32 node);
+
+	void InsertLeaf(int32 node);
+	void RemoveLeaf(int32 node);
+
+	int32 ComputeHeight(int32 nodeId) const;
+
+	int32 m_root;
+
+	b2DynamicTreeNode* m_nodes;
+	int32 m_nodeCount;
+	int32 m_nodeCapacity;
+
+	int32 m_freeList;
+
+	/// This is used incrementally traverse the tree for re-balancing.
+	uint32 m_path;
+
+	int32 m_insertionCount;
+};
+
+inline void* b2DynamicTree::GetUserData(int32 proxyId) const
+{
+	b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
+	return m_nodes[proxyId].userData;
+}
+
+inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const
+{
+	b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
+	return m_nodes[proxyId].aabb;
+}
+
+template <typename T>
+inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const
+{
+	const int32 k_stackSize = 128;
+	int32 stack[k_stackSize];
+
+	int32 count = 0;
+	stack[count++] = m_root;
+
+	while (count > 0)
+	{
+		int32 nodeId = stack[--count];
+		if (nodeId == b2_nullNode)
+		{
+			continue;
+		}
+
+		const b2DynamicTreeNode* node = m_nodes + nodeId;
+
+		if (b2TestOverlap(node->aabb, aabb))
+		{
+			if (node->IsLeaf())
+			{
+				bool proceed = callback->QueryCallback(nodeId);
+				if (proceed == false)
+				{
+					return;
+				}
+			}
+			else
+			{
+				if (count < k_stackSize)
+				{
+					stack[count++] = node->child1;
+				}
+
+				if (count < k_stackSize)
+				{
+					stack[count++] = node->child2;
+				}
+			}
+		}
+	}
+}
+
+template <typename T>
+inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const
+{
+	b2Vec2 p1 = input.p1;
+	b2Vec2 p2 = input.p2;
+	b2Vec2 r = p2 - p1;
+	b2Assert(r.LengthSquared() > 0.0f);
+	r.Normalize();
+
+	// v is perpendicular to the segment.
+	b2Vec2 v = b2Cross(1.0f, r);
+	b2Vec2 abs_v = b2Abs(v);
+
+	// Separating axis for segment (Gino, p80).
+	// |dot(v, p1 - c)| > dot(|v|, h)
+
+	float32 maxFraction = input.maxFraction;
+
+	// Build a bounding box for the segment.
+	b2AABB segmentAABB;
+	{
+		b2Vec2 t = p1 + maxFraction * (p2 - p1);
+		segmentAABB.lowerBound = b2Min(p1, t);
+		segmentAABB.upperBound = b2Max(p1, t);
+	}
+
+	const int32 k_stackSize = 128;
+	int32 stack[k_stackSize];
+
+	int32 count = 0;
+	stack[count++] = m_root;
+
+	while (count > 0)
+	{
+		int32 nodeId = stack[--count];
+		if (nodeId == b2_nullNode)
+		{
+			continue;
+		}
+
+		const b2DynamicTreeNode* node = m_nodes + nodeId;
+
+		if (b2TestOverlap(node->aabb, segmentAABB) == false)
+		{
+			continue;
+		}
+
+		// Separating axis for segment (Gino, p80).
+		// |dot(v, p1 - c)| > dot(|v|, h)
+		b2Vec2 c = node->aabb.GetCenter();
+		b2Vec2 h = node->aabb.GetExtents();
+		float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h);
+		if (separation > 0.0f)
+		{
+			continue;
+		}
+
+		if (node->IsLeaf())
+		{
+			b2RayCastInput subInput;
+			subInput.p1 = input.p1;
+			subInput.p2 = input.p2;
+			subInput.maxFraction = maxFraction;
+
+			float32 value = callback->RayCastCallback(subInput, nodeId);
+
+			if (value == 0.0f)
+			{
+				// The client has terminated the ray cast.
+				return;
+			}
+
+			if (value > 0.0f)
+			{
+				// Update segment bounding box.
+				maxFraction = value;
+				b2Vec2 t = p1 + maxFraction * (p2 - p1);
+				segmentAABB.lowerBound = b2Min(p1, t);
+				segmentAABB.upperBound = b2Max(p1, t);
+			}
+		}
+		else
+		{
+			if (count < k_stackSize)
+			{
+				stack[count++] = node->child1;
+			}
+
+			if (count < k_stackSize)
+			{
+				stack[count++] = node->child2;
+			}
+		}
+	}
+}
+
+#endif

+ 59 - 0
include/Box2D/Collision/b2TimeOfImpact.h

@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_TIME_OF_IMPACT_H
+#define B2_TIME_OF_IMPACT_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Distance.h>
+#include <climits>
+
+/// Input parameters for b2TimeOfImpact
+struct b2TOIInput
+{
+	b2DistanceProxy proxyA;
+	b2DistanceProxy proxyB;
+	b2Sweep sweepA;
+	b2Sweep sweepB;
+	float32 tMax;		// defines sweep interval [0, tMax]
+};
+
+// Output parameters for b2TimeOfImpact.
+struct b2TOIOutput
+{
+	enum State
+	{
+		e_unknown,
+		e_failed,
+		e_overlapped,
+		e_touching,
+		e_separated
+	};
+
+	State state;
+	float32 t;
+};
+
+/// Compute the upper bound on time before two shapes penetrate. Time is represented as
+/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate,
+/// non-tunneling collision. If you change the time interval, you should call this function
+/// again.
+/// Note: use b2Distance to compute the contact point and normal at the time of impact.
+void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input);
+
+#endif

+ 59 - 0
include/Box2D/Common/b2BlockAllocator.h

@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_BLOCK_ALLOCATOR_H
+#define B2_BLOCK_ALLOCATOR_H
+
+#include <Box2D/Common/b2Settings.h>
+
+const int32 b2_chunkSize = 4096;
+const int32 b2_maxBlockSize = 640;
+const int32 b2_blockSizes = 14;
+const int32 b2_chunkArrayIncrement = 128;
+
+struct b2Block;
+struct b2Chunk;
+
+// This is a small object allocator used for allocating small
+// objects that persist for more than one time step.
+// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp
+class b2BlockAllocator
+{
+public:
+	b2BlockAllocator();
+	~b2BlockAllocator();
+
+	void* Allocate(int32 size);
+	void Free(void* p, int32 size);
+
+	void Clear();
+
+private:
+
+	b2Chunk* m_chunks;
+	int32 m_chunkCount;
+	int32 m_chunkSpace;
+
+	b2Block* m_freeLists[b2_blockSizes];
+
+	static int32 s_blockSizes[b2_blockSizes];
+	static uint8 s_blockSizeLookup[b2_maxBlockSize + 1];
+	static bool s_blockSizeLookupInitialized;
+};
+
+#endif

+ 624 - 0
include/Box2D/Common/b2Math.h

@@ -0,0 +1,624 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_MATH_H
+#define B2_MATH_H
+
+#include <Box2D/Common/b2Settings.h>
+
+#include <cmath>
+#include <cfloat>
+#include <cstddef>
+#include <limits>
+
+/// This function is used to ensure that a floating point number is
+/// not a NaN or infinity.
+inline bool b2IsValid(float32 x)
+{
+	if (x != x)
+	{
+		// NaN.
+		return false;
+	}
+
+	float32 infinity = std::numeric_limits<float32>::infinity();
+	return -infinity < x && x < infinity;
+}
+
+/// This is a approximate yet fast inverse square-root.
+inline float32 b2InvSqrt(float32 x)
+{
+	union
+	{
+		float32 x;
+		int32 i;
+	} convert;
+
+	convert.x = x;
+	float32 xhalf = 0.5f * x;
+	convert.i = 0x5f3759df - (convert.i >> 1);
+	x = convert.x;
+	x = x * (1.5f - xhalf * x * x);
+	return x;
+}
+
+#define	b2Sqrt(x)	sqrtf(x)
+#define	b2Atan2(y, x)	atan2f(y, x)
+
+inline float32 b2Abs(float32 a)
+{
+	return a > 0.0f ? a : -a;
+}
+
+/// A 2D column vector.
+struct b2Vec2
+{
+	/// Default constructor does nothing (for performance).
+	b2Vec2() {}
+
+	/// Construct using coordinates.
+	b2Vec2(float32 x, float32 y) : x(x), y(y) {}
+
+	/// Set this vector to all zeros.
+	void SetZero() { x = 0.0f; y = 0.0f; }
+
+	/// Set this vector to some specified coordinates.
+	void Set(float32 x_, float32 y_) { x = x_; y = y_; }
+
+	/// Negate this vector.
+	b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; }
+	
+	/// Read from and indexed element.
+	float32 operator () (int32 i) const
+	{
+		return (&x)[i];
+	}
+
+	/// Write to an indexed element.
+	float32& operator () (int32 i)
+	{
+		return (&x)[i];
+	}
+
+	/// Add a vector to this vector.
+	void operator += (const b2Vec2& v)
+	{
+		x += v.x; y += v.y;
+	}
+	
+	/// Subtract a vector from this vector.
+	void operator -= (const b2Vec2& v)
+	{
+		x -= v.x; y -= v.y;
+	}
+
+	/// Multiply this vector by a scalar.
+	void operator *= (float32 a)
+	{
+		x *= a; y *= a;
+	}
+
+	/// Get the length of this vector (the norm).
+	float32 Length() const
+	{
+		return b2Sqrt(x * x + y * y);
+	}
+
+	/// Get the length squared. For performance, use this instead of
+	/// b2Vec2::Length (if possible).
+	float32 LengthSquared() const
+	{
+		return x * x + y * y;
+	}
+
+	/// Convert this vector into a unit vector. Returns the length.
+	float32 Normalize()
+	{
+		float32 length = Length();
+		if (length < b2_epsilon)
+		{
+			return 0.0f;
+		}
+		float32 invLength = 1.0f / length;
+		x *= invLength;
+		y *= invLength;
+
+		return length;
+	}
+
+	/// Does this vector contain finite coordinates?
+	bool IsValid() const
+	{
+		return b2IsValid(x) && b2IsValid(y);
+	}
+
+	float32 x, y;
+};
+
+/// A 2D column vector with 3 elements.
+struct b2Vec3
+{
+	/// Default constructor does nothing (for performance).
+	b2Vec3() {}
+
+	/// Construct using coordinates.
+	b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}
+
+	/// Set this vector to all zeros.
+	void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; }
+
+	/// Set this vector to some specified coordinates.
+	void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; }
+
+	/// Negate this vector.
+	b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; }
+
+	/// Add a vector to this vector.
+	void operator += (const b2Vec3& v)
+	{
+		x += v.x; y += v.y; z += v.z;
+	}
+
+	/// Subtract a vector from this vector.
+	void operator -= (const b2Vec3& v)
+	{
+		x -= v.x; y -= v.y; z -= v.z;
+	}
+
+	/// Multiply this vector by a scalar.
+	void operator *= (float32 s)
+	{
+		x *= s; y *= s; z *= s;
+	}
+
+	float32 x, y, z;
+};
+
+/// A 2-by-2 matrix. Stored in column-major order.
+struct b2Mat22
+{
+	/// The default constructor does nothing (for performance).
+	b2Mat22() {}
+
+	/// Construct this matrix using columns.
+	b2Mat22(const b2Vec2& c1, const b2Vec2& c2)
+	{
+		col1 = c1;
+		col2 = c2;
+	}
+
+	/// Construct this matrix using scalars.
+	b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22)
+	{
+		col1.x = a11; col1.y = a21;
+		col2.x = a12; col2.y = a22;
+	}
+
+	/// Construct this matrix using an angle. This matrix becomes
+	/// an orthonormal rotation matrix.
+	explicit b2Mat22(float32 angle)
+	{
+		// TODO_ERIN compute sin+cos together.
+		float32 c = cosf(angle), s = sinf(angle);
+		col1.x = c; col2.x = -s;
+		col1.y = s; col2.y = c;
+	}
+
+	/// Initialize this matrix using columns.
+	void Set(const b2Vec2& c1, const b2Vec2& c2)
+	{
+		col1 = c1;
+		col2 = c2;
+	}
+
+	/// Initialize this matrix using an angle. This matrix becomes
+	/// an orthonormal rotation matrix.
+	void Set(float32 angle)
+	{
+		float32 c = cosf(angle), s = sinf(angle);
+		col1.x = c; col2.x = -s;
+		col1.y = s; col2.y = c;
+	}
+
+	/// Set this to the identity matrix.
+	void SetIdentity()
+	{
+		col1.x = 1.0f; col2.x = 0.0f;
+		col1.y = 0.0f; col2.y = 1.0f;
+	}
+
+	/// Set this matrix to all zeros.
+	void SetZero()
+	{
+		col1.x = 0.0f; col2.x = 0.0f;
+		col1.y = 0.0f; col2.y = 0.0f;
+	}
+
+	/// Extract the angle from this matrix (assumed to be
+	/// a rotation matrix).
+	float32 GetAngle() const
+	{
+		return b2Atan2(col1.y, col1.x);
+	}
+
+	b2Mat22 GetInverse() const
+	{
+		float32 a = col1.x, b = col2.x, c = col1.y, d = col2.y;
+		b2Mat22 B;
+		float32 det = a * d - b * c;
+		if (det != 0.0f)
+		{
+			det = 1.0f / det;
+		}
+		B.col1.x =  det * d;	B.col2.x = -det * b;
+		B.col1.y = -det * c;	B.col2.y =  det * a;
+		return B;
+	}
+
+	/// Solve A * x = b, where b is a column vector. This is more efficient
+	/// than computing the inverse in one-shot cases.
+	b2Vec2 Solve(const b2Vec2& b) const
+	{
+		float32 a11 = col1.x, a12 = col2.x, a21 = col1.y, a22 = col2.y;
+		float32 det = a11 * a22 - a12 * a21;
+		if (det != 0.0f)
+		{
+			det = 1.0f / det;
+		}
+		b2Vec2 x;
+		x.x = det * (a22 * b.x - a12 * b.y);
+		x.y = det * (a11 * b.y - a21 * b.x);
+		return x;
+	}
+
+	b2Vec2 col1, col2;
+};
+
+/// A 3-by-3 matrix. Stored in column-major order.
+struct b2Mat33
+{
+	/// The default constructor does nothing (for performance).
+	b2Mat33() {}
+
+	/// Construct this matrix using columns.
+	b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3)
+	{
+		col1 = c1;
+		col2 = c2;
+		col3 = c3;
+	}
+
+	/// Set this matrix to all zeros.
+	void SetZero()
+	{
+		col1.SetZero();
+		col2.SetZero();
+		col3.SetZero();
+	}
+
+	/// Solve A * x = b, where b is a column vector. This is more efficient
+	/// than computing the inverse in one-shot cases.
+	b2Vec3 Solve33(const b2Vec3& b) const;
+
+	/// Solve A * x = b, where b is a column vector. This is more efficient
+	/// than computing the inverse in one-shot cases. Solve only the upper
+	/// 2-by-2 matrix equation.
+	b2Vec2 Solve22(const b2Vec2& b) const;
+
+	b2Vec3 col1, col2, col3;
+};
+
+/// A transform contains translation and rotation. It is used to represent
+/// the position and orientation of rigid frames.
+struct b2Transform
+{
+	/// The default constructor does nothing (for performance).
+	b2Transform() {}
+
+	/// Initialize using a position vector and a rotation matrix.
+	b2Transform(const b2Vec2& position, const b2Mat22& R) : position(position), R(R) {}
+
+	/// Set this to the identity transform.
+	void SetIdentity()
+	{
+		position.SetZero();
+		R.SetIdentity();
+	}
+
+	/// Set this based on the position and angle.
+	void Set(const b2Vec2& p, float32 angle)
+	{
+		position = p;
+		R.Set(angle);
+	}
+
+	/// Calculate the angle that the rotation matrix represents.
+	float32 GetAngle() const
+	{
+		return b2Atan2(R.col1.y, R.col1.x);
+	}
+
+	b2Vec2 position;
+	b2Mat22 R;
+};
+
+/// This describes the motion of a body/shape for TOI computation.
+/// Shapes are defined with respect to the body origin, which may
+/// no coincide with the center of mass. However, to support dynamics
+/// we must interpolate the center of mass position.
+struct b2Sweep
+{
+	/// Get the interpolated transform at a specific time.
+	/// @param alpha is a factor in [0,1], where 0 indicates t0.
+	void GetTransform(b2Transform* xf, float32 alpha) const;
+
+	/// Advance the sweep forward, yielding a new initial state.
+	/// @param t the new initial time.
+	void Advance(float32 t);
+
+	/// Normalize the angles.
+	void Normalize();
+
+	b2Vec2 localCenter;	///< local center of mass position
+	b2Vec2 c0, c;		///< center world positions
+	float32 a0, a;		///< world angles
+};
+
+
+extern const b2Vec2 b2Vec2_zero;
+extern const b2Mat22 b2Mat22_identity;
+extern const b2Transform b2Transform_identity;
+
+/// Perform the dot product on two vectors.
+inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b)
+{
+	return a.x * b.x + a.y * b.y;
+}
+
+/// Perform the cross product on two vectors. In 2D this produces a scalar.
+inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b)
+{
+	return a.x * b.y - a.y * b.x;
+}
+
+/// Perform the cross product on a vector and a scalar. In 2D this produces
+/// a vector.
+inline b2Vec2 b2Cross(const b2Vec2& a, float32 s)
+{
+	return b2Vec2(s * a.y, -s * a.x);
+}
+
+/// Perform the cross product on a scalar and a vector. In 2D this produces
+/// a vector.
+inline b2Vec2 b2Cross(float32 s, const b2Vec2& a)
+{
+	return b2Vec2(-s * a.y, s * a.x);
+}
+
+/// Multiply a matrix times a vector. If a rotation matrix is provided,
+/// then this transforms the vector from one frame to another.
+inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v)
+{
+	return b2Vec2(A.col1.x * v.x + A.col2.x * v.y, A.col1.y * v.x + A.col2.y * v.y);
+}
+
+/// Multiply a matrix transpose times a vector. If a rotation matrix is provided,
+/// then this transforms the vector from one frame to another (inverse transform).
+inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v)
+{
+	return b2Vec2(b2Dot(v, A.col1), b2Dot(v, A.col2));
+}
+
+/// Add two vectors component-wise.
+inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(a.x + b.x, a.y + b.y);
+}
+
+/// Subtract two vectors component-wise.
+inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(a.x - b.x, a.y - b.y);
+}
+
+inline b2Vec2 operator * (float32 s, const b2Vec2& a)
+{
+	return b2Vec2(s * a.x, s * a.y);
+}
+
+inline bool operator == (const b2Vec2& a, const b2Vec2& b)
+{
+	return a.x == b.x && a.y == b.y;
+}
+
+inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b)
+{
+	b2Vec2 c = a - b;
+	return c.Length();
+}
+
+inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b)
+{
+	b2Vec2 c = a - b;
+	return b2Dot(c, c);
+}
+
+inline b2Vec3 operator * (float32 s, const b2Vec3& a)
+{
+	return b2Vec3(s * a.x, s * a.y, s * a.z);
+}
+
+/// Add two vectors component-wise.
+inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b)
+{
+	return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
+}
+
+/// Subtract two vectors component-wise.
+inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b)
+{
+	return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
+}
+
+/// Perform the dot product on two vectors.
+inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b)
+{
+	return a.x * b.x + a.y * b.y + a.z * b.z;
+}
+
+/// Perform the cross product on two vectors.
+inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b)
+{
+	return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
+}
+
+inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B)
+{
+	return b2Mat22(A.col1 + B.col1, A.col2 + B.col2);
+}
+
+// A * B
+inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B)
+{
+	return b2Mat22(b2Mul(A, B.col1), b2Mul(A, B.col2));
+}
+
+// A^T * B
+inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B)
+{
+	b2Vec2 c1(b2Dot(A.col1, B.col1), b2Dot(A.col2, B.col1));
+	b2Vec2 c2(b2Dot(A.col1, B.col2), b2Dot(A.col2, B.col2));
+	return b2Mat22(c1, c2);
+}
+
+/// Multiply a matrix times a vector.
+inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v)
+{
+	return v.x * A.col1 + v.y * A.col2 + v.z * A.col3;
+}
+
+inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v)
+{
+	float32 x = T.position.x + T.R.col1.x * v.x + T.R.col2.x * v.y;
+	float32 y = T.position.y + T.R.col1.y * v.x + T.R.col2.y * v.y;
+
+	return b2Vec2(x, y);
+}
+
+inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v)
+{
+	return b2MulT(T.R, v - T.position);
+}
+
+inline b2Vec2 b2Abs(const b2Vec2& a)
+{
+	return b2Vec2(b2Abs(a.x), b2Abs(a.y));
+}
+
+inline b2Mat22 b2Abs(const b2Mat22& A)
+{
+	return b2Mat22(b2Abs(A.col1), b2Abs(A.col2));
+}
+
+template <typename T>
+inline T b2Min(T a, T b)
+{
+	return a < b ? a : b;
+}
+
+inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y));
+}
+
+template <typename T>
+inline T b2Max(T a, T b)
+{
+	return a > b ? a : b;
+}
+
+inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b)
+{
+	return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y));
+}
+
+template <typename T>
+inline T b2Clamp(T a, T low, T high)
+{
+	return b2Max(low, b2Min(a, high));
+}
+
+inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high)
+{
+	return b2Max(low, b2Min(a, high));
+}
+
+template<typename T> inline void b2Swap(T& a, T& b)
+{
+	T tmp = a;
+	a = b;
+	b = tmp;
+}
+
+/// "Next Largest Power of 2
+/// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm
+/// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with
+/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next
+/// largest power of 2. For a 32-bit value:"
+inline uint32 b2NextPowerOfTwo(uint32 x)
+{
+	x |= (x >> 1);
+	x |= (x >> 2);
+	x |= (x >> 4);
+	x |= (x >> 8);
+	x |= (x >> 16);
+	return x + 1;
+}
+
+inline bool b2IsPowerOfTwo(uint32 x)
+{
+	bool result = x > 0 && (x & (x - 1)) == 0;
+	return result;
+}
+
+inline void b2Sweep::GetTransform(b2Transform* xf, float32 alpha) const
+{
+	xf->position = (1.0f - alpha) * c0 + alpha * c;
+	float32 angle = (1.0f - alpha) * a0 + alpha * a;
+	xf->R.Set(angle);
+
+	// Shift to origin
+	xf->position -= b2Mul(xf->R, localCenter);
+}
+
+inline void b2Sweep::Advance(float32 t)
+{
+	c0 = (1.0f - t) * c0 + t * c;
+	a0 = (1.0f - t) * a0 + t * a;
+}
+
+/// Normalize an angle in radians to be between -pi and pi
+inline void b2Sweep::Normalize()
+{
+	float32 twoPi = 2.0f * b2_pi;
+	float32 d =  twoPi * floorf(a0 / twoPi);
+	a0 -= d;
+	a -= d;
+}
+
+#endif

+ 151 - 0
include/Box2D/Common/b2Settings.h

@@ -0,0 +1,151 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_SETTINGS_H
+#define B2_SETTINGS_H
+
+#include <cassert>
+#include <cmath>
+
+#define B2_NOT_USED(x) ((void)(x))
+#define b2Assert(A) assert(A)
+
+typedef signed char	int8;
+typedef signed short int16;
+typedef signed int int32;
+typedef unsigned char uint8;
+typedef unsigned short uint16;
+typedef unsigned int uint32;
+typedef float float32;
+
+#define	b2_maxFloat		FLT_MAX
+#define	b2_epsilon		FLT_EPSILON
+#define b2_pi			3.14159265359f
+
+/// @file
+/// Global tuning constants based on meters-kilograms-seconds (MKS) units.
+///
+
+// Collision
+
+/// The maximum number of contact points between two convex shapes.
+#define b2_maxManifoldPoints	2
+
+/// The maximum number of vertices on a convex polygon.
+#define b2_maxPolygonVertices	8
+
+/// This is used to fatten AABBs in the dynamic tree. This allows proxies
+/// to move by a small amount without triggering a tree adjustment.
+/// This is in meters.
+#define b2_aabbExtension		0.1f
+
+/// This is used to fatten AABBs in the dynamic tree. This is used to predict
+/// the future position based on the current displacement.
+/// This is a dimensionless multiplier.
+#define b2_aabbMultiplier		2.0f
+
+/// A small length used as a collision and constraint tolerance. Usually it is
+/// chosen to be numerically significant, but visually insignificant.
+#define b2_linearSlop			0.005f
+
+/// A small angle used as a collision and constraint tolerance. Usually it is
+/// chosen to be numerically significant, but visually insignificant.
+#define b2_angularSlop			(2.0f / 180.0f * b2_pi)
+
+/// The radius of the polygon/edge shape skin. This should not be modified. Making
+/// this smaller means polygons will have an insufficient buffer for continuous collision.
+/// Making it larger may create artifacts for vertex collision.
+#define b2_polygonRadius		(2.0f * b2_linearSlop)
+
+
+// Dynamics
+
+/// Maximum number of contacts to be handled to solve a TOI impact.
+#define b2_maxTOIContacts			32
+
+/// A velocity threshold for elastic collisions. Any collision with a relative linear
+/// velocity below this threshold will be treated as inelastic.
+#define b2_velocityThreshold		1.0f
+
+/// The maximum linear position correction used when solving constraints. This helps to
+/// prevent overshoot.
+#define b2_maxLinearCorrection		0.2f
+
+/// The maximum angular position correction used when solving constraints. This helps to
+/// prevent overshoot.
+#define b2_maxAngularCorrection		(8.0f / 180.0f * b2_pi)
+
+/// The maximum linear velocity of a body. This limit is very large and is used
+/// to prevent numerical problems. You shouldn't need to adjust this.
+#define b2_maxTranslation			2.0f
+#define b2_maxTranslationSquared	(b2_maxTranslation * b2_maxTranslation)
+
+/// The maximum angular velocity of a body. This limit is very large and is used
+/// to prevent numerical problems. You shouldn't need to adjust this.
+#define b2_maxRotation				(0.5f * b2_pi)
+#define b2_maxRotationSquared		(b2_maxRotation * b2_maxRotation)
+
+/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so
+/// that overlap is removed in one time step. However using values close to 1 often lead
+/// to overshoot.
+#define b2_contactBaumgarte			0.2f
+
+// Sleep
+
+/// The time that a body must be still before it will go to sleep.
+#define b2_timeToSleep				0.5f
+
+/// A body cannot sleep if its linear velocity is above this tolerance.
+#define b2_linearSleepTolerance		0.01f
+
+/// A body cannot sleep if its angular velocity is above this tolerance.
+#define b2_angularSleepTolerance	(2.0f / 180.0f * b2_pi)
+
+// Memory Allocation
+
+/// Implement this function to use your own memory allocator.
+void* b2Alloc(int32 size);
+
+/// If you implement b2Alloc, you should also implement this function.
+void b2Free(void* mem);
+
+/// Version numbering scheme.
+/// See http://en.wikipedia.org/wiki/Software_versioning
+struct b2Version
+{
+	int32 major;		///< significant changes
+	int32 minor;		///< incremental changes
+	int32 revision;		///< bug fixes
+};
+
+/// Current version.
+extern b2Version b2_version;
+
+/// Friction mixing law. Feel free to customize this.
+inline float32 b2MixFriction(float32 friction1, float32 friction2)
+{
+	return sqrtf(friction1 * friction2);
+}
+
+/// Restitution mixing law. Feel free to customize this.
+inline float32 b2MixRestitution(float32 restitution1, float32 restitution2)
+{
+	return restitution1 > restitution2 ? restitution1 : restitution2;
+}
+
+#endif

+ 60 - 0
include/Box2D/Common/b2StackAllocator.h

@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_STACK_ALLOCATOR_H
+#define B2_STACK_ALLOCATOR_H
+
+#include <Box2D/Common/b2Settings.h>
+
+const int32 b2_stackSize = 100 * 1024;	// 100k
+const int32 b2_maxStackEntries = 32;
+
+struct b2StackEntry
+{
+	char* data;
+	int32 size;
+	bool usedMalloc;
+};
+
+// This is a stack allocator used for fast per step allocations.
+// You must nest allocate/free pairs. The code will assert
+// if you try to interleave multiple allocate/free pairs.
+class b2StackAllocator
+{
+public:
+	b2StackAllocator();
+	~b2StackAllocator();
+
+	void* Allocate(int32 size);
+	void Free(void* p);
+
+	int32 GetMaxAllocation() const;
+
+private:
+
+	char m_data[b2_stackSize];
+	int32 m_index;
+
+	int32 m_allocation;
+	int32 m_maxAllocation;
+
+	b2StackEntry m_entries[b2_maxStackEntries];
+	int32 m_entryCount;
+};
+
+#endif

+ 38 - 0
include/Box2D/Dynamics/Contacts/b2CircleContact.h

@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CIRCLE_CONTACT_H
+#define B2_CIRCLE_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2CircleContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+	~b2CircleContact() {}
+
+	void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif

+ 242 - 0
include/Box2D/Dynamics/Contacts/b2Contact.h

@@ -0,0 +1,242 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CONTACT_H
+#define B2_CONTACT_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+
+class b2Body;
+class b2Contact;
+class b2Fixture;
+class b2World;
+class b2BlockAllocator;
+class b2StackAllocator;
+class b2ContactListener;
+
+typedef b2Contact* b2ContactCreateFcn(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator);
+
+struct b2ContactRegister
+{
+	b2ContactCreateFcn* createFcn;
+	b2ContactDestroyFcn* destroyFcn;
+	bool primary;
+};
+
+/// A contact edge is used to connect bodies and contacts together
+/// in a contact graph where each body is a node and each contact
+/// is an edge. A contact edge belongs to a doubly linked list
+/// maintained in each attached body. Each contact has two contact
+/// nodes, one for each attached body.
+struct b2ContactEdge
+{
+	b2Body* other;			///< provides quick access to the other body attached.
+	b2Contact* contact;		///< the contact
+	b2ContactEdge* prev;	///< the previous contact edge in the body's contact list
+	b2ContactEdge* next;	///< the next contact edge in the body's contact list
+};
+
+/// The class manages contact between two shapes. A contact exists for each overlapping
+/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist
+/// that has no contact points.
+class b2Contact
+{
+public:
+
+	/// Get the contact manifold. Do not modify the manifold unless you understand the
+	/// internals of Box2D.
+	b2Manifold* GetManifold();
+	const b2Manifold* GetManifold() const;
+
+	/// Get the world manifold.
+	void GetWorldManifold(b2WorldManifold* worldManifold) const;
+
+	/// Is this contact touching?
+	bool IsTouching() const;
+
+	/// Enable/disable this contact. This can be used inside the pre-solve
+	/// contact listener. The contact is only disabled for the current
+	/// time step (or sub-step in continuous collisions).
+	void SetEnabled(bool flag);
+
+	/// Has this contact been disabled?
+	bool IsEnabled() const;
+
+	/// Get the next contact in the world's contact list.
+	b2Contact* GetNext();
+	const b2Contact* GetNext() const;
+
+	/// Get the first fixture in this contact.
+	b2Fixture* GetFixtureA();
+	const b2Fixture* GetFixtureA() const;
+
+	/// Get the second fixture in this contact.
+	b2Fixture* GetFixtureB();
+	const b2Fixture* GetFixtureB() const;
+
+	/// Evaluate this contact with your own manifold and transforms.
+	virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0;
+
+protected:
+	friend class b2ContactManager;
+	friend class b2World;
+	friend class b2ContactSolver;
+	friend class b2Body;
+	friend class b2Fixture;
+
+	// Flags stored in m_flags
+	enum
+	{
+		// Used when crawling contact graph when forming islands.
+		e_islandFlag		= 0x0001,
+
+        // Set when the shapes are touching.
+		e_touchingFlag		= 0x0002,
+
+		// This contact can be disabled (by user)
+		e_enabledFlag		= 0x0004,
+
+		// This contact needs filtering because a fixture filter was changed.
+		e_filterFlag		= 0x0008,
+
+		// This bullet contact had a TOI event
+		e_bulletHitFlag		= 0x0010,
+
+	};
+
+	/// Flag this contact for filtering. Filtering will occur the next time step.
+	void FlagForFiltering();
+
+	static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn,
+						b2Shape::Type typeA, b2Shape::Type typeB);
+	static void InitializeRegisters();
+	static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {}
+	b2Contact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+	virtual ~b2Contact() {}
+
+	void Update(b2ContactListener* listener);
+
+	static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount];
+	static bool s_initialized;
+
+	uint32 m_flags;
+
+	// World pool and list pointers.
+	b2Contact* m_prev;
+	b2Contact* m_next;
+
+	// Nodes for connecting bodies.
+	b2ContactEdge m_nodeA;
+	b2ContactEdge m_nodeB;
+
+	b2Fixture* m_fixtureA;
+	b2Fixture* m_fixtureB;
+
+	b2Manifold m_manifold;
+
+	int32 m_toiCount;
+//	float32 m_toi;
+};
+
+inline b2Manifold* b2Contact::GetManifold()
+{
+	return &m_manifold;
+}
+
+inline const b2Manifold* b2Contact::GetManifold() const
+{
+	return &m_manifold;
+}
+
+inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const
+{
+	const b2Body* bodyA = m_fixtureA->GetBody();
+	const b2Body* bodyB = m_fixtureB->GetBody();
+	const b2Shape* shapeA = m_fixtureA->GetShape();
+	const b2Shape* shapeB = m_fixtureB->GetShape();
+
+	worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius);
+}
+
+inline void b2Contact::SetEnabled(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_enabledFlag;
+	}
+	else
+	{
+		m_flags &= ~e_enabledFlag;
+	}
+}
+
+inline bool b2Contact::IsEnabled() const
+{
+	return (m_flags & e_enabledFlag) == e_enabledFlag;
+}
+
+inline bool b2Contact::IsTouching() const
+{
+	return (m_flags & e_touchingFlag) == e_touchingFlag;
+}
+
+inline b2Contact* b2Contact::GetNext()
+{
+	return m_next;
+}
+
+inline const b2Contact* b2Contact::GetNext() const
+{
+	return m_next;
+}
+
+inline b2Fixture* b2Contact::GetFixtureA()
+{
+	return m_fixtureA;
+}
+
+inline const b2Fixture* b2Contact::GetFixtureA() const
+{
+	return m_fixtureA;
+}
+
+inline b2Fixture* b2Contact::GetFixtureB()
+{
+	return m_fixtureB;
+}
+
+inline const b2Fixture* b2Contact::GetFixtureB() const
+{
+	return m_fixtureB;
+}
+
+inline void b2Contact::FlagForFiltering()
+{
+	m_flags |= e_filterFlag;
+}
+
+#endif

+ 78 - 0
include/Box2D/Dynamics/Contacts/b2ContactSolver.h

@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CONTACT_SOLVER_H
+#define B2_CONTACT_SOLVER_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Dynamics/b2Island.h>
+
+class b2Contact;
+class b2Body;
+class b2StackAllocator;
+
+struct b2ContactConstraintPoint
+{
+	b2Vec2 localPoint;
+	b2Vec2 rA;
+	b2Vec2 rB;
+	float32 normalImpulse;
+	float32 tangentImpulse;
+	float32 normalMass;
+	float32 tangentMass;
+	float32 velocityBias;
+};
+
+struct b2ContactConstraint
+{
+	b2ContactConstraintPoint points[b2_maxManifoldPoints];
+	b2Vec2 localNormal;
+	b2Vec2 localPoint;
+	b2Vec2 normal;
+	b2Mat22 normalMass;
+	b2Mat22 K;
+	b2Body* bodyA;
+	b2Body* bodyB;
+	b2Manifold::Type type;
+	float32 radius;
+	float32 friction;
+	int32 pointCount;
+	b2Manifold* manifold;
+};
+
+class b2ContactSolver
+{
+public:
+	b2ContactSolver(b2Contact** contacts, int32 contactCount,
+					b2StackAllocator* allocator, float32 impulseRatio);
+
+	~b2ContactSolver();
+
+	void WarmStart();
+	void SolveVelocityConstraints();
+	void StoreImpulses();
+
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2StackAllocator* m_allocator;
+	b2ContactConstraint* m_constraints;
+	int m_constraintCount;
+};
+
+#endif

+ 38 - 0
include/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h

@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H
+#define B2_POLYGON_AND_CIRCLE_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2PolygonAndCircleContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+	~b2PolygonAndCircleContact() {}
+
+	void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif

+ 38 - 0
include/Box2D/Dynamics/Contacts/b2PolygonContact.h

@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_POLYGON_CONTACT_H
+#define B2_POLYGON_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2PolygonContact : public b2Contact
+{
+public:
+	static b2Contact* Create(b2Fixture* fixtureA, b2Fixture* fixtureB, b2BlockAllocator* allocator);
+	static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+	b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+	~b2PolygonContact() {}
+
+	void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif

+ 51 - 0
include/Box2D/Dynamics/Contacts/b2TOISolver.h

@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2006-2010 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_TOI_SOLVER_H
+#define B2_TOI_SOLVER_H
+
+#include <Box2D/Common/b2Math.h>
+
+class b2Contact;
+class b2Body;
+struct b2TOIConstraint;
+class b2StackAllocator;
+
+/// This is a pure position solver for a single movable body in contact with
+/// multiple non-moving bodies.
+class b2TOISolver
+{
+public:
+	b2TOISolver(b2StackAllocator* allocator);
+	~b2TOISolver();
+
+	void Initialize(b2Contact** contacts, int32 contactCount, b2Body* toiBody);
+	void Clear();
+
+	// Perform one solver iteration. Returns true if converged.
+	bool Solve(float32 baumgarte);
+
+private:
+
+	b2TOIConstraint* m_constraints;
+	int32 m_count;
+	b2Body* m_toiBody;
+	b2StackAllocator* m_allocator;
+};
+
+#endif

+ 140 - 0
include/Box2D/Dynamics/Joints/b2DistanceJoint.h

@@ -0,0 +1,140 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_DISTANCE_JOINT_H
+#define B2_DISTANCE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Distance joint definition. This requires defining an
+/// anchor point on both bodies and the non-zero length of the
+/// distance joint. The definition uses local anchor points
+/// so that the initial configuration can violate the constraint
+/// slightly. This helps when saving and loading a game.
+/// @warning Do not use a zero or short length.
+struct b2DistanceJointDef : public b2JointDef
+{
+	b2DistanceJointDef()
+	{
+		type = e_distanceJoint;
+		localAnchorA.Set(0.0f, 0.0f);
+		localAnchorB.Set(0.0f, 0.0f);
+		length = 1.0f;
+		frequencyHz = 0.0f;
+		dampingRatio = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, and length using the world
+	/// anchors.
+	void Initialize(b2Body* bodyA, b2Body* bodyB,
+					const b2Vec2& anchorA, const b2Vec2& anchorB);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The natural length between the anchor points.
+	float32 length;
+
+	/// The mass-spring-damper frequency in Hertz.
+	float32 frequencyHz;
+
+	/// The damping ratio. 0 = no damping, 1 = critical damping.
+	float32 dampingRatio;
+};
+
+/// A distance joint constrains two points on two bodies
+/// to remain at a fixed distance from each other. You can view
+/// this as a massless, rigid rod.
+class b2DistanceJoint : public b2Joint
+{
+public:
+
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Set/get the natural length.
+	/// Manipulating the length can lead to non-physical behavior when the frequency is zero.
+	void SetLength(float32 length);
+	float32 GetLength() const;
+
+	// Set/get frequency in Hz.
+	void SetFrequency(float32 hz);
+	float32 GetFrequency() const;
+
+	// Set/get damping ratio.
+	void SetDampingRatio(float32 ratio);
+	float32 GetDampingRatio() const;
+
+protected:
+
+	friend class b2Joint;
+	b2DistanceJoint(const b2DistanceJointDef* data);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+	b2Vec2 m_u;
+	float32 m_frequencyHz;
+	float32 m_dampingRatio;
+	float32 m_gamma;
+	float32 m_bias;
+	float32 m_impulse;
+	float32 m_mass;
+	float32 m_length;
+};
+
+inline void b2DistanceJoint::SetLength(float32 length)
+{
+	m_length = length;
+}
+
+inline float32 b2DistanceJoint::GetLength() const
+{
+	return m_length;
+}
+
+inline void b2DistanceJoint::SetFrequency(float32 hz)
+{
+	m_frequencyHz = hz;
+}
+
+inline float32 b2DistanceJoint::GetFrequency() const
+{
+	return m_frequencyHz;
+}
+
+inline void b2DistanceJoint::SetDampingRatio(float32 ratio)
+{
+	m_dampingRatio = ratio;
+}
+
+inline float32 b2DistanceJoint::GetDampingRatio() const
+{
+	return m_dampingRatio;
+}
+
+#endif

+ 99 - 0
include/Box2D/Dynamics/Joints/b2FrictionJoint.h

@@ -0,0 +1,99 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_FRICTION_JOINT_H
+#define B2_FRICTION_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Friction joint definition.
+struct b2FrictionJointDef : public b2JointDef
+{
+	b2FrictionJointDef()
+	{
+		type = e_frictionJoint;
+		localAnchorA.SetZero();
+		localAnchorB.SetZero();
+		maxForce = 0.0f;
+		maxTorque = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, axis, and reference angle using the world
+	/// anchor and world axis.
+	void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
+
+	/// The local anchor point relative to bodyA's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to bodyB's origin.
+	b2Vec2 localAnchorB;
+
+	/// The maximum friction force in N.
+	float32 maxForce;
+
+	/// The maximum friction torque in N-m.
+	float32 maxTorque;
+};
+
+/// Friction joint. This is used for top-down friction.
+/// It provides 2D translational friction and angular friction.
+class b2FrictionJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Set the maximum friction force in N.
+	void SetMaxForce(float32 force);
+
+	/// Get the maximum friction force in N.
+	float32 GetMaxForce() const;
+
+	/// Set the maximum friction torque in N*m.
+	void SetMaxTorque(float32 torque);
+
+	/// Get the maximum friction torque in N*m.
+	float32 GetMaxTorque() const;
+
+protected:
+
+	friend class b2Joint;
+
+	b2FrictionJoint(const b2FrictionJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchorA;
+	b2Vec2 m_localAnchorB;
+
+	b2Mat22 m_linearMass;
+	float32 m_angularMass;
+
+	b2Vec2 m_linearImpulse;
+	float32 m_angularImpulse;
+
+	float32 m_maxForce;
+	float32 m_maxTorque;
+};
+
+#endif

+ 111 - 0
include/Box2D/Dynamics/Joints/b2GearJoint.h

@@ -0,0 +1,111 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_GEAR_JOINT_H
+#define B2_GEAR_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+class b2RevoluteJoint;
+class b2PrismaticJoint;
+
+/// Gear joint definition. This definition requires two existing
+/// revolute or prismatic joints (any combination will work).
+/// The provided joints must attach a dynamic body to a static body.
+struct b2GearJointDef : public b2JointDef
+{
+	b2GearJointDef()
+	{
+		type = e_gearJoint;
+		joint1 = NULL;
+		joint2 = NULL;
+		ratio = 1.0f;
+	}
+
+	/// The first revolute/prismatic joint attached to the gear joint.
+	b2Joint* joint1;
+
+	/// The second revolute/prismatic joint attached to the gear joint.
+	b2Joint* joint2;
+
+	/// The gear ratio.
+	/// @see b2GearJoint for explanation.
+	float32 ratio;
+};
+
+/// A gear joint is used to connect two joints together. Either joint
+/// can be a revolute or prismatic joint. You specify a gear ratio
+/// to bind the motions together:
+/// coordinate1 + ratio * coordinate2 = constant
+/// The ratio can be negative or positive. If one joint is a revolute joint
+/// and the other joint is a prismatic joint, then the ratio will have units
+/// of length or units of 1/length.
+/// @warning The revolute and prismatic joints must be attached to
+/// fixed bodies (which must be body1 on those joints).
+class b2GearJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Set/Get the gear ratio.
+	void SetRatio(float32 ratio);
+	float32 GetRatio() const;
+
+protected:
+
+	friend class b2Joint;
+	b2GearJoint(const b2GearJointDef* data);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Body* m_ground1;
+	b2Body* m_ground2;
+
+	// One of these is NULL.
+	b2RevoluteJoint* m_revolute1;
+	b2PrismaticJoint* m_prismatic1;
+
+	// One of these is NULL.
+	b2RevoluteJoint* m_revolute2;
+	b2PrismaticJoint* m_prismatic2;
+
+	b2Vec2 m_groundAnchor1;
+	b2Vec2 m_groundAnchor2;
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+
+	b2Jacobian m_J;
+
+	float32 m_constant;
+	float32 m_ratio;
+
+	// Effective mass
+	float32 m_mass;
+
+	// Impulse for accumulation/warm starting.
+	float32 m_impulse;
+};
+
+#endif

+ 226 - 0
include/Box2D/Dynamics/Joints/b2Joint.h

@@ -0,0 +1,226 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_JOINT_H
+#define B2_JOINT_H
+
+#include <Box2D/Common/b2Math.h>
+
+class b2Body;
+class b2Joint;
+struct b2TimeStep;
+class b2BlockAllocator;
+
+enum b2JointType
+{
+	e_unknownJoint,
+	e_revoluteJoint,
+	e_prismaticJoint,
+	e_distanceJoint,
+	e_pulleyJoint,
+	e_mouseJoint,
+	e_gearJoint,
+	e_lineJoint,
+    e_weldJoint,
+	e_frictionJoint,
+};
+
+enum b2LimitState
+{
+	e_inactiveLimit,
+	e_atLowerLimit,
+	e_atUpperLimit,
+	e_equalLimits
+};
+
+struct b2Jacobian
+{
+	b2Vec2 linearA;
+	float32 angularA;
+	b2Vec2 linearB;
+	float32 angularB;
+
+	void SetZero();
+	void Set(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2);
+	float32 Compute(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2);
+};
+
+/// A joint edge is used to connect bodies and joints together
+/// in a joint graph where each body is a node and each joint
+/// is an edge. A joint edge belongs to a doubly linked list
+/// maintained in each attached body. Each joint has two joint
+/// nodes, one for each attached body.
+struct b2JointEdge
+{
+	b2Body* other;			///< provides quick access to the other body attached.
+	b2Joint* joint;			///< the joint
+	b2JointEdge* prev;		///< the previous joint edge in the body's joint list
+	b2JointEdge* next;		///< the next joint edge in the body's joint list
+};
+
+/// Joint definitions are used to construct joints.
+struct b2JointDef
+{
+	b2JointDef()
+	{
+		type = e_unknownJoint;
+		userData = NULL;
+		bodyA = NULL;
+		bodyB = NULL;
+		collideConnected = false;
+	}
+
+	/// The joint type is set automatically for concrete joint types.
+	b2JointType type;
+
+	/// Use this to attach application specific data to your joints.
+	void* userData;
+
+	/// The first attached body.
+	b2Body* bodyA;
+
+	/// The second attached body.
+	b2Body* bodyB;
+
+	/// Set this flag to true if the attached bodies should collide.
+	bool collideConnected;
+};
+
+/// The base joint class. Joints are used to constraint two bodies together in
+/// various fashions. Some joints also feature limits and motors.
+class b2Joint
+{
+public:
+
+	/// Get the type of the concrete joint.
+	b2JointType GetType() const;
+
+	/// Get the first body attached to this joint.
+	b2Body* GetBodyA();
+
+	/// Get the second body attached to this joint.
+	b2Body* GetBodyB();
+
+	/// Get the anchor point on bodyA in world coordinates.
+	virtual b2Vec2 GetAnchorA() const = 0;
+
+	/// Get the anchor point on bodyB in world coordinates.
+	virtual b2Vec2 GetAnchorB() const = 0;
+
+	/// Get the reaction force on body2 at the joint anchor in Newtons.
+	virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0;
+
+	/// Get the reaction torque on body2 in N*m.
+	virtual float32 GetReactionTorque(float32 inv_dt) const = 0;
+
+	/// Get the next joint the world joint list.
+	b2Joint* GetNext();
+
+	/// Get the user data pointer.
+	void* GetUserData() const;
+
+	/// Set the user data pointer.
+	void SetUserData(void* data);
+
+	/// Short-cut function to determine if either body is inactive.
+	bool IsActive() const;
+
+protected:
+	friend class b2World;
+	friend class b2Body;
+	friend class b2Island;
+
+	static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator);
+	static void Destroy(b2Joint* joint, b2BlockAllocator* allocator);
+
+	b2Joint(const b2JointDef* def);
+	virtual ~b2Joint() {}
+
+	virtual void InitVelocityConstraints(const b2TimeStep& step) = 0;
+	virtual void SolveVelocityConstraints(const b2TimeStep& step) = 0;
+
+	// This returns true if the position errors are within tolerance.
+	virtual bool SolvePositionConstraints(float32 baumgarte) = 0;
+
+	b2JointType m_type;
+	b2Joint* m_prev;
+	b2Joint* m_next;
+	b2JointEdge m_edgeA;
+	b2JointEdge m_edgeB;
+	b2Body* m_bodyA;
+	b2Body* m_bodyB;
+
+	bool m_islandFlag;
+	bool m_collideConnected;
+
+	void* m_userData;
+
+	// Cache here per time step to reduce cache misses.
+	b2Vec2 m_localCenterA, m_localCenterB;
+	float32 m_invMassA, m_invIA;
+	float32 m_invMassB, m_invIB;
+};
+
+inline void b2Jacobian::SetZero()
+{
+	linearA.SetZero(); angularA = 0.0f;
+	linearB.SetZero(); angularB = 0.0f;
+}
+
+inline void b2Jacobian::Set(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2)
+{
+	linearA = x1; angularA = a1;
+	linearB = x2; angularB = a2;
+}
+
+inline float32 b2Jacobian::Compute(const b2Vec2& x1, float32 a1, const b2Vec2& x2, float32 a2)
+{
+	return b2Dot(linearA, x1) + angularA * a1 + b2Dot(linearB, x2) + angularB * a2;
+}
+
+inline b2JointType b2Joint::GetType() const
+{
+	return m_type;
+}
+
+inline b2Body* b2Joint::GetBodyA()
+{
+	return m_bodyA;
+}
+
+inline b2Body* b2Joint::GetBodyB()
+{
+	return m_bodyB;
+}
+
+inline b2Joint* b2Joint::GetNext()
+{
+	return m_next;
+}
+
+inline void* b2Joint::GetUserData() const
+{
+	return m_userData;
+}
+
+inline void b2Joint::SetUserData(void* data)
+{
+	m_userData = data;
+}
+
+#endif

+ 170 - 0
include/Box2D/Dynamics/Joints/b2LineJoint.h

@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_LINE_JOINT_H
+#define B2_LINE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Line joint definition. This requires defining a line of
+/// motion using an axis and an anchor point. The definition uses local
+/// anchor points and a local axis so that the initial configuration
+/// can violate the constraint slightly. The joint translation is zero
+/// when the local anchor points coincide in world space. Using local
+/// anchors and a local axis helps when saving and loading a game.
+struct b2LineJointDef : public b2JointDef
+{
+	b2LineJointDef()
+	{
+		type = e_lineJoint;
+		localAnchorA.SetZero();
+		localAnchorB.SetZero();
+		localAxisA.Set(1.0f, 0.0f);
+		enableLimit = false;
+		lowerTranslation = 0.0f;
+		upperTranslation = 0.0f;
+		enableMotor = false;
+		maxMotorForce = 0.0f;
+		motorSpeed = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, axis, and reference angle using the world
+	/// anchor and world axis.
+	void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The local translation axis in body1.
+	b2Vec2 localAxisA;
+
+	/// Enable/disable the joint limit.
+	bool enableLimit;
+
+	/// The lower translation limit, usually in meters.
+	float32 lowerTranslation;
+
+	/// The upper translation limit, usually in meters.
+	float32 upperTranslation;
+
+	/// Enable/disable the joint motor.
+	bool enableMotor;
+
+	/// The maximum motor torque, usually in N-m.
+	float32 maxMotorForce;
+
+	/// The desired motor speed in radians per second.
+	float32 motorSpeed;
+};
+
+/// A line joint. This joint provides two degrees of freedom: translation
+/// along an axis fixed in body1 and rotation in the plane. You can use a
+/// joint limit to restrict the range of motion and a joint motor to drive
+/// the motion or to model joint friction.
+class b2LineJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the current joint translation, usually in meters.
+	float32 GetJointTranslation() const;
+
+	/// Get the current joint translation speed, usually in meters per second.
+	float32 GetJointSpeed() const;
+
+	/// Is the joint limit enabled?
+	bool IsLimitEnabled() const;
+
+	/// Enable/disable the joint limit.
+	void EnableLimit(bool flag);
+
+	/// Get the lower joint limit, usually in meters.
+	float32 GetLowerLimit() const;
+
+	/// Get the upper joint limit, usually in meters.
+	float32 GetUpperLimit() const;
+
+	/// Set the joint limits, usually in meters.
+	void SetLimits(float32 lower, float32 upper);
+
+	/// Is the joint motor enabled?
+	bool IsMotorEnabled() const;
+
+	/// Enable/disable the joint motor.
+	void EnableMotor(bool flag);
+
+	/// Set the motor speed, usually in meters per second.
+	void SetMotorSpeed(float32 speed);
+
+	/// Get the motor speed, usually in meters per second.
+	float32 GetMotorSpeed() const;
+
+	/// Set/Get the maximum motor force, usually in N.
+	void SetMaxMotorForce(float32 force);
+	float32 GetMaxMotorForce() const;
+
+	/// Get the current motor force, usually in N.
+	float32 GetMotorForce() const;
+
+protected:
+
+	friend class b2Joint;
+	b2LineJoint(const b2LineJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+	b2Vec2 m_localXAxis1;
+	b2Vec2 m_localYAxis1;
+
+	b2Vec2 m_axis, m_perp;
+	float32 m_s1, m_s2;
+	float32 m_a1, m_a2;
+
+	b2Mat22 m_K;
+	b2Vec2 m_impulse;
+
+	float32 m_motorMass;			// effective mass for motor/limit translational constraint.
+	float32 m_motorImpulse;
+
+	float32 m_lowerTranslation;
+	float32 m_upperTranslation;
+	float32 m_maxMotorForce;
+	float32 m_motorSpeed;
+
+	bool m_enableLimit;
+	bool m_enableMotor;
+	b2LimitState m_limitState;
+};
+
+inline float32 b2LineJoint::GetMotorSpeed() const
+{
+	return m_motorSpeed;
+}
+
+#endif

+ 114 - 0
include/Box2D/Dynamics/Joints/b2MouseJoint.h

@@ -0,0 +1,114 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_MOUSE_JOINT_H
+#define B2_MOUSE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Mouse joint definition. This requires a world target point,
+/// tuning parameters, and the time step.
+struct b2MouseJointDef : public b2JointDef
+{
+	b2MouseJointDef()
+	{
+		type = e_mouseJoint;
+		target.Set(0.0f, 0.0f);
+		maxForce = 0.0f;
+		frequencyHz = 5.0f;
+		dampingRatio = 0.7f;
+	}
+
+	/// The initial world target point. This is assumed
+	/// to coincide with the body anchor initially.
+	b2Vec2 target;
+
+	/// The maximum constraint force that can be exerted
+	/// to move the candidate body. Usually you will express
+	/// as some multiple of the weight (multiplier * mass * gravity).
+	float32 maxForce;
+
+	/// The response speed.
+	float32 frequencyHz;
+
+	/// The damping ratio. 0 = no damping, 1 = critical damping.
+	float32 dampingRatio;
+};
+
+/// A mouse joint is used to make a point on a body track a
+/// specified world point. This a soft constraint with a maximum
+/// force. This allows the constraint to stretch and without
+/// applying huge forces.
+/// NOTE: this joint is not documented in the manual because it was
+/// developed to be used in the testbed. If you want to learn how to
+/// use the mouse joint, look at the testbed.
+class b2MouseJoint : public b2Joint
+{
+public:
+
+	/// Implements b2Joint.
+	b2Vec2 GetAnchorA() const;
+
+	/// Implements b2Joint.
+	b2Vec2 GetAnchorB() const;
+
+	/// Implements b2Joint.
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+
+	/// Implements b2Joint.
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Use this to update the target point.
+	void SetTarget(const b2Vec2& target);
+	const b2Vec2& GetTarget() const;
+
+	/// Set/get the maximum force in Newtons.
+	void SetMaxForce(float32 force);
+	float32 GetMaxForce() const;
+
+	/// Set/get the frequency in Hertz.
+	void SetFrequency(float32 hz);
+	float32 GetFrequency() const;
+
+	/// Set/get the damping ratio (dimensionless).
+	void SetDampingRatio(float32 ratio);
+	float32 GetDampingRatio() const;
+
+protected:
+	friend class b2Joint;
+
+	b2MouseJoint(const b2MouseJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte) { B2_NOT_USED(baumgarte); return true; }
+
+	b2Vec2 m_localAnchor;
+	b2Vec2 m_target;
+	b2Vec2 m_impulse;
+
+	b2Mat22 m_mass;		// effective mass for point-to-point constraint.
+	b2Vec2 m_C;				// position error
+	float32 m_maxForce;
+	float32 m_frequencyHz;
+	float32 m_dampingRatio;
+	float32 m_beta;
+	float32 m_gamma;
+};
+
+#endif

+ 175 - 0
include/Box2D/Dynamics/Joints/b2PrismaticJoint.h

@@ -0,0 +1,175 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_PRISMATIC_JOINT_H
+#define B2_PRISMATIC_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Prismatic joint definition. This requires defining a line of
+/// motion using an axis and an anchor point. The definition uses local
+/// anchor points and a local axis so that the initial configuration
+/// can violate the constraint slightly. The joint translation is zero
+/// when the local anchor points coincide in world space. Using local
+/// anchors and a local axis helps when saving and loading a game.
+/// @warning at least one body should by dynamic with a non-fixed rotation.
+struct b2PrismaticJointDef : public b2JointDef
+{
+	b2PrismaticJointDef()
+	{
+		type = e_prismaticJoint;
+		localAnchorA.SetZero();
+		localAnchorB.SetZero();
+		localAxis1.Set(1.0f, 0.0f);
+		referenceAngle = 0.0f;
+		enableLimit = false;
+		lowerTranslation = 0.0f;
+		upperTranslation = 0.0f;
+		enableMotor = false;
+		maxMotorForce = 0.0f;
+		motorSpeed = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, axis, and reference angle using the world
+	/// anchor and world axis.
+	void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The local translation axis in body1.
+	b2Vec2 localAxis1;
+
+	/// The constrained angle between the bodies: body2_angle - body1_angle.
+	float32 referenceAngle;
+
+	/// Enable/disable the joint limit.
+	bool enableLimit;
+
+	/// The lower translation limit, usually in meters.
+	float32 lowerTranslation;
+
+	/// The upper translation limit, usually in meters.
+	float32 upperTranslation;
+
+	/// Enable/disable the joint motor.
+	bool enableMotor;
+
+	/// The maximum motor torque, usually in N-m.
+	float32 maxMotorForce;
+
+	/// The desired motor speed in radians per second.
+	float32 motorSpeed;
+};
+
+/// A prismatic joint. This joint provides one degree of freedom: translation
+/// along an axis fixed in body1. Relative rotation is prevented. You can
+/// use a joint limit to restrict the range of motion and a joint motor to
+/// drive the motion or to model joint friction.
+class b2PrismaticJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the current joint translation, usually in meters.
+	float32 GetJointTranslation() const;
+
+	/// Get the current joint translation speed, usually in meters per second.
+	float32 GetJointSpeed() const;
+
+	/// Is the joint limit enabled?
+	bool IsLimitEnabled() const;
+
+	/// Enable/disable the joint limit.
+	void EnableLimit(bool flag);
+
+	/// Get the lower joint limit, usually in meters.
+	float32 GetLowerLimit() const;
+
+	/// Get the upper joint limit, usually in meters.
+	float32 GetUpperLimit() const;
+
+	/// Set the joint limits, usually in meters.
+	void SetLimits(float32 lower, float32 upper);
+
+	/// Is the joint motor enabled?
+	bool IsMotorEnabled() const;
+
+	/// Enable/disable the joint motor.
+	void EnableMotor(bool flag);
+
+	/// Set the motor speed, usually in meters per second.
+	void SetMotorSpeed(float32 speed);
+
+	/// Get the motor speed, usually in meters per second.
+	float32 GetMotorSpeed() const;
+
+	/// Set the maximum motor force, usually in N.
+	void SetMaxMotorForce(float32 force);
+
+	/// Get the current motor force, usually in N.
+	float32 GetMotorForce() const;
+
+protected:
+	friend class b2Joint;
+	friend class b2GearJoint;
+	b2PrismaticJoint(const b2PrismaticJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+	b2Vec2 m_localXAxis1;
+	b2Vec2 m_localYAxis1;
+	float32 m_refAngle;
+
+	b2Vec2 m_axis, m_perp;
+	float32 m_s1, m_s2;
+	float32 m_a1, m_a2;
+
+	b2Mat33 m_K;
+	b2Vec3 m_impulse;
+
+	float32 m_motorMass;			// effective mass for motor/limit translational constraint.
+	float32 m_motorImpulse;
+
+	float32 m_lowerTranslation;
+	float32 m_upperTranslation;
+	float32 m_maxMotorForce;
+	float32 m_motorSpeed;
+	
+	bool m_enableLimit;
+	bool m_enableMotor;
+	b2LimitState m_limitState;
+};
+
+inline float32 b2PrismaticJoint::GetMotorSpeed() const
+{
+	return m_motorSpeed;
+}
+
+#endif

+ 148 - 0
include/Box2D/Dynamics/Joints/b2PulleyJoint.h

@@ -0,0 +1,148 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_PULLEY_JOINT_H
+#define B2_PULLEY_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+const float32 b2_minPulleyLength = 2.0f;
+
+/// Pulley joint definition. This requires two ground anchors,
+/// two dynamic body anchor points, max lengths for each side,
+/// and a pulley ratio.
+struct b2PulleyJointDef : public b2JointDef
+{
+	b2PulleyJointDef()
+	{
+		type = e_pulleyJoint;
+		groundAnchorA.Set(-1.0f, 1.0f);
+		groundAnchorB.Set(1.0f, 1.0f);
+		localAnchorA.Set(-1.0f, 0.0f);
+		localAnchorB.Set(1.0f, 0.0f);
+		lengthA = 0.0f;
+		maxLengthA = 0.0f;
+		lengthB = 0.0f;
+		maxLengthB = 0.0f;
+		ratio = 1.0f;
+		collideConnected = true;
+	}
+
+	/// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.
+	void Initialize(b2Body* bodyA, b2Body* bodyB,
+					const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB,
+					const b2Vec2& anchorA, const b2Vec2& anchorB,
+					float32 ratio);
+
+	/// The first ground anchor in world coordinates. This point never moves.
+	b2Vec2 groundAnchorA;
+
+	/// The second ground anchor in world coordinates. This point never moves.
+	b2Vec2 groundAnchorB;
+
+	/// The local anchor point relative to bodyA's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to bodyB's origin.
+	b2Vec2 localAnchorB;
+
+	/// The a reference length for the segment attached to bodyA.
+	float32 lengthA;
+
+	/// The maximum length of the segment attached to bodyA.
+	float32 maxLengthA;
+
+	/// The a reference length for the segment attached to bodyB.
+	float32 lengthB;
+
+	/// The maximum length of the segment attached to bodyB.
+	float32 maxLengthB;
+
+	/// The pulley ratio, used to simulate a block-and-tackle.
+	float32 ratio;
+};
+
+/// The pulley joint is connected to two bodies and two fixed ground points.
+/// The pulley supports a ratio such that:
+/// length1 + ratio * length2 <= constant
+/// Yes, the force transmitted is scaled by the ratio.
+/// The pulley also enforces a maximum length limit on both sides. This is
+/// useful to prevent one side of the pulley hitting the top.
+class b2PulleyJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the first ground anchor.
+	b2Vec2 GetGroundAnchorA() const;
+
+	/// Get the second ground anchor.
+	b2Vec2 GetGroundAnchorB() const;
+
+	/// Get the current length of the segment attached to body1.
+	float32 GetLength1() const;
+
+	/// Get the current length of the segment attached to body2.
+	float32 GetLength2() const;
+
+	/// Get the pulley ratio.
+	float32 GetRatio() const;
+
+protected:
+
+	friend class b2Joint;
+	b2PulleyJoint(const b2PulleyJointDef* data);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_groundAnchor1;
+	b2Vec2 m_groundAnchor2;
+	b2Vec2 m_localAnchor1;
+	b2Vec2 m_localAnchor2;
+
+	b2Vec2 m_u1;
+	b2Vec2 m_u2;
+	
+	float32 m_constant;
+	float32 m_ratio;
+	
+	float32 m_maxLength1;
+	float32 m_maxLength2;
+
+	// Effective masses
+	float32 m_pulleyMass;
+	float32 m_limitMass1;
+	float32 m_limitMass2;
+
+	// Impulses for accumulation/warm starting.
+	float32 m_impulse;
+	float32 m_limitImpulse1;
+	float32 m_limitImpulse2;
+
+	b2LimitState m_state;
+	b2LimitState m_limitState1;
+	b2LimitState m_limitState2;
+};
+
+#endif

+ 174 - 0
include/Box2D/Dynamics/Joints/b2RevoluteJoint.h

@@ -0,0 +1,174 @@
+/*
+* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_REVOLUTE_JOINT_H
+#define B2_REVOLUTE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Revolute joint definition. This requires defining an
+/// anchor point where the bodies are joined. The definition
+/// uses local anchor points so that the initial configuration
+/// can violate the constraint slightly. You also need to
+/// specify the initial relative angle for joint limits. This
+/// helps when saving and loading a game.
+/// The local anchor points are measured from the body's origin
+/// rather than the center of mass because:
+/// 1. you might not know where the center of mass will be.
+/// 2. if you add/remove shapes from a body and recompute the mass,
+///    the joints will be broken.
+struct b2RevoluteJointDef : public b2JointDef
+{
+	b2RevoluteJointDef()
+	{
+		type = e_revoluteJoint;
+		localAnchorA.Set(0.0f, 0.0f);
+		localAnchorB.Set(0.0f, 0.0f);
+		referenceAngle = 0.0f;
+		lowerAngle = 0.0f;
+		upperAngle = 0.0f;
+		maxMotorTorque = 0.0f;
+		motorSpeed = 0.0f;
+		enableLimit = false;
+		enableMotor = false;
+	}
+
+	/// Initialize the bodies, anchors, and reference angle using a world
+	/// anchor point.
+	void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The body2 angle minus body1 angle in the reference state (radians).
+	float32 referenceAngle;
+
+	/// A flag to enable joint limits.
+	bool enableLimit;
+
+	/// The lower angle for the joint limit (radians).
+	float32 lowerAngle;
+
+	/// The upper angle for the joint limit (radians).
+	float32 upperAngle;
+
+	/// A flag to enable the joint motor.
+	bool enableMotor;
+
+	/// The desired motor speed. Usually in radians per second.
+	float32 motorSpeed;
+
+	/// The maximum motor torque used to achieve the desired motor speed.
+	/// Usually in N-m.
+	float32 maxMotorTorque;
+};
+
+/// A revolute joint constrains two bodies to share a common point while they
+/// are free to rotate about the point. The relative rotation about the shared
+/// point is the joint angle. You can limit the relative rotation with
+/// a joint limit that specifies a lower and upper angle. You can use a motor
+/// to drive the relative rotation about the shared point. A maximum motor torque
+/// is provided so that infinite forces are not generated.
+class b2RevoluteJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+	/// Get the current joint angle in radians.
+	float32 GetJointAngle() const;
+
+	/// Get the current joint angle speed in radians per second.
+	float32 GetJointSpeed() const;
+
+	/// Is the joint limit enabled?
+	bool IsLimitEnabled() const;
+
+	/// Enable/disable the joint limit.
+	void EnableLimit(bool flag);
+
+	/// Get the lower joint limit in radians.
+	float32 GetLowerLimit() const;
+
+	/// Get the upper joint limit in radians.
+	float32 GetUpperLimit() const;
+
+	/// Set the joint limits in radians.
+	void SetLimits(float32 lower, float32 upper);
+
+	/// Is the joint motor enabled?
+	bool IsMotorEnabled() const;
+
+	/// Enable/disable the joint motor.
+	void EnableMotor(bool flag);
+
+	/// Set the motor speed in radians per second.
+	void SetMotorSpeed(float32 speed);
+
+	/// Get the motor speed in radians per second.
+	float32 GetMotorSpeed() const;
+
+	/// Set the maximum motor torque, usually in N-m.
+	void SetMaxMotorTorque(float32 torque);
+
+	/// Get the current motor torque, usually in N-m.
+	float32 GetMotorTorque() const;
+
+protected:
+	
+	friend class b2Joint;
+	friend class b2GearJoint;
+
+	b2RevoluteJoint(const b2RevoluteJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchor1;	// relative
+	b2Vec2 m_localAnchor2;
+	b2Vec3 m_impulse;
+	float32 m_motorImpulse;
+
+	b2Mat33 m_mass;			// effective mass for point-to-point constraint.
+	float32 m_motorMass;	// effective mass for motor/limit angular constraint.
+	
+	bool m_enableMotor;
+	float32 m_maxMotorTorque;
+	float32 m_motorSpeed;
+
+	bool m_enableLimit;
+	float32 m_referenceAngle;
+	float32 m_lowerAngle;
+	float32 m_upperAngle;
+	b2LimitState m_limitState;
+};
+
+inline float32 b2RevoluteJoint::GetMotorSpeed() const
+{
+	return m_motorSpeed;
+}
+
+#endif

+ 82 - 0
include/Box2D/Dynamics/Joints/b2WeldJoint.h

@@ -0,0 +1,82 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_WELD_JOINT_H
+#define B2_WELD_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Weld joint definition. You need to specify local anchor points
+/// where they are attached and the relative body angle. The position
+/// of the anchor points is important for computing the reaction torque.
+struct b2WeldJointDef : public b2JointDef
+{
+	b2WeldJointDef()
+	{
+		type = e_weldJoint;
+		localAnchorA.Set(0.0f, 0.0f);
+		localAnchorB.Set(0.0f, 0.0f);
+		referenceAngle = 0.0f;
+	}
+
+	/// Initialize the bodies, anchors, and reference angle using a world
+	/// anchor point.
+	void Initialize(b2Body* body1, b2Body* body2, const b2Vec2& anchor);
+
+	/// The local anchor point relative to body1's origin.
+	b2Vec2 localAnchorA;
+
+	/// The local anchor point relative to body2's origin.
+	b2Vec2 localAnchorB;
+
+	/// The body2 angle minus body1 angle in the reference state (radians).
+	float32 referenceAngle;
+};
+
+/// A weld joint essentially glues two bodies together. A weld joint may
+/// distort somewhat because the island constraint solver is approximate.
+class b2WeldJoint : public b2Joint
+{
+public:
+	b2Vec2 GetAnchorA() const;
+	b2Vec2 GetAnchorB() const;
+
+	b2Vec2 GetReactionForce(float32 inv_dt) const;
+	float32 GetReactionTorque(float32 inv_dt) const;
+
+protected:
+
+	friend class b2Joint;
+
+	b2WeldJoint(const b2WeldJointDef* def);
+
+	void InitVelocityConstraints(const b2TimeStep& step);
+	void SolveVelocityConstraints(const b2TimeStep& step);
+
+	bool SolvePositionConstraints(float32 baumgarte);
+
+	b2Vec2 m_localAnchorA;
+	b2Vec2 m_localAnchorB;
+	float32 m_referenceAngle;
+
+	b2Vec3 m_impulse;
+
+	b2Mat33 m_mass;
+};
+
+#endif

+ 802 - 0
include/Box2D/Dynamics/b2Body.h

@@ -0,0 +1,802 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_BODY_H
+#define B2_BODY_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+#include <memory>
+
+class b2Fixture;
+class b2Joint;
+class b2Contact;
+class b2Controller;
+class b2World;
+struct b2FixtureDef;
+struct b2JointEdge;
+struct b2ContactEdge;
+
+/// The body type.
+/// static: zero mass, zero velocity, may be manually moved
+/// kinematic: zero mass, non-zero velocity set by user, moved by solver
+/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver
+enum b2BodyType
+{
+	b2_staticBody = 0,
+	b2_kinematicBody,
+	b2_dynamicBody,
+};
+
+/// A body definition holds all the data needed to construct a rigid body.
+/// You can safely re-use body definitions. Shapes are added to a body after construction.
+struct b2BodyDef
+{
+	/// This constructor sets the body definition default values.
+	b2BodyDef()
+	{
+		userData = NULL;
+		position.Set(0.0f, 0.0f);
+		angle = 0.0f;
+		linearVelocity.Set(0.0f, 0.0f);
+		angularVelocity = 0.0f;
+		linearDamping = 0.0f;
+		angularDamping = 0.0f;
+		allowSleep = true;
+		awake = true;
+		fixedRotation = false;
+		bullet = false;
+		type = b2_staticBody;
+		active = true;
+		inertiaScale = 1.0f;
+	}
+
+	/// The body type: static, kinematic, or dynamic.
+	/// Note: if a dynamic body would have zero mass, the mass is set to one.
+	b2BodyType type;
+
+	/// The world position of the body. Avoid creating bodies at the origin
+	/// since this can lead to many overlapping shapes.
+	b2Vec2 position;
+
+	/// The world angle of the body in radians.
+	float32 angle;
+
+	/// The linear velocity of the body's origin in world co-ordinates.
+	b2Vec2 linearVelocity;
+
+	/// The angular velocity of the body.
+	float32 angularVelocity;
+
+	/// Linear damping is use to reduce the linear velocity. The damping parameter
+	/// can be larger than 1.0f but the damping effect becomes sensitive to the
+	/// time step when the damping parameter is large.
+	float32 linearDamping;
+
+	/// Angular damping is use to reduce the angular velocity. The damping parameter
+	/// can be larger than 1.0f but the damping effect becomes sensitive to the
+	/// time step when the damping parameter is large.
+	float32 angularDamping;
+
+	/// Set this flag to false if this body should never fall asleep. Note that
+	/// this increases CPU usage.
+	bool allowSleep;
+
+	/// Is this body initially awake or sleeping?
+	bool awake;
+
+	/// Should this body be prevented from rotating? Useful for characters.
+	bool fixedRotation;
+
+	/// Is this a fast moving body that should be prevented from tunneling through
+	/// other moving bodies? Note that all bodies are prevented from tunneling through
+	/// kinematic and static bodies. This setting is only considered on dynamic bodies.
+	/// @warning You should use this flag sparingly since it increases processing time.
+	bool bullet;
+
+	/// Does this body start out active?
+	bool active;
+
+	/// Use this to store application specific body data.
+	void* userData;
+
+	/// Experimental: scales the inertia tensor.
+	float32 inertiaScale;
+};
+
+/// A rigid body. These are created via b2World::CreateBody.
+class b2Body
+{
+public:
+	/// Creates a fixture and attach it to this body. Use this function if you need
+	/// to set some fixture parameters, like friction. Otherwise you can create the
+	/// fixture directly from a shape.
+	/// If the density is non-zero, this function automatically updates the mass of the body.
+	/// Contacts are not created until the next time step.
+	/// @param def the fixture definition.
+	/// @warning This function is locked during callbacks.
+	b2Fixture* CreateFixture(const b2FixtureDef* def);
+
+	/// Creates a fixture from a shape and attach it to this body.
+	/// This is a convenience function. Use b2FixtureDef if you need to set parameters
+	/// like friction, restitution, user data, or filtering.
+	/// If the density is non-zero, this function automatically updates the mass of the body.
+	/// @param shape the shape to be cloned.
+	/// @param density the shape density (set to zero for static bodies).
+	/// @warning This function is locked during callbacks.
+	b2Fixture* CreateFixture(const b2Shape* shape, float32 density);
+
+	/// Destroy a fixture. This removes the fixture from the broad-phase and
+	/// destroys all contacts associated with this fixture. This will
+	/// automatically adjust the mass of the body if the body is dynamic and the
+	/// fixture has positive density.
+	/// All fixtures attached to a body are implicitly destroyed when the body is destroyed.
+	/// @param fixture the fixture to be removed.
+	/// @warning This function is locked during callbacks.
+	void DestroyFixture(b2Fixture* fixture);
+
+	/// Set the position of the body's origin and rotation.
+	/// This breaks any contacts and wakes the other bodies.
+	/// Manipulating a body's transform may cause non-physical behavior.
+	/// @param position the world position of the body's local origin.
+	/// @param angle the world rotation in radians.
+	void SetTransform(const b2Vec2& position, float32 angle);
+
+	/// Get the body transform for the body's origin.
+	/// @return the world transform of the body's origin.
+	const b2Transform& GetTransform() const;
+
+	/// Get the world body origin position.
+	/// @return the world position of the body's origin.
+	const b2Vec2& GetPosition() const;
+
+	/// Get the angle in radians.
+	/// @return the current world rotation angle in radians.
+	float32 GetAngle() const;
+
+	/// Get the world position of the center of mass.
+	const b2Vec2& GetWorldCenter() const;
+
+	/// Get the local position of the center of mass.
+	const b2Vec2& GetLocalCenter() const;
+
+	/// Set the linear velocity of the center of mass.
+	/// @param v the new linear velocity of the center of mass.
+	void SetLinearVelocity(const b2Vec2& v);
+
+	/// Get the linear velocity of the center of mass.
+	/// @return the linear velocity of the center of mass.
+	b2Vec2 GetLinearVelocity() const;
+
+	/// Set the angular velocity.
+	/// @param omega the new angular velocity in radians/second.
+	void SetAngularVelocity(float32 omega);
+
+	/// Get the angular velocity.
+	/// @return the angular velocity in radians/second.
+	float32 GetAngularVelocity() const;
+
+	/// Apply a force at a world point. If the force is not
+	/// applied at the center of mass, it will generate a torque and
+	/// affect the angular velocity. This wakes up the body.
+	/// @param force the world force vector, usually in Newtons (N).
+	/// @param point the world position of the point of application.
+	void ApplyForce(const b2Vec2& force, const b2Vec2& point);
+
+	/// Apply a torque. This affects the angular velocity
+	/// without affecting the linear velocity of the center of mass.
+	/// This wakes up the body.
+	/// @param torque about the z-axis (out of the screen), usually in N-m.
+	void ApplyTorque(float32 torque);
+
+	/// Apply an impulse at a point. This immediately modifies the velocity.
+	/// It also modifies the angular velocity if the point of application
+	/// is not at the center of mass. This wakes up the body.
+	/// @param impulse the world impulse vector, usually in N-seconds or kg-m/s.
+	/// @param point the world position of the point of application.
+	void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point);
+
+	/// Apply an angular impulse.
+	/// @param impulse the angular impulse in units of kg*m*m/s
+	void ApplyAngularImpulse(float32 impulse);
+
+	/// Get the total mass of the body.
+	/// @return the mass, usually in kilograms (kg).
+	float32 GetMass() const;
+
+	/// Get the rotational inertia of the body about the local origin.
+	/// @return the rotational inertia, usually in kg-m^2.
+	float32 GetInertia() const;
+
+	/// Get the mass data of the body.
+	/// @return a struct containing the mass, inertia and center of the body.
+	void GetMassData(b2MassData* data) const;
+
+	/// Set the mass properties to override the mass properties of the fixtures.
+	/// Note that this changes the center of mass position.
+	/// Note that creating or destroying fixtures can also alter the mass.
+	/// This function has no effect if the body isn't dynamic.
+	/// @param massData the mass properties.
+	void SetMassData(const b2MassData* data);
+
+	/// This resets the mass properties to the sum of the mass properties of the fixtures.
+	/// This normally does not need to be called unless you called SetMassData to override
+	/// the mass and you later want to reset the mass.
+	void ResetMassData();
+
+	/// Get the world coordinates of a point given the local coordinates.
+	/// @param localPoint a point on the body measured relative the the body's origin.
+	/// @return the same point expressed in world coordinates.
+	b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const;
+
+	/// Get the world coordinates of a vector given the local coordinates.
+	/// @param localVector a vector fixed in the body.
+	/// @return the same vector expressed in world coordinates.
+	b2Vec2 GetWorldVector(const b2Vec2& localVector) const;
+
+	/// Gets a local point relative to the body's origin given a world point.
+	/// @param a point in world coordinates.
+	/// @return the corresponding local point relative to the body's origin.
+	b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const;
+
+	/// Gets a local vector given a world vector.
+	/// @param a vector in world coordinates.
+	/// @return the corresponding local vector.
+	b2Vec2 GetLocalVector(const b2Vec2& worldVector) const;
+
+	/// Get the world linear velocity of a world point attached to this body.
+	/// @param a point in world coordinates.
+	/// @return the world velocity of a point.
+	b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const;
+
+	/// Get the world velocity of a local point.
+	/// @param a point in local coordinates.
+	/// @return the world velocity of a point.
+	b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const;
+
+	/// Get the linear damping of the body.
+	float32 GetLinearDamping() const;
+
+	/// Set the linear damping of the body.
+	void SetLinearDamping(float32 linearDamping);
+
+	/// Get the angular damping of the body.
+	float32 GetAngularDamping() const;
+
+	/// Set the angular damping of the body.
+	void SetAngularDamping(float32 angularDamping);
+
+	/// Set the type of this body. This may alter the mass and velocity.
+	void SetType(b2BodyType type);
+
+	/// Get the type of this body.
+	b2BodyType GetType() const;
+
+	/// Should this body be treated like a bullet for continuous collision detection?
+	void SetBullet(bool flag);
+
+	/// Is this body treated like a bullet for continuous collision detection?
+	bool IsBullet() const;
+
+	/// You can disable sleeping on this body. If you disable sleeping, the
+	/// body will be woken.
+	void SetSleepingAllowed(bool flag);
+
+	/// Is this body allowed to sleep
+	bool IsSleepingAllowed() const;
+
+	/// Set the sleep state of the body. A sleeping body has very
+	/// low CPU cost.
+	/// @param flag set to true to put body to sleep, false to wake it.
+	void SetAwake(bool flag);
+
+	/// Get the sleeping state of this body.
+	/// @return true if the body is sleeping.
+	bool IsAwake() const;
+
+	/// Set the active state of the body. An inactive body is not
+	/// simulated and cannot be collided with or woken up.
+	/// If you pass a flag of true, all fixtures will be added to the
+	/// broad-phase.
+	/// If you pass a flag of false, all fixtures will be removed from
+	/// the broad-phase and all contacts will be destroyed.
+	/// Fixtures and joints are otherwise unaffected. You may continue
+	/// to create/destroy fixtures and joints on inactive bodies.
+	/// Fixtures on an inactive body are implicitly inactive and will
+	/// not participate in collisions, ray-casts, or queries.
+	/// Joints connected to an inactive body are implicitly inactive.
+	/// An inactive body is still owned by a b2World object and remains
+	/// in the body list.
+	void SetActive(bool flag);
+
+	/// Get the active state of the body.
+	bool IsActive() const;
+
+	/// Set this body to have fixed rotation. This causes the mass
+	/// to be reset.
+	void SetFixedRotation(bool flag);
+
+	/// Does this body have fixed rotation?
+	bool IsFixedRotation() const;
+
+	/// Get the list of all fixtures attached to this body.
+	b2Fixture* GetFixtureList();
+	const b2Fixture* GetFixtureList() const;
+
+	/// Get the list of all joints attached to this body.
+	b2JointEdge* GetJointList();
+	const b2JointEdge* GetJointList() const;
+
+	/// Get the list of all contacts attached to this body.
+	/// @warning this list changes during the time step and you may
+	/// miss some collisions if you don't use b2ContactListener.
+	b2ContactEdge* GetContactList();
+	const b2ContactEdge* GetContactList() const;
+
+	/// Get the next body in the world's body list.
+	b2Body* GetNext();
+	const b2Body* GetNext() const;
+
+	/// Get the user data pointer that was provided in the body definition.
+	void* GetUserData() const;
+
+	/// Set the user data. Use this to store your application specific data.
+	void SetUserData(void* data);
+
+	/// Get the parent world of this body.
+	b2World* GetWorld();
+	const b2World* GetWorld() const;
+
+private:
+
+	friend class b2World;
+	friend class b2Island;
+	friend class b2ContactManager;
+	friend class b2ContactSolver;
+	friend class b2TOISolver;
+	
+	friend class b2DistanceJoint;
+	friend class b2GearJoint;
+	friend class b2LineJoint;
+	friend class b2MouseJoint;
+	friend class b2PrismaticJoint;
+	friend class b2PulleyJoint;
+	friend class b2RevoluteJoint;
+	friend class b2WeldJoint;
+	friend class b2FrictionJoint;
+
+	// m_flags
+	enum
+	{
+		e_islandFlag		= 0x0001,
+		e_awakeFlag			= 0x0002,
+		e_autoSleepFlag		= 0x0004,
+		e_bulletFlag		= 0x0008,
+		e_fixedRotationFlag	= 0x0010,
+		e_activeFlag		= 0x0020,
+		e_toiFlag			= 0x0040,
+	};
+
+	b2Body(const b2BodyDef* bd, b2World* world);
+	~b2Body();
+
+	void SynchronizeFixtures();
+	void SynchronizeTransform();
+
+	// This is used to prevent connected bodies from colliding.
+	// It may lie, depending on the collideConnected flag.
+	bool ShouldCollide(const b2Body* other) const;
+
+	void Advance(float32 t);
+
+	b2BodyType m_type;
+
+	uint16 m_flags;
+
+	int32 m_islandIndex;
+
+	b2Transform m_xf;		// the body origin transform
+	b2Sweep m_sweep;		// the swept motion for CCD
+
+	b2Vec2 m_linearVelocity;
+	float32 m_angularVelocity;
+
+	b2Vec2 m_force;
+	float32 m_torque;
+
+	b2World* m_world;
+	b2Body* m_prev;
+	b2Body* m_next;
+
+	b2Fixture* m_fixtureList;
+	int32 m_fixtureCount;
+
+	b2JointEdge* m_jointList;
+	b2ContactEdge* m_contactList;
+
+	float32 m_mass, m_invMass;
+
+	// Rotational inertia about the center of mass.
+	float32 m_I, m_invI;
+
+	float32 m_linearDamping;
+	float32 m_angularDamping;
+
+	float32 m_sleepTime;
+
+	void* m_userData;
+};
+
+inline b2BodyType b2Body::GetType() const
+{
+	return m_type;
+}
+
+inline const b2Transform& b2Body::GetTransform() const
+{
+	return m_xf;
+}
+
+inline const b2Vec2& b2Body::GetPosition() const
+{
+	return m_xf.position;
+}
+
+inline float32 b2Body::GetAngle() const
+{
+	return m_sweep.a;
+}
+
+inline const b2Vec2& b2Body::GetWorldCenter() const
+{
+	return m_sweep.c;
+}
+
+inline const b2Vec2& b2Body::GetLocalCenter() const
+{
+	return m_sweep.localCenter;
+}
+
+inline void b2Body::SetLinearVelocity(const b2Vec2& v)
+{
+	if (m_type == b2_staticBody)
+	{
+		return;
+	}
+
+	if (b2Dot(v,v) > 0.0f)
+	{
+		SetAwake(true);
+	}
+
+	m_linearVelocity = v;
+}
+
+inline b2Vec2 b2Body::GetLinearVelocity() const
+{
+	return m_linearVelocity;
+}
+
+inline void b2Body::SetAngularVelocity(float32 w)
+{
+	if (m_type == b2_staticBody)
+	{
+		return;
+	}
+
+	if (w * w > 0.0f)
+	{
+		SetAwake(true);
+	}
+
+	m_angularVelocity = w;
+}
+
+inline float32 b2Body::GetAngularVelocity() const
+{
+	return m_angularVelocity;
+}
+
+inline float32 b2Body::GetMass() const
+{
+	return m_mass;
+}
+
+inline float32 b2Body::GetInertia() const
+{
+	return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
+}
+
+inline void b2Body::GetMassData(b2MassData* data) const
+{
+	data->mass = m_mass;
+	data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
+	data->center = m_sweep.localCenter;
+}
+
+inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const
+{
+	return b2Mul(m_xf, localPoint);
+}
+
+inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const
+{
+	return b2Mul(m_xf.R, localVector);
+}
+
+inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const
+{
+	return b2MulT(m_xf, worldPoint);
+}
+
+inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const
+{
+	return b2MulT(m_xf.R, worldVector);
+}
+
+inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const
+{
+	return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c);
+}
+
+inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const
+{
+	return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint));
+}
+
+inline float32 b2Body::GetLinearDamping() const
+{
+	return m_linearDamping;
+}
+
+inline void b2Body::SetLinearDamping(float32 linearDamping)
+{
+	m_linearDamping = linearDamping;
+}
+
+inline float32 b2Body::GetAngularDamping() const
+{
+	return m_angularDamping;
+}
+
+inline void b2Body::SetAngularDamping(float32 angularDamping)
+{
+	m_angularDamping = angularDamping;
+}
+
+inline void b2Body::SetBullet(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_bulletFlag;
+	}
+	else
+	{
+		m_flags &= ~e_bulletFlag;
+	}
+}
+
+inline bool b2Body::IsBullet() const
+{
+	return (m_flags & e_bulletFlag) == e_bulletFlag;
+}
+
+inline void b2Body::SetAwake(bool flag)
+{
+	if (flag)
+	{
+		if ((m_flags & e_awakeFlag) == 0)
+		{
+			m_flags |= e_awakeFlag;
+			m_sleepTime = 0.0f;
+		}
+	}
+	else
+	{
+		m_flags &= ~e_awakeFlag;
+		m_sleepTime = 0.0f;
+		m_linearVelocity.SetZero();
+		m_angularVelocity = 0.0f;
+		m_force.SetZero();
+		m_torque = 0.0f;
+	}
+}
+
+inline bool b2Body::IsAwake() const
+{
+	return (m_flags & e_awakeFlag) == e_awakeFlag;
+}
+
+inline bool b2Body::IsActive() const
+{
+	return (m_flags & e_activeFlag) == e_activeFlag;
+}
+
+inline void b2Body::SetFixedRotation(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_fixedRotationFlag;
+	}
+	else
+	{
+		m_flags &= ~e_fixedRotationFlag;
+	}
+
+	ResetMassData();
+}
+
+inline bool b2Body::IsFixedRotation() const
+{
+	return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag;
+}
+
+inline void b2Body::SetSleepingAllowed(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_autoSleepFlag;
+	}
+	else
+	{
+		m_flags &= ~e_autoSleepFlag;
+		SetAwake(true);
+	}
+}
+
+inline bool b2Body::IsSleepingAllowed() const
+{
+	return (m_flags & e_autoSleepFlag) == e_autoSleepFlag;
+}
+
+inline b2Fixture* b2Body::GetFixtureList()
+{
+	return m_fixtureList;
+}
+
+inline const b2Fixture* b2Body::GetFixtureList() const
+{
+	return m_fixtureList;
+}
+
+inline b2JointEdge* b2Body::GetJointList()
+{
+	return m_jointList;
+}
+
+inline const b2JointEdge* b2Body::GetJointList() const
+{
+	return m_jointList;
+}
+
+inline b2ContactEdge* b2Body::GetContactList()
+{
+	return m_contactList;
+}
+
+inline const b2ContactEdge* b2Body::GetContactList() const
+{
+	return m_contactList;
+}
+
+inline b2Body* b2Body::GetNext()
+{
+	return m_next;
+}
+
+inline const b2Body* b2Body::GetNext() const
+{
+	return m_next;
+}
+
+inline void b2Body::SetUserData(void* data)
+{
+	m_userData = data;
+}
+
+inline void* b2Body::GetUserData() const
+{
+	return m_userData;
+}
+
+inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point)
+{
+	if (m_type != b2_dynamicBody)
+	{
+		return;
+	}
+
+	if (IsAwake() == false)
+	{
+		SetAwake(true);
+	}
+
+	m_force += force;
+	m_torque += b2Cross(point - m_sweep.c, force);
+}
+
+inline void b2Body::ApplyTorque(float32 torque)
+{
+	if (m_type != b2_dynamicBody)
+	{
+		return;
+	}
+
+	if (IsAwake() == false)
+	{
+		SetAwake(true);
+	}
+
+	m_torque += torque;
+}
+
+inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point)
+{
+	if (m_type != b2_dynamicBody)
+	{
+		return;
+	}
+
+	if (IsAwake() == false)
+	{
+		SetAwake(true);
+	}
+	m_linearVelocity += m_invMass * impulse;
+	m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse);
+}
+
+inline void b2Body::ApplyAngularImpulse(float32 impulse)
+{
+	if (m_type != b2_dynamicBody)
+	{
+		return;
+	}
+
+	if (IsAwake() == false)
+	{
+		SetAwake(true);
+	}
+	m_angularVelocity += m_invI * impulse;
+}
+
+inline void b2Body::SynchronizeTransform()
+{
+	m_xf.R.Set(m_sweep.a);
+	m_xf.position = m_sweep.c - b2Mul(m_xf.R, m_sweep.localCenter);
+}
+
+inline void b2Body::Advance(float32 t)
+{
+	// Advance to the new safe time.
+	m_sweep.Advance(t);
+	m_sweep.c = m_sweep.c0;
+	m_sweep.a = m_sweep.a0;
+	SynchronizeTransform();
+}
+
+inline b2World* b2Body::GetWorld()
+{
+	return m_world;
+}
+
+inline const b2World* b2Body::GetWorld() const
+{
+	return m_world;
+}
+
+#endif

+ 52 - 0
include/Box2D/Dynamics/b2ContactManager.h

@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_CONTACT_MANAGER_H
+#define B2_CONTACT_MANAGER_H
+
+#include <Box2D/Collision/b2BroadPhase.h>
+
+class b2Contact;
+class b2ContactFilter;
+class b2ContactListener;
+class b2BlockAllocator;
+
+// Delegate of b2World.
+class b2ContactManager
+{
+public:
+	b2ContactManager();
+
+	// Broad-phase callback.
+	void AddPair(void* proxyUserDataA, void* proxyUserDataB);
+
+	void FindNewContacts();
+
+	void Destroy(b2Contact* c);
+
+	void Collide();
+            
+	b2BroadPhase m_broadPhase;
+	b2Contact* m_contactList;
+	int32 m_contactCount;
+	b2ContactFilter* m_contactFilter;
+	b2ContactListener* m_contactListener;
+	b2BlockAllocator* m_allocator;
+};
+
+#endif

+ 326 - 0
include/Box2D/Dynamics/b2Fixture.h

@@ -0,0 +1,326 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_FIXTURE_H
+#define B2_FIXTURE_H
+
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+class b2BlockAllocator;
+class b2Body;
+class b2BroadPhase;
+
+/// This holds contact filtering data.
+struct b2Filter
+{
+	/// The collision category bits. Normally you would just set one bit.
+	uint16 categoryBits;
+
+	/// The collision mask bits. This states the categories that this
+	/// shape would accept for collision.
+	uint16 maskBits;
+
+	/// Collision groups allow a certain group of objects to never collide (negative)
+	/// or always collide (positive). Zero means no collision group. Non-zero group
+	/// filtering always wins against the mask bits.
+	int16 groupIndex;
+};
+
+/// A fixture definition is used to create a fixture. This class defines an
+/// abstract fixture definition. You can reuse fixture definitions safely.
+struct b2FixtureDef
+{
+	/// The constructor sets the default fixture definition values.
+	b2FixtureDef()
+	{
+		shape = NULL;
+		userData = NULL;
+		friction = 0.2f;
+		restitution = 0.0f;
+		density = 0.0f;
+		filter.categoryBits = 0x0001;
+		filter.maskBits = 0xFFFF;
+		filter.groupIndex = 0;
+		isSensor = false;
+	}
+
+	virtual ~b2FixtureDef() {}
+
+	/// The shape, this must be set. The shape will be cloned, so you
+	/// can create the shape on the stack.
+	const b2Shape* shape;
+
+	/// Use this to store application specific fixture data.
+	void* userData;
+
+	/// The friction coefficient, usually in the range [0,1].
+	float32 friction;
+
+	/// The restitution (elasticity) usually in the range [0,1].
+	float32 restitution;
+
+	/// The density, usually in kg/m^2.
+	float32 density;
+
+	/// A sensor shape collects contact information but never generates a collision
+	/// response.
+	bool isSensor;
+
+	/// Contact filtering data.
+	b2Filter filter;
+};
+
+
+/// A fixture is used to attach a shape to a body for collision detection. A fixture
+/// inherits its transform from its parent. Fixtures hold additional non-geometric data
+/// such as friction, collision filters, etc.
+/// Fixtures are created via b2Body::CreateFixture.
+/// @warning you cannot reuse fixtures.
+class b2Fixture
+{
+public:
+	/// Get the type of the child shape. You can use this to down cast to the concrete shape.
+	/// @return the shape type.
+	b2Shape::Type GetType() const;
+
+	/// Get the child shape. You can modify the child shape, however you should not change the
+	/// number of vertices because this will crash some collision caching mechanisms.
+	/// Manipulating the shape may lead to non-physical behavior.
+	b2Shape* GetShape();
+	const b2Shape* GetShape() const;
+
+	/// Set if this fixture is a sensor.
+	void SetSensor(bool sensor);
+
+	/// Is this fixture a sensor (non-solid)?
+	/// @return the true if the shape is a sensor.
+	bool IsSensor() const;
+
+	/// Set the contact filtering data. This will not update contacts until the next time
+	/// step when either parent body is active and awake.
+	void SetFilterData(const b2Filter& filter);
+
+	/// Get the contact filtering data.
+	const b2Filter& GetFilterData() const;
+
+	/// Get the parent body of this fixture. This is NULL if the fixture is not attached.
+	/// @return the parent body.
+	b2Body* GetBody();
+	const b2Body* GetBody() const;
+
+	/// Get the next fixture in the parent body's fixture list.
+	/// @return the next shape.
+	b2Fixture* GetNext();
+	const b2Fixture* GetNext() const;
+
+	/// Get the user data that was assigned in the fixture definition. Use this to
+	/// store your application specific data.
+	void* GetUserData() const;
+
+	/// Set the user data. Use this to store your application specific data.
+	void SetUserData(void* data);
+
+	/// Test a point for containment in this fixture.
+	/// @param xf the shape world transform.
+	/// @param p a point in world coordinates.
+	bool TestPoint(const b2Vec2& p) const;
+
+	/// Cast a ray against this shape.
+	/// @param output the ray-cast results.
+	/// @param input the ray-cast input parameters.
+	bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const;
+
+	/// Get the mass data for this fixture. The mass data is based on the density and
+	/// the shape. The rotational inertia is about the shape's origin. This operation
+	/// may be expensive.
+	void GetMassData(b2MassData* massData) const;
+
+	/// Set the density of this fixture. This will _not_ automatically adjust the mass
+	/// of the body. You must call b2Body::ResetMassData to update the body's mass.
+	void SetDensity(float32 density);
+
+	/// Get the density of this fixture.
+	float32 GetDensity() const;
+
+	/// Get the coefficient of friction.
+	float32 GetFriction() const;
+
+	/// Set the coefficient of friction.
+	void SetFriction(float32 friction);
+
+	/// Get the coefficient of restitution.
+	float32 GetRestitution() const;
+
+	/// Set the coefficient of restitution.
+	void SetRestitution(float32 restitution);
+
+	/// Get the fixture's AABB. This AABB may be enlarge and/or stale.
+	/// If you need a more accurate AABB, compute it using the shape and
+	/// the body transform.
+	const b2AABB& GetAABB() const;
+
+protected:
+
+	friend class b2Body;
+	friend class b2World;
+	friend class b2Contact;
+	friend class b2ContactManager;
+
+	b2Fixture();
+	~b2Fixture();
+
+	// We need separation create/destroy functions from the constructor/destructor because
+	// the destructor cannot access the allocator (no destructor arguments allowed by C++).
+	void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def);
+	void Destroy(b2BlockAllocator* allocator);
+
+	// These support body activation/deactivation.
+	void CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf);
+	void DestroyProxy(b2BroadPhase* broadPhase);
+
+	void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2);
+
+	b2AABB m_aabb;
+
+	float32 m_density;
+
+	b2Fixture* m_next;
+	b2Body* m_body;
+
+	b2Shape* m_shape;
+
+	float32 m_friction;
+	float32 m_restitution;
+
+	int32 m_proxyId;
+	b2Filter m_filter;
+
+	bool m_isSensor;
+
+	void* m_userData;
+};
+
+inline b2Shape::Type b2Fixture::GetType() const
+{
+	return m_shape->GetType();
+}
+
+inline b2Shape* b2Fixture::GetShape()
+{
+	return m_shape;
+}
+
+inline const b2Shape* b2Fixture::GetShape() const
+{
+	return m_shape;
+}
+
+inline bool b2Fixture::IsSensor() const
+{
+	return m_isSensor;
+}
+
+inline const b2Filter& b2Fixture::GetFilterData() const
+{
+	return m_filter;
+}
+
+inline void* b2Fixture::GetUserData() const
+{
+	return m_userData;
+}
+
+inline void b2Fixture::SetUserData(void* data)
+{
+	m_userData = data;
+}
+
+inline b2Body* b2Fixture::GetBody()
+{
+	return m_body;
+}
+
+inline const b2Body* b2Fixture::GetBody() const
+{
+	return m_body;
+}
+
+inline b2Fixture* b2Fixture::GetNext()
+{
+	return m_next;
+}
+
+inline const b2Fixture* b2Fixture::GetNext() const
+{
+	return m_next;
+}
+
+inline void b2Fixture::SetDensity(float32 density)
+{
+	b2Assert(b2IsValid(density) && density >= 0.0f);
+	m_density = density;
+}
+
+inline float32 b2Fixture::GetDensity() const
+{
+	return m_density;
+}
+
+inline float32 b2Fixture::GetFriction() const
+{
+	return m_friction;
+}
+
+inline void b2Fixture::SetFriction(float32 friction)
+{
+	m_friction = friction;
+}
+
+inline float32 b2Fixture::GetRestitution() const
+{
+	return m_restitution;
+}
+
+inline void b2Fixture::SetRestitution(float32 restitution)
+{
+	m_restitution = restitution;
+}
+
+inline bool b2Fixture::TestPoint(const b2Vec2& p) const
+{
+	return m_shape->TestPoint(m_body->GetTransform(), p);
+}
+
+inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const
+{
+	return m_shape->RayCast(output, input, m_body->GetTransform());
+}
+
+inline void b2Fixture::GetMassData(b2MassData* massData) const
+{
+	m_shape->ComputeMass(massData, m_density);
+}
+
+inline const b2AABB& b2Fixture::GetAABB() const
+{
+	return m_aabb;
+}
+
+#endif

+ 105 - 0
include/Box2D/Dynamics/b2Island.h

@@ -0,0 +1,105 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_ISLAND_H
+#define B2_ISLAND_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+
+class b2Contact;
+class b2Joint;
+class b2StackAllocator;
+class b2ContactListener;
+struct b2ContactConstraint;
+
+/// This is an internal structure.
+struct b2Position
+{
+	b2Vec2 x;
+	float32 a;
+};
+
+/// This is an internal structure.
+struct b2Velocity
+{
+	b2Vec2 v;
+	float32 w;
+};
+
+/// This is an internal class.
+class b2Island
+{
+public:
+	b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity,
+			b2StackAllocator* allocator, b2ContactListener* listener);
+	~b2Island();
+
+	void Clear()
+	{
+		m_bodyCount = 0;
+		m_contactCount = 0;
+		m_jointCount = 0;
+	}
+
+	void Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep);
+
+	void Add(b2Body* body)
+	{
+		b2Assert(m_bodyCount < m_bodyCapacity);
+		body->m_islandIndex = m_bodyCount;
+		m_bodies[m_bodyCount++] = body;
+	}
+
+	void Add(b2Contact* contact)
+	{
+		b2Assert(m_contactCount < m_contactCapacity);
+		m_contacts[m_contactCount++] = contact;
+	}
+
+	void Add(b2Joint* joint)
+	{
+		b2Assert(m_jointCount < m_jointCapacity);
+		m_joints[m_jointCount++] = joint;
+	}
+
+	void Report(const b2ContactConstraint* constraints);
+
+	b2StackAllocator* m_allocator;
+	b2ContactListener* m_listener;
+
+	b2Body** m_bodies;
+	b2Contact** m_contacts;
+	b2Joint** m_joints;
+
+	b2Position* m_positions;
+	b2Velocity* m_velocities;
+
+	int32 m_bodyCount;
+	int32 m_jointCount;
+	int32 m_contactCount;
+
+	int32 m_bodyCapacity;
+	int32 m_contactCapacity;
+	int32 m_jointCapacity;
+
+	int32 m_positionIterationCount;
+};
+
+#endif

+ 35 - 0
include/Box2D/Dynamics/b2TimeStep.h

@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_TIME_STEP_H
+#define B2_TIME_STEP_H
+
+#include <Box2D/Common/b2Settings.h>
+
+/// This is an internal structure.
+struct b2TimeStep
+{
+	float32 dt;			// time step
+	float32 inv_dt;		// inverse time step (0 if dt == 0).
+	float32 dtRatio;	// dt * inv_dt0
+	int32 velocityIterations;
+	int32 positionIterations;
+	bool warmStarting;
+};
+
+#endif

+ 285 - 0
include/Box2D/Dynamics/b2World.h

@@ -0,0 +1,285 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_WORLD_H
+#define B2_WORLD_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Common/b2StackAllocator.h>
+#include <Box2D/Dynamics/b2ContactManager.h>
+#include <Box2D/Dynamics/b2WorldCallbacks.h>
+
+struct b2AABB;
+struct b2BodyDef;
+struct b2JointDef;
+struct b2TimeStep;
+class b2Body;
+class b2Fixture;
+class b2Joint;
+
+/// The world class manages all physics entities, dynamic simulation,
+/// and asynchronous queries. The world also contains efficient memory
+/// management facilities.
+class b2World
+{
+public:
+	/// Construct a world object.
+	/// @param gravity the world gravity vector.
+	/// @param doSleep improve performance by not simulating inactive bodies.
+	b2World(const b2Vec2& gravity, bool doSleep);
+
+	/// Destruct the world. All physics entities are destroyed and all heap memory is released.
+	~b2World();
+
+	/// Register a destruction listener. The listener is owned by you and must
+	/// remain in scope.
+	void SetDestructionListener(b2DestructionListener* listener);
+
+	/// Register a contact filter to provide specific control over collision.
+	/// Otherwise the default filter is used (b2_defaultFilter). The listener is
+	/// owned by you and must remain in scope. 
+	void SetContactFilter(b2ContactFilter* filter);
+
+	/// Register a contact event listener. The listener is owned by you and must
+	/// remain in scope.
+	void SetContactListener(b2ContactListener* listener);
+
+	/// Register a routine for debug drawing. The debug draw functions are called
+	/// inside with b2World::DrawDebugData method. The debug draw object is owned
+	/// by you and must remain in scope.
+	void SetDebugDraw(b2DebugDraw* debugDraw);
+
+	/// Create a rigid body given a definition. No reference to the definition
+	/// is retained.
+	/// @warning This function is locked during callbacks.
+	b2Body* CreateBody(const b2BodyDef* def);
+
+	/// Destroy a rigid body given a definition. No reference to the definition
+	/// is retained. This function is locked during callbacks.
+	/// @warning This automatically deletes all associated shapes and joints.
+	/// @warning This function is locked during callbacks.
+	void DestroyBody(b2Body* body);
+
+	/// Create a joint to constrain bodies together. No reference to the definition
+	/// is retained. This may cause the connected bodies to cease colliding.
+	/// @warning This function is locked during callbacks.
+	b2Joint* CreateJoint(const b2JointDef* def);
+
+	/// Destroy a joint. This may cause the connected bodies to begin colliding.
+	/// @warning This function is locked during callbacks.
+	void DestroyJoint(b2Joint* joint);
+
+	/// Take a time step. This performs collision detection, integration,
+	/// and constraint solution.
+	/// @param timeStep the amount of time to simulate, this should not vary.
+	/// @param velocityIterations for the velocity constraint solver.
+	/// @param positionIterations for the position constraint solver.
+	void Step(	float32 timeStep,
+				int32 velocityIterations,
+				int32 positionIterations);
+
+	/// Call this after you are done with time steps to clear the forces. You normally
+	/// call this after each call to Step, unless you are performing sub-steps. By default,
+	/// forces will be automatically cleared, so you don't need to call this function.
+	/// @see SetAutoClearForces
+	void ClearForces();
+
+	/// Call this to draw shapes and other debug draw data.
+	void DrawDebugData();
+
+	/// Query the world for all fixtures that potentially overlap the
+	/// provided AABB.
+	/// @param callback a user implemented callback class.
+	/// @param aabb the query box.
+	void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const;
+
+	/// Ray-cast the world for all fixtures in the path of the ray. Your callback
+	/// controls whether you get the closest point, any point, or n-points.
+	/// The ray-cast ignores shapes that contain the starting point.
+	/// @param callback a user implemented callback class.
+	/// @param point1 the ray starting point
+	/// @param point2 the ray ending point
+	void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const;
+
+	/// Get the world body list. With the returned body, use b2Body::GetNext to get
+	/// the next body in the world list. A NULL body indicates the end of the list.
+	/// @return the head of the world body list.
+	b2Body* GetBodyList();
+
+	/// Get the world joint list. With the returned joint, use b2Joint::GetNext to get
+	/// the next joint in the world list. A NULL joint indicates the end of the list.
+	/// @return the head of the world joint list.
+	b2Joint* GetJointList();
+
+	/// Get the world contact list. With the returned contact, use b2Contact::GetNext to get
+	/// the next contact in the world list. A NULL contact indicates the end of the list.
+	/// @return the head of the world contact list.
+	/// @warning contacts are 
+	b2Contact* GetContactList();
+
+	/// Enable/disable warm starting. For testing.
+	void SetWarmStarting(bool flag) { m_warmStarting = flag; }
+
+	/// Enable/disable continuous physics. For testing.
+	void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }
+
+	/// Get the number of broad-phase proxies.
+	int32 GetProxyCount() const;
+
+	/// Get the number of bodies.
+	int32 GetBodyCount() const;
+
+	/// Get the number of joints.
+	int32 GetJointCount() const;
+
+	/// Get the number of contacts (each may have 0 or more contact points).
+	int32 GetContactCount() const;
+
+	/// Change the global gravity vector.
+	void SetGravity(const b2Vec2& gravity);
+	
+	/// Get the global gravity vector.
+	b2Vec2 GetGravity() const;
+
+	/// Is the world locked (in the middle of a time step).
+	bool IsLocked() const;
+
+	/// Set flag to control automatic clearing of forces after each time step.
+	void SetAutoClearForces(bool flag);
+
+	/// Get the flag that controls automatic clearing of forces after each time step.
+	bool GetAutoClearForces() const;
+
+private:
+
+	// m_flags
+	enum
+	{
+		e_newFixture	= 0x0001,
+		e_locked		= 0x0002,
+		e_clearForces	= 0x0004,
+	};
+
+	friend class b2Body;
+	friend class b2ContactManager;
+	friend class b2Controller;
+
+	void Solve(const b2TimeStep& step);
+	void SolveTOI();
+	void SolveTOI(b2Body* body);
+
+	void DrawJoint(b2Joint* joint);
+	void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color);
+
+	b2BlockAllocator m_blockAllocator;
+	b2StackAllocator m_stackAllocator;
+
+	int32 m_flags;
+
+	b2ContactManager m_contactManager;
+
+	b2Body* m_bodyList;
+	b2Joint* m_jointList;
+
+	int32 m_bodyCount;
+	int32 m_jointCount;
+
+	b2Vec2 m_gravity;
+	bool m_allowSleep;
+
+	b2Body* m_groundBody;
+
+	b2DestructionListener* m_destructionListener;
+	b2DebugDraw* m_debugDraw;
+
+	// This is used to compute the time step ratio to
+	// support a variable time step.
+	float32 m_inv_dt0;
+
+	// This is for debugging the solver.
+	bool m_warmStarting;
+
+	// This is for debugging the solver.
+	bool m_continuousPhysics;
+};
+
+inline b2Body* b2World::GetBodyList()
+{
+	return m_bodyList;
+}
+
+inline b2Joint* b2World::GetJointList()
+{
+	return m_jointList;
+}
+
+inline b2Contact* b2World::GetContactList()
+{
+	return m_contactManager.m_contactList;
+}
+
+inline int32 b2World::GetBodyCount() const
+{
+	return m_bodyCount;
+}
+
+inline int32 b2World::GetJointCount() const
+{
+	return m_jointCount;
+}
+
+inline int32 b2World::GetContactCount() const
+{
+	return m_contactManager.m_contactCount;
+}
+
+inline void b2World::SetGravity(const b2Vec2& gravity)
+{
+	m_gravity = gravity;
+}
+
+inline b2Vec2 b2World::GetGravity() const
+{
+	return m_gravity;
+}
+
+inline bool b2World::IsLocked() const
+{
+	return (m_flags & e_locked) == e_locked;
+}
+
+inline void b2World::SetAutoClearForces(bool flag)
+{
+	if (flag)
+	{
+		m_flags |= e_clearForces;
+	}
+	else
+	{
+		m_flags &= ~e_clearForces;
+	}
+}
+
+/// Get the flag that controls automatic clearing of forces after each time step.
+inline bool b2World::GetAutoClearForces() const
+{
+	return (m_flags & e_clearForces) == e_clearForces;
+}
+
+#endif

+ 217 - 0
include/Box2D/Dynamics/b2WorldCallbacks.h

@@ -0,0 +1,217 @@
+/*
+* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
+*
+* This software is provided 'as-is', without any express or implied
+* warranty.  In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_WORLD_CALLBACKS_H
+#define B2_WORLD_CALLBACKS_H
+
+#include <Box2D/Common/b2Settings.h>
+
+struct b2Vec2;
+struct b2Transform;
+class b2Fixture;
+class b2Body;
+class b2Joint;
+class b2Contact;
+struct b2ContactPoint;
+struct b2ContactResult;
+struct b2Manifold;
+
+/// Joints and fixtures are destroyed when their associated
+/// body is destroyed. Implement this listener so that you
+/// may nullify references to these joints and shapes.
+class b2DestructionListener
+{
+public:
+	virtual ~b2DestructionListener() {}
+
+	/// Called when any joint is about to be destroyed due
+	/// to the destruction of one of its attached bodies.
+	virtual void SayGoodbye(b2Joint* joint) = 0;
+
+	/// Called when any fixture is about to be destroyed due
+	/// to the destruction of its parent body.
+	virtual void SayGoodbye(b2Fixture* fixture) = 0;
+};
+
+/// Implement this class to provide collision filtering. In other words, you can implement
+/// this class if you want finer control over contact creation.
+class b2ContactFilter
+{
+public:
+	virtual ~b2ContactFilter() {}
+
+	/// Return true if contact calculations should be performed between these two shapes.
+	/// @warning for performance reasons this is only called when the AABBs begin to overlap.
+	virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB);
+};
+
+/// Contact impulses for reporting. Impulses are used instead of forces because
+/// sub-step forces may approach infinity for rigid body collisions. These
+/// match up one-to-one with the contact points in b2Manifold.
+struct b2ContactImpulse
+{
+	float32 normalImpulses[b2_maxManifoldPoints];
+	float32 tangentImpulses[b2_maxManifoldPoints];
+};
+
+/// Implement this class to get contact information. You can use these results for
+/// things like sounds and game logic. You can also get contact results by
+/// traversing the contact lists after the time step. However, you might miss
+/// some contacts because continuous physics leads to sub-stepping.
+/// Additionally you may receive multiple callbacks for the same contact in a
+/// single time step.
+/// You should strive to make your callbacks efficient because there may be
+/// many callbacks per time step.
+/// @warning You cannot create/destroy Box2D entities inside these callbacks.
+class b2ContactListener
+{
+public:
+	virtual ~b2ContactListener() {}
+
+	/// Called when two fixtures begin to touch.
+	virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); }
+
+	/// Called when two fixtures cease to touch.
+	virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); }
+
+	/// This is called after a contact is updated. This allows you to inspect a
+	/// contact before it goes to the solver. If you are careful, you can modify the
+	/// contact manifold (e.g. disable contact).
+	/// A copy of the old manifold is provided so that you can detect changes.
+	/// Note: this is called only for awake bodies.
+	/// Note: this is called even when the number of contact points is zero.
+	/// Note: this is not called for sensors.
+	/// Note: if you set the number of contact points to zero, you will not
+	/// get an EndContact callback. However, you may get a BeginContact callback
+	/// the next step.
+	virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
+	{
+		B2_NOT_USED(contact);
+		B2_NOT_USED(oldManifold);
+	}
+
+	/// This lets you inspect a contact after the solver is finished. This is useful
+	/// for inspecting impulses.
+	/// Note: the contact manifold does not include time of impact impulses, which can be
+	/// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
+	/// in a separate data structure.
+	/// Note: this is only called for contacts that are touching, solid, and awake.
+	virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
+	{
+		B2_NOT_USED(contact);
+		B2_NOT_USED(impulse);
+	}
+};
+
+/// Callback class for AABB queries.
+/// See b2World::Query
+class b2QueryCallback
+{
+public:
+	virtual ~b2QueryCallback() {}
+
+	/// Called for each fixture found in the query AABB.
+	/// @return false to terminate the query.
+	virtual bool ReportFixture(b2Fixture* fixture) = 0;
+};
+
+/// Callback class for ray casts.
+/// See b2World::RayCast
+class b2RayCastCallback
+{
+public:
+	virtual ~b2RayCastCallback() {}
+
+	/// Called for each fixture found in the query. You control how the ray cast
+	/// proceeds by returning a float:
+	/// return -1: ignore this fixture and continue
+	/// return 0: terminate the ray cast
+	/// return fraction: clip the ray to this point
+	/// return 1: don't clip the ray and continue
+	/// @param fixture the fixture hit by the ray
+	/// @param point the point of initial intersection
+	/// @param normal the normal vector at the point of intersection
+	/// @return -1 to filter, 0 to terminate, fraction to clip the ray for
+	/// closest hit, 1 to continue
+	virtual float32 ReportFixture(	b2Fixture* fixture, const b2Vec2& point,
+									const b2Vec2& normal, float32 fraction) = 0;
+};
+
+/// Color for debug drawing. Each value has the range [0,1].
+struct b2Color
+{
+	b2Color() {}
+	b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {}
+	void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; }
+	float32 r, g, b;
+};
+
+/// Implement and register this class with a b2World to provide debug drawing of physics
+/// entities in your game.
+class b2DebugDraw
+{
+public:
+	b2DebugDraw();
+
+	virtual ~b2DebugDraw() {}
+
+	enum
+	{
+		e_shapeBit				= 0x0001, ///< draw shapes
+		e_jointBit				= 0x0002, ///< draw joint connections
+		e_aabbBit				= 0x0004, ///< draw axis aligned bounding boxes
+		e_pairBit				= 0x0008, ///< draw broad-phase pairs
+		e_centerOfMassBit		= 0x0010, ///< draw center of mass frame
+	};
+
+	/// Set the drawing flags.
+	void SetFlags(uint32 flags);
+
+	/// Get the drawing flags.
+	uint32 GetFlags() const;
+	
+	/// Append flags to the current flags.
+	void AppendFlags(uint32 flags);
+
+	/// Clear flags from the current flags.
+	void ClearFlags(uint32 flags);
+
+	/// Draw a closed polygon provided in CCW order.
+	virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
+
+	/// Draw a solid closed polygon provided in CCW order.
+	virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
+
+	/// Draw a circle.
+	virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0;
+	
+	/// Draw a solid circle.
+	virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0;
+	
+	/// Draw a line segment.
+	virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0;
+
+	/// Draw a transform. Choose your own length scale.
+	/// @param xf a transform.
+	virtual void DrawTransform(const b2Transform& xf) = 0;
+
+protected:
+	uint32 m_drawFlags;
+};
+
+#endif

+ 2 - 0
include/Polycode.h

@@ -103,6 +103,8 @@
 		#else
 			#ifdef RPI_CORE
 				#include "polycode/core/PolyRPICore.h"
+			#elif defined(__ANDROID__)
+				#include "polycode/core/PolyAndroidCore.h"
 			#else
 				#ifdef EMSCRIPTEN
 					#include "polycode/core/PolyEmscriptenCore.h"

+ 2774 - 0
include/SLES/OpenSLES.h

@@ -0,0 +1,2774 @@
+/*
+ * Copyright (c) 2007-2009 The Khronos Group Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and /or associated documentation files (the "Materials "), to
+ * deal in the Materials without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Materials, and to permit persons to whom the Materials are
+ * furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Materials.
+ *
+ * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE
+ * MATERIALS.
+ *
+ * OpenSLES.h - OpenSL ES version 1.0.1
+ *
+ */
+
+/****************************************************************************/
+/* NOTE: This file is a standard OpenSL ES header file and should not be    */
+/* modified in any way.                                                     */
+/****************************************************************************/
+
+#ifndef OPENSL_ES_H_
+#define OPENSL_ES_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "OpenSLES_Platform.h"
+
+
+/*****************************************************************************/
+/* Common types, structures, and defines                                */
+/*****************************************************************************/
+
+#ifndef _KHRONOS_KEYS_
+#define _KHRONOS_KEYS_
+
+#define KHRONOS_TITLE "KhronosTitle"
+#define KHRONOS_ALBUM "KhronosAlbum"
+#define KHRONOS_TRACK_NUMBER "KhronosTrackNumber"
+#define KHRONOS_ARTIST "KhronosArtist"
+#define KHRONOS_GENRE "KhronosGenre"
+#define KHRONOS_YEAR "KhronosYear"
+#define KHRONOS_COMMENT "KhronosComment"
+#define KHRONOS_ARTIST_URL "KhronosArtistURL"
+#define KHRONOS_CONTENT_URL "KhronosContentURL"
+#define KHRONOS_RATING "KhronosRating"
+#define KHRONOS_ALBUM_ART "KhronosAlbumArt"
+#define KHRONOS_COPYRIGHT "KhronosCopyright"
+
+#endif
+
+
+/* remap common types to SL types for clarity */
+typedef sl_int8_t              SLint8;          /* 8 bit signed integer  */
+typedef sl_uint8_t             SLuint8;         /* 8 bit unsigned integer */
+typedef sl_int16_t             SLint16;         /* 16 bit signed integer */
+typedef sl_uint16_t            SLuint16;        /* 16 bit unsigned integer */
+typedef sl_int32_t             SLint32;           /* 32 bit signed integer */
+typedef sl_uint32_t            SLuint32;          /* 32 bit unsigned integer */
+
+typedef SLuint32                    SLboolean;
+#define SL_BOOLEAN_FALSE            ((SLboolean) 0x00000000)
+#define SL_BOOLEAN_TRUE             ((SLboolean) 0x00000001)
+
+typedef SLuint8						SLchar;			/* UTF-8 is to be used */
+typedef SLint16						SLmillibel;
+typedef SLuint32					SLmillisecond;
+typedef SLuint32					SLmilliHertz;
+typedef SLint32						SLmillimeter;
+typedef SLint32						SLmillidegree;
+typedef SLint16						SLpermille;
+typedef SLuint32					SLmicrosecond;
+typedef SLuint32					SLresult;
+
+#define SL_MILLIBEL_MAX 	((SLmillibel) 0x7FFF)
+#define SL_MILLIBEL_MIN 	((SLmillibel) (-SL_MILLIBEL_MAX-1))
+
+#define SL_MILLIHERTZ_MAX	((SLmilliHertz) 0xFFFFFFFF)
+#define SL_MILLIMETER_MAX	((SLmillimeter) 0x7FFFFFFF)
+
+/** Interface ID defined as a UUID */
+typedef const struct SLInterfaceID_ {
+    SLuint32 time_low;
+    SLuint16 time_mid;
+    SLuint16 time_hi_and_version;
+    SLuint16 clock_seq;
+    SLuint8  node[6];
+} * SLInterfaceID;
+
+/* Forward declaration for the object interface */
+struct SLObjectItf_;
+
+typedef const struct SLObjectItf_ * const * SLObjectItf;
+
+/* Objects ID's */
+
+#define SL_OBJECTID_ENGINE			((SLuint32) 0x00001001)
+#define SL_OBJECTID_LEDDEVICE		((SLuint32) 0x00001002)
+#define SL_OBJECTID_VIBRADEVICE		((SLuint32) 0x00001003)
+#define SL_OBJECTID_AUDIOPLAYER		((SLuint32) 0x00001004)
+#define SL_OBJECTID_AUDIORECORDER	((SLuint32) 0x00001005)
+#define SL_OBJECTID_MIDIPLAYER		((SLuint32) 0x00001006)
+#define SL_OBJECTID_LISTENER		((SLuint32) 0x00001007)
+#define SL_OBJECTID_3DGROUP			((SLuint32) 0x00001008)
+#define SL_OBJECTID_OUTPUTMIX		((SLuint32) 0x00001009)
+#define SL_OBJECTID_METADATAEXTRACTOR	((SLuint32) 0x0000100A)
+
+
+/* SL Profiles */
+
+#define SL_PROFILES_PHONE	((SLuint16) 0x0001)
+#define SL_PROFILES_MUSIC	((SLuint16) 0x0002)
+#define SL_PROFILES_GAME	((SLuint16) 0x0004)
+
+/* Types of voices supported by the system */
+
+#define SL_VOICETYPE_2D_AUDIO		((SLuint16) 0x0001)
+#define SL_VOICETYPE_MIDI			((SLuint16) 0x0002)
+#define SL_VOICETYPE_3D_AUDIO 		((SLuint16) 0x0004)
+#define SL_VOICETYPE_3D_MIDIOUTPUT 	((SLuint16) 0x0008)
+
+/* Convenient macros representing various different priority levels, for use with the SetPriority method */
+
+#define SL_PRIORITY_LOWEST		((SLint32) (-0x7FFFFFFF-1))
+#define SL_PRIORITY_VERYLOW		((SLint32) -0x60000000)
+#define SL_PRIORITY_LOW			((SLint32) -0x40000000)
+#define SL_PRIORITY_BELOWNORMAL	((SLint32) -0x20000000)
+#define SL_PRIORITY_NORMAL		((SLint32) 0x00000000)
+#define SL_PRIORITY_ABOVENORMAL	((SLint32) 0x20000000)
+#define SL_PRIORITY_HIGH		((SLint32) 0x40000000)
+#define SL_PRIORITY_VERYHIGH	((SLint32) 0x60000000)
+#define SL_PRIORITY_HIGHEST	((SLint32) 0x7FFFFFFF)
+
+
+/** These macros list the various sample formats that are possible on audio input and output devices. */
+
+#define SL_PCMSAMPLEFORMAT_FIXED_8	((SLuint16) 0x0008)
+#define SL_PCMSAMPLEFORMAT_FIXED_16	((SLuint16) 0x0010)
+#define SL_PCMSAMPLEFORMAT_FIXED_20 	((SLuint16) 0x0014)
+#define SL_PCMSAMPLEFORMAT_FIXED_24	((SLuint16) 0x0018)
+#define SL_PCMSAMPLEFORMAT_FIXED_28 	((SLuint16) 0x001C)
+#define SL_PCMSAMPLEFORMAT_FIXED_32	((SLuint16) 0x0020)
+
+
+/** These macros specify the commonly used sampling rates (in milliHertz) supported by most audio I/O devices. */
+
+#define SL_SAMPLINGRATE_8		((SLuint32) 8000000)
+#define SL_SAMPLINGRATE_11_025	((SLuint32) 11025000)
+#define SL_SAMPLINGRATE_12		((SLuint32) 12000000)
+#define SL_SAMPLINGRATE_16		((SLuint32) 16000000)
+#define SL_SAMPLINGRATE_22_05	((SLuint32) 22050000)
+#define SL_SAMPLINGRATE_24		((SLuint32) 24000000)
+#define SL_SAMPLINGRATE_32		((SLuint32) 32000000)
+#define SL_SAMPLINGRATE_44_1	((SLuint32) 44100000)
+#define SL_SAMPLINGRATE_48		((SLuint32) 48000000)
+#define SL_SAMPLINGRATE_64		((SLuint32) 64000000)
+#define SL_SAMPLINGRATE_88_2	((SLuint32) 88200000)
+#define SL_SAMPLINGRATE_96		((SLuint32) 96000000)
+#define SL_SAMPLINGRATE_192	((SLuint32) 192000000)
+
+#define SL_SPEAKER_FRONT_LEFT			((SLuint32) 0x00000001)
+#define SL_SPEAKER_FRONT_RIGHT			((SLuint32) 0x00000002)
+#define SL_SPEAKER_FRONT_CENTER			((SLuint32) 0x00000004)
+#define SL_SPEAKER_LOW_FREQUENCY			((SLuint32) 0x00000008)
+#define SL_SPEAKER_BACK_LEFT			((SLuint32) 0x00000010)
+#define SL_SPEAKER_BACK_RIGHT			((SLuint32) 0x00000020)
+#define SL_SPEAKER_FRONT_LEFT_OF_CENTER	((SLuint32) 0x00000040)
+#define SL_SPEAKER_FRONT_RIGHT_OF_CENTER	((SLuint32) 0x00000080)
+#define SL_SPEAKER_BACK_CENTER			((SLuint32) 0x00000100)
+#define SL_SPEAKER_SIDE_LEFT			((SLuint32) 0x00000200)
+#define SL_SPEAKER_SIDE_RIGHT			((SLuint32) 0x00000400)
+#define SL_SPEAKER_TOP_CENTER			((SLuint32) 0x00000800)
+#define SL_SPEAKER_TOP_FRONT_LEFT		((SLuint32) 0x00001000)
+#define SL_SPEAKER_TOP_FRONT_CENTER		((SLuint32) 0x00002000)
+#define SL_SPEAKER_TOP_FRONT_RIGHT		((SLuint32) 0x00004000)
+#define SL_SPEAKER_TOP_BACK_LEFT			((SLuint32) 0x00008000)
+#define SL_SPEAKER_TOP_BACK_CENTER		((SLuint32) 0x00010000)
+#define SL_SPEAKER_TOP_BACK_RIGHT		((SLuint32) 0x00020000)
+
+
+/*****************************************************************************/
+/* Errors                                                                    */
+/*                                                                           */
+/*****************************************************************************/
+
+#define SL_RESULT_SUCCESS				((SLuint32) 0x00000000)
+#define SL_RESULT_PRECONDITIONS_VIOLATED	((SLuint32) 0x00000001)
+#define SL_RESULT_PARAMETER_INVALID		((SLuint32) 0x00000002)
+#define SL_RESULT_MEMORY_FAILURE			((SLuint32) 0x00000003)
+#define SL_RESULT_RESOURCE_ERROR			((SLuint32) 0x00000004)
+#define SL_RESULT_RESOURCE_LOST			((SLuint32) 0x00000005)
+#define SL_RESULT_IO_ERROR				((SLuint32) 0x00000006)
+#define SL_RESULT_BUFFER_INSUFFICIENT		((SLuint32) 0x00000007)
+#define SL_RESULT_CONTENT_CORRUPTED		((SLuint32) 0x00000008)
+#define SL_RESULT_CONTENT_UNSUPPORTED		((SLuint32) 0x00000009)
+#define SL_RESULT_CONTENT_NOT_FOUND		((SLuint32) 0x0000000A)
+#define SL_RESULT_PERMISSION_DENIED		((SLuint32) 0x0000000B)
+#define SL_RESULT_FEATURE_UNSUPPORTED		((SLuint32) 0x0000000C)
+#define SL_RESULT_INTERNAL_ERROR			((SLuint32) 0x0000000D)
+#define SL_RESULT_UNKNOWN_ERROR			((SLuint32) 0x0000000E)
+#define SL_RESULT_OPERATION_ABORTED		((SLuint32) 0x0000000F)
+#define SL_RESULT_CONTROL_LOST			((SLuint32) 0x00000010)
+
+
+/* Object state definitions */
+
+#define SL_OBJECT_STATE_UNREALIZED	((SLuint32) 0x00000001)
+#define SL_OBJECT_STATE_REALIZED		((SLuint32) 0x00000002)
+#define SL_OBJECT_STATE_SUSPENDED	((SLuint32) 0x00000003)
+
+/* Object event definitions */
+
+#define SL_OBJECT_EVENT_RUNTIME_ERROR			((SLuint32) 0x00000001)
+#define SL_OBJECT_EVENT_ASYNC_TERMINATION		((SLuint32) 0x00000002)
+#define SL_OBJECT_EVENT_RESOURCES_LOST			((SLuint32) 0x00000003)
+#define SL_OBJECT_EVENT_RESOURCES_AVAILABLE		((SLuint32) 0x00000004)
+#define SL_OBJECT_EVENT_ITF_CONTROL_TAKEN		((SLuint32) 0x00000005)
+#define SL_OBJECT_EVENT_ITF_CONTROL_RETURNED		((SLuint32) 0x00000006)
+#define SL_OBJECT_EVENT_ITF_PARAMETERS_CHANGED	((SLuint32) 0x00000007)
+
+
+/*****************************************************************************/
+/* Interface definitions                                                     */
+/*****************************************************************************/
+
+/** NULL Interface */
+
+extern const SLInterfaceID SL_IID_NULL;
+
+/*---------------------------------------------------------------------------*/
+/* Data Source and Data Sink Structures                                      */
+/*---------------------------------------------------------------------------*/
+
+/** Data locator macros  */
+#define SL_DATALOCATOR_URI			((SLuint32) 0x00000001)
+#define SL_DATALOCATOR_ADDRESS		((SLuint32) 0x00000002)
+#define SL_DATALOCATOR_IODEVICE		((SLuint32) 0x00000003)
+#define SL_DATALOCATOR_OUTPUTMIX		((SLuint32) 0x00000004)
+#define SL_DATALOCATOR_RESERVED5		((SLuint32) 0x00000005)
+#define SL_DATALOCATOR_BUFFERQUEUE	((SLuint32) 0x00000006)
+#define SL_DATALOCATOR_MIDIBUFFERQUEUE	((SLuint32) 0x00000007)
+#define SL_DATALOCATOR_RESERVED8		((SLuint32) 0x00000008)
+
+
+
+/** URI-based data locator definition where locatorType must be SL_DATALOCATOR_URI*/
+typedef struct SLDataLocator_URI_ {
+	SLuint32 		locatorType;
+	SLchar *		URI;
+} SLDataLocator_URI;
+
+/** Address-based data locator definition where locatorType must be SL_DATALOCATOR_ADDRESS*/
+typedef struct SLDataLocator_Address_ {
+	SLuint32 	locatorType;
+	void 		*pAddress;
+	SLuint32	length;
+} SLDataLocator_Address;
+
+/** IODevice-types */
+#define SL_IODEVICE_AUDIOINPUT	((SLuint32) 0x00000001)
+#define SL_IODEVICE_LEDARRAY	((SLuint32) 0x00000002)
+#define SL_IODEVICE_VIBRA		((SLuint32) 0x00000003)
+#define SL_IODEVICE_RESERVED4	((SLuint32) 0x00000004)
+#define SL_IODEVICE_RESERVED5	((SLuint32) 0x00000005)
+
+/** IODevice-based data locator definition where locatorType must be SL_DATALOCATOR_IODEVICE*/
+typedef struct SLDataLocator_IODevice_ {
+	SLuint32	locatorType;
+	SLuint32	deviceType;
+	SLuint32	deviceID;
+	SLObjectItf	device;
+} SLDataLocator_IODevice;
+
+/** OutputMix-based data locator definition where locatorType must be SL_DATALOCATOR_OUTPUTMIX*/
+typedef struct SLDataLocator_OutputMix {
+	SLuint32 		locatorType;
+	SLObjectItf		outputMix;
+} SLDataLocator_OutputMix;
+
+
+/** BufferQueue-based data locator definition where locatorType must be SL_DATALOCATOR_BUFFERQUEUE*/
+typedef struct SLDataLocator_BufferQueue {
+	SLuint32	locatorType;
+	SLuint32	numBuffers;
+} SLDataLocator_BufferQueue;
+
+/** MidiBufferQueue-based data locator definition where locatorType must be SL_DATALOCATOR_MIDIBUFFERQUEUE*/
+typedef struct SLDataLocator_MIDIBufferQueue {
+	SLuint32	locatorType;
+	SLuint32	tpqn;
+	SLuint32	numBuffers;
+} SLDataLocator_MIDIBufferQueue;
+
+/** Data format defines */
+#define SL_DATAFORMAT_MIME		((SLuint32) 0x00000001)
+#define SL_DATAFORMAT_PCM		((SLuint32) 0x00000002)
+#define SL_DATAFORMAT_RESERVED3	((SLuint32) 0x00000003)
+
+
+/** MIME-type-based data format definition where formatType must be SL_DATAFORMAT_MIME*/
+typedef struct SLDataFormat_MIME_ {
+	SLuint32 		formatType;
+	SLchar * 		mimeType;
+	SLuint32		containerType;
+} SLDataFormat_MIME;
+
+/* Byte order of a block of 16- or 32-bit data */
+#define SL_BYTEORDER_BIGENDIAN				((SLuint32) 0x00000001)
+#define SL_BYTEORDER_LITTLEENDIAN			((SLuint32) 0x00000002)
+
+/* Container type */
+#define SL_CONTAINERTYPE_UNSPECIFIED	((SLuint32) 0x00000001)
+#define SL_CONTAINERTYPE_RAW		((SLuint32) 0x00000002)
+#define SL_CONTAINERTYPE_ASF		((SLuint32) 0x00000003)
+#define SL_CONTAINERTYPE_AVI		((SLuint32) 0x00000004)
+#define SL_CONTAINERTYPE_BMP		((SLuint32) 0x00000005)
+#define SL_CONTAINERTYPE_JPG		((SLuint32) 0x00000006)
+#define SL_CONTAINERTYPE_JPG2000		((SLuint32) 0x00000007)
+#define SL_CONTAINERTYPE_M4A		((SLuint32) 0x00000008)
+#define SL_CONTAINERTYPE_MP3		((SLuint32) 0x00000009)
+#define SL_CONTAINERTYPE_MP4		((SLuint32) 0x0000000A)
+#define SL_CONTAINERTYPE_MPEG_ES		((SLuint32) 0x0000000B)
+#define SL_CONTAINERTYPE_MPEG_PS		((SLuint32) 0x0000000C)
+#define SL_CONTAINERTYPE_MPEG_TS		((SLuint32) 0x0000000D)
+#define SL_CONTAINERTYPE_QT		((SLuint32) 0x0000000E)
+#define SL_CONTAINERTYPE_WAV		((SLuint32) 0x0000000F)
+#define SL_CONTAINERTYPE_XMF_0		((SLuint32) 0x00000010)
+#define SL_CONTAINERTYPE_XMF_1		((SLuint32) 0x00000011)
+#define SL_CONTAINERTYPE_XMF_2		((SLuint32) 0x00000012)
+#define SL_CONTAINERTYPE_XMF_3		((SLuint32) 0x00000013)
+#define SL_CONTAINERTYPE_XMF_GENERIC	((SLuint32) 0x00000014)
+#define SL_CONTAINERTYPE_AMR  		((SLuint32) 0x00000015)
+#define SL_CONTAINERTYPE_AAC		((SLuint32) 0x00000016)
+#define SL_CONTAINERTYPE_3GPP		((SLuint32) 0x00000017)
+#define SL_CONTAINERTYPE_3GA		((SLuint32) 0x00000018)
+#define SL_CONTAINERTYPE_RM		((SLuint32) 0x00000019)
+#define SL_CONTAINERTYPE_DMF		((SLuint32) 0x0000001A)
+#define SL_CONTAINERTYPE_SMF		((SLuint32) 0x0000001B)
+#define SL_CONTAINERTYPE_MOBILE_DLS	((SLuint32) 0x0000001C)
+#define SL_CONTAINERTYPE_OGG	((SLuint32) 0x0000001D)
+
+
+/** PCM-type-based data format definition where formatType must be SL_DATAFORMAT_PCM*/
+typedef struct SLDataFormat_PCM_ {
+	SLuint32 		formatType;
+	SLuint32 		numChannels;
+	SLuint32 		samplesPerSec;
+	SLuint32 		bitsPerSample;
+	SLuint32 		containerSize;
+	SLuint32 		channelMask;
+	SLuint32		endianness;
+} SLDataFormat_PCM;
+
+typedef struct SLDataSource_ {
+	void *pLocator;
+	void *pFormat;
+} SLDataSource;
+
+
+typedef struct SLDataSink_ {
+	void *pLocator;
+	void *pFormat;
+} SLDataSink;
+
+
+
+
+
+
+/*---------------------------------------------------------------------------*/
+/* Standard Object Interface                                                 */
+/*---------------------------------------------------------------------------*/
+
+extern const SLInterfaceID SL_IID_OBJECT;
+
+/** Object callback */
+
+
+typedef void (SLAPIENTRY *slObjectCallback) (
+	SLObjectItf caller,
+	const void * pContext,
+	SLuint32 event,
+	SLresult result,
+    SLuint32 param,
+    void *pInterface
+);
+
+
+struct SLObjectItf_ {
+	SLresult (*Realize) (
+		SLObjectItf self,
+		SLboolean async
+	);
+	SLresult (*Resume) (
+		SLObjectItf self,
+		SLboolean async
+	);
+	SLresult (*GetState) (
+		SLObjectItf self,
+		SLuint32 * pState
+	);
+	SLresult (*GetInterface) (
+		SLObjectItf self,
+		const SLInterfaceID iid,
+		void * pInterface
+	);
+	SLresult (*RegisterCallback) (
+		SLObjectItf self,
+		slObjectCallback callback,
+		void * pContext
+	);
+	void (*AbortAsyncOperation) (
+		SLObjectItf self
+	);
+	void (*Destroy) (
+		SLObjectItf self
+	);
+	SLresult (*SetPriority) (
+		SLObjectItf self,
+		SLint32 priority,
+		SLboolean preemptable
+	);
+	SLresult (*GetPriority) (
+		SLObjectItf self,
+		SLint32 *pPriority,
+		SLboolean *pPreemptable
+	);
+	SLresult (*SetLossOfControlInterfaces) (
+		SLObjectItf self,
+		SLint16 numInterfaces,
+		SLInterfaceID * pInterfaceIDs,
+		SLboolean enabled
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Audio IO Device capabilities interface                                    */
+/*---------------------------------------------------------------------------*/
+
+#define SL_DEFAULTDEVICEID_AUDIOINPUT 	((SLuint32) 0xFFFFFFFF)
+#define SL_DEFAULTDEVICEID_AUDIOOUTPUT 	((SLuint32) 0xFFFFFFFE)
+#define SL_DEFAULTDEVICEID_LED          ((SLuint32) 0xFFFFFFFD)
+#define SL_DEFAULTDEVICEID_VIBRA        ((SLuint32) 0xFFFFFFFC)
+#define SL_DEFAULTDEVICEID_RESERVED1    ((SLuint32) 0xFFFFFFFB)
+
+
+#define SL_DEVCONNECTION_INTEGRATED         ((SLint16) 0x0001)
+#define SL_DEVCONNECTION_ATTACHED_WIRED     ((SLint16) 0x0100)
+#define SL_DEVCONNECTION_ATTACHED_WIRELESS  ((SLint16) 0x0200)
+#define SL_DEVCONNECTION_NETWORK 		    ((SLint16) 0x0400)
+
+
+#define SL_DEVLOCATION_HANDSET 	((SLuint16) 0x0001)
+#define SL_DEVLOCATION_HEADSET 	((SLuint16) 0x0002)
+#define SL_DEVLOCATION_CARKIT 	((SLuint16) 0x0003)
+#define SL_DEVLOCATION_DOCK 	((SLuint16) 0x0004)
+#define SL_DEVLOCATION_REMOTE 	((SLuint16) 0x0005)
+/* Note: SL_DEVLOCATION_RESLTE is deprecated, use SL_DEVLOCATION_REMOTE instead. */
+#define SL_DEVLOCATION_RESLTE 	((SLuint16) 0x0005)
+
+
+#define SL_DEVSCOPE_UNKNOWN     ((SLuint16) 0x0001)
+#define SL_DEVSCOPE_ENVIRONMENT ((SLuint16) 0x0002)
+#define SL_DEVSCOPE_USER        ((SLuint16) 0x0003)
+
+
+typedef struct SLAudioInputDescriptor_ {
+	SLchar *deviceName;
+	SLint16 deviceConnection;
+	SLint16 deviceScope;
+	SLint16 deviceLocation;
+	SLboolean isForTelephony;
+	SLmilliHertz minSampleRate;
+	SLmilliHertz maxSampleRate;
+	SLboolean isFreqRangeContinuous;
+	SLmilliHertz *samplingRatesSupported;
+	SLint16 numOfSamplingRatesSupported;
+	SLint16 maxChannels;
+} SLAudioInputDescriptor;
+
+
+typedef struct SLAudioOutputDescriptor_ {
+	SLchar *pDeviceName;
+	SLint16 deviceConnection;
+	SLint16 deviceScope;
+	SLint16 deviceLocation;
+	SLboolean isForTelephony;
+	SLmilliHertz minSampleRate;
+	SLmilliHertz maxSampleRate;
+	SLboolean isFreqRangeContinuous;
+	SLmilliHertz *samplingRatesSupported;
+	SLint16 numOfSamplingRatesSupported;
+	SLint16 maxChannels;
+} SLAudioOutputDescriptor;
+
+
+
+extern const SLInterfaceID SL_IID_AUDIOIODEVICECAPABILITIES;
+
+struct SLAudioIODeviceCapabilitiesItf_;
+typedef const struct SLAudioIODeviceCapabilitiesItf_ * const * SLAudioIODeviceCapabilitiesItf;
+
+
+typedef void (SLAPIENTRY *slAvailableAudioInputsChangedCallback) (
+	SLAudioIODeviceCapabilitiesItf caller,
+	void *pContext,
+	SLuint32 deviceID,
+	SLint32 numInputs,
+	SLboolean isNew
+);
+
+
+typedef void (SLAPIENTRY *slAvailableAudioOutputsChangedCallback) (
+	SLAudioIODeviceCapabilitiesItf caller,
+	void *pContext,
+	SLuint32 deviceID,
+	SLint32 numOutputs,
+	SLboolean isNew
+);
+
+typedef void (SLAPIENTRY *slDefaultDeviceIDMapChangedCallback) (
+	SLAudioIODeviceCapabilitiesItf caller,
+	void *pContext,
+	SLboolean isOutput,
+	SLint32 numDevices
+);
+
+
+struct SLAudioIODeviceCapabilitiesItf_ {
+	SLresult (*GetAvailableAudioInputs)(
+		SLAudioIODeviceCapabilitiesItf self,
+		SLint32  *pNumInputs,
+		SLuint32 *pInputDeviceIDs
+	);
+	SLresult (*QueryAudioInputCapabilities)(
+		SLAudioIODeviceCapabilitiesItf self,
+		SLuint32 deviceId,
+		SLAudioInputDescriptor *pDescriptor
+	);
+	SLresult (*RegisterAvailableAudioInputsChangedCallback) (
+		SLAudioIODeviceCapabilitiesItf self,
+		slAvailableAudioInputsChangedCallback callback,
+		void *pContext
+	);
+	SLresult (*GetAvailableAudioOutputs)(
+		SLAudioIODeviceCapabilitiesItf self,
+		SLint32 *pNumOutputs,
+		SLuint32 *pOutputDeviceIDs
+	);
+	SLresult (*QueryAudioOutputCapabilities)(
+		SLAudioIODeviceCapabilitiesItf self,
+		SLuint32 deviceId,
+		SLAudioOutputDescriptor *pDescriptor
+	);
+	SLresult (*RegisterAvailableAudioOutputsChangedCallback) (
+		SLAudioIODeviceCapabilitiesItf self,
+		slAvailableAudioOutputsChangedCallback callback,
+		void *pContext
+	);
+	SLresult (*RegisterDefaultDeviceIDMapChangedCallback) (
+		SLAudioIODeviceCapabilitiesItf self,
+		slDefaultDeviceIDMapChangedCallback callback,
+		void *pContext
+	);
+	SLresult (*GetAssociatedAudioInputs) (
+		SLAudioIODeviceCapabilitiesItf self,
+		SLuint32 deviceId,
+		SLint32 *pNumAudioInputs,
+		SLuint32 *pAudioInputDeviceIDs
+	);
+	SLresult (*GetAssociatedAudioOutputs) (
+		SLAudioIODeviceCapabilitiesItf self,
+		SLuint32 deviceId,
+		SLint32 *pNumAudioOutputs,
+		SLuint32 *pAudioOutputDeviceIDs
+	);
+	SLresult (*GetDefaultAudioDevices) (
+		SLAudioIODeviceCapabilitiesItf self,
+		SLuint32 defaultDeviceID,
+		SLint32 *pNumAudioDevices,
+		SLuint32 *pAudioDeviceIDs
+	);
+	SLresult (*QuerySampleFormatsSupported)(
+		SLAudioIODeviceCapabilitiesItf self,
+		SLuint32 deviceId,
+		SLmilliHertz samplingRate,
+		SLint32 *pSampleFormats,
+		SLint32 *pNumOfSampleFormats
+	);
+};
+
+
+
+/*---------------------------------------------------------------------------*/
+/* Capabilities of the LED array IODevice                                    */
+/*---------------------------------------------------------------------------*/
+
+typedef struct SLLEDDescriptor_ {
+	SLuint8   ledCount;
+	SLuint8   primaryLED;
+	SLuint32  colorMask;
+} SLLEDDescriptor;
+
+
+/*---------------------------------------------------------------------------*/
+/* LED Array interface                                                       */
+/*---------------------------------------------------------------------------*/
+
+typedef struct SLHSL_ {
+    SLmillidegree  hue;
+    SLpermille     saturation;
+    SLpermille     lightness;
+} SLHSL;
+
+
+extern const SLInterfaceID SL_IID_LED;
+
+struct SLLEDArrayItf_;
+typedef const struct SLLEDArrayItf_ * const * SLLEDArrayItf;
+
+struct SLLEDArrayItf_ {
+	SLresult (*ActivateLEDArray) (
+		SLLEDArrayItf self,
+		SLuint32 lightMask
+	);
+	SLresult (*IsLEDArrayActivated) (
+		SLLEDArrayItf self,
+		SLuint32 *lightMask
+	);
+	SLresult (*SetColor) (
+		SLLEDArrayItf self,
+		SLuint8 index,
+		const SLHSL *color
+	);
+	SLresult (*GetColor) (
+		SLLEDArrayItf self,
+		SLuint8 index,
+		SLHSL *color
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Capabilities of the Vibra IODevice                                        */
+/*---------------------------------------------------------------------------*/
+
+typedef struct SLVibraDescriptor_ {
+	SLboolean supportsFrequency;
+	SLboolean supportsIntensity;
+	SLmilliHertz  minFrequency;
+	SLmilliHertz  maxFrequency;
+} SLVibraDescriptor;
+
+
+
+/*---------------------------------------------------------------------------*/
+/* Vibra interface                                                           */
+/*---------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_VIBRA;
+
+
+struct SLVibraItf_;
+typedef const struct SLVibraItf_ * const * SLVibraItf;
+
+struct SLVibraItf_ {
+	SLresult (*Vibrate) (
+		SLVibraItf self,
+		SLboolean vibrate
+	);
+	SLresult (*IsVibrating) (
+		SLVibraItf self,
+		SLboolean *pVibrating
+	);
+	SLresult (*SetFrequency) (
+		SLVibraItf self,
+		SLmilliHertz frequency
+	);
+	SLresult (*GetFrequency) (
+		SLVibraItf self,
+		SLmilliHertz *pFrequency
+	);
+	SLresult (*SetIntensity) (
+		SLVibraItf self,
+		SLpermille intensity
+	);
+	SLresult (*GetIntensity) (
+		SLVibraItf self,
+		SLpermille *pIntensity
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Meta data extraction related types and interface                          */
+/*---------------------------------------------------------------------------*/
+
+#define SL_CHARACTERENCODING_UNKNOWN			((SLuint32) 0x00000000)
+#define SL_CHARACTERENCODING_BINARY       ((SLuint32) 0x00000001)
+#define SL_CHARACTERENCODING_ASCII        ((SLuint32) 0x00000002)
+#define SL_CHARACTERENCODING_BIG5         ((SLuint32) 0x00000003)
+#define SL_CHARACTERENCODING_CODEPAGE1252		((SLuint32) 0x00000004)
+#define SL_CHARACTERENCODING_GB2312			((SLuint32) 0x00000005)
+#define SL_CHARACTERENCODING_HZGB2312			((SLuint32) 0x00000006)
+#define SL_CHARACTERENCODING_GB12345			((SLuint32) 0x00000007)
+#define SL_CHARACTERENCODING_GB18030			((SLuint32) 0x00000008)
+#define SL_CHARACTERENCODING_GBK				((SLuint32) 0x00000009)
+#define SL_CHARACTERENCODING_IMAPUTF7			((SLuint32) 0x0000000A)
+#define SL_CHARACTERENCODING_ISO2022JP			((SLuint32) 0x0000000B)
+#define SL_CHARACTERENCODING_ISO2022JP1		((SLuint32) 0x0000000B)
+#define SL_CHARACTERENCODING_ISO88591			((SLuint32) 0x0000000C)
+#define SL_CHARACTERENCODING_ISO885910			((SLuint32) 0x0000000D)
+#define SL_CHARACTERENCODING_ISO885913			((SLuint32) 0x0000000E)
+#define SL_CHARACTERENCODING_ISO885914			((SLuint32) 0x0000000F)
+#define SL_CHARACTERENCODING_ISO885915			((SLuint32) 0x00000010)
+#define SL_CHARACTERENCODING_ISO88592			((SLuint32) 0x00000011)
+#define SL_CHARACTERENCODING_ISO88593			((SLuint32) 0x00000012)
+#define SL_CHARACTERENCODING_ISO88594			((SLuint32) 0x00000013)
+#define SL_CHARACTERENCODING_ISO88595			((SLuint32) 0x00000014)
+#define SL_CHARACTERENCODING_ISO88596			((SLuint32) 0x00000015)
+#define SL_CHARACTERENCODING_ISO88597			((SLuint32) 0x00000016)
+#define SL_CHARACTERENCODING_ISO88598			((SLuint32) 0x00000017)
+#define SL_CHARACTERENCODING_ISO88599			((SLuint32) 0x00000018)
+#define SL_CHARACTERENCODING_ISOEUCJP			((SLuint32) 0x00000019)
+#define SL_CHARACTERENCODING_SHIFTJIS			((SLuint32) 0x0000001A)
+#define SL_CHARACTERENCODING_SMS7BIT			((SLuint32) 0x0000001B)
+#define SL_CHARACTERENCODING_UTF7			((SLuint32) 0x0000001C)
+#define SL_CHARACTERENCODING_UTF8			((SLuint32) 0x0000001D)
+#define SL_CHARACTERENCODING_JAVACONFORMANTUTF8	((SLuint32) 0x0000001E)
+#define SL_CHARACTERENCODING_UTF16BE			((SLuint32) 0x0000001F)
+#define SL_CHARACTERENCODING_UTF16LE			((SLuint32) 0x00000020)
+
+
+#define SL_METADATA_FILTER_KEY		((SLuint8) 0x01)
+#define SL_METADATA_FILTER_LANG		((SLuint8) 0x02)
+#define SL_METADATA_FILTER_ENCODING	((SLuint8) 0x04)
+
+
+typedef struct SLMetadataInfo_ {
+    SLuint32     size;
+    SLuint32     encoding;
+    SLchar       langCountry[16];
+    SLuint8      data[1];
+} SLMetadataInfo;
+
+extern const SLInterfaceID SL_IID_METADATAEXTRACTION;
+
+struct SLMetadataExtractionItf_;
+typedef const struct SLMetadataExtractionItf_ * const * SLMetadataExtractionItf;
+
+
+struct SLMetadataExtractionItf_ {
+	SLresult (*GetItemCount) (
+		SLMetadataExtractionItf self,
+		SLuint32 *pItemCount
+	);
+	SLresult (*GetKeySize) (
+		SLMetadataExtractionItf self,
+		SLuint32 index,
+		SLuint32 *pKeySize
+	);
+	SLresult (*GetKey) (
+		SLMetadataExtractionItf self,
+		SLuint32 index,
+		SLuint32 keySize,
+		SLMetadataInfo *pKey
+	);
+	SLresult (*GetValueSize) (
+		SLMetadataExtractionItf self,
+		SLuint32 index,
+		SLuint32 *pValueSize
+	);
+	SLresult (*GetValue) (
+		SLMetadataExtractionItf self,
+		SLuint32 index,
+		SLuint32 valueSize,
+		SLMetadataInfo *pValue
+	);
+	SLresult (*AddKeyFilter) (
+		SLMetadataExtractionItf self,
+		SLuint32 keySize,
+		const void *pKey,
+		SLuint32 keyEncoding,
+		const SLchar *pValueLangCountry,
+		SLuint32 valueEncoding,
+		SLuint8 filterMask
+	);
+	SLresult (*ClearKeyFilter) (
+		SLMetadataExtractionItf self
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Meta data traversal related types and interface                          */
+/*---------------------------------------------------------------------------*/
+
+#define SL_METADATATRAVERSALMODE_ALL	((SLuint32) 0x00000001)
+#define SL_METADATATRAVERSALMODE_NODE	((SLuint32) 0x00000002)
+
+
+#define SL_NODETYPE_UNSPECIFIED	((SLuint32) 0x00000001)
+#define SL_NODETYPE_AUDIO		((SLuint32) 0x00000002)
+#define SL_NODETYPE_VIDEO		((SLuint32) 0x00000003)
+#define SL_NODETYPE_IMAGE		((SLuint32) 0x00000004)
+
+#define SL_NODE_PARENT 0xFFFFFFFF
+
+extern const SLInterfaceID SL_IID_METADATATRAVERSAL;
+
+struct SLMetadataTraversalItf_;
+typedef const struct SLMetadataTraversalItf_ * const * SLMetadataTraversalItf;
+
+struct SLMetadataTraversalItf_ {
+	SLresult (*SetMode) (
+		SLMetadataTraversalItf self,
+		SLuint32 mode
+	);
+	SLresult (*GetChildCount) (
+		SLMetadataTraversalItf self,
+		SLuint32 *pCount
+	);
+	SLresult (*GetChildMIMETypeSize) (
+		SLMetadataTraversalItf self,
+		SLuint32 index,
+		SLuint32 *pSize
+	);
+	SLresult (*GetChildInfo) (
+		SLMetadataTraversalItf self,
+		SLuint32 index,
+		SLint32 *pNodeID,
+		SLuint32 *pType,
+		SLuint32 size,
+		SLchar *pMimeType
+	);
+	SLresult (*SetActiveNode) (
+		SLMetadataTraversalItf self,
+		SLuint32 index
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Dynamic Source types and interface                                        */
+/*---------------------------------------------------------------------------*/
+
+extern const SLInterfaceID SL_IID_DYNAMICSOURCE;
+
+struct SLDynamicSourceItf_;
+typedef const struct SLDynamicSourceItf_ * const * SLDynamicSourceItf;
+
+struct SLDynamicSourceItf_ {
+	SLresult (*SetSource) (
+		SLDynamicSourceItf self,
+		SLDataSource *pDataSource
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Output Mix interface                                                      */
+/*---------------------------------------------------------------------------*/
+
+extern const SLInterfaceID SL_IID_OUTPUTMIX;
+
+struct SLOutputMixItf_;
+typedef const struct SLOutputMixItf_ * const * SLOutputMixItf;
+
+typedef void (SLAPIENTRY *slMixDeviceChangeCallback) (
+	SLOutputMixItf caller,
+    void *pContext
+);
+
+
+struct SLOutputMixItf_ {
+	SLresult (*GetDestinationOutputDeviceIDs) (
+		SLOutputMixItf self,
+		SLint32 *pNumDevices,
+		SLuint32 *pDeviceIDs
+	);
+	SLresult (*RegisterDeviceChangeCallback) (
+		SLOutputMixItf self,
+		slMixDeviceChangeCallback callback,
+		void *pContext
+    );
+    SLresult (*ReRoute)(
+        SLOutputMixItf self,
+        SLint32 numOutputDevices,
+        SLuint32 *pOutputDeviceIDs
+    );
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Playback interface                                                        */
+/*---------------------------------------------------------------------------*/
+
+/** Playback states */
+#define SL_PLAYSTATE_STOPPED	((SLuint32) 0x00000001)
+#define SL_PLAYSTATE_PAUSED	((SLuint32) 0x00000002)
+#define SL_PLAYSTATE_PLAYING	((SLuint32) 0x00000003)
+
+/** Play events **/
+#define SL_PLAYEVENT_HEADATEND		((SLuint32) 0x00000001)
+#define SL_PLAYEVENT_HEADATMARKER	((SLuint32) 0x00000002)
+#define SL_PLAYEVENT_HEADATNEWPOS	((SLuint32) 0x00000004)
+#define SL_PLAYEVENT_HEADMOVING		((SLuint32) 0x00000008)
+#define SL_PLAYEVENT_HEADSTALLED	((SLuint32) 0x00000010)
+
+#define SL_TIME_UNKNOWN	((SLuint32) 0xFFFFFFFF)
+
+
+extern const SLInterfaceID SL_IID_PLAY;
+
+/** Playback interface methods */
+
+struct SLPlayItf_;
+typedef const struct SLPlayItf_ * const * SLPlayItf;
+
+typedef void (SLAPIENTRY *slPlayCallback) (
+	SLPlayItf caller,
+	void *pContext,
+	SLuint32 event
+);
+
+struct SLPlayItf_ {
+	SLresult (*SetPlayState) (
+		SLPlayItf self,
+		SLuint32 state
+	);
+	SLresult (*GetPlayState) (
+		SLPlayItf self,
+		SLuint32 *pState
+	);
+	SLresult (*GetDuration) (
+		SLPlayItf self,
+		SLmillisecond *pMsec
+	);
+	SLresult (*GetPosition) (
+		SLPlayItf self,
+		SLmillisecond *pMsec
+	);
+	SLresult (*RegisterCallback) (
+		SLPlayItf self,
+		slPlayCallback callback,
+		void *pContext
+	);
+	SLresult (*SetCallbackEventsMask) (
+		SLPlayItf self,
+		SLuint32 eventFlags
+	);
+	SLresult (*GetCallbackEventsMask) (
+		SLPlayItf self,
+		SLuint32 *pEventFlags
+	);
+	SLresult (*SetMarkerPosition) (
+		SLPlayItf self,
+		SLmillisecond mSec
+	);
+	SLresult (*ClearMarkerPosition) (
+		SLPlayItf self
+	);
+	SLresult (*GetMarkerPosition) (
+		SLPlayItf self,
+		SLmillisecond *pMsec
+	);
+	SLresult (*SetPositionUpdatePeriod) (
+		SLPlayItf self,
+		SLmillisecond mSec
+	);
+	SLresult (*GetPositionUpdatePeriod) (
+		SLPlayItf self,
+		SLmillisecond *pMsec
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Prefetch status interface                                                 */
+/*---------------------------------------------------------------------------*/
+
+#define SL_PREFETCHEVENT_STATUSCHANGE		((SLuint32) 0x00000001)
+#define SL_PREFETCHEVENT_FILLLEVELCHANGE	((SLuint32) 0x00000002)
+
+#define SL_PREFETCHSTATUS_UNDERFLOW		((SLuint32) 0x00000001)
+#define SL_PREFETCHSTATUS_SUFFICIENTDATA	((SLuint32) 0x00000002)
+#define SL_PREFETCHSTATUS_OVERFLOW		((SLuint32) 0x00000003)
+
+
+extern const SLInterfaceID SL_IID_PREFETCHSTATUS;
+
+
+/** Prefetch status interface methods */
+
+struct SLPrefetchStatusItf_;
+typedef const struct SLPrefetchStatusItf_ * const * SLPrefetchStatusItf;
+
+typedef void (SLAPIENTRY *slPrefetchCallback) (
+	SLPrefetchStatusItf caller,
+	void *pContext,
+	SLuint32 event
+);
+
+struct SLPrefetchStatusItf_ {
+	SLresult (*GetPrefetchStatus) (
+		SLPrefetchStatusItf self,
+		SLuint32 *pStatus
+	);
+	SLresult (*GetFillLevel) (
+		SLPrefetchStatusItf self,
+		SLpermille *pLevel
+	);
+	SLresult (*RegisterCallback) (
+		SLPrefetchStatusItf self,
+		slPrefetchCallback callback,
+		void *pContext
+	);
+	SLresult (*SetCallbackEventsMask) (
+		SLPrefetchStatusItf self,
+		SLuint32 eventFlags
+	);
+	SLresult (*GetCallbackEventsMask) (
+		SLPrefetchStatusItf self,
+		SLuint32 *pEventFlags
+	);
+	SLresult (*SetFillUpdatePeriod) (
+		SLPrefetchStatusItf self,
+		SLpermille period
+	);
+	SLresult (*GetFillUpdatePeriod) (
+		SLPrefetchStatusItf self,
+		SLpermille *pPeriod
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Playback Rate interface                                                   */
+/*---------------------------------------------------------------------------*/
+
+#define SL_RATEPROP_RESERVED1		  		((SLuint32) 0x00000001)
+#define SL_RATEPROP_RESERVED2		  		((SLuint32) 0x00000002)
+#define SL_RATEPROP_SILENTAUDIO				((SLuint32) 0x00000100)
+#define SL_RATEPROP_STAGGEREDAUDIO	((SLuint32) 0x00000200)
+#define SL_RATEPROP_NOPITCHCORAUDIO	((SLuint32) 0x00000400)
+#define SL_RATEPROP_PITCHCORAUDIO	((SLuint32) 0x00000800)
+
+
+extern const SLInterfaceID SL_IID_PLAYBACKRATE;
+
+struct SLPlaybackRateItf_;
+typedef const struct SLPlaybackRateItf_ * const * SLPlaybackRateItf;
+
+struct SLPlaybackRateItf_ {
+	SLresult (*SetRate)(
+		SLPlaybackRateItf self,
+		SLpermille rate
+	);
+	SLresult (*GetRate)(
+		SLPlaybackRateItf self,
+		SLpermille *pRate
+	);
+	SLresult (*SetPropertyConstraints)(
+		SLPlaybackRateItf self,
+		SLuint32 constraints
+	);
+	SLresult (*GetProperties)(
+		SLPlaybackRateItf self,
+		SLuint32 *pProperties
+	);
+	SLresult (*GetCapabilitiesOfRate)(
+		SLPlaybackRateItf self,
+		SLpermille rate,
+		SLuint32 *pCapabilities
+	);
+	SLresult (*GetRateRange) (
+		SLPlaybackRateItf self,
+		SLuint8 index,
+		SLpermille *pMinRate,
+		SLpermille *pMaxRate,
+		SLpermille *pStepSize,
+		SLuint32 *pCapabilities
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Seek Interface                                                            */
+/*---------------------------------------------------------------------------*/
+
+#define SL_SEEKMODE_FAST		((SLuint32) 0x0001)
+#define SL_SEEKMODE_ACCURATE	((SLuint32) 0x0002)
+
+extern const SLInterfaceID SL_IID_SEEK;
+
+struct SLSeekItf_;
+typedef const struct SLSeekItf_ * const * SLSeekItf;
+
+struct SLSeekItf_ {
+	SLresult (*SetPosition)(
+		SLSeekItf self,
+		SLmillisecond pos,
+		SLuint32 seekMode
+	);
+	SLresult (*SetLoop)(
+		SLSeekItf self,
+		SLboolean loopEnable,
+		SLmillisecond startPos,
+		SLmillisecond endPos
+	);
+	SLresult (*GetLoop)(
+		SLSeekItf self,
+		SLboolean *pLoopEnabled,
+		SLmillisecond *pStartPos,
+		SLmillisecond *pEndPos
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Standard Recording Interface                                              */
+/*---------------------------------------------------------------------------*/
+
+/** Recording states */
+#define SL_RECORDSTATE_STOPPED 	((SLuint32) 0x00000001)
+#define SL_RECORDSTATE_PAUSED	((SLuint32) 0x00000002)
+#define SL_RECORDSTATE_RECORDING	((SLuint32) 0x00000003)
+
+
+/** Record event **/
+#define SL_RECORDEVENT_HEADATLIMIT	((SLuint32) 0x00000001)
+#define SL_RECORDEVENT_HEADATMARKER	((SLuint32) 0x00000002)
+#define SL_RECORDEVENT_HEADATNEWPOS	((SLuint32) 0x00000004)
+#define SL_RECORDEVENT_HEADMOVING	((SLuint32) 0x00000008)
+#define SL_RECORDEVENT_HEADSTALLED 	((SLuint32) 0x00000010)
+/* Note: SL_RECORDEVENT_BUFFER_INSUFFICIENT is deprecated, use SL_RECORDEVENT_BUFFER_FULL instead. */
+#define SL_RECORDEVENT_BUFFER_INSUFFICIENT      ((SLuint32) 0x00000020)
+#define SL_RECORDEVENT_BUFFER_FULL	((SLuint32) 0x00000020)
+
+
+extern const SLInterfaceID SL_IID_RECORD;
+
+struct SLRecordItf_;
+typedef const struct SLRecordItf_ * const * SLRecordItf;
+
+typedef void (SLAPIENTRY *slRecordCallback) (
+	SLRecordItf caller,
+	void *pContext,
+	SLuint32 event
+);
+
+/** Recording interface methods */
+struct SLRecordItf_ {
+	SLresult (*SetRecordState) (
+		SLRecordItf self,
+		SLuint32 state
+	);
+	SLresult (*GetRecordState) (
+		SLRecordItf self,
+		SLuint32 *pState
+	);
+	SLresult (*SetDurationLimit) (
+		SLRecordItf self,
+		SLmillisecond msec
+	);
+	SLresult (*GetPosition) (
+		SLRecordItf self,
+		SLmillisecond *pMsec
+	);
+	SLresult (*RegisterCallback) (
+		SLRecordItf self,
+		slRecordCallback callback,
+		void *pContext
+	);
+	SLresult (*SetCallbackEventsMask) (
+		SLRecordItf self,
+		SLuint32 eventFlags
+	);
+	SLresult (*GetCallbackEventsMask) (
+		SLRecordItf self,
+		SLuint32 *pEventFlags
+	);
+	SLresult (*SetMarkerPosition) (
+		SLRecordItf self,
+		SLmillisecond mSec
+	);
+	SLresult (*ClearMarkerPosition) (
+		SLRecordItf self
+	);
+	SLresult (*GetMarkerPosition) (
+		SLRecordItf self,
+		SLmillisecond *pMsec
+	);
+	SLresult (*SetPositionUpdatePeriod) (
+		SLRecordItf self,
+		SLmillisecond mSec
+	);
+	SLresult (*GetPositionUpdatePeriod) (
+		SLRecordItf self,
+		SLmillisecond *pMsec
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Equalizer interface                                                       */
+/*---------------------------------------------------------------------------*/
+
+#define SL_EQUALIZER_UNDEFINED				((SLuint16) 0xFFFF)
+
+extern const SLInterfaceID SL_IID_EQUALIZER;
+
+struct SLEqualizerItf_;
+typedef const struct SLEqualizerItf_ * const * SLEqualizerItf;
+
+struct SLEqualizerItf_ {
+	SLresult (*SetEnabled)(
+		SLEqualizerItf self,
+		SLboolean enabled
+	);
+	SLresult (*IsEnabled)(
+		SLEqualizerItf self,
+		SLboolean *pEnabled
+	);
+	SLresult (*GetNumberOfBands)(
+		SLEqualizerItf self,
+		SLuint16 *pAmount
+	);
+	SLresult (*GetBandLevelRange)(
+		SLEqualizerItf self,
+		SLmillibel *pMin,
+		SLmillibel *pMax
+	);
+	SLresult (*SetBandLevel)(
+		SLEqualizerItf self,
+		SLuint16 band,
+		SLmillibel level
+	);
+	SLresult (*GetBandLevel)(
+		SLEqualizerItf self,
+		SLuint16 band,
+		SLmillibel *pLevel
+	);
+	SLresult (*GetCenterFreq)(
+		SLEqualizerItf self,
+		SLuint16 band,
+		SLmilliHertz *pCenter
+	);
+	SLresult (*GetBandFreqRange)(
+		SLEqualizerItf self,
+		SLuint16 band,
+		SLmilliHertz *pMin,
+		SLmilliHertz *pMax
+	);
+	SLresult (*GetBand)(
+		SLEqualizerItf self,
+		SLmilliHertz frequency,
+		SLuint16 *pBand
+	);
+	SLresult (*GetCurrentPreset)(
+		SLEqualizerItf self,
+		SLuint16 *pPreset
+	);
+	SLresult (*UsePreset)(
+		SLEqualizerItf self,
+		SLuint16 index
+	);
+	SLresult (*GetNumberOfPresets)(
+		SLEqualizerItf self,
+		SLuint16 *pNumPresets
+	);
+	SLresult (*GetPresetName)(
+		SLEqualizerItf self,
+		SLuint16 index,
+		const SLchar ** ppName
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Volume Interface                                                           */
+/* --------------------------------------------------------------------------*/
+
+extern const SLInterfaceID SL_IID_VOLUME;
+
+struct SLVolumeItf_;
+typedef const struct SLVolumeItf_ * const * SLVolumeItf;
+
+struct SLVolumeItf_ {
+	SLresult (*SetVolumeLevel) (
+		SLVolumeItf self,
+		SLmillibel level
+	);
+	SLresult (*GetVolumeLevel) (
+		SLVolumeItf self,
+		SLmillibel *pLevel
+	);
+	SLresult (*GetMaxVolumeLevel) (
+		SLVolumeItf  self,
+		SLmillibel *pMaxLevel
+	);
+	SLresult (*SetMute) (
+		SLVolumeItf self,
+		SLboolean mute
+	);
+	SLresult (*GetMute) (
+		SLVolumeItf self,
+		SLboolean *pMute
+	);
+	SLresult (*EnableStereoPosition) (
+		SLVolumeItf self,
+		SLboolean enable
+	);
+	SLresult (*IsEnabledStereoPosition) (
+		SLVolumeItf self,
+		SLboolean *pEnable
+	);
+	SLresult (*SetStereoPosition) (
+		SLVolumeItf self,
+		SLpermille stereoPosition
+	);
+	SLresult (*GetStereoPosition) (
+		SLVolumeItf self,
+		SLpermille *pStereoPosition
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Device Volume Interface                                                   */
+/* --------------------------------------------------------------------------*/
+
+extern const SLInterfaceID SL_IID_DEVICEVOLUME;
+
+struct SLDeviceVolumeItf_;
+typedef const struct SLDeviceVolumeItf_ * const * SLDeviceVolumeItf;
+
+struct SLDeviceVolumeItf_ {
+	SLresult (*GetVolumeScale) (
+		SLDeviceVolumeItf self,
+		SLuint32 deviceID,
+		SLint32 *pMinValue,
+		SLint32 *pMaxValue,
+		SLboolean *pIsMillibelScale
+	);
+	SLresult (*SetVolume) (
+		SLDeviceVolumeItf self,
+		SLuint32 deviceID,
+		SLint32 volume
+	);
+	SLresult (*GetVolume) (
+		SLDeviceVolumeItf self,
+		SLuint32 deviceID,
+		SLint32 *pVolume
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Buffer Queue Interface                                                    */
+/*---------------------------------------------------------------------------*/
+
+extern const SLInterfaceID SL_IID_BUFFERQUEUE;
+
+struct SLBufferQueueItf_;
+typedef const struct SLBufferQueueItf_ * const * SLBufferQueueItf;
+
+typedef void (SLAPIENTRY *slBufferQueueCallback)(
+	SLBufferQueueItf caller,
+	void *pContext
+);
+
+/** Buffer queue state **/
+
+typedef struct SLBufferQueueState_ {
+	SLuint32	count;
+	SLuint32	playIndex;
+} SLBufferQueueState;
+
+
+struct SLBufferQueueItf_ {
+	SLresult (*Enqueue) (
+		SLBufferQueueItf self,
+		const void *pBuffer,
+		SLuint32 size
+	);
+	SLresult (*Clear) (
+		SLBufferQueueItf self
+	);
+	SLresult (*GetState) (
+		SLBufferQueueItf self,
+		SLBufferQueueState *pState
+	);
+	SLresult (*RegisterCallback) (
+		SLBufferQueueItf self,
+		slBufferQueueCallback callback,
+		void* pContext
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* PresetReverb                                                              */
+/*---------------------------------------------------------------------------*/
+
+#define SL_REVERBPRESET_NONE		((SLuint16) 0x0000)
+#define SL_REVERBPRESET_SMALLROOM	((SLuint16) 0x0001)
+#define SL_REVERBPRESET_MEDIUMROOM	((SLuint16) 0x0002)
+#define SL_REVERBPRESET_LARGEROOM	((SLuint16) 0x0003)
+#define SL_REVERBPRESET_MEDIUMHALL	((SLuint16) 0x0004)
+#define SL_REVERBPRESET_LARGEHALL	((SLuint16) 0x0005)
+#define SL_REVERBPRESET_PLATE 		((SLuint16) 0x0006)
+
+
+extern const SLInterfaceID SL_IID_PRESETREVERB;
+
+struct SLPresetReverbItf_;
+typedef const struct SLPresetReverbItf_ * const * SLPresetReverbItf;
+
+struct SLPresetReverbItf_ {
+	SLresult (*SetPreset) (
+		SLPresetReverbItf self,
+		SLuint16 preset
+	);
+	SLresult (*GetPreset) (
+		SLPresetReverbItf self,
+		SLuint16 *pPreset
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* EnvironmentalReverb                                                       */
+/*---------------------------------------------------------------------------*/
+
+#define SL_I3DL2_ENVIRONMENT_PRESET_DEFAULT \
+	{ SL_MILLIBEL_MIN,    0,  1000,   500, SL_MILLIBEL_MIN,  20, SL_MILLIBEL_MIN,  40, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_GENERIC \
+	{ -1000, -100, 1490,  830, -2602,   7,   200,  11, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_PADDEDCELL \
+	{ -1000,-6000,  170,  100, -1204,   1,   207,   2, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_ROOM \
+	{ -1000, -454,  400,  830, -1646,   2,    53,   3, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_BATHROOM \
+	{ -1000,-1200, 1490,  540,  -370,   7,  1030,  11, 1000, 600 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_LIVINGROOM \
+	{ -1000,-6000,  500,  100, -1376,   3, -1104,   4, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_STONEROOM \
+	{ -1000, -300, 2310,  640,  -711,  12,    83,  17, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_AUDITORIUM \
+	{ -1000, -476, 4320,  590,  -789,  20,  -289,  30, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_CONCERTHALL \
+	{ -1000, -500, 3920,  700, -1230,  20,    -2,  29, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_CAVE \
+	{ -1000,    0, 2910, 1300,  -602,  15,  -302,  22, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_ARENA \
+	{ -1000, -698, 7240,  330, -1166,  20,    16,  30, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_HANGAR \
+	{ -1000,-1000, 10050,  230,  -602,  20,   198,  30, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_CARPETEDHALLWAY \
+	{ -1000,-4000,  300,  100, -1831,   2, -1630,  30, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_HALLWAY \
+	{ -1000, -300, 1490,  590, -1219,   7,   441,  11, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR \
+	{ -1000, -237, 2700,  790, -1214,  13,   395,  20, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_ALLEY \
+	{ -1000, -270, 1490,  860, -1204,   7,    -4,  11, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_FOREST \
+	{ -1000,-3300, 1490,  540, -2560, 162,  -613,  88,  790,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_CITY \
+	{ -1000, -800, 1490,  670, -2273,   7, -2217,  11,  500,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_MOUNTAINS \
+	{ -1000,-2500, 1490,  210, -2780, 300, -2014, 100,  270,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_QUARRY \
+	{ -1000,-1000, 1490,  830, SL_MILLIBEL_MIN,  61,   500,  25, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_PLAIN \
+	{ -1000,-2000, 1490,  500, -2466, 179, -2514, 100,  210,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_PARKINGLOT \
+	{ -1000,    0, 1650, 1500, -1363,   8, -1153,  12, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_SEWERPIPE \
+	{ -1000,-1000, 2810,  140,   429,  14,   648,  21,  800, 600 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_UNDERWATER \
+	{ -1000,-4000, 1490,  100,  -449,   7,  1700,  11, 1000,1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_SMALLROOM \
+	{ -1000,-600, 1100, 830, -400, 5, 500, 10, 1000, 1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_MEDIUMROOM \
+	{ -1000,-600, 1300, 830, -1000, 20, -200, 20, 1000, 1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_LARGEROOM \
+	{ -1000,-600, 1500, 830, -1600, 5, -1000, 40, 1000, 1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_MEDIUMHALL \
+	{ -1000,-600, 1800, 700, -1300, 15, -800, 30, 1000, 1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_LARGEHALL \
+	{ -1000,-600, 1800, 700, -2000, 30, -1400, 60, 1000, 1000 }
+#define SL_I3DL2_ENVIRONMENT_PRESET_PLATE \
+	{ -1000,-200, 1300, 900, 0, 2, 0, 10, 1000, 750 }
+
+
+typedef struct SLEnvironmentalReverbSettings_ {
+	SLmillibel    roomLevel;
+	SLmillibel    roomHFLevel;
+	SLmillisecond decayTime;
+	SLpermille    decayHFRatio;
+	SLmillibel    reflectionsLevel;
+	SLmillisecond reflectionsDelay;
+	SLmillibel    reverbLevel;
+	SLmillisecond reverbDelay;
+	SLpermille    diffusion;
+	SLpermille    density;
+} SLEnvironmentalReverbSettings;
+
+
+
+
+extern const SLInterfaceID SL_IID_ENVIRONMENTALREVERB;
+
+
+struct SLEnvironmentalReverbItf_;
+typedef const struct SLEnvironmentalReverbItf_ * const * SLEnvironmentalReverbItf;
+
+struct SLEnvironmentalReverbItf_ {
+	SLresult (*SetRoomLevel) (
+		SLEnvironmentalReverbItf self,
+		SLmillibel room
+	);
+	SLresult (*GetRoomLevel) (
+		SLEnvironmentalReverbItf self,
+		SLmillibel *pRoom
+	);
+	SLresult (*SetRoomHFLevel) (
+		SLEnvironmentalReverbItf self,
+		SLmillibel roomHF
+	);
+	SLresult (*GetRoomHFLevel) (
+		SLEnvironmentalReverbItf self,
+		SLmillibel *pRoomHF
+	);
+	SLresult (*SetDecayTime) (
+		SLEnvironmentalReverbItf self,
+		SLmillisecond decayTime
+	);
+	SLresult (*GetDecayTime) (
+		SLEnvironmentalReverbItf self,
+		SLmillisecond *pDecayTime
+	);
+	SLresult (*SetDecayHFRatio) (
+		SLEnvironmentalReverbItf self,
+		SLpermille decayHFRatio
+	);
+	SLresult (*GetDecayHFRatio) (
+		SLEnvironmentalReverbItf self,
+		SLpermille *pDecayHFRatio
+	);
+	SLresult (*SetReflectionsLevel) (
+		SLEnvironmentalReverbItf self,
+		SLmillibel reflectionsLevel
+	);
+	SLresult (*GetReflectionsLevel) (
+		SLEnvironmentalReverbItf self,
+		SLmillibel *pReflectionsLevel
+	);
+	SLresult (*SetReflectionsDelay) (
+		SLEnvironmentalReverbItf self,
+		SLmillisecond reflectionsDelay
+	);
+	SLresult (*GetReflectionsDelay) (
+		SLEnvironmentalReverbItf self,
+		SLmillisecond *pReflectionsDelay
+	);
+	SLresult (*SetReverbLevel) (
+		SLEnvironmentalReverbItf self,
+		SLmillibel reverbLevel
+	);
+	SLresult (*GetReverbLevel) (
+		SLEnvironmentalReverbItf self,
+		SLmillibel *pReverbLevel
+	);
+	SLresult (*SetReverbDelay) (
+		SLEnvironmentalReverbItf self,
+		SLmillisecond reverbDelay
+	);
+	SLresult (*GetReverbDelay) (
+		SLEnvironmentalReverbItf self,
+		SLmillisecond *pReverbDelay
+	);
+	SLresult (*SetDiffusion) (
+		SLEnvironmentalReverbItf self,
+		SLpermille diffusion
+	);
+	SLresult (*GetDiffusion) (
+		SLEnvironmentalReverbItf self,
+		SLpermille *pDiffusion
+	);
+	SLresult (*SetDensity) (
+		SLEnvironmentalReverbItf self,
+		SLpermille density
+	);
+	SLresult (*GetDensity) (
+		SLEnvironmentalReverbItf self,
+		SLpermille *pDensity
+	);
+	SLresult (*SetEnvironmentalReverbProperties) (
+		SLEnvironmentalReverbItf self,
+		const SLEnvironmentalReverbSettings *pProperties
+	);
+	SLresult (*GetEnvironmentalReverbProperties) (
+		SLEnvironmentalReverbItf self,
+		SLEnvironmentalReverbSettings *pProperties
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Effects Send Interface                                                    */
+/*---------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_EFFECTSEND;
+
+struct SLEffectSendItf_;
+typedef const struct SLEffectSendItf_ * const * SLEffectSendItf;
+
+struct SLEffectSendItf_ {
+	SLresult (*EnableEffectSend) (
+		SLEffectSendItf self,
+		const void *pAuxEffect,
+		SLboolean enable,
+		SLmillibel initialLevel
+	);
+	SLresult (*IsEnabled) (
+		SLEffectSendItf self,
+		const void * pAuxEffect,
+		SLboolean *pEnable
+	);
+	SLresult (*SetDirectLevel) (
+		SLEffectSendItf self,
+		SLmillibel directLevel
+	);
+	SLresult (*GetDirectLevel) (
+		SLEffectSendItf self,
+		SLmillibel *pDirectLevel
+	);
+	SLresult (*SetSendLevel) (
+		SLEffectSendItf self,
+		const void *pAuxEffect,
+		SLmillibel sendLevel
+	);
+	SLresult (*GetSendLevel)(
+		SLEffectSendItf self,
+		const void *pAuxEffect,
+		SLmillibel *pSendLevel
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* 3D Grouping Interface                                                     */
+/*---------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_3DGROUPING;
+
+
+struct SL3DGroupingItf_ ;
+typedef const struct SL3DGroupingItf_ * const * SL3DGroupingItf;
+
+struct SL3DGroupingItf_ {
+	SLresult (*Set3DGroup) (
+		SL3DGroupingItf self,
+		SLObjectItf group
+	);
+	SLresult (*Get3DGroup) (
+		SL3DGroupingItf self,
+		SLObjectItf *pGroup
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* 3D Commit Interface                                                       */
+/*---------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_3DCOMMIT;
+
+struct SL3DCommitItf_;
+typedef const struct SL3DCommitItf_* const * SL3DCommitItf;
+
+struct SL3DCommitItf_ {
+	SLresult (*Commit) (
+		SL3DCommitItf self
+	);
+	SLresult (*SetDeferred) (
+		SL3DCommitItf self,
+		SLboolean deferred
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* 3D Location Interface                                                     */
+/*---------------------------------------------------------------------------*/
+
+typedef struct SLVec3D_ {
+	SLint32	x;
+	SLint32	y;
+	SLint32	z;
+} SLVec3D;
+
+extern const SLInterfaceID SL_IID_3DLOCATION;
+
+struct SL3DLocationItf_;
+typedef const struct SL3DLocationItf_ * const * SL3DLocationItf;
+
+struct SL3DLocationItf_ {
+	SLresult (*SetLocationCartesian) (
+		SL3DLocationItf self,
+		const SLVec3D *pLocation
+	);
+	SLresult (*SetLocationSpherical) (
+		SL3DLocationItf self,
+		SLmillidegree azimuth,
+		SLmillidegree elevation,
+		SLmillimeter distance
+	);
+	SLresult (*Move) (
+		SL3DLocationItf self,
+		const SLVec3D *pMovement
+	);
+	SLresult (*GetLocationCartesian) (
+		SL3DLocationItf self,
+		SLVec3D *pLocation
+	);
+	SLresult (*SetOrientationVectors) (
+		SL3DLocationItf self,
+		const SLVec3D *pFront,
+		const SLVec3D *pAbove
+	);
+	SLresult (*SetOrientationAngles) (
+		SL3DLocationItf self,
+		SLmillidegree heading,
+		SLmillidegree pitch,
+		SLmillidegree roll
+	);
+	SLresult (*Rotate) (
+		SL3DLocationItf self,
+		SLmillidegree theta,
+		const SLVec3D *pAxis
+	);
+	SLresult (*GetOrientationVectors) (
+		SL3DLocationItf self,
+		SLVec3D *pFront,
+		SLVec3D *pUp
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* 3D Doppler Interface                                                      */
+/*---------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_3DDOPPLER;
+
+struct SL3DDopplerItf_;
+typedef const struct SL3DDopplerItf_ * const * SL3DDopplerItf;
+
+struct SL3DDopplerItf_ {
+	SLresult (*SetVelocityCartesian) (
+		SL3DDopplerItf self,
+		const SLVec3D *pVelocity
+	);
+	SLresult (*SetVelocitySpherical) (
+		SL3DDopplerItf self,
+		SLmillidegree azimuth,
+		SLmillidegree elevation,
+		SLmillimeter speed
+	);
+	SLresult (*GetVelocityCartesian) (
+		SL3DDopplerItf self,
+		SLVec3D *pVelocity
+	);
+	SLresult (*SetDopplerFactor) (
+		SL3DDopplerItf self,
+		SLpermille dopplerFactor
+	);
+	SLresult (*GetDopplerFactor) (
+		SL3DDopplerItf self,
+		SLpermille *pDopplerFactor
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* 3D Source Interface and associated defines                                */
+/* --------------------------------------------------------------------------*/
+
+#define SL_ROLLOFFMODEL_EXPONENTIAL	((SLuint32) 0x00000000)
+#define SL_ROLLOFFMODEL_LINEAR		((SLuint32) 0x00000001)
+
+
+extern const SLInterfaceID SL_IID_3DSOURCE;
+
+struct SL3DSourceItf_;
+typedef const struct SL3DSourceItf_ * const * SL3DSourceItf;
+
+struct SL3DSourceItf_ {
+	SLresult (*SetHeadRelative) (
+		SL3DSourceItf self,
+		SLboolean headRelative
+	);
+	SLresult (*GetHeadRelative) (
+		SL3DSourceItf self,
+		SLboolean *pHeadRelative
+	);
+	SLresult (*SetRolloffDistances) (
+		SL3DSourceItf self,
+		SLmillimeter minDistance,
+		SLmillimeter maxDistance
+	);
+	SLresult (*GetRolloffDistances) (
+		SL3DSourceItf self,
+		SLmillimeter *pMinDistance,
+		SLmillimeter *pMaxDistance
+	);
+	SLresult (*SetRolloffMaxDistanceMute) (
+		SL3DSourceItf self,
+		SLboolean mute
+	);
+	SLresult (*GetRolloffMaxDistanceMute) (
+		SL3DSourceItf self,
+		SLboolean *pMute
+	);
+	SLresult (*SetRolloffFactor) (
+		SL3DSourceItf self,
+		SLpermille rolloffFactor
+	);
+	SLresult (*GetRolloffFactor) (
+		SL3DSourceItf self,
+		SLpermille *pRolloffFactor
+	);
+	SLresult (*SetRoomRolloffFactor) (
+		SL3DSourceItf self,
+		SLpermille roomRolloffFactor
+	);
+	SLresult (*GetRoomRolloffFactor) (
+		SL3DSourceItf self,
+		SLpermille *pRoomRolloffFactor
+	);
+	SLresult (*SetRolloffModel) (
+		SL3DSourceItf self,
+		SLuint8 model
+	);
+	SLresult (*GetRolloffModel) (
+		SL3DSourceItf self,
+		SLuint8 *pModel
+	);
+	SLresult (*SetCone) (
+		SL3DSourceItf self,
+		SLmillidegree innerAngle,
+		SLmillidegree outerAngle,
+		SLmillibel outerLevel
+	);
+	SLresult (*GetCone) (
+		SL3DSourceItf self,
+		SLmillidegree *pInnerAngle,
+		SLmillidegree *pOuterAngle,
+		SLmillibel *pOuterLevel
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* 3D Macroscopic Interface                                                  */
+/* --------------------------------------------------------------------------*/
+
+extern const SLInterfaceID SL_IID_3DMACROSCOPIC;
+
+struct SL3DMacroscopicItf_;
+typedef const struct SL3DMacroscopicItf_ * const * SL3DMacroscopicItf;
+
+struct SL3DMacroscopicItf_ {
+	SLresult (*SetSize) (
+		SL3DMacroscopicItf self,
+		SLmillimeter width,
+		SLmillimeter height,
+		SLmillimeter depth
+	);
+	SLresult (*GetSize) (
+		SL3DMacroscopicItf self,
+		SLmillimeter *pWidth,
+		SLmillimeter *pHeight,
+		SLmillimeter *pDepth
+	);
+	SLresult (*SetOrientationAngles) (
+		SL3DMacroscopicItf self,
+		SLmillidegree heading,
+		SLmillidegree pitch,
+		SLmillidegree roll
+	);
+	SLresult (*SetOrientationVectors) (
+		SL3DMacroscopicItf self,
+		const SLVec3D *pFront,
+		const SLVec3D *pAbove
+	);
+	SLresult (*Rotate) (
+		SL3DMacroscopicItf self,
+		SLmillidegree theta,
+		const SLVec3D *pAxis
+	);
+	SLresult (*GetOrientationVectors) (
+		SL3DMacroscopicItf self,
+		SLVec3D *pFront,
+		SLVec3D *pUp
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Mute Solo Interface                                                       */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_MUTESOLO;
+
+struct SLMuteSoloItf_;
+typedef const struct SLMuteSoloItf_ * const * SLMuteSoloItf;
+
+struct SLMuteSoloItf_ {
+	SLresult (*SetChannelMute) (
+		SLMuteSoloItf self,
+		SLuint8 chan,
+		SLboolean mute
+	);
+	SLresult (*GetChannelMute) (
+		SLMuteSoloItf self,
+		SLuint8 chan,
+		SLboolean *pMute
+	);
+	SLresult (*SetChannelSolo) (
+		SLMuteSoloItf self,
+		SLuint8 chan,
+		SLboolean solo
+	);
+	SLresult (*GetChannelSolo) (
+		SLMuteSoloItf self,
+		SLuint8 chan,
+		SLboolean *pSolo
+	);
+	SLresult (*GetNumChannels) (
+		SLMuteSoloItf self,
+		SLuint8 *pNumChannels
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Dynamic Interface Management Interface and associated types and macros    */
+/* --------------------------------------------------------------------------*/
+
+#define SL_DYNAMIC_ITF_EVENT_RUNTIME_ERROR			((SLuint32) 0x00000001)
+#define SL_DYNAMIC_ITF_EVENT_ASYNC_TERMINATION		((SLuint32) 0x00000002)
+#define SL_DYNAMIC_ITF_EVENT_RESOURCES_LOST			((SLuint32) 0x00000003)
+#define SL_DYNAMIC_ITF_EVENT_RESOURCES_LOST_PERMANENTLY	((SLuint32) 0x00000004)
+#define SL_DYNAMIC_ITF_EVENT_RESOURCES_AVAILABLE		((SLuint32) 0x00000005)
+
+
+
+
+extern const SLInterfaceID SL_IID_DYNAMICINTERFACEMANAGEMENT;
+
+struct SLDynamicInterfaceManagementItf_;
+typedef const struct SLDynamicInterfaceManagementItf_ * const * SLDynamicInterfaceManagementItf;
+
+typedef void (SLAPIENTRY *slDynamicInterfaceManagementCallback) (
+	SLDynamicInterfaceManagementItf caller,
+	void * pContext,
+	SLuint32 event,
+	SLresult result,
+    const SLInterfaceID iid
+);
+
+
+struct SLDynamicInterfaceManagementItf_ {
+	SLresult (*AddInterface) (
+		SLDynamicInterfaceManagementItf self,
+		const SLInterfaceID iid,
+		SLboolean async
+	);
+	SLresult (*RemoveInterface) (
+		SLDynamicInterfaceManagementItf self,
+		const SLInterfaceID iid
+	);
+	SLresult (*ResumeInterface) (
+		SLDynamicInterfaceManagementItf self,
+		const SLInterfaceID iid,
+		SLboolean async
+	);
+	SLresult (*RegisterCallback) (
+		SLDynamicInterfaceManagementItf self,
+		slDynamicInterfaceManagementCallback callback,
+		void * pContext
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Midi Message Interface and associated types                               */
+/* --------------------------------------------------------------------------*/
+
+#define SL_MIDIMESSAGETYPE_NOTE_ON_OFF		((SLuint32) 0x00000001)
+#define SL_MIDIMESSAGETYPE_POLY_PRESSURE	((SLuint32) 0x00000002)
+#define SL_MIDIMESSAGETYPE_CONTROL_CHANGE	((SLuint32) 0x00000003)
+#define SL_MIDIMESSAGETYPE_PROGRAM_CHANGE	((SLuint32) 0x00000004)
+#define SL_MIDIMESSAGETYPE_CHANNEL_PRESSURE	((SLuint32) 0x00000005)
+#define SL_MIDIMESSAGETYPE_PITCH_BEND		((SLuint32) 0x00000006)
+#define SL_MIDIMESSAGETYPE_SYSTEM_MESSAGE	((SLuint32) 0x00000007)
+
+
+extern const SLInterfaceID SL_IID_MIDIMESSAGE;
+
+struct SLMIDIMessageItf_;
+typedef const struct SLMIDIMessageItf_ * const * SLMIDIMessageItf;
+
+typedef void (SLAPIENTRY *slMetaEventCallback) (
+	SLMIDIMessageItf caller,
+	void *pContext,
+	SLuint8 type,
+    SLuint32 length,
+	const SLuint8 *pData,
+	SLuint32 tick,
+	SLuint16 track
+);
+
+typedef void (SLAPIENTRY *slMIDIMessageCallback) (
+	SLMIDIMessageItf caller,
+	void *pContext,
+	SLuint8 statusByte,
+	SLuint32 length,
+	const SLuint8 *pData,
+	SLuint32 tick,
+	SLuint16 track
+);
+
+struct SLMIDIMessageItf_ {
+	SLresult (*SendMessage) (
+		SLMIDIMessageItf self,
+		const SLuint8 *data,
+		SLuint32 length
+	);
+	SLresult (*RegisterMetaEventCallback) (
+		SLMIDIMessageItf self,
+		slMetaEventCallback callback,
+		void *pContext
+	);
+	SLresult (*RegisterMIDIMessageCallback) (
+		SLMIDIMessageItf self,
+		slMIDIMessageCallback callback,
+		void *pContext
+	);
+	SLresult (*AddMIDIMessageCallbackFilter) (
+		SLMIDIMessageItf self,
+		SLuint32 messageType
+	);
+	SLresult (*ClearMIDIMessageCallbackFilter) (
+		SLMIDIMessageItf self
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Midi Mute Solo interface                                                  */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_MIDIMUTESOLO;
+
+struct SLMIDIMuteSoloItf_;
+typedef const struct SLMIDIMuteSoloItf_ * const * SLMIDIMuteSoloItf;
+
+struct SLMIDIMuteSoloItf_ {
+	SLresult (*SetChannelMute) (
+		SLMIDIMuteSoloItf self,
+		SLuint8 channel,
+		SLboolean mute
+	);
+	SLresult (*GetChannelMute) (
+		SLMIDIMuteSoloItf self,
+		SLuint8 channel,
+		SLboolean *pMute
+	);
+	SLresult (*SetChannelSolo) (
+		SLMIDIMuteSoloItf self,
+		SLuint8 channel,
+		SLboolean solo
+	);
+	SLresult (*GetChannelSolo) (
+		SLMIDIMuteSoloItf self,
+		SLuint8 channel,
+		SLboolean *pSolo
+	);
+	SLresult (*GetTrackCount) (
+		SLMIDIMuteSoloItf self,
+		SLuint16 *pCount
+	);
+	SLresult (*SetTrackMute) (
+		SLMIDIMuteSoloItf self,
+		SLuint16 track,
+		SLboolean mute
+	);
+	SLresult (*GetTrackMute) (
+		SLMIDIMuteSoloItf self,
+		SLuint16 track,
+		SLboolean *pMute
+	);
+	SLresult (*SetTrackSolo) (
+		SLMIDIMuteSoloItf self,
+		SLuint16 track,
+		SLboolean solo
+	);
+	SLresult (*GetTrackSolo) (
+		SLMIDIMuteSoloItf self,
+		SLuint16 track,
+		SLboolean *pSolo
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Midi Tempo interface                                                      */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_MIDITEMPO;
+
+struct SLMIDITempoItf_;
+typedef const struct SLMIDITempoItf_ * const * SLMIDITempoItf;
+
+struct SLMIDITempoItf_ {
+	SLresult (*SetTicksPerQuarterNote) (
+		SLMIDITempoItf self,
+		SLuint32 tpqn
+	);
+	SLresult (*GetTicksPerQuarterNote) (
+		SLMIDITempoItf self,
+		SLuint32 *pTpqn
+	);
+	SLresult (*SetMicrosecondsPerQuarterNote) (
+		SLMIDITempoItf self,
+		SLmicrosecond uspqn
+	);
+	SLresult (*GetMicrosecondsPerQuarterNote) (
+		SLMIDITempoItf self,
+		SLmicrosecond *uspqn
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Midi Time interface                                                       */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_MIDITIME;
+
+struct SLMIDITimeItf_;
+typedef const struct SLMIDITimeItf_ * const * SLMIDITimeItf;
+
+struct SLMIDITimeItf_ {
+	SLresult (*GetDuration) (
+		SLMIDITimeItf self,
+		SLuint32 *pDuration
+	);
+	SLresult (*SetPosition) (
+		SLMIDITimeItf self,
+		SLuint32 position
+	);
+	SLresult (*GetPosition) (
+		SLMIDITimeItf self,
+		SLuint32 *pPosition
+	);
+	SLresult (*SetLoopPoints) (
+		SLMIDITimeItf self,
+		SLuint32 startTick,
+		SLuint32 numTicks
+	);
+	SLresult (*GetLoopPoints) (
+		SLMIDITimeItf self,
+		SLuint32 *pStartTick,
+		SLuint32 *pNumTicks
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Audio Decoder Capabilities Interface                                      */
+/* --------------------------------------------------------------------------*/
+
+/*Audio Codec related defines*/
+
+#define SL_RATECONTROLMODE_CONSTANTBITRATE	((SLuint32) 0x00000001)
+#define SL_RATECONTROLMODE_VARIABLEBITRATE	((SLuint32) 0x00000002)
+
+#define SL_AUDIOCODEC_PCM         ((SLuint32) 0x00000001)
+#define SL_AUDIOCODEC_MP3         ((SLuint32) 0x00000002)
+#define SL_AUDIOCODEC_AMR         ((SLuint32) 0x00000003)
+#define SL_AUDIOCODEC_AMRWB       ((SLuint32) 0x00000004)
+#define SL_AUDIOCODEC_AMRWBPLUS   ((SLuint32) 0x00000005)
+#define SL_AUDIOCODEC_AAC         ((SLuint32) 0x00000006)
+#define SL_AUDIOCODEC_WMA         ((SLuint32) 0x00000007)
+#define SL_AUDIOCODEC_REAL        ((SLuint32) 0x00000008)
+
+#define SL_AUDIOPROFILE_PCM                   ((SLuint32) 0x00000001)
+
+#define SL_AUDIOPROFILE_MPEG1_L3              ((SLuint32) 0x00000001)
+#define SL_AUDIOPROFILE_MPEG2_L3              ((SLuint32) 0x00000002)
+#define SL_AUDIOPROFILE_MPEG25_L3             ((SLuint32) 0x00000003)
+
+#define SL_AUDIOCHANMODE_MP3_MONO             ((SLuint32) 0x00000001)
+#define SL_AUDIOCHANMODE_MP3_STEREO           ((SLuint32) 0x00000002)
+#define SL_AUDIOCHANMODE_MP3_JOINTSTEREO      ((SLuint32) 0x00000003)
+#define SL_AUDIOCHANMODE_MP3_DUAL             ((SLuint32) 0x00000004)
+
+#define SL_AUDIOPROFILE_AMR			((SLuint32) 0x00000001)
+
+#define SL_AUDIOSTREAMFORMAT_CONFORMANCE	((SLuint32) 0x00000001)
+#define SL_AUDIOSTREAMFORMAT_IF1			((SLuint32) 0x00000002)
+#define SL_AUDIOSTREAMFORMAT_IF2			((SLuint32) 0x00000003)
+#define SL_AUDIOSTREAMFORMAT_FSF			((SLuint32) 0x00000004)
+#define SL_AUDIOSTREAMFORMAT_RTPPAYLOAD	((SLuint32) 0x00000005)
+#define SL_AUDIOSTREAMFORMAT_ITU			((SLuint32) 0x00000006)
+
+#define SL_AUDIOPROFILE_AMRWB			((SLuint32) 0x00000001)
+
+#define SL_AUDIOPROFILE_AMRWBPLUS		((SLuint32) 0x00000001)
+
+#define SL_AUDIOPROFILE_AAC_AAC			((SLuint32) 0x00000001)
+
+#define SL_AUDIOMODE_AAC_MAIN			((SLuint32) 0x00000001)
+#define SL_AUDIOMODE_AAC_LC			((SLuint32) 0x00000002)
+#define SL_AUDIOMODE_AAC_SSR			((SLuint32) 0x00000003)
+#define SL_AUDIOMODE_AAC_LTP			((SLuint32) 0x00000004)
+#define SL_AUDIOMODE_AAC_HE			((SLuint32) 0x00000005)
+#define SL_AUDIOMODE_AAC_SCALABLE		((SLuint32) 0x00000006)
+#define SL_AUDIOMODE_AAC_ERLC			((SLuint32) 0x00000007)
+#define SL_AUDIOMODE_AAC_LD			((SLuint32) 0x00000008)
+#define SL_AUDIOMODE_AAC_HE_PS			((SLuint32) 0x00000009)
+#define SL_AUDIOMODE_AAC_HE_MPS			((SLuint32) 0x0000000A)
+
+#define SL_AUDIOSTREAMFORMAT_MP2ADTS		((SLuint32) 0x00000001)
+#define SL_AUDIOSTREAMFORMAT_MP4ADTS		((SLuint32) 0x00000002)
+#define SL_AUDIOSTREAMFORMAT_MP4LOAS		((SLuint32) 0x00000003)
+#define SL_AUDIOSTREAMFORMAT_MP4LATM		((SLuint32) 0x00000004)
+#define SL_AUDIOSTREAMFORMAT_ADIF		((SLuint32) 0x00000005)
+#define SL_AUDIOSTREAMFORMAT_MP4FF		((SLuint32) 0x00000006)
+#define SL_AUDIOSTREAMFORMAT_RAW			((SLuint32) 0x00000007)
+
+#define SL_AUDIOPROFILE_WMA7		((SLuint32) 0x00000001)
+#define SL_AUDIOPROFILE_WMA8		((SLuint32) 0x00000002)
+#define SL_AUDIOPROFILE_WMA9		((SLuint32) 0x00000003)
+#define SL_AUDIOPROFILE_WMA10		((SLuint32) 0x00000004)
+
+#define SL_AUDIOMODE_WMA_LEVEL1		((SLuint32) 0x00000001)
+#define SL_AUDIOMODE_WMA_LEVEL2		((SLuint32) 0x00000002)
+#define SL_AUDIOMODE_WMA_LEVEL3		((SLuint32) 0x00000003)
+#define SL_AUDIOMODE_WMA_LEVEL4		((SLuint32) 0x00000004)
+#define SL_AUDIOMODE_WMAPRO_LEVELM0	((SLuint32) 0x00000005)
+#define SL_AUDIOMODE_WMAPRO_LEVELM1	((SLuint32) 0x00000006)
+#define SL_AUDIOMODE_WMAPRO_LEVELM2	((SLuint32) 0x00000007)
+#define SL_AUDIOMODE_WMAPRO_LEVELM3	((SLuint32) 0x00000008)
+
+#define SL_AUDIOPROFILE_REALAUDIO		((SLuint32) 0x00000001)
+
+#define SL_AUDIOMODE_REALAUDIO_G2		((SLuint32) 0x00000001)
+#define SL_AUDIOMODE_REALAUDIO_8			((SLuint32) 0x00000002)
+#define SL_AUDIOMODE_REALAUDIO_10		((SLuint32) 0x00000003)
+#define SL_AUDIOMODE_REALAUDIO_SURROUND	((SLuint32) 0x00000004)
+
+typedef struct SLAudioCodecDescriptor_ {
+    SLuint32      maxChannels;
+    SLuint32      minBitsPerSample;
+    SLuint32      maxBitsPerSample;
+    SLmilliHertz  minSampleRate;
+    SLmilliHertz  maxSampleRate;
+    SLboolean     isFreqRangeContinuous;
+    SLmilliHertz *pSampleRatesSupported;
+    SLuint32      numSampleRatesSupported;
+    SLuint32      minBitRate;
+    SLuint32      maxBitRate;
+    SLboolean     isBitrateRangeContinuous;
+    SLuint32     *pBitratesSupported;
+    SLuint32      numBitratesSupported;
+    SLuint32	  profileSetting;
+    SLuint32      modeSetting;
+} SLAudioCodecDescriptor;
+
+/*Structure used to retrieve the profile and level settings supported by an audio encoder */
+
+typedef struct SLAudioCodecProfileMode_ {
+    SLuint32 profileSetting;
+    SLuint32 modeSetting;
+} SLAudioCodecProfileMode;
+
+extern const SLInterfaceID SL_IID_AUDIODECODERCAPABILITIES;
+
+struct SLAudioDecoderCapabilitiesItf_;
+typedef const struct SLAudioDecoderCapabilitiesItf_ * const * SLAudioDecoderCapabilitiesItf;
+
+struct SLAudioDecoderCapabilitiesItf_ {
+    SLresult (*GetAudioDecoders) (
+        SLAudioDecoderCapabilitiesItf self,
+        SLuint32 * pNumDecoders ,
+        SLuint32 *pDecoderIds
+    );
+    SLresult (*GetAudioDecoderCapabilities) (
+        SLAudioDecoderCapabilitiesItf self,
+        SLuint32 decoderId,
+        SLuint32 *pIndex,
+        SLAudioCodecDescriptor *pDescriptor
+    );
+};
+
+
+
+
+/*---------------------------------------------------------------------------*/
+/* Audio Encoder Capabilities Interface                                      */
+/* --------------------------------------------------------------------------*/
+
+/* Structure used when setting audio encoding parameters */
+
+typedef struct SLAudioEncoderSettings_ {
+    SLuint32 encoderId;
+    SLuint32 channelsIn;
+    SLuint32 channelsOut;
+    SLmilliHertz sampleRate;
+    SLuint32 bitRate;
+    SLuint32 bitsPerSample;
+    SLuint32 rateControl;
+    SLuint32 profileSetting;
+    SLuint32 levelSetting;
+    SLuint32 channelMode;
+    SLuint32 streamFormat;
+    SLuint32 encodeOptions;
+    SLuint32 blockAlignment;
+} SLAudioEncoderSettings;
+
+extern const SLInterfaceID SL_IID_AUDIOENCODERCAPABILITIES;
+
+struct SLAudioEncoderCapabilitiesItf_;
+typedef const struct SLAudioEncoderCapabilitiesItf_ * const * SLAudioEncoderCapabilitiesItf;
+
+struct SLAudioEncoderCapabilitiesItf_ {
+    SLresult (*GetAudioEncoders) (
+        SLAudioEncoderCapabilitiesItf self,
+        SLuint32 *pNumEncoders ,
+        SLuint32 *pEncoderIds
+    );
+    SLresult (*GetAudioEncoderCapabilities) (
+        SLAudioEncoderCapabilitiesItf self,
+        SLuint32 encoderId,
+        SLuint32 *pIndex,
+        SLAudioCodecDescriptor * pDescriptor
+    );
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Audio Encoder Interface                                                   */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_AUDIOENCODER;
+
+struct SLAudioEncoderItf_;
+typedef const struct SLAudioEncoderItf_ * const * SLAudioEncoderItf;
+
+struct SLAudioEncoderItf_ {
+    SLresult (*SetEncoderSettings) (
+        SLAudioEncoderItf		self,
+        SLAudioEncoderSettings 	*pSettings
+    );
+    SLresult (*GetEncoderSettings) (
+        SLAudioEncoderItf		self,
+        SLAudioEncoderSettings	*pSettings
+    );
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Bass Boost Interface                                                      */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_BASSBOOST;
+
+struct SLBassBoostItf_;
+typedef const struct SLBassBoostItf_ * const * SLBassBoostItf;
+
+struct SLBassBoostItf_ {
+	SLresult (*SetEnabled)(
+		SLBassBoostItf self,
+		SLboolean enabled
+	);
+	SLresult (*IsEnabled)(
+		SLBassBoostItf self,
+		SLboolean *pEnabled
+	);
+	SLresult (*SetStrength)(
+		SLBassBoostItf self,
+		SLpermille strength
+	);
+	SLresult (*GetRoundedStrength)(
+		SLBassBoostItf self,
+		SLpermille *pStrength
+	);
+	SLresult (*IsStrengthSupported)(
+		SLBassBoostItf self,
+		SLboolean *pSupported
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Pitch Interface                                                           */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_PITCH;
+
+struct SLPitchItf_;
+typedef const struct SLPitchItf_ * const * SLPitchItf;
+
+struct SLPitchItf_ {
+	SLresult (*SetPitch) (
+		SLPitchItf self,
+		SLpermille pitch
+	);
+	SLresult (*GetPitch) (
+		SLPitchItf self,
+		SLpermille *pPitch
+	);
+	SLresult (*GetPitchCapabilities) (
+		SLPitchItf self,
+		SLpermille *pMinPitch,
+		SLpermille *pMaxPitch
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Rate Pitch Interface                                                      */
+/* RatePitchItf is an interface for controlling the rate a sound is played   */
+/* back. A change in rate will cause a change in pitch.                      */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_RATEPITCH;
+
+struct SLRatePitchItf_;
+typedef const struct SLRatePitchItf_ * const * SLRatePitchItf;
+
+struct SLRatePitchItf_ {
+	SLresult (*SetRate) (
+		SLRatePitchItf self,
+		SLpermille rate
+	);
+	SLresult (*GetRate) (
+		SLRatePitchItf self,
+		SLpermille *pRate
+	);
+	SLresult (*GetRatePitchCapabilities) (
+		SLRatePitchItf self,
+		SLpermille *pMinRate,
+		SLpermille *pMaxRate
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Virtualizer Interface                                                      */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_VIRTUALIZER;
+
+struct SLVirtualizerItf_;
+typedef const struct SLVirtualizerItf_ * const * SLVirtualizerItf;
+
+struct SLVirtualizerItf_ {
+	SLresult (*SetEnabled)(
+		SLVirtualizerItf self,
+		SLboolean enabled
+	);
+	SLresult (*IsEnabled)(
+		SLVirtualizerItf self,
+		SLboolean *pEnabled
+	);
+	SLresult (*SetStrength)(
+		SLVirtualizerItf self,
+		SLpermille strength
+	);
+	SLresult (*GetRoundedStrength)(
+		SLVirtualizerItf self,
+		SLpermille *pStrength
+	);
+	SLresult (*IsStrengthSupported)(
+		SLVirtualizerItf self,
+		SLboolean *pSupported
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Visualization Interface                                                   */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_VISUALIZATION;
+
+struct SLVisualizationItf_;
+typedef const struct SLVisualizationItf_ * const * SLVisualizationItf;
+
+typedef void (SLAPIENTRY *slVisualizationCallback) (
+	void *pContext,
+	const SLuint8 waveform[],
+	const SLuint8 fft[],
+	SLmilliHertz samplerate
+);
+
+struct SLVisualizationItf_{
+	SLresult (*RegisterVisualizationCallback)(
+		SLVisualizationItf self,
+		slVisualizationCallback callback,
+		void *pContext,
+		SLmilliHertz rate
+	);
+	SLresult (*GetMaxRate)(
+		SLVisualizationItf self,
+		SLmilliHertz* pRate
+	);
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Engine Interface                                                          */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_ENGINE;
+
+struct SLEngineItf_;
+typedef const struct SLEngineItf_ * const * SLEngineItf;
+
+
+struct SLEngineItf_ {
+
+	SLresult (*CreateLEDDevice) (
+		SLEngineItf self,
+		SLObjectItf * pDevice,
+		SLuint32 deviceID,
+		SLuint32 numInterfaces,
+		const SLInterfaceID * pInterfaceIds,
+		const SLboolean * pInterfaceRequired
+	);
+	SLresult (*CreateVibraDevice) (
+		SLEngineItf self,
+		SLObjectItf * pDevice,
+		SLuint32 deviceID,
+		SLuint32 numInterfaces,
+		const SLInterfaceID * pInterfaceIds,
+		const SLboolean * pInterfaceRequired
+	);
+	SLresult (*CreateAudioPlayer) (
+		SLEngineItf self,
+		SLObjectItf * pPlayer,
+		SLDataSource *pAudioSrc,
+		SLDataSink *pAudioSnk,
+		SLuint32 numInterfaces,
+		const SLInterfaceID * pInterfaceIds,
+		const SLboolean * pInterfaceRequired
+	);
+	SLresult (*CreateAudioRecorder) (
+		SLEngineItf self,
+		SLObjectItf * pRecorder,
+		SLDataSource *pAudioSrc,
+		SLDataSink *pAudioSnk,
+		SLuint32 numInterfaces,
+		const SLInterfaceID * pInterfaceIds,
+		const SLboolean * pInterfaceRequired
+	);
+	SLresult (*CreateMidiPlayer) (
+		SLEngineItf self,
+		SLObjectItf * pPlayer,
+		SLDataSource *pMIDISrc,
+		SLDataSource *pBankSrc,
+		SLDataSink *pAudioOutput,
+		SLDataSink *pVibra,
+		SLDataSink *pLEDArray,
+		SLuint32 numInterfaces,
+		const SLInterfaceID * pInterfaceIds,
+		const SLboolean * pInterfaceRequired
+	);
+	SLresult (*CreateListener) (
+		SLEngineItf self,
+		SLObjectItf * pListener,
+		SLuint32 numInterfaces,
+		const SLInterfaceID * pInterfaceIds,
+		const SLboolean * pInterfaceRequired
+	);
+	SLresult (*Create3DGroup) (
+		SLEngineItf self,
+		SLObjectItf * pGroup,
+		SLuint32 numInterfaces,
+		const SLInterfaceID * pInterfaceIds,
+		const SLboolean * pInterfaceRequired
+	);
+	SLresult (*CreateOutputMix) (
+		SLEngineItf self,
+		SLObjectItf * pMix,
+		SLuint32 numInterfaces,
+		const SLInterfaceID * pInterfaceIds,
+		const SLboolean * pInterfaceRequired
+	);
+	SLresult (*CreateMetadataExtractor) (
+		SLEngineItf self,
+		SLObjectItf * pMetadataExtractor,
+		SLDataSource * pDataSource,
+		SLuint32 numInterfaces,
+		const SLInterfaceID * pInterfaceIds,
+		const SLboolean * pInterfaceRequired
+	);
+    SLresult (*CreateExtensionObject) (
+        SLEngineItf self,
+        SLObjectItf * pObject,
+        void * pParameters,
+        SLuint32 objectID,
+        SLuint32 numInterfaces,
+        const SLInterfaceID * pInterfaceIds,
+        const SLboolean * pInterfaceRequired
+    );
+	SLresult (*QueryNumSupportedInterfaces) (
+		SLEngineItf self,
+		SLuint32 objectID,
+		SLuint32 * pNumSupportedInterfaces
+	);
+	SLresult (*QuerySupportedInterfaces) (
+		SLEngineItf self,
+		SLuint32 objectID,
+		SLuint32 index,
+		SLInterfaceID * pInterfaceId
+	);
+    SLresult (*QueryNumSupportedExtensions) (
+        SLEngineItf self,
+        SLuint32 * pNumExtensions
+    );
+    SLresult (*QuerySupportedExtension) (
+        SLEngineItf self, 
+        SLuint32 index,
+        SLchar * pExtensionName,
+        SLint16 * pNameLength
+    );
+    SLresult (*IsExtensionSupported) (
+        SLEngineItf self, 
+        const SLchar * pExtensionName,
+        SLboolean * pSupported
+    );
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* Engine Capabilities Interface                                             */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_ENGINECAPABILITIES;
+
+struct SLEngineCapabilitiesItf_;
+typedef const struct SLEngineCapabilitiesItf_ * const * SLEngineCapabilitiesItf;
+
+struct SLEngineCapabilitiesItf_ {
+	SLresult (*QuerySupportedProfiles) (
+		SLEngineCapabilitiesItf self,
+		SLuint16 *pProfilesSupported
+	);
+	SLresult (*QueryAvailableVoices) (
+		SLEngineCapabilitiesItf self,
+		SLuint16 voiceType,
+		SLint16 *pNumMaxVoices,
+		SLboolean *pIsAbsoluteMax,
+		SLint16 *pNumFreeVoices
+	);
+	SLresult (*QueryNumberOfMIDISynthesizers) (
+		SLEngineCapabilitiesItf self,
+		SLint16 *pNumMIDIsynthesizers
+	);
+	SLresult (*QueryAPIVersion) (
+		SLEngineCapabilitiesItf self,
+		SLint16 *pMajor,
+		SLint16 *pMinor,
+		SLint16 *pStep
+	);
+	SLresult (*QueryLEDCapabilities) (
+		SLEngineCapabilitiesItf self,
+        SLuint32 *pIndex,
+		SLuint32 *pLEDDeviceID,
+		SLLEDDescriptor *pDescriptor
+	);
+	SLresult (*QueryVibraCapabilities) (
+		SLEngineCapabilitiesItf self,
+        SLuint32 *pIndex,
+		SLuint32 *pVibraDeviceID,
+		SLVibraDescriptor *pDescriptor
+	);
+	SLresult (*IsThreadSafe) (
+		SLEngineCapabilitiesItf self,
+		SLboolean *pIsThreadSafe
+	);
+};
+
+/*---------------------------------------------------------------------------*/
+/* Thread Sync Interface                                                     */
+/* --------------------------------------------------------------------------*/
+
+
+extern const SLInterfaceID SL_IID_THREADSYNC;
+
+struct SLThreadSyncItf_;
+typedef const struct SLThreadSyncItf_ * const * SLThreadSyncItf;
+
+
+struct SLThreadSyncItf_ {
+	SLresult (*EnterCriticalSection) (
+		SLThreadSyncItf self
+	);
+	SLresult (*ExitCriticalSection) (
+		SLThreadSyncItf self
+	);
+};
+
+
+/*****************************************************************************/
+/* SL engine constructor                                                     */
+/*****************************************************************************/
+
+#define SL_ENGINEOPTION_THREADSAFE	((SLuint32) 0x00000001)
+#define SL_ENGINEOPTION_LOSSOFCONTROL	((SLuint32) 0x00000002)
+
+typedef struct SLEngineOption_ {
+	SLuint32 feature;
+	SLuint32 data;
+} SLEngineOption;
+
+
+SLresult SLAPIENTRY slCreateEngine(
+	SLObjectItf             *pEngine,
+	SLuint32                numOptions,
+	const SLEngineOption    *pEngineOptions,
+	SLuint32                numInterfaces,
+	const SLInterfaceID     *pInterfaceIds,
+	const SLboolean         * pInterfaceRequired
+);
+
+SLresult SLAPIENTRY slQueryNumSupportedEngineInterfaces(
+	SLuint32 * pNumSupportedInterfaces
+);
+
+SLresult SLAPIENTRY slQuerySupportedEngineInterfaces(
+	SLuint32 index,
+	SLInterfaceID * pInterfaceId
+);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* OPENSL_ES_H_ */

+ 47 - 0
include/SLES/OpenSLES_Platform.h

@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2007-2009 The Khronos Group Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and /or associated documentation files (the "Materials "), to
+ * deal in the Materials without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Materials, and to permit persons to whom the Materials are
+ * furnished to do so, subject to 
+ * the following conditions: 
+ *
+ * The above copyright notice and this permission notice shall be included 
+ * in all copies or substantial portions of the Materials. 
+ *
+ * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE
+ * MATERIALS.
+ *
+ * OpenSLES_Platform.h - OpenSL ES version 1.0
+ *
+ */
+
+/****************************************************************************/
+/* NOTE: This file contains definitions for the base types and the          */
+/* SLAPIENTRY macro. This file **WILL NEED TO BE EDITED** to provide        */
+/* the correct definitions specific to the platform being used.             */
+/****************************************************************************/
+
+#ifndef _OPENSLES_PLATFORM_H_
+#define _OPENSLES_PLATFORM_H_
+
+typedef unsigned char               sl_uint8_t;
+typedef signed char                 sl_int8_t;
+typedef unsigned short              sl_uint16_t;
+typedef signed short                sl_int16_t;
+typedef unsigned long               sl_uint32_t;
+typedef signed long                 sl_int32_t;
+
+#ifndef SLAPIENTRY
+#define SLAPIENTRY                 /* override per-platform */
+#endif
+
+#endif /* _OPENSLES_PLATFORM_H_ */

+ 58 - 0
include/polycode/core/PolyAAssetFileProvider.h

@@ -0,0 +1,58 @@
+/*
+ Copyright (C) 2016 by Joachim Meyer
+ 
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ 
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ 
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "polycode/core/PolyCoreFileProvider.h"
+#include <android/asset_manager.h>
+
+namespace Polycode {
+    
+	class _PolyExport AAssetFile : public CoreFile {
+	public:
+		
+		long read( void * ptr, size_t size, size_t count);
+		long write( const void * ptr, size_t size, size_t count);
+		int seek(long int offset, int origin);
+		long tell();
+		
+		AAsset *file;
+	};
+	
+	class _PolyExport AAssetFileProvider : public CoreFileProvider {
+		public:
+			AAssetFileProvider(AAssetManager *manager);
+			
+			Polycode::CoreFile *openFile(const String &fileName, const String &opts);
+			void closeFile(Polycode::CoreFile *file);
+			
+			bool parseFolder(const Polycode::String& pathString, bool showHidden, std::vector<OSFileEntry> &targetVector);
+			
+			void addSource(const String &source);
+			void removeSource(const String &source);
+		
+			std::vector<String> sourceFolders;
+			
+			AAssetManager* manager;
+	};
+
+}

+ 160 - 0
include/polycode/core/PolyAndroidCore.h

@@ -0,0 +1,160 @@
+/*
+ Copyright (C) 2016 by Joachim Meyer
+ 
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ 
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ 
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <stdio.h>
+#include <assert.h>
+#include <math.h>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+#include <android/native_activity.h>
+
+#include "polycode/core/PolyGlobals.h"
+#include "polycode/core/PolyCore.h"
+#include "polycode/core/PolyInputEvent.h"
+
+#define POLYCODE_CORE AndroidCore
+
+namespace Polycode {
+
+	class PolycodeView;
+// 	class ANativeActivity;
+	
+	class AndroidEvent {
+	public:
+		int eventGroup;
+		int eventCode;
+
+		int mouseX;
+		int mouseY;
+
+		std::vector<TouchInfo> touches;
+		TouchInfo touch;
+
+		PolyKEY keyCode;
+		wchar_t unicodeChar;
+
+		char mouseButton;
+		long eventTime;
+
+		static const int EVENTBASE_PLATFORMEVENT = 0x300;
+		static const int INPUT_EVENT = EVENTBASE_PLATFORMEVENT + 0;
+		static const int SYSTEM_FOCUS_EVENT = EVENTBASE_PLATFORMEVENT + 1;
+	};
+
+
+	class AndroidCoreMutex : public CoreMutex {
+	public:
+		void lock();
+		void unlock();
+		pthread_mutex_t pMutex;
+	};
+
+	class OpenGLGraphicsInterface;
+
+	class _PolyExport AndroidCore : public Core {
+	public:
+
+		AndroidCore(PolycodeView *view, int xRes, int yRes, bool fullScreen, bool vSync, int aaLevel, int anisotropyLevel, int frameRate, int monitorIndex = -1, bool retinaSupport = false);
+		~AndroidCore();
+
+		void Render();
+		bool systemUpdate();
+		
+		void setCursor(int cursorType);
+		void openOnScreenKeyboard(bool open);
+		
+		void createThread(Threaded *target);
+		CoreMutex *createMutex();
+				
+		void copyStringToClipboard(const String& str);
+		String getClipboardString();
+		
+		void addFileSource(const String &type, const String &source);
+		
+		void createFolder(const String& folderPath);
+		void copyDiskItem(const String& itemPath, const String& destItemPath);
+		void moveDiskItem(const String& itemPath, const String& destItemPath);
+		void removeDiskItem(const String& itemPath);
+		
+		String openFolderPicker();
+		std::vector<String> openFilePicker(std::vector<CoreFileExtension> extensions, bool allowMultiple);
+		String saveFilePicker(std::vector<CoreFileExtension> extensions);
+		
+		void handleVideoModeChange(VideoModeChangeInfo *modeInfo);
+		void flushRenderContext();
+		bool isWindowInitialized();
+		
+		void openURL(String url);
+		
+		unsigned int getTicks();
+		
+		String executeExternalCommand(String command, String args, String inDirectory);
+		bool systemParseFolder(const Polycode::String& pathString, bool showHidden, std::vector<OSFileEntry> &targetVector);
+
+		void handleSystemEvent(AndroidEvent systemEvent);
+		void checkEvents();
+		
+		void setDeviceSize(Number x, Number y);
+
+		Number getBackingXRes();
+		Number getBackingYRes();
+		
+		void _setAcceleration(const Vector3& acceleration);
+		void _setGyroRotation(const Vector3& rotation);
+		
+		CoreMutex* getEGLMutex();
+		
+		bool recreateContext;
+		
+		PolyKEY mapKey(int keyCode);
+		void extractResources();
+	private:
+		PolycodeView* view;
+		
+		Number deviceWidth;
+		Number deviceHeight;
+
+		int lastMouseY;
+		int lastMouseX;
+
+		EGLDisplay display;
+		EGLSurface surface;
+		EGLContext context;
+		
+		CoreMutex* eglMutex;
+		
+		std::vector<AndroidEvent> systemInputEvents;
+
+		double pcFreq;
+
+		OpenGLGraphicsInterface *graphicsInterface;
+
+		void initKeyMap();
+		PolyKEY keyMap[1024];
+	};
+}

+ 11 - 5
include/polycode/core/PolyCore.h

@@ -94,8 +94,9 @@ namespace Polycode {
 	
 	class CoreMotionEvent : public Event {
 		public:
-			Vector3 amount;
-	};
+			CoreMotionEvent();
+            Vector3 amount;
+    };
 
 	/**
 	* The main core of the framework. The core deals with system-level functions, such as window initialization and OS interaction. Each platform has its own implementation of this base class. NOTE: SOME OF THE FUNCTIONALITY IN THE CORE IS NOT FULLY IMPLEMENTED!!
@@ -152,6 +153,12 @@ namespace Polycode {
 		*/
 		virtual void warpCursor(int x, int y) {}
 		
+		/**
+		 * Opens / closes the on-screen keyboard on a mobile device.
+		 * @param open True to open false to close
+		 */
+		virtual void openOnScreenKeyboard(bool open){};
+		
 		/**
 		* Launches a Threaded class into its own thread. See the documentation for Threaded for information on how to crated threaded classes.
 		* @param target Target threaded class.
@@ -307,12 +314,11 @@ namespace Polycode {
 
 		virtual void handleVideoModeChange(VideoModeChangeInfo *modeInfo) = 0;
 		virtual void flushRenderContext() = 0;
-		virtual void prepareRenderContext() {}
-		
+		virtual void prepareRenderContext() {}		virtual bool isWindowInitialized() {return true;};
 		CoreFile *openFile(const Polycode::String& fileName, const Polycode::String& opts);
 		void closeFile(CoreFile *file);
 		
-		void addFileSource(const String &type, const String &source);
+		virtual void addFileSource(const String &type, const String &source);
 		void removeFileSource(const String &type, const String &source);
 		
 		std::vector<OSFileEntry> parseFolder(const Polycode::String& pathString, bool showHidden);

+ 5 - 0
include/polycode/core/PolyGlobals.h

@@ -69,6 +69,7 @@ typedef unsigned int PolyRendererIndexType;
 #define PLATFORM_MAC	  2
 #define PLATFORM_UNIX	  3
 #define PLATFORM_IOS	  4
+#define PLATFORM_ANDROID  5
 
 #if defined(_WINDOWS) || defined(WINAPI_FAMILY)	 || defined(WIN32)
 	#define PLATFORM PLATFORM_WINDOWS
@@ -79,9 +80,13 @@ typedef unsigned int PolyRendererIndexType;
 	#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
 		#define PLATFORM PLATFORM_IOS
 		#define STRICT_OPENGLES2 1
+		#define POLYCODE_NUMBER_IS_SINGLE 1
 	#else
 		#define PLATFORM PLATFORM_MAC
 	#endif
+#elif defined(__ANDROID__)
+	#define PLATFORM PLATFORM_ANDROID
+	#define POLYCODE_NUMBER_IS_SINGLE 1
 #else
 	#include <cstddef>
 	#define PLATFORM PLATFORM_UNIX

+ 1 - 0
include/polycode/core/PolyOpenGLGraphicsInterface.h

@@ -58,6 +58,7 @@ THE SOFTWARE.
 		#include <EGL/egl.h>
 		#include <EGL/eglext.h>
 		#include <GLES2/gl2.h>
+		#include <GLES2/gl2ext.h>
 	#else
 		#ifdef EMSCRIPTEN
 			#include "SDL/SDL_opengl.h"

+ 57 - 0
include/polycode/core/PolyOpenSLAudioInterface.h

@@ -0,0 +1,57 @@
+/*
+ Copyright (C) 2016 by Joachim Meyer
+ 
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ 
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ 
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "polycode/core/PolyGlobals.h"
+#include "polycode/core/PolySoundManager.h"
+
+#include <SLES/OpenSLES_Android.h>
+
+namespace Polycode {
+	
+	class OpenSLAudioInterface : public AudioInterface {
+	public:
+		OpenSLAudioInterface();
+		~OpenSLAudioInterface();
+		
+		void setMixer(AudioMixer* newMixer);
+		
+		void initOpenSL();
+		void terminateOpenSL();
+		
+		static void queueCallback(SLAndroidSimpleBufferQueueItf caller, void *pContext);
+		
+		SLAndroidSimpleBufferQueueItf mPlayerQueue;
+	private:
+		int16_t* buffer;
+		
+		SLObjectItf mEngineObj;
+		SLEngineItf mEngine;
+		SLObjectItf mOutputMixObj;
+		
+		SLObjectItf mPlayerObj; 
+		SLPlayItf mPlayer;
+		SLVolumeItf mVolume;
+    };
+}
+

+ 1 - 1
include/polycode/core/PolySDLCore.h

@@ -59,7 +59,7 @@ namespace Polycode {
 		void flushRenderContext();
 		
 		void handleVideoModeChange(VideoModeChangeInfo *modeInfo);
-		void setVideoMode(int xRes, int yRes, bool fullScreen, bool vSync, int aaLevel, int anisotropyLevel, bool retinaSupport = true);
+//		void setVideoMode(int xRes, int yRes, bool fullScreen, bool vSync, int aaLevel, int anisotropyLevel, bool retinaSupport = true);
 		void createThread(Threaded *target);
 		std::vector<Rectangle> getVideoModes();
 		

Некоторые файлы не были показаны из-за большого количества измененных файлов