Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Changeset 8284


Ignore:
Timestamp:
Apr 21, 2011, 6:58:23 PM (14 years ago)
Author:
rgrieder
Message:

Merged revisions 7978 - 8096 from kicklib to kicklib2.

Location:
code/branches/kicklib2
Files:
2 deleted
295 edited
25 copied

Legend:

Unmodified
Added
Removed
  • code/branches/kicklib2

  • code/branches/kicklib2/CMakeLists.txt

    r7383 r8284  
    101101OPTION(ORXONOX_RELEASE "Enable when building restributable releases" FALSE)
    102102
     103IF(APPLE)
     104  # Set 10.5 as the base SDK by default
     105  SET(XCODE_ATTRIBUTE_SDKROOT macosx10.5)
     106
     107  # 10.6 sets x86_64 as the default architecture.
     108  # Because Carbon isn't supported on 64-bit and we still need it, force the architectures to ppc and i386
     109  IF(CMAKE_OSX_ARCHITECTURES MATCHES "x86_64")
     110    SET(CMAKE_OSX_ARCHITECTURES "i386")
     111  ENDIF()
     112  IF(CMAKE_OSX_ARCHITECTURES MATCHES "ppc64")
     113    SET(CMAKE_OSX_ARCHITECTURES "ppc")
     114  ENDIF()
     115  IF(NOT CMAKE_OSX_ARCHITECTURES)
     116    SET(CMAKE_OSX_ARCHITECTURES "i386")
     117  ENDIF()
     118ENDIF()
     119
    103120########### Subfolders and Subscripts ###########
     121
     122# General build and compiler options and configurations
     123INCLUDE(CompilerConfig)
    104124
    105125# Library finding
    106126INCLUDE(LibraryConfig)
    107 
    108 # General build and compiler options and configurations
    109 INCLUDE(CompilerConfig)
    110127
    111128# Configure installation paths and options
  • code/branches/kicklib2/cmake/CompilerConfig.cmake

    r5781 r8284  
    3434  MESSAGE(STATUS "Warning: Your compiler is not officially supported.")
    3535ENDIF()
    36 
    37 SET(COMPILER_CONFIG_USER_SCRIPT "" CACHE FILEPATH
    38     "Specify a CMake script if you wish to write your own compiler config.
    39      See CompilerConfigGCC.cmake or CompilerConfigMSVC.cmake for examples.")
    40 IF(COMPILER_CONFIG_USER_SCRIPT)
    41   IF(EXISTS ${CMAKE_MODULE_PATH}/${COMPILER_CONFIG_USER_SCRIPT})
    42     INCLUDE(${CMAKE_MODULE_PATH}/${COMPILER_CONFIG_USER_SCRIPT})
    43   ENDIF()
    44 ENDIF(COMPILER_CONFIG_USER_SCRIPT)
  • code/branches/kicklib2/cmake/CompilerConfigGCC.cmake

    r7458 r8284  
    2626INCLUDE(FlagUtilities)
    2727INCLUDE(CompareVersionStrings)
     28INCLUDE(CheckCXXCompilerFlag)
    2829
    2930# Shortcut for CMAKE_COMPILER_IS_GNUCXX and ..._GNUC
     
    3637  OUTPUT_VARIABLE GCC_VERSION
    3738)
    38 
    39 # Complain about incompatibilities
    40 COMPARE_VERSION_STRINGS("${GCC_VERSION}" "4.4.0" _compare_result)
    41 IF(NOT _compare_result LESS 0)
    42   IF(${Boost_VERSION} LESS 103700)
    43     MESSAGE(STATUS "Warning: Boost versions earlier than 1.37 may not compile with GCC 4.4 or later!")
    44   ENDIF()
    45 ENDIF()
    4639
    4740# GCC may not support #pragma GCC system_header correctly when using
     
    7265
    7366# CMake doesn't seem to set the PIC flags right on certain 64 bit systems
    74 IF(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64")
     67IF(NOT MINGW AND ${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64")
    7568  ADD_COMPILER_FLAGS("-fPIC" CACHE)
     69ENDIF()
     70
     71# Use SSE if possible
     72# Commented because this might not work for cross compiling
     73#CHECK_CXX_COMPILER_FLAG(-msse _gcc_have_sse)
     74#IF(_gcc_have_sse)
     75#  ADD_COMPILER_FLAGS("-msse" CACHE)
     76#ENDIF()
     77
     78IF(NOT MINGW)
     79  # Have GCC visibility?
     80  CHECK_CXX_COMPILER_FLAG("-fvisibility=hidden" _gcc_have_visibility)
     81  IF(_gcc_have_visibility)
     82    # Note: There is a possible bug with the flag in gcc < 4.2 and Debug versions
     83    COMPARE_VERSION_STRINGS("${GCC_VERSION}" "4.2.0" _compare_result)
     84    IF(NOT CMAKE_BUILD_TYPE STREQUAL "Debug" OR _compare_result GREATER -1)
     85      ADD_COMPILER_FLAGS("-DORXONOX_GCC_VISIBILITY -fvisibility=default -fvisibility-inlines-hidden" CACHE)
     86    ENDIF()
     87  ENDIF(_gcc_have_visibility)
    7688ENDIF()
    7789
  • code/branches/kicklib2/cmake/CompilerConfigMSVC.cmake

    r7818 r8284  
    6060
    6161# Overwrite CMake default flags here for the individual configurations
    62 SET_COMPILER_FLAGS("-MDd -Od -Zi -D_DEBUG -RTC1" Debug          CACHE)
    63 SET_COMPILER_FLAGS("-MD  -O2     -DNDEBUG"       Release        CACHE)
    64 SET_COMPILER_FLAGS("-MD  -O2 -Zi -DNDEBUG"       RelWithDebInfo CACHE)
    65 SET_COMPILER_FLAGS("-MD  -O1     -DNDEBUG"       MinSizeRel     CACHE)
    66 ADD_COMPILER_FLAGS("-D_SECURE_SCL=0"       MSVC9 ReleaseAll     CACHE)
     62SET_COMPILER_FLAGS("-MDd -Od -Oi -Zi -D_DEBUG -RTC1" Debug          CACHE)
     63SET_COMPILER_FLAGS("-MD  -O2         -DNDEBUG"       Release        CACHE)
     64SET_COMPILER_FLAGS("-MD  -O2     -Zi -DNDEBUG"       RelWithDebInfo CACHE)
     65SET_COMPILER_FLAGS("-MD  -O1         -DNDEBUG"       MinSizeRel     CACHE)
     66
     67# Enable non standard floating point optimisations
     68# Note: It hasn't been checked yet whether we have code that might break
     69#ADD_COMPILER_FLAGS("-fp:fast" CACHE)
     70
     71# No iterator checking for release builds (MSVC 8 dosn't understand this though)
     72ADD_COMPILER_FLAGS("-D_SECURE_SCL=0" ReleaseAll CACHE)
     73
     74# Newer MSVC versions come with std::shared_ptr which conflicts with
     75# boost::shared_ptr in cpptcl. And since we don't yet use the new C++ standard
     76# anyway, disable it completely.
     77ADD_COMPILER_FLAGS("-D_HAS_CPP0X=0" CACHE)
    6778
    6879# Use Link time code generation for Release config if ORXONOX_RELEASE is defined
  • code/branches/kicklib2/cmake/LibraryConfig.cmake

    r8283 r8284  
    4040# On Windows using a package causes way less problems
    4141SET(_option_msg "Set this to true to use precompiled dependecy archives")
    42 IF(WIN32)
     42IF(WIN32 OR APPLE)
    4343  OPTION(DEPENDENCY_PACKAGE_ENABLE "${_option_msg}" ON)
    44 ELSE(WIN32)
     44ELSE()
    4545  OPTION(DEPENDENCY_PACKAGE_ENABLE "${_option_msg}" FALSE)
    46 ENDIF(WIN32)
     46ENDIF()
    4747
    4848# Scripts for specific library and CMake config
    4949INCLUDE(LibraryConfigTardis)
    50 INCLUDE(LibraryConfigApple)
    5150
    5251IF(DEPENDENCY_PACKAGE_ENABLE)
     
    5958  ELSEIF(MSVC90)
    6059    SET(_compiler_prefix msvc9)
     60  ELSEIF(MSVC100)
     61    SET(_compiler_prefix msvc10)
    6162  ENDIF()
    6263  FIND_PATH(DEPENDENCY_PACKAGE_DIR
     
    7374                   "Disable LIBRARY_USE_PACKAGE if you have none intalled.")
    7475  ELSE()
    75     INCLUDE(PackageConfigMinGW)
    76     INCLUDE(PackageConfigMSVC)
    77     INCLUDE(PackageConfig) # For both msvc and mingw
     76    IF(WIN32)
     77      INCLUDE(PackageConfigMinGW)
     78      INCLUDE(PackageConfigMSVC)
     79      INCLUDE(PackageConfig) # For both msvc and mingw
     80    ELSEIF(APPLE)
     81      INCLUDE(PackageConfigOSX)
     82    ENDIF(WIN32)
    7883  ENDIF()
    7984ENDIF(DEPENDENCY_PACKAGE_ENABLE)
     
    141146
    142147##### Boost #####
    143 # Expand the next statement if newer boost versions than 1.36.1 are released
     148# Expand the next statement if newer boost versions are released
    144149SET(Boost_ADDITIONAL_VERSIONS 1.37 1.37.0 1.38 1.38.0 1.39 1.39.0 1.40 1.40.0
    145                               1.41 1.41.0 1.42 1.42.0 1.43 1.43.0 1.44 1.44.0)
     150                              1.41 1.41.0 1.42 1.42.0 1.43 1.43.0 1.44 1.44.0
     151                              1.45 1.45.0 1.46 1.46.0 1.46.1)
    146152IF( NOT TARDIS )
    147153  FIND_PACKAGE(Boost 1.35 REQUIRED thread filesystem system date_time)
     
    149155# No auto linking, so this option is useless anyway
    150156MARK_AS_ADVANCED(Boost_LIB_DIAGNOSTIC_DEFINITIONS)
     157# Complain about incompatibilities
     158IF(GCC_VERSION)
     159  COMPARE_VERSION_STRINGS("${GCC_VERSION}" "4.4.0" _compare_result)
     160  IF(NOT _compare_result LESS 0)
     161    IF(${Boost_VERSION} LESS 103700)
     162      MESSAGE(STATUS "Warning: Boost versions earlier than 1.37 may not compile with GCC 4.4 or later!")
     163    ENDIF()
     164  ENDIF()
     165ENDIF()
    151166
    152167
  • code/branches/kicklib2/cmake/PackageConfig.cmake

    r8283 r8284  
    2525 #
    2626
    27 # Check package version info
    28 # MAJOR: Breaking change
    29 # MINOR: No breaking changes by the dependency package
    30 #        For example any code running on 3.0 should still run on 3.1
    31 #        But you can specify that the code only runs on 3.1 and higher
    32 #        or 4.0 and higher (so both 3.1 and 4.0 will work).
    33 IF(MSVC)
    34   SET(ALLOWED_MINIMUM_VERSIONS 4.3 5.1 6.0)
    35 ELSE()
    36   SET(ALLOWED_MINIMUM_VERSIONS 4.1 5.2)
    37 ENDIF()
    38 
    39 IF(NOT EXISTS ${DEPENDENCY_PACKAGE_DIR}/version.txt)
    40   SET(DEPENDENCY_VERSION 1.0)
    41 ELSE()
    42   # Get version from file
    43   FILE(READ ${DEPENDENCY_PACKAGE_DIR}/version.txt _file_content)
    44   SET(_match)
    45   STRING(REGEX MATCH "([0-9]+.[0-9]+)" _match ${_file_content})
    46   IF(_match)
    47     SET(DEPENDENCY_VERSION ${_match})
    48   ELSE()
    49     MESSAGE(FATAL_ERROR "The version.txt file in the dependency file has corrupt version information.")
    50   ENDIF()
    51 ENDIF()
    52 
    53 INCLUDE(CompareVersionStrings)
    54 SET(_version_match FALSE)
    55 FOREACH(_version ${ALLOWED_MINIMUM_VERSIONS})
    56   # Get major version
    57   STRING(REGEX REPLACE "^([0-9]+)\\..*$" "\\1" _major_version "${_version}")
    58   COMPARE_VERSION_STRINGS(${DEPENDENCY_VERSION} ${_major_version} _result TRUE)
    59   IF(_result EQUAL 0)
    60     COMPARE_VERSION_STRINGS(${DEPENDENCY_VERSION} ${_version} _result FALSE)
    61     IF(NOT _result LESS 0)
    62       SET(_version_match TRUE)
    63     ENDIF()
    64   ENDIF()
    65 ENDFOREACH(_version)
    66 IF(NOT _version_match)
    67   MESSAGE(FATAL_ERROR "Your dependency package version is ${DEPENDENCY_VERSION}\n"
    68           "Possible required versions: ${ALLOWED_MINIMUM_VERSIONS}\n"
    69           "You can get a new version from www.orxonox.net")
    70 ENDIF()
    71 
    7227IF(NOT _INTERNAL_PACKAGE_MESSAGE)
    7328  MESSAGE(STATUS "Using library package for the dependencies.")
     
    7732# Ogre versions >= 1.7 require the POCO library on Windows with MSVC for threading
    7833COMPARE_VERSION_STRINGS(${DEPENDENCY_VERSION} 5 _result TRUE)
    79 IF(NOT _result EQUAL -1 AND NOT MINGW)
    80     SET(POCO_REQUIRED TRUE)
     34IF(NOT _result EQUAL -1 AND NOT APPLE)
     35  SET(POCO_REQUIRED TRUE)
    8136ENDIF()
    8237
  • code/branches/kicklib2/cmake/PackageConfigMSVC.cmake

    r7818 r8284  
    2828IF(MSVC)
    2929
     30  INCLUDE(CheckPackageVersion)
     31  CHECK_PACKAGE_VERSION(4.3 6.0)
     32
    3033  # 64 bit system?
    3134  IF(CMAKE_SIZEOF_VOID_P EQUAL 8)
     
    3639
    3740  # Choose right MSVC version
    38   STRING(REGEX REPLACE "^Visual Studio ([0-9][0-9]?) .*$" "\\1"
     41  STRING(REGEX REPLACE "^Visual Studio ([0-9][0-9]?).*$" "\\1"
    3942         _msvc_version "${CMAKE_GENERATOR}")
    4043
     
    5659  SET(TCL_LIBRARY  ${DEP_LIBRARY_DIR}/tcl85.lib CACHE FILEPATH "")
    5760  SET(ZLIB_LIBRARY ${DEP_LIBRARY_DIR}/zdll.lib  CACHE FILEPATH "")
     61  # Part of Platform SDK and usually gets linked automatically
     62  SET(WMI_LIBRARY  wbemuuid.lib)
    5863
    5964ENDIF(MSVC)
  • code/branches/kicklib2/cmake/PackageConfigMinGW.cmake

    r5781 r8284  
    2828IF(MINGW)
    2929
     30  INCLUDE(CheckPackageVersion)
     31  CHECK_PACKAGE_VERSION(6.0)
     32
    3033  # 64 bit system?
    3134  IF(CMAKE_SIZEOF_VOID_P EQUAL 8)
     
    4851  # to specify the libraries ourselves.
    4952  SET(TCL_LIBRARY  ${DEP_BINARY_DIR}/tcl85.dll CACHE FILEPATH "")
    50   SET(ZLIB_LIBRARY ${DEP_BINARY_DIR}/zlib1.dll CACHE FILEPATH "")
     53  SET(ZLIB_LIBRARY ${DEP_BINARY_DIR}/libzlib.dll CACHE FILEPATH "")
     54
     55  # Not included in MinGW, so we need to supply it for OIS
     56  SET(WMI_INCLUDE_DIR ${DEP_INCLUDE_DIR}/wmi/include)
     57  SET(WMI_LIBRARY     ${DEP_LIBRARY_DIR}/wbemuuid.lib)
    5158
    5259ENDIF(MINGW)
  • code/branches/kicklib2/cmake/tools/CheckOGREPlugins.cmake

    r8264 r8284  
    5252      NAMES ${_plugin}
    5353      PATHS $ENV{OGRE_HOME} $ENV{OGRE_PLUGIN_DIR}
    54       PATH_SUFFIXES bin/Release bin/release Release release lib lib/OGRE bin
     54      PATH_SUFFIXES bin/Release bin/release Release release lib lib/OGRE bin Ogre.framework/Resources
    5555    )
    5656    FIND_LIBRARY(OGRE_PLUGIN_${_plugin}_DEBUG
    5757      NAMES ${_plugin}d ${_plugin}_d ${_plugin}
    5858      PATHS $ENV{OGRE_HOME} $ENV{OGRE_PLUGIN_DIR}
    59       PATH_SUFFIXES bin/Debug bin/debug Debug debug lib lib/OGRE bin
     59      PATH_SUFFIXES bin/Debug bin/debug Debug debug lib lib/OGRE bin Ogre.framework/Resources
    6060    )
    6161    # We only need at least one render system. Check at the end.
  • code/branches/kicklib2/cmake/tools/FindALUT.cmake

    r7163 r8284  
    1 # - Locate FreeAlut
    2 # This module defines
    3 #  ALUT_LIBRARY
    4 #  ALUT_FOUND, if false, do not try to link against Alut
    5 #  ALUT_INCLUDE_DIR, where to find the headers
    6 #
    7 # $ALUTDIR is an environment variable that would
    8 # correspond to the ./configure --prefix=$ALUTDIR
    9 # used in building Alut.
    10 #
    11 # Created by Eric Wing. This was influenced by the FindSDL.cmake module.
    12 # On OSX, this will prefer the Framework version (if found) over others.
    13 # People will have to manually change the cache values of
    14 # ALUT_LIBRARY to override this selection.
    15 # Tiger will include OpenAL as part of the System.
    16 # But for now, we have to look around.
    17 # Other (Unix) systems should be able to utilize the non-framework paths.
    18 #
    19 # Several changes and additions by Fabian 'x3n' Landau
    20 # Some simplifications by Adrian Friedli and Reto Grieder
    21 #                 > www.orxonox.net <
     1 #
     2 #             ORXONOX - the hottest 3D action shooter ever to exist
     3 #                             > www.orxonox.net <
     4 #
     5 #        This program is free software; you can redistribute it and/or
     6 #         modify it under the terms of the GNU General Public License
     7 #        as published by the Free Software Foundation; either version 2
     8 #            of the License, or (at your option) any later version.
     9 #
     10 #       This program is distributed in the hope that it will be useful,
     11 #        but WITHOUT ANY WARRANTY; without even the implied warranty of
     12 #        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     13 #                 GNU General Public License for more details.
     14 #
     15 #   You should have received a copy of the GNU General Public License along
     16 #      with this program; if not, write to the Free Software Foundation,
     17 #     Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
     18 #
     19 #
     20 #  Author:
     21 #    Kevin Young
     22 #  Description:
     23 #    Variables defined:
     24 #      ALUT_FOUND
     25 #      ALUT_INCLUDE_DIR
     26 #      ALUT_LIBRARY
     27 #
    2228
    2329INCLUDE(FindPackageHandleStandardArgs)
    2430INCLUDE(HandleLibraryTypes)
    2531
    26 FIND_PATH(ALUT_INCLUDE_DIR AL/alut.h
    27   PATHS
    28   $ENV{ALUTDIR}
    29   ~/Library/Frameworks/OpenAL.framework
    30   /Library/Frameworks/OpenAL.framework
    31   /System/Library/Frameworks/OpenAL.framework # Tiger
    32   PATH_SUFFIXES include include/OpenAL include/AL Headers
     32FIND_PATH(ALUT_INCLUDE_DIR alut.h
     33  PATHS $ENV{ALUTDIR}
     34  PATH_SUFFIXES include include/AL Headers Headers/AL
    3335)
    34 
    35 # I'm not sure if I should do a special casing for Apple. It is
    36 # unlikely that other Unix systems will find the framework path.
    37 # But if they do ([Next|Open|GNU]Step?),
    38 # do they want the -framework option also?
    39 IF(${ALUT_INCLUDE_DIR} MATCHES ".framework")
    40 
    41   STRING(REGEX REPLACE "(.*)/.*\\.framework/.*" "\\1" ALUT_FRAMEWORK_PATH_TMP ${ALUT_INCLUDE_DIR})
    42   IF("${ALUT_FRAMEWORK_PATH_TMP}" STREQUAL "/Library/Frameworks"
    43       OR "${ALUT_FRAMEWORK_PATH_TMP}" STREQUAL "/System/Library/Frameworks"
    44       )
    45     # String is in default search path, don't need to use -F
    46     SET (ALUT_LIBRARY_OPTIMIZED "-framework OpenAL" CACHE STRING "OpenAL framework for OSX")
    47   ELSE()
    48     # String is not /Library/Frameworks, need to use -F
    49     SET(ALUT_LIBRARY_OPTIMIZED "-F${ALUT_FRAMEWORK_PATH_TMP} -framework OpenAL" CACHE STRING "OpenAL framework for OSX")
    50   ENDIF()
    51   # Clear the temp variable so nobody can see it
    52   SET(ALUT_FRAMEWORK_PATH_TMP "" CACHE INTERNAL "")
    53 
    54 ELSE()
    55   FIND_LIBRARY(ALUT_LIBRARY_OPTIMIZED
    56     NAMES alut
    57     PATHS $ENV{ALUTDIR}
    58     PATH_SUFFIXES lib libs
    59   )
    60   FIND_LIBRARY(ALUT_LIBRARY_DEBUG
    61     NAMES alutd alut_d alutD alut_D
    62     PATHS $ENV{ALUTDIR}
    63     PATH_SUFFIXES lib libs
    64   )
    65 ENDIF()
     36FIND_LIBRARY(ALUT_LIBRARY_OPTIMIZED
     37  NAMES alut ALUT
     38  PATHS $ENV{ALUTDIR}
     39  PATH_SUFFIXES lib bin/Release bin/release Release release ALUT
     40)
     41FIND_LIBRARY(ALUT_LIBRARY_DEBUG
     42  NAMES alutd alut_d alutD alut_D ALUTd ALUT_d ALUTD ALUT_D
     43  PATHS $ENV{ALUTDIR}
     44  PATH_SUFFIXES lib bin/Debug bin/debug Debug debug ALUT
     45)
    6646
    6747# Handle the REQUIRED argument and set ALUT_FOUND
    6848FIND_PACKAGE_HANDLE_STANDARD_ARGS(ALUT DEFAULT_MSG
    69     ALUT_LIBRARY_OPTIMIZED
    70     ALUT_INCLUDE_DIR
     49  ALUT_LIBRARY_OPTIMIZED
     50  ALUT_INCLUDE_DIR
    7151)
    7252
     
    7555
    7656MARK_AS_ADVANCED(
    77     ALUT_INCLUDE_DIR
    78     ALUT_LIBRARY_OPTIMIZED
    79     ALUT_LIBRARY_DEBUG
     57  ALUT_INCLUDE_DIR
     58  ALUT_LIBRARY_OPTIMIZED
     59  ALUT_LIBRARY_DEBUG
    8060)
  • code/branches/kicklib2/cmake/tools/FindCEGUI.cmake

    r8283 r8284  
    3131INCLUDE(HandleLibraryTypes)
    3232
    33 # Find headers
     33# Find CEGUI headers
    3434FIND_PATH(CEGUI_INCLUDE_DIR CEGUI.h
    3535  PATHS $ENV{CEGUIDIR}
     
    4444  NAMES CEGUIBase CEGUI
    4545  PATHS $ENV{CEGUIDIR}
    46   PATH_SUFFIXES lib bin
     46  PATH_SUFFIXES lib bin CEGUIBase.framework CEGUI.framework
    4747)
    4848FIND_LIBRARY(CEGUI_LIBRARY_DEBUG
     
    5454)
    5555
     56# Find CEGUILua headers
     57FIND_PATH(CEGUILUA_INCLUDE_DIR CEGUILua.h
     58  PATHS $ENV{CEGUIDIR} ${CEGUI_INCLUDE_DIR}/ScriptingModules/LuaScriptModule
     59  PATH_SUFFIXES include include/CEGUI CEGUILuaScriptModule.framework/Headers
     60)
    5661# Find CEGUILua libraries
    5762FIND_LIBRARY(CEGUILUA_LIBRARY_OPTIMIZED
    5863  NAMES CEGUILua CEGUILuaScriptModule
    5964  PATHS $ENV{CEGUIDIR}
    60   PATH_SUFFIXES lib bin
     65  PATH_SUFFIXES lib bin CEGUILuaScriptModule.framework
    6166)
    6267FIND_LIBRARY(CEGUILUA_LIBRARY_DEBUG
     
    6671)
    6772
     73# Find CEGUI Tolua++ include file
     74# We only need to add this path since we use tolua++ like a normal
     75# dependency but it is shipped with CEGUILua.
     76FIND_PATH(CEGUI_TOLUA_INCLUDE_DIR tolua++.h
     77  PATHS
     78    ${CEGUILUA_INCLUDE_DIR}
     79    # For newer CEGUI versions >= 0.7
     80    ${CEGUILUA_INCLUDE_DIR}/support/tolua++
     81    # For Apples
     82    $ENV{CEGUIDIR}
     83  PATH_SUFFIXES ceguitolua++.framework/Headers
     84  NO_DEFAULT_PATH # MUST be in CEGUILUA_INCLUDE_DIR somewhere
     85)
    6886# Find CEGUI Tolua++ libraries
    6987FIND_LIBRARY(CEGUI_TOLUA_LIBRARY_OPTIMIZED
    70   NAMES CEGUItoluapp tolua++
     88  NAMES CEGUItoluapp tolua++ ceguitolua++
    7189  PATHS $ENV{CEGUIDIR}
    72   PATH_SUFFIXES lib bin
     90  PATH_SUFFIXES lib bin ceguitolua++.framework
    7391)
    7492FIND_LIBRARY(CEGUI_TOLUA_LIBRARY_DEBUG
     
    8199COMPARE_VERSION_STRINGS("${CEGUI_VERSION}" "0.7" _version_compare TRUE)
    82100IF(_version_compare GREATER -1)
     101  # Find CEGUI OGRE Renderer headers
     102  FIND_PATH(CEGUI_OGRE_RENDERER_INCLUDE_DIR CEGUIOgreRenderer.h
     103    PATHS $ENV{CEGUIDIR} ${CEGUI_INCLUDE_DIR}/RendererModules/Ogre
     104    PATH_SUFFIXES include include/CEGUI CEGUI.framework/Headers
     105  )
    83106  # Find CEGUI OGRE Renderer libraries
    84107  FIND_LIBRARY(CEGUI_OGRE_RENDERER_LIBRARY_OPTIMIZED
     
    92115    PATH_SUFFIXES lib bin
    93116  )
    94   SET(CEGUI_OGRE_RENDERER_LIBRARY_NAME CEGUI_OGRE_RENDERER_LIBRARY_OPTIMIZED)
     117  SET(CEGUI_OGRE_RENDERER_REQUIRED_VARIABLES
     118    CEGUI_OGRE_RENDERER_INCLUDE_DIR
     119    CEGUI_OGRE_RENDERER_LIBRARY_OPTIMIZED
     120  )
    95121ELSE()
     122  SET(CEGUI_OLD_VERSION TRUE)
    96123  SET(CEGUI_OGRE_RENDERER_BUILD_REQUIRED TRUE)
    97124ENDIF()
     
    102129  CEGUI_INCLUDE_DIR
    103130  CEGUI_LIBRARY_OPTIMIZED
     131  CEGUILUA_INCLUDE_DIR
    104132  CEGUILUA_LIBRARY_OPTIMIZED
     133  CEGUI_TOLUA_INCLUDE_DIR
    105134  CEGUI_TOLUA_LIBRARY_OPTIMIZED
    106   ${CEGUI_OGRE_RENDERER_LIBRARY_NAME}
     135  ${CEGUI_OGRE_RENDERER_REQUIRED_VARIABLES}
    107136)
    108137
     
    119148  CEGUI_LIBRARY_OPTIMIZED
    120149  CEGUI_LIBRARY_DEBUG
     150  CEGUILUA_INCLUDE_DIR
    121151  CEGUILUA_LIBRARY_OPTIMIZED
    122152  CEGUILUA_LIBRARY_DEBUG
     153  CEGUI_TOLUA_INCLUDE_DIR
    123154  CEGUI_TOLUA_LIBRARY_OPTIMIZED
    124155  CEGUI_TOLUA_LIBRARY_DEBUG
     156  CEGUI_OGRE_RENDERER_INCLUDE_DIR
    125157  CEGUI_OGRE_RENDERER_LIBRARY_OPTIMIZED
    126158  CEGUI_OGRE_RENDERER_LIBRARY_DEBUG
  • code/branches/kicklib2/cmake/tools/FindOgg.cmake

    r7163 r8284  
    2222)
    2323FIND_LIBRARY(OGG_LIBRARY_OPTIMIZED
    24   NAMES ogg
     24  NAMES ogg ogg-0
    2525  PATHS $ENV{OGGDIR}
    2626  PATH_SUFFIXES lib
  • code/branches/kicklib2/cmake/tools/FindPOCO.cmake

    r7285 r8284  
    2929FIND_PATH(POCO_INCLUDE_DIR Poco/Poco.h
    3030  PATHS $ENV{POCODIR}
    31   PATH_SUFFIXES include
     31  PATH_SUFFIXES include Foundation/include
    3232)
    3333FIND_LIBRARY(POCO_LIBRARY_OPTIMIZED
  • code/branches/kicklib2/cmake/tools/FindVorbis.cmake

    r7163 r8284  
    2222)
    2323FIND_LIBRARY(VORBIS_LIBRARY_OPTIMIZED
    24   NAMES vorbis
     24  NAMES vorbis vorbis-0
    2525  PATHS $ENV{VORBISDIR}
    2626  PATH_SUFFIXES lib
     
    3232)
    3333FIND_LIBRARY(VORBISFILE_LIBRARY_OPTIMIZED
    34   NAMES vorbisfile
     34  NAMES vorbisfile vorbisfile-3
    3535  PATHS $ENV{VORBISDIR}
    3636  PATH_SUFFIXES lib
  • code/branches/kicklib2/cmake/tools/GenerateToluaBindings.cmake

    r7415 r8284  
    3232 #    RUNTIME_LIBRARY_DIRECTORY - Working directory
    3333 #
     34
     35# Workaround for XCode: The folder where the bind files are written to has
     36# to be present beforehand.
     37# We have to do this here because the header files are all stored in a single
     38# location per configuration.
     39IF(CMAKE_CONFIGURATION_TYPES)
     40  FOREACH(_dir ${CMAKE_CONFIGURATION_TYPES})
     41    FILE(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/src/toluabind/${_dir}")
     42  ENDFOREACH(_dir)
     43ENDIF()
    3444
    3545FUNCTION(GENERATE_TOLUA_BINDINGS _tolua_package _target_source_files)
  • code/branches/kicklib2/cmake/tools/TargetUtilities.cmake

    r8079 r8284  
    5353 #    This function also installs the target!
    5454 #  Prerequisistes:
    55  #    ORXONOX_DEFAULT_LINK, ORXONOX_CONFIG_FILES
     55 #    ORXONOX_DEFAULT_LINK, ORXONOX_CONFIG_FILES, ORXONOX_CONFIG_FILES_GENERATED
    5656 #  Parameters:
    5757 #    _target_name, ARGN for the macro arguments
     
    169169    GENERATE_TOLUA_BINDINGS(${_target_name_capitalised} _${_target_name}_files
    170170                            INPUTFILES ${_arg_TOLUA_FILES})
     171    # Workaround for XCode: The folder where the bind files are written to has
     172    # to be present beforehand.
     173    IF(CMAKE_CONFIGURATION_TYPES)
     174      FOREACH(_dir ${CMAKE_CONFIGURATION_TYPES})
     175        FILE(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${_dir})
     176      ENDFOREACH(_dir)
     177    ENDIF()
    171178  ENDIF()
    172179
     
    192199
    193200    IF(NOT _arg_ORXONOX_EXTERNAL)
    194       # Move the prereqs.h file to the config section
     201      # Move the ...Prereqs.h and the PCH files to the 'Config' section
    195202      IF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${_target_name_capitalised}Prereqs.h)
    196203        SOURCE_GROUP("Config" FILES ${_target_name_capitalised}Prereqs.h)
    197204      ENDIF()
    198       # Add config files to the config section
    199       LIST(APPEND _${_target_name}_files ${ORXONOX_CONFIG_FILES})
     205      IF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${_arg_PCH_FILE})
     206        SOURCE_GROUP("Config" FILES ${CMAKE_CURRENT_SOURCE_DIR}/${_arg_PCH_FILE})
     207      ENDIF()
     208      # Also include all config files
     209      LIST(APPEND _${_target_name}_files ${ORXONOX_CONFIG_FILES} ${ORXONOX_CONFIG_FILES_GENERATED})
     210      # Add unprocessed config files to the 'Config' section
    200211      SOURCE_GROUP("Config" FILES ${ORXONOX_CONFIG_FILES})
     212      # Add generated config files to the 'Generated' section
     213      SOURCE_GROUP("Generated" FILES ${ORXONOX_CONFIG_FILES_GENERATED})
    201214    ENDIF()
    202215  ENDIF()
     
    217230  IF(_arg_ORXONOX_EXTERNAL)
    218231    REMOVE_COMPILER_FLAGS("-W3 -W4" MSVC)
    219     ADD_COMPILER_FLAGS("-w")
     232    ADD_COMPILER_FLAGS("-w" NOT MSVC)
     233    ADD_COMPILER_FLAGS("-W0" MSVC)
    220234  ENDIF()
    221235
    222236  # Don't compile header files
    223237  FOREACH(_file ${_${_target_name}_files})
    224     IF(NOT _file MATCHES "\\.(c|cc|cpp|cxx)$")
     238    IF(NOT _file MATCHES "\\.(c|cc|cpp|cxx|mm)$")
    225239      SET_SOURCE_FILES_PROPERTIES(${_file} PROPERTIES HEADER_FILE_ONLY TRUE)
    226240    ENDIF()
  • code/branches/kicklib2/data/gui/scripts/AudioMenu.lua

    r8079 r8284  
    3232    table.insert(themeList, "Default")
    3333    table.insert(themeList, "Drum n' Bass")
     34    table.insert(themeList, "8-Bit Style")
     35    table.insert(themeList, "Corny Jazz")
    3436    for k,v in pairs(themeList) do
    3537        item = CEGUI.createListboxTextItem(v)
     
    3941    if orxonox.getConfig("MoodManager", "mood_") == "dnb" then
    4042        listboxwindow:setItemSelectState(1,true)
     43    elseif orxonox.getConfig("MoodManager", "mood_") == "eightbit" then
     44        listboxwindow:setItemSelectState(2,true)
     45    elseif orxonox.getConfig("MoodManager", "mood_") == "jazzy" then
     46        listboxwindow:setItemSelectState(3,true)
    4147    else
    4248        listboxwindow:setItemSelectState(0,true)
     
    168174    if listboxwindow:isItemSelected(1) then
    169175        orxonox.config("MoodManager", "mood_", "dnb")
     176    elseif listboxwindow:isItemSelected(2) then
     177        orxonox.config("MoodManager", "mood_", "eightbit")
     178    elseif listboxwindow:isItemSelected(3) then
     179        orxonox.config("MoodManager", "mood_", "jazzy")
    170180    else
    171181        orxonox.config("MoodManager", "mood_", "default")
  • code/branches/kicklib2/src/CMakeLists.txt

    r8283 r8284  
    6969# Set the search paths for include files
    7070INCLUDE_DIRECTORIES(
     71  # OrxonoxConfig.h
     72  ${CMAKE_CURRENT_BINARY_DIR}
     73
     74  # All includes in "externals" should be prefixed with the path
     75  # relative to "external" to avoid conflicts
     76  ${CMAKE_CURRENT_SOURCE_DIR}/external
     77  # Include directories needed even if only included by Orxonox
     78  ${CMAKE_CURRENT_SOURCE_DIR}/external/bullet
     79  ${CMAKE_CURRENT_SOURCE_DIR}/external/ois
     80
    7181  # External
    7282  ${OGRE_INCLUDE_DIR}
    7383  ${CEGUI_INCLUDE_DIR}
     84  ${CEGUI_TOLUA_INCLUDE_DIR}
    7485  #${ENET_INCLUDE_DIR}
    7586  ${Boost_INCLUDE_DIRS}
     
    8394  ${DIRECTX_INCLUDE_DIR}
    8495  ${ZLIB_INCLUDE_DIR}
     96)
    8597
    86   # All includes in "externals" should be prefixed with the path
    87   # relative to "external" to avoid conflicts
    88   ${CMAKE_CURRENT_SOURCE_DIR}/external
    89   # Include directories needed even if only included by Orxonox
    90   ${CMAKE_CURRENT_SOURCE_DIR}/external/bullet
    91   ${CMAKE_CURRENT_SOURCE_DIR}/external/ois
    92 
    93   # OrxonoxConfig.h
    94   ${CMAKE_CURRENT_BINARY_DIR}
    95 )
     98IF(CEGUI_OLD_VERSION)
     99  INCLUDE_DIRECTORIES(${CEGUILUA_INCLUDE_DIR})
     100ENDIF()
    96101
    97102IF (DBGHELP_FOUND)
     
    165170    SET(MSVC_PLATFORM "Win32")
    166171  ENDIF()
    167   STRING(REGEX REPLACE "^Visual Studio ([0-9][0-9]?) .*$" "\\1"
    168          VISUAL_STUDIO_VERSION_SIMPLE "${CMAKE_GENERATOR}")
    169   CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/orxonox-main.vcproj.user.in" "${CMAKE_CURRENT_BINARY_DIR}/orxonox-main.vcproj.user")
     172  IF(MSVC10)
     173    CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/orxonox-main.vcxproj.user.in" "${CMAKE_CURRENT_BINARY_DIR}/orxonox-main.vcxproj.user")
     174  ELSE()
     175    STRING(REGEX REPLACE "^Visual Studio ([0-9][0-9]?).*$" "\\1"
     176           VISUAL_STUDIO_VERSION_SIMPLE "${CMAKE_GENERATOR}")
     177    CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/orxonox-main.vcproj.user.in" "${CMAKE_CURRENT_BINARY_DIR}/orxonox-main.vcproj.user")
     178  ENDIF()
    170179ENDIF(MSVC)
    171180
  • code/branches/kicklib2/src/OrxonoxConfig.cmake

    r7818 r8284  
    3232
    3333# Global switch to disable Precompiled Header Files
    34 IF(PCH_COMPILER_SUPPORT)
     34# Note: PCH temporarily disabled on Mac because of severe problems
     35IF(PCH_COMPILER_SUPPORT AND NOT APPLE)
    3536  OPTION(PCH_ENABLE "Global PCH switch" TRUE)
    3637ENDIF()
     
    5354ENDIF()
    5455
    55 # 32/64 bit system check
    56 IF(CMAKE_SIZEOF_VOID_P EQUAL 8)
    57   SET(ORXONOX_ARCH_64 TRUE)
    58 ELSE()
    59   SET(ORXONOX_ARCH_32 TRUE)
    60 ENDIF()
    61 
    6256# Platforms
    6357SET(ORXONOX_PLATFORM_WINDOWS ${WIN32})
     
    7569ENDIF(MSVC)
    7670
    77 # Check iso646.h include (literal operators)
     71# Check some non standard system includes
    7872INCLUDE(CheckIncludeFileCXX)
    7973CHECK_INCLUDE_FILE_CXX(iso646.h HAVE_ISO646_H)
     74CHECK_INCLUDE_FILE_CXX(stdint.h HAVE_STDINT_H)
     75
     76# Part of a woraround for OS X warnings. See OrxonoxConfig.h.in
     77SET(ORX_HAVE_STDINT_H ${HAVE_STDINT_H})
    8078
    8179IF(MSVC)
     
    106104
    107105SET(ORXONOX_CONFIG_FILES
    108   ${CMAKE_CURRENT_BINARY_DIR}/OrxonoxConfig.h
    109106  ${CMAKE_CURRENT_SOURCE_DIR}/OrxonoxConfig.h.in
    110   ${CMAKE_CURRENT_BINARY_DIR}/SpecialConfig.h
    111107  ${CMAKE_CURRENT_SOURCE_DIR}/SpecialConfig.h.in
    112108)
     109SET(ORXONOX_CONFIG_FILES_GENERATED
     110  ${CMAKE_CURRENT_BINARY_DIR}/OrxonoxConfig.h
     111  ${CMAKE_CURRENT_BINARY_DIR}/SpecialConfig.h
     112)
  • code/branches/kicklib2/src/OrxonoxConfig.h.in

    r7818 r8284  
    8080
    8181// Architecture
    82 #cmakedefine ORXONOX_ARCH_32
    83 #cmakedefine ORXONOX_ARCH_64
     82#if defined(__x86_64__) || defined(_M_X64) || defined(__powerpc64__) || defined(__alpha__) || defined(__ia64__) || defined(__s390__) || defined(__s390x__)
     83#   define ORXONOX_ARCH_64
     84#else
     85#   define ORXONOX_ARCH_32
     86#endif
    8487
    8588// See if we can use __forceinline or if we need to use __inline instead
    8689#cmakedefine HAVE_FORCEINLINE
    87 #ifndef FORCEINLINE
     90#ifndef ORX_FORCEINLINE
    8891#  ifdef HAVE_FORCEINLINE
    89 #    define FORCEINLINE __forceinline
     92#    define ORX_FORCEINLINE __forceinline
    9093#  else
    91 #    define FORCEINLINE __inline
     94#    define ORX_FORCEINLINE __inline
    9295#  endif
    9396#endif
     
    158161#endif
    159162
    160 #cmakedefine HAVE_STDINT_H
    161 #ifdef HAVE_STDINT_H
     163// On OS X some headers already define HAVE_STDINT_H and that spits out
     164// some warnings. Therefore we use this macro.
     165// Note: This requires some extra code in OrxonoxConfig.cmake
     166#cmakedefine ORX_HAVE_STDINT_H
     167#ifdef ORX_HAVE_STDINT_H
    162168#  include <stdint.h>
    163169#elif defined(ORXONOX_COMPILER_MSVC)
  • code/branches/kicklib2/src/SpecialConfig.h.in

    r8283 r8284  
    9292
    9393    // OGRE PLUGINS
     94    // Apple has trouble finding OGRE plugins because of its install-name convention
     95    // Adopting the executable_path structure for later use in app bundles
    9496#ifdef NDEBUG
    9597    const char ogrePlugins[] = "@OGRE_PLUGINS_RELEASE@";
    9698#  ifdef DEPENDENCY_PACKAGE_ENABLE
    97     const char ogrePluginsDirectory[] = ".";
     99#    ifdef ORXONOX_PLATFORM_APPLE
     100       const char ogrePluginsDirectory[] = "@executable_path/../Plugins";
     101#    else
     102       const char ogrePluginsDirectory[] = ".";
     103#    endif
    98104#  else
    99105    const char ogrePluginsDirectory[] = "@OGRE_PLUGINS_FOLDER_RELEASE@";
     
    102108    const char ogrePlugins[] = "@OGRE_PLUGINS_DEBUG@";
    103109#  ifdef DEPENDENCY_PACKAGE_ENABLE
    104     const char ogrePluginsDirectory[] = ".";
     110#    ifdef ORXONOX_PLATFORM_APPLE
     111       const char ogrePluginsDirectory[] = "@OGRE_PLUGINS_FOLDER_DEBUG@";
     112#    else
     113       const char ogrePluginsDirectory[] = ".";
     114#    endif
    105115#  else
    106116    const char ogrePluginsDirectory[] = "@OGRE_PLUGINS_FOLDER_DEBUG@";
  • code/branches/kicklib2/src/external/bullet/Bullet-C-Api.h

    r5781 r8284  
    148148        extern  void plSetOrientation(plRigidBodyHandle object, const plQuaternion orientation);
    149149        extern  void plSetEuler(plReal yaw,plReal pitch,plReal roll, plQuaternion orient);
     150        extern  void plSetOpenGLMatrix(plRigidBodyHandle object, plReal* matrix);
    150151
    151152        typedef struct plRayCastResult {
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btAxisSweep3.h

    r5781 r8284  
    151151       
    152152        virtual void    rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0), const btVector3& aabbMax = btVector3(0,0,0));
     153        virtual void    aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback);
     154
    153155       
    154156        void quantize(BP_FP_INT_TYPE* out, const btVector3& point, int isMax) const;
     
    281283                        {
    282284                                rayCallback.process(getHandle(m_pEdges[axis][i].m_handle));
     285                        }
     286                }
     287        }
     288}
     289
     290template <typename BP_FP_INT_TYPE>
     291void    btAxisSweep3Internal<BP_FP_INT_TYPE>::aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback)
     292{
     293        if (m_raycastAccelerator)
     294        {
     295                m_raycastAccelerator->aabbTest(aabbMin,aabbMax,callback);
     296        } else
     297        {
     298                //choose axis?
     299                BP_FP_INT_TYPE axis = 0;
     300                //for each proxy
     301                for (BP_FP_INT_TYPE i=1;i<m_numHandles*2+1;i++)
     302                {
     303                        if (m_pEdges[axis][i].IsMax())
     304                        {
     305                                Handle* handle = getHandle(m_pEdges[axis][i].m_handle);
     306                                if (TestAabbAgainstAabb2(aabbMin,aabbMax,handle->m_aabbMin,handle->m_aabbMax))
     307                                {
     308                                        callback.process(handle);
     309                                }
    283310                        }
    284311                }
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btBroadphaseInterface.h

    r5781 r8284  
    2727
    2828
    29 struct  btBroadphaseRayCallback
     29struct  btBroadphaseAabbCallback
     30{
     31        virtual ~btBroadphaseAabbCallback() {}
     32        virtual bool    process(const btBroadphaseProxy* proxy) = 0;
     33};
     34
     35
     36struct  btBroadphaseRayCallback : public btBroadphaseAabbCallback
    3037{
    3138        ///added some cached data to accelerate ray-AABB tests
     
    3542
    3643        virtual ~btBroadphaseRayCallback() {}
    37         virtual bool    process(const btBroadphaseProxy* proxy) = 0;
    3844};
    3945
     
    5561        virtual void    rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0), const btVector3& aabbMax = btVector3(0,0,0)) = 0;
    5662
     63        virtual void    aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback) = 0;
     64
    5765        ///calculateOverlappingPairs is optional: incremental algorithms (sweep and prune) might do it during the set aabb
    5866        virtual void    calculateOverlappingPairs(btDispatcher* dispatcher)=0;
     
    6674
    6775        ///reset broadphase internal structures, to ensure determinism/reproducability
    68         virtual void resetPool(btDispatcher* dispatcher) {};
     76        virtual void resetPool(btDispatcher* dispatcher) { (void) dispatcher; };
    6977
    7078        virtual void    printStats() = 0;
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btBroadphaseProxy.h

    r5781 r8284  
    4747        MINKOWSKI_SUM_SHAPE_PROXYTYPE,
    4848        MINKOWSKI_DIFFERENCE_SHAPE_PROXYTYPE,
     49        BOX_2D_SHAPE_PROXYTYPE,
     50        CONVEX_2D_SHAPE_PROXYTYPE,
    4951        CUSTOM_CONVEX_SHAPE_TYPE,
    5052//concave shapes
     
    140142        }
    141143
     144        static SIMD_FORCE_INLINE bool   isNonMoving(int proxyType)
     145        {
     146                return (isConcave(proxyType) && !(proxyType==GIMPACT_SHAPE_PROXYTYPE));
     147        }
     148
    142149        static SIMD_FORCE_INLINE bool   isConcave(int proxyType)
    143150        {
     
    149156                return (proxyType == COMPOUND_SHAPE_PROXYTYPE);
    150157        }
     158
     159        static SIMD_FORCE_INLINE bool   isSoftBody(int proxyType)
     160        {
     161                return (proxyType == SOFTBODY_SHAPE_PROXYTYPE);
     162        }
     163
    151164        static SIMD_FORCE_INLINE bool isInfinite(int proxyType)
    152165        {
    153166                return (proxyType == STATIC_PLANE_PROXYTYPE);
    154167        }
     168
     169        static SIMD_FORCE_INLINE bool isConvex2d(int proxyType)
     170        {
     171                return (proxyType == BOX_2D_SHAPE_PROXYTYPE) || (proxyType == CONVEX_2D_SHAPE_PROXYTYPE);
     172        }
     173
    155174       
    156175}
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btDbvt.cpp

    r5781 r8284  
    6262        {
    6363                getmaxdepth(node->childs[0],depth+1,maxdepth);
    64                 getmaxdepth(node->childs[0],depth+1,maxdepth);
     64                getmaxdepth(node->childs[1],depth+1,maxdepth);
    6565        } else maxdepth=btMax(maxdepth,depth);
    6666}
     
    239239        for(int i=0,ni=leaves.size();i<ni;++i)
    240240        {
    241                 if(dot(axis,leaves[i]->volume.Center()-org)<0)
     241                if(btDot(axis,leaves[i]->volume.Center()-org)<0)
    242242                        left.push_back(leaves[i]);
    243243                else
     
    320320                                for(int j=0;j<3;++j)
    321321                                {
    322                                         ++splitcount[j][dot(x,axis[j])>0?1:0];
     322                                        ++splitcount[j][btDot(x,axis[j])>0?1:0];
    323323                                }
    324324                        }
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btDbvt.h

    r5781 r8284  
    3333
    3434// Template implementation of ICollide
    35 #ifdef WIN32
     35#ifdef _WIN32
    3636#if (defined (_MSC_VER) && _MSC_VER >= 1400)
    3737#define DBVT_USE_TEMPLATE               1
     
    5858
    5959//SSE gives errors on a MSVC 7.1
    60 #ifdef BT_USE_SSE
     60#if defined (BT_USE_SSE) && defined (_WIN32)
    6161#define DBVT_SELECT_IMPL                DBVT_IMPL_SSE
    6262#define DBVT_MERGE_IMPL                 DBVT_IMPL_SSE
     
    9393
    9494#if DBVT_USE_MEMMOVE
    95 #ifndef __CELLOS_LV2__
     95#if !defined( __CELLOS_LV2__) && !defined(__MWERKS__)
    9696#include <memory.h>
    9797#endif
     
    485485                pi=btVector3(mi.x(),mi.y(),mi.z());break;
    486486        }
    487         if((dot(n,px)+o)<0)             return(-1);
    488         if((dot(n,pi)+o)>=0)    return(+1);
     487        if((btDot(n,px)+o)<0)           return(-1);
     488        if((btDot(n,pi)+o)>=0)  return(+1);
    489489        return(0);
    490490}
     
    497497                b[(signs>>1)&1]->y(),
    498498                b[(signs>>2)&1]->z());
    499         return(dot(p,v));
     499        return(btDot(p,v));
    500500}
    501501
     
    948948                                                                DBVT_IPOLICY) const
    949949{
     950        (void) rayTo;
    950951        DBVT_CHECKTYPE
    951952        if(root)
     
    962963                {
    963964                        const btDbvtNode*       node=stack[--depth];
    964                         bounds[0] = node->volume.Mins()+aabbMin;
    965                         bounds[1] = node->volume.Maxs()+aabbMax;
     965                        bounds[0] = node->volume.Mins()-aabbMax;
     966                        bounds[1] = node->volume.Maxs()-aabbMin;
    966967                        btScalar tmin=1.f,lambda_min=0.f;
    967968                        unsigned int result1=false;
     
    10011002                        rayDir.normalize ();
    10021003
    1003                         ///what about division by zero? --> just set rayDirection[i] to INF/1e30
     1004                        ///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT
    10041005                        btVector3 rayDirectionInverse;
    1005                         rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[0];
    1006                         rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[1];
    1007                         rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[2];
     1006                        rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0];
     1007                        rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1];
     1008                        rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2];
    10081009                        unsigned int signs[3] = { rayDirectionInverse[0] < 0.0, rayDirectionInverse[1] < 0.0, rayDirectionInverse[2] < 0.0};
    10091010
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2007 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516///btDbvtBroadphase implementation by Nathanael Presson
    1617
     
    124125        m_needcleanup           =       true;
    125126        m_releasepaircache      =       (paircache!=0)?false:true;
    126         m_prediction            =       1/(btScalar)2;
     127        m_prediction            =       0;
    127128        m_stageCurrent          =       0;
    128129        m_fixedleft                     =       0;
     
    250251}
    251252
     253
     254struct  BroadphaseAabbTester : btDbvt::ICollide
     255{
     256        btBroadphaseAabbCallback& m_aabbCallback;
     257        BroadphaseAabbTester(btBroadphaseAabbCallback& orgCallback)
     258                :m_aabbCallback(orgCallback)
     259        {
     260        }
     261        void                                    Process(const btDbvtNode* leaf)
     262        {
     263                btDbvtProxy*    proxy=(btDbvtProxy*)leaf->data;
     264                m_aabbCallback.process(proxy);
     265        }
     266};     
     267
     268void    btDbvtBroadphase::aabbTest(const btVector3& aabbMin,const btVector3& aabbMax,btBroadphaseAabbCallback& aabbCallback)
     269{
     270        BroadphaseAabbTester callback(aabbCallback);
     271
     272        const ATTRIBUTE_ALIGNED16(btDbvtVolume) bounds=btDbvtVolume::FromMM(aabbMin,aabbMax);
     273                //process all children, that overlap with  the given AABB bounds
     274        m_sets[0].collideTV(m_sets[0].m_root,bounds,callback);
     275        m_sets[1].collideTV(m_sets[1].m_root,bounds,callback);
     276
     277}
     278
     279
     280
    252281//
    253282void                                                    btDbvtBroadphase::setAabb(              btBroadphaseProxy* absproxy,
     
    315344                }       
    316345        }
     346}
     347
     348
     349//
     350void                                                    btDbvtBroadphase::setAabbForceUpdate(           btBroadphaseProxy* absproxy,
     351                                                                                                                  const btVector3& aabbMin,
     352                                                                                                                  const btVector3& aabbMax,
     353                                                                                                                  btDispatcher* /*dispatcher*/)
     354{
     355        btDbvtProxy*                                            proxy=(btDbvtProxy*)absproxy;
     356        ATTRIBUTE_ALIGNED16(btDbvtVolume)       aabb=btDbvtVolume::FromMM(aabbMin,aabbMax);
     357        bool    docollide=false;
     358        if(proxy->stage==STAGECOUNT)
     359        {/* fixed -> dynamic set        */
     360                m_sets[1].remove(proxy->leaf);
     361                proxy->leaf=m_sets[0].insert(aabb,proxy);
     362                docollide=true;
     363        }
     364        else
     365        {/* dynamic set                         */
     366                ++m_updates_call;
     367                /* Teleporting                  */
     368                m_sets[0].update(proxy->leaf,aabb);
     369                ++m_updates_done;
     370                docollide=true;
     371        }
     372        listremove(proxy,m_stageRoots[proxy->stage]);
     373        proxy->m_aabbMin = aabbMin;
     374        proxy->m_aabbMax = aabbMax;
     375        proxy->stage    =       m_stageCurrent;
     376        listappend(proxy,m_stageRoots[m_stageCurrent]);
     377        if(docollide)
     378        {
     379                m_needcleanup=true;
     380                if(!m_deferedcollide)
     381                {
     382                        btDbvtTreeCollider      collider(this);
     383                        m_sets[1].collideTTpersistentStack(m_sets[1].m_root,proxy->leaf,collider);
     384                        m_sets[0].collideTTpersistentStack(m_sets[0].m_root,proxy->leaf,collider);
     385                }
     386        }       
    317387}
    318388
     
    572642                m_deferedcollide        =       false;
    573643                m_needcleanup           =       true;
    574                 m_prediction            =       1/(btScalar)2;
    575644                m_stageCurrent          =       0;
    576645                m_fixedleft                     =       0;
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2007 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516///btDbvtBroadphase implementation by Nathanael Presson
    1617#ifndef BT_DBVT_BROADPHASE_H
     
    102103        void                                                    collide(btDispatcher* dispatcher);
    103104        void                                                    optimize();
    104         /* btBroadphaseInterface Implementation */
     105       
     106        /* btBroadphaseInterface Implementation */
    105107        btBroadphaseProxy*                              createProxy(const btVector3& aabbMin,const btVector3& aabbMax,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy);
    106         void                                                    destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
    107         void                                                    setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher);
    108         virtual void    rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0), const btVector3& aabbMax = btVector3(0,0,0));
     108        virtual void                                    destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
     109        virtual void                                    setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher);
     110        virtual void                                    rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0), const btVector3& aabbMax = btVector3(0,0,0));
     111        virtual void                                    aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback);
    109112
    110         virtual void    getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const;
    111         void                                                    calculateOverlappingPairs(btDispatcher* dispatcher);
    112         btOverlappingPairCache*                 getOverlappingPairCache();
    113         const btOverlappingPairCache*   getOverlappingPairCache() const;
    114         void                                                    getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const;
    115         void                                                    printStats();
    116         static void                                             benchmark(btBroadphaseInterface*);
     113        virtual void                                    getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const;
     114        virtual void                                    calculateOverlappingPairs(btDispatcher* dispatcher);
     115        virtual btOverlappingPairCache* getOverlappingPairCache();
     116        virtual const btOverlappingPairCache*   getOverlappingPairCache() const;
     117        virtual void                                    getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const;
     118        virtual void                                    printStats();
    117119
    118 
    119         void    performDeferredRemoval(btDispatcher* dispatcher);
    120120
    121121        ///reset broadphase internal structures, to ensure determinism/reproducability
    122122        virtual void resetPool(btDispatcher* dispatcher);
    123123
     124        void    performDeferredRemoval(btDispatcher* dispatcher);
     125       
     126        void    setVelocityPrediction(btScalar prediction)
     127        {
     128                m_prediction = prediction;
     129        }
     130        btScalar getVelocityPrediction() const
     131        {
     132                return m_prediction;
     133        }
     134
     135        ///this setAabbForceUpdate is similar to setAabb but always forces the aabb update.
     136        ///it is not part of the btBroadphaseInterface but specific to btDbvtBroadphase.
     137        ///it bypasses certain optimizations that prevent aabb updates (when the aabb shrinks), see
     138        ///http://code.google.com/p/bullet/issues/detail?id=223
     139        void                                                    setAabbForceUpdate(             btBroadphaseProxy* absproxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* /*dispatcher*/);
     140
     141        static void                                             benchmark(btBroadphaseInterface*);
     142
     143
    124144};
    125145
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btDispatcher.h

    r5781 r8284  
    4747                m_useEpa(true),
    4848                m_allowedCcdPenetration(btScalar(0.04)),
    49                 m_useConvexConservativeDistanceUtil(true),
     49                m_useConvexConservativeDistanceUtil(false),
    5050                m_convexConservativeDistanceThreshold(0.0f),
     51                m_convexMaxDistanceUseCPT(false),
    5152                m_stackAllocator(0)
    5253        {
     
    6566        bool            m_useConvexConservativeDistanceUtil;
    6667        btScalar        m_convexConservativeDistanceThreshold;
     68        bool            m_convexMaxDistanceUseCPT;
    6769        btStackAlloc*   m_stackAllocator;
    6870};
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h

    r5781 r8284  
    134134        virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const
    135135        {
    136                 aabbMin.setValue(-1e30f,-1e30f,-1e30f);
    137                 aabbMax.setValue(1e30f,1e30f,1e30f);
     136                aabbMin.setValue(-BT_LARGE_FLOAT,-BT_LARGE_FLOAT,-BT_LARGE_FLOAT);
     137                aabbMax.setValue(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT);
    138138        }
    139139
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btOverlappingPairCache.cpp

    r5781 r8284  
    241241        int count = m_overlappingPairArray.size();
    242242        int oldCapacity = m_overlappingPairArray.capacity();
    243         void* mem = &m_overlappingPairArray.expand();
     243        void* mem = &m_overlappingPairArray.expandNonInitializing();
    244244
    245245        //this is where we add an actual pair, so also call the 'ghost'
     
    468468                return 0;
    469469       
    470         void* mem = &m_overlappingPairArray.expand();
     470        void* mem = &m_overlappingPairArray.expandNonInitializing();
    471471        btBroadphasePair* pair = new (mem) btBroadphasePair(*proxy0,*proxy1);
    472472       
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btOverlappingPairCache.h

    r5781 r8284  
    458458        virtual void    sortOverlappingPairs(btDispatcher* dispatcher)
    459459        {
     460        (void) dispatcher;
    460461        }
    461462
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp

    r5781 r8284  
    1818#include "LinearMath/btAabbUtil2.h"
    1919#include "LinearMath/btIDebugDraw.h"
     20#include "LinearMath/btSerializer.h"
    2021
    2122#define RAYAABB2
     
    7980btVector3 color[4]=
    8081{
    81         btVector3(255,0,0),
    82         btVector3(0,255,0),
    83         btVector3(0,0,255),
    84         btVector3(0,255,255)
     82        btVector3(1,0,0),
     83        btVector3(0,1,0),
     84        btVector3(0,0,1),
     85        btVector3(0,1,1)
    8586};
    8687#endif //DEBUG_PATCH_COLORS
     
    475476        ///what about division by zero? --> just set rayDirection[i] to 1.0
    476477        btVector3 rayDirectionInverse;
    477         rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[0];
    478         rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[1];
    479         rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[2];
     478        rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0];
     479        rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1];
     480        rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2];
    480481        unsigned int sign[3] = { rayDirectionInverse[0] < 0.0, rayDirectionInverse[1] < 0.0, rayDirectionInverse[2] < 0.0};
    481482#endif
     
    494495                bounds[1] = rootNode->m_aabbMaxOrg;
    495496                /* Add box cast extents */
    496                 bounds[0] += aabbMin;
    497                 bounds[1] += aabbMax;
     497                bounds[0] -= aabbMax;
     498                bounds[1] -= aabbMin;
    498499
    499500                aabbOverlap = TestAabbAgainstAabb2(rayAabbMin,rayAabbMax,rootNode->m_aabbMinOrg,rootNode->m_aabbMaxOrg);
     
    562563        lambda_max = rayDirection.dot(rayTarget-raySource);
    563564        ///what about division by zero? --> just set rayDirection[i] to 1.0
    564         rayDirection[0] = rayDirection[0] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDirection[0];
    565         rayDirection[1] = rayDirection[1] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDirection[1];
    566         rayDirection[2] = rayDirection[2] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDirection[2];
     565        rayDirection[0] = rayDirection[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDirection[0];
     566        rayDirection[1] = rayDirection[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDirection[1];
     567        rayDirection[2] = rayDirection[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDirection[2];
    567568        unsigned int sign[3] = { rayDirection[0] < 0.0, rayDirection[1] < 0.0, rayDirection[2] < 0.0};
    568569#endif
     
    618619                        bounds[1] = unQuantize(rootNode->m_quantizedAabbMax);
    619620                        /* Add box cast extents */
    620                         bounds[0] += aabbMin;
    621                         bounds[1] += aabbMax;
     621                        bounds[0] -= aabbMax;
     622                        bounds[1] -= aabbMin;
    622623                        btVector3 normal;
    623624#if 0
     
    831832}
    832833
    833 unsigned btQuantizedBvh::calculateSerializeBufferSize()
     834unsigned btQuantizedBvh::calculateSerializeBufferSize() const
    834835{
    835836        unsigned baseSize = sizeof(btQuantizedBvh) + getAlignmentSerializationPadding();
     
    842843}
    843844
    844 bool btQuantizedBvh::serialize(void *o_alignedDataBuffer, unsigned /*i_dataBufferSize */, bool i_swapEndian)
     845bool btQuantizedBvh::serialize(void *o_alignedDataBuffer, unsigned /*i_dataBufferSize */, bool i_swapEndian) const
    845846{
    846847        btAssert(m_subtreeHeaderCount == m_SubtreeHeaders.size());
     
    11441145}
    11451146
    1146 
    1147 
    1148 
     1147void btQuantizedBvh::deSerializeFloat(struct btQuantizedBvhFloatData& quantizedBvhFloatData)
     1148{
     1149        m_bvhAabbMax.deSerializeFloat(quantizedBvhFloatData.m_bvhAabbMax);
     1150        m_bvhAabbMin.deSerializeFloat(quantizedBvhFloatData.m_bvhAabbMin);
     1151        m_bvhQuantization.deSerializeFloat(quantizedBvhFloatData.m_bvhQuantization);
     1152
     1153        m_curNodeIndex = quantizedBvhFloatData.m_curNodeIndex;
     1154        m_useQuantization = quantizedBvhFloatData.m_useQuantization!=0;
     1155       
     1156        {
     1157                int numElem = quantizedBvhFloatData.m_numContiguousLeafNodes;
     1158                m_contiguousNodes.resize(numElem);
     1159
     1160                if (numElem)
     1161                {
     1162                        btOptimizedBvhNodeFloatData* memPtr = quantizedBvhFloatData.m_contiguousNodesPtr;
     1163
     1164                        for (int i=0;i<numElem;i++,memPtr++)
     1165                        {
     1166                                m_contiguousNodes[i].m_aabbMaxOrg.deSerializeFloat(memPtr->m_aabbMaxOrg);
     1167                                m_contiguousNodes[i].m_aabbMinOrg.deSerializeFloat(memPtr->m_aabbMinOrg);
     1168                                m_contiguousNodes[i].m_escapeIndex = memPtr->m_escapeIndex;
     1169                                m_contiguousNodes[i].m_subPart = memPtr->m_subPart;
     1170                                m_contiguousNodes[i].m_triangleIndex = memPtr->m_triangleIndex;
     1171                        }
     1172                }
     1173        }
     1174
     1175        {
     1176                int numElem = quantizedBvhFloatData.m_numQuantizedContiguousNodes;
     1177                m_quantizedContiguousNodes.resize(numElem);
     1178               
     1179                if (numElem)
     1180                {
     1181                        btQuantizedBvhNodeData* memPtr = quantizedBvhFloatData.m_quantizedContiguousNodesPtr;
     1182                        for (int i=0;i<numElem;i++,memPtr++)
     1183                        {
     1184                                m_quantizedContiguousNodes[i].m_escapeIndexOrTriangleIndex = memPtr->m_escapeIndexOrTriangleIndex;
     1185                                m_quantizedContiguousNodes[i].m_quantizedAabbMax[0] = memPtr->m_quantizedAabbMax[0];
     1186                                m_quantizedContiguousNodes[i].m_quantizedAabbMax[1] = memPtr->m_quantizedAabbMax[1];
     1187                                m_quantizedContiguousNodes[i].m_quantizedAabbMax[2] = memPtr->m_quantizedAabbMax[2];
     1188                                m_quantizedContiguousNodes[i].m_quantizedAabbMin[0] = memPtr->m_quantizedAabbMin[0];
     1189                                m_quantizedContiguousNodes[i].m_quantizedAabbMin[1] = memPtr->m_quantizedAabbMin[1];
     1190                                m_quantizedContiguousNodes[i].m_quantizedAabbMin[2] = memPtr->m_quantizedAabbMin[2];
     1191                        }
     1192                }
     1193        }
     1194
     1195        m_traversalMode = btTraversalMode(quantizedBvhFloatData.m_traversalMode);
     1196       
     1197        {
     1198                int numElem = quantizedBvhFloatData.m_numSubtreeHeaders;
     1199                m_SubtreeHeaders.resize(numElem);
     1200                if (numElem)
     1201                {
     1202                        btBvhSubtreeInfoData* memPtr = quantizedBvhFloatData.m_subTreeInfoPtr;
     1203                        for (int i=0;i<numElem;i++,memPtr++)
     1204                        {
     1205                                m_SubtreeHeaders[i].m_quantizedAabbMax[0] = memPtr->m_quantizedAabbMax[0] ;
     1206                                m_SubtreeHeaders[i].m_quantizedAabbMax[1] = memPtr->m_quantizedAabbMax[1];
     1207                                m_SubtreeHeaders[i].m_quantizedAabbMax[2] = memPtr->m_quantizedAabbMax[2];
     1208                                m_SubtreeHeaders[i].m_quantizedAabbMin[0] = memPtr->m_quantizedAabbMin[0];
     1209                                m_SubtreeHeaders[i].m_quantizedAabbMin[1] = memPtr->m_quantizedAabbMin[1];
     1210                                m_SubtreeHeaders[i].m_quantizedAabbMin[2] = memPtr->m_quantizedAabbMin[2];
     1211                                m_SubtreeHeaders[i].m_rootNodeIndex = memPtr->m_rootNodeIndex;
     1212                                m_SubtreeHeaders[i].m_subtreeSize = memPtr->m_subtreeSize;
     1213                        }
     1214                }
     1215        }
     1216}
     1217
     1218void btQuantizedBvh::deSerializeDouble(struct btQuantizedBvhDoubleData& quantizedBvhDoubleData)
     1219{
     1220        m_bvhAabbMax.deSerializeDouble(quantizedBvhDoubleData.m_bvhAabbMax);
     1221        m_bvhAabbMin.deSerializeDouble(quantizedBvhDoubleData.m_bvhAabbMin);
     1222        m_bvhQuantization.deSerializeDouble(quantizedBvhDoubleData.m_bvhQuantization);
     1223
     1224        m_curNodeIndex = quantizedBvhDoubleData.m_curNodeIndex;
     1225        m_useQuantization = quantizedBvhDoubleData.m_useQuantization!=0;
     1226       
     1227        {
     1228                int numElem = quantizedBvhDoubleData.m_numContiguousLeafNodes;
     1229                m_contiguousNodes.resize(numElem);
     1230
     1231                if (numElem)
     1232                {
     1233                        btOptimizedBvhNodeDoubleData* memPtr = quantizedBvhDoubleData.m_contiguousNodesPtr;
     1234
     1235                        for (int i=0;i<numElem;i++,memPtr++)
     1236                        {
     1237                                m_contiguousNodes[i].m_aabbMaxOrg.deSerializeDouble(memPtr->m_aabbMaxOrg);
     1238                                m_contiguousNodes[i].m_aabbMinOrg.deSerializeDouble(memPtr->m_aabbMinOrg);
     1239                                m_contiguousNodes[i].m_escapeIndex = memPtr->m_escapeIndex;
     1240                                m_contiguousNodes[i].m_subPart = memPtr->m_subPart;
     1241                                m_contiguousNodes[i].m_triangleIndex = memPtr->m_triangleIndex;
     1242                        }
     1243                }
     1244        }
     1245
     1246        {
     1247                int numElem = quantizedBvhDoubleData.m_numQuantizedContiguousNodes;
     1248                m_quantizedContiguousNodes.resize(numElem);
     1249               
     1250                if (numElem)
     1251                {
     1252                        btQuantizedBvhNodeData* memPtr = quantizedBvhDoubleData.m_quantizedContiguousNodesPtr;
     1253                        for (int i=0;i<numElem;i++,memPtr++)
     1254                        {
     1255                                m_quantizedContiguousNodes[i].m_escapeIndexOrTriangleIndex = memPtr->m_escapeIndexOrTriangleIndex;
     1256                                m_quantizedContiguousNodes[i].m_quantizedAabbMax[0] = memPtr->m_quantizedAabbMax[0];
     1257                                m_quantizedContiguousNodes[i].m_quantizedAabbMax[1] = memPtr->m_quantizedAabbMax[1];
     1258                                m_quantizedContiguousNodes[i].m_quantizedAabbMax[2] = memPtr->m_quantizedAabbMax[2];
     1259                                m_quantizedContiguousNodes[i].m_quantizedAabbMin[0] = memPtr->m_quantizedAabbMin[0];
     1260                                m_quantizedContiguousNodes[i].m_quantizedAabbMin[1] = memPtr->m_quantizedAabbMin[1];
     1261                                m_quantizedContiguousNodes[i].m_quantizedAabbMin[2] = memPtr->m_quantizedAabbMin[2];
     1262                        }
     1263                }
     1264        }
     1265
     1266        m_traversalMode = btTraversalMode(quantizedBvhDoubleData.m_traversalMode);
     1267       
     1268        {
     1269                int numElem = quantizedBvhDoubleData.m_numSubtreeHeaders;
     1270                m_SubtreeHeaders.resize(numElem);
     1271                if (numElem)
     1272                {
     1273                        btBvhSubtreeInfoData* memPtr = quantizedBvhDoubleData.m_subTreeInfoPtr;
     1274                        for (int i=0;i<numElem;i++,memPtr++)
     1275                        {
     1276                                m_SubtreeHeaders[i].m_quantizedAabbMax[0] = memPtr->m_quantizedAabbMax[0] ;
     1277                                m_SubtreeHeaders[i].m_quantizedAabbMax[1] = memPtr->m_quantizedAabbMax[1];
     1278                                m_SubtreeHeaders[i].m_quantizedAabbMax[2] = memPtr->m_quantizedAabbMax[2];
     1279                                m_SubtreeHeaders[i].m_quantizedAabbMin[0] = memPtr->m_quantizedAabbMin[0];
     1280                                m_SubtreeHeaders[i].m_quantizedAabbMin[1] = memPtr->m_quantizedAabbMin[1];
     1281                                m_SubtreeHeaders[i].m_quantizedAabbMin[2] = memPtr->m_quantizedAabbMin[2];
     1282                                m_SubtreeHeaders[i].m_rootNodeIndex = memPtr->m_rootNodeIndex;
     1283                                m_SubtreeHeaders[i].m_subtreeSize = memPtr->m_subtreeSize;
     1284                        }
     1285                }
     1286        }
     1287
     1288}
     1289
     1290
     1291
     1292///fills the dataBuffer and returns the struct name (and 0 on failure)
     1293const char*     btQuantizedBvh::serialize(void* dataBuffer, btSerializer* serializer) const
     1294{
     1295        btQuantizedBvhData* quantizedData = (btQuantizedBvhData*)dataBuffer;
     1296       
     1297        m_bvhAabbMax.serialize(quantizedData->m_bvhAabbMax);
     1298        m_bvhAabbMin.serialize(quantizedData->m_bvhAabbMin);
     1299        m_bvhQuantization.serialize(quantizedData->m_bvhQuantization);
     1300
     1301        quantizedData->m_curNodeIndex = m_curNodeIndex;
     1302        quantizedData->m_useQuantization = m_useQuantization;
     1303       
     1304        quantizedData->m_numContiguousLeafNodes = m_contiguousNodes.size();
     1305        quantizedData->m_contiguousNodesPtr = (btOptimizedBvhNodeData*) (m_contiguousNodes.size() ? serializer->getUniquePointer((void*)&m_contiguousNodes[0]) : 0);
     1306        if (quantizedData->m_contiguousNodesPtr)
     1307        {
     1308                int sz = sizeof(btOptimizedBvhNodeData);
     1309                int numElem = m_contiguousNodes.size();
     1310                btChunk* chunk = serializer->allocate(sz,numElem);
     1311                btOptimizedBvhNodeData* memPtr = (btOptimizedBvhNodeData*)chunk->m_oldPtr;
     1312                for (int i=0;i<numElem;i++,memPtr++)
     1313                {
     1314                        m_contiguousNodes[i].m_aabbMaxOrg.serialize(memPtr->m_aabbMaxOrg);
     1315                        m_contiguousNodes[i].m_aabbMinOrg.serialize(memPtr->m_aabbMinOrg);
     1316                        memPtr->m_escapeIndex = m_contiguousNodes[i].m_escapeIndex;
     1317                        memPtr->m_subPart = m_contiguousNodes[i].m_subPart;
     1318                        memPtr->m_triangleIndex = m_contiguousNodes[i].m_triangleIndex;
     1319                }
     1320                serializer->finalizeChunk(chunk,"btOptimizedBvhNodeData",BT_ARRAY_CODE,(void*)&m_contiguousNodes[0]);
     1321        }
     1322
     1323        quantizedData->m_numQuantizedContiguousNodes = m_quantizedContiguousNodes.size();
     1324//      printf("quantizedData->m_numQuantizedContiguousNodes=%d\n",quantizedData->m_numQuantizedContiguousNodes);
     1325        quantizedData->m_quantizedContiguousNodesPtr =(btQuantizedBvhNodeData*) (m_quantizedContiguousNodes.size() ? serializer->getUniquePointer((void*)&m_quantizedContiguousNodes[0]) : 0);
     1326        if (quantizedData->m_quantizedContiguousNodesPtr)
     1327        {
     1328                int sz = sizeof(btQuantizedBvhNodeData);
     1329                int numElem = m_quantizedContiguousNodes.size();
     1330                btChunk* chunk = serializer->allocate(sz,numElem);
     1331                btQuantizedBvhNodeData* memPtr = (btQuantizedBvhNodeData*)chunk->m_oldPtr;
     1332                for (int i=0;i<numElem;i++,memPtr++)
     1333                {
     1334                        memPtr->m_escapeIndexOrTriangleIndex = m_quantizedContiguousNodes[i].m_escapeIndexOrTriangleIndex;
     1335                        memPtr->m_quantizedAabbMax[0] = m_quantizedContiguousNodes[i].m_quantizedAabbMax[0];
     1336                        memPtr->m_quantizedAabbMax[1] = m_quantizedContiguousNodes[i].m_quantizedAabbMax[1];
     1337                        memPtr->m_quantizedAabbMax[2] = m_quantizedContiguousNodes[i].m_quantizedAabbMax[2];
     1338                        memPtr->m_quantizedAabbMin[0] = m_quantizedContiguousNodes[i].m_quantizedAabbMin[0];
     1339                        memPtr->m_quantizedAabbMin[1] = m_quantizedContiguousNodes[i].m_quantizedAabbMin[1];
     1340                        memPtr->m_quantizedAabbMin[2] = m_quantizedContiguousNodes[i].m_quantizedAabbMin[2];
     1341                }
     1342                serializer->finalizeChunk(chunk,"btQuantizedBvhNodeData",BT_ARRAY_CODE,(void*)&m_quantizedContiguousNodes[0]);
     1343        }
     1344
     1345        quantizedData->m_traversalMode = int(m_traversalMode);
     1346        quantizedData->m_numSubtreeHeaders = m_SubtreeHeaders.size();
     1347
     1348        quantizedData->m_subTreeInfoPtr = (btBvhSubtreeInfoData*) (m_SubtreeHeaders.size() ? serializer->getUniquePointer((void*)&m_SubtreeHeaders[0]) : 0);
     1349        if (quantizedData->m_subTreeInfoPtr)
     1350        {
     1351                int sz = sizeof(btBvhSubtreeInfoData);
     1352                int numElem = m_SubtreeHeaders.size();
     1353                btChunk* chunk = serializer->allocate(sz,numElem);
     1354                btBvhSubtreeInfoData* memPtr = (btBvhSubtreeInfoData*)chunk->m_oldPtr;
     1355                for (int i=0;i<numElem;i++,memPtr++)
     1356                {
     1357                        memPtr->m_quantizedAabbMax[0] = m_SubtreeHeaders[i].m_quantizedAabbMax[0];
     1358                        memPtr->m_quantizedAabbMax[1] = m_SubtreeHeaders[i].m_quantizedAabbMax[1];
     1359                        memPtr->m_quantizedAabbMax[2] = m_SubtreeHeaders[i].m_quantizedAabbMax[2];
     1360                        memPtr->m_quantizedAabbMin[0] = m_SubtreeHeaders[i].m_quantizedAabbMin[0];
     1361                        memPtr->m_quantizedAabbMin[1] = m_SubtreeHeaders[i].m_quantizedAabbMin[1];
     1362                        memPtr->m_quantizedAabbMin[2] = m_SubtreeHeaders[i].m_quantizedAabbMin[2];
     1363
     1364                        memPtr->m_rootNodeIndex = m_SubtreeHeaders[i].m_rootNodeIndex;
     1365                        memPtr->m_subtreeSize = m_SubtreeHeaders[i].m_subtreeSize;
     1366                }
     1367                serializer->finalizeChunk(chunk,"btBvhSubtreeInfoData",BT_ARRAY_CODE,(void*)&m_SubtreeHeaders[0]);
     1368        }
     1369        return btQuantizedBvhDataName;
     1370}
     1371
     1372
     1373
     1374
     1375
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btQuantizedBvh.h

    r5781 r8284  
    1717#define QUANTIZED_BVH_H
    1818
     19class btSerializer;
     20
    1921//#define DEBUG_CHECK_DEQUANTIZATION 1
    2022#ifdef DEBUG_CHECK_DEQUANTIZATION
     
    2931#include "LinearMath/btVector3.h"
    3032#include "LinearMath/btAlignedAllocator.h"
     33
     34#ifdef BT_USE_DOUBLE_PRECISION
     35#define btQuantizedBvhData btQuantizedBvhDoubleData
     36#define btOptimizedBvhNodeData btOptimizedBvhNodeDoubleData
     37#define btQuantizedBvhDataName "btQuantizedBvhDoubleData"
     38#else
     39#define btQuantizedBvhData btQuantizedBvhFloatData
     40#define btOptimizedBvhNodeData btOptimizedBvhNodeFloatData
     41#define btQuantizedBvhDataName "btQuantizedBvhFloatData"
     42#endif
     43
    3144
    3245
     
    191204
    192205        //This is only used for serialization so we don't have to add serialization directly to btAlignedObjectArray
    193         int m_subtreeHeaderCount;
     206        mutable int m_subtreeHeaderCount;
    194207
    195208       
     
    444457        }
    445458
     459////////////////////////////////////////////////////////////////////
    446460
    447461        /////Calculate space needed to store BVH for serialization
    448         unsigned calculateSerializeBufferSize();
     462        unsigned calculateSerializeBufferSize() const;
    449463
    450464        /// Data buffer MUST be 16 byte aligned
    451         virtual bool serialize(void *o_alignedDataBuffer, unsigned i_dataBufferSize, bool i_swapEndian);
     465        virtual bool serialize(void *o_alignedDataBuffer, unsigned i_dataBufferSize, bool i_swapEndian) const;
    452466
    453467        ///deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place'
     
    455469
    456470        static unsigned int getAlignmentSerializationPadding();
     471//////////////////////////////////////////////////////////////////////
     472
     473       
     474        virtual int     calculateSerializeBufferSizeNew() const;
     475
     476        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     477        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     478
     479        virtual void deSerializeFloat(struct btQuantizedBvhFloatData& quantizedBvhFloatData);
     480
     481        virtual void deSerializeDouble(struct btQuantizedBvhDoubleData& quantizedBvhDoubleData);
     482
     483
     484////////////////////////////////////////////////////////////////////
    457485
    458486        SIMD_FORCE_INLINE bool isQuantized()
     
    471499
    472500
     501struct  btBvhSubtreeInfoData
     502{
     503        int                     m_rootNodeIndex;
     504        int                     m_subtreeSize;
     505        unsigned short m_quantizedAabbMin[3];
     506        unsigned short m_quantizedAabbMax[3];
     507};
     508
     509struct btOptimizedBvhNodeFloatData
     510{
     511        btVector3FloatData      m_aabbMinOrg;
     512        btVector3FloatData      m_aabbMaxOrg;
     513        int     m_escapeIndex;
     514        int     m_subPart;
     515        int     m_triangleIndex;
     516        char m_pad[4];
     517};
     518
     519struct btOptimizedBvhNodeDoubleData
     520{
     521        btVector3DoubleData     m_aabbMinOrg;
     522        btVector3DoubleData     m_aabbMaxOrg;
     523        int     m_escapeIndex;
     524        int     m_subPart;
     525        int     m_triangleIndex;
     526        char    m_pad[4];
     527};
     528
     529
     530struct btQuantizedBvhNodeData
     531{
     532        unsigned short m_quantizedAabbMin[3];
     533        unsigned short m_quantizedAabbMax[3];
     534        int     m_escapeIndexOrTriangleIndex;
     535};
     536
     537struct  btQuantizedBvhFloatData
     538{
     539        btVector3FloatData                      m_bvhAabbMin;
     540        btVector3FloatData                      m_bvhAabbMax;
     541        btVector3FloatData                      m_bvhQuantization;
     542        int                                     m_curNodeIndex;
     543        int                                     m_useQuantization;
     544        int                                     m_numContiguousLeafNodes;
     545        int                                     m_numQuantizedContiguousNodes;
     546        btOptimizedBvhNodeFloatData     *m_contiguousNodesPtr;
     547        btQuantizedBvhNodeData          *m_quantizedContiguousNodesPtr;
     548        btBvhSubtreeInfoData    *m_subTreeInfoPtr;
     549        int                                     m_traversalMode;
     550        int                                     m_numSubtreeHeaders;
     551       
     552};
     553
     554struct  btQuantizedBvhDoubleData
     555{
     556        btVector3DoubleData                     m_bvhAabbMin;
     557        btVector3DoubleData                     m_bvhAabbMax;
     558        btVector3DoubleData                     m_bvhQuantization;
     559        int                                                     m_curNodeIndex;
     560        int                                                     m_useQuantization;
     561        int                                                     m_numContiguousLeafNodes;
     562        int                                                     m_numQuantizedContiguousNodes;
     563        btOptimizedBvhNodeDoubleData    *m_contiguousNodesPtr;
     564        btQuantizedBvhNodeData                  *m_quantizedContiguousNodesPtr;
     565
     566        int                                                     m_traversalMode;
     567        int                                                     m_numSubtreeHeaders;
     568        btBvhSubtreeInfoData            *m_subTreeInfoPtr;
     569};
     570
     571
     572SIMD_FORCE_INLINE       int     btQuantizedBvh::calculateSerializeBufferSizeNew() const
     573{
     574        return sizeof(btQuantizedBvhData);
     575}
     576
     577
     578
    473579#endif //QUANTIZED_BVH_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btSimpleBroadphase.cpp

    r5781 r8284  
    2121#include "LinearMath/btTransform.h"
    2222#include "LinearMath/btMatrix3x3.h"
     23#include "LinearMath/btAabbUtil2.h"
     24
    2325#include <new>
    2426
     
    163165                }
    164166                rayCallback.process(proxy);
     167        }
     168}
     169
     170
     171void    btSimpleBroadphase::aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback)
     172{
     173        for (int i=0; i <= m_LastHandleIndex; i++)
     174        {
     175                btSimpleBroadphaseProxy* proxy = &m_pHandles[i];
     176                if(!proxy->m_clientObject)
     177                {
     178                        continue;
     179                }
     180                if (TestAabbAgainstAabb2(aabbMin,aabbMax,proxy->m_aabbMin,proxy->m_aabbMax))
     181                {
     182                        callback.process(proxy);
     183                }
    165184        }
    166185}
  • code/branches/kicklib2/src/external/bullet/BulletCollision/BroadphaseCollision/btSimpleBroadphase.h

    r5781 r8284  
    137137
    138138        virtual void    rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0),const btVector3& aabbMax=btVector3(0,0,0));
     139        virtual void    aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback);
    139140               
    140141        btOverlappingPairCache* getOverlappingPairCache()
     
    154155        virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const
    155156        {
    156                 aabbMin.setValue(-1e30f,-1e30f,-1e30f);
    157                 aabbMax.setValue(1e30f,1e30f,1e30f);
     157                aabbMin.setValue(-BT_LARGE_FLOAT,-BT_LARGE_FLOAT,-BT_LARGE_FLOAT);
     158                aabbMax.setValue(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT);
    158159        }
    159160
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CMakeLists.txt

    r5929 r8284  
    66        BroadphaseCollision/btBroadphaseProxy.cpp
    77        BroadphaseCollision/btCollisionAlgorithm.cpp
     8        BroadphaseCollision/btDbvt.cpp
     9        BroadphaseCollision/btDbvtBroadphase.cpp
    810        BroadphaseCollision/btDispatcher.cpp
    9         BroadphaseCollision/btDbvtBroadphase.cpp
    10         BroadphaseCollision/btDbvt.cpp
    1111        BroadphaseCollision/btMultiSapBroadphase.cpp
    1212        BroadphaseCollision/btOverlappingPairCache.cpp
     
    1515
    1616        CollisionDispatch/btActivatingCollisionAlgorithm.cpp
     17        CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp
     18        CollisionDispatch/btBox2dBox2dCollisionAlgorithm.cpp
     19        CollisionDispatch/btBoxBoxDetector.cpp
    1720        CollisionDispatch/btCollisionDispatcher.cpp
    1821        CollisionDispatch/btCollisionObject.cpp
     
    2023        CollisionDispatch/btCompoundCollisionAlgorithm.cpp
    2124        CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp
     25        CollisionDispatch/btConvexConvexAlgorithm.cpp
     26        CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp
     27        CollisionDispatch/btConvex2dConvex2dAlgorithm.cpp
    2228        CollisionDispatch/btDefaultCollisionConfiguration.cpp
    23         CollisionDispatch/btSphereSphereCollisionAlgorithm.cpp
    24         CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp
    25         CollisionDispatch/btBoxBoxDetector.cpp
     29        CollisionDispatch/btEmptyCollisionAlgorithm.cpp
    2630        CollisionDispatch/btGhostObject.cpp
    27         CollisionDispatch/btSphereBoxCollisionAlgorithm.cpp
    28         CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp
    29         CollisionDispatch/btSphereTriangleCollisionAlgorithm.cpp
    30         CollisionDispatch/btConvexConvexAlgorithm.cpp
    31         CollisionDispatch/btEmptyCollisionAlgorithm.cpp
     31        CollisionDispatch/btInternalEdgeUtility.cpp
     32        CollisionDispatch/btInternalEdgeUtility.h
    3233        CollisionDispatch/btManifoldResult.cpp
    3334        CollisionDispatch/btSimulationIslandManager.cpp
     35        CollisionDispatch/btSphereBoxCollisionAlgorithm.cpp
     36        CollisionDispatch/btSphereSphereCollisionAlgorithm.cpp
     37        CollisionDispatch/btSphereTriangleCollisionAlgorithm.cpp
    3438        CollisionDispatch/btUnionFind.cpp
    3539        CollisionDispatch/SphereTriangleDetector.cpp
    3640
    3741        CollisionShapes/btBoxShape.cpp
     42        CollisionShapes/btBox2dShape.cpp
    3843        CollisionShapes/btBvhTriangleMeshShape.cpp
    3944        CollisionShapes/btCapsuleShape.cpp
     
    4348        CollisionShapes/btConeShape.cpp
    4449        CollisionShapes/btConvexHullShape.cpp
     50        CollisionShapes/btConvexInternalShape.cpp
    4551        CollisionShapes/btConvexPointCloudShape.cpp
    4652        CollisionShapes/btConvexShape.cpp
    47         CollisionShapes/btConvexInternalShape.cpp
     53        CollisionShapes/btConvex2dShape.cpp
    4854        CollisionShapes/btConvexTriangleMeshShape.cpp
    4955        CollisionShapes/btCylinderShape.cpp
     
    5662        CollisionShapes/btPolyhedralConvexShape.cpp
    5763        CollisionShapes/btScaledBvhTriangleMeshShape.cpp
    58         CollisionShapes/btTetrahedronShape.cpp
     64        CollisionShapes/btShapeHull.cpp
    5965        CollisionShapes/btSphereShape.cpp
    60         CollisionShapes/btShapeHull.cpp
    6166        CollisionShapes/btStaticPlaneShape.cpp
    6267        CollisionShapes/btStridingMeshInterface.cpp
     68        CollisionShapes/btTetrahedronShape.cpp
     69        CollisionShapes/btTriangleBuffer.cpp
    6370        CollisionShapes/btTriangleCallback.cpp
    64         CollisionShapes/btTriangleBuffer.cpp
    6571        CollisionShapes/btTriangleIndexVertexArray.cpp
    6672        CollisionShapes/btTriangleIndexVertexMaterialArray.cpp
     
    6975        CollisionShapes/btUniformScalingShape.cpp
    7076
    71         Gimpact/btContactProcessing.cpp
    72         Gimpact/btGImpactShape.cpp
    73         Gimpact/btGImpactBvh.cpp
    74         Gimpact/btGenericPoolAllocator.cpp
    75         Gimpact/btGImpactCollisionAlgorithm.cpp
    76         Gimpact/btTriangleShapeEx.cpp
    77         Gimpact/btGImpactQuantizedBvh.cpp
    78 
    7977        NarrowPhaseCollision/btContinuousConvexCollision.cpp
     78        NarrowPhaseCollision/btConvexCast.cpp
     79        NarrowPhaseCollision/btGjkConvexCast.cpp
    8080        NarrowPhaseCollision/btGjkEpa2.cpp
    8181        NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.cpp
    82         NarrowPhaseCollision/btConvexCast.cpp
    83         NarrowPhaseCollision/btGjkConvexCast.cpp
    8482        NarrowPhaseCollision/btGjkPairDetector.cpp
    8583        NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.cpp
     
    9189COMPILATION_END
    9290
    93 COMPILATION_BEGIN BulletGImpactCompilation.cpp
    94         Gimpact/gim_contact.cpp
    95         Gimpact/gim_memory.cpp
    96         Gimpact/gim_tri_collision.cpp
    97         Gimpact/gim_box_set.cpp
    98 COMPILATION_END
    99 
    10091        # Headers
    10192        BroadphaseCollision/btAxisSweep3.h
     
    10394        BroadphaseCollision/btBroadphaseProxy.h
    10495        BroadphaseCollision/btCollisionAlgorithm.h
     96        BroadphaseCollision/btDbvt.h
     97        BroadphaseCollision/btDbvtBroadphase.h
    10598        BroadphaseCollision/btDispatcher.h
    106         BroadphaseCollision/btDbvtBroadphase.h
    107         BroadphaseCollision/btDbvt.h
    10899        BroadphaseCollision/btMultiSapBroadphase.h
    109100        BroadphaseCollision/btOverlappingPairCache.h
     
    113104
    114105        CollisionDispatch/btActivatingCollisionAlgorithm.h
     106        CollisionDispatch/btBoxBoxCollisionAlgorithm.h
     107        CollisionDispatch/btBox2dBox2dCollisionAlgorithm.h
     108        CollisionDispatch/btBoxBoxDetector.h
    115109        CollisionDispatch/btCollisionConfiguration.h
    116110        CollisionDispatch/btCollisionCreateFunc.h
     
    120114        CollisionDispatch/btCompoundCollisionAlgorithm.h
    121115        CollisionDispatch/btConvexConcaveCollisionAlgorithm.h
     116        CollisionDispatch/btConvexConvexAlgorithm.h
     117        CollisionDispatch/btConvex2dConvex2dAlgorithm.h
     118        CollisionDispatch/btConvexPlaneCollisionAlgorithm.h
    122119        CollisionDispatch/btDefaultCollisionConfiguration.h
    123         CollisionDispatch/btSphereSphereCollisionAlgorithm.h
    124         CollisionDispatch/btBoxBoxCollisionAlgorithm.h
    125         CollisionDispatch/btBoxBoxDetector.h
     120        CollisionDispatch/btEmptyCollisionAlgorithm.h
    126121        CollisionDispatch/btGhostObject.h
    127         CollisionDispatch/btSphereBoxCollisionAlgorithm.h
    128         CollisionDispatch/btConvexPlaneCollisionAlgorithm.h
    129         CollisionDispatch/btSphereTriangleCollisionAlgorithm.h
    130         CollisionDispatch/btConvexConvexAlgorithm.h
    131         CollisionDispatch/btEmptyCollisionAlgorithm.h
    132122        CollisionDispatch/btManifoldResult.h
    133123        CollisionDispatch/btSimulationIslandManager.h
     124        CollisionDispatch/btSphereBoxCollisionAlgorithm.h
     125        CollisionDispatch/btSphereSphereCollisionAlgorithm.h
     126        CollisionDispatch/btSphereTriangleCollisionAlgorithm.h
    134127        CollisionDispatch/btUnionFind.h
    135128        CollisionDispatch/SphereTriangleDetector.h
    136129
    137130        CollisionShapes/btBoxShape.h
     131        CollisionShapes/btBox2dShape.h
    138132        CollisionShapes/btBvhTriangleMeshShape.h
    139133        CollisionShapes/btCapsuleShape.h
    140         CollisionShapes/btCollisionMargin
     134        CollisionShapes/btCollisionMargin.h
    141135        CollisionShapes/btCollisionShape.h
    142136        CollisionShapes/btCompoundShape.h
     
    144138        CollisionShapes/btConeShape.h
    145139        CollisionShapes/btConvexHullShape.h
     140        CollisionShapes/btConvexInternalShape.h
    146141        CollisionShapes/btConvexPointCloudShape.h
    147142        CollisionShapes/btConvexShape.h
    148         CollisionShapes/btConvexInternalShape.h
     143        CollisionShapes/btConvex2dShape.h
    149144        CollisionShapes/btConvexTriangleMeshShape.h
    150145        CollisionShapes/btCylinderShape.h
    151146        CollisionShapes/btEmptyShape.h
    152147        CollisionShapes/btHeightfieldTerrainShape.h
     148        CollisionShapes/btMaterial.h
    153149        CollisionShapes/btMinkowskiSumShape.h
    154         CollisionShapes/btMaterial.h
    155150        CollisionShapes/btMultimaterialTriangleMeshShape.h
    156151        CollisionShapes/btMultiSphereShape.h
     
    158153        CollisionShapes/btPolyhedralConvexShape.h
    159154        CollisionShapes/btScaledBvhTriangleMeshShape.h
    160         CollisionShapes/btTetrahedronShape.h
     155        CollisionShapes/btShapeHull.h
    161156        CollisionShapes/btSphereShape.h
    162         CollisionShapes/btShapeHull.h
    163157        CollisionShapes/btStaticPlaneShape.h
    164158        CollisionShapes/btStridingMeshInterface.h
     159        CollisionShapes/btTetrahedronShape.h
     160        CollisionShapes/btTriangleBuffer.h
    165161        CollisionShapes/btTriangleCallback.h
    166         CollisionShapes/btTriangleBuffer.h
    167162        CollisionShapes/btTriangleIndexVertexArray.h
    168163        CollisionShapes/btTriangleIndexVertexMaterialArray.h
     164        CollisionShapes/btTriangleInfoMap.h
    169165        CollisionShapes/btTriangleMesh.h
    170166        CollisionShapes/btTriangleMeshShape.h
     167        CollisionShapes/btTriangleShape.h
    171168        CollisionShapes/btUniformScalingShape.h
    172 
    173         Gimpact/btGImpactShape.h
    174         Gimpact/gim_contact.h
    175         Gimpact/btGImpactBvh.h
    176         Gimpact/btGenericPoolAllocator.h
    177         Gimpact/gim_memory.h
    178         Gimpact/btGImpactCollisionAlgorithm.h
    179         Gimpact/btTriangleShapeEx.h
    180         Gimpact/gim_tri_collision.h
    181         Gimpact/btGImpactQuantizedBvh.h
    182         Gimpact/gim_box_set.h
    183169
    184170        NarrowPhaseCollision/btContinuousConvexCollision.h
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/SphereTriangleDetector.cpp

    r5781 r8284  
    3838        btScalar timeOfImpact = btScalar(1.);
    3939        btScalar depth = btScalar(0.);
    40 //      output.m_distance = btScalar(1e30);
     40//      output.m_distance = btScalar(BT_LARGE_FLOAT);
    4141        //move sphere into triangle space
    4242        btTransform     sphereInTr = transformB.inverseTimes(transformA);
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/SphereTriangleDetector.h

    r5781 r8284  
    3535        virtual ~SphereTriangleDetector() {};
    3636
     37        bool collide(const btVector3& sphereCenter,btVector3 &point, btVector3& resultNormal, btScalar& depth, btScalar &timeOfImpact, btScalar contactBreakingThreshold);
     38
    3739private:
    3840
    39         bool collide(const btVector3& sphereCenter,btVector3 &point, btVector3& resultNormal, btScalar& depth, btScalar &timeOfImpact, btScalar contactBreakingThreshold);
     41       
    4042        bool pointInTriangle(const btVector3 vertices[], const btVector3 &normal, btVector3 *p );
    4143        bool facecontains(const btVector3 &p,const btVector3* vertices,btVector3& normal);
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp

    r5781 r8284  
    6262
    6363        btDiscreteCollisionDetectorInterface::ClosestPointInput input;
    64         input.m_maximumDistanceSquared = 1e30f;
     64        input.m_maximumDistanceSquared = BT_LARGE_FLOAT;
    6565        input.m_transformA = body0->getWorldTransform();
    6666        input.m_transformB = body1->getWorldTransform();
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp

    r5781 r8284  
    1 
    21/*
    32 * Box-Box collision detection re-distributed under the ZLib license with permission from Russell L. Smith
     
    213212        } else
    214213        {
    215                 a=1e30f;
     214                a=BT_LARGE_FLOAT;
    216215        }
    217216    cx = a*(cx + q*(p[n*2-2]+p[0]));
     
    268267{
    269268  const btScalar fudge_factor = btScalar(1.05);
    270   btVector3 p,pp,normalC;
     269  btVector3 p,pp,normalC(0.f,0.f,0.f);
    271270  const btScalar *normalR = 0;
    272271  btScalar A[3],B[3],R11,R12,R13,R21,R22,R23,R31,R32,R33,
     
    334333#define TST(expr1,expr2,n1,n2,n3,cc) \
    335334  s2 = btFabs(expr1) - (expr2); \
    336   if (s2 > 0) return 0; \
     335  if (s2 > SIMD_EPSILON) return 0; \
    337336  l = btSqrt((n1)*(n1) + (n2)*(n2) + (n3)*(n3)); \
    338   if (l > 0) { \
     337  if (l > SIMD_EPSILON) { \
    339338    s2 /= l; \
    340339    if (s2*fudge_factor > s) { \
     
    346345    } \
    347346  }
     347
     348  btScalar fudge2 (1.0e-5f);
     349
     350  Q11 += fudge2;
     351  Q12 += fudge2;
     352  Q13 += fudge2;
     353
     354  Q21 += fudge2;
     355  Q22 += fudge2;
     356  Q23 += fudge2;
     357
     358  Q31 += fudge2;
     359  Q32 += fudge2;
     360  Q33 += fudge2;
    348361
    349362  // separating axis = u1 x (v1,v2,v3)
     
    425438#else
    426439                output.addContactPoint(-normal,pb,-*depth);
     440
    427441#endif //
    428442                *return_code = code;
     
    594608
    595609  if (cnum <= maxc) {
     610
     611          if (code<4)
     612          {
    596613    // we have less contacts than we need, so we use them all
    597     for (j=0; j < cnum; j++) {
    598 
    599                 //AddContactPoint...
    600 
    601                 //dContactGeom *con = CONTACT(contact,skip*j);
    602       //for (i=0; i<3; i++) con->pos[i] = point[j*3+i] + pa[i];
    603       //con->depth = dep[j];
    604 
     614    for (j=0; j < cnum; j++)
     615        {
    605616                btVector3 pointInWorld;
    606617                for (i=0; i<3; i++)
     
    609620
    610621    }
     622          } else
     623          {
     624                  // we have less contacts than we need, so we use them all
     625                for (j=0; j < cnum; j++)
     626                {
     627                        btVector3 pointInWorld;
     628                        for (i=0; i<3; i++)
     629                                pointInWorld[i] = point[j*3+i] + pa[i]-normal[i]*dep[j];
     630                                //pointInWorld[i] = point[j*3+i] + pa[i];
     631                        output.addContactPoint(-normal,pointInWorld,-dep[j]);
     632                }
     633          }
    611634  }
    612635  else {
     
    633656                for (i=0; i<3; i++)
    634657                        posInWorld[i] = point[iret[j]*3+i] + pa[i];
    635                 output.addContactPoint(-normal,posInWorld,-dep[iret[j]]);
     658                if (code<4)
     659           {
     660                        output.addContactPoint(-normal,posInWorld,-dep[iret[j]]);
     661                } else
     662                {
     663                        output.addContactPoint(-normal,posInWorld-normal*dep[iret[j]],-dep[iret[j]]);
     664                }
    636665    }
    637666    cnum = maxc;
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btCollisionDispatcher.cpp

    r5781 r8284  
    3535
    3636btCollisionDispatcher::btCollisionDispatcher (btCollisionConfiguration* collisionConfiguration):
    37         m_count(0),
    38         m_useIslands(true),
    39         m_staticWarningReported(false),
     37m_dispatcherFlags(btCollisionDispatcher::CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD),
    4038        m_collisionConfiguration(collisionConfiguration)
    4139{
     
    8078        btCollisionObject* body1 = (btCollisionObject*)b1;
    8179
    82         //test for Bullet 2.74: use a relative contact breaking threshold without clamping against 'gContactBreakingThreshold'
    83         //btScalar contactBreakingThreshold = btMin(gContactBreakingThreshold,btMin(body0->getCollisionShape()->getContactBreakingThreshold(),body1->getCollisionShape()->getContactBreakingThreshold()));
    84         btScalar contactBreakingThreshold = btMin(body0->getCollisionShape()->getContactBreakingThreshold(),body1->getCollisionShape()->getContactBreakingThreshold());
     80        //optional relative contact breaking threshold, turned on by default (use setDispatcherFlags to switch off feature for improved performance)
     81       
     82        btScalar contactBreakingThreshold =  (m_dispatcherFlags & btCollisionDispatcher::CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD) ?
     83                btMin(body0->getCollisionShape()->getContactBreakingThreshold(gContactBreakingThreshold) , body1->getCollisionShape()->getContactBreakingThreshold(gContactBreakingThreshold))
     84                : gContactBreakingThreshold ;
    8585
    8686        btScalar contactProcessingThreshold = btMin(body0->getContactProcessingThreshold(),body1->getContactProcessingThreshold());
     
    170170
    171171#ifdef BT_DEBUG
    172         if (!m_staticWarningReported)
     172        if (!(m_dispatcherFlags & btCollisionDispatcher::CD_STATIC_STATIC_REPORTED))
    173173        {
    174174                //broadphase filtering already deals with this
     
    176176                        (body1->isStaticObject() || body1->isKinematicObject()))
    177177                {
    178                         m_staticWarningReported = true;
     178                        m_dispatcherFlags |= btCollisionDispatcher::CD_STATIC_STATIC_REPORTED;
    179179                        printf("warning btCollisionDispatcher::needsCollision: static-static collision!\n");
    180180                }
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btCollisionDispatcher.h

    r5781 r8284  
    4343class btCollisionDispatcher : public btDispatcher
    4444{
    45         int m_count;
     45        int             m_dispatcherFlags;
    4646       
    4747        btAlignedObjectArray<btPersistentManifold*>     m_manifoldsPtr;
    4848
    49         bool m_useIslands;
    50 
    51         bool    m_staticWarningReported;
    52        
    5349        btManifoldResult        m_defaultManifoldResult;
    5450
     
    6056
    6157        btCollisionAlgorithmCreateFunc* m_doubleDispatch[MAX_BROADPHASE_COLLISION_TYPES][MAX_BROADPHASE_COLLISION_TYPES];
    62        
    6358
    6459        btCollisionConfiguration*       m_collisionConfiguration;
     
    6661
    6762public:
     63
     64        enum DispatcherFlags
     65        {
     66                CD_STATIC_STATIC_REPORTED = 1,
     67                CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD = 2
     68        };
     69
     70        int     getDispatcherFlags() const
     71        {
     72                return m_dispatcherFlags;
     73        }
     74
     75        void    setDispatcherFlags(int flags)
     76        {
     77        (void) flags;
     78                m_dispatcherFlags = 0;
     79        }
    6880
    6981        ///registerCollisionCreateFunc allows registration of custom/alternative collision create functions
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btCollisionObject.cpp

    r5781 r8284  
    1616
    1717#include "btCollisionObject.h"
     18#include "LinearMath/btSerializer.h"
    1819
    1920btCollisionObject::btCollisionObject()
    2021        :       m_anisotropicFriction(1.f,1.f,1.f),
    2122        m_hasAnisotropicFriction(false),
    22         m_contactProcessingThreshold(1e30f),
     23        m_contactProcessingThreshold(BT_LARGE_FLOAT),
    2324                m_broadphaseHandle(0),
    2425                m_collisionShape(0),
     26                m_extensionPointer(0),
    2527                m_rootCollisionShape(0),
    2628                m_collisionFlags(btCollisionObject::CF_STATIC_OBJECT),
     
    3133                m_friction(btScalar(0.5)),
    3234                m_restitution(btScalar(0.)),
     35                m_internalType(CO_COLLISION_OBJECT),
    3336                m_userObjectPointer(0),
    34                 m_internalType(CO_COLLISION_OBJECT),
    3537                m_hitFraction(btScalar(1.)),
    3638                m_ccdSweptSphereRadius(btScalar(0.)),
     
    3840                m_checkCollideWith(false)
    3941{
    40        
     42        m_worldTransform.setIdentity();
    4143}
    4244
     
    6567}
    6668
     69const char* btCollisionObject::serialize(void* dataBuffer, btSerializer* serializer) const
     70{
     71
     72        btCollisionObjectData* dataOut = (btCollisionObjectData*)dataBuffer;
     73
     74        m_worldTransform.serialize(dataOut->m_worldTransform);
     75        m_interpolationWorldTransform.serialize(dataOut->m_interpolationWorldTransform);
     76        m_interpolationLinearVelocity.serialize(dataOut->m_interpolationLinearVelocity);
     77        m_interpolationAngularVelocity.serialize(dataOut->m_interpolationAngularVelocity);
     78        m_anisotropicFriction.serialize(dataOut->m_anisotropicFriction);
     79        dataOut->m_hasAnisotropicFriction = m_hasAnisotropicFriction;
     80        dataOut->m_contactProcessingThreshold = m_contactProcessingThreshold;
     81        dataOut->m_broadphaseHandle = 0;
     82        dataOut->m_collisionShape = serializer->getUniquePointer(m_collisionShape);
     83        dataOut->m_rootCollisionShape = 0;//@todo
     84        dataOut->m_collisionFlags = m_collisionFlags;
     85        dataOut->m_islandTag1 = m_islandTag1;
     86        dataOut->m_companionId = m_companionId;
     87        dataOut->m_activationState1 = m_activationState1;
     88        dataOut->m_activationState1 = m_activationState1;
     89        dataOut->m_deactivationTime = m_deactivationTime;
     90        dataOut->m_friction = m_friction;
     91        dataOut->m_restitution = m_restitution;
     92        dataOut->m_internalType = m_internalType;
     93       
     94        char* name = (char*) serializer->findNameForPointer(this);
     95        dataOut->m_name = (char*)serializer->getUniquePointer(name);
     96        if (dataOut->m_name)
     97        {
     98                serializer->serializeName(name);
     99        }
     100        dataOut->m_hitFraction = m_hitFraction;
     101        dataOut->m_ccdSweptSphereRadius = m_ccdSweptSphereRadius;
     102        dataOut->m_ccdMotionThreshold = m_ccdMotionThreshold;
     103        dataOut->m_ccdMotionThreshold = m_ccdMotionThreshold;
     104        dataOut->m_checkCollideWith = m_checkCollideWith;
     105
     106        return btCollisionObjectDataName;
     107}
    67108
    68109
     110void btCollisionObject::serializeSingleObject(class btSerializer* serializer) const
     111{
     112        int len = calculateSerializeBufferSize();
     113        btChunk* chunk = serializer->allocate(len,1);
     114        const char* structType = serialize(chunk->m_oldPtr, serializer);
     115        serializer->finalizeChunk(chunk,structType,BT_COLLISIONOBJECT_CODE,(void*)this);
     116}
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btCollisionObject.h

    r5781 r8284  
    2828struct  btBroadphaseProxy;
    2929class   btCollisionShape;
     30struct btCollisionShapeData;
    3031#include "LinearMath/btMotionState.h"
    3132#include "LinearMath/btAlignedAllocator.h"
    3233#include "LinearMath/btAlignedObjectArray.h"
    3334
    34 
    3535typedef btAlignedObjectArray<class btCollisionObject*> btCollisionObjectArray;
     36
     37#ifdef BT_USE_DOUBLE_PRECISION
     38#define btCollisionObjectData btCollisionObjectDoubleData
     39#define btCollisionObjectDataName "btCollisionObjectDoubleData"
     40#else
     41#define btCollisionObjectData btCollisionObjectFloatData
     42#define btCollisionObjectDataName "btCollisionObjectFloatData"
     43#endif
    3644
    3745
     
    5462        btVector3       m_interpolationAngularVelocity;
    5563       
    56         btVector3               m_anisotropicFriction;
    57         bool                            m_hasAnisotropicFriction;
    58         btScalar                m_contactProcessingThreshold;   
     64        btVector3       m_anisotropicFriction;
     65        int                     m_hasAnisotropicFriction;
     66        btScalar        m_contactProcessingThreshold;   
    5967
    6068        btBroadphaseProxy*              m_broadphaseHandle;
    6169        btCollisionShape*               m_collisionShape;
     70        ///m_extensionPointer is used by some internal low-level Bullet extensions.
     71        void*                                   m_extensionPointer;
    6272       
    6373        ///m_rootCollisionShape is temporarily used to store the original collision shape
     
    7787        btScalar                m_restitution;
    7888
    79         ///users can point to their objects, m_userPointer is not used by Bullet, see setUserPointer/getUserPointer
    80         void*                   m_userObjectPointer;
    81 
    8289        ///m_internalType is reserved to distinguish Bullet's btCollisionObject, btRigidBody, btSoftBody, btGhostObject etc.
    8390        ///do not assign your own m_internalType unless you write a new dynamics object class.
    8491        int                             m_internalType;
    8592
     93        ///users can point to their objects, m_userPointer is not used by Bullet, see setUserPointer/getUserPointer
     94        void*                   m_userObjectPointer;
     95
    8696        ///time of impact calculation
    8797        btScalar                m_hitFraction;
     
    94104       
    95105        /// If some object should have elaborate collision filtering by sub-classes
    96         bool                    m_checkCollideWith;
    97 
    98         char    m_pad[7];
     106        int                     m_checkCollideWith;
    99107
    100108        virtual bool    checkCollideWithOverride(btCollisionObject* /* co */)
     
    113121                CF_NO_CONTACT_RESPONSE = 4,
    114122                CF_CUSTOM_MATERIAL_CALLBACK = 8,//this allows per-triangle material (friction/restitution)
    115                 CF_CHARACTER_OBJECT = 16
     123                CF_CHARACTER_OBJECT = 16,
     124                CF_DISABLE_VISUALIZE_OBJECT = 32, //disable debug drawing
     125                CF_DISABLE_SPU_COLLISION_PROCESSING = 64//disable parallel/SPU processing
    116126        };
    117127
     
    119129        {
    120130                CO_COLLISION_OBJECT =1,
    121                 CO_RIGID_BODY,
     131                CO_RIGID_BODY=2,
    122132                ///CO_GHOST_OBJECT keeps track of all objects overlapping its AABB and that pass its collision filter
    123133                ///It is useful for collision sensors, explosion objects, character controller etc.
    124                 CO_GHOST_OBJECT,
    125                 CO_SOFT_BODY,
    126                 CO_HF_FLUID
     134                CO_GHOST_OBJECT=4,
     135                CO_SOFT_BODY=8,
     136                CO_HF_FLUID=16,
     137                CO_USER_TYPE=32
    127138        };
    128139
     
    144155        bool    hasAnisotropicFriction() const
    145156        {
    146                 return m_hasAnisotropicFriction;
     157                return m_hasAnisotropicFriction!=0;
    147158        }
    148159
     
    214225        }
    215226
     227        ///Avoid using this internal API call, the extension pointer is used by some Bullet extensions.
     228        ///If you need to store your own user pointer, use 'setUserPointer/getUserPointer' instead.
     229        void*           internalGetExtensionPointer() const
     230        {
     231                return m_extensionPointer;
     232        }
     233        ///Avoid using this internal API call, the extension pointer is used by some Bullet extensions
     234        ///If you need to store your own user pointer, use 'setUserPointer/getUserPointer' instead.
     235        void    internalSetExtensionPointer(void* pointer)
     236        {
     237                m_extensionPointer = pointer;
     238        }
     239
    216240        SIMD_FORCE_INLINE       int     getActivationState() const { return m_activationState1;}
    217241       
     
    394418        void    setCcdMotionThreshold(btScalar ccdMotionThreshold)
    395419        {
    396                 m_ccdMotionThreshold = ccdMotionThreshold*ccdMotionThreshold;
     420                m_ccdMotionThreshold = ccdMotionThreshold;
    397421        }
    398422
     
    417441                return true;
    418442        }
     443
     444        virtual int     calculateSerializeBufferSize()  const;
     445
     446        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     447        virtual const char*     serialize(void* dataBuffer, class btSerializer* serializer) const;
     448
     449        virtual void serializeSingleObject(class btSerializer* serializer) const;
     450
    419451};
    420452
     453///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     454struct  btCollisionObjectDoubleData
     455{
     456        void                                    *m_broadphaseHandle;
     457        void                                    *m_collisionShape;
     458        btCollisionShapeData    *m_rootCollisionShape;
     459        char                                    *m_name;
     460
     461        btTransformDoubleData   m_worldTransform;
     462        btTransformDoubleData   m_interpolationWorldTransform;
     463        btVector3DoubleData             m_interpolationLinearVelocity;
     464        btVector3DoubleData             m_interpolationAngularVelocity;
     465        btVector3DoubleData             m_anisotropicFriction;
     466        double                                  m_contactProcessingThreshold;   
     467        double                                  m_deactivationTime;
     468        double                                  m_friction;
     469        double                                  m_restitution;
     470        double                                  m_hitFraction;
     471        double                                  m_ccdSweptSphereRadius;
     472        double                                  m_ccdMotionThreshold;
     473
     474        int                                             m_hasAnisotropicFriction;
     475        int                                             m_collisionFlags;
     476        int                                             m_islandTag1;
     477        int                                             m_companionId;
     478        int                                             m_activationState1;
     479        int                                             m_internalType;
     480        int                                             m_checkCollideWith;
     481
     482        char    m_padding[4];
     483};
     484
     485///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     486struct  btCollisionObjectFloatData
     487{
     488        void                                    *m_broadphaseHandle;
     489        void                                    *m_collisionShape;
     490        btCollisionShapeData    *m_rootCollisionShape;
     491        char                                    *m_name;
     492
     493        btTransformFloatData    m_worldTransform;
     494        btTransformFloatData    m_interpolationWorldTransform;
     495        btVector3FloatData              m_interpolationLinearVelocity;
     496        btVector3FloatData              m_interpolationAngularVelocity;
     497        btVector3FloatData              m_anisotropicFriction;
     498        float                                   m_contactProcessingThreshold;   
     499        float                                   m_deactivationTime;
     500        float                                   m_friction;
     501        float                                   m_restitution;
     502        float                                   m_hitFraction;
     503        float                                   m_ccdSweptSphereRadius;
     504        float                                   m_ccdMotionThreshold;
     505
     506        int                                             m_hasAnisotropicFriction;
     507        int                                             m_collisionFlags;
     508        int                                             m_islandTag1;
     509        int                                             m_companionId;
     510        int                                             m_activationState1;
     511        int                                             m_internalType;
     512        int                                             m_checkCollideWith;
     513};
     514
     515
     516
     517SIMD_FORCE_INLINE       int     btCollisionObject::calculateSerializeBufferSize() const
     518{
     519        return sizeof(btCollisionObjectData);
     520}
     521
     522
     523
    421524#endif //COLLISION_OBJECT_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btCollisionWorld.cpp

    r5781 r8284  
    2727#include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"
    2828#include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"
    29 
     29#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
    3030#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
    3131#include "LinearMath/btAabbUtil2.h"
    3232#include "LinearMath/btQuickprof.h"
    3333#include "LinearMath/btStackAlloc.h"
     34#include "LinearMath/btSerializer.h"
    3435
    3536//#define USE_BRUTEFORCE_RAYBROADPHASE 1
     
    4344
    4445
     46///for debug drawing
     47
     48//for debug rendering
     49#include "BulletCollision/CollisionShapes/btBoxShape.h"
     50#include "BulletCollision/CollisionShapes/btCapsuleShape.h"
     51#include "BulletCollision/CollisionShapes/btCompoundShape.h"
     52#include "BulletCollision/CollisionShapes/btConeShape.h"
     53#include "BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h"
     54#include "BulletCollision/CollisionShapes/btCylinderShape.h"
     55#include "BulletCollision/CollisionShapes/btMultiSphereShape.h"
     56#include "BulletCollision/CollisionShapes/btPolyhedralConvexShape.h"
     57#include "BulletCollision/CollisionShapes/btSphereShape.h"
     58#include "BulletCollision/CollisionShapes/btTriangleCallback.h"
     59#include "BulletCollision/CollisionShapes/btTriangleMeshShape.h"
     60#include "BulletCollision/CollisionShapes/btStaticPlaneShape.h"
     61
     62
     63
    4564btCollisionWorld::btCollisionWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache, btCollisionConfiguration* collisionConfiguration)
    4665:m_dispatcher1(dispatcher),
    4766m_broadphasePairCache(pairCache),
    48 m_debugDrawer(0)
     67m_debugDrawer(0),
     68m_forceUpdateAllAabbs(true)
    4969{
    5070        m_stackAlloc = collisionConfiguration->getStackAllocator();
     
    89109{
    90110
     111        btAssert(collisionObject);
     112
    91113        //check that the object isn't already added
    92                 btAssert( m_collisionObjects.findLinearSearch(collisionObject)  == m_collisionObjects.size());
    93 
    94                 m_collisionObjects.push_back(collisionObject);
    95 
    96                 //calculate new AABB
    97                 btTransform trans = collisionObject->getWorldTransform();
    98 
    99                 btVector3       minAabb;
    100                 btVector3       maxAabb;
    101                 collisionObject->getCollisionShape()->getAabb(trans,minAabb,maxAabb);
    102 
    103                 int type = collisionObject->getCollisionShape()->getShapeType();
    104                 collisionObject->setBroadphaseHandle( getBroadphase()->createProxy(
    105                         minAabb,
    106                         maxAabb,
    107                         type,
    108                         collisionObject,
    109                         collisionFilterGroup,
    110                         collisionFilterMask,
    111                         m_dispatcher1,0
    112                         ))      ;
     114        btAssert( m_collisionObjects.findLinearSearch(collisionObject)  == m_collisionObjects.size());
     115
     116        m_collisionObjects.push_back(collisionObject);
     117
     118        //calculate new AABB
     119        btTransform trans = collisionObject->getWorldTransform();
     120
     121        btVector3       minAabb;
     122        btVector3       maxAabb;
     123        collisionObject->getCollisionShape()->getAabb(trans,minAabb,maxAabb);
     124
     125        int type = collisionObject->getCollisionShape()->getShapeType();
     126        collisionObject->setBroadphaseHandle( getBroadphase()->createProxy(
     127                minAabb,
     128                maxAabb,
     129                type,
     130                collisionObject,
     131                collisionFilterGroup,
     132                collisionFilterMask,
     133                m_dispatcher1,0
     134                ))      ;
    113135
    114136
     
    163185
    164186                //only update aabb of active objects
    165                 if (colObj->isActive())
     187                if (m_forceUpdateAllAabbs || colObj->isActive())
    166188                {
    167189                        updateSingleAabb(colObj);
     
    226248
    227249void    btCollisionWorld::rayTestSingle(const btTransform& rayFromTrans,const btTransform& rayToTrans,
    228                                           btCollisionObject* collisionObject,
    229                                           const btCollisionShape* collisionShape,
    230                                           const btTransform& colObjWorldTransform,
    231                                           RayResultCallback& resultCallback)
     250                                                                                btCollisionObject* collisionObject,
     251                                                                                const btCollisionShape* collisionShape,
     252                                                                                const btTransform& colObjWorldTransform,
     253                                                                                RayResultCallback& resultCallback)
    232254{
    233255        btSphereShape pointShape(btScalar(0.0));
     
    237259        if (collisionShape->isConvex())
    238260        {
    239 //              BT_PROFILE("rayTestConvex");
     261                //              BT_PROFILE("rayTestConvex");
    240262                btConvexCast::CastResult castResult;
    241263                castResult.m_fraction = resultCallback.m_closestHitFraction;
     
    266288                                        btCollisionWorld::LocalRayResult localRayResult
    267289                                                (
    268                                                         collisionObject,
    269                                                         0,
    270                                                         castResult.m_normal,
    271                                                         castResult.m_fraction
     290                                                collisionObject,
     291                                                0,
     292                                                castResult.m_normal,
     293                                                castResult.m_fraction
    272294                                                );
    273295
     
    281303                if (collisionShape->isConcave())
    282304                {
    283 //                      BT_PROFILE("rayTestConcave");
     305                        //                      BT_PROFILE("rayTestConcave");
    284306                        if (collisionShape->getShapeType()==TRIANGLE_MESH_SHAPE_PROXYTYPE)
    285307                        {
     
    297319                                        btTriangleMeshShape*    m_triangleMesh;
    298320
     321                                        btTransform m_colObjWorldTransform;
     322
    299323                                        BridgeTriangleRaycastCallback( const btVector3& from,const btVector3& to,
    300                                                 btCollisionWorld::RayResultCallback* resultCallback, btCollisionObject* collisionObject,btTriangleMeshShape*    triangleMesh):
    301                   //@BP Mod
    302                                                 btTriangleRaycastCallback(from,to, resultCallback->m_flags),
    303                                                         m_resultCallback(resultCallback),
    304                                                         m_collisionObject(collisionObject),
    305                                                         m_triangleMesh(triangleMesh)
    306                                                 {
    307                                                 }
     324                                                btCollisionWorld::RayResultCallback* resultCallback, btCollisionObject* collisionObject,btTriangleMeshShape*    triangleMesh,const btTransform& colObjWorldTransform):
     325                                        //@BP Mod
     326                                        btTriangleRaycastCallback(from,to, resultCallback->m_flags),
     327                                                m_resultCallback(resultCallback),
     328                                                m_collisionObject(collisionObject),
     329                                                m_triangleMesh(triangleMesh),
     330                                                m_colObjWorldTransform(colObjWorldTransform)
     331                                        {
     332                                        }
    308333
    309334
     
    314339                                                shapeInfo.m_triangleIndex = triangleIndex;
    315340
     341                                                btVector3 hitNormalWorld = m_colObjWorldTransform.getBasis() * hitNormalLocal;
     342
    316343                                                btCollisionWorld::LocalRayResult rayResult
    317                                                 (m_collisionObject,
     344                                                        (m_collisionObject,
    318345                                                        &shapeInfo,
    319                                                         hitNormalLocal,
     346                                                        hitNormalWorld,
    320347                                                        hitFraction);
    321348
    322                                                 bool    normalInWorldSpace = false;
     349                                                bool    normalInWorldSpace = true;
    323350                                                return m_resultCallback->addSingleResult(rayResult,normalInWorldSpace);
    324351                                        }
     
    326353                                };
    327354
    328                                 BridgeTriangleRaycastCallback rcb(rayFromLocal,rayToLocal,&resultCallback,collisionObject,triangleMesh);
     355                                BridgeTriangleRaycastCallback rcb(rayFromLocal,rayToLocal,&resultCallback,collisionObject,triangleMesh,colObjWorldTransform);
    329356                                rcb.m_hitFraction = resultCallback.m_closestHitFraction;
    330357                                triangleMesh->performRaycast(&rcb,rayFromLocal,rayToLocal);
     
    347374                                        btConcaveShape* m_triangleMesh;
    348375
     376                                        btTransform m_colObjWorldTransform;
     377
    349378                                        BridgeTriangleRaycastCallback( const btVector3& from,const btVector3& to,
    350                                                 btCollisionWorld::RayResultCallback* resultCallback, btCollisionObject* collisionObject,btConcaveShape* triangleMesh):
    351                   //@BP Mod
    352                   btTriangleRaycastCallback(from,to, resultCallback->m_flags),
    353                                                         m_resultCallback(resultCallback),
    354                                                         m_collisionObject(collisionObject),
    355                                                         m_triangleMesh(triangleMesh)
    356                                                 {
    357                                                 }
     379                                                btCollisionWorld::RayResultCallback* resultCallback, btCollisionObject* collisionObject,btConcaveShape* triangleMesh, const btTransform& colObjWorldTransform):
     380                                        //@BP Mod
     381                                        btTriangleRaycastCallback(from,to, resultCallback->m_flags),
     382                                                m_resultCallback(resultCallback),
     383                                                m_collisionObject(collisionObject),
     384                                                m_triangleMesh(triangleMesh),
     385                                                m_colObjWorldTransform(colObjWorldTransform)
     386                                        {
     387                                        }
    358388
    359389
     
    364394                                                shapeInfo.m_triangleIndex = triangleIndex;
    365395
     396                                                btVector3 hitNormalWorld = m_colObjWorldTransform.getBasis() * hitNormalLocal;
     397
    366398                                                btCollisionWorld::LocalRayResult rayResult
    367                                                 (m_collisionObject,
     399                                                        (m_collisionObject,
    368400                                                        &shapeInfo,
    369                                                         hitNormalLocal,
     401                                                        hitNormalWorld,
    370402                                                        hitFraction);
    371403
    372                                                 bool    normalInWorldSpace = false;
     404                                                bool    normalInWorldSpace = true;
    373405                                                return m_resultCallback->addSingleResult(rayResult,normalInWorldSpace);
    374 
    375 
    376406                                        }
    377407
     
    379409
    380410
    381                                 BridgeTriangleRaycastCallback   rcb(rayFromLocal,rayToLocal,&resultCallback,collisionObject,concaveShape);
     411                                BridgeTriangleRaycastCallback   rcb(rayFromLocal,rayToLocal,&resultCallback,collisionObject,concaveShape, colObjWorldTransform);
    382412                                rcb.m_hitFraction = resultCallback.m_closestHitFraction;
    383413
     
    390420                        }
    391421                } else {
    392 //                      BT_PROFILE("rayTestCompound");
     422                        //                      BT_PROFILE("rayTestCompound");
    393423                        ///@todo: use AABB tree or other BVH acceleration structure, see btDbvt
    394424                        if (collisionShape->isCompound())
     
    404434                                        btCollisionShape* saveCollisionShape = collisionObject->getCollisionShape();
    405435                                        collisionObject->internalSetTemporaryCollisionShape((btCollisionShape*)childCollisionShape);
     436                    struct LocalInfoAdder2 : public RayResultCallback {
     437                                                RayResultCallback* m_userCallback;
     438                                                int m_i;
     439                        LocalInfoAdder2 (int i, RayResultCallback *user)
     440                                                        : m_userCallback(user),
     441                                                        m_i(i)
     442                                                {
     443                                                        m_closestHitFraction = m_userCallback->m_closestHitFraction;
     444                                                }
     445                                                virtual btScalar addSingleResult (btCollisionWorld::LocalRayResult &r, bool b)
     446                            {
     447                                    btCollisionWorld::LocalShapeInfo    shapeInfo;
     448                                    shapeInfo.m_shapePart = -1;
     449                                    shapeInfo.m_triangleIndex = m_i;
     450                                    if (r.m_localShapeInfo == NULL)
     451                                        r.m_localShapeInfo = &shapeInfo;
     452
     453                                                                        const btScalar result = m_userCallback->addSingleResult(r, b);
     454                                                                        m_closestHitFraction = m_userCallback->m_closestHitFraction;
     455                                                                        return result;
     456                            }
     457                    };
     458
     459                    LocalInfoAdder2 my_cb(i, &resultCallback);
     460
    406461                                        rayTestSingle(rayFromTrans,rayToTrans,
    407462                                                collisionObject,
    408463                                                childCollisionShape,
    409464                                                childWorldTrans,
    410                                                 resultCallback);
     465                                                my_cb);
    411466                                        // restore
    412467                                        collisionObject->internalSetTemporaryCollisionShape(saveCollisionShape);
     
    418473
    419474void    btCollisionWorld::objectQuerySingle(const btConvexShape* castShape,const btTransform& convexFromTrans,const btTransform& convexToTrans,
    420                                           btCollisionObject* collisionObject,
    421                                           const btCollisionShape* collisionShape,
    422                                           const btTransform& colObjWorldTransform,
    423                                           ConvexResultCallback& resultCallback, btScalar allowedPenetration)
     475                                                                                        btCollisionObject* collisionObject,
     476                                                                                        const btCollisionShape* collisionShape,
     477                                                                                        const btTransform& colObjWorldTransform,
     478                                                                                        ConvexResultCallback& resultCallback, btScalar allowedPenetration)
    424479{
    425480        if (collisionShape->isConvex())
     
    433488                btVoronoiSimplexSolver  simplexSolver;
    434489                btGjkEpaPenetrationDepthSolver  gjkEpaPenetrationSolver;
    435                
     490
    436491                btContinuousConvexCollision convexCaster1(castShape,convexShape,&simplexSolver,&gjkEpaPenetrationSolver);
    437492                //btGjkConvexCast convexCaster2(castShape,convexShape,&simplexSolver);
     
    439494
    440495                btConvexCast* castPtr = &convexCaster1;
    441        
    442        
    443                
     496
     497
     498
    444499                if (castPtr->calcTimeOfImpact(convexFromTrans,convexToTrans,colObjWorldTransform,colObjWorldTransform,castResult))
    445500                {
     
    451506                                        castResult.m_normal.normalize();
    452507                                        btCollisionWorld::LocalConvexResult localConvexResult
    453                                                                 (
    454                                                                         collisionObject,
    455                                                                         0,
    456                                                                         castResult.m_normal,
    457                                                                         castResult.m_hitPoint,
    458                                                                         castResult.m_fraction
    459                                                                 );
     508                                                (
     509                                                collisionObject,
     510                                                0,
     511                                                castResult.m_normal,
     512                                                castResult.m_hitPoint,
     513                                                castResult.m_fraction
     514                                                );
    460515
    461516                                        bool normalInWorldSpace = true;
     
    487542                                        BridgeTriangleConvexcastCallback(const btConvexShape* castShape, const btTransform& from,const btTransform& to,
    488543                                                btCollisionWorld::ConvexResultCallback* resultCallback, btCollisionObject* collisionObject,btTriangleMeshShape* triangleMesh, const btTransform& triangleToWorld):
    489                                                 btTriangleConvexcastCallback(castShape, from,to, triangleToWorld, triangleMesh->getMargin()),
    490                                                         m_resultCallback(resultCallback),
    491                                                         m_collisionObject(collisionObject),
    492                                                         m_triangleMesh(triangleMesh)
    493                                                 {
    494                                                 }
     544                                        btTriangleConvexcastCallback(castShape, from,to, triangleToWorld, triangleMesh->getMargin()),
     545                                                m_resultCallback(resultCallback),
     546                                                m_collisionObject(collisionObject),
     547                                                m_triangleMesh(triangleMesh)
     548                                        {
     549                                        }
    495550
    496551
     
    504559
    505560                                                        btCollisionWorld::LocalConvexResult convexResult
    506                                                         (m_collisionObject,
     561                                                                (m_collisionObject,
    507562                                                                &shapeInfo,
    508563                                                                hitNormalLocal,
     
    544599                                        BridgeTriangleConvexcastCallback(const btConvexShape* castShape, const btTransform& from,const btTransform& to,
    545600                                                btCollisionWorld::ConvexResultCallback* resultCallback, btCollisionObject* collisionObject,btConcaveShape*      triangleMesh, const btTransform& triangleToWorld):
    546                                                 btTriangleConvexcastCallback(castShape, from,to, triangleToWorld, triangleMesh->getMargin()),
    547                                                         m_resultCallback(resultCallback),
    548                                                         m_collisionObject(collisionObject),
    549                                                         m_triangleMesh(triangleMesh)
    550                                                 {
    551                                                 }
     601                                        btTriangleConvexcastCallback(castShape, from,to, triangleToWorld, triangleMesh->getMargin()),
     602                                                m_resultCallback(resultCallback),
     603                                                m_collisionObject(collisionObject),
     604                                                m_triangleMesh(triangleMesh)
     605                                        {
     606                                        }
    552607
    553608
     
    561616
    562617                                                        btCollisionWorld::LocalConvexResult convexResult
    563                                                         (m_collisionObject,
     618                                                                (m_collisionObject,
    564619                                                                &shapeInfo,
    565620                                                                hitNormalLocal,
     
    604659                                        btCollisionShape* saveCollisionShape = collisionObject->getCollisionShape();
    605660                                        collisionObject->internalSetTemporaryCollisionShape((btCollisionShape*)childCollisionShape);
     661                    struct      LocalInfoAdder : public ConvexResultCallback {
     662                            ConvexResultCallback* m_userCallback;
     663                                                        int m_i;
     664
     665                            LocalInfoAdder (int i, ConvexResultCallback *user)
     666                                                                : m_userCallback(user), m_i(i)
     667                                                        {
     668                                                                m_closestHitFraction = m_userCallback->m_closestHitFraction;
     669                                                        }
     670                            virtual btScalar addSingleResult (btCollisionWorld::LocalConvexResult&      r,      bool b)
     671                            {
     672                                    btCollisionWorld::LocalShapeInfo    shapeInfo;
     673                                    shapeInfo.m_shapePart = -1;
     674                                    shapeInfo.m_triangleIndex = m_i;
     675                                    if (r.m_localShapeInfo == NULL)
     676                                        r.m_localShapeInfo = &shapeInfo;
     677                                                                        const btScalar result = m_userCallback->addSingleResult(r, b);
     678                                                                        m_closestHitFraction = m_userCallback->m_closestHitFraction;
     679                                                                        return result;
     680                                   
     681                            }
     682                    };
     683
     684                    LocalInfoAdder my_cb(i, &resultCallback);
     685                                       
     686
    606687                                        objectQuerySingle(castShape, convexFromTrans,convexToTrans,
    607688                                                collisionObject,
    608689                                                childCollisionShape,
    609690                                                childWorldTrans,
    610                                                 resultCallback, allowedPenetration);
     691                                                my_cb, allowedPenetration);
    611692                                        // restore
    612693                                        collisionObject->internalSetTemporaryCollisionShape(saveCollisionShape);
     
    631712
    632713        btSingleRayCallback(const btVector3& rayFromWorld,const btVector3& rayToWorld,const btCollisionWorld* world,btCollisionWorld::RayResultCallback& resultCallback)
    633         :m_rayFromWorld(rayFromWorld),
    634         m_rayToWorld(rayToWorld),
    635         m_world(world),
    636         m_resultCallback(resultCallback)
     714                :m_rayFromWorld(rayFromWorld),
     715                m_rayToWorld(rayToWorld),
     716                m_world(world),
     717                m_resultCallback(resultCallback)
    637718        {
    638719                m_rayFromTrans.setIdentity();
     
    644725
    645726                rayDir.normalize ();
    646                 ///what about division by zero? --> just set rayDirection[i] to INF/1e30
    647                 m_rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[0];
    648                 m_rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[1];
    649                 m_rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[2];
     727                ///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT
     728                m_rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0];
     729                m_rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1];
     730                m_rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2];
    650731                m_signs[0] = m_rayDirectionInverse[0] < 0.0;
    651732                m_signs[1] = m_rayDirectionInverse[1] < 0.0;
     
    656737        }
    657738
    658        
     739
    659740
    660741        virtual bool    process(const btBroadphaseProxy* proxy)
     
    687768                                m_world->rayTestSingle(m_rayFromTrans,m_rayToTrans,
    688769                                        collisionObject,
    689                                                 collisionObject->getCollisionShape(),
    690                                                 collisionObject->getWorldTransform(),
    691                                                 m_resultCallback);
     770                                        collisionObject->getCollisionShape(),
     771                                        collisionObject->getWorldTransform(),
     772                                        m_resultCallback);
    692773                        }
    693774                }
     
    698779void    btCollisionWorld::rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const
    699780{
    700         BT_PROFILE("rayTest");
     781        //BT_PROFILE("rayTest");
    701782        /// use the broadphase to accelerate the search for objects, based on their aabb
    702783        /// and for each object with ray-aabb overlap, perform an exact ray test
     
    737818                btVector3 unnormalizedRayDir = (m_convexToTrans.getOrigin()-m_convexFromTrans.getOrigin());
    738819                btVector3 rayDir = unnormalizedRayDir.normalized();
    739                 ///what about division by zero? --> just set rayDirection[i] to INF/1e30
    740                 m_rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[0];
    741                 m_rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[1];
    742                 m_rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDir[2];
     820                ///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT
     821                m_rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0];
     822                m_rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1];
     823                m_rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2];
    743824                m_signs[0] = m_rayDirectionInverse[0] < 0.0;
    744825                m_signs[1] = m_rayDirectionInverse[1] < 0.0;
     
    761842                        //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject();
    762843                        m_world->objectQuerySingle(m_castShape, m_convexFromTrans,m_convexToTrans,
    763                                         collisionObject,
    764                                                 collisionObject->getCollisionShape(),
    765                                                 collisionObject->getWorldTransform(),
    766                                                 m_resultCallback,
    767                                                 m_allowedCcdPenetration);
    768                 }
    769                
     844                                collisionObject,
     845                                collisionObject->getCollisionShape(),
     846                                collisionObject->getWorldTransform(),
     847                                m_resultCallback,
     848                                m_allowedCcdPenetration);
     849                }
     850
    770851                return true;
    771852        }
     
    782863        /// unfortunately the implementation for rayTest and convexSweepTest duplicated, albeit practically identical
    783864
    784        
     865
    785866
    786867        btTransform     convexFromTrans,convexToTrans;
     
    825906                                objectQuerySingle(castShape, convexFromTrans,convexToTrans,
    826907                                        collisionObject,
    827                                                 collisionObject->getCollisionShape(),
    828                                                 collisionObject->getWorldTransform(),
    829                                                 resultCallback,
    830                                                 allowedCcdPenetration);
     908                                        collisionObject->getCollisionShape(),
     909                                        collisionObject->getWorldTransform(),
     910                                        resultCallback,
     911                                        allowedCcdPenetration);
    831912                        }
    832913                }
     
    834915#endif //USE_BRUTEFORCE_RAYBROADPHASE
    835916}
     917
     918
     919
     920struct btBridgedManifoldResult : public btManifoldResult
     921{
     922
     923        btCollisionWorld::ContactResultCallback&        m_resultCallback;
     924
     925        btBridgedManifoldResult( btCollisionObject* obj0,btCollisionObject* obj1,btCollisionWorld::ContactResultCallback& resultCallback )
     926                :btManifoldResult(obj0,obj1),
     927                m_resultCallback(resultCallback)
     928        {
     929        }
     930
     931        virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth)
     932        {
     933                bool isSwapped = m_manifoldPtr->getBody0() != m_body0;
     934                btVector3 pointA = pointInWorld + normalOnBInWorld * depth;
     935                btVector3 localA;
     936                btVector3 localB;
     937                if (isSwapped)
     938                {
     939                        localA = m_rootTransB.invXform(pointA );
     940                        localB = m_rootTransA.invXform(pointInWorld);
     941                } else
     942                {
     943                        localA = m_rootTransA.invXform(pointA );
     944                        localB = m_rootTransB.invXform(pointInWorld);
     945                }
     946               
     947                btManifoldPoint newPt(localA,localB,normalOnBInWorld,depth);
     948                newPt.m_positionWorldOnA = pointA;
     949                newPt.m_positionWorldOnB = pointInWorld;
     950               
     951           //BP mod, store contact triangles.
     952                if (isSwapped)
     953                {
     954                        newPt.m_partId0 = m_partId1;
     955                        newPt.m_partId1 = m_partId0;
     956                        newPt.m_index0  = m_index1;
     957                        newPt.m_index1  = m_index0;
     958                } else
     959                {
     960                        newPt.m_partId0 = m_partId0;
     961                        newPt.m_partId1 = m_partId1;
     962                        newPt.m_index0  = m_index0;
     963                        newPt.m_index1  = m_index1;
     964                }
     965
     966                //experimental feature info, for per-triangle material etc.
     967                btCollisionObject* obj0 = isSwapped? m_body1 : m_body0;
     968                btCollisionObject* obj1 = isSwapped? m_body0 : m_body1;
     969                m_resultCallback.addSingleResult(newPt,obj0,newPt.m_partId0,newPt.m_index0,obj1,newPt.m_partId1,newPt.m_index1);
     970
     971        }
     972       
     973};
     974
     975
     976
     977struct btSingleContactCallback : public btBroadphaseAabbCallback
     978{
     979
     980        btCollisionObject* m_collisionObject;
     981        btCollisionWorld*       m_world;
     982        btCollisionWorld::ContactResultCallback&        m_resultCallback;
     983       
     984       
     985        btSingleContactCallback(btCollisionObject* collisionObject, btCollisionWorld* world,btCollisionWorld::ContactResultCallback& resultCallback)
     986                :m_collisionObject(collisionObject),
     987                m_world(world),
     988                m_resultCallback(resultCallback)
     989        {
     990        }
     991
     992        virtual bool    process(const btBroadphaseProxy* proxy)
     993        {
     994                btCollisionObject*      collisionObject = (btCollisionObject*)proxy->m_clientObject;
     995                if (collisionObject == m_collisionObject)
     996                        return true;
     997
     998                //only perform raycast if filterMask matches
     999                if(m_resultCallback.needsCollision(collisionObject->getBroadphaseHandle()))
     1000                {
     1001                        btCollisionAlgorithm* algorithm = m_world->getDispatcher()->findAlgorithm(m_collisionObject,collisionObject);
     1002                        if (algorithm)
     1003                        {
     1004                                btBridgedManifoldResult contactPointResult(m_collisionObject,collisionObject, m_resultCallback);
     1005                                //discrete collision detection query
     1006                                algorithm->processCollision(m_collisionObject,collisionObject, m_world->getDispatchInfo(),&contactPointResult);
     1007
     1008                                algorithm->~btCollisionAlgorithm();
     1009                                m_world->getDispatcher()->freeCollisionAlgorithm(algorithm);
     1010                        }
     1011                }
     1012                return true;
     1013        }
     1014};
     1015
     1016
     1017///contactTest performs a discrete collision test against all objects in the btCollisionWorld, and calls the resultCallback.
     1018///it reports one or more contact points for every overlapping object (including the one with deepest penetration)
     1019void    btCollisionWorld::contactTest( btCollisionObject* colObj, ContactResultCallback& resultCallback)
     1020{
     1021        btVector3 aabbMin,aabbMax;
     1022        colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(),aabbMin,aabbMax);
     1023        btSingleContactCallback contactCB(colObj,this,resultCallback);
     1024       
     1025        m_broadphasePairCache->aabbTest(aabbMin,aabbMax,contactCB);
     1026}
     1027
     1028
     1029///contactTest performs a discrete collision test between two collision objects and calls the resultCallback if overlap if detected.
     1030///it reports one or more contact points (including the one with deepest penetration)
     1031void    btCollisionWorld::contactPairTest(btCollisionObject* colObjA, btCollisionObject* colObjB, ContactResultCallback& resultCallback)
     1032{
     1033        btCollisionAlgorithm* algorithm = getDispatcher()->findAlgorithm(colObjA,colObjB);
     1034        if (algorithm)
     1035        {
     1036                btBridgedManifoldResult contactPointResult(colObjA,colObjB, resultCallback);
     1037                //discrete collision detection query
     1038                algorithm->processCollision(colObjA,colObjB, getDispatchInfo(),&contactPointResult);
     1039
     1040                algorithm->~btCollisionAlgorithm();
     1041                getDispatcher()->freeCollisionAlgorithm(algorithm);
     1042        }
     1043
     1044}
     1045
     1046
     1047
     1048
     1049class DebugDrawcallback : public btTriangleCallback, public btInternalTriangleIndexCallback
     1050{
     1051        btIDebugDraw*   m_debugDrawer;
     1052        btVector3       m_color;
     1053        btTransform     m_worldTrans;
     1054
     1055public:
     1056
     1057        DebugDrawcallback(btIDebugDraw* debugDrawer,const btTransform& worldTrans,const btVector3& color) :
     1058          m_debugDrawer(debugDrawer),
     1059                  m_color(color),
     1060                  m_worldTrans(worldTrans)
     1061          {
     1062          }
     1063
     1064          virtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int  triangleIndex)
     1065          {
     1066                  processTriangle(triangle,partId,triangleIndex);
     1067          }
     1068
     1069          virtual void processTriangle(btVector3* triangle,int partId, int triangleIndex)
     1070          {
     1071                  (void)partId;
     1072                  (void)triangleIndex;
     1073
     1074                  btVector3 wv0,wv1,wv2;
     1075                  wv0 = m_worldTrans*triangle[0];
     1076                  wv1 = m_worldTrans*triangle[1];
     1077                  wv2 = m_worldTrans*triangle[2];
     1078                  btVector3 center = (wv0+wv1+wv2)*btScalar(1./3.);
     1079
     1080                  btVector3 normal = (wv1-wv0).cross(wv2-wv0);
     1081                  normal.normalize();
     1082                  btVector3 normalColor(1,1,0);
     1083                  m_debugDrawer->drawLine(center,center+normal,normalColor);
     1084
     1085
     1086
     1087                 
     1088                  m_debugDrawer->drawLine(wv0,wv1,m_color);
     1089                  m_debugDrawer->drawLine(wv1,wv2,m_color);
     1090                  m_debugDrawer->drawLine(wv2,wv0,m_color);
     1091          }
     1092};
     1093
     1094
     1095void btCollisionWorld::debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color)
     1096{
     1097        // Draw a small simplex at the center of the object
     1098        getDebugDrawer()->drawTransform(worldTransform,1);
     1099
     1100        if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE)
     1101        {
     1102                const btCompoundShape* compoundShape = static_cast<const btCompoundShape*>(shape);
     1103                for (int i=compoundShape->getNumChildShapes()-1;i>=0;i--)
     1104                {
     1105                        btTransform childTrans = compoundShape->getChildTransform(i);
     1106                        const btCollisionShape* colShape = compoundShape->getChildShape(i);
     1107                        debugDrawObject(worldTransform*childTrans,colShape,color);
     1108                }
     1109
     1110        } else
     1111        {
     1112                switch (shape->getShapeType())
     1113                {
     1114
     1115                case BOX_SHAPE_PROXYTYPE:
     1116                        {
     1117                                const btBoxShape* boxShape = static_cast<const btBoxShape*>(shape);
     1118                                btVector3 halfExtents = boxShape->getHalfExtentsWithMargin();
     1119                                getDebugDrawer()->drawBox(-halfExtents,halfExtents,worldTransform,color);
     1120                                break;
     1121                        }
     1122
     1123                case SPHERE_SHAPE_PROXYTYPE:
     1124                        {
     1125                                const btSphereShape* sphereShape = static_cast<const btSphereShape*>(shape);
     1126                                btScalar radius = sphereShape->getMargin();//radius doesn't include the margin, so draw with margin
     1127
     1128                                getDebugDrawer()->drawSphere(radius, worldTransform, color);
     1129                                break;
     1130                        }
     1131                case MULTI_SPHERE_SHAPE_PROXYTYPE:
     1132                        {
     1133                                const btMultiSphereShape* multiSphereShape = static_cast<const btMultiSphereShape*>(shape);
     1134
     1135                                btTransform childTransform;
     1136                                childTransform.setIdentity();
     1137
     1138                                for (int i = multiSphereShape->getSphereCount()-1; i>=0;i--)
     1139                                {
     1140                                        childTransform.setOrigin(multiSphereShape->getSpherePosition(i));
     1141                                        getDebugDrawer()->drawSphere(multiSphereShape->getSphereRadius(i), worldTransform*childTransform, color);
     1142                                }
     1143
     1144                                break;
     1145                        }
     1146                case CAPSULE_SHAPE_PROXYTYPE:
     1147                        {
     1148                                const btCapsuleShape* capsuleShape = static_cast<const btCapsuleShape*>(shape);
     1149
     1150                                btScalar radius = capsuleShape->getRadius();
     1151                                btScalar halfHeight = capsuleShape->getHalfHeight();
     1152
     1153                                int upAxis = capsuleShape->getUpAxis();
     1154
     1155
     1156                                btVector3 capStart(0.f,0.f,0.f);
     1157                                capStart[upAxis] = -halfHeight;
     1158
     1159                                btVector3 capEnd(0.f,0.f,0.f);
     1160                                capEnd[upAxis] = halfHeight;
     1161
     1162                                // Draw the ends
     1163                                {
     1164
     1165                                        btTransform childTransform = worldTransform;
     1166                                        childTransform.getOrigin() = worldTransform * capStart;
     1167                                        getDebugDrawer()->drawSphere(radius, childTransform, color);
     1168                                }
     1169
     1170                                {
     1171                                        btTransform childTransform = worldTransform;
     1172                                        childTransform.getOrigin() = worldTransform * capEnd;
     1173                                        getDebugDrawer()->drawSphere(radius, childTransform, color);
     1174                                }
     1175
     1176                                // Draw some additional lines
     1177                                btVector3 start = worldTransform.getOrigin();
     1178
     1179
     1180                                capStart[(upAxis+1)%3] = radius;
     1181                                capEnd[(upAxis+1)%3] = radius;
     1182                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color);
     1183                                capStart[(upAxis+1)%3] = -radius;
     1184                                capEnd[(upAxis+1)%3] = -radius;
     1185                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color);
     1186
     1187                                capStart[(upAxis+1)%3] = 0.f;
     1188                                capEnd[(upAxis+1)%3] = 0.f;
     1189
     1190                                capStart[(upAxis+2)%3] = radius;
     1191                                capEnd[(upAxis+2)%3] = radius;
     1192                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color);
     1193                                capStart[(upAxis+2)%3] = -radius;
     1194                                capEnd[(upAxis+2)%3] = -radius;
     1195                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color);
     1196
     1197
     1198                                break;
     1199                        }
     1200                case CONE_SHAPE_PROXYTYPE:
     1201                        {
     1202                                const btConeShape* coneShape = static_cast<const btConeShape*>(shape);
     1203                                btScalar radius = coneShape->getRadius();//+coneShape->getMargin();
     1204                                btScalar height = coneShape->getHeight();//+coneShape->getMargin();
     1205                                btVector3 start = worldTransform.getOrigin();
     1206
     1207                                int upAxis= coneShape->getConeUpIndex();
     1208
     1209
     1210                                btVector3       offsetHeight(0,0,0);
     1211                                offsetHeight[upAxis] = height * btScalar(0.5);
     1212                                btVector3       offsetRadius(0,0,0);
     1213                                offsetRadius[(upAxis+1)%3] = radius;
     1214                                btVector3       offset2Radius(0,0,0);
     1215                                offset2Radius[(upAxis+2)%3] = radius;
     1216
     1217                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight+offsetRadius),color);
     1218                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight-offsetRadius),color);
     1219                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight+offset2Radius),color);
     1220                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight-offset2Radius),color);
     1221
     1222                                // Drawing the base of the cone
     1223                                btVector3 yaxis(0,0,0);
     1224                                yaxis[upAxis] = btScalar(1.0);
     1225                                btVector3 xaxis(0,0,0);
     1226                                xaxis[(upAxis+1)%3] = btScalar(1.0);
     1227                                getDebugDrawer()->drawArc(start-worldTransform.getBasis()*(offsetHeight),worldTransform.getBasis()*yaxis,worldTransform.getBasis()*xaxis,radius,radius,0,SIMD_2_PI,color,false,10.0);
     1228                break;
     1229
     1230                        }
     1231                case CYLINDER_SHAPE_PROXYTYPE:
     1232                        {
     1233                                const btCylinderShape* cylinder = static_cast<const btCylinderShape*>(shape);
     1234                                int upAxis = cylinder->getUpAxis();
     1235                                btScalar radius = cylinder->getRadius();
     1236                                btScalar halfHeight = cylinder->getHalfExtentsWithMargin()[upAxis];
     1237                                btVector3 start = worldTransform.getOrigin();
     1238                                btVector3       offsetHeight(0,0,0);
     1239                                offsetHeight[upAxis] = halfHeight;
     1240                                btVector3       offsetRadius(0,0,0);
     1241                                offsetRadius[(upAxis+1)%3] = radius;
     1242                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight+offsetRadius),start+worldTransform.getBasis() * (-offsetHeight+offsetRadius),color);
     1243                                getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight-offsetRadius),start+worldTransform.getBasis() * (-offsetHeight-offsetRadius),color);
     1244
     1245                                // Drawing top and bottom caps of the cylinder
     1246                                btVector3 yaxis(0,0,0);
     1247                                yaxis[upAxis] = btScalar(1.0);
     1248                                btVector3 xaxis(0,0,0);
     1249                                xaxis[(upAxis+1)%3] = btScalar(1.0);
     1250                                getDebugDrawer()->drawArc(start-worldTransform.getBasis()*(offsetHeight),worldTransform.getBasis()*yaxis,worldTransform.getBasis()*xaxis,radius,radius,0,SIMD_2_PI,color,false,btScalar(10.0));
     1251                                getDebugDrawer()->drawArc(start+worldTransform.getBasis()*(offsetHeight),worldTransform.getBasis()*yaxis,worldTransform.getBasis()*xaxis,radius,radius,0,SIMD_2_PI,color,false,btScalar(10.0));
     1252                                break;
     1253                        }
     1254
     1255                case STATIC_PLANE_PROXYTYPE:
     1256                        {
     1257                                const btStaticPlaneShape* staticPlaneShape = static_cast<const btStaticPlaneShape*>(shape);
     1258                                btScalar planeConst = staticPlaneShape->getPlaneConstant();
     1259                                const btVector3& planeNormal = staticPlaneShape->getPlaneNormal();
     1260                                btVector3 planeOrigin = planeNormal * planeConst;
     1261                                btVector3 vec0,vec1;
     1262                                btPlaneSpace1(planeNormal,vec0,vec1);
     1263                                btScalar vecLen = 100.f;
     1264                                btVector3 pt0 = planeOrigin + vec0*vecLen;
     1265                                btVector3 pt1 = planeOrigin - vec0*vecLen;
     1266                                btVector3 pt2 = planeOrigin + vec1*vecLen;
     1267                                btVector3 pt3 = planeOrigin - vec1*vecLen;
     1268                                getDebugDrawer()->drawLine(worldTransform*pt0,worldTransform*pt1,color);
     1269                                getDebugDrawer()->drawLine(worldTransform*pt2,worldTransform*pt3,color);
     1270                                break;
     1271
     1272                        }
     1273                default:
     1274                        {
     1275
     1276                                if (shape->isConcave())
     1277                                {
     1278                                        btConcaveShape* concaveMesh = (btConcaveShape*) shape;
     1279
     1280                                        ///@todo pass camera, for some culling? no -> we are not a graphics lib
     1281                                        btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
     1282                                        btVector3 aabbMin(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
     1283
     1284                                        DebugDrawcallback drawCallback(getDebugDrawer(),worldTransform,color);
     1285                                        concaveMesh->processAllTriangles(&drawCallback,aabbMin,aabbMax);
     1286
     1287                                }
     1288
     1289                                if (shape->getShapeType() == CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE)
     1290                                {
     1291                                        btConvexTriangleMeshShape* convexMesh = (btConvexTriangleMeshShape*) shape;
     1292                                        //todo: pass camera for some culling                   
     1293                                        btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
     1294                                        btVector3 aabbMin(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
     1295                                        //DebugDrawcallback drawCallback;
     1296                                        DebugDrawcallback drawCallback(getDebugDrawer(),worldTransform,color);
     1297                                        convexMesh->getMeshInterface()->InternalProcessAllTriangles(&drawCallback,aabbMin,aabbMax);
     1298                                }
     1299
     1300
     1301                                /// for polyhedral shapes
     1302                                if (shape->isPolyhedral())
     1303                                {
     1304                                        btPolyhedralConvexShape* polyshape = (btPolyhedralConvexShape*) shape;
     1305
     1306                                        int i;
     1307                                        for (i=0;i<polyshape->getNumEdges();i++)
     1308                                        {
     1309                                                btVector3 a,b;
     1310                                                polyshape->getEdge(i,a,b);
     1311                                                btVector3 wa = worldTransform * a;
     1312                                                btVector3 wb = worldTransform * b;
     1313                                                getDebugDrawer()->drawLine(wa,wb,color);
     1314
     1315                                        }
     1316
     1317
     1318                                }
     1319                        }
     1320                }
     1321        }
     1322}
     1323
     1324
     1325void    btCollisionWorld::debugDrawWorld()
     1326{
     1327        if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints)
     1328        {
     1329                int numManifolds = getDispatcher()->getNumManifolds();
     1330                btVector3 color(0,0,0);
     1331                for (int i=0;i<numManifolds;i++)
     1332                {
     1333                        btPersistentManifold* contactManifold = getDispatcher()->getManifoldByIndexInternal(i);
     1334                        //btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
     1335                        //btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
     1336
     1337                        int numContacts = contactManifold->getNumContacts();
     1338                        for (int j=0;j<numContacts;j++)
     1339                        {
     1340                                btManifoldPoint& cp = contactManifold->getContactPoint(j);
     1341                                getDebugDrawer()->drawContactPoint(cp.m_positionWorldOnB,cp.m_normalWorldOnB,cp.getDistance(),cp.getLifeTime(),color);
     1342                        }
     1343                }
     1344        }
     1345
     1346        if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb))
     1347        {
     1348                int i;
     1349
     1350                for (  i=0;i<m_collisionObjects.size();i++)
     1351                {
     1352                        btCollisionObject* colObj = m_collisionObjects[i];
     1353                        if ((colObj->getCollisionFlags() & btCollisionObject::CF_DISABLE_VISUALIZE_OBJECT)==0)
     1354                        {
     1355                                if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawWireframe)
     1356                                {
     1357                                        btVector3 color(btScalar(1.),btScalar(1.),btScalar(1.));
     1358                                        switch(colObj->getActivationState())
     1359                                        {
     1360                                        case  ACTIVE_TAG:
     1361                                                color = btVector3(btScalar(1.),btScalar(1.),btScalar(1.)); break;
     1362                                        case ISLAND_SLEEPING:
     1363                                                color =  btVector3(btScalar(0.),btScalar(1.),btScalar(0.));break;
     1364                                        case WANTS_DEACTIVATION:
     1365                                                color = btVector3(btScalar(0.),btScalar(1.),btScalar(1.));break;
     1366                                        case DISABLE_DEACTIVATION:
     1367                                                color = btVector3(btScalar(1.),btScalar(0.),btScalar(0.));break;
     1368                                        case DISABLE_SIMULATION:
     1369                                                color = btVector3(btScalar(1.),btScalar(1.),btScalar(0.));break;
     1370                                        default:
     1371                                                {
     1372                                                        color = btVector3(btScalar(1),btScalar(0.),btScalar(0.));
     1373                                                }
     1374                                        };
     1375
     1376                                        debugDrawObject(colObj->getWorldTransform(),colObj->getCollisionShape(),color);
     1377                                }
     1378                                if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawAabb))
     1379                                {
     1380                                        btVector3 minAabb,maxAabb;
     1381                                        btVector3 colorvec(1,0,0);
     1382                                        colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb,maxAabb);
     1383                                        m_debugDrawer->drawAabb(minAabb,maxAabb,colorvec);
     1384                                }
     1385                        }
     1386
     1387                }
     1388        }
     1389}
     1390
     1391
     1392void    btCollisionWorld::serializeCollisionObjects(btSerializer* serializer)
     1393{
     1394        int i;
     1395        //serialize all collision objects
     1396        for (i=0;i<m_collisionObjects.size();i++)
     1397        {
     1398                btCollisionObject* colObj = m_collisionObjects[i];
     1399                if (colObj->getInternalType() == btCollisionObject::CO_COLLISION_OBJECT)
     1400                {
     1401                        colObj->serializeSingleObject(serializer);
     1402                }
     1403        }
     1404
     1405        ///keep track of shapes already serialized
     1406        btHashMap<btHashPtr,btCollisionShape*>  serializedShapes;
     1407
     1408        for (i=0;i<m_collisionObjects.size();i++)
     1409        {
     1410                btCollisionObject* colObj = m_collisionObjects[i];
     1411                btCollisionShape* shape = colObj->getCollisionShape();
     1412
     1413                if (!serializedShapes.find(shape))
     1414                {
     1415                        serializedShapes.insert(shape,shape);
     1416                        shape->serializeSingleShape(serializer);
     1417                }
     1418        }
     1419
     1420}
     1421
     1422
     1423void    btCollisionWorld::serialize(btSerializer* serializer)
     1424{
     1425
     1426        serializer->startSerialization();
     1427       
     1428        serializeCollisionObjects(serializer);
     1429       
     1430        serializer->finishSerialization();
     1431}
     1432
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btCollisionWorld.h

    r5781 r8284  
    2323 * Bullet is a Collision Detection and Rigid Body Dynamics Library. The Library is Open Source and free for commercial use, under the ZLib license ( http://opensource.org/licenses/zlib-license.php ).
    2424 *
     25 * The main documentation is Bullet_User_Manual.pdf, included in the source code distribution.
    2526 * There is the Physics Forum for feedback and general Collision Detection and Physics discussions.
    2627 * Please visit http://www.bulletphysics.com
     
    3031 * @subsection step1 Step 1: Download
    3132 * You can download the Bullet Physics Library from the Google Code repository: http://code.google.com/p/bullet/downloads/list
     33 *
    3234 * @subsection step2 Step 2: Building
    33  * Bullet comes with autogenerated Project Files for Microsoft Visual Studio 6, 7, 7.1 and 8.
    34  * The main Workspace/Solution is located in Bullet/msvc/8/wksbullet.sln (replace 8 with your version).
    35  *
    36  * Under other platforms, like Linux or Mac OS-X, Bullet can be build using either using make, cmake, http://www.cmake.org , or jam, http://www.perforce.com/jam/jam.html . cmake can autogenerate Xcode, KDevelop, MSVC and other build systems. just run cmake . in the root of Bullet.
    37  * So if you are not using MSVC or cmake, you can run ./autogen.sh ./configure to create both Makefile and Jamfile and then run make or jam.
    38  * Jam is a build system that can build the library, demos and also autogenerate the MSVC Project Files.
    39  * If you don't have jam installed, you can make jam from the included jam-2.5 sources, or download jam from ftp://ftp.perforce.com/jam
     35 * Bullet main build system for all platforms is cmake, you can download http://www.cmake.org
     36 * cmake can autogenerate projectfiles for Microsoft Visual Studio, Apple Xcode, KDevelop and Unix Makefiles.
     37 * The easiest is to run the CMake cmake-gui graphical user interface and choose the options and generate projectfiles.
     38 * You can also use cmake in the command-line. Here are some examples for various platforms:
     39 * cmake . -G "Visual Studio 9 2008"
     40 * cmake . -G Xcode
     41 * cmake . -G "Unix Makefiles"
     42 * Although cmake is recommended, you can also use autotools for UNIX: ./autogen.sh ./configure to create a Makefile and then run make.
    4043 *
    4144 * @subsection step3 Step 3: Testing demos
     
    5457 *
    5558 * @section copyright Copyright
    56  * Copyright (C) 2005-2008 Erwin Coumans, some contributions Copyright Gino van den Bergen, Christer Ericson, Simon Hobbs, Ricardo Padrela, F Richter(res), Stephane Redon
    57  * Special thanks to all visitors of the Bullet Physics forum, and in particular above contributors, John McCutchan, Nathanael Presson, Dave Eberle, Dirk Gregorius, Erin Catto, Dave Eberle, Adam Moravanszky,
    58  * Pierre Terdiman, Kenny Erleben, Russell Smith, Oliver Strunk, Jan Paul van Waveren, Marten Svanfeldt.
     59 * For up-to-data information and copyright and contributors list check out the Bullet_User_Manual.pdf
    5960 *
    6061 */
    61 
    62 
    6362 
    6463 
     
    7170class btConvexShape;
    7271class btBroadphaseInterface;
     72class btSerializer;
     73
    7374#include "LinearMath/btVector3.h"
    7475#include "LinearMath/btTransform.h"
     
    8283{
    8384
    84 
    8585       
    8686protected:
    8787
    8888        btAlignedObjectArray<btCollisionObject*>        m_collisionObjects;
    89 
    9089       
    9190        btDispatcher*   m_dispatcher1;
     
    9998        btIDebugDraw*   m_debugDrawer;
    10099
    101 
    102        
     100        ///m_forceUpdateAllAabbs can be set to false as an optimization to only update active object AABBs
     101        ///it is true by default, because it is error-prone (setting the position of static objects wouldn't update their AABB)
     102        bool m_forceUpdateAllAabbs;
     103
     104        void    serializeCollisionObjects(btSerializer* serializer);
     105
    103106public:
    104107
     
    142145
    143146        virtual void    updateAabbs();
    144 
    145147       
    146148        virtual void    setDebugDrawer(btIDebugDraw*    debugDrawer)
     
    153155                return m_debugDrawer;
    154156        }
     157
     158        virtual void    debugDrawWorld();
     159
     160        virtual void debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color);
    155161
    156162
     
    161167                int     m_shapePart;
    162168                int     m_triangleIndex;
    163 
    164169               
    165170                //const btCollisionShape*       m_shapeTemp;
     
    239244                btVector3       m_hitNormalWorld;
    240245                btVector3       m_hitPointWorld;
    241 
    242246                       
    243247                virtual btScalar        addSingleResult(LocalRayResult& rayResult,bool normalInWorldSpace)
     
    245249                        //caller already does the filter on the m_closestHitFraction
    246250                        btAssert(rayResult.m_hitFraction <= m_closestHitFraction);
    247 
    248251                       
    249252                        m_closestHitFraction = rayResult.m_hitFraction;
     
    262265        };
    263266
     267        struct  AllHitsRayResultCallback : public RayResultCallback
     268        {
     269                AllHitsRayResultCallback(const btVector3&       rayFromWorld,const btVector3&   rayToWorld)
     270                :m_rayFromWorld(rayFromWorld),
     271                m_rayToWorld(rayToWorld)
     272                {
     273                }
     274
     275                btAlignedObjectArray<btCollisionObject*>                m_collisionObjects;
     276
     277                btVector3       m_rayFromWorld;//used to calculate hitPointWorld from hitFraction
     278                btVector3       m_rayToWorld;
     279
     280                btAlignedObjectArray<btVector3> m_hitNormalWorld;
     281                btAlignedObjectArray<btVector3> m_hitPointWorld;
     282                btAlignedObjectArray<btScalar> m_hitFractions;
     283                       
     284                virtual btScalar        addSingleResult(LocalRayResult& rayResult,bool normalInWorldSpace)
     285                {
     286                        m_collisionObject = rayResult.m_collisionObject;
     287                        m_collisionObjects.push_back(rayResult.m_collisionObject);
     288                        btVector3 hitNormalWorld;
     289                        if (normalInWorldSpace)
     290                        {
     291                                hitNormalWorld = rayResult.m_hitNormalLocal;
     292                        } else
     293                        {
     294                                ///need to transform normal into worldspace
     295                                hitNormalWorld = m_collisionObject->getWorldTransform().getBasis()*rayResult.m_hitNormalLocal;
     296                        }
     297                        m_hitNormalWorld.push_back(hitNormalWorld);
     298                        btVector3 hitPointWorld;
     299                        hitPointWorld.setInterpolate3(m_rayFromWorld,m_rayToWorld,rayResult.m_hitFraction);
     300                        m_hitPointWorld.push_back(hitPointWorld);
     301                        m_hitFractions.push_back(rayResult.m_hitFraction);
     302                        return m_closestHitFraction;
     303                }
     304        };
     305
    264306
    265307        struct LocalConvexResult
     
    292334                short int       m_collisionFilterGroup;
    293335                short int       m_collisionFilterMask;
    294 
    295336               
    296337                ConvexResultCallback()
     
    304345                {
    305346                }
    306 
    307347               
    308348                bool    hasHit() const
     
    310350                        return (m_closestHitFraction < btScalar(1.));
    311351                }
    312 
    313352
    314353               
     
    339378                btVector3       m_hitPointWorld;
    340379                btCollisionObject*      m_hitCollisionObject;
    341 
    342380               
    343381                virtual btScalar        addSingleResult(LocalConvexResult& convexResult,bool normalInWorldSpace)
     
    345383//caller already does the filter on the m_closestHitFraction
    346384                        btAssert(convexResult.m_hitFraction <= m_closestHitFraction);
    347 
    348385                                               
    349386                        m_closestHitFraction = convexResult.m_hitFraction;
     
    362399        };
    363400
     401        ///ContactResultCallback is used to report contact points
     402        struct  ContactResultCallback
     403        {
     404                short int       m_collisionFilterGroup;
     405                short int       m_collisionFilterMask;
     406               
     407                ContactResultCallback()
     408                        :m_collisionFilterGroup(btBroadphaseProxy::DefaultFilter),
     409                        m_collisionFilterMask(btBroadphaseProxy::AllFilter)
     410                {
     411                }
     412
     413                virtual ~ContactResultCallback()
     414                {
     415                }
     416               
     417                virtual bool needsCollision(btBroadphaseProxy* proxy0) const
     418                {
     419                        bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0;
     420                        collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask);
     421                        return collides;
     422                }
     423
     424                virtual btScalar        addSingleResult(btManifoldPoint& cp,    const btCollisionObject* colObj0,int partId0,int index0,const btCollisionObject* colObj1,int partId1,int index1) = 0;
     425        };
     426
     427
     428
    364429        int     getNumCollisionObjects() const
    365430        {
     
    369434        /// rayTest performs a raycast on all objects in the btCollisionWorld, and calls the resultCallback
    370435        /// This allows for several queries: first hit, all hits, any hit, dependent on the value returned by the callback.
    371         void    rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const;
    372 
    373         // convexTest performs a swept convex cast on all objects in the btCollisionWorld, and calls the resultCallback
    374         // This allows for several queries: first hit, all hits, any hit, dependent on the value return by the callback.
     436        virtual void rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const;
     437
     438        /// convexTest performs a swept convex cast on all objects in the btCollisionWorld, and calls the resultCallback
     439        /// This allows for several queries: first hit, all hits, any hit, dependent on the value return by the callback.
    375440        void    convexSweepTest (const btConvexShape* castShape, const btTransform& from, const btTransform& to, ConvexResultCallback& resultCallback,  btScalar allowedCcdPenetration = btScalar(0.)) const;
     441
     442        ///contactTest performs a discrete collision test between colObj against all objects in the btCollisionWorld, and calls the resultCallback.
     443        ///it reports one or more contact points for every overlapping object (including the one with deepest penetration)
     444        void    contactTest(btCollisionObject* colObj, ContactResultCallback& resultCallback);
     445
     446        ///contactTest performs a discrete collision test between two collision objects and calls the resultCallback if overlap if detected.
     447        ///it reports one or more contact points (including the one with deepest penetration)
     448        void    contactPairTest(btCollisionObject* colObjA, btCollisionObject* colObjB, ContactResultCallback& resultCallback);
    376449
    377450
     
    392465                                          ConvexResultCallback& resultCallback, btScalar        allowedPenetration);
    393466
    394         void    addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup=btBroadphaseProxy::DefaultFilter,short int collisionFilterMask=btBroadphaseProxy::AllFilter);
     467        virtual void    addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup=btBroadphaseProxy::DefaultFilter,short int collisionFilterMask=btBroadphaseProxy::AllFilter);
    395468
    396469        btCollisionObjectArray& getCollisionObjectArray()
     
    405478
    406479
    407         void    removeCollisionObject(btCollisionObject* collisionObject);
     480        virtual void    removeCollisionObject(btCollisionObject* collisionObject);
    408481
    409482        virtual void    performDiscreteCollisionDetection();
     
    418491                return m_dispatchInfo;
    419492        }
     493       
     494        bool    getForceUpdateAllAabbs() const
     495        {
     496                return m_forceUpdateAllAabbs;
     497        }
     498        void setForceUpdateAllAabbs( bool forceUpdateAllAabbs)
     499        {
     500                m_forceUpdateAllAabbs = forceUpdateAllAabbs;
     501        }
     502
     503        ///Preliminary serialization test for Bullet 2.76. Loading those files requires a separate parser (Bullet/Demos/SerializeDemo)
     504        virtual void    serialize(btSerializer* serializer);
    420505
    421506};
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.cpp

    r5781 r8284  
    115115        void    ProcessChildShape(btCollisionShape* childShape,int index)
    116116        {
    117                
     117                btAssert(index>=0);
    118118                btCompoundShape* compoundShape = static_cast<btCompoundShape*>(m_compoundColObj->getCollisionShape());
     119                btAssert(index<compoundShape->getNumChildShapes());
    119120
    120121
     
    142143                        if (!m_childCollisionAlgorithms[index])
    143144                                m_childCollisionAlgorithms[index] = m_dispatcher->findAlgorithm(m_compoundColObj,m_otherObj,m_sharedManifold);
     145
     146                        ///detect swapping case
     147                        if (m_resultOut->getBody0Internal() == m_compoundColObj)
     148                        {
     149                                m_resultOut->setShapeIdentifiersA(-1,index);
     150                        } else
     151                        {
     152                                m_resultOut->setShapeIdentifiersB(-1,index);
     153                        }
    144154
    145155                        m_childCollisionAlgorithms[index]->processCollision(m_compoundColObj,m_otherObj,m_dispatchInfo,m_resultOut);
     
    258268                int i;
    259269                btManifoldArray manifoldArray;
    260 
     270        btCollisionShape* childShape = 0;
     271        btTransform     orgTrans;
     272        btTransform     orgInterpolationTrans;
     273        btTransform     newChildWorldTrans;
     274        btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;       
     275       
    261276                for (i=0;i<numChildren;i++)
    262277                {
    263278                        if (m_childCollisionAlgorithms[i])
    264279                        {
    265                                 btCollisionShape* childShape = compoundShape->getChildShape(i);
     280                                childShape = compoundShape->getChildShape(i);
    266281                        //if not longer overlapping, remove the algorithm
    267                                 btTransform     orgTrans = colObj->getWorldTransform();
    268                                 btTransform     orgInterpolationTrans = colObj->getInterpolationWorldTransform();
     282                orgTrans = colObj->getWorldTransform();
     283                orgInterpolationTrans = colObj->getInterpolationWorldTransform();
    269284                                const btTransform& childTrans = compoundShape->getChildTransform(i);
    270                                 btTransform     newChildWorldTrans = orgTrans*childTrans ;
     285                newChildWorldTrans = orgTrans*childTrans ;
    271286
    272287                                //perform an AABB check first
    273                                 btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
    274288                                childShape->getAabb(newChildWorldTrans,aabbMin0,aabbMax0);
    275289                                otherObj->getCollisionShape()->getAabb(otherObj->getWorldTransform(),aabbMin1,aabbMax1);
     
    281295                                        m_childCollisionAlgorithms[i] = 0;
    282296                                }
    283 
    284297                        }
    285                        
    286                 }
    287 
    288                
    289 
     298                }
    290299        }
    291300}
     
    312321        int numChildren = m_childCollisionAlgorithms.size();
    313322        int i;
     323    btTransform orgTrans;
     324    btScalar frac;
    314325        for (i=0;i<numChildren;i++)
    315326        {
     
    318329
    319330                //backup
    320                 btTransform     orgTrans = colObj->getWorldTransform();
     331        orgTrans = colObj->getWorldTransform();
    321332       
    322333                const btTransform& childTrans = compoundShape->getChildTransform(i);
     
    326337                btCollisionShape* tmpShape = colObj->getCollisionShape();
    327338                colObj->internalSetTemporaryCollisionShape( childShape );
    328                 btScalar frac = m_childCollisionAlgorithms[i]->calculateTimeOfImpact(colObj,otherObj,dispatchInfo,resultOut);
     339        frac = m_childCollisionAlgorithms[i]->calculateTimeOfImpact(colObj,otherObj,dispatchInfo,resultOut);
    329340                if (frac<hitFraction)
    330341                {
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp

    r5781 r8284  
    9696        if (m_dispatchInfoPtr && m_dispatchInfoPtr->m_debugDraw && (m_dispatchInfoPtr->m_debugDraw->getDebugMode() &btIDebugDraw::DBG_DrawWireframe ))
    9797        {
    98                 btVector3 color(255,255,0);
     98                btVector3 color(1,1,0);
    9999                btTransform& tr = ob->getWorldTransform();
    100100                m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[0]),tr(triangle[1]),color);
     
    122122               
    123123                btCollisionAlgorithm* colAlgo = ci.m_dispatcher1->findAlgorithm(m_convexBody,m_triBody,m_manifoldPtr);
    124                 ///this should use the btDispatcher, so the actual registered algorithm is used
    125                 //              btConvexConvexAlgorithm cvxcvxalgo(m_manifoldPtr,ci,m_convexBody,m_triBody);
    126 
    127                 m_resultOut->setShapeIdentifiers(-1,-1,partId,triangleIndex);
    128         //      cvxcvxalgo.setShapeIdentifiers(-1,-1,partId,triangleIndex);
    129 //              cvxcvxalgo.processCollision(m_convexBody,m_triBody,*m_dispatchInfoPtr,m_resultOut);
     124
     125                if (m_resultOut->getBody0Internal() == m_triBody)
     126                {
     127                        m_resultOut->setShapeIdentifiersA(partId,triangleIndex);
     128                }
     129                else
     130                {
     131                        m_resultOut->setShapeIdentifiersB(partId,triangleIndex);
     132                }
     133       
    130134                colAlgo->processCollision(m_convexBody,m_triBody,*m_dispatchInfoPtr,m_resultOut);
    131135                colAlgo->~btCollisionAlgorithm();
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.cpp

    r5781 r8284  
    1414*/
    1515
     16///Specialized capsule-capsule collision algorithm has been added for Bullet 2.75 release to increase ragdoll performance
     17///If you experience problems with capsule-capsule collision, try to define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER and report it in the Bullet forums
     18///with reproduction case
     19//define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER 1
     20
    1621#include "btConvexConvexAlgorithm.h"
    1722
     
    2126#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
    2227#include "BulletCollision/CollisionShapes/btConvexShape.h"
     28#include "BulletCollision/CollisionShapes/btCapsuleShape.h"
     29
     30
    2331#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
    2432#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
     
    4452
    4553
    46 
     54///////////
     55
     56
     57
     58static SIMD_FORCE_INLINE void segmentsClosestPoints(
     59        btVector3& ptsVector,
     60        btVector3& offsetA,
     61        btVector3& offsetB,
     62        btScalar& tA, btScalar& tB,
     63        const btVector3& translation,
     64        const btVector3& dirA, btScalar hlenA,
     65        const btVector3& dirB, btScalar hlenB )
     66{
     67        // compute the parameters of the closest points on each line segment
     68
     69        btScalar dirA_dot_dirB = btDot(dirA,dirB);
     70        btScalar dirA_dot_trans = btDot(dirA,translation);
     71        btScalar dirB_dot_trans = btDot(dirB,translation);
     72
     73        btScalar denom = 1.0f - dirA_dot_dirB * dirA_dot_dirB;
     74
     75        if ( denom == 0.0f ) {
     76                tA = 0.0f;
     77        } else {
     78                tA = ( dirA_dot_trans - dirB_dot_trans * dirA_dot_dirB ) / denom;
     79                if ( tA < -hlenA )
     80                        tA = -hlenA;
     81                else if ( tA > hlenA )
     82                        tA = hlenA;
     83        }
     84
     85        tB = tA * dirA_dot_dirB - dirB_dot_trans;
     86
     87        if ( tB < -hlenB ) {
     88                tB = -hlenB;
     89                tA = tB * dirA_dot_dirB + dirA_dot_trans;
     90
     91                if ( tA < -hlenA )
     92                        tA = -hlenA;
     93                else if ( tA > hlenA )
     94                        tA = hlenA;
     95        } else if ( tB > hlenB ) {
     96                tB = hlenB;
     97                tA = tB * dirA_dot_dirB + dirA_dot_trans;
     98
     99                if ( tA < -hlenA )
     100                        tA = -hlenA;
     101                else if ( tA > hlenA )
     102                        tA = hlenA;
     103        }
     104
     105        // compute the closest points relative to segment centers.
     106
     107        offsetA = dirA * tA;
     108        offsetB = dirB * tB;
     109
     110        ptsVector = translation - offsetA + offsetB;
     111}
     112
     113
     114static SIMD_FORCE_INLINE btScalar capsuleCapsuleDistance(
     115        btVector3& normalOnB,
     116        btVector3& pointOnB,
     117        btScalar capsuleLengthA,
     118        btScalar        capsuleRadiusA,
     119        btScalar capsuleLengthB,
     120        btScalar        capsuleRadiusB,
     121        int capsuleAxisA,
     122        int capsuleAxisB,
     123        const btTransform& transformA,
     124        const btTransform& transformB,
     125        btScalar distanceThreshold )
     126{
     127        btVector3 directionA = transformA.getBasis().getColumn(capsuleAxisA);
     128        btVector3 translationA = transformA.getOrigin();
     129        btVector3 directionB = transformB.getBasis().getColumn(capsuleAxisB);
     130        btVector3 translationB = transformB.getOrigin();
     131
     132        // translation between centers
     133
     134        btVector3 translation = translationB - translationA;
     135
     136        // compute the closest points of the capsule line segments
     137
     138        btVector3 ptsVector;           // the vector between the closest points
     139       
     140        btVector3 offsetA, offsetB;    // offsets from segment centers to their closest points
     141        btScalar tA, tB;              // parameters on line segment
     142
     143        segmentsClosestPoints( ptsVector, offsetA, offsetB, tA, tB, translation,
     144                                                   directionA, capsuleLengthA, directionB, capsuleLengthB );
     145
     146        btScalar distance = ptsVector.length() - capsuleRadiusA - capsuleRadiusB;
     147
     148        if ( distance > distanceThreshold )
     149                return distance;
     150
     151        btScalar lenSqr = ptsVector.length2();
     152        if (lenSqr<= (SIMD_EPSILON*SIMD_EPSILON))
     153        {
     154                //degenerate case where 2 capsules are likely at the same location: take a vector tangential to 'directionA'
     155                btVector3 q;
     156                btPlaneSpace1(directionA,normalOnB,q);
     157        } else
     158        {
     159                // compute the contact normal
     160                normalOnB = ptsVector*-btRecipSqrt(lenSqr);
     161        }
     162        pointOnB = transformB.getOrigin()+offsetB + normalOnB * capsuleRadiusB;
     163
     164        return distance;
     165}
     166
     167
     168
     169
     170
     171
     172
     173//////////
    47174
    48175
     
    70197m_lowLevelOfDetail(false),
    71198#ifdef USE_SEPDISTANCE_UTIL2
    72 ,m_sepDistance((static_cast<btConvexShape*>(body0->getCollisionShape()))->getAngularMotionDisc(),
     199m_sepDistance((static_cast<btConvexShape*>(body0->getCollisionShape()))->getAngularMotionDisc(),
    73200                          (static_cast<btConvexShape*>(body1->getCollisionShape()))->getAngularMotionDisc()),
    74201#endif
     
    112239                m_transformA(transformA),
    113240                m_transformB(transformB),
     241                m_unPerturbedTransform(unPerturbedTransform),
    114242                m_perturbA(perturbA),
    115                 m_unPerturbedTransform(unPerturbedTransform),
    116243                m_debugDrawer(debugDrawer)
    117244        {
     
    156283extern btScalar gContactBreakingThreshold;
    157284
     285
    158286//
    159287// Convex-Convex collision algorithm
     
    177305        btConvexShape* min1 = static_cast<btConvexShape*>(body1->getCollisionShape());
    178306
     307        btVector3  normalOnB;
     308                btVector3  pointOnBWorld;
     309#ifndef BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
     310        if ((min0->getShapeType() == CAPSULE_SHAPE_PROXYTYPE) && (min1->getShapeType() == CAPSULE_SHAPE_PROXYTYPE))
     311        {
     312                btCapsuleShape* capsuleA = (btCapsuleShape*) min0;
     313                btCapsuleShape* capsuleB = (btCapsuleShape*) min1;
     314                btVector3 localScalingA = capsuleA->getLocalScaling();
     315                btVector3 localScalingB = capsuleB->getLocalScaling();
     316               
     317                btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
     318
     319                btScalar dist = capsuleCapsuleDistance(normalOnB,       pointOnBWorld,capsuleA->getHalfHeight(),capsuleA->getRadius(),
     320                        capsuleB->getHalfHeight(),capsuleB->getRadius(),capsuleA->getUpAxis(),capsuleB->getUpAxis(),
     321                        body0->getWorldTransform(),body1->getWorldTransform(),threshold);
     322
     323                if (dist<threshold)
     324                {
     325                        btAssert(normalOnB.length2()>=(SIMD_EPSILON*SIMD_EPSILON));
     326                        resultOut->addContactPoint(normalOnB,pointOnBWorld,dist);       
     327                }
     328                resultOut->refreshContactPoints();
     329                return;
     330        }
     331#endif //BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
     332
     333
    179334#ifdef USE_SEPDISTANCE_UTIL2
    180         m_sepDistance.updateSeparatingDistance(body0->getWorldTransform(),body1->getWorldTransform());
     335        if (dispatchInfo.m_useConvexConservativeDistanceUtil)
     336        {
     337                m_sepDistance.updateSeparatingDistance(body0->getWorldTransform(),body1->getWorldTransform());
     338        }
     339
    181340        if (!dispatchInfo.m_useConvexConservativeDistanceUtil || m_sepDistance.getConservativeSeparatingDistance()<=0.f)
    182341#endif //USE_SEPDISTANCE_UTIL2
     
    195354        if (dispatchInfo.m_useConvexConservativeDistanceUtil)
    196355        {
    197                 input.m_maximumDistanceSquared = 1e30f;
     356                input.m_maximumDistanceSquared = BT_LARGE_FLOAT;
    198357        } else
    199358#endif //USE_SEPDISTANCE_UTIL2
    200359        {
    201                 input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactBreakingThreshold();
     360                if (dispatchInfo.m_convexMaxDistanceUseCPT)
     361                {
     362                        input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactProcessingThreshold();
     363                } else
     364                {
     365                        input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactBreakingThreshold();
     366                }
    202367                input.m_maximumDistanceSquared*= input.m_maximumDistanceSquared;
    203368        }
     
    208373
    209374        gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
    210         btScalar sepDist = gjkPairDetector.getCachedSeparatingDistance()+dispatchInfo.m_convexConservativeDistanceThreshold;
    211 
    212         //now perturbe directions to get multiple contact points
    213         btVector3 v0,v1;
    214         btVector3 sepNormalWorldSpace = gjkPairDetector.getCachedSeparatingAxis().normalized();
    215         btPlaneSpace1(sepNormalWorldSpace,v0,v1);
     375
     376       
     377
     378#ifdef USE_SEPDISTANCE_UTIL2
     379        btScalar sepDist = 0.f;
     380        if (dispatchInfo.m_useConvexConservativeDistanceUtil)
     381        {
     382                sepDist = gjkPairDetector.getCachedSeparatingDistance();
     383                if (sepDist>SIMD_EPSILON)
     384                {
     385                        sepDist += dispatchInfo.m_convexConservativeDistanceThreshold;
     386                        //now perturbe directions to get multiple contact points
     387                       
     388                }
     389        }
     390#endif //USE_SEPDISTANCE_UTIL2
     391
    216392        //now perform 'm_numPerturbationIterations' collision queries with the perturbated collision objects
    217393       
    218394        //perform perturbation when more then 'm_minimumPointsPerturbationThreshold' points
    219         if (resultOut->getPersistentManifold()->getNumContacts() < m_minimumPointsPerturbationThreshold)
     395        if (m_numPerturbationIterations && resultOut->getPersistentManifold()->getNumContacts() < m_minimumPointsPerturbationThreshold)
    220396        {
    221397               
    222398                int i;
     399                btVector3 v0,v1;
     400                btVector3 sepNormalWorldSpace;
     401       
     402                sepNormalWorldSpace = gjkPairDetector.getCachedSeparatingAxis().normalized();
     403                btPlaneSpace1(sepNormalWorldSpace,v0,v1);
     404
    223405
    224406                bool perturbeA = true;
     
    250432                for ( i=0;i<m_numPerturbationIterations;i++)
    251433                {
     434                        if (v0.length2()>SIMD_EPSILON)
     435                        {
    252436                        btQuaternion perturbeRot(v0,perturbeAngle);
    253437                        btScalar iterationAngle = i*(SIMD_2_PI/btScalar(m_numPerturbationIterations));
     
    273457                        btPerturbedContactResult perturbedResultOut(resultOut,input.m_transformA,input.m_transformB,unPerturbedTransform,perturbeA,dispatchInfo.m_debugDraw);
    274458                        gjkPairDetector.getClosestPoints(input,perturbedResultOut,dispatchInfo.m_debugDraw);
     459                        }
    275460                       
    276                        
    277461                }
    278462        }
     
    281465
    282466#ifdef USE_SEPDISTANCE_UTIL2
    283         if (dispatchInfo.m_useConvexConservativeDistanceUtil)
     467        if (dispatchInfo.m_useConvexConservativeDistanceUtil && (sepDist>SIMD_EPSILON))
    284468        {
    285469                m_sepDistance.initSeparatingDistance(gjkPairDetector.getCachedSeparatingAxis(),sepDist,body0->getWorldTransform(),body1->getWorldTransform());
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h

    r5781 r8284  
    3232///Either improve GJK for large size ratios (testing a 100 units versus a 0.1 unit object) or only enable the util
    3333///for certain pairs that have a small size ratio
    34 ///#define USE_SEPDISTANCE_UTIL2 1
     34
     35//#define USE_SEPDISTANCE_UTIL2 1
    3536
    3637///The convexConvexAlgorithm collision algorithm implements time of impact, convex closest points and penetration depth calculations between two convex objects.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp

    r5781 r8284  
    103103        btStaticPlaneShape* planeShape = (btStaticPlaneShape*) planeObj->getCollisionShape();
    104104
    105     bool hasCollision = false;
     105   
    106106        const btVector3& planeNormal = planeShape->getPlaneNormal();
    107         const btScalar& planeConstant = planeShape->getPlaneConstant();
     107        //const btScalar& planeConstant = planeShape->getPlaneConstant();
    108108
    109109        //first perform a collision query with the non-perturbated collision objects
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h

    r5781 r8284  
    6161                       
    6262                CreateFunc()
    63                         : m_numPerturbationIterations(3),
    64                         m_minimumPointsPerturbationThreshold(3)
     63                        : m_numPerturbationIterations(1),
     64                        m_minimumPointsPerturbationThreshold(1)
    6565                {
    6666                }
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp

    r5781 r8284  
    4646        void* mem = btAlignedAlloc(sizeof(btVoronoiSimplexSolver),16);
    4747        m_simplexSolver = new (mem)btVoronoiSimplexSolver();
    48        
    49 #define USE_EPA 1
    50 #ifdef USE_EPA
    51         mem = btAlignedAlloc(sizeof(btGjkEpaPenetrationDepthSolver),16);
    52         m_pdSolver = new (mem)btGjkEpaPenetrationDepthSolver;
    53 #else
    54         mem = btAlignedAlloc(sizeof(btMinkowskiPenetrationDepthSolver),16);
    55         m_pdSolver = new (mem)btMinkowskiPenetrationDepthSolver;
    56 #endif//USE_EPA
    57        
    58 
     48
     49        if (constructionInfo.m_useEpaPenetrationAlgorithm)
     50        {
     51                mem = btAlignedAlloc(sizeof(btGjkEpaPenetrationDepthSolver),16);
     52                m_pdSolver = new (mem)btGjkEpaPenetrationDepthSolver;
     53        }else
     54        {
     55                mem = btAlignedAlloc(sizeof(btMinkowskiPenetrationDepthSolver),16);
     56                m_pdSolver = new (mem)btMinkowskiPenetrationDepthSolver;
     57        }
     58       
    5959        //default CreationFunctions, filling the m_doubleDispatch table
    6060        mem = btAlignedAlloc(sizeof(btConvexConvexAlgorithm::CreateFunc),16);
     
    103103        int sl = sizeof(btConvexSeparatingDistanceUtil);
    104104        sl = sizeof(btGjkPairDetector);
    105         int     collisionAlgorithmMaxElementSize = btMax(maxSize,maxSize2);
     105        int     collisionAlgorithmMaxElementSize = btMax(maxSize,constructionInfo.m_customCollisionAlgorithmMaxElementSize);
     106        collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize2);
    106107        collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize3);
    107108
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h

    r5781 r8284  
    2828        int                                     m_defaultMaxPersistentManifoldPoolSize;
    2929        int                                     m_defaultMaxCollisionAlgorithmPoolSize;
     30        int                                     m_customCollisionAlgorithmMaxElementSize;
    3031        int                                     m_defaultStackAllocatorSize;
     32        int                                     m_useEpaPenetrationAlgorithm;
    3133
    3234        btDefaultCollisionConstructionInfo()
     
    3638                m_defaultMaxPersistentManifoldPoolSize(4096),
    3739                m_defaultMaxCollisionAlgorithmPoolSize(4096),
    38                 m_defaultStackAllocatorSize(0)
     40                m_customCollisionAlgorithmMaxElementSize(0),
     41                m_defaultStackAllocatorSize(0),
     42                m_useEpaPenetrationAlgorithm(true)
    3943        {
    4044        }
     
    109113        }
    110114
     115        virtual btVoronoiSimplexSolver* getSimplexSolver()
     116        {
     117                return m_simplexSolver;
     118        }
     119
    111120
    112121        virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1);
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btGhostObject.h

    r5781 r8284  
    161161        }
    162162
    163         virtual void    removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy0,btDispatcher* dispatcher)
     163        virtual void    removeOverlappingPairsContainingProxy(btBroadphaseProxy* /*proxy0*/,btDispatcher* /*dispatcher*/)
    164164        {
    165165                btAssert(0);
     
    173173
    174174#endif
     175
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btManifoldResult.cpp

    r5781 r8284  
    4848                m_body0(body0),
    4949                m_body1(body1)
     50#ifdef DEBUG_PART_INDEX
     51                ,m_partId0(-1),
     52        m_partId1(-1),
     53        m_index0(-1),
     54        m_index1(-1)
     55#endif //DEBUG_PART_INDEX
    5056{
    5157        m_rootTransA = body0->getWorldTransform();
     
    8995
    9096   //BP mod, store contact triangles.
    91    newPt.m_partId0 = m_partId0;
    92    newPt.m_partId1 = m_partId1;
    93    newPt.m_index0  = m_index0;
    94    newPt.m_index1  = m_index1;
     97        if (isSwapped)
     98        {
     99                newPt.m_partId0 = m_partId1;
     100                newPt.m_partId1 = m_partId0;
     101                newPt.m_index0  = m_index1;
     102                newPt.m_index1  = m_index0;
     103        } else
     104        {
     105                newPt.m_partId0 = m_partId0;
     106                newPt.m_partId1 = m_partId1;
     107                newPt.m_index0  = m_index0;
     108                newPt.m_index1  = m_index1;
     109        }
    95110        //printf("depth=%f\n",depth);
    96111        ///@todo, check this for any side effects
     
    113128                btCollisionObject* obj0 = isSwapped? m_body1 : m_body0;
    114129                btCollisionObject* obj1 = isSwapped? m_body0 : m_body1;
    115                 (*gContactAddedCallback)(m_manifoldPtr->getContactPoint(insertIndex),obj0,m_partId0,m_index0,obj1,m_partId1,m_index1);
     130                (*gContactAddedCallback)(m_manifoldPtr->getContactPoint(insertIndex),obj0,newPt.m_partId0,newPt.m_index0,obj1,newPt.m_partId1,newPt.m_index1);
    116131        }
    117132
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btManifoldResult.h

    r5781 r8284  
    2929extern ContactAddedCallback             gContactAddedCallback;
    3030
     31//#define DEBUG_PART_INDEX 1
    3132
    3233
     
    3435class btManifoldResult : public btDiscreteCollisionDetectorInterface::Result
    3536{
     37protected:
     38
    3639        btPersistentManifold* m_manifoldPtr;
    3740
     
    5154
    5255        btManifoldResult()
     56#ifdef DEBUG_PART_INDEX
     57                :
     58        m_partId0(-1),
     59        m_partId1(-1),
     60        m_index0(-1),
     61        m_index1(-1)
     62#endif //DEBUG_PART_INDEX
    5363        {
    5464        }
     
    7282        }
    7383
    74         virtual void setShapeIdentifiers(int partId0,int index0,        int partId1,int index1)
     84        virtual void setShapeIdentifiersA(int partId0,int index0)
    7585        {
    76                         m_partId0=partId0;
    77                         m_partId1=partId1;
    78                         m_index0=index0;
    79                         m_index1=index1;               
     86                m_partId0=partId0;
     87                m_index0=index0;
     88        }
     89
     90        virtual void setShapeIdentifiersB(      int partId1,int index1)
     91        {
     92                m_partId1=partId1;
     93                m_index1=index1;
    8094        }
    8195
     
    100114        }
    101115
     116        const btCollisionObject* getBody0Internal() const
     117        {
     118                return m_body0;
     119        }
    102120
     121        const btCollisionObject* getBody1Internal() const
     122        {
     123                return m_body1;
     124        }
     125       
    103126};
    104127
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btSimulationIslandManager.cpp

    r5781 r8284  
     1
    12/*
    23Bullet Continuous Collision Detection and Physics Library
     
    4546       
    4647        {
     48                btOverlappingPairCache* pairCachePtr = colWorld->getPairCache();
     49                const int numOverlappingPairs = pairCachePtr->getNumOverlappingPairs();
     50                btBroadphasePair* pairPtr = pairCachePtr->getOverlappingPairArrayPtr();
    4751               
    48                 for (int i=0;i<colWorld->getPairCache()->getNumOverlappingPairs();i++)
    49                 {
    50                         btBroadphasePair* pairPtr = colWorld->getPairCache()->getOverlappingPairArrayPtr();
     52                for (int i=0;i<numOverlappingPairs;i++)
     53                {
    5154                        const btBroadphasePair& collisionPair = pairPtr[i];
    5255                        btCollisionObject* colObj0 = (btCollisionObject*)collisionPair.m_pProxy0->m_clientObject;
     
    6467}
    6568
    66 
     69#ifdef STATIC_SIMULATION_ISLAND_OPTIMIZATION
     70void   btSimulationIslandManager::updateActivationState(btCollisionWorld* colWorld,btDispatcher* dispatcher)
     71{
     72
     73        // put the index into m_controllers into m_tag   
     74        int index = 0;
     75        {
     76
     77                int i;
     78                for (i=0;i<colWorld->getCollisionObjectArray().size(); i++)
     79                {
     80                        btCollisionObject*   collisionObject= colWorld->getCollisionObjectArray()[i];
     81                        //Adding filtering here
     82                        if (!collisionObject->isStaticOrKinematicObject())
     83                        {
     84                                collisionObject->setIslandTag(index++);
     85                        }
     86                        collisionObject->setCompanionId(-1);
     87                        collisionObject->setHitFraction(btScalar(1.));
     88                }
     89        }
     90        // do the union find
     91
     92        initUnionFind( index );
     93
     94        findUnions(dispatcher,colWorld);
     95}
     96
     97void   btSimulationIslandManager::storeIslandActivationState(btCollisionWorld* colWorld)
     98{
     99        // put the islandId ('find' value) into m_tag   
     100        {
     101                int index = 0;
     102                int i;
     103                for (i=0;i<colWorld->getCollisionObjectArray().size();i++)
     104                {
     105                        btCollisionObject* collisionObject= colWorld->getCollisionObjectArray()[i];
     106                        if (!collisionObject->isStaticOrKinematicObject())
     107                        {
     108                                collisionObject->setIslandTag( m_unionFind.find(index) );
     109                                //Set the correct object offset in Collision Object Array
     110                                m_unionFind.getElement(index).m_sz = i;
     111                                collisionObject->setCompanionId(-1);
     112                                index++;
     113                        } else
     114                        {
     115                                collisionObject->setIslandTag(-1);
     116                                collisionObject->setCompanionId(-2);
     117                        }
     118                }
     119        }
     120}
     121
     122
     123#else //STATIC_SIMULATION_ISLAND_OPTIMIZATION
    67124void    btSimulationIslandManager::updateActivationState(btCollisionWorld* colWorld,btDispatcher* dispatcher)
    68125{
    69        
     126
    70127        initUnionFind( int (colWorld->getCollisionObjectArray().size()));
    71        
     128
    72129        // put the index into m_controllers into m_tag 
    73130        {
    74                
     131
    75132                int index = 0;
    76133                int i;
     
    82139                        collisionObject->setHitFraction(btScalar(1.));
    83140                        index++;
    84                        
     141
    85142                }
    86143        }
    87144        // do the union find
    88        
     145
    89146        findUnions(dispatcher,colWorld);
    90        
    91 
    92        
    93 }
    94 
    95 
    96 
     147}
    97148
    98149void    btSimulationIslandManager::storeIslandActivationState(btCollisionWorld* colWorld)
     
    100151        // put the islandId ('find' value) into m_tag   
    101152        {
    102                
    103                
     153
     154
    104155                int index = 0;
    105156                int i;
     
    120171        }
    121172}
     173
     174#endif //STATIC_SIMULATION_ISLAND_OPTIMIZATION
    122175
    123176inline  int     getIslandId(const btPersistentManifold* lhs)
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.cpp

    r5781 r8284  
    6060       
    6161        btDiscreteCollisionDetectorInterface::ClosestPointInput input;
    62         input.m_maximumDistanceSquared = btScalar(1e30);///@todo: tighter bounds
     62        input.m_maximumDistanceSquared = btScalar(BT_LARGE_FLOAT);///@todo: tighter bounds
    6363        input.m_transformA = sphereObj->getWorldTransform();
    6464        input.m_transformB = triObj->getWorldTransform();
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btUnionFind.cpp

    r5781 r8284  
    7171        {
    7272                m_elements[i].m_id = find(i);
     73#ifndef STATIC_SIMULATION_ISLAND_OPTIMIZATION
    7374                m_elements[i].m_sz = i;
     75#endif //STATIC_SIMULATION_ISLAND_OPTIMIZATION
    7476        }
    7577       
     
    7981
    8082}
    81 
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionDispatch/btUnionFind.h

    r5781 r8284  
    1919#include "LinearMath/btAlignedObjectArray.h"
    2020
    21         #define USE_PATH_COMPRESSION 1
     21#define USE_PATH_COMPRESSION 1
     22
     23///see for discussion of static island optimizations by Vroonsh here: http://code.google.com/p/bullet/issues/detail?id=406
     24#define STATIC_SIMULATION_ISLAND_OPTIMIZATION 1
    2225
    2326struct  btElement
     
    107110       
    108111                #ifdef USE_PATH_COMPRESSION
    109                                 //
    110                                 m_elements[x].m_id = m_elements[m_elements[x].m_id].m_id;
    111                 #endif //
     112                                const btElement* elementPtr = &m_elements[m_elements[x].m_id];
     113                                m_elements[x].m_id = elementPtr->m_id;
     114                                x = elementPtr->m_id;                   
     115                #else//
    112116                                x = m_elements[x].m_id;
     117                #endif         
    113118                                //btAssert(x < m_N);
    114119                                //btAssert(x >= 0);
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btBoxShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
    15 
    1615#include "btBoxShape.h"
    1716
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btBoxShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    4242        const btVector3& getHalfExtentsWithoutMargin() const
    4343        {
    44                 return m_implicitShapeDimensions;//changed in Bullet 2.63: assume the scaling and margin are included
     44                return m_implicitShapeDimensions;//scaling is included, margin is not
    4545        }
    4646       
     
    313313};
    314314
     315
    315316#endif //OBB_BOX_MINKOWSKI_H
    316317
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    1818#include "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h"
    1919#include "BulletCollision/CollisionShapes/btOptimizedBvh.h"
     20#include "LinearMath/btSerializer.h"
    2021
    2122///Bvh Concave triangle mesh is a static-triangle mesh shape with Bounding Volume Hierarchy optimization.
     
    2425:btTriangleMeshShape(meshInterface),
    2526m_bvh(0),
     27m_triangleInfoMap(0),
    2628m_useQuantizedAabbCompression(useQuantizedAabbCompression),
    2729m_ownsBvh(false)
     
    3133#ifndef DISABLE_BVH
    3234
    33         btVector3 bvhAabbMin,bvhAabbMax;
    34         if(meshInterface->hasPremadeAabb())
    35         {
    36                 meshInterface->getPremadeAabb(&bvhAabbMin, &bvhAabbMax);
    37         }
    38         else
    39         {
    40                 meshInterface->calculateAabbBruteForce(bvhAabbMin,bvhAabbMax);
    41         }
    42        
    4335        if (buildBvh)
    4436        {
    45                 void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16);
    46                 m_bvh = new (mem) btOptimizedBvh();
    47                 m_bvh->build(meshInterface,m_useQuantizedAabbCompression,bvhAabbMin,bvhAabbMax);
    48                 m_ownsBvh = true;
     37                buildOptimizedBvh();
    4938        }
    5039
     
    5645:btTriangleMeshShape(meshInterface),
    5746m_bvh(0),
     47m_triangleInfoMap(0),
    5848m_useQuantizedAabbCompression(useQuantizedAabbCompression),
    5949m_ownsBvh(false)
     
    344334   {
    345335      btTriangleMeshShape::setLocalScaling(scaling);
    346       if (m_ownsBvh)
    347       {
    348          m_bvh->~btOptimizedBvh();
    349          btAlignedFree(m_bvh);
    350       }
    351       ///m_localAabbMin/m_localAabbMax is already re-calculated in btTriangleMeshShape. We could just scale aabb, but this needs some more work
    352       void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16);
    353       m_bvh = new(mem) btOptimizedBvh();
    354       //rebuild the bvh...
    355       m_bvh->build(m_meshInterface,m_useQuantizedAabbCompression,m_localAabbMin,m_localAabbMax);
    356       m_ownsBvh = true;
     336          buildOptimizedBvh();
    357337   }
     338}
     339
     340void   btBvhTriangleMeshShape::buildOptimizedBvh()
     341{
     342        if (m_ownsBvh)
     343        {
     344                m_bvh->~btOptimizedBvh();
     345                btAlignedFree(m_bvh);
     346        }
     347        ///m_localAabbMin/m_localAabbMax is already re-calculated in btTriangleMeshShape. We could just scale aabb, but this needs some more work
     348        void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16);
     349        m_bvh = new(mem) btOptimizedBvh();
     350        //rebuild the bvh...
     351        m_bvh->build(m_meshInterface,m_useQuantizedAabbCompression,m_localAabbMin,m_localAabbMax);
     352        m_ownsBvh = true;
    358353}
    359354
     
    373368
    374369
     370
     371///fills the dataBuffer and returns the struct name (and 0 on failure)
     372const char*     btBvhTriangleMeshShape::serialize(void* dataBuffer, btSerializer* serializer) const
     373{
     374        btTriangleMeshShapeData* trimeshData = (btTriangleMeshShapeData*) dataBuffer;
     375
     376        btCollisionShape::serialize(&trimeshData->m_collisionShapeData,serializer);
     377
     378        m_meshInterface->serialize(&trimeshData->m_meshInterface, serializer);
     379
     380        trimeshData->m_collisionMargin = float(m_collisionMargin);
     381
     382       
     383
     384        if (m_bvh && !(serializer->getSerializationFlags()&BT_SERIALIZE_NO_BVH))
     385        {
     386                void* chunk = serializer->findPointer(m_bvh);
     387                if (chunk)
     388                {
     389#ifdef BT_USE_DOUBLE_PRECISION
     390                        trimeshData->m_quantizedDoubleBvh = (btQuantizedBvhData*)chunk;
     391                        trimeshData->m_quantizedFloatBvh = 0;
     392#else
     393                        trimeshData->m_quantizedFloatBvh  = (btQuantizedBvhData*)chunk;
     394                        trimeshData->m_quantizedDoubleBvh= 0;
     395#endif //BT_USE_DOUBLE_PRECISION
     396                } else
     397                {
     398
     399#ifdef BT_USE_DOUBLE_PRECISION
     400                        trimeshData->m_quantizedDoubleBvh = (btQuantizedBvhData*)serializer->getUniquePointer(m_bvh);
     401                        trimeshData->m_quantizedFloatBvh = 0;
     402#else
     403                        trimeshData->m_quantizedFloatBvh  = (btQuantizedBvhData*)serializer->getUniquePointer(m_bvh);
     404                        trimeshData->m_quantizedDoubleBvh= 0;
     405#endif //BT_USE_DOUBLE_PRECISION
     406       
     407                        int sz = m_bvh->calculateSerializeBufferSizeNew();
     408                        btChunk* chunk = serializer->allocate(sz,1);
     409                        const char* structType = m_bvh->serialize(chunk->m_oldPtr, serializer);
     410                        serializer->finalizeChunk(chunk,structType,BT_QUANTIZED_BVH_CODE,m_bvh);
     411                }
     412        } else
     413        {
     414                trimeshData->m_quantizedFloatBvh = 0;
     415                trimeshData->m_quantizedDoubleBvh = 0;
     416        }
     417
     418       
     419
     420        if (m_triangleInfoMap && !(serializer->getSerializationFlags()&BT_SERIALIZE_NO_TRIANGLEINFOMAP))
     421        {
     422                void* chunk = serializer->findPointer(m_triangleInfoMap);
     423                if (chunk)
     424                {
     425                        trimeshData->m_triangleInfoMap = (btTriangleInfoMapData*)chunk;
     426                } else
     427                {
     428                        trimeshData->m_triangleInfoMap = (btTriangleInfoMapData*)serializer->getUniquePointer(m_triangleInfoMap);
     429                        int sz = m_triangleInfoMap->calculateSerializeBufferSize();
     430                        btChunk* chunk = serializer->allocate(sz,1);
     431                        const char* structType = m_triangleInfoMap->serialize(chunk->m_oldPtr, serializer);
     432                        serializer->finalizeChunk(chunk,structType,BT_TRIANLGE_INFO_MAP,m_triangleInfoMap);
     433                }
     434        } else
     435        {
     436                trimeshData->m_triangleInfoMap = 0;
     437        }
     438
     439        return "btTriangleMeshShapeData";
     440}
     441
     442void    btBvhTriangleMeshShape::serializeSingleBvh(btSerializer* serializer) const
     443{
     444        if (m_bvh)
     445        {
     446                int len = m_bvh->calculateSerializeBufferSizeNew(); //make sure not to use calculateSerializeBufferSize because it is used for in-place
     447                btChunk* chunk = serializer->allocate(len,1);
     448                const char* structType = m_bvh->serialize(chunk->m_oldPtr, serializer);
     449                serializer->finalizeChunk(chunk,structType,BT_QUANTIZED_BVH_CODE,(void*)m_bvh);
     450        }
     451}
     452
     453void    btBvhTriangleMeshShape::serializeSingleTriangleInfoMap(btSerializer* serializer) const
     454{
     455        if (m_triangleInfoMap)
     456        {
     457                int len = m_triangleInfoMap->calculateSerializeBufferSize();
     458                btChunk* chunk = serializer->allocate(len,1);
     459                const char* structType = m_triangleInfoMap->serialize(chunk->m_oldPtr, serializer);
     460                serializer->finalizeChunk(chunk,structType,BT_TRIANLGE_INFO_MAP,(void*)m_triangleInfoMap);
     461        }
     462}
     463
     464
     465
     466
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2020#include "btOptimizedBvh.h"
    2121#include "LinearMath/btAlignedAllocator.h"
    22 
     22#include "btTriangleInfoMap.h"
    2323
    2424///The btBvhTriangleMeshShape is a static-triangle mesh shape with several optimizations, such as bounding volume hierarchy and cache friendly traversal for PlayStation 3 Cell SPU. It is recommended to enable useQuantizedAabbCompression for better memory usage.
     
    3030
    3131        btOptimizedBvh* m_bvh;
     32        btTriangleInfoMap*      m_triangleInfoMap;
     33
    3234        bool m_useQuantizedAabbCompression;
    3335        bool m_ownsBvh;
     
    3840        BT_DECLARE_ALIGNED_ALLOCATOR();
    3941
    40         btBvhTriangleMeshShape() : btTriangleMeshShape(0),m_bvh(0),m_ownsBvh(false) {m_shapeType = TRIANGLE_MESH_SHAPE_PROXYTYPE;};
     42        btBvhTriangleMeshShape() : btTriangleMeshShape(0),m_bvh(0),m_triangleInfoMap(0),m_ownsBvh(false) {m_shapeType = TRIANGLE_MESH_SHAPE_PROXYTYPE;};
    4143        btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression, bool buildBvh = true);
    4244
     
    7476        }
    7577
     78        void    setOptimizedBvh(btOptimizedBvh* bvh, const btVector3& localScaling=btVector3(1,1,1));
    7679
    77         void    setOptimizedBvh(btOptimizedBvh* bvh, const btVector3& localScaling=btVector3(1,1,1));
     80        void    buildOptimizedBvh();
    7881
    7982        bool    usesQuantizedAabbCompression() const
     
    8184                return  m_useQuantizedAabbCompression;
    8285        }
     86
     87        void    setTriangleInfoMap(btTriangleInfoMap* triangleInfoMap)
     88        {
     89                m_triangleInfoMap = triangleInfoMap;
     90        }
     91
     92        const btTriangleInfoMap*        getTriangleInfoMap() const
     93        {
     94                return m_triangleInfoMap;
     95        }
     96       
     97        btTriangleInfoMap*      getTriangleInfoMap()
     98        {
     99                return m_triangleInfoMap;
     100        }
     101
     102        virtual int     calculateSerializeBufferSize() const;
     103
     104        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     105        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     106
     107        virtual void    serializeSingleBvh(btSerializer* serializer) const;
     108
     109        virtual void    serializeSingleTriangleInfoMap(btSerializer* serializer) const;
     110
     111};
     112
     113///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     114struct  btTriangleMeshShapeData
     115{
     116        btCollisionShapeData    m_collisionShapeData;
     117
     118        btStridingMeshInterfaceData m_meshInterface;
     119
     120        btQuantizedBvhFloatData         *m_quantizedFloatBvh;
     121        btQuantizedBvhDoubleData        *m_quantizedDoubleBvh;
     122
     123        btTriangleInfoMapData   *m_triangleInfoMap;
     124       
     125        float   m_collisionMargin;
     126
     127        char m_pad3[4];
     128       
     129};
     130
     131
     132SIMD_FORCE_INLINE       int     btBvhTriangleMeshShape::calculateSerializeBufferSize() const
     133{
     134        return sizeof(btTriangleMeshShapeData);
    83135}
    84 ;
     136
     137
    85138
    86139#endif //BVH_TRIANGLE_MESH_SHAPE_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btCapsuleShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    3333        btVector3 supVec(0,0,0);
    3434
    35         btScalar maxDot(btScalar(-1e30));
     35        btScalar maxDot(btScalar(-BT_LARGE_FLOAT));
    3636
    3737        btVector3 vec = vec0;
     
    8989        for (int j=0;j<numVectors;j++)
    9090        {
    91                 btScalar maxDot(btScalar(-1e30));
     91                btScalar maxDot(btScalar(-BT_LARGE_FLOAT));
    9292                const btVector3& vec = vectors[j];
    9393
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btCapsuleShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    4444        virtual void    batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
    4545       
     46        virtual void setMargin(btScalar collisionMargin)
     47        {
     48                //correct the m_implicitShapeDimensions for the margin
     49                btVector3 oldMargin(getMargin(),getMargin(),getMargin());
     50                btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions+oldMargin;
     51               
     52                btConvexInternalShape::setMargin(collisionMargin);
     53                btVector3 newMargin(getMargin(),getMargin(),getMargin());
     54                m_implicitShapeDimensions = implicitShapeDimensionsWithMargin - newMargin;
     55
     56        }
     57
    4658        virtual void getAabb (const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const
    4759        {
     
    7789                return m_implicitShapeDimensions[m_upAxis];
    7890        }
     91
     92        virtual void    setLocalScaling(const btVector3& scaling)
     93        {
     94                btVector3 oldMargin(getMargin(),getMargin(),getMargin());
     95                btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions+oldMargin;
     96                btVector3 unScaledImplicitShapeDimensionsWithMargin = implicitShapeDimensionsWithMargin / m_localScaling;
     97
     98                btConvexInternalShape::setLocalScaling(scaling);
     99
     100                m_implicitShapeDimensions = (unScaledImplicitShapeDimensionsWithMargin * m_localScaling) - oldMargin;
     101
     102        }
     103
     104        virtual int     calculateSerializeBufferSize() const;
     105
     106        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     107        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     108
    79109
    80110};
     
    114144};
    115145
     146///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     147struct  btCapsuleShapeData
     148{
     149        btConvexInternalShapeData       m_convexInternalShapeData;
    116150
     151        int     m_upAxis;
     152
     153        char    m_padding[4];
     154};
     155
     156SIMD_FORCE_INLINE       int     btCapsuleShape::calculateSerializeBufferSize() const
     157{
     158        return sizeof(btCapsuleShapeData);
     159}
     160
     161        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     162SIMD_FORCE_INLINE       const char*     btCapsuleShape::serialize(void* dataBuffer, btSerializer* serializer) const
     163{
     164        btCapsuleShapeData* shapeData = (btCapsuleShapeData*) dataBuffer;
     165       
     166        btConvexInternalShape::serialize(&shapeData->m_convexInternalShapeData,serializer);
     167
     168        shapeData->m_upAxis = m_upAxis;
     169       
     170        return "btCapsuleShapeData";
     171}
    117172
    118173#endif //BT_CAPSULE_SHAPE_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btCollisionMargin.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btCollisionShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
    15 
    1615#include "BulletCollision/CollisionShapes/btCollisionShape.h"
    17 
    18 
    19 btScalar gContactThresholdFactor=btScalar(0.02);
    20 
     16#include "LinearMath/btSerializer.h"
    2117
    2218/*
     
    4642}
    4743
    48 btScalar        btCollisionShape::getContactBreakingThreshold() const
     44
     45btScalar        btCollisionShape::getContactBreakingThreshold(btScalar defaultContactThreshold) const
    4946{
    50         return getAngularMotionDisc() * gContactThresholdFactor;
     47        return getAngularMotionDisc() * defaultContactThreshold;
    5148}
     49
    5250btScalar        btCollisionShape::getAngularMotionDisc() const
    5351{
     
    9795        temporalAabbMax += angularMotion3d;
    9896}
     97
     98///fills the dataBuffer and returns the struct name (and 0 on failure)
     99const char*     btCollisionShape::serialize(void* dataBuffer, btSerializer* serializer) const
     100{
     101        btCollisionShapeData* shapeData = (btCollisionShapeData*) dataBuffer;
     102        char* name = (char*) serializer->findNameForPointer(this);
     103        shapeData->m_name = (char*)serializer->getUniquePointer(name);
     104        if (shapeData->m_name)
     105        {
     106                serializer->serializeName(name);
     107        }
     108        shapeData->m_shapeType = m_shapeType;
     109        //shapeData->m_padding//??
     110        return "btCollisionShapeData";
     111}
     112
     113void    btCollisionShape::serializeSingleShape(btSerializer* serializer) const
     114{
     115        int len = calculateSerializeBufferSize();
     116        btChunk* chunk = serializer->allocate(len,1);
     117        const char* structType = serialize(chunk->m_oldPtr, serializer);
     118        serializer->finalizeChunk(chunk,structType,BT_SHAPE_CODE,(void*)this);
     119}
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btCollisionShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2121#include "LinearMath/btMatrix3x3.h"
    2222#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" //for the shape types
     23class btSerializer;
     24
    2325
    2426///The btCollisionShape class provides an interface for collision shapes that can be shared among btCollisionObjects.
     
    4749        virtual btScalar        getAngularMotionDisc() const;
    4850
    49         virtual btScalar        getContactBreakingThreshold() const;
     51        virtual btScalar        getContactBreakingThreshold(btScalar defaultContactThresholdFactor) const;
    5052
    5153
     
    5456        void calculateTemporalAabb(const btTransform& curTrans,const btVector3& linvel,const btVector3& angvel,btScalar timeStep, btVector3& temporalAabbMin,btVector3& temporalAabbMax) const;
    5557
    56 #ifndef __SPU__
     58
    5759
    5860        SIMD_FORCE_INLINE bool  isPolyhedral() const
     
    6163        }
    6264
     65        SIMD_FORCE_INLINE bool  isConvex2d() const
     66        {
     67                return btBroadphaseProxy::isConvex2d(getShapeType());
     68        }
     69
    6370        SIMD_FORCE_INLINE bool  isConvex() const
    6471        {
    6572                return btBroadphaseProxy::isConvex(getShapeType());
     73        }
     74        SIMD_FORCE_INLINE bool  isNonMoving() const
     75        {
     76                return btBroadphaseProxy::isNonMoving(getShapeType());
    6677        }
    6778        SIMD_FORCE_INLINE bool  isConcave() const
     
    7485        }
    7586
     87        SIMD_FORCE_INLINE bool  isSoftBody() const
     88        {
     89                return btBroadphaseProxy::isSoftBody(getShapeType());
     90        }
     91
    7692        ///isInfinite is used to catch simulation error (aabb check)
    7793        SIMD_FORCE_INLINE bool isInfinite() const
     
    8096        }
    8197
    82        
     98#ifndef __SPU__
    8399        virtual void    setLocalScaling(const btVector3& scaling) =0;
    84100        virtual const btVector3& getLocalScaling() const =0;
     
    107123        }
    108124
     125        virtual int     calculateSerializeBufferSize() const;
     126
     127        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     128        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     129
     130        virtual void    serializeSingleShape(btSerializer* serializer) const;
     131
    109132};     
     133
     134///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     135struct  btCollisionShapeData
     136{
     137        char    *m_name;
     138        int             m_shapeType;
     139        char    m_padding[4];
     140};
     141
     142SIMD_FORCE_INLINE       int     btCollisionShape::calculateSerializeBufferSize() const
     143{
     144        return sizeof(btCollisionShapeData);
     145}
     146
     147
    110148
    111149#endif //COLLISION_SHAPE_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btCompoundShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    1717#include "btCollisionShape.h"
    1818#include "BulletCollision/BroadphaseCollision/btDbvt.h"
     19#include "LinearMath/btSerializer.h"
    1920
    2021btCompoundShape::btCompoundShape(bool enableDynamicAabbTree)
    21 : m_localAabbMin(btScalar(1e30),btScalar(1e30),btScalar(1e30)),
    22 m_localAabbMax(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30)),
     22: m_localAabbMin(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT)),
     23m_localAabbMax(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT)),
     24m_dynamicAabbTree(0),
     25m_updateRevision(1),
    2326m_collisionMargin(btScalar(0.)),
    24 m_localScaling(btScalar(1.),btScalar(1.),btScalar(1.)),
    25 m_dynamicAabbTree(0),
    26 m_updateRevision(1)
     27m_localScaling(btScalar(1.),btScalar(1.),btScalar(1.))
    2728{
    2829        m_shapeType = COMPOUND_SHAPE_PROXYTYPE;
     
    5253        //m_childShapes.push_back(shape);
    5354        btCompoundShapeChild child;
     55        child.m_node = 0;
    5456        child.m_transform = localTransform;
    5557        child.m_childShape = shape;
     
    9496                m_children[childIndex].m_childShape->getAabb(newChildTransform,localAabbMin,localAabbMax);
    9597                ATTRIBUTE_ALIGNED16(btDbvtVolume)       bounds=btDbvtVolume::FromMM(localAabbMin,localAabbMax);
    96                 int index = m_children.size()-1;
     98                //int index = m_children.size()-1;
    9799                m_dynamicAabbTree->update(m_children[childIndex].m_node,bounds);
    98100        }
     
    110112        }
    111113        m_children.swap(childShapeIndex,m_children.size()-1);
     114    if (m_dynamicAabbTree)
     115                m_children[childShapeIndex].m_node->dataAsInt = childShapeIndex;
    112116        m_children.pop_back();
    113117
     
    125129                if(m_children[i].m_childShape == shape)
    126130                {
    127                         m_children.swap(i,m_children.size()-1);
    128                         m_children.pop_back();
    129                         //remove it from the m_dynamicAabbTree too
    130                         //@todo: this leads to problems due to caching in the btCompoundCollisionAlgorithm
    131                         //so effectively, removeChildShape is broken at the moment
    132                         //m_dynamicAabbTree->remove(m_aabbProxies[i]);
    133                         //m_aabbProxies.swap(i,m_children.size()-1);
    134                         //m_aabbProxies.pop_back();
     131                        removeChildShapeByIndex(i);
    135132                }
    136133        }
     
    146143        // Brute force, it iterates over all the shapes left.
    147144
    148         m_localAabbMin = btVector3(btScalar(1e30),btScalar(1e30),btScalar(1e30));
    149         m_localAabbMax = btVector3(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
     145        m_localAabbMin = btVector3(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
     146        m_localAabbMax = btVector3(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
    150147
    151148        //extend the local aabbMin/aabbMax
     
    224221        for (k = 0; k < n; k++)
    225222        {
     223                btAssert(masses[k]>0);
    226224                center += m_children[k].m_transform.getOrigin() * masses[k];
    227225                totalMass += masses[k];
    228226        }
     227
     228        btAssert(totalMass>0);
     229
    229230        center /= totalMass;
    230231        principal.setOrigin(center);
     
    272273
    273274
     275void btCompoundShape::setLocalScaling(const btVector3& scaling)
     276{
     277
     278        for(int i = 0; i < m_children.size(); i++)
     279        {
     280                btTransform childTrans = getChildTransform(i);
     281                btVector3 childScale = m_children[i].m_childShape->getLocalScaling();
     282//              childScale = childScale * (childTrans.getBasis() * scaling);
     283                childScale = childScale * scaling / m_localScaling;
     284                m_children[i].m_childShape->setLocalScaling(childScale);
     285                childTrans.setOrigin((childTrans.getOrigin())*scaling);
     286                updateChildTransform(i, childTrans);
     287                recalculateLocalAabb();
     288        }
     289        m_localScaling = scaling;
     290}
     291
     292
     293void btCompoundShape::createAabbTreeFromChildren()
     294{
     295    if ( !m_dynamicAabbTree )
     296    {
     297        void* mem = btAlignedAlloc(sizeof(btDbvt),16);
     298        m_dynamicAabbTree = new(mem) btDbvt();
     299        btAssert(mem==m_dynamicAabbTree);
     300
     301        for ( int index = 0; index < m_children.size(); index++ )
     302        {
     303            btCompoundShapeChild &child = m_children[index];
     304
     305            //extend the local aabbMin/aabbMax
     306            btVector3 localAabbMin,localAabbMax;
     307            child.m_childShape->getAabb(child.m_transform,localAabbMin,localAabbMax);
     308
     309            const btDbvtVolume  bounds=btDbvtVolume::FromMM(localAabbMin,localAabbMax);
     310            child.m_node = m_dynamicAabbTree->insert(bounds,(void*)index);
     311        }
     312    }
     313}
     314
     315
     316///fills the dataBuffer and returns the struct name (and 0 on failure)
     317const char*     btCompoundShape::serialize(void* dataBuffer, btSerializer* serializer) const
     318{
     319
     320        btCompoundShapeData* shapeData = (btCompoundShapeData*) dataBuffer;
     321        btCollisionShape::serialize(&shapeData->m_collisionShapeData, serializer);
     322
     323        shapeData->m_collisionMargin = float(m_collisionMargin);
     324        shapeData->m_numChildShapes = m_children.size();
     325        shapeData->m_childShapePtr = 0;
     326        if (shapeData->m_numChildShapes)
     327        {
     328                btChunk* chunk = serializer->allocate(sizeof(btCompoundShapeChildData),shapeData->m_numChildShapes);
     329                btCompoundShapeChildData* memPtr = (btCompoundShapeChildData*)chunk->m_oldPtr;
     330                shapeData->m_childShapePtr = (btCompoundShapeChildData*)serializer->getUniquePointer(memPtr);
     331
     332                for (int i=0;i<shapeData->m_numChildShapes;i++,memPtr++)
     333                {
     334                        memPtr->m_childMargin = float(m_children[i].m_childMargin);
     335                        memPtr->m_childShape = (btCollisionShapeData*)serializer->getUniquePointer(m_children[i].m_childShape);
     336                        //don't serialize shapes that already have been serialized
     337                        if (!serializer->findPointer(m_children[i].m_childShape))
     338                        {
     339                                btChunk* chunk = serializer->allocate(m_children[i].m_childShape->calculateSerializeBufferSize(),1);
     340                                const char* structType = m_children[i].m_childShape->serialize(chunk->m_oldPtr,serializer);
     341                                serializer->finalizeChunk(chunk,structType,BT_SHAPE_CODE,m_children[i].m_childShape);
     342                        }
     343
     344                        memPtr->m_childShapeType = m_children[i].m_childShapeType;
     345                        m_children[i].m_transform.serializeFloat(memPtr->m_transform);
     346                }
     347                serializer->finalizeChunk(chunk,"btCompoundShapeChildData",BT_ARRAY_CODE,chunk->m_oldPtr);
     348        }
     349        return "btCompoundShapeData";
     350}
     351
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btCompoundShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    6363        int                                                             m_updateRevision;
    6464
     65        btScalar        m_collisionMargin;
     66
     67protected:
     68        btVector3       m_localScaling;
     69
    6570public:
    6671        BT_DECLARE_ALIGNED_ALLOCATOR();
     
    117122        virtual void recalculateLocalAabb();
    118123
    119         virtual void    setLocalScaling(const btVector3& scaling)
    120         {
    121                 m_localScaling = scaling;
    122         }
     124        virtual void    setLocalScaling(const btVector3& scaling);
     125
    123126        virtual const btVector3& getLocalScaling() const
    124127        {
     
    141144        }
    142145
    143         //this is optional, but should make collision queries faster, by culling non-overlapping nodes
    144         void    createAabbTreeFromChildren();
    145146
    146147        btDbvt*                                                 getDynamicAabbTree()
     
    148149                return m_dynamicAabbTree;
    149150        }
     151
     152        void createAabbTreeFromChildren();
    150153
    151154        ///computes the exact moment of inertia and the transform from the coordinate system defined by the principal axes of the moment of inertia
     
    161164        }
    162165
    163 private:
    164         btScalar        m_collisionMargin;
    165 protected:
    166         btVector3       m_localScaling;
    167 
    168 };
     166        virtual int     calculateSerializeBufferSize() const;
     167
     168        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     169        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     170
     171
     172};
     173
     174///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     175struct btCompoundShapeChildData
     176{
     177        btTransformFloatData    m_transform;
     178        btCollisionShapeData    *m_childShape;
     179        int                                             m_childShapeType;
     180        float                                   m_childMargin;
     181};
     182
     183///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     184struct  btCompoundShapeData
     185{
     186        btCollisionShapeData            m_collisionShapeData;
     187
     188        btCompoundShapeChildData        *m_childShapePtr;
     189
     190        int                                                     m_numChildShapes;
     191
     192        float   m_collisionMargin;
     193
     194};
     195
     196
     197SIMD_FORCE_INLINE       int     btCompoundShape::calculateSerializeBufferSize() const
     198{
     199        return sizeof(btCompoundShapeData);
     200}
     201
     202
     203
     204
    169205
    170206
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConcaveShape.cpp

    r5781 r8284  
    1 
    21/*
    32Bullet Continuous Collision Detection and Physics Library
    4 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    54
    65This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConcaveShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConeShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConeShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexHullShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516#include "btConvexHullShape.h"
    1617#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
    1718
    1819#include "LinearMath/btQuaternion.h"
    19 
    20 
    21 
    22 btConvexHullShape ::btConvexHullShape (const btScalar* points,int numPoints,int stride) : btPolyhedralConvexShape ()
     20#include "LinearMath/btSerializer.h"
     21
     22btConvexHullShape ::btConvexHullShape (const btScalar* points,int numPoints,int stride) : btPolyhedralConvexAabbCachingShape ()
    2323{
    2424        m_shapeType = CONVEX_HULL_SHAPE_PROXYTYPE;
    2525        m_unscaledPoints.resize(numPoints);
    2626
    27         unsigned char* pointsBaseAddress = (unsigned char*)points;
     27        unsigned char* pointsAddress = (unsigned char*)points;
    2828
    2929        for (int i=0;i<numPoints;i++)
    3030        {
    31                 btVector3* point = (btVector3*)(pointsBaseAddress + i*stride);
    32                 m_unscaledPoints[i] = point[0];
     31                btScalar* point = (btScalar*)pointsAddress;
     32                m_unscaledPoints[i] = btVector3(point[0], point[1], point[2]);
     33                pointsAddress += stride;
    3334        }
    3435
     
    5253}
    5354
    54 btVector3       btConvexHullShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
     55btVector3       btConvexHullShape::localGetSupportingVertexWithoutMargin(const btVector3& vec)const
    5556{
    5657        btVector3 supVec(btScalar(0.),btScalar(0.),btScalar(0.));
    57         btScalar newDot,maxDot = btScalar(-1e30);
    58 
    59         btVector3 vec = vec0;
    60         btScalar lenSqr = vec.length2();
    61         if (lenSqr < btScalar(0.0001))
    62         {
    63                 vec.setValue(1,0,0);
    64         } else
    65         {
    66                 btScalar rlen = btScalar(1.) / btSqrt(lenSqr );
    67                 vec *= rlen;
    68         }
    69 
     58        btScalar newDot,maxDot = btScalar(-BT_LARGE_FLOAT);
    7059
    7160        for (int i=0;i<m_unscaledPoints.size();i++)
     
    9079                for (int i=0;i<numVectors;i++)
    9180                {
    92                         supportVerticesOut[i][3] = btScalar(-1e30);
     81                        supportVerticesOut[i][3] = btScalar(-BT_LARGE_FLOAT);
    9382                }
    9483        }
     
    186175}
    187176
     177///fills the dataBuffer and returns the struct name (and 0 on failure)
     178const char*     btConvexHullShape::serialize(void* dataBuffer, btSerializer* serializer) const
     179{
     180        //int szc = sizeof(btConvexHullShapeData);
     181        btConvexHullShapeData* shapeData = (btConvexHullShapeData*) dataBuffer;
     182        btConvexInternalShape::serialize(&shapeData->m_convexInternalShapeData, serializer);
     183
     184        int numElem = m_unscaledPoints.size();
     185        shapeData->m_numUnscaledPoints = numElem;
     186#ifdef BT_USE_DOUBLE_PRECISION
     187        shapeData->m_unscaledPointsFloatPtr = 0;
     188        shapeData->m_unscaledPointsDoublePtr = numElem ? (btVector3Data*)serializer->getUniquePointer((void*)&m_unscaledPoints[0]):  0;
     189#else
     190        shapeData->m_unscaledPointsFloatPtr = numElem ? (btVector3Data*)serializer->getUniquePointer((void*)&m_unscaledPoints[0]):  0;
     191        shapeData->m_unscaledPointsDoublePtr = 0;
     192#endif
     193       
     194        if (numElem)
     195        {
     196                int sz = sizeof(btVector3Data);
     197        //      int sz2 = sizeof(btVector3DoubleData);
     198        //      int sz3 = sizeof(btVector3FloatData);
     199                btChunk* chunk = serializer->allocate(sz,numElem);
     200                btVector3Data* memPtr = (btVector3Data*)chunk->m_oldPtr;
     201                for (int i=0;i<numElem;i++,memPtr++)
     202                {
     203                        m_unscaledPoints[i].serialize(*memPtr);
     204                }
     205                serializer->finalizeChunk(chunk,btVector3DataName,BT_ARRAY_CODE,(void*)&m_unscaledPoints[0]);
     206        }
     207       
     208        return "btConvexHullShapeData";
     209}
     210
     211
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexHullShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2121#include "LinearMath/btAlignedObjectArray.h"
    2222
     23
    2324///The btConvexHullShape implements an implicit convex hull of an array of vertices.
    2425///Bullet provides a general and fast collision detector for convex shapes based on GJK and EPA using localGetSupportingVertex.
    25 ATTRIBUTE_ALIGNED16(class) btConvexHullShape : public btPolyhedralConvexShape
     26ATTRIBUTE_ALIGNED16(class) btConvexHullShape : public btPolyhedralConvexAabbCachingShape
    2627{
    2728        btAlignedObjectArray<btVector3> m_unscaledPoints;
     
    8990        virtual void    setLocalScaling(const btVector3& scaling);
    9091
     92        virtual int     calculateSerializeBufferSize() const;
     93
     94        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     95        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     96
    9197};
     98
     99///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     100struct  btConvexHullShapeData
     101{
     102        btConvexInternalShapeData       m_convexInternalShapeData;
     103
     104        btVector3FloatData      *m_unscaledPointsFloatPtr;
     105        btVector3DoubleData     *m_unscaledPointsDoublePtr;
     106
     107        int             m_numUnscaledPoints;
     108        char m_padding3[4];
     109
     110};
     111
     112
     113SIMD_FORCE_INLINE       int     btConvexHullShape::calculateSerializeBufferSize() const
     114{
     115        return sizeof(btConvexHullShapeData);
     116}
    92117
    93118
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexInternalShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    3535void    btConvexInternalShape::getAabbSlow(const btTransform& trans,btVector3&minAabb,btVector3&maxAabb) const
    3636{
    37 
     37#ifndef __SPU__
     38        //use localGetSupportingVertexWithoutMargin?
    3839        btScalar margin = getMargin();
    3940        for (int i=0;i<3;i++)
     
    5051                minAabb[i] = tmp[i]-margin;
    5152        }
     53#endif
    5254}
    5355
     
    8082
    8183
     84btConvexInternalAabbCachingShape::btConvexInternalAabbCachingShape()
     85        :       btConvexInternalShape(),
     86m_localAabbMin(1,1,1),
     87m_localAabbMax(-1,-1,-1),
     88m_isLocalAabbValid(false)
     89{
     90}
     91
     92
     93void btConvexInternalAabbCachingShape::getAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax) const
     94{
     95        getNonvirtualAabb(trans,aabbMin,aabbMax,getMargin());
     96}
     97
     98void    btConvexInternalAabbCachingShape::setLocalScaling(const btVector3& scaling)
     99{
     100        btConvexInternalShape::setLocalScaling(scaling);
     101        recalcLocalAabb();
     102}
     103
     104
     105void    btConvexInternalAabbCachingShape::recalcLocalAabb()
     106{
     107        m_isLocalAabbValid = true;
     108       
     109        #if 1
     110        static const btVector3 _directions[] =
     111        {
     112                btVector3( 1.,  0.,  0.),
     113                btVector3( 0.,  1.,  0.),
     114                btVector3( 0.,  0.,  1.),
     115                btVector3( -1., 0.,  0.),
     116                btVector3( 0., -1.,  0.),
     117                btVector3( 0.,  0., -1.)
     118        };
     119       
     120        btVector3 _supporting[] =
     121        {
     122                btVector3( 0., 0., 0.),
     123                btVector3( 0., 0., 0.),
     124                btVector3( 0., 0., 0.),
     125                btVector3( 0., 0., 0.),
     126                btVector3( 0., 0., 0.),
     127                btVector3( 0., 0., 0.)
     128        };
     129       
     130        batchedUnitVectorGetSupportingVertexWithoutMargin(_directions, _supporting, 6);
     131       
     132        for ( int i = 0; i < 3; ++i )
     133        {
     134                m_localAabbMax[i] = _supporting[i][i] + m_collisionMargin;
     135                m_localAabbMin[i] = _supporting[i + 3][i] - m_collisionMargin;
     136        }
     137       
     138        #else
     139
     140        for (int i=0;i<3;i++)
     141        {
     142                btVector3 vec(btScalar(0.),btScalar(0.),btScalar(0.));
     143                vec[i] = btScalar(1.);
     144                btVector3 tmp = localGetSupportingVertex(vec);
     145                m_localAabbMax[i] = tmp[i]+m_collisionMargin;
     146                vec[i] = btScalar(-1.);
     147                tmp = localGetSupportingVertex(vec);
     148                m_localAabbMin[i] = tmp[i]-m_collisionMargin;
     149        }
     150        #endif
     151}
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexInternalShape.h

    r5781 r8284  
     1/*
     2Bullet Continuous Collision Detection and Physics Library
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
     4
     5This software is provided 'as-is', without any express or implied warranty.
     6In no event will the authors be held liable for any damages arising from the use of this software.
     7Permission is granted to anyone to use this software for any purpose,
     8including commercial applications, and to alter it and redistribute it freely,
     9subject to the following restrictions:
     10
     111. 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.
     122. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
     133. This notice may not be removed or altered from any source distribution.
     14*/
    115
    216#ifndef BT_CONVEX_INTERNAL_SHAPE_H
     
    418
    519#include "btConvexShape.h"
     20#include "LinearMath/btAabbUtil2.h"
     21
    622
    723///The btConvexInternalShape is an internal base class, shared by most convex shape implementations.
     
    3652        {
    3753                return m_implicitShapeDimensions;
     54        }
     55
     56        ///warning: use setImplicitShapeDimensions with care
     57        ///changing a collision shape while the body is in the world is not recommended,
     58        ///it is best to remove the body from the world, then make the change, and re-add it
     59        ///alternatively flush the contact points, see documentation for 'cleanProxyFromPairs'
     60        void    setImplicitShapeDimensions(const btVector3& dimensions)
     61        {
     62                m_implicitShapeDimensions = dimensions;
    3863        }
    3964
     
    86111        }
    87112
     113        virtual int     calculateSerializeBufferSize() const;
     114
     115        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     116        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
    88117
    89118       
    90119};
    91120
     121///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     122struct  btConvexInternalShapeData
     123{
     124        btCollisionShapeData    m_collisionShapeData;
     125
     126        btVector3FloatData      m_localScaling;
     127
     128        btVector3FloatData      m_implicitShapeDimensions;
     129       
     130        float                   m_collisionMargin;
     131
     132        int     m_padding;
     133
     134};
     135
     136
     137
     138SIMD_FORCE_INLINE       int     btConvexInternalShape::calculateSerializeBufferSize() const
     139{
     140        return sizeof(btConvexInternalShapeData);
     141}
     142
     143///fills the dataBuffer and returns the struct name (and 0 on failure)
     144SIMD_FORCE_INLINE       const char*     btConvexInternalShape::serialize(void* dataBuffer, btSerializer* serializer) const
     145{
     146        btConvexInternalShapeData* shapeData = (btConvexInternalShapeData*) dataBuffer;
     147        btCollisionShape::serialize(&shapeData->m_collisionShapeData, serializer);
     148
     149        m_implicitShapeDimensions.serializeFloat(shapeData->m_implicitShapeDimensions);
     150        m_localScaling.serializeFloat(shapeData->m_localScaling);
     151        shapeData->m_collisionMargin = float(m_collisionMargin);
     152
     153        return "btConvexInternalShapeData";
     154}
     155
     156
     157
     158
     159///btConvexInternalAabbCachingShape adds local aabb caching for convex shapes, to avoid expensive bounding box calculations
     160class btConvexInternalAabbCachingShape : public btConvexInternalShape
     161{
     162        btVector3       m_localAabbMin;
     163        btVector3       m_localAabbMax;
     164        bool            m_isLocalAabbValid;
     165       
     166protected:
     167                                       
     168        btConvexInternalAabbCachingShape();
     169       
     170        void setCachedLocalAabb (const btVector3& aabbMin, const btVector3& aabbMax)
     171        {
     172                m_isLocalAabbValid = true;
     173                m_localAabbMin = aabbMin;
     174                m_localAabbMax = aabbMax;
     175        }
     176
     177        inline void getCachedLocalAabb (btVector3& aabbMin, btVector3& aabbMax) const
     178        {
     179                btAssert(m_isLocalAabbValid);
     180                aabbMin = m_localAabbMin;
     181                aabbMax = m_localAabbMax;
     182        }
     183
     184        inline void getNonvirtualAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax, btScalar margin) const
     185        {
     186
     187                //lazy evaluation of local aabb
     188                btAssert(m_isLocalAabbValid);
     189                btTransformAabb(m_localAabbMin,m_localAabbMax,margin,trans,aabbMin,aabbMax);
     190        }
     191               
     192public:
     193               
     194        virtual void    setLocalScaling(const btVector3& scaling);
     195
     196        virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
     197
     198        void    recalcLocalAabb();
     199
     200};
    92201
    93202#endif //BT_CONVEX_INTERNAL_SHAPE_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexPointCloudShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516#include "btConvexPointCloudShape.h"
    1617#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
     
    2829{
    2930        btVector3 supVec(btScalar(0.),btScalar(0.),btScalar(0.));
    30         btScalar newDot,maxDot = btScalar(-1e30);
     31        btScalar newDot,maxDot = btScalar(-BT_LARGE_FLOAT);
    3132
    3233        btVector3 vec = vec0;
     
    6364                for (int i=0;i<numVectors;i++)
    6465                {
    65                         supportVerticesOut[i][3] = btScalar(-1e30);
     66                        supportVerticesOut[i][3] = btScalar(-BT_LARGE_FLOAT);
    6667                }
    6768        }
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexPointCloudShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2222
    2323///The btConvexPointCloudShape implements an implicit convex hull of an array of vertices.
    24 ATTRIBUTE_ALIGNED16(class) btConvexPointCloudShape : public btPolyhedralConvexShape
     24ATTRIBUTE_ALIGNED16(class) btConvexPointCloudShape : public btPolyhedralConvexAabbCachingShape
    2525{
    2626        btVector3* m_unscaledPoints;
     
    2929public:
    3030        BT_DECLARE_ALIGNED_ALLOCATOR();
     31
     32        btConvexPointCloudShape()
     33        {
     34                m_localScaling.setValue(1.f,1.f,1.f);
     35                m_shapeType = CONVEX_POINT_CLOUD_SHAPE_PROXYTYPE;
     36                m_unscaledPoints = 0;
     37                m_numPoints = 0;
     38        }
    3139
    3240        btConvexPointCloudShape(btVector3* points,int numPoints, const btVector3& localScaling,bool computeAabb = true)
     
    4149        }
    4250
    43         void setPoints (btVector3* points, int numPoints, bool computeAabb = true)
     51        void setPoints (btVector3* points, int numPoints, bool computeAabb = true,const btVector3& localScaling=btVector3(1.f,1.f,1.f))
    4452        {
    4553                m_unscaledPoints = points;
    4654                m_numPoints = numPoints;
     55                m_localScaling = localScaling;
    4756
    4857                if (computeAabb)
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2222#include "btConvexPointCloudShape.h"
    2323
     24///not supported on IBM SDK, until we fix the alignment of btVector3
     25#if defined (__CELLOS_LV2__) && defined (__SPU__)
     26#include <spu_intrinsics.h>
     27static inline vec_float4 vec_dot3( vec_float4 vec0, vec_float4 vec1 )
     28{
     29    vec_float4 result;
     30    result = spu_mul( vec0, vec1 );
     31    result = spu_madd( spu_rlqwbyte( vec0, 4 ), spu_rlqwbyte( vec1, 4 ), result );
     32    return spu_madd( spu_rlqwbyte( vec0, 8 ), spu_rlqwbyte( vec1, 8 ), result );
     33}
     34#endif //__SPU__
     35
    2436btConvexShape::btConvexShape ()
    2537{
     
    3345
    3446
    35 static btVector3 convexHullSupport (const btVector3& localDir, const btVector3* points, int numPoints, const btVector3& localScaling)
    36 {
    37         btVector3 supVec(btScalar(0.),btScalar(0.),btScalar(0.));
    38         btScalar newDot,maxDot = btScalar(-1e30);
    39 
    40         btVector3 vec0(localDir.getX(),localDir.getY(),localDir.getZ());
    41         btVector3 vec = vec0;
    42         btScalar lenSqr = vec.length2();
    43         if (lenSqr < btScalar(0.0001))
    44         {
    45                 vec.setValue(1,0,0);
    46         } else {
    47                 btScalar rlen = btScalar(1.) / btSqrt(lenSqr );
    48                 vec *= rlen;
    49         }
    50 
     47static btVector3 convexHullSupport (const btVector3& localDirOrg, const btVector3* points, int numPoints, const btVector3& localScaling)
     48{       
     49
     50        btVector3 vec = localDirOrg * localScaling;
     51
     52#if defined (__CELLOS_LV2__) && defined (__SPU__)
     53
     54        btVector3 localDir = vec;
     55
     56        vec_float4 v_distMax = {-FLT_MAX,0,0,0};
     57        vec_int4 v_idxMax = {-999,0,0,0};
     58        int v=0;
     59        int numverts = numPoints;
     60
     61        for(;v<(int)numverts-4;v+=4) {
     62                vec_float4 p0 = vec_dot3(points[v  ].get128(),localDir.get128());
     63                vec_float4 p1 = vec_dot3(points[v+1].get128(),localDir.get128());
     64                vec_float4 p2 = vec_dot3(points[v+2].get128(),localDir.get128());
     65                vec_float4 p3 = vec_dot3(points[v+3].get128(),localDir.get128());
     66                const vec_int4 i0 = {v  ,0,0,0};
     67                const vec_int4 i1 = {v+1,0,0,0};
     68                const vec_int4 i2 = {v+2,0,0,0};
     69                const vec_int4 i3 = {v+3,0,0,0};
     70                vec_uint4  retGt01 = spu_cmpgt(p0,p1);
     71                vec_float4 pmax01 = spu_sel(p1,p0,retGt01);
     72                vec_int4   imax01 = spu_sel(i1,i0,retGt01);
     73                vec_uint4  retGt23 = spu_cmpgt(p2,p3);
     74                vec_float4 pmax23 = spu_sel(p3,p2,retGt23);
     75                vec_int4   imax23 = spu_sel(i3,i2,retGt23);
     76                vec_uint4  retGt0123 = spu_cmpgt(pmax01,pmax23);
     77                vec_float4 pmax0123 = spu_sel(pmax23,pmax01,retGt0123);
     78                vec_int4   imax0123 = spu_sel(imax23,imax01,retGt0123);
     79                vec_uint4  retGtMax = spu_cmpgt(v_distMax,pmax0123);
     80                v_distMax = spu_sel(pmax0123,v_distMax,retGtMax);
     81                v_idxMax = spu_sel(imax0123,v_idxMax,retGtMax);
     82        }
     83        for(;v<(int)numverts;v++) {
     84                vec_float4 p = vec_dot3(points[v].get128(),localDir.get128());
     85                const vec_int4 i = {v,0,0,0};
     86                vec_uint4  retGtMax = spu_cmpgt(v_distMax,p);
     87                v_distMax = spu_sel(p,v_distMax,retGtMax);
     88                v_idxMax = spu_sel(i,v_idxMax,retGtMax);
     89        }
     90        int ptIndex = spu_extract(v_idxMax,0);
     91        const btVector3& supVec= points[ptIndex] * localScaling;
     92        return supVec;
     93#else
     94
     95        btScalar newDot,maxDot = btScalar(-BT_LARGE_FLOAT);
     96        int ptIndex = -1;
    5197
    5298        for (int i=0;i<numPoints;i++)
    5399        {
    54                 btVector3 vtx = points[i] * localScaling;
    55 
    56                 newDot = vec.dot(vtx);
     100
     101                newDot = vec.dot(points[i]);
    57102                if (newDot > maxDot)
    58103                {
    59104                        maxDot = newDot;
    60                         supVec = vtx;
    61                 }
    62         }
    63         return btVector3(supVec.getX(),supVec.getY(),supVec.getZ());
     105                        ptIndex = i;
     106                }
     107        }
     108        btAssert(ptIndex >= 0);
     109        btVector3 supVec = points[ptIndex] * localScaling;
     110        return supVec;
     111#endif //__SPU__
    64112}
    65113
     
    161209                btVector3 supVec(0,0,0);
    162210
    163                 btScalar maxDot(btScalar(-1e30));
     211                btScalar maxDot(btScalar(-BT_LARGE_FLOAT));
    164212
    165213                btVector3 vec = vec0;
     
    293341        return btScalar(0.0f);
    294342}
    295 
     343#ifndef __SPU__
    296344void btConvexShape::getAabbNonVirtual (const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const
    297345{
     
    361409        case CONVEX_HULL_SHAPE_PROXYTYPE:
    362410        {
    363                 btPolyhedralConvexShape* convexHullShape = (btPolyhedralConvexShape*)this;
     411                btPolyhedralConvexAabbCachingShape* convexHullShape = (btPolyhedralConvexAabbCachingShape*)this;
    364412                btScalar margin = convexHullShape->getMarginNonVirtual();
    365413                convexHullShape->getNonvirtualAabb (t, aabbMin, aabbMax, margin);
     
    378426        btAssert (0);
    379427}
     428
     429#endif //__SPU__
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516#include "btConvexTriangleMeshShape.h"
    1617#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
     
    2122
    2223btConvexTriangleMeshShape ::btConvexTriangleMeshShape (btStridingMeshInterface* meshInterface, bool calcAabb)
    23 : btPolyhedralConvexShape(), m_stridingMesh(meshInterface)
     24: btPolyhedralConvexAabbCachingShape(), m_stridingMesh(meshInterface)
    2425{
    2526        m_shapeType = CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE;
     
    4445        LocalSupportVertexCallback(const btVector3& supportVecLocal)
    4546                : m_supportVertexLocal(btScalar(0.),btScalar(0.),btScalar(0.)),
    46                 m_maxDot(btScalar(-1e30)),
     47                m_maxDot(btScalar(-BT_LARGE_FLOAT)),
    4748                m_supportVecLocal(supportVecLocal)
    4849        {
     
    9293
    9394        LocalSupportVertexCallback      supportCallback(vec);
    94         btVector3 aabbMax(btScalar(1e30),btScalar(1e30),btScalar(1e30));
     95        btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
    9596        m_stridingMesh->InternalProcessAllTriangles(&supportCallback,-aabbMax,aabbMax);
    9697        supVec = supportCallback.GetSupportVertexLocal();
     
    105106                for (int i=0;i<numVectors;i++)
    106107                {
    107                         supportVerticesOut[i][3] = btScalar(-1e30);
     108                        supportVerticesOut[i][3] = btScalar(-BT_LARGE_FLOAT);
    108109                }
    109110        }
     
    116117                const btVector3& vec = vectors[j];
    117118                LocalSupportVertexCallback      supportCallback(vec);
    118                 btVector3 aabbMax(btScalar(1e30),btScalar(1e30),btScalar(1e30));
     119                btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
    119120                m_stridingMesh->InternalProcessAllTriangles(&supportCallback,-aabbMax,aabbMax);
    120121                supportVerticesOut[j] = supportCallback.GetSupportVertexLocal();
     
    298299
    299300   CenterCallback centerCallback;
    300    btVector3 aabbMax(btScalar(1e30),btScalar(1e30),btScalar(1e30));
     301   btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
    301302   m_stridingMesh->InternalProcessAllTriangles(&centerCallback, -aabbMax, aabbMax);
    302303   btVector3 center = centerCallback.getCenter();
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h

    r5781 r8284  
     1/*
     2Bullet Continuous Collision Detection and Physics Library
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
     4
     5This software is provided 'as-is', without any express or implied warranty.
     6In no event will the authors be held liable for any damages arising from the use of this software.
     7Permission is granted to anyone to use this software for any purpose,
     8including commercial applications, and to alter it and redistribute it freely,
     9subject to the following restrictions:
     10
     111. 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.
     122. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
     133. This notice may not be removed or altered from any source distribution.
     14*/
    115#ifndef CONVEX_TRIANGLEMESH_SHAPE_H
    216#define CONVEX_TRIANGLEMESH_SHAPE_H
     
    923/// The btConvexTriangleMeshShape is a convex hull of a triangle mesh, but the performance is not as good as btConvexHullShape.
    1024/// A small benefit of this class is that it uses the btStridingMeshInterface, so you can avoid the duplication of the triangle mesh data. Nevertheless, most users should use the much better performing btConvexHullShape instead.
    11 class btConvexTriangleMeshShape : public btPolyhedralConvexShape
     25class btConvexTriangleMeshShape : public btPolyhedralConvexAabbCachingShape
    1226{
    1327
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btCylinderShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516#include "btCylinderShape.h"
    1617
    1718btCylinderShape::btCylinderShape (const btVector3& halfExtents)
    18 :btBoxShape(halfExtents),
     19:btConvexInternalShape(),
    1920m_upAxis(1)
    2021{
     22        btVector3 margin(getMargin(),getMargin(),getMargin());
     23        m_implicitShapeDimensions = (halfExtents * m_localScaling) - margin;
    2124        m_shapeType = CYLINDER_SHAPE_PROXYTYPE;
    22         recalcLocalAabb();
    2325}
    2426
     
    2830{
    2931        m_upAxis = 0;
    30         recalcLocalAabb();
     32
    3133}
    3234
     
    3638{
    3739        m_upAxis = 2;
    38         recalcLocalAabb();
     40
    3941}
    4042
    4143void btCylinderShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
    4244{
    43         //skip the box 'getAabb'
    44         btPolyhedralConvexShape::getAabb(t,aabbMin,aabbMax);
     45        btTransformAabb(getHalfExtentsWithoutMargin(),getMargin(),t,aabbMin,aabbMax);
     46}
     47
     48void    btCylinderShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
     49{
     50        //approximation of box shape, todo: implement cylinder shape inertia before people notice ;-)
     51        btVector3 halfExtents = getHalfExtentsWithMargin();
     52
     53        btScalar lx=btScalar(2.)*(halfExtents.x());
     54        btScalar ly=btScalar(2.)*(halfExtents.y());
     55        btScalar lz=btScalar(2.)*(halfExtents.z());
     56
     57        inertia.setValue(mass/(btScalar(12.0)) * (ly*ly + lz*lz),
     58                                        mass/(btScalar(12.0)) * (lx*lx + lz*lz),
     59                                        mass/(btScalar(12.0)) * (lx*lx + ly*ly));
     60
    4561}
    4662
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btCylinderShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2222
    2323/// The btCylinderShape class implements a cylinder shape primitive, centered around the origin. Its central axis aligned with the Y axis. btCylinderShapeX is aligned with the X axis and btCylinderShapeZ around the Z axis.
    24 class btCylinderShape : public btBoxShape
     24class btCylinderShape : public btConvexInternalShape
    2525
    2626{
     
    3131
    3232public:
     33
     34        btVector3 getHalfExtentsWithMargin() const
     35        {
     36                btVector3 halfExtents = getHalfExtentsWithoutMargin();
     37                btVector3 margin(getMargin(),getMargin(),getMargin());
     38                halfExtents += margin;
     39                return halfExtents;
     40        }
     41       
     42        const btVector3& getHalfExtentsWithoutMargin() const
     43        {
     44                return m_implicitShapeDimensions;//changed in Bullet 2.63: assume the scaling and margin are included
     45        }
     46
    3347        btCylinderShape (const btVector3& halfExtents);
    3448       
    35         ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version
    3649        void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
    3750
     51        virtual void    calculateLocalInertia(btScalar mass,btVector3& inertia) const;
     52
    3853        virtual btVector3       localGetSupportingVertexWithoutMargin(const btVector3& vec)const;
    3954
    4055        virtual void    batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
     56
     57        virtual void setMargin(btScalar collisionMargin)
     58        {
     59                //correct the m_implicitShapeDimensions for the margin
     60                btVector3 oldMargin(getMargin(),getMargin(),getMargin());
     61                btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions+oldMargin;
     62               
     63                btConvexInternalShape::setMargin(collisionMargin);
     64                btVector3 newMargin(getMargin(),getMargin(),getMargin());
     65                m_implicitShapeDimensions = implicitShapeDimensionsWithMargin - newMargin;
     66
     67        }
    4168
    4269        virtual btVector3       localGetSupportingVertex(const btVector3& vec) const
     
    74101        }
    75102
     103        virtual void    setLocalScaling(const btVector3& scaling)
     104        {
     105                btVector3 oldMargin(getMargin(),getMargin(),getMargin());
     106                btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions+oldMargin;
     107                btVector3 unScaledImplicitShapeDimensionsWithMargin = implicitShapeDimensionsWithMargin / m_localScaling;
     108
     109                btConvexInternalShape::setLocalScaling(scaling);
     110
     111                m_implicitShapeDimensions = (unScaledImplicitShapeDimensionsWithMargin * m_localScaling) - oldMargin;
     112
     113        }
     114
    76115        //debugging
    77116        virtual const char*     getName()const
     
    80119        }
    81120
    82 
     121        virtual int     calculateSerializeBufferSize() const;
     122
     123        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     124        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
    83125
    84126};
     
    113155        virtual void    batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
    114156
    115         virtual int     getUpAxis() const
    116         {
    117                 return 2;
    118         }
    119157                //debugging
    120158        virtual const char*     getName()const
     
    130168};
    131169
     170///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     171struct  btCylinderShapeData
     172{
     173        btConvexInternalShapeData       m_convexInternalShapeData;
     174
     175        int     m_upAxis;
     176
     177        char    m_padding[4];
     178};
     179
     180SIMD_FORCE_INLINE       int     btCylinderShape::calculateSerializeBufferSize() const
     181{
     182        return sizeof(btCylinderShapeData);
     183}
     184
     185        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     186SIMD_FORCE_INLINE       const char*     btCylinderShape::serialize(void* dataBuffer, btSerializer* serializer) const
     187{
     188        btCylinderShapeData* shapeData = (btCylinderShapeData*) dataBuffer;
     189       
     190        btConvexInternalShape::serialize(&shapeData->m_convexInternalShapeData,serializer);
     191
     192        shapeData->m_upAxis = m_upAxis;
     193       
     194        return "btCylinderShapeData";
     195}
     196
     197
    132198
    133199#endif //CYLINDER_MINKOWSKI_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btEmptyShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btEmptyShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btMaterial.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2008 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    3333
    3434#endif // MATERIAL_H
     35
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btMinkowskiSumShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516
    1617#include "btMinkowskiSumShape.h"
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btMinkowskiSumShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btMultiSphereShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    1414*/
    1515
     16
     17
    1618#include "btMultiSphereShape.h"
    1719#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
    1820#include "LinearMath/btQuaternion.h"
     21#include "LinearMath/btSerializer.h"
    1922
    20 btMultiSphereShape::btMultiSphereShape (const btVector3& inertiaHalfExtents,const btVector3* positions,const btScalar* radi,int numSpheres)
    21 :btConvexInternalShape (), m_inertiaHalfExtents(inertiaHalfExtents)
     23btMultiSphereShape::btMultiSphereShape (const btVector3* positions,const btScalar* radi,int numSpheres)
     24:btConvexInternalAabbCachingShape ()
    2225{
    2326        m_shapeType = MULTI_SPHERE_SHAPE_PROXYTYPE;
    24         btScalar startMargin = btScalar(1e30);
     27        //btScalar startMargin = btScalar(BT_LARGE_FLOAT);
    2528
    26         m_numSpheres = numSpheres;
    27         for (int i=0;i<m_numSpheres;i++)
     29        m_localPositionArray.resize(numSpheres);
     30        m_radiArray.resize(numSpheres);
     31        for (int i=0;i<numSpheres;i++)
    2832        {
    29                 m_localPositions[i] = positions[i];
    30                 m_radi[i] = radi[i];
    31                 if (radi[i] < startMargin)
    32                         startMargin = radi[i];
     33                m_localPositionArray[i] = positions[i];
     34                m_radiArray[i] = radi[i];
     35               
    3336        }
    34         setMargin(startMargin);
     37
     38        recalcLocalAabb();
    3539
    3640}
    37 
    38 
    3941
    4042 
     
    4446        btVector3 supVec(0,0,0);
    4547
    46         btScalar maxDot(btScalar(-1e30));
     48        btScalar maxDot(btScalar(-BT_LARGE_FLOAT));
    4749
    4850
     
    6163        btScalar newDot;
    6264
    63         const btVector3* pos = &m_localPositions[0];
    64         const btScalar* rad = &m_radi[0];
     65        const btVector3* pos = &m_localPositionArray[0];
     66        const btScalar* rad = &m_radiArray[0];
     67        int numSpheres = m_localPositionArray.size();
    6568
    66         for (i=0;i<m_numSpheres;i++)
     69        for (i=0;i<numSpheres;i++)
    6770        {
    6871                vtx = (*pos) +vec*m_localScaling*(*rad) - vec * getMargin();
     
    8689        for (int j=0;j<numVectors;j++)
    8790        {
    88                 btScalar maxDot(btScalar(-1e30));
     91                btScalar maxDot(btScalar(-BT_LARGE_FLOAT));
    8992
    9093                const btVector3& vec = vectors[j];
     
    9396                btScalar newDot;
    9497
    95                 const btVector3* pos = &m_localPositions[0];
    96                 const btScalar* rad = &m_radi[0];
    97 
    98                 for (int i=0;i<m_numSpheres;i++)
     98                const btVector3* pos = &m_localPositionArray[0];
     99                const btScalar* rad = &m_radiArray[0];
     100                int numSpheres = m_localPositionArray.size();
     101                for (int i=0;i<numSpheres;i++)
    99102                {
    100103                        vtx = (*pos) +vec*m_localScaling*(*rad) - vec * getMargin();
     
    122125        //as an approximation, take the inertia of the box that bounds the spheres
    123126
    124         btTransform ident;
    125         ident.setIdentity();
    126 //      btVector3 aabbMin,aabbMax;
     127        btVector3 localAabbMin,localAabbMax;
     128        getCachedLocalAabb(localAabbMin,localAabbMax);
     129        btVector3 halfExtents = (localAabbMax-localAabbMin)*btScalar(0.5);
    127130
    128 //      getAabb(ident,aabbMin,aabbMax);
     131        btScalar lx=btScalar(2.)*(halfExtents.x());
     132        btScalar ly=btScalar(2.)*(halfExtents.y());
     133        btScalar lz=btScalar(2.)*(halfExtents.z());
    129134
    130         btVector3 halfExtents = m_inertiaHalfExtents;//(aabbMax - aabbMin)* btScalar(0.5);
    131 
    132         btScalar margin = CONVEX_DISTANCE_MARGIN;
    133 
    134         btScalar lx=btScalar(2.)*(halfExtents[0]+margin);
    135         btScalar ly=btScalar(2.)*(halfExtents[1]+margin);
    136         btScalar lz=btScalar(2.)*(halfExtents[2]+margin);
    137         const btScalar x2 = lx*lx;
    138         const btScalar y2 = ly*ly;
    139         const btScalar z2 = lz*lz;
    140         const btScalar scaledmass = mass * btScalar(.08333333);
    141 
    142         inertia[0] = scaledmass * (y2+z2);
    143         inertia[1] = scaledmass * (x2+z2);
    144         inertia[2] = scaledmass * (x2+y2);
     135        inertia.setValue(mass/(btScalar(12.0)) * (ly*ly + lz*lz),
     136                                        mass/(btScalar(12.0)) * (lx*lx + lz*lz),
     137                                        mass/(btScalar(12.0)) * (lx*lx + ly*ly));
    145138
    146139}
    147140
    148141
     142///fills the dataBuffer and returns the struct name (and 0 on failure)
     143const char*     btMultiSphereShape::serialize(void* dataBuffer, btSerializer* serializer) const
     144{
     145        btMultiSphereShapeData* shapeData = (btMultiSphereShapeData*) dataBuffer;
     146        btConvexInternalShape::serialize(&shapeData->m_convexInternalShapeData, serializer);
    149147
     148        int numElem = m_localPositionArray.size();
     149        shapeData->m_localPositionArrayPtr = numElem ? (btPositionAndRadius*)serializer->getUniquePointer((void*)&m_localPositionArray[0]):  0;
     150       
     151        shapeData->m_localPositionArraySize = numElem;
     152        if (numElem)
     153        {
     154                btChunk* chunk = serializer->allocate(sizeof(btPositionAndRadius),numElem);
     155                btPositionAndRadius* memPtr = (btPositionAndRadius*)chunk->m_oldPtr;
     156                for (int i=0;i<numElem;i++,memPtr++)
     157                {
     158                        m_localPositionArray[i].serializeFloat(memPtr->m_pos);
     159                        memPtr->m_radius = float(m_radiArray[i]);
     160                }
     161                serializer->finalizeChunk(chunk,"btPositionAndRadius",BT_ARRAY_CODE,(void*)&m_localPositionArray[0]);
     162        }
     163       
     164        return "btMultiSphereShapeData";
     165}
     166
     167
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btMultiSphereShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    1919#include "btConvexInternalShape.h"
    2020#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types
    21 
    22 #define MAX_NUM_SPHERES 5
    23 
    24 ///The btMultiSphereShape represents the convex hull of a collection of spheres. You can create special capsules or other smooth volumes.
    25 ///It is possible to animate the spheres for deformation.
    26 class btMultiSphereShape : public btConvexInternalShape
    27 
    28 {
    29        
    30         btVector3 m_localPositions[MAX_NUM_SPHERES];
    31         btScalar  m_radi[MAX_NUM_SPHERES];
    32         btVector3       m_inertiaHalfExtents;
    33 
    34         int m_numSpheres;
    35        
     21#include "LinearMath/btAlignedObjectArray.h"
     22#include "LinearMath/btAabbUtil2.h"
    3623
    3724
    3825
     26///The btMultiSphereShape represents the convex hull of a collection of spheres. You can create special capsules or other smooth volumes.
     27///It is possible to animate the spheres for deformation, but call 'recalcLocalAabb' after changing any sphere position/radius
     28class btMultiSphereShape : public btConvexInternalAabbCachingShape
     29{
     30       
     31        btAlignedObjectArray<btVector3> m_localPositionArray;
     32        btAlignedObjectArray<btScalar>  m_radiArray;
     33       
    3934public:
    40         btMultiSphereShape (const btVector3& inertiaHalfExtents,const btVector3* positions,const btScalar* radi,int numSpheres);
     35        btMultiSphereShape (const btVector3* positions,const btScalar* radi,int numSpheres);
    4136
    4237        ///CollisionShape Interface
     
    5045        int     getSphereCount() const
    5146        {
    52                 return m_numSpheres;
     47                return m_localPositionArray.size();
    5348        }
    5449
    5550        const btVector3&        getSpherePosition(int index) const
    5651        {
    57                 return m_localPositions[index];
     52                return m_localPositionArray[index];
    5853        }
    5954
    6055        btScalar        getSphereRadius(int index) const
    6156        {
    62                 return m_radi[index];
     57                return m_radiArray[index];
    6358        }
    6459
     
    6964        }
    7065
     66        virtual int     calculateSerializeBufferSize() const;
     67
     68        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     69        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     70
     71
    7172};
    7273
    7374
     75struct  btPositionAndRadius
     76{
     77        btVector3FloatData      m_pos;
     78        float           m_radius;
     79};
     80
     81struct  btMultiSphereShapeData
     82{
     83        btConvexInternalShapeData       m_convexInternalShapeData;
     84
     85        btPositionAndRadius     *m_localPositionArrayPtr;
     86        int                             m_localPositionArraySize;
     87        char    m_padding[4];
     88};
     89
     90
     91
     92SIMD_FORCE_INLINE       int     btMultiSphereShape::calculateSerializeBufferSize() const
     93{
     94        return sizeof(btMultiSphereShapeData);
     95}
     96
     97
     98
    7499#endif //MULTI_SPHERE_MINKOWSKI_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2008 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2008 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    3838            m_shapeType = MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE;
    3939
    40             btVector3 m_triangle[3];
    4140            const unsigned char *vertexbase;
    4241            int numverts;
     
    7271            m_shapeType = MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE;
    7372
    74             btVector3 m_triangle[3];
    7573            const unsigned char *vertexbase;
    7674            int numverts;
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btOptimizedBvh.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    1414*/
    1515
     16
    1617#include "btOptimizedBvh.h"
    1718#include "btStridingMeshInterface.h"
     
    5657                        btOptimizedBvhNode node;
    5758                        btVector3       aabbMin,aabbMax;
    58                         aabbMin.setValue(btScalar(1e30),btScalar(1e30),btScalar(1e30));
    59                         aabbMax.setValue(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
     59                        aabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
     60                        aabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
    6061                        aabbMin.setMin(triangle[0]);
    6162                        aabbMax.setMax(triangle[0]);
     
    104105                        btQuantizedBvhNode node;
    105106                        btVector3       aabbMin,aabbMax;
    106                         aabbMin.setValue(btScalar(1e30),btScalar(1e30),btScalar(1e30));
    107                         aabbMax.setValue(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
     107                        aabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
     108                        aabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
    108109                        aabbMin.setMin(triangle[0]);
    109110                        aabbMax.setMax(triangle[0]);
     
    168169                NodeTriangleCallback    callback(m_leafNodes);
    169170
    170                 btVector3 aabbMin(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
    171                 btVector3 aabbMax(btScalar(1e30),btScalar(1e30),btScalar(1e30));
     171                btVector3 aabbMin(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
     172                btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
    172173
    173174                triangles->InternalProcessAllTriangles(&callback,aabbMin,aabbMax);
     
    337338
    338339                               
    339                                 aabbMin.setValue(btScalar(1e30),btScalar(1e30),btScalar(1e30));
    340                                 aabbMax.setValue(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
     340                                aabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
     341                                aabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
    341342                                aabbMin.setMin(triangleVerts[0]);
    342343                                aabbMax.setMax(triangleVerts[0]);
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btOptimizedBvh.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
     16///Contains contributions from Disney Studio's
    1517
    1618#ifndef OPTIMIZED_BVH_H
     
    4648
    4749        /// Data buffer MUST be 16 byte aligned
    48         virtual bool serialize(void *o_alignedDataBuffer, unsigned i_dataBufferSize, bool i_swapEndian)
     50        virtual bool serializeInPlace(void *o_alignedDataBuffer, unsigned i_dataBufferSize, bool i_swapEndian) const
    4951        {
    5052                return btQuantizedBvh::serialize(o_alignedDataBuffer,i_dataBufferSize,i_swapEndian);
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btPolyhedralConvexShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    1616#include "BulletCollision/CollisionShapes/btPolyhedralConvexShape.h"
    1717
    18 btPolyhedralConvexShape::btPolyhedralConvexShape() :btConvexInternalShape(),
    19 m_localAabbMin(1,1,1),
    20 m_localAabbMax(-1,-1,-1),
    21 m_isLocalAabbValid(false),
    22 m_optionalHull(0)
     18btPolyhedralConvexShape::btPolyhedralConvexShape() :btConvexInternalShape()
    2319{
    2420
     
    2824btVector3       btPolyhedralConvexShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
    2925{
     26
     27
     28        btVector3 supVec(0,0,0);
     29#ifndef __SPU__
    3030        int i;
    31         btVector3 supVec(0,0,0);
    32 
    33         btScalar maxDot(btScalar(-1e30));
     31        btScalar maxDot(btScalar(-BT_LARGE_FLOAT));
    3432
    3533        btVector3 vec = vec0;
     
    5856        }
    5957
     58       
     59#endif //__SPU__
    6060        return supVec;
     61}
    6162
    62 }
     63
    6364
    6465void    btPolyhedralConvexShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
    6566{
     67#ifndef __SPU__
    6668        int i;
    6769
     
    7173        for (i=0;i<numVectors;i++)
    7274        {
    73                 supportVerticesOut[i][3] = btScalar(-1e30);
     75                supportVerticesOut[i][3] = btScalar(-BT_LARGE_FLOAT);
    7476        }
    7577
     
    9193                }
    9294        }
     95#endif //__SPU__
    9396}
    9497
     
    97100void    btPolyhedralConvexShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
    98101{
     102#ifndef __SPU__
    99103        //not yet, return box inertia
    100104
     
    116120
    117121        inertia = scaledmass * (btVector3(y2+z2,x2+z2,x2+y2));
    118 
     122#endif //__SPU__
    119123}
    120124
    121125
    122126
    123 void btPolyhedralConvexShape::getAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax) const
    124 {
    125         getNonvirtualAabb(trans,aabbMin,aabbMax,getMargin());
    126 }
    127 
    128 
    129 
    130 void    btPolyhedralConvexShape::setLocalScaling(const btVector3& scaling)
     127void    btPolyhedralConvexAabbCachingShape::setLocalScaling(const btVector3& scaling)
    131128{
    132129        btConvexInternalShape::setLocalScaling(scaling);
     
    134131}
    135132
    136 void    btPolyhedralConvexShape::recalcLocalAabb()
     133btPolyhedralConvexAabbCachingShape::btPolyhedralConvexAabbCachingShape()
     134:btPolyhedralConvexShape(),
     135m_localAabbMin(1,1,1),
     136m_localAabbMax(-1,-1,-1),
     137m_isLocalAabbValid(false)
     138{
     139}
     140
     141void btPolyhedralConvexAabbCachingShape::getAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax) const
     142{
     143        getNonvirtualAabb(trans,aabbMin,aabbMax,getMargin());
     144}
     145
     146void    btPolyhedralConvexAabbCachingShape::recalcLocalAabb()
    137147{
    138148        m_isLocalAabbValid = true;
     
    182192}
    183193
    184 
    185 
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btPolyhedralConvexShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    1818
    1919#include "LinearMath/btMatrix3x3.h"
    20 #include "LinearMath/btAabbUtil2.h"
    2120#include "btConvexInternalShape.h"
    2221
     
    2726
    2827protected:
    29         btVector3       m_localAabbMin;
    30         btVector3       m_localAabbMax;
    31         bool            m_isLocalAabbValid;
    32 
     28       
    3329public:
    3430
     
    3935        virtual btVector3       localGetSupportingVertexWithoutMargin(const btVector3& vec)const;
    4036        virtual void    batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
    41 
    4237       
    4338        virtual void    calculateLocalInertia(btScalar mass,btVector3& inertia) const;
     39       
     40       
     41        virtual int     getNumVertices() const = 0 ;
     42        virtual int getNumEdges() const = 0;
     43        virtual void getEdge(int i,btVector3& pa,btVector3& pb) const = 0;
     44        virtual void getVertex(int i,btVector3& vtx) const = 0;
     45        virtual int     getNumPlanes() const = 0;
     46        virtual void getPlane(btVector3& planeNormal,btVector3& planeSupport,int i ) const = 0;
     47//      virtual int getIndex(int i) const = 0 ;
    4448
     49        virtual bool isInside(const btVector3& pt,btScalar tolerance) const = 0;
     50       
     51};
     52
     53
     54///The btPolyhedralConvexAabbCachingShape adds aabb caching to the btPolyhedralConvexShape
     55class btPolyhedralConvexAabbCachingShape : public btPolyhedralConvexShape
     56{
     57
     58        btVector3       m_localAabbMin;
     59        btVector3       m_localAabbMax;
     60        bool            m_isLocalAabbValid;
     61               
     62protected:
    4563
    4664        void setCachedLocalAabb (const btVector3& aabbMin, const btVector3& aabbMax)
     
    5876        }
    5977
     78public:
     79
     80        btPolyhedralConvexAabbCachingShape();
     81       
    6082        inline void getNonvirtualAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax, btScalar margin) const
    6183        {
     
    6688        }
    6789
    68        
     90        virtual void    setLocalScaling(const btVector3& scaling);
     91
    6992        virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
    7093
    71         virtual void    setLocalScaling(const btVector3& scaling);
    72 
    7394        void    recalcLocalAabb();
    74 
    75         virtual int     getNumVertices() const = 0 ;
    76         virtual int getNumEdges() const = 0;
    77         virtual void getEdge(int i,btVector3& pa,btVector3& pb) const = 0;
    78         virtual void getVertex(int i,btVector3& vtx) const = 0;
    79         virtual int     getNumPlanes() const = 0;
    80         virtual void getPlane(btVector3& planeNormal,btVector3& planeSupport,int i ) const = 0;
    81 //      virtual int getIndex(int i) const = 0 ;
    82 
    83         virtual bool isInside(const btVector3& pt,btScalar tolerance) const = 0;
    84        
    85         /// optional Hull is for optional Separating Axis Test Hull collision detection, see Hull.cpp
    86         class   Hull*   m_optionalHull;
    8795
    8896};
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2008 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516
    1617#include "btScaledBvhTriangleMeshShape.h"
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2008 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btShapeHull.cpp

    r5781 r8284  
    11/*
    2 btbtShapeHull implemented by John McCutchan.
    3 
    42Bullet Continuous Collision Detection and Physics Library
    5 Copyright (c) 2003-2008 Erwin Coumans  http://bulletphysics.com
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    64
    75This software is provided 'as-is', without any express or implied warranty.
    86In no event will the authors be held liable for any damages arising from the use of this software.
    9 Permission is granted to anyone to use this software for any purpose,
    10 including commercial applications, and to alter it and redistribute it freely,
     7Permission is granted to anyone to use this software for any purpose, 
     8including commercial applications, and to alter it and redistribute it freely, 
    119subject to the following restrictions:
    1210
     
    1614*/
    1715
     16//btShapeHull was implemented by John McCutchan.
     17
     18
    1819#include "btShapeHull.h"
    1920#include "LinearMath/btConvexHull.h"
    2021
    2122#define NUM_UNITSPHERE_POINTS 42
    22 
    23 static btVector3 btUnitSpherePoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] =
    24 {
    25         btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)),
    26         btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)),
    27         btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)),
    28         btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)),
    29         btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)),
    30         btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)),
    31         btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)),
    32         btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)),
    33         btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)),
    34         btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)),
    35         btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)),
    36         btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)),
    37         btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)),
    38         btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)),
    39         btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)),
    40         btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)),
    41         btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)),
    42         btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)),
    43         btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)),
    44         btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)),
    45         btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)),
    46         btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)),
    47         btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)),
    48         btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)),
    49         btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)),
    50         btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)),
    51         btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)),
    52         btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)),
    53         btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)),
    54         btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)),
    55         btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)),
    56         btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)),
    57         btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)),
    58         btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)),
    59         btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)),
    60         btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)),
    61         btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)),
    62         btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)),
    63         btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)),
    64         btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)),
    65         btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)),
    66         btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654))
    67 };
    6823
    6924btShapeHull::btShapeHull (const btConvexShape* shape)
     
    9348                                btVector3 norm;
    9449                                m_shape->getPreferredPenetrationDirection(i,norm);
    95                                 btUnitSpherePoints[numSampleDirections] = norm;
     50                                getUnitSpherePoints()[numSampleDirections] = norm;
    9651                                numSampleDirections++;
    9752                        }
     
    10358        for (i = 0; i < numSampleDirections; i++)
    10459        {
    105                 supportPoints[i] = m_shape->localGetSupportingVertex(btUnitSpherePoints[i]);
     60                supportPoints[i] = m_shape->localGetSupportingVertex(getUnitSpherePoints()[i]);
    10661        }
    10762
     
    163118}
    164119
     120
     121btVector3* btShapeHull::getUnitSpherePoints()
     122{
     123        static btVector3 sUnitSpherePoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] =
     124        {
     125                btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)),
     126                btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)),
     127                btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)),
     128                btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)),
     129                btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)),
     130                btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)),
     131                btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)),
     132                btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)),
     133                btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)),
     134                btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)),
     135                btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)),
     136                btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)),
     137                btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)),
     138                btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)),
     139                btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)),
     140                btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)),
     141                btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)),
     142                btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)),
     143                btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)),
     144                btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)),
     145                btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)),
     146                btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)),
     147                btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)),
     148                btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)),
     149                btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)),
     150                btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)),
     151                btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)),
     152                btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)),
     153                btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)),
     154                btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)),
     155                btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)),
     156                btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)),
     157                btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)),
     158                btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)),
     159                btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)),
     160                btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)),
     161                btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)),
     162                btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)),
     163                btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)),
     164                btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)),
     165                btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)),
     166                btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654))
     167        };
     168        return sUnitSpherePoints;
     169}
     170
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btShapeHull.h

    r5781 r8284  
    11/*
    2 btShapeHull implemented by John McCutchan.
    3 
    42Bullet Continuous Collision Detection and Physics Library
    5 Copyright (c) 2003-2008 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    64
    75This software is provided 'as-is', without any express or implied warranty.
    86In no event will the authors be held liable for any damages arising from the use of this software.
    9 Permission is granted to anyone to use this software for any purpose,
    10 including commercial applications, and to alter it and redistribute it freely,
     7Permission is granted to anyone to use this software for any purpose, 
     8including commercial applications, and to alter it and redistribute it freely, 
    119subject to the following restrictions:
    1210
     
    15133. This notice may not be removed or altered from any source distribution.
    1614*/
     15
     16///btShapeHull implemented by John McCutchan.
    1717
    1818#ifndef _SHAPE_HULL_H
     
    2828class btShapeHull
    2929{
     30protected:
     31
     32        btAlignedObjectArray<btVector3> m_vertices;
     33        btAlignedObjectArray<unsigned int> m_indices;
     34        unsigned int m_numIndices;
     35        const btConvexShape* m_shape;
     36
     37        static btVector3* getUnitSpherePoints();
     38
    3039public:
    3140        btShapeHull (const btConvexShape* shape);
     
    4655                return &m_indices[0];
    4756        }
    48 
    49 protected:
    50         btAlignedObjectArray<btVector3> m_vertices;
    51         btAlignedObjectArray<unsigned int> m_indices;
    52         unsigned int m_numIndices;
    53         const btConvexShape* m_shape;
    5457};
    5558
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btSphereShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btSphereShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
    15 
    1615#ifndef SPHERE_MINKOWSKI_H
    1716#define SPHERE_MINKOWSKI_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btStaticPlaneShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    3939        (void)t;
    4040        /*
    41         btVector3 infvec (btScalar(1e30),btScalar(1e30),btScalar(1e30));
     41        btVector3 infvec (btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
    4242
    4343        btVector3 center = m_planeNormal*m_planeConstant;
     
    4848        */
    4949
    50         aabbMin.setValue(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
    51         aabbMax.setValue(btScalar(1e30),btScalar(1e30),btScalar(1e30));
     50        aabbMin.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
     51        aabbMax.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
    5252
    5353}
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btStaticPlaneShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2121
    2222///The btStaticPlaneShape simulates an infinite non-moving (static) collision plane.
    23 class btStaticPlaneShape : public btConcaveShape
     23ATTRIBUTE_ALIGNED16(class) btStaticPlaneShape : public btConcaveShape
    2424{
    2525protected:
     
    5959        virtual const char*     getName()const {return "STATICPLANE";}
    6060
     61        virtual int     calculateSerializeBufferSize() const;
     62
     63        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     64        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     65
    6166
    6267};
    6368
     69///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     70struct  btStaticPlaneShapeData
     71{
     72        btCollisionShapeData    m_collisionShapeData;
     73
     74        btVector3FloatData      m_localScaling;
     75        btVector3FloatData      m_planeNormal;
     76        float                   m_planeConstant;
     77        char    m_pad[4];
     78};
     79
     80
     81SIMD_FORCE_INLINE       int     btStaticPlaneShape::calculateSerializeBufferSize() const
     82{
     83        return sizeof(btStaticPlaneShapeData);
     84}
     85
     86///fills the dataBuffer and returns the struct name (and 0 on failure)
     87SIMD_FORCE_INLINE       const char*     btStaticPlaneShape::serialize(void* dataBuffer, btSerializer* serializer) const
     88{
     89        btStaticPlaneShapeData* planeData = (btStaticPlaneShapeData*) dataBuffer;
     90        btCollisionShape::serialize(&planeData->m_collisionShapeData,serializer);
     91
     92        m_localScaling.serializeFloat(planeData->m_localScaling);
     93        m_planeNormal.serializeFloat(planeData->m_planeNormal);
     94        planeData->m_planeConstant = float(m_planeConstant);
     95               
     96        return "btStaticPlaneShapeData";
     97}
     98
     99
    64100#endif //STATIC_PLANE_SHAPE_H
     101
     102
     103
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btStridingMeshInterface.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    1515
    1616#include "btStridingMeshInterface.h"
     17#include "LinearMath/btSerializer.h"
    1718
    1819btStridingMeshInterface::~btStridingMeshInterface()
     
    3637        int gfxindex;
    3738        btVector3 triangle[3];
    38         btScalar* graphicsbase;
    3939
    4040        btVector3 meshScaling = getScaling();
     
    4646                numtotalphysicsverts+=numtriangles*3; //upper bound
    4747
    48                 switch (gfxindextype)
     48                ///unlike that developers want to pass in double-precision meshes in single-precision Bullet build
     49                ///so disable this feature by default
     50                ///see patch http://code.google.com/p/bullet/issues/detail?id=213
     51
     52                switch (type)
    4953                {
    50                 case PHY_INTEGER:
     54                case PHY_FLOAT:
     55                 {
     56
     57                         float* graphicsbase;
     58
     59                         switch (gfxindextype)
     60                         {
     61                         case PHY_INTEGER:
     62                                 {
     63                                         for (gfxindex=0;gfxindex<numtriangles;gfxindex++)
     64                                         {
     65                                                 unsigned int* tri_indices= (unsigned int*)(indexbase+gfxindex*indexstride);
     66                                                 graphicsbase = (float*)(vertexbase+tri_indices[0]*stride);
     67                                                 triangle[0].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ());
     68                                                 graphicsbase = (float*)(vertexbase+tri_indices[1]*stride);
     69                                                 triangle[1].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),    graphicsbase[2]*meshScaling.getZ());
     70                                                 graphicsbase = (float*)(vertexbase+tri_indices[2]*stride);
     71                                                 triangle[2].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),    graphicsbase[2]*meshScaling.getZ());
     72                                                 callback->internalProcessTriangleIndex(triangle,part,gfxindex);
     73                                         }
     74                                         break;
     75                                 }
     76                         case PHY_SHORT:
     77                                 {
     78                                         for (gfxindex=0;gfxindex<numtriangles;gfxindex++)
     79                                         {
     80                                                 unsigned short int* tri_indices= (unsigned short int*)(indexbase+gfxindex*indexstride);
     81                                                 graphicsbase = (float*)(vertexbase+tri_indices[0]*stride);
     82                                                 triangle[0].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ());
     83                                                 graphicsbase = (float*)(vertexbase+tri_indices[1]*stride);
     84                                                 triangle[1].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),    graphicsbase[2]*meshScaling.getZ());
     85                                                 graphicsbase = (float*)(vertexbase+tri_indices[2]*stride);
     86                                                 triangle[2].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),    graphicsbase[2]*meshScaling.getZ());
     87                                                 callback->internalProcessTriangleIndex(triangle,part,gfxindex);
     88                                         }
     89                                         break;
     90                                 }
     91                         default:
     92                                 btAssert((gfxindextype == PHY_INTEGER) || (gfxindextype == PHY_SHORT));
     93                         }
     94                         break;
     95                 }
     96
     97                case PHY_DOUBLE:
    5198                        {
    52                                 for (gfxindex=0;gfxindex<numtriangles;gfxindex++)
    53                                 {
    54                                         unsigned int* tri_indices= (unsigned int*)(indexbase+gfxindex*indexstride);
    55                                         graphicsbase = (btScalar*)(vertexbase+tri_indices[0]*stride);
    56                                         triangle[0].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ());
    57                                         graphicsbase = (btScalar*)(vertexbase+tri_indices[1]*stride);
    58                                         triangle[1].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),     graphicsbase[2]*meshScaling.getZ());
    59                                         graphicsbase = (btScalar*)(vertexbase+tri_indices[2]*stride);
    60                                         triangle[2].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),     graphicsbase[2]*meshScaling.getZ());
    61                                         callback->internalProcessTriangleIndex(triangle,part,gfxindex);
    62                                 }
    63                                 break;
    64                         }
    65                 case PHY_SHORT:
    66                         {
    67                                 for (gfxindex=0;gfxindex<numtriangles;gfxindex++)
    68                                 {
    69                                         unsigned short int* tri_indices= (unsigned short int*)(indexbase+gfxindex*indexstride);
    70                                         graphicsbase = (btScalar*)(vertexbase+tri_indices[0]*stride);
    71                                         triangle[0].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ());
    72                                         graphicsbase = (btScalar*)(vertexbase+tri_indices[1]*stride);
    73                                         triangle[1].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),     graphicsbase[2]*meshScaling.getZ());
    74                                         graphicsbase = (btScalar*)(vertexbase+tri_indices[2]*stride);
    75                                         triangle[2].setValue(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),     graphicsbase[2]*meshScaling.getZ());
    76                                         callback->internalProcessTriangleIndex(triangle,part,gfxindex);
     99                                double* graphicsbase;
     100
     101                                switch (gfxindextype)
     102                                {
     103                                case PHY_INTEGER:
     104                                        {
     105                                                for (gfxindex=0;gfxindex<numtriangles;gfxindex++)
     106                                                {
     107                                                        unsigned int* tri_indices= (unsigned int*)(indexbase+gfxindex*indexstride);
     108                                                        graphicsbase = (double*)(vertexbase+tri_indices[0]*stride);
     109                                                        triangle[0].setValue((btScalar)graphicsbase[0]*meshScaling.getX(),(btScalar)graphicsbase[1]*meshScaling.getY(),(btScalar)graphicsbase[2]*meshScaling.getZ());
     110                                                        graphicsbase = (double*)(vertexbase+tri_indices[1]*stride);
     111                                                        triangle[1].setValue((btScalar)graphicsbase[0]*meshScaling.getX(),(btScalar)graphicsbase[1]*meshScaling.getY(),  (btScalar)graphicsbase[2]*meshScaling.getZ());
     112                                                        graphicsbase = (double*)(vertexbase+tri_indices[2]*stride);
     113                                                        triangle[2].setValue((btScalar)graphicsbase[0]*meshScaling.getX(),(btScalar)graphicsbase[1]*meshScaling.getY(),  (btScalar)graphicsbase[2]*meshScaling.getZ());
     114                                                        callback->internalProcessTriangleIndex(triangle,part,gfxindex);
     115                                                }
     116                                                break;
     117                                        }
     118                                case PHY_SHORT:
     119                                        {
     120                                                for (gfxindex=0;gfxindex<numtriangles;gfxindex++)
     121                                                {
     122                                                        unsigned short int* tri_indices= (unsigned short int*)(indexbase+gfxindex*indexstride);
     123                                                        graphicsbase = (double*)(vertexbase+tri_indices[0]*stride);
     124                                                        triangle[0].setValue((btScalar)graphicsbase[0]*meshScaling.getX(),(btScalar)graphicsbase[1]*meshScaling.getY(),(btScalar)graphicsbase[2]*meshScaling.getZ());
     125                                                        graphicsbase = (double*)(vertexbase+tri_indices[1]*stride);
     126                                                        triangle[1].setValue((btScalar)graphicsbase[0]*meshScaling.getX(),(btScalar)graphicsbase[1]*meshScaling.getY(),  (btScalar)graphicsbase[2]*meshScaling.getZ());
     127                                                        graphicsbase = (double*)(vertexbase+tri_indices[2]*stride);
     128                                                        triangle[2].setValue((btScalar)graphicsbase[0]*meshScaling.getX(),(btScalar)graphicsbase[1]*meshScaling.getY(),  (btScalar)graphicsbase[2]*meshScaling.getZ());
     129                                                        callback->internalProcessTriangleIndex(triangle,part,gfxindex);
     130                                                }
     131                                                break;
     132                                        }
     133                                default:
     134                                        btAssert((gfxindextype == PHY_INTEGER) || (gfxindextype == PHY_SHORT));
    77135                                }
    78136                                break;
    79137                        }
    80138                default:
    81                         btAssert((gfxindextype == PHY_INTEGER) || (gfxindextype == PHY_SHORT));
     139                        btAssert((type == PHY_FLOAT) || (type == PHY_DOUBLE));
    82140                }
    83141
     
    96154                AabbCalculationCallback()
    97155                {
    98                         m_aabbMin.setValue(btScalar(1e30),btScalar(1e30),btScalar(1e30));
    99                         m_aabbMax.setValue(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
     156                        m_aabbMin.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
     157                        m_aabbMax.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
    100158                }
    101159
     
    114172        };
    115173
    116                 //first calculate the total aabb for all triangles
     174        //first calculate the total aabb for all triangles
    117175        AabbCalculationCallback aabbCallback;
    118         aabbMin.setValue(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
    119         aabbMax.setValue(btScalar(1e30),btScalar(1e30),btScalar(1e30));
     176        aabbMin.setValue(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
     177        aabbMax.setValue(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
    120178        InternalProcessAllTriangles(&aabbCallback,aabbMin,aabbMax);
    121179
     
    123181        aabbMax = aabbCallback.m_aabbMax;
    124182}
     183
     184
     185
     186///fills the dataBuffer and returns the struct name (and 0 on failure)
     187const char*     btStridingMeshInterface::serialize(void* dataBuffer, btSerializer* serializer) const
     188{
     189        btStridingMeshInterfaceData* trimeshData = (btStridingMeshInterfaceData*) dataBuffer;
     190
     191        trimeshData->m_numMeshParts = getNumSubParts();
     192
     193        //void* uniquePtr = 0;
     194
     195        trimeshData->m_meshPartsPtr = 0;
     196
     197        if (trimeshData->m_numMeshParts)
     198        {
     199                btChunk* chunk = serializer->allocate(sizeof(btMeshPartData),trimeshData->m_numMeshParts);
     200                btMeshPartData* memPtr = (btMeshPartData*)chunk->m_oldPtr;
     201                trimeshData->m_meshPartsPtr = (btMeshPartData *)serializer->getUniquePointer(memPtr);
     202
     203
     204        //      int numtotalphysicsverts = 0;
     205                int part,graphicssubparts = getNumSubParts();
     206                const unsigned char * vertexbase;
     207                const unsigned char * indexbase;
     208                int indexstride;
     209                PHY_ScalarType type;
     210                PHY_ScalarType gfxindextype;
     211                int stride,numverts,numtriangles;
     212                int gfxindex;
     213        //      btVector3 triangle[3];
     214
     215                btVector3 meshScaling = getScaling();
     216
     217                ///if the number of parts is big, the performance might drop due to the innerloop switch on indextype
     218                for (part=0;part<graphicssubparts ;part++,memPtr++)
     219                {
     220                        getLockedReadOnlyVertexIndexBase(&vertexbase,numverts,type,stride,&indexbase,indexstride,numtriangles,gfxindextype,part);
     221                        memPtr->m_numTriangles = numtriangles;//indices = 3*numtriangles
     222                        memPtr->m_numVertices = numverts;
     223                        memPtr->m_indices16 = 0;
     224                        memPtr->m_indices32 = 0;
     225                        memPtr->m_3indices16 = 0;
     226                        memPtr->m_vertices3f = 0;
     227                        memPtr->m_vertices3d = 0;
     228
     229                        switch (gfxindextype)
     230                        {
     231                        case PHY_INTEGER:
     232                                {
     233                                        int numindices = numtriangles*3;
     234                               
     235                                        if (numindices)
     236                                        {
     237                                                btChunk* chunk = serializer->allocate(sizeof(btIntIndexData),numindices);
     238                                                btIntIndexData* tmpIndices = (btIntIndexData*)chunk->m_oldPtr;
     239                                                memPtr->m_indices32 = (btIntIndexData*)serializer->getUniquePointer(tmpIndices);
     240                                                for (gfxindex=0;gfxindex<numtriangles;gfxindex++)
     241                                                {
     242                                                        unsigned int* tri_indices= (unsigned int*)(indexbase+gfxindex*indexstride);
     243                                                        tmpIndices[gfxindex*3].m_value = tri_indices[0];
     244                                                        tmpIndices[gfxindex*3+1].m_value = tri_indices[1];
     245                                                        tmpIndices[gfxindex*3+2].m_value = tri_indices[2];
     246                                                }
     247                                                serializer->finalizeChunk(chunk,"btIntIndexData",BT_ARRAY_CODE,(void*)chunk->m_oldPtr);
     248                                        }
     249                                        break;
     250                                }
     251                        case PHY_SHORT:
     252                                {
     253                                        if (numtriangles)
     254                                        {
     255                                                btChunk* chunk = serializer->allocate(sizeof(btShortIntIndexTripletData),numtriangles);
     256                                                btShortIntIndexTripletData* tmpIndices = (btShortIntIndexTripletData*)chunk->m_oldPtr;
     257                                                memPtr->m_3indices16 = (btShortIntIndexTripletData*) serializer->getUniquePointer(tmpIndices);
     258                                                for (gfxindex=0;gfxindex<numtriangles;gfxindex++)
     259                                                {
     260                                                        unsigned short int* tri_indices= (unsigned short int*)(indexbase+gfxindex*indexstride);
     261                                                        tmpIndices[gfxindex].m_values[0] = tri_indices[0];
     262                                                        tmpIndices[gfxindex].m_values[1] = tri_indices[1];
     263                                                        tmpIndices[gfxindex].m_values[2] = tri_indices[2];
     264                                                }
     265                                                serializer->finalizeChunk(chunk,"btShortIntIndexTripletData",BT_ARRAY_CODE,(void*)chunk->m_oldPtr);
     266                                        }
     267                                        break;
     268                                }
     269                        default:
     270                                {
     271                                        btAssert(0);
     272                                        //unknown index type
     273                                }
     274                        }
     275
     276                        switch (type)
     277                        {
     278                        case PHY_FLOAT:
     279                         {
     280                                 float* graphicsbase;
     281
     282                                 if (numverts)
     283                                 {
     284                                         btChunk* chunk = serializer->allocate(sizeof(btVector3FloatData),numverts);
     285                                         btVector3FloatData* tmpVertices = (btVector3FloatData*) chunk->m_oldPtr;
     286                                         memPtr->m_vertices3f = (btVector3FloatData *)serializer->getUniquePointer(tmpVertices);
     287                                         for (int i=0;i<numverts;i++)
     288                                         {
     289                                                 graphicsbase = (float*)(vertexbase+i*stride);
     290                                                 tmpVertices[i].m_floats[0] = graphicsbase[0];
     291                                                 tmpVertices[i].m_floats[1] = graphicsbase[1];
     292                                                 tmpVertices[i].m_floats[2] = graphicsbase[2];
     293                                         }
     294                                         serializer->finalizeChunk(chunk,"btVector3FloatData",BT_ARRAY_CODE,(void*)chunk->m_oldPtr);
     295                                 }
     296                                 break;
     297                                }
     298
     299                        case PHY_DOUBLE:
     300                                {
     301                                        if (numverts)
     302                                        {
     303                                                btChunk* chunk = serializer->allocate(sizeof(btVector3DoubleData),numverts);
     304                                                btVector3DoubleData* tmpVertices = (btVector3DoubleData*) chunk->m_oldPtr;
     305                                                memPtr->m_vertices3d = (btVector3DoubleData *) serializer->getUniquePointer(tmpVertices);
     306                                                for (int i=0;i<numverts;i++)
     307                                         {
     308                                                 double* graphicsbase = (double*)(vertexbase+i*stride);//for now convert to float, might leave it at double
     309                                                 tmpVertices[i].m_floats[0] = graphicsbase[0];
     310                                                 tmpVertices[i].m_floats[1] = graphicsbase[1];
     311                                                 tmpVertices[i].m_floats[2] = graphicsbase[2];
     312                                         }
     313                                                serializer->finalizeChunk(chunk,"btVector3DoubleData",BT_ARRAY_CODE,(void*)chunk->m_oldPtr);
     314                                        }
     315                                        break;
     316                                }
     317
     318                        default:
     319                                btAssert((type == PHY_FLOAT) || (type == PHY_DOUBLE));
     320                        }
     321
     322                        unLockReadOnlyVertexBase(part);
     323                }
     324
     325                serializer->finalizeChunk(chunk,"btMeshPartData",BT_ARRAY_CODE,chunk->m_oldPtr);
     326        }
     327
     328
     329        m_scaling.serializeFloat(trimeshData->m_scaling);
     330        return "btStridingMeshInterfaceData";
     331}
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btStridingMeshInterface.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2020#include "btTriangleCallback.h"
    2121#include "btConcaveShape.h"
     22
     23
    2224
    2325
     
    9092                }
    9193
    92        
     94                virtual int     calculateSerializeBufferSize() const;
     95
     96                ///fills the dataBuffer and returns the struct name (and 0 on failure)
     97                virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     98
    9399
    94100};
    95101
     102struct  btIntIndexData
     103{
     104        int     m_value;
     105};
     106
     107struct  btShortIntIndexData
     108{
     109        short m_value;
     110        char m_pad[2];
     111};
     112
     113struct  btShortIntIndexTripletData
     114{
     115        short   m_values[3];
     116        char    m_pad[2];
     117};
     118
     119///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     120struct  btMeshPartData
     121{
     122        btVector3FloatData                      *m_vertices3f;
     123        btVector3DoubleData                     *m_vertices3d;
     124
     125        btIntIndexData                          *m_indices32;
     126        btShortIntIndexTripletData      *m_3indices16;
     127
     128        btShortIntIndexData                     *m_indices16;//backwards compatibility
     129
     130        int                     m_numTriangles;//length of m_indices = m_numTriangles
     131        int                     m_numVertices;
     132};
     133
     134
     135///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     136struct  btStridingMeshInterfaceData
     137{
     138        btMeshPartData  *m_meshPartsPtr;
     139        btVector3FloatData      m_scaling;
     140        int     m_numMeshParts;
     141        char m_padding[4];
     142};
     143
     144
     145
     146
     147SIMD_FORCE_INLINE       int     btStridingMeshInterface::calculateSerializeBufferSize() const
     148{
     149        return sizeof(btStridingMeshInterfaceData);
     150}
     151
     152
     153
    96154#endif //STRIDING_MESHINTERFACE_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTetrahedronShape.cpp

    r5781 r8284  
    1 
    21/*
    32Bullet Continuous Collision Detection and Physics Library
    4 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    54
    65This software is provided 'as-is', without any express or implied warranty.
     
    14133. This notice may not be removed or altered from any source distribution.
    1514*/
     15
    1616#include "btTetrahedronShape.h"
    1717#include "LinearMath/btMatrix3x3.h"
    1818
    19 btBU_Simplex1to4::btBU_Simplex1to4() : btPolyhedralConvexShape (),
    20 m_numVertices(0)
    21 {
    22         m_shapeType = TETRAHEDRAL_SHAPE_PROXYTYPE;
    23 }
    24 
    25 btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0) : btPolyhedralConvexShape (),
    26 m_numVertices(0)
    27 {
    28         m_shapeType = TETRAHEDRAL_SHAPE_PROXYTYPE;
    29         addVertex(pt0);
    30 }
    31 
    32 btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0,const btVector3& pt1) : btPolyhedralConvexShape (),
     19btBU_Simplex1to4::btBU_Simplex1to4() : btPolyhedralConvexAabbCachingShape (),
     20m_numVertices(0)
     21{
     22        m_shapeType = TETRAHEDRAL_SHAPE_PROXYTYPE;
     23}
     24
     25btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0) : btPolyhedralConvexAabbCachingShape (),
     26m_numVertices(0)
     27{
     28        m_shapeType = TETRAHEDRAL_SHAPE_PROXYTYPE;
     29        addVertex(pt0);
     30}
     31
     32btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0,const btVector3& pt1) : btPolyhedralConvexAabbCachingShape (),
    3333m_numVertices(0)
    3434{
     
    3838}
    3939
    40 btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0,const btVector3& pt1,const btVector3& pt2) : btPolyhedralConvexShape (),
     40btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0,const btVector3& pt1,const btVector3& pt2) : btPolyhedralConvexAabbCachingShape (),
    4141m_numVertices(0)
    4242{
     
    4747}
    4848
    49 btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0,const btVector3& pt1,const btVector3& pt2,const btVector3& pt3) : btPolyhedralConvexShape (),
     49btBU_Simplex1to4::btBU_Simplex1to4(const btVector3& pt0,const btVector3& pt1,const btVector3& pt2,const btVector3& pt3) : btPolyhedralConvexAabbCachingShape (),
    5050m_numVertices(0)
    5151{
     
    5858
    5959
     60void btBU_Simplex1to4::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
     61{
     62#if 1
     63        btPolyhedralConvexAabbCachingShape::getAabb(t,aabbMin,aabbMax);
     64#else
     65        aabbMin.setValue(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT);
     66        aabbMax.setValue(-BT_LARGE_FLOAT,-BT_LARGE_FLOAT,-BT_LARGE_FLOAT);
     67
     68        //just transform the vertices in worldspace, and take their AABB
     69        for (int i=0;i<m_numVertices;i++)
     70        {
     71                btVector3 worldVertex = t(m_vertices[i]);
     72                aabbMin.setMin(worldVertex);
     73                aabbMax.setMax(worldVertex);
     74        }
     75#endif
     76}
     77
     78
    6079
    6180
     
    6483{
    6584        m_vertices[m_numVertices++] = pt;
    66 
    6785        recalcLocalAabb();
    6886}
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTetrahedronShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2323
    2424///The btBU_Simplex1to4 implements tetrahedron, triangle, line, vertex collision shapes. In most cases it is better to use btConvexHullShape instead.
    25 class btBU_Simplex1to4 : public btPolyhedralConvexShape
     25class btBU_Simplex1to4 : public btPolyhedralConvexAabbCachingShape
    2626{
    2727protected:
     
    4444        }
    4545       
    46 
     46        virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
    4747
    4848        void addVertex(const btVector3& pt);
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleBuffer.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleBuffer.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleCallback.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleCallback.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleIndexVertexArray.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
    66In no event will the authors be held liable for any damages arising from the use of this software.
    7 Permission is granted to anyone to use this software for any purpose,
    8 including commercial applications, and to alter it and redistribute it freely,
     7Permission is granted to anyone to use this software for any purpose, 
     8including commercial applications, and to alter it and redistribute it freely, 
    99subject to the following restrictions:
    1010
     
    4545        numverts = mesh.m_numVertices;
    4646        (*vertexbase) = (unsigned char *) mesh.m_vertexBase;
    47         #ifdef BT_USE_DOUBLE_PRECISION
    48         type = PHY_DOUBLE;
    49         #else
    50         type = PHY_FLOAT;
    51         #endif
     47
     48   type = mesh.m_vertexType;
     49
    5250        vertexStride = mesh.m_vertexStride;
    5351
     
    6563        numverts = mesh.m_numVertices;
    6664        (*vertexbase) = (const unsigned char *)mesh.m_vertexBase;
    67         #ifdef BT_USE_DOUBLE_PRECISION
    68         type = PHY_DOUBLE;
    69         #else
    70         type = PHY_FLOAT;
    71         #endif
     65
     66   type = mesh.m_vertexType;
     67   
    7268        vertexStride = mesh.m_vertexStride;
    7369
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2828        BT_DECLARE_ALIGNED_ALLOCATOR();
    2929
    30         int                     m_numTriangles;
    31         const unsigned char *           m_triangleIndexBase;
    32         int                     m_triangleIndexStride;
    33         int                     m_numVertices;
    34         const unsigned char *           m_vertexBase;
    35         int                     m_vertexStride;
    36         // The index type is set when adding an indexed mesh to the
    37         // btTriangleIndexVertexArray, do not set it manually
    38         PHY_ScalarType          m_indexType;
    39         int                     pad;
     30   int                     m_numTriangles;
     31   const unsigned char *   m_triangleIndexBase;
     32   int                     m_triangleIndexStride;
     33   int                     m_numVertices;
     34   const unsigned char *   m_vertexBase;
     35   int                     m_vertexStride;
     36
     37   // The index type is set when adding an indexed mesh to the
     38   // btTriangleIndexVertexArray, do not set it manually
     39   PHY_ScalarType m_indexType;
     40
     41   // The vertex type has a default type similar to Bullet's precision mode (float or double)
     42   // but can be set manually if you for example run Bullet with double precision but have
     43   // mesh data in single precision..
     44   PHY_ScalarType m_vertexType;
     45
     46
     47   btIndexedMesh()
     48           :m_indexType(PHY_INTEGER),
     49#ifdef BT_USE_DOUBLE_PRECISION
     50      m_vertexType(PHY_DOUBLE)
     51#else // BT_USE_DOUBLE_PRECISION
     52      m_vertexType(PHY_FLOAT)
     53#endif // BT_USE_DOUBLE_PRECISION
     54      {
     55      }
    4056}
    4157;
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp

    r5781 r8284  
    1 
    21/*
    32Bullet Continuous Collision Detection and Physics Library
    4 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    54
    65This software is provided 'as-is', without any express or implied warranty.
    76In no event will the authors be held liable for any damages arising from the use of this software.
    8 Permission is granted to anyone to use this software for any purpose,
    9 including commercial applications, and to alter it and redistribute it freely,
     7Permission is granted to anyone to use this software for any purpose, 
     8including commercial applications, and to alter it and redistribute it freely, 
    109subject to the following restrictions:
    1110
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleMesh.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516
    1617#include "btTriangleMesh.h"
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleMesh.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
    15 
    1615
    1716#ifndef TRIANGLE_MESH_H
     
    4241                btTriangleMesh (bool use32bitIndices=true,bool use4componentVertices=true);
    4342
    44                 int             findOrAddVertex(const btVector3& vertex, bool removeDuplicateVertices);
    45                 void    addIndex(int index);
    46 
    4743                bool    getUse32bitIndices() const
    4844                {
     
    6359                virtual void    preallocateIndices(int numindices){(void) numindices;}
    6460
     61                ///findOrAddVertex is an internal method, use addTriangle instead
     62                int             findOrAddVertex(const btVector3& vertex, bool removeDuplicateVertices);
     63                ///addIndex is an internal method, use addTriangle instead
     64                void    addIndex(int index);
    6565               
    6666};
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleMeshShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    9292
    9393        SupportVertexCallback(const btVector3& supportVecWorld,const btTransform& trans)
    94                 : m_supportVertexLocal(btScalar(0.),btScalar(0.),btScalar(0.)), m_worldTrans(trans) ,m_maxDot(btScalar(-1e30))
     94                : m_supportVertexLocal(btScalar(0.),btScalar(0.),btScalar(0.)), m_worldTrans(trans) ,m_maxDot(btScalar(-BT_LARGE_FLOAT))
    9595               
    9696        {
     
    200200        SupportVertexCallback supportCallback(vec,ident);
    201201
    202         btVector3 aabbMax(btScalar(1e30),btScalar(1e30),btScalar(1e30));
     202        btVector3 aabbMax(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
    203203       
    204204        processAllTriangles(&supportCallback,-aabbMax,aabbMax);
     
    208208        return supportVertex;
    209209}
     210
     211
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleMeshShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    8080        virtual const char*     getName()const {return "TRIANGLEMESH";}
    8181
     82       
    8283
    8384};
    8485
     86
     87
     88
    8589#endif //TRIANGLE_MESH_SHAPE_H
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btTriangleShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2020#include "btBoxShape.h"
    2121
    22 class btTriangleShape : public btPolyhedralConvexShape
     22ATTRIBUTE_ALIGNED16(class) btTriangleShape : public btPolyhedralConvexShape
    2323{
    2424
     
    3131        {
    3232                return 3;
     33        }
     34
     35        btVector3& getVertexPtr(int index)
     36        {
     37                return m_vertices1[index];
    3338        }
    3439
     
    7883        }
    7984
    80 
     85        btTriangleShape() : btPolyhedralConvexShape ()
     86    {
     87                m_shapeType = TRIANGLE_SHAPE_PROXYTYPE;
     88        }
    8189
    8290        btTriangleShape(const btVector3& p0,const btVector3& p1,const btVector3& p2) : btPolyhedralConvexShape ()
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btUniformScalingShape.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2007 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/CollisionShapes/btUniformScalingShape.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp

    r5781 r8284  
    9797        {
    9898               
    99                 btGjkPairDetector gjk(m_convexA,m_convexB,m_simplexSolver,m_penetrationDepthSolver);           
     99                btGjkPairDetector gjk(m_convexA,m_convexB,m_convexA->getShapeType(),m_convexB->getShapeType(),m_convexA->getMargin(),m_convexB->getMargin(),m_simplexSolver,m_penetrationDepthSolver);         
    100100                btGjkPairDetector::ClosestPointInput input;
    101101       
     
    122122                while (dist > radius)
    123123                {
     124                        if (result.m_debugDrawer)
     125                        {
     126                                result.m_debugDrawer->drawSphere(c,0.2f,btVector3(1,1,1));
     127                        }
    124128                        numIter++;
    125129                        if (numIter > maxIter)
     
    170174                        btTransformUtil::integrateTransform(fromB,linVelB,angVelB,lambda,interpolatedTransB);
    171175                        relativeTrans = interpolatedTransB.inverseTimes(interpolatedTransA);
     176
     177                        if (result.m_debugDrawer)
     178                        {
     179                                result.m_debugDrawer->drawSphere(interpolatedTransA.getOrigin(),0.2f,btVector3(1,0,0));
     180                        }
    172181
    173182                        result.DebugDraw( lambda );
     
    198207                                return false;
    199208                        }
     209                       
    200210
    201211                }
     
    225235
    226236}
    227 
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btConvexCast.h

    r5781 r8284  
    4242
    4343                CastResult()
    44                         :m_fraction(btScalar(1e30)),
     44                        :m_fraction(btScalar(BT_LARGE_FLOAT)),
    4545                        m_debugDrawer(0),
    4646                        m_allowedPenetration(btScalar(0))
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h

    r5781 r8284  
    1515
    1616
    17 #ifndef CONVEX_PENETRATION_DEPTH_H
    18 #define CONVEX_PENETRATION_DEPTH_H
     17#ifndef __CONVEX_PENETRATION_DEPTH_H
     18#define __CONVEX_PENETRATION_DEPTH_H
    1919
    2020class btStackAlloc;
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h

    r5781 r8284  
    3434                virtual ~Result(){}     
    3535
    36                 ///setShapeIdentifiers provides experimental support for per-triangle material / custom material combiner
    37                 virtual void setShapeIdentifiers(int partId0,int index0,        int partId1,int index1)=0;
     36                ///setShapeIdentifiersA/B provides experimental support for per-triangle material / custom material combiner
     37                virtual void setShapeIdentifiersA(int partId0,int index0)=0;
     38                virtual void setShapeIdentifiersB(int partId1,int index1)=0;
    3839                virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth)=0;
    3940        };
     
    4243        {
    4344                ClosestPointInput()
    44                         :m_maximumDistanceSquared(btScalar(1e30)),
     45                        :m_maximumDistanceSquared(btScalar(BT_LARGE_FLOAT)),
    4546                        m_stackAlloc(0)
    4647                {
     
    6970                btScalar        m_distance; //negative means penetration !
    7071
    71                 btStorageResult() : m_distance(btScalar(1e30))
     72                btStorageResult() : m_distance(btScalar(BT_LARGE_FLOAT))
    7273                {
    7374
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp

    r5781 r8284  
    6969                btMatrix3x3                             m_toshape1;
    7070                btTransform                             m_toshape0;
     71#ifdef __SPU__
     72                bool                                    m_enableMargin;
     73#else
    7174                btVector3                               (btConvexShape::*Ls)(const btVector3&) const;
     75#endif//__SPU__
     76               
     77
     78                MinkowskiDiff()
     79                {
     80
     81                }
     82#ifdef __SPU__
     83                        void                                    EnableMargin(bool enable)
     84                {
     85                        m_enableMargin = enable;
     86                }       
     87                inline btVector3                Support0(const btVector3& d) const
     88                {
     89                        if (m_enableMargin)
     90                        {
     91                                return m_shapes[0]->localGetSupportVertexNonVirtual(d);
     92                        } else
     93                        {
     94                                return m_shapes[0]->localGetSupportVertexWithoutMarginNonVirtual(d);
     95                        }
     96                }
     97                inline btVector3                Support1(const btVector3& d) const
     98                {
     99                        if (m_enableMargin)
     100                        {
     101                                return m_toshape0*(m_shapes[1]->localGetSupportVertexNonVirtual(m_toshape1*d));
     102                        } else
     103                        {
     104                                return m_toshape0*(m_shapes[1]->localGetSupportVertexWithoutMarginNonVirtual(m_toshape1*d));
     105                        }
     106                }
     107#else
    72108                void                                    EnableMargin(bool enable)
    73109                {
     
    85121                        return(m_toshape0*((m_shapes[1])->*(Ls))(m_toshape1*d));
    86122                }
     123#endif //__SPU__
     124
    87125                inline btVector3                Support(const btVector3& d) const
    88126                {
     
    203241                                        }
    204242                                        /* Check for termination                                */
    205                                         const btScalar  omega=dot(m_ray,w)/rl;
     243                                        const btScalar  omega=btDot(m_ray,w)/rl;
    206244                                        alpha=btMax(omega,alpha);
    207245                                        if(((rl-alpha)-(GJK_ACCURARY*rl))<=0)
     
    260298                                case    eStatus::Valid:         m_distance=m_ray.length();break;
    261299                                case    eStatus::Inside:        m_distance=0;break;
     300                                default:
     301                                        {
     302                                        }
    262303                                }       
    263304                                return(m_status);
     
    289330                                                        btVector3               axis=btVector3(0,0,0);
    290331                                                        axis[i]=1;
    291                                                         const btVector3 p=cross(d,axis);
     332                                                        const btVector3 p=btCross(d,axis);
    292333                                                        if(p.length2()>0)
    293334                                                        {
     
    304345                                case    3:
    305346                                        {
    306                                                 const btVector3 n=cross(m_simplex->c[1]->w-m_simplex->c[0]->w,
     347                                                const btVector3 n=btCross(m_simplex->c[1]->w-m_simplex->c[0]->w,
    307348                                                        m_simplex->c[2]->w-m_simplex->c[0]->w);
    308349                                                if(n.length2()>0)
     
    358399                                if(l>GJK_SIMPLEX2_EPS)
    359400                                {
    360                                         const btScalar  t(l>0?-dot(a,d)/l:0);
     401                                        const btScalar  t(l>0?-btDot(a,d)/l:0);
    361402                                        if(t>=1)                { w[0]=0;w[1]=1;m=2;return(b.length2()); }
    362403                                        else if(t<=0)   { w[0]=1;w[1]=0;m=1;return(a.length2()); }
     
    373414                                const btVector3*        vt[]={&a,&b,&c};
    374415                                const btVector3         dl[]={a-b,b-c,c-a};
    375                                 const btVector3         n=cross(dl[0],dl[1]);
     416                                const btVector3         n=btCross(dl[0],dl[1]);
    376417                                const btScalar          l=n.length2();
    377418                                if(l>GJK_SIMPLEX3_EPS)
    378419                                {
    379420                                        btScalar        mindist=-1;
    380                                         btScalar        subw[2];
    381                                         U                       subm;
     421                                        btScalar        subw[2]={0.f,0.f};
     422                                        U                       subm(0);
    382423                                        for(U i=0;i<3;++i)
    383424                                        {
    384                                                 if(dot(*vt[i],cross(dl[i],n))>0)
     425                                                if(btDot(*vt[i],btCross(dl[i],n))>0)
    385426                                                {
    386427                                                        const U                 j=imd3[i];
     
    398439                                        if(mindist<0)
    399440                                        {
    400                                                 const btScalar  d=dot(a,n);     
     441                                                const btScalar  d=btDot(a,n);   
    401442                                                const btScalar  s=btSqrt(l);
    402443                                                const btVector3 p=n*(d/l);
    403444                                                mindist =       p.length2();
    404445                                                m               =       7;
    405                                                 w[0]    =       (cross(dl[1],b-p)).length()/s;
    406                                                 w[1]    =       (cross(dl[2],c-p)).length()/s;
     446                                                w[0]    =       (btCross(dl[1],b-p)).length()/s;
     447                                                w[1]    =       (btCross(dl[2],c-p)).length()/s;
    407448                                                w[2]    =       1-(w[0]+w[1]);
    408449                                        }
     
    421462                                const btVector3         dl[]={a-d,b-d,c-d};
    422463                                const btScalar          vl=det(dl[0],dl[1],dl[2]);
    423                                 const bool                      ng=(vl*dot(a,cross(b-c,a-b)))<=0;
     464                                const bool                      ng=(vl*btDot(a,btCross(b-c,a-b)))<=0;
    424465                                if(ng&&(btFabs(vl)>GJK_SIMPLEX4_EPS))
    425466                                {
    426467                                        btScalar        mindist=-1;
    427                                         btScalar        subw[3];
    428                                         U                       subm;
     468                                        btScalar        subw[3]={0.f,0.f,0.f};
     469                                        U                       subm(0);
    429470                                        for(U i=0;i<3;++i)
    430471                                        {
    431472                                                const U                 j=imd3[i];
    432                                                 const btScalar  s=vl*dot(d,cross(dl[i],dl[j]));
     473                                                const btScalar  s=vl*btDot(d,btCross(dl[i],dl[j]));
    433474                                                if(s>0)
    434475                                                {
     
    602643                                                                best->pass      =       (U1)(++pass);
    603644                                                                gjk.getsupport(best->n,*w);
    604                                                                 const btScalar  wdist=dot(best->n,w->w)-best->d;
     645                                                                const btScalar  wdist=btDot(best->n,w->w)-best->d;
    605646                                                                if(wdist>EPA_ACCURACY)
    606647                                                                {
     
    629670                                                m_result.c[1]   =       outer.c[1];
    630671                                                m_result.c[2]   =       outer.c[2];
    631                                                 m_result.p[0]   =       cross(  outer.c[1]->w-projection,
     672                                                m_result.p[0]   =       btCross(        outer.c[1]->w-projection,
    632673                                                        outer.c[2]->w-projection).length();
    633                                                 m_result.p[1]   =       cross(  outer.c[2]->w-projection,
     674                                                m_result.p[1]   =       btCross(        outer.c[2]->w-projection,
    634675                                                        outer.c[0]->w-projection).length();
    635                                                 m_result.p[2]   =       cross(  outer.c[0]->w-projection,
     676                                                m_result.p[2]   =       btCross(        outer.c[0]->w-projection,
    636677                                                        outer.c[1]->w-projection).length();
    637678                                                const btScalar  sum=m_result.p[0]+m_result.p[1]+m_result.p[2];
     
    667708                                        face->c[1]      =       b;
    668709                                        face->c[2]      =       c;
    669                                         face->n         =       cross(b->w-a->w,c->w-a->w);
     710                                        face->n         =       btCross(b->w-a->w,c->w-a->w);
    670711                                        const btScalar  l=face->n.length();
    671712                                        const bool              v=l>EPA_ACCURACY;
    672713                                        face->p         =       btMin(btMin(
    673                                                 dot(a->w,cross(face->n,a->w-b->w)),
    674                                                 dot(b->w,cross(face->n,b->w-c->w))),
    675                                                 dot(c->w,cross(face->n,c->w-a->w)))     /
     714                                                btDot(a->w,btCross(face->n,a->w-b->w)),
     715                                                btDot(b->w,btCross(face->n,b->w-c->w))),
     716                                                btDot(c->w,btCross(face->n,c->w-a->w))) /
    676717                                                (v?l:1);
    677718                                        face->p         =       face->p>=-EPA_INSIDE_EPS?0:face->p;
    678719                                        if(v)
    679720                                        {
    680                                                 face->d         =       dot(a->w,face->n)/l;
     721                                                face->d         =       btDot(a->w,face->n)/l;
    681722                                                face->n         /=      l;
    682723                                                if(forced||(face->d>=-EPA_PLANE_EPS))
     
    716757                                {
    717758                                        const U e1=i1m3[e];
    718                                         if((dot(f->n,w->w)-f->d)<-EPA_PLANE_EPS)
     759                                        if((btDot(f->n,w->w)-f->d)<-EPA_PLANE_EPS)
    719760                                        {
    720761                                                sFace*  nf=newface(f->c[e1],f->c[e],w,false);
     
    855896                results.status=sResults::GJK_Failed;
    856897                break;
     898                default:
     899                                        {
     900                                        }
    857901        }
    858902        return(false);
    859903}
    860904
     905#ifndef __SPU__
    861906//
    862907btScalar        btGjkEpaSolver2::SignedDistance(const btVector3& position,
     
    924969                return(true);
    925970}
     971#endif //__SPU__
    926972
    927973/* Symbols cleanup              */
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h

    r5781 r8284  
    5656                                                        sResults& results,
    5757                                                        bool usemargins=true);
    58 
     58#ifndef __SPU__
    5959static btScalar SignedDistance( const btVector3& position,
    6060                                                                btScalar margin,
     
    6767                                                                const btVector3& guess,
    6868                                                                sResults& results);
     69#endif //__SPU__
     70
    6971};
    7072
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.cpp

    r5781 r8284  
    3333        (void)simplexSolver;
    3434
    35         const btScalar                          radialmargin(btScalar(0.));
     35//      const btScalar                          radialmargin(btScalar(0.));
    3636       
    3737        btVector3       guessVector(transformA.getOrigin()-transformB.getOrigin());
    3838        btGjkEpaSolver2::sResults       results;
     39       
     40
    3941        if(btGjkEpaSolver2::Penetration(pConvexA,transformA,
    4042                                                                pConvexB,transformB,
     
    4648                wWitnessOnA = results.witnesses[0];
    4749                wWitnessOnB = results.witnesses[1];
     50                v = results.normal;
    4851                return true;           
     52                } else
     53        {
     54                if(btGjkEpaSolver2::Distance(pConvexA,transformA,pConvexB,transformB,guessVector,results))
     55                {
     56                        wWitnessOnA = results.witnesses[0];
     57                        wWitnessOnB = results.witnesses[1];
     58                        v = results.normal;
     59                        return false;
    4960                }
     61        }
    5062
    5163        return false;
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h

    r5781 r8284  
    2626        public :
    2727
     28                btGjkEpaPenetrationDepthSolver()
     29                {
     30                }
     31
    2832                bool                    calcPenDepth( btSimplexSolverInterface& simplexSolver,
    2933                                                                          const btConvexShape* pConvexA, const btConvexShape* pConvexB,
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.cpp

    r5781 r8284  
    3939
    4040
    41 
    4241btGjkPairDetector::btGjkPairDetector(const btConvexShape* objectA,const btConvexShape* objectB,btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver*  penetrationDepthSolver)
    43 :m_cachedSeparatingAxis(btScalar(0.),btScalar(0.),btScalar(1.)),
     42:m_cachedSeparatingAxis(btScalar(0.),btScalar(1.),btScalar(0.)),
    4443m_penetrationDepthSolver(penetrationDepthSolver),
    4544m_simplexSolver(simplexSolver),
    4645m_minkowskiA(objectA),
    4746m_minkowskiB(objectB),
     47m_shapeTypeA(objectA->getShapeType()),
     48m_shapeTypeB(objectB->getShapeType()),
     49m_marginA(objectA->getMargin()),
     50m_marginB(objectB->getMargin()),
    4851m_ignoreMargin(false),
    4952m_lastUsedMethod(-1),
     
    5154{
    5255}
    53 
    54 void btGjkPairDetector::getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults)
     56btGjkPairDetector::btGjkPairDetector(const btConvexShape* objectA,const btConvexShape* objectB,int shapeTypeA,int shapeTypeB,btScalar marginA, btScalar marginB, btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver*        penetrationDepthSolver)
     57:m_cachedSeparatingAxis(btScalar(0.),btScalar(1.),btScalar(0.)),
     58m_penetrationDepthSolver(penetrationDepthSolver),
     59m_simplexSolver(simplexSolver),
     60m_minkowskiA(objectA),
     61m_minkowskiB(objectB),
     62m_shapeTypeA(shapeTypeA),
     63m_shapeTypeB(shapeTypeB),
     64m_marginA(marginA),
     65m_marginB(marginB),
     66m_ignoreMargin(false),
     67m_lastUsedMethod(-1),
     68m_catchDegeneracies(1)
     69{
     70}
     71
     72void    btGjkPairDetector::getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults)
     73{
     74        (void)swapResults;
     75
     76        getClosestPointsNonVirtual(input,output,debugDraw);
     77}
     78
     79#ifdef __SPU__
     80void btGjkPairDetector::getClosestPointsNonVirtual(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw)
     81#else
     82void btGjkPairDetector::getClosestPointsNonVirtual(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw)
     83#endif
    5584{
    5685        m_cachedSeparatingDistance = 0.f;
     
    6594        localTransB.getOrigin() -= positionOffset;
    6695
    67 #ifdef __SPU__
    68         btScalar marginA = m_minkowskiA->getMarginNonVirtual();
    69         btScalar marginB = m_minkowskiB->getMarginNonVirtual();
    70 #else
    71         btScalar marginA = m_minkowskiA->getMargin();
    72         btScalar marginB = m_minkowskiB->getMargin();
    73 #ifdef TEST_NON_VIRTUAL
    74         btScalar marginAv = m_minkowskiA->getMarginNonVirtual();
    75         btScalar marginBv = m_minkowskiB->getMarginNonVirtual();
    76         btAssert(marginA == marginAv);
    77         btAssert(marginB == marginBv);
    78 #endif //TEST_NON_VIRTUAL
    79 #endif
    80        
    81 
     96        bool check2d = m_minkowskiA->isConvex2d() && m_minkowskiB->isConvex2d();
     97
     98        btScalar marginA = m_marginA;
     99        btScalar marginB = m_marginB;
    82100
    83101        gNumGjkChecks++;
     
    108126
    109127        {
    110                 btScalar squaredDistance = SIMD_INFINITY;
     128                btScalar squaredDistance = BT_LARGE_FLOAT;
    111129                btScalar delta = btScalar(0.);
    112130               
     
    124142                        btVector3 seperatingAxisInB = m_cachedSeparatingAxis* input.m_transformB.getBasis();
    125143
     144#if 1
     145
     146                        btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInA);
     147                        btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInB);
     148
     149//                      btVector3 pInA  = localGetSupportingVertexWithoutMargin(m_shapeTypeA, m_minkowskiA, seperatingAxisInA,input.m_convexVertexData[0]);//, &featureIndexA);
     150//                      btVector3 qInB  = localGetSupportingVertexWithoutMargin(m_shapeTypeB, m_minkowskiB, seperatingAxisInB,input.m_convexVertexData[1]);//, &featureIndexB);
     151
     152#else
    126153#ifdef __SPU__
    127154                        btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInA);
     
    137164#endif //
    138165#endif //__SPU__
     166#endif
     167
    139168
    140169                        btVector3  pWorld = localTransA(pInA); 
     
    145174#endif
    146175
     176                        if (check2d)
     177                        {
     178                                pWorld[2] = 0.f;
     179                                qWorld[2] = 0.f;
     180                        }
     181
    147182                        btVector3 w     = pWorld - qWorld;
    148183                        delta = m_cachedSeparatingAxis.dot(w);
     
    151186                        if ((delta > btScalar(0.0)) && (delta * delta > squaredDistance * input.m_maximumDistanceSquared))
    152187                        {
     188                                m_degenerateSimplex = 10;
    153189                                checkSimplex=true;
    154190                                //checkPenetration = false;
     
    172208                                {
    173209                                        m_degenerateSimplex = 2;
     210                                } else
     211                                {
     212                                        m_degenerateSimplex = 11;
    174213                                }
    175214                                checkSimplex = true;
     
    185224                spu_printf("addVertex 2\n");
    186225#endif
     226                        btVector3 newCachedSeparatingAxis;
     227
    187228                        //calculate the closest point to the origin (update vector v)
    188                         if (!m_simplexSolver->closest(m_cachedSeparatingAxis))
     229                        if (!m_simplexSolver->closest(newCachedSeparatingAxis))
    189230                        {
    190231                                m_degenerateSimplex = 3;
     
    193234                        }
    194235
    195                         if(m_cachedSeparatingAxis.length2()<REL_ERROR2)
     236                        if(newCachedSeparatingAxis.length2()<REL_ERROR2)
    196237            {
     238                                m_cachedSeparatingAxis = newCachedSeparatingAxis;
    197239                m_degenerateSimplex = 6;
    198240                checkSimplex = true;
     
    201243
    202244                        btScalar previousSquaredDistance = squaredDistance;
    203                         squaredDistance = m_cachedSeparatingAxis.length2();
     245                        squaredDistance = newCachedSeparatingAxis.length2();
     246#if 0
     247///warning: this termination condition leads to some problems in 2d test case see Bullet/Demos/Box2dDemo
     248                        if (squaredDistance>previousSquaredDistance)
     249                        {
     250                                m_degenerateSimplex = 7;
     251                                squaredDistance = previousSquaredDistance;
     252                checkSimplex = false;
     253                break;
     254                        }
     255#endif //
    204256                       
     257                        m_cachedSeparatingAxis = newCachedSeparatingAxis;
     258
    205259                        //redundant m_simplexSolver->compute_points(pointOnA, pointOnB);
    206260
     
    210264                                m_simplexSolver->backup_closest(m_cachedSeparatingAxis);
    211265                                checkSimplex = true;
     266                                m_degenerateSimplex = 12;
     267                               
    212268                                break;
    213269                        }
     
    240296                                //do we need this backup_closest here ?
    241297                                m_simplexSolver->backup_closest(m_cachedSeparatingAxis);
     298                                m_degenerateSimplex = 13;
    242299                                break;
    243300                        }
     
    248305                        m_simplexSolver->compute_points(pointOnA, pointOnB);
    249306                        normalInB = pointOnA-pointOnB;
    250                         btScalar lenSqr = m_cachedSeparatingAxis.length2();
     307                        btScalar lenSqr =m_cachedSeparatingAxis.length2();
     308                       
    251309                        //valid normal
    252310                        if (lenSqr < 0.0001)
     
    280338                {
    281339                        //penetration case
    282                
     340
    283341                        //if there is no way to handle penetrations, bail out
    284342                        if (m_penetrationDepthSolver)
     
    288346                               
    289347                                gNumDeepPenetrationChecks++;
     348                                m_cachedSeparatingAxis.setZero();
    290349
    291350                                bool isValid2 = m_penetrationDepthSolver->calcPenDepth(
     
    297356                                        );
    298357
     358
    299359                                if (isValid2)
    300360                                {
    301361                                        btVector3 tmpNormalInB = tmpPointOnB-tmpPointOnA;
    302362                                        btScalar lenSqr = tmpNormalInB.length2();
     363                                        if (lenSqr <= (SIMD_EPSILON*SIMD_EPSILON))
     364                                        {
     365                                                tmpNormalInB = m_cachedSeparatingAxis;
     366                                                lenSqr = m_cachedSeparatingAxis.length2();
     367                                        }
     368
    303369                                        if (lenSqr > (SIMD_EPSILON*SIMD_EPSILON))
    304370                                        {
     
    316382                                                } else
    317383                                                {
    318                                                        
     384                                                        m_lastUsedMethod = 8;
    319385                                                }
    320386                                        } else
    321387                                        {
    322                                                 //isValid = false;
    323                                                 m_lastUsedMethod = 4;
     388                                                m_lastUsedMethod = 9;
    324389                                        }
    325390                                } else
     391
    326392                                {
    327                                         m_lastUsedMethod = 5;
     393                                        ///this is another degenerate case, where the initial GJK calculation reports a degenerate case
     394                                        ///EPA reports no penetration, and the second GJK (using the supporting vector without margin)
     395                                        ///reports a valid positive distance. Use the results of the second GJK instead of failing.
     396                                        ///thanks to Jacob.Langford for the reproduction case
     397                                        ///http://code.google.com/p/bullet/issues/detail?id=250
     398
     399                               
     400                                        if (m_cachedSeparatingAxis.length2() > btScalar(0.))
     401                                        {
     402                                                btScalar distance2 = (tmpPointOnA-tmpPointOnB).length()-margin;
     403                                                //only replace valid distances when the distance is less
     404                                                if (!isValid || (distance2 < distance))
     405                                                {
     406                                                        distance = distance2;
     407                                                        pointOnA = tmpPointOnA;
     408                                                        pointOnB = tmpPointOnB;
     409                                                        pointOnA -= m_cachedSeparatingAxis * marginA ;
     410                                                        pointOnB += m_cachedSeparatingAxis * marginB ;
     411                                                        normalInB = m_cachedSeparatingAxis;
     412                                                        normalInB.normalize();
     413                                                        isValid = true;
     414                                                        m_lastUsedMethod = 6;
     415                                                } else
     416                                                {
     417                                                        m_lastUsedMethod = 5;
     418                                                }
     419                                        }
    328420                                }
    329421                               
    330422                        }
     423
    331424                }
    332425        }
    333426
    334         if (isValid)
     427       
     428
     429        if (isValid && ((distance < 0) || (distance*distance < input.m_maximumDistanceSquared)))
    335430        {
    336 #ifdef __SPU__
    337                 //spu_printf("distance\n");
    338 #endif //__CELLOS_LV2__
    339 
    340 
    341 #ifdef DEBUG_SPU_COLLISION_DETECTION
    342                 spu_printf("output 1\n");
    343 #endif
     431#if 0
     432///some debugging
     433//              if (check2d)
     434                {
     435                        printf("n = %2.3f,%2.3f,%2.3f. ",normalInB[0],normalInB[1],normalInB[2]);
     436                        printf("distance = %2.3f exit=%d deg=%d\n",distance,m_lastUsedMethod,m_degenerateSimplex);
     437                }
     438#endif
     439
    344440                m_cachedSeparatingAxis = normalInB;
    345441                m_cachedSeparatingDistance = distance;
     
    350446                        distance);
    351447
    352 #ifdef DEBUG_SPU_COLLISION_DETECTION
    353                 spu_printf("output 2\n");
    354 #endif
    355                 //printf("gjk add:%f",distance);
    356448        }
    357449
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h

    r5781 r8284  
    3737        const btConvexShape* m_minkowskiA;
    3838        const btConvexShape* m_minkowskiB;
     39        int     m_shapeTypeA;
     40        int m_shapeTypeB;
     41        btScalar        m_marginA;
     42        btScalar        m_marginB;
     43
    3944        bool            m_ignoreMargin;
    4045        btScalar        m_cachedSeparatingDistance;
     
    5156
    5257        btGjkPairDetector(const btConvexShape* objectA,const btConvexShape* objectB,btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver*     penetrationDepthSolver);
     58        btGjkPairDetector(const btConvexShape* objectA,const btConvexShape* objectB,int shapeTypeA,int shapeTypeB,btScalar marginA, btScalar marginB, btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver*   penetrationDepthSolver);
    5359        virtual ~btGjkPairDetector() {};
    5460
    5561        virtual void    getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults=false);
     62
     63        void    getClosestPointsNonVirtual(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw);
     64       
    5665
    5766        void setMinkowskiA(btConvexShape* minkA)
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btManifoldPoint.h

    r5781 r8284  
    2020#include "LinearMath/btTransformUtil.h"
    2121
     22// Don't change following order of parameters
     23ATTRIBUTE_ALIGNED16(struct) PfxConstraintRow {
     24        btScalar mNormal[3];
     25        btScalar mRhs;
     26        btScalar mJacDiagInv;
     27        btScalar mLowerLimit;
     28        btScalar mUpperLimit;
     29        btScalar mAccumImpulse;
     30};
    2231
    2332
     
    3544                                m_appliedImpulseLateral1(0.f),
    3645                                m_appliedImpulseLateral2(0.f),
     46                                m_contactMotion1(0.f),
     47                                m_contactMotion2(0.f),
     48                                m_contactCFM1(0.f),
     49                                m_contactCFM2(0.f),
    3750                                m_lifeTime(0)
    3851                        {
     
    5366                                        m_appliedImpulseLateral1(0.f),
    5467                                        m_appliedImpulseLateral2(0.f),
     68                                        m_contactMotion1(0.f),
     69                                        m_contactMotion2(0.f),
     70                                        m_contactCFM1(0.f),
     71                                        m_contactCFM2(0.f),
    5572                                        m_lifeTime(0)
    5673                        {
    57                                
    58                                        
     74                                mConstraintRow[0].mAccumImpulse = 0.f;
     75                                mConstraintRow[1].mAccumImpulse = 0.f;
     76                                mConstraintRow[2].mAccumImpulse = 0.f;
    5977                        }
    6078
     
    84102                        btScalar                m_appliedImpulseLateral1;
    85103                        btScalar                m_appliedImpulseLateral2;
     104                        btScalar                m_contactMotion1;
     105                        btScalar                m_contactMotion2;
     106                        btScalar                m_contactCFM1;
     107                        btScalar                m_contactCFM2;
     108
    86109                        int                             m_lifeTime;//lifetime of the contactpoint in frames
    87110                       
    88111                        btVector3               m_lateralFrictionDir1;
    89112                        btVector3               m_lateralFrictionDir2;
     113
     114
     115
     116                        PfxConstraintRow mConstraintRow[3];
     117
    90118
    91119                        btScalar getDistance() const
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.cpp

    r5781 r8284  
    2121
    2222#define NUM_UNITSPHERE_POINTS 42
    23 static btVector3        sPenetrationDirections[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] =
    24 {
    25 btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)),
    26 btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)),
    27 btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)),
    28 btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)),
    29 btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)),
    30 btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)),
    31 btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)),
    32 btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)),
    33 btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)),
    34 btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)),
    35 btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)),
    36 btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)),
    37 btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)),
    38 btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)),
    39 btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)),
    40 btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)),
    41 btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)),
    42 btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)),
    43 btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)),
    44 btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)),
    45 btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)),
    46 btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)),
    47 btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)),
    48 btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)),
    49 btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)),
    50 btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)),
    51 btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)),
    52 btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)),
    53 btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)),
    54 btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)),
    55 btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)),
    56 btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)),
    57 btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)),
    58 btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)),
    59 btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)),
    60 btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)),
    61 btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)),
    62 btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)),
    63 btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)),
    64 btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)),
    65 btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)),
    66 btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654))
    67 };
    6823
    6924
     
    7934        (void)v;
    8035       
     36        bool check2d= convexA->isConvex2d() && convexB->isConvex2d();
    8137
    8238        struct btIntermediateResult : public btDiscreteCollisionDetectorInterface::Result
     
    9248                bool    m_hasResult;
    9349
    94                 virtual void setShapeIdentifiers(int partId0,int index0,        int partId1,int index1)
     50                virtual void setShapeIdentifiersA(int partId0,int index0)
    9551                {
    9652                        (void)partId0;
    9753                        (void)index0;
     54                }
     55                virtual void setShapeIdentifiersB(int partId1,int index1)
     56                {
    9857                        (void)partId1;
    9958                        (void)index1;
     
    10968
    11069        //just take fixed number of orientation, and sample the penetration depth in that direction
    111         btScalar minProj = btScalar(1e30);
     70        btScalar minProj = btScalar(BT_LARGE_FLOAT);
    11271        btVector3 minNorm(btScalar(0.), btScalar(0.), btScalar(0.));
    11372        btVector3 minA,minB;
     
    13089        for (i=0;i<numSampleDirections;i++)
    13190        {
    132                 const btVector3& norm = sPenetrationDirections[i];
     91                btVector3 norm = getPenetrationDirections()[i];
    13392                seperatingAxisInABatch[i] =  (-norm) * transA.getBasis() ;
    13493                seperatingAxisInBBatch[i] =  norm   * transB.getBasis() ;
     
    144103                                convexA->getPreferredPenetrationDirection(i,norm);
    145104                                norm  = transA.getBasis() * norm;
    146                                 sPenetrationDirections[numSampleDirections] = norm;
     105                                getPenetrationDirections()[numSampleDirections] = norm;
    147106                                seperatingAxisInABatch[numSampleDirections] = (-norm) * transA.getBasis();
    148107                                seperatingAxisInBBatch[numSampleDirections] = norm * transB.getBasis();
     
    161120                                convexB->getPreferredPenetrationDirection(i,norm);
    162121                                norm  = transB.getBasis() * norm;
    163                                 sPenetrationDirections[numSampleDirections] = norm;
     122                                getPenetrationDirections()[numSampleDirections] = norm;
    164123                                seperatingAxisInABatch[numSampleDirections] = (-norm) * transA.getBasis();
    165124                                seperatingAxisInBBatch[numSampleDirections] = norm * transB.getBasis();
     
    171130
    172131
     132
    173133        convexA->batchedUnitVectorGetSupportingVertexWithoutMargin(seperatingAxisInABatch,supportVerticesABatch,numSampleDirections);
    174134        convexB->batchedUnitVectorGetSupportingVertexWithoutMargin(seperatingAxisInBBatch,supportVerticesBBatch,numSampleDirections);
     
    176136        for (i=0;i<numSampleDirections;i++)
    177137        {
    178                 const btVector3& norm = sPenetrationDirections[i];
    179                 seperatingAxisInA = seperatingAxisInABatch[i];
    180                 seperatingAxisInB = seperatingAxisInBBatch[i];
    181 
    182                 pInA = supportVerticesABatch[i];
    183                 qInB = supportVerticesBBatch[i];
    184 
    185                 pWorld = transA(pInA); 
    186                 qWorld = transB(qInB);
    187                 w       = qWorld - pWorld;
    188                 btScalar delta = norm.dot(w);
    189                 //find smallest delta
    190                 if (delta < minProj)
    191                 {
    192                         minProj = delta;
    193                         minNorm = norm;
    194                         minA = pWorld;
    195                         minB = qWorld;
     138                btVector3 norm = getPenetrationDirections()[i];
     139                if (check2d)
     140                {
     141                        norm[2] = 0.f;
     142                }
     143                if (norm.length2()>0.01)
     144                {
     145
     146                        seperatingAxisInA = seperatingAxisInABatch[i];
     147                        seperatingAxisInB = seperatingAxisInBBatch[i];
     148
     149                        pInA = supportVerticesABatch[i];
     150                        qInB = supportVerticesBBatch[i];
     151
     152                        pWorld = transA(pInA); 
     153                        qWorld = transB(qInB);
     154                        if (check2d)
     155                        {
     156                                pWorld[2] = 0.f;
     157                                qWorld[2] = 0.f;
     158                        }
     159
     160                        w       = qWorld - pWorld;
     161                        btScalar delta = norm.dot(w);
     162                        //find smallest delta
     163                        if (delta < minProj)
     164                        {
     165                                minProj = delta;
     166                                minNorm = norm;
     167                                minA = pWorld;
     168                                minB = qWorld;
     169                        }
    196170                }
    197171        }       
     
    210184                                convexA->getPreferredPenetrationDirection(i,norm);
    211185                                norm  = transA.getBasis() * norm;
    212                                 sPenetrationDirections[numSampleDirections] = norm;
     186                                getPenetrationDirections()[numSampleDirections] = norm;
    213187                                numSampleDirections++;
    214188                        }
     
    225199                                convexB->getPreferredPenetrationDirection(i,norm);
    226200                                norm  = transB.getBasis() * norm;
    227                                 sPenetrationDirections[numSampleDirections] = norm;
     201                                getPenetrationDirections()[numSampleDirections] = norm;
    228202                                numSampleDirections++;
    229203                        }
     
    234208        for (int i=0;i<numSampleDirections;i++)
    235209        {
    236                 const btVector3& norm = sPenetrationDirections[i];
     210                const btVector3& norm = getPenetrationDirections()[i];
    237211                seperatingAxisInA = (-norm)* transA.getBasis();
    238212                seperatingAxisInB = norm* transB.getBasis();
     
    262236                return false;
    263237
    264         minProj += (convexA->getMarginNonVirtual() + convexB->getMarginNonVirtual());
     238        btScalar extraSeparation = 0.5f;///scale dependent
     239        minProj += extraSeparation+(convexA->getMarginNonVirtual() + convexB->getMarginNonVirtual());
    265240
    266241
     
    300275        input.m_transformA = displacedTrans;
    301276        input.m_transformB = transB;
    302         input.m_maximumDistanceSquared = btScalar(1e30);//minProj;
     277        input.m_maximumDistanceSquared = btScalar(BT_LARGE_FLOAT);//minProj;
    303278       
    304279        btIntermediateResult res;
     280        gjkdet.setCachedSeperatingAxis(-minNorm);
    305281        gjkdet.getClosestPoints(input,res,debugDraw);
    306282
     
    311287        btScalar penetration_relaxation= btScalar(1.);
    312288        minNorm*=penetration_relaxation;
     289       
    313290
    314291        if (res.m_hasResult)
     
    317294                pa = res.m_pointInWorld - minNorm * correctedMinNorm;
    318295                pb = res.m_pointInWorld;
     296                v = minNorm;
    319297               
    320298#ifdef DEBUG_DRAW
     
    331309}
    332310
    333 
    334 
     311btVector3*      btMinkowskiPenetrationDepthSolver::getPenetrationDirections()
     312{
     313        static btVector3        sPenetrationDirections[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] =
     314        {
     315        btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)),
     316        btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)),
     317        btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)),
     318        btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)),
     319        btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)),
     320        btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)),
     321        btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)),
     322        btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)),
     323        btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)),
     324        btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)),
     325        btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)),
     326        btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)),
     327        btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)),
     328        btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)),
     329        btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)),
     330        btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)),
     331        btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)),
     332        btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)),
     333        btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)),
     334        btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)),
     335        btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)),
     336        btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)),
     337        btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)),
     338        btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)),
     339        btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)),
     340        btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)),
     341        btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)),
     342        btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)),
     343        btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)),
     344        btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)),
     345        btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)),
     346        btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)),
     347        btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)),
     348        btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)),
     349        btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)),
     350        btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)),
     351        btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)),
     352        btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)),
     353        btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)),
     354        btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)),
     355        btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)),
     356        btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654))
     357        };
     358
     359        return sPenetrationDirections;
     360}
     361
     362
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h

    r5781 r8284  
    2323class btMinkowskiPenetrationDepthSolver : public btConvexPenetrationDepthSolver
    2424{
     25protected:
     26
     27        static btVector3*       getPenetrationDirections();
     28
    2529public:
    2630
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btPersistentManifold.cpp

    r5781 r8284  
    2626
    2727btPersistentManifold::btPersistentManifold()
    28 :m_body0(0),
     28:btTypedObject(BT_PERSISTENT_MANIFOLD_TYPE),
     29m_body0(0),
    2930m_body1(0),
    3031m_cachedPoints (0),
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btPersistentManifold.h

    r5781 r8284  
    3131typedef bool (*ContactProcessedCallback)(btManifoldPoint& cp,void* body0,void* body1);
    3232extern ContactDestroyedCallback gContactDestroyedCallback;
    33 
    34 
    35 
     33extern ContactProcessedCallback gContactProcessedCallback;
     34
     35
     36enum btContactManifoldTypes
     37{
     38        BT_PERSISTENT_MANIFOLD_TYPE = 1,
     39        MAX_CONTACT_MANIFOLD_TYPE
     40};
    3641
    3742#define MANIFOLD_CACHE_SIZE 4
     
    4449///the contact point with deepest penetration is always kept, and it tries to maximuze the area covered by the points
    4550///note that some pairs of objects might have more then one contact manifold.
    46 ATTRIBUTE_ALIGNED16( class) btPersistentManifold
     51
     52
     53ATTRIBUTE_ALIGNED128( class) btPersistentManifold : public btTypedObject
     54//ATTRIBUTE_ALIGNED16( class) btPersistentManifold : public btTypedObject
    4755{
    4856
     
    5361        void* m_body0;
    5462        void* m_body1;
     63
    5564        int     m_cachedPoints;
    5665
     
    6877        BT_DECLARE_ALIGNED_ALLOCATOR();
    6978
     79        int     m_companionIdA;
     80        int     m_companionIdB;
     81
    7082        int m_index1a;
    7183
     
    7385
    7486        btPersistentManifold(void* body0,void* body1,int , btScalar contactBreakingThreshold,btScalar contactProcessingThreshold)
    75                 : m_body0(body0),m_body1(body1),m_cachedPoints(0),
     87                : btTypedObject(BT_PERSISTENT_MANIFOLD_TYPE),
     88        m_body0(body0),m_body1(body1),m_cachedPoints(0),
    7689                m_contactBreakingThreshold(contactBreakingThreshold),
    7790                m_contactProcessingThreshold(contactProcessingThreshold)
    7891        {
    79                
    8092        }
    8193
     
    135147                        //get rid of duplicated userPersistentData pointer
    136148                        m_pointCache[lastUsedIndex].m_userPersistentData = 0;
     149                        m_pointCache[lastUsedIndex].mConstraintRow[0].mAccumImpulse = 0.f;
     150                        m_pointCache[lastUsedIndex].mConstraintRow[1].mAccumImpulse = 0.f;
     151                        m_pointCache[lastUsedIndex].mConstraintRow[2].mAccumImpulse = 0.f;
     152
    137153                        m_pointCache[lastUsedIndex].m_appliedImpulse = 0.f;
    138154                        m_pointCache[lastUsedIndex].m_lateralFrictionInitialized = false;
     
    152168#ifdef MAINTAIN_PERSISTENCY
    153169                int     lifeTime = m_pointCache[insertIndex].getLifeTime();
    154                 btScalar        appliedImpulse = m_pointCache[insertIndex].m_appliedImpulse;
    155                 btScalar        appliedLateralImpulse1 = m_pointCache[insertIndex].m_appliedImpulseLateral1;
    156                 btScalar        appliedLateralImpulse2 = m_pointCache[insertIndex].m_appliedImpulseLateral2;
    157                                
     170                btScalar        appliedImpulse = m_pointCache[insertIndex].mConstraintRow[0].mAccumImpulse;
     171                btScalar        appliedLateralImpulse1 = m_pointCache[insertIndex].mConstraintRow[1].mAccumImpulse;
     172                btScalar        appliedLateralImpulse2 = m_pointCache[insertIndex].mConstraintRow[2].mAccumImpulse;
     173//              bool isLateralFrictionInitialized = m_pointCache[insertIndex].m_lateralFrictionInitialized;
     174               
     175               
     176                       
    158177                btAssert(lifeTime>=0);
    159178                void* cache = m_pointCache[insertIndex].m_userPersistentData;
     
    166185                m_pointCache[insertIndex].m_appliedImpulseLateral2 = appliedLateralImpulse2;
    167186               
     187                m_pointCache[insertIndex].mConstraintRow[0].mAccumImpulse =  appliedImpulse;
     188                m_pointCache[insertIndex].mConstraintRow[1].mAccumImpulse = appliedLateralImpulse1;
     189                m_pointCache[insertIndex].mConstraintRow[2].mAccumImpulse = appliedLateralImpulse2;
     190
     191
    168192                m_pointCache[insertIndex].m_lifeTime = lifeTime;
    169193#else
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btPointCollector.h

    r5781 r8284  
    3232
    3333        btPointCollector ()
    34                 : m_distance(btScalar(1e30)),m_hasResult(false)
     34                : m_distance(btScalar(BT_LARGE_FLOAT)),m_hasResult(false)
    3535        {
    3636        }
    3737
    38         virtual void setShapeIdentifiers(int partId0,int index0,        int partId1,int index1)
     38        virtual void setShapeIdentifiersA(int partId0,int index0)
    3939        {
    4040                (void)partId0;
    4141                (void)index0;
     42                       
     43        }
     44        virtual void setShapeIdentifiersB(int partId1,int index1)
     45        {
    4246                (void)partId1;
    4347                (void)index1;
    44                 //??
    4548        }
    4649
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.cpp

    r5781 r8284  
    115115                        }
    116116                }
    117                 m_simplexSolver->addVertex( w, supVertexA , supVertexB);
     117                ///Just like regular GJK only add the vertex if it isn't already (close) to current vertex, it would lead to divisions by zero and NaN etc.
     118                if (!m_simplexSolver->inSimplex(w))
     119                        m_simplexSolver->addVertex( w, supVertexA , supVertexB);
     120
    118121                if (m_simplexSolver->closest(v))
    119122                {
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.cpp

    r5781 r8284  
    6969        m_numVertices = 0;
    7070        m_needsUpdate = true;
    71         m_lastW = btVector3(btScalar(1e30),btScalar(1e30),btScalar(1e30));
     71        m_lastW = btVector3(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
    7272        m_cachedBC.reset();
    7373}
     
    290290        for (i=0;i<numverts;i++)
    291291        {
     292#ifdef BT_USE_EQUAL_VERTEX_THRESHOLD
     293                if ( m_simplexVectorW[i].distance2(w) <= m_equalVertexThreshold)
     294#else
    292295                if (m_simplexVectorW[i] == w)
     296#endif
    293297                        found = true;
    294298        }
  • code/branches/kicklib2/src/external/bullet/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h

    r5781 r8284  
    2424
    2525#define VORONOI_SIMPLEX_MAX_VERTS 5
     26
     27///disable next define, or use defaultCollisionConfiguration->getSimplexSolver()->setEqualVertexThreshold(0.f) to disable/configure
     28#define BT_USE_EQUAL_VERTEX_THRESHOLD
     29#define VORONOI_DEFAULT_EQUAL_VERTEX_THRESHOLD 0.0001f
     30
    2631
    2732struct btUsageBitfield{
     
    107112        btVector3       m_cachedV;
    108113        btVector3       m_lastW;
     114       
     115        btScalar        m_equalVertexThreshold;
    109116        bool            m_cachedValidClosest;
     117
    110118
    111119        btSubSimplexClosestResult m_cachedBC;
     
    123131public:
    124132
     133        btVoronoiSimplexSolver()
     134                :  m_equalVertexThreshold(VORONOI_DEFAULT_EQUAL_VERTEX_THRESHOLD)
     135        {
     136        }
    125137         void reset();
    126138
    127139         void addVertex(const btVector3& w, const btVector3& p, const btVector3& q);
    128140
     141         void   setEqualVertexThreshold(btScalar threshold)
     142         {
     143                 m_equalVertexThreshold = threshold;
     144         }
     145
     146         btScalar       getEqualVertexThreshold() const
     147         {
     148                 return m_equalVertexThreshold;
     149         }
    129150
    130151         bool closest(btVector3& v);
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/CMakeLists.txt

    r5929 r8284  
    33COMPILATION_BEGIN BulletDynamicsCompilation.cpp
    44
     5        Character/btKinematicCharacterController.cpp
     6
     7        ConstraintSolver/btConeTwistConstraint.cpp
    58        ConstraintSolver/btContactConstraint.cpp
    6         ConstraintSolver/btConeTwistConstraint.cpp
    79        ConstraintSolver/btGeneric6DofConstraint.cpp
     10        ConstraintSolver/btGeneric6DofSpringConstraint.cpp
     11        ConstraintSolver/btHinge2Constraint.cpp
    812        ConstraintSolver/btHingeConstraint.cpp
    913        ConstraintSolver/btPoint2PointConstraint.cpp
     
    1216        ConstraintSolver/btSolve2LinearConstraint.cpp
    1317        ConstraintSolver/btTypedConstraint.cpp
     18        ConstraintSolver/btUniversalConstraint.cpp
    1419
     20        Dynamics/btContinuousDynamicsWorld.cpp
     21        Dynamics/btDiscreteDynamicsWorld.cpp
     22        Dynamics/btRigidBody.cpp
     23        Dynamics/btSimpleDynamicsWorld.cpp
    1524        Dynamics/Bullet-C-API.cpp
    16         Dynamics/btDiscreteDynamicsWorld.cpp
    17         Dynamics/btSimpleDynamicsWorld.cpp
    18         Dynamics/btRigidBody.cpp
    19 
    2025        Vehicle/btRaycastVehicle.cpp
    2126        Vehicle/btWheelInfo.cpp
    22 
    23         Character/btKinematicCharacterController.cpp
    2427
    2528COMPILATION_END
    2629
    2730        # Headers
     31        ConstraintSolver/btConeTwistConstraint.h
    2832        ConstraintSolver/btConstraintSolver.h
    2933        ConstraintSolver/btContactConstraint.h
    3034        ConstraintSolver/btContactSolverInfo.h
    31         ConstraintSolver/btConeTwistConstraint.h
    3235        ConstraintSolver/btGeneric6DofConstraint.h
     36        ConstraintSolver/btGeneric6DofSpringConstraint.h
     37        ConstraintSolver/btHinge2Constraint.h
    3338        ConstraintSolver/btHingeConstraint.h
    3439        ConstraintSolver/btJacobianEntry.h
     
    4045        ConstraintSolver/btSolverConstraint.h
    4146        ConstraintSolver/btTypedConstraint.h
    42 
     47        ConstraintSolver/btUniversalConstraint.h
    4348        Dynamics/btActionInterface.h
    4449        Dynamics/btContinuousDynamicsWorld.h
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Character/btCharacterControllerInterface.h

    r5781 r8284  
    3131       
    3232        virtual void    setWalkDirection(const btVector3& walkDirection) = 0;
     33        virtual void    setVelocityForTimeInterval(const btVector3& velocity, btScalar timeInterval) = 0;
    3334        virtual void    reset () = 0;
    3435        virtual void    warp (const btVector3& origin) = 0;
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Character/btKinematicCharacterController.cpp

    r5781 r8284  
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516
    1617#include "LinearMath/btIDebugDraw.h"
     
    2324#include "btKinematicCharacterController.h"
    2425
    25 static btVector3 upAxisDirection[3] = { btVector3(1.0f, 0.0f, 0.0f), btVector3(0.0f, 1.0f, 0.0f), btVector3(0.0f, 0.0f, 1.0f) };
     26
     27// static helper method
     28static btVector3
     29getNormalizedVector(const btVector3& v)
     30{
     31        btVector3 n = v.normalized();
     32        if (n.length() < SIMD_EPSILON) {
     33                n.setValue(0, 0, 0);
     34        }
     35        return n;
     36}
     37
    2638
    2739///@todo Interact with dynamic objects,
     
    5365{
    5466public:
    55         btKinematicClosestNotMeConvexResultCallback (btCollisionObject* me) : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
    56         {
    57                 m_me = me;
     67        btKinematicClosestNotMeConvexResultCallback (btCollisionObject* me, const btVector3& up, btScalar minSlopeDot)
     68        : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
     69        , m_me(me)
     70        , m_up(up)
     71        , m_minSlopeDot(minSlopeDot)
     72        {
    5873        }
    5974
     
    6176        {
    6277                if (convexResult.m_hitCollisionObject == m_me)
    63                         return 1.0;
     78                        return btScalar(1.0);
     79
     80                btVector3 hitNormalWorld;
     81                if (normalInWorldSpace)
     82                {
     83                        hitNormalWorld = convexResult.m_hitNormalLocal;
     84                } else
     85                {
     86                        ///need to transform normal into worldspace
     87                        hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis()*convexResult.m_hitNormalLocal;
     88                }
     89
     90                btScalar dotUp = m_up.dot(hitNormalWorld);
     91                if (dotUp < m_minSlopeDot) {
     92                        return btScalar(1.0);
     93                }
    6494
    6595                return ClosestConvexResultCallback::addSingleResult (convexResult, normalInWorldSpace);
     
    6797protected:
    6898        btCollisionObject* m_me;
     99        const btVector3 m_up;
     100        btScalar m_minSlopeDot;
    69101};
    70102
     
    99131{
    100132        m_upAxis = upAxis;
    101         m_addedMargin = 0.02f;
     133        m_addedMargin = 0.02;
    102134        m_walkDirection.setValue(0,0,0);
    103135        m_useGhostObjectSweepTest = true;
     
    106138        m_turnAngle = btScalar(0.0);
    107139        m_convexShape=convexShape;     
     140        m_useWalkDirection = true;      // use walk direction by default, legacy behavior
     141        m_velocityTimeInterval = 0.0;
     142        m_verticalVelocity = 0.0;
     143        m_verticalOffset = 0.0;
     144        m_gravity = 9.8 * 3 ; // 3G acceleration.
     145        m_fallSpeed = 55.0; // Terminal velocity of a sky diver in m/s.
     146        m_jumpSpeed = 10.0; // ?
     147        m_wasOnGround = false;
     148        m_wasJumping = false;
     149        setMaxSlope(btRadians(45.0));
    108150}
    109151
     
    145187                                const btManifoldPoint&pt = manifold->getContactPoint(p);
    146188
    147                                 if (pt.getDistance() < 0.0)
     189                                btScalar dist = pt.getDistance();
     190
     191                                if (dist < 0.0)
    148192                                {
    149                                         if (pt.getDistance() < maxPen)
     193                                        if (dist < maxPen)
    150194                                        {
    151                                                 maxPen = pt.getDistance();
     195                                                maxPen = dist;
    152196                                                m_touchingNormal = pt.m_normalWorldOnB * directionSign;//??
    153197
    154198                                        }
    155                                         m_currentPosition += pt.m_normalWorldOnB * directionSign * pt.getDistance() * btScalar(0.2);
     199                                        m_currentPosition += pt.m_normalWorldOnB * directionSign * dist * btScalar(0.2);
    156200                                        penetration = true;
    157201                                } else {
    158                                         //printf("touching %f\n", pt.getDistance());
     202                                        //printf("touching %f\n", dist);
    159203                                }
    160204                        }
     
    174218        // phase 1: up
    175219        btTransform start, end;
    176         m_targetPosition = m_currentPosition + upAxisDirection[m_upAxis] * m_stepHeight;
     220        m_targetPosition = m_currentPosition + getUpAxisDirections()[m_upAxis] * (m_stepHeight + (m_verticalOffset > 0.f?m_verticalOffset:0.f));
    177221
    178222        start.setIdentity ();
     
    180224
    181225        /* FIXME: Handle penetration properly */
    182         start.setOrigin (m_currentPosition + upAxisDirection[m_upAxis] * btScalar(0.1f));
     226        start.setOrigin (m_currentPosition + getUpAxisDirections()[m_upAxis] * (m_convexShape->getMargin() + m_addedMargin));
    183227        end.setOrigin (m_targetPosition);
    184228
    185         btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject);
     229        btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, -getUpAxisDirections()[m_upAxis], btScalar(0.7071));
    186230        callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
    187231        callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
     
    198242        if (callback.hasHit())
    199243        {
    200                 // we moved up only a fraction of the step height
    201                 m_currentStepOffset = m_stepHeight * callback.m_closestHitFraction;
    202                 m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
     244                // Only modify the position if the hit was a slope and not a wall or ceiling.
     245                if(callback.m_hitNormalWorld.dot(getUpAxisDirections()[m_upAxis]) > 0.0)
     246                {
     247                        // we moved up only a fraction of the step height
     248                        m_currentStepOffset = m_stepHeight * callback.m_closestHitFraction;
     249                        m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
     250                }
     251                m_verticalVelocity = 0.0;
     252                m_verticalOffset = 0.0;
    203253        } else {
    204254                m_currentStepOffset = m_stepHeight;
     
    245295void btKinematicCharacterController::stepForwardAndStrafe ( btCollisionWorld* collisionWorld, const btVector3& walkMove)
    246296{
    247 
    248         btVector3 originalDir = walkMove.normalized();
    249         if (walkMove.length() < SIMD_EPSILON)
    250         {
    251                 originalDir.setValue(0.f,0.f,0.f);
    252         }
    253 //      printf("originalDir=%f,%f,%f\n",originalDir[0],originalDir[1],originalDir[2]);
     297        // printf("m_normalizedDirection=%f,%f,%f\n",
     298        //      m_normalizedDirection[0],m_normalizedDirection[1],m_normalizedDirection[2]);
    254299        // phase 2: forward and strafe
    255300        btTransform start, end;
    256301        m_targetPosition = m_currentPosition + walkMove;
     302
    257303        start.setIdentity ();
    258304        end.setIdentity ();
     
    264310        if (m_touchingContact)
    265311        {
    266                 if (originalDir.dot(m_touchingNormal) > btScalar(0.0))
     312                if (m_normalizedDirection.dot(m_touchingNormal) > btScalar(0.0))
     313                {
    267314                        updateTargetPositionBasedOnCollision (m_touchingNormal);
     315                }
    268316        }
    269317
     
    274322                start.setOrigin (m_currentPosition);
    275323                end.setOrigin (m_targetPosition);
    276 
    277                 btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject);
     324                btVector3 sweepDirNegative(m_currentPosition - m_targetPosition);
     325
     326                btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, sweepDirNegative, btScalar(0.0));
    278327                callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
    279328                callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
     
    300349                {       
    301350                        // we moved only a fraction
    302                         btScalar hitDistance = (callback.m_hitPointWorld - m_currentPosition).length();
    303                         if (hitDistance<0.f)
    304                         {
    305 //                              printf("neg dist?\n");
    306                         }
    307 
    308                         /* If the distance is farther than the collision margin, move */
    309                         if (hitDistance > m_addedMargin)
    310                         {
    311 //                              printf("callback.m_closestHitFraction=%f\n",callback.m_closestHitFraction);
    312                                 m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
    313                         }
     351                        btScalar hitDistance;
     352                        hitDistance = (callback.m_hitPointWorld - m_currentPosition).length();
     353
     354//                      m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
    314355
    315356                        updateTargetPositionBasedOnCollision (callback.m_hitNormalWorld);
     
    320361                                currentDir.normalize();
    321362                                /* See Quake2: "If velocity is against original velocity, stop ead to avoid tiny oscilations in sloping corners." */
    322                                 if (currentDir.dot(originalDir) <= btScalar(0.0))
     363                                if (currentDir.dot(m_normalizedDirection) <= btScalar(0.0))
    323364                                {
    324365                                        break;
     
    329370                                break;
    330371                        }
     372
    331373                } else {
    332374                        // we moved whole way
     
    345387
    346388        // phase 3: down
    347         btVector3 step_drop = upAxisDirection[m_upAxis] * m_currentStepOffset;
    348         btVector3 gravity_drop = upAxisDirection[m_upAxis] * m_stepHeight;
    349         m_targetPosition -= (step_drop + gravity_drop);
     389        /*btScalar additionalDownStep = (m_wasOnGround && !onGround()) ? m_stepHeight : 0.0;
     390        btVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + additionalDownStep);
     391        btScalar downVelocity = (additionalDownStep == 0.0 && m_verticalVelocity<0.0?-m_verticalVelocity:0.0) * dt;
     392        btVector3 gravity_drop = getUpAxisDirections()[m_upAxis] * downVelocity;
     393        m_targetPosition -= (step_drop + gravity_drop);*/
     394
     395        btScalar downVelocity = (m_verticalVelocity<0.f?-m_verticalVelocity:0.f) * dt;
     396        if(downVelocity > 0.0 && downVelocity < m_stepHeight
     397                && (m_wasOnGround || !m_wasJumping))
     398        {
     399                downVelocity = m_stepHeight;
     400        }
     401
     402        btVector3 step_drop = getUpAxisDirections()[m_upAxis] * (m_currentStepOffset + downVelocity);
     403        m_targetPosition -= step_drop;
    350404
    351405        start.setIdentity ();
     
    355409        end.setOrigin (m_targetPosition);
    356410
    357         btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject);
     411        btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, getUpAxisDirections()[m_upAxis], m_maxSlopeCosine);
    358412        callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
    359413        callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
     
    371425                // we dropped a fraction of the height -> hit floor
    372426                m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
     427                m_verticalVelocity = 0.0;
     428                m_verticalOffset = 0.0;
     429                m_wasJumping = false;
    373430        } else {
    374431                // we dropped the full height
     
    378435}
    379436
     437
     438
     439void btKinematicCharacterController::setWalkDirection
     440(
     441const btVector3& walkDirection
     442)
     443{
     444        m_useWalkDirection = true;
     445        m_walkDirection = walkDirection;
     446        m_normalizedDirection = getNormalizedVector(m_walkDirection);
     447}
     448
     449
     450
     451void btKinematicCharacterController::setVelocityForTimeInterval
     452(
     453const btVector3& velocity,
     454btScalar timeInterval
     455)
     456{
     457//      printf("setVelocity!\n");
     458//      printf("  interval: %f\n", timeInterval);
     459//      printf("  velocity: (%f, %f, %f)\n",
     460//               velocity.x(), velocity.y(), velocity.z());
     461
     462        m_useWalkDirection = false;
     463        m_walkDirection = velocity;
     464        m_normalizedDirection = getNormalizedVector(m_walkDirection);
     465        m_velocityTimeInterval = timeInterval;
     466}
     467
     468
     469
    380470void btKinematicCharacterController::reset ()
    381471{
     
    402492                if (numPenetrationLoops > 4)
    403493                {
    404 //                      printf("character could not recover from penetration = %d\n", numPenetrationLoops);
     494                        //printf("character could not recover from penetration = %d\n", numPenetrationLoops);
    405495                        break;
    406496                }
     
    414504}
    415505
     506#include <stdio.h>
     507
    416508void btKinematicCharacterController::playerStep (  btCollisionWorld* collisionWorld, btScalar dt)
    417509{
     510//      printf("playerStep(): ");
     511//      printf("  dt = %f", dt);
     512
     513        // quick check...
     514        if (!m_useWalkDirection && m_velocityTimeInterval <= 0.0) {
     515//              printf("\n");
     516                return;         // no motion
     517        }
     518
     519        m_wasOnGround = onGround();
     520
     521        // Update fall velocity.
     522        m_verticalVelocity -= m_gravity * dt;
     523        if(m_verticalVelocity > 0.0 && m_verticalVelocity > m_jumpSpeed)
     524        {
     525                m_verticalVelocity = m_jumpSpeed;
     526        }
     527        if(m_verticalVelocity < 0.0 && btFabs(m_verticalVelocity) > btFabs(m_fallSpeed))
     528        {
     529                m_verticalVelocity = -btFabs(m_fallSpeed);
     530        }
     531        m_verticalOffset = m_verticalVelocity * dt;
     532
     533
    418534        btTransform xform;
    419535        xform = m_ghostObject->getWorldTransform ();
     
    423539
    424540        stepUp (collisionWorld);
    425         stepForwardAndStrafe (collisionWorld, m_walkDirection);
     541        if (m_useWalkDirection) {
     542                stepForwardAndStrafe (collisionWorld, m_walkDirection);
     543        } else {
     544                //printf("  time: %f", m_velocityTimeInterval);
     545                // still have some time left for moving!
     546                btScalar dtMoving =
     547                        (dt < m_velocityTimeInterval) ? dt : m_velocityTimeInterval;
     548                m_velocityTimeInterval -= dt;
     549
     550                // how far will we move while we are moving?
     551                btVector3 move = m_walkDirection * dtMoving;
     552
     553                //printf("  dtMoving: %f", dtMoving);
     554
     555                // okay, step
     556                stepForwardAndStrafe(collisionWorld, move);
     557        }
    426558        stepDown (collisionWorld, dt);
     559
     560        // printf("\n");
    427561
    428562        xform.setOrigin (m_currentPosition);
     
    454588        if (!canJump())
    455589                return;
     590
     591        m_verticalVelocity = m_jumpSpeed;
     592        m_wasJumping = true;
    456593
    457594#if 0
     
    466603}
    467604
     605void btKinematicCharacterController::setGravity(btScalar gravity)
     606{
     607        m_gravity = gravity;
     608}
     609
     610btScalar btKinematicCharacterController::getGravity() const
     611{
     612        return m_gravity;
     613}
     614
     615void btKinematicCharacterController::setMaxSlope(btScalar slopeRadians)
     616{
     617        m_maxSlopeRadians = slopeRadians;
     618        m_maxSlopeCosine = btCos(slopeRadians);
     619}
     620
     621btScalar btKinematicCharacterController::getMaxSlope() const
     622{
     623        return m_maxSlopeRadians;
     624}
     625
    468626bool btKinematicCharacterController::onGround () const
    469627{
    470         return true;
    471 }
    472 
    473 
    474 void    btKinematicCharacterController::debugDraw(btIDebugDraw* debugDrawer)
    475 {
    476 }
     628        return m_verticalVelocity == 0.0 && m_verticalOffset == 0.0;
     629}
     630
     631
     632btVector3* btKinematicCharacterController::getUpAxisDirections()
     633{
     634        static btVector3 sUpAxisDirection[3] = { btVector3(1.0f, 0.0f, 0.0f), btVector3(0.0f, 1.0f, 0.0f), btVector3(0.0f, 0.0f, 1.0f) };
     635       
     636        return sUpAxisDirection;
     637}
     638
     639void btKinematicCharacterController::debugDraw(btIDebugDraw* debugDrawer)
     640{
     641}
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Character/btKinematicCharacterController.h

    r5781 r8284  
    1414*/
    1515
     16
    1617#ifndef KINEMATIC_CHARACTER_CONTROLLER_H
    1718#define KINEMATIC_CHARACTER_CONTROLLER_H
     
    2021
    2122#include "btCharacterControllerInterface.h"
     23
     24#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
     25
    2226
    2327class btCollisionShape;
     
    3337{
    3438protected:
     39
    3540        btScalar m_halfHeight;
    3641       
     
    3843        btConvexShape*  m_convexShape;//is also in m_ghostObject, but it needs to be convex, so we store it here to avoid upcast
    3944       
     45        btScalar m_verticalVelocity;
     46        btScalar m_verticalOffset;
    4047        btScalar m_fallSpeed;
    4148        btScalar m_jumpSpeed;
    4249        btScalar m_maxJumpHeight;
     50        btScalar m_maxSlopeRadians; // Slope angle that is set (used for returning the exact value)
     51        btScalar m_maxSlopeCosine;  // Cosine equivalent of m_maxSlopeRadians (calculated once when set, for optimization)
     52        btScalar m_gravity;
    4353
    4454        btScalar m_turnAngle;
     
    5060        ///this is the desired walk direction, set by the user
    5161        btVector3       m_walkDirection;
     62        btVector3       m_normalizedDirection;
    5263
    5364        //some internal variables
     
    6273        btVector3 m_touchingNormal;
    6374
     75        bool  m_wasOnGround;
     76        bool  m_wasJumping;
    6477        bool    m_useGhostObjectSweepTest;
     78        bool    m_useWalkDirection;
     79        btScalar        m_velocityTimeInterval;
     80        int m_upAxis;
    6581
    66         int m_upAxis;
    67        
     82        static btVector3* getUpAxisDirections();
     83
    6884        btVector3 computeReflectionDirection (const btVector3& direction, const btVector3& normal);
    6985        btVector3 parallelComponent (const btVector3& direction, const btVector3& normal);
     
    99115        }
    100116
    101         virtual void    setWalkDirection(const btVector3& walkDirection)
    102         {
    103                 m_walkDirection = walkDirection;
    104         }
     117        /// This should probably be called setPositionIncrementPerSimulatorStep.
     118        /// This is neither a direction nor a velocity, but the amount to
     119        ///     increment the position each simulation iteration, regardless
     120        ///     of dt.
     121        /// This call will reset any velocity set by setVelocityForTimeInterval().
     122        virtual void    setWalkDirection(const btVector3& walkDirection);
     123
     124        /// Caller provides a velocity with which the character should move for
     125        ///     the given time period.  After the time period, velocity is reset
     126        ///     to zero.
     127        /// This call will reset any walk direction set by setWalkDirection().
     128        /// Negative time intervals will result in no motion.
     129        virtual void setVelocityForTimeInterval(const btVector3& velocity,
     130                                btScalar timeInterval);
    105131
    106132        void reset ();
     
    114140        void setMaxJumpHeight (btScalar maxJumpHeight);
    115141        bool canJump () const;
     142
    116143        void jump ();
     144
     145        void setGravity(btScalar gravity);
     146        btScalar getGravity() const;
     147
     148        /// The max slope determines the maximum angle that the controller can walk up.
     149        /// The slope angle is measured in radians.
     150        void setMaxSlope(btScalar slopeRadians);
     151        btScalar getMaxSlope() const;
    117152
    118153        btPairCachingGhostObject* getGhostObject();
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp

    r5781 r8284  
    2323#include <new>
    2424
    25 //-----------------------------------------------------------------------------
    26 
     25
     26
     27//#define CONETWIST_USE_OBSOLETE_SOLVER true
    2728#define CONETWIST_USE_OBSOLETE_SOLVER false
    2829#define CONETWIST_DEF_FIX_THRESH btScalar(.05f)
    2930
    30 //-----------------------------------------------------------------------------
    31 
    32 btConeTwistConstraint::btConeTwistConstraint()
    33 :btTypedConstraint(CONETWIST_CONSTRAINT_TYPE),
    34 m_useSolveConstraintObsolete(CONETWIST_USE_OBSOLETE_SOLVER)
    35 {
    36 }
     31
     32SIMD_FORCE_INLINE btScalar computeAngularImpulseDenominator(const btVector3& axis, const btMatrix3x3& invInertiaWorld)
     33{
     34        btVector3 vec = axis * invInertiaWorld;
     35        return axis.dot(vec);
     36}
     37
     38
    3739
    3840
     
    6466        m_maxMotorImpulse = btScalar(-1);
    6567
    66         setLimit(btScalar(1e30), btScalar(1e30), btScalar(1e30));
     68        setLimit(btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT));
    6769        m_damping = btScalar(0.01);
    6870        m_fixThresh = CONETWIST_DEF_FIX_THRESH;
    69 }
    70 
    71 
    72 //-----------------------------------------------------------------------------
     71        m_flags = 0;
     72        m_linCFM = btScalar(0.f);
     73        m_linERP = btScalar(0.7f);
     74        m_angCFM = btScalar(0.f);
     75}
     76
    7377
    7478void btConeTwistConstraint::getInfo1 (btConstraintInfo1* info)
     
    8387                info->m_numConstraintRows = 3;
    8488                info->nub = 3;
    85                 calcAngleInfo2();
     89                calcAngleInfo2(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform(),m_rbA.getInvInertiaTensorWorld(),m_rbB.getInvInertiaTensorWorld());
    8690                if(m_solveSwingLimit)
    8791                {
     
    100104                }
    101105        }
    102 } // btConeTwistConstraint::getInfo1()
     106}
     107
     108void btConeTwistConstraint::getInfo1NonVirtual (btConstraintInfo1* info)
     109{
     110        //always reserve 6 rows: object transform is not available on SPU
     111        info->m_numConstraintRows = 6;
     112        info->nub = 0;
     113               
     114}
    103115       
    104 //-----------------------------------------------------------------------------
    105116
    106117void btConeTwistConstraint::getInfo2 (btConstraintInfo2* info)
    107118{
     119        getInfo2NonVirtual(info,m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform(),m_rbA.getInvInertiaTensorWorld(),m_rbB.getInvInertiaTensorWorld());
     120}
     121
     122void btConeTwistConstraint::getInfo2NonVirtual (btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btMatrix3x3& invInertiaWorldA,const btMatrix3x3& invInertiaWorldB)
     123{
     124        calcAngleInfo2(transA,transB,invInertiaWorldA,invInertiaWorldB);
     125       
    108126        btAssert(!m_useSolveConstraintObsolete);
    109         //retrieve matrices
    110         btTransform body0_trans;
    111         body0_trans = m_rbA.getCenterOfMassTransform();
    112     btTransform body1_trans;
    113         body1_trans = m_rbB.getCenterOfMassTransform();
    114127    // set jacobian
    115128    info->m_J1linearAxis[0] = 1;
    116129    info->m_J1linearAxis[info->rowskip+1] = 1;
    117130    info->m_J1linearAxis[2*info->rowskip+2] = 1;
    118         btVector3 a1 = body0_trans.getBasis() * m_rbAFrame.getOrigin();
     131        btVector3 a1 = transA.getBasis() * m_rbAFrame.getOrigin();
    119132        {
    120133                btVector3* angular0 = (btVector3*)(info->m_J1angularAxis);
     
    124137                a1neg.getSkewSymmetricMatrix(angular0,angular1,angular2);
    125138        }
    126         btVector3 a2 = body1_trans.getBasis() * m_rbBFrame.getOrigin();
     139        btVector3 a2 = transB.getBasis() * m_rbBFrame.getOrigin();
    127140        {
    128141                btVector3* angular0 = (btVector3*)(info->m_J2angularAxis);
     
    132145        }
    133146    // set right hand side
    134     btScalar k = info->fps * info->erp;
     147        btScalar linERP = (m_flags & BT_CONETWIST_FLAGS_LIN_ERP) ? m_linERP : info->erp;
     148    btScalar k = info->fps * linERP;
    135149    int j;
    136150        for (j=0; j<3; j++)
    137151    {
    138         info->m_constraintError[j*info->rowskip] = k * (a2[j] + body1_trans.getOrigin()[j] - a1[j] - body0_trans.getOrigin()[j]);
     152        info->m_constraintError[j*info->rowskip] = k * (a2[j] + transB.getOrigin()[j] - a1[j] - transA.getOrigin()[j]);
    139153                info->m_lowerLimit[j*info->rowskip] = -SIMD_INFINITY;
    140154                info->m_upperLimit[j*info->rowskip] = SIMD_INFINITY;
     155                if(m_flags & BT_CONETWIST_FLAGS_LIN_CFM)
     156                {
     157                        info->cfm[j*info->rowskip] = m_linCFM;
     158                }
    141159    }
    142160        int row = 3;
     
    150168                if((m_swingSpan1 < m_fixThresh) && (m_swingSpan2 < m_fixThresh))
    151169                {
    152                         btTransform trA = m_rbA.getCenterOfMassTransform()*m_rbAFrame;
     170                        btTransform trA = transA*m_rbAFrame;
    153171                        btVector3 p = trA.getBasis().getColumn(1);
    154172                        btVector3 q = trA.getBasis().getColumn(2);
     
    187205
    188206                        info->m_constraintError[srow] = k * m_swingCorrection;
    189                         info->cfm[srow] = 0.0f;
     207                        if(m_flags & BT_CONETWIST_FLAGS_ANG_CFM)
     208                        {
     209                                info->cfm[srow] = m_angCFM;
     210                        }
    190211                        // m_swingCorrection is always positive or 0
    191212                        info->m_lowerLimit[srow] = 0;
     
    207228                btScalar k = info->fps * m_biasFactor;
    208229                info->m_constraintError[srow] = k * m_twistCorrection;
    209                 info->cfm[srow] = 0.0f;
     230                if(m_flags & BT_CONETWIST_FLAGS_ANG_CFM)
     231                {
     232                        info->cfm[srow] = m_angCFM;
     233                }
    210234                if(m_twistSpan > 0.0f)
    211235                {
     
    231255}
    232256       
    233 //-----------------------------------------------------------------------------
     257
    234258
    235259void    btConeTwistConstraint::buildJacobian()
     
    240264                m_accTwistLimitImpulse = btScalar(0.);
    241265                m_accSwingLimitImpulse = btScalar(0.);
     266                m_accMotorImpulse = btVector3(0.,0.,0.);
    242267
    243268                if (!m_angularOnly)
     
    274299                }
    275300
    276                 calcAngleInfo2();
    277         }
    278 }
    279 
    280 //-----------------------------------------------------------------------------
    281 
    282 void    btConeTwistConstraint::solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar timeStep)
    283 {
     301                calcAngleInfo2(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform(),m_rbA.getInvInertiaTensorWorld(),m_rbB.getInvInertiaTensorWorld());
     302        }
     303}
     304
     305
     306
     307void    btConeTwistConstraint::solveConstraintObsolete(btRigidBody& bodyA,btRigidBody& bodyB,btScalar   timeStep)
     308{
     309        #ifndef __SPU__
    284310        if (m_useSolveConstraintObsolete)
    285311        {
     
    296322
    297323                        btVector3 vel1;
    298                         bodyA.getVelocityInLocalPointObsolete(rel_pos1,vel1);
     324                        bodyA.internalGetVelocityInLocalPointObsolete(rel_pos1,vel1);
    299325                        btVector3 vel2;
    300                         bodyB.getVelocityInLocalPointObsolete(rel_pos2,vel2);
     326                        bodyB.internalGetVelocityInLocalPointObsolete(rel_pos2,vel2);
    301327                        btVector3 vel = vel1 - vel2;
    302328
     
    315341                                btVector3 ftorqueAxis1 = rel_pos1.cross(normal);
    316342                                btVector3 ftorqueAxis2 = rel_pos2.cross(normal);
    317                                 bodyA.applyImpulse(normal*m_rbA.getInvMass(), m_rbA.getInvInertiaTensorWorld()*ftorqueAxis1,impulse);
    318                                 bodyB.applyImpulse(normal*m_rbB.getInvMass(), m_rbB.getInvInertiaTensorWorld()*ftorqueAxis2,-impulse);
     343                                bodyA.internalApplyImpulse(normal*m_rbA.getInvMass(), m_rbA.getInvInertiaTensorWorld()*ftorqueAxis1,impulse);
     344                                bodyB.internalApplyImpulse(normal*m_rbB.getInvMass(), m_rbB.getInvInertiaTensorWorld()*ftorqueAxis2,-impulse);
    319345               
    320346                        }
     
    327353                        btTransform trACur = m_rbA.getCenterOfMassTransform();
    328354                        btTransform trBCur = m_rbB.getCenterOfMassTransform();
    329                         btVector3 omegaA; bodyA.getAngularVelocity(omegaA);
    330                         btVector3 omegaB; bodyB.getAngularVelocity(omegaB);
     355                        btVector3 omegaA; bodyA.internalGetAngularVelocity(omegaA);
     356                        btVector3 omegaB; bodyB.internalGetAngularVelocity(omegaB);
    331357                        btTransform trAPred; trAPred.setIdentity();
    332358                        btVector3 zerovec(0,0,0);
     
    402428                                btVector3 impulseAxis =  impulse / impulseMag;
    403429
    404                                 bodyA.applyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*impulseAxis, impulseMag);
    405                                 bodyB.applyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*impulseAxis, -impulseMag);
    406 
    407                         }
    408                 }
    409                 else // no motor: do a little damping
    410                 {
    411                         const btVector3& angVelA = getRigidBodyA().getAngularVelocity();
    412                         const btVector3& angVelB = getRigidBodyB().getAngularVelocity();
     430                                bodyA.internalApplyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*impulseAxis, impulseMag);
     431                                bodyB.internalApplyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*impulseAxis, -impulseMag);
     432
     433                        }
     434                }
     435                else if (m_damping > SIMD_EPSILON) // no motor: do a little damping
     436                {
     437                        btVector3 angVelA; bodyA.internalGetAngularVelocity(angVelA);
     438                        btVector3 angVelB; bodyB.internalGetAngularVelocity(angVelB);
    413439                        btVector3 relVel = angVelB - angVelA;
    414440                        if (relVel.length2() > SIMD_EPSILON)
     
    422448                                btScalar  impulseMag  = impulse.length();
    423449                                btVector3 impulseAxis = impulse / impulseMag;
    424                                 bodyA.applyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*impulseAxis, impulseMag);
    425                                 bodyB.applyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*impulseAxis, -impulseMag);
     450                                bodyA.internalApplyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*impulseAxis, impulseMag);
     451                                bodyB.internalApplyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*impulseAxis, -impulseMag);
    426452                        }
    427453                }
     
    431457                        ///solve angular part
    432458                        btVector3 angVelA;
    433                         bodyA.getAngularVelocity(angVelA);
     459                        bodyA.internalGetAngularVelocity(angVelA);
    434460                        btVector3 angVelB;
    435                         bodyB.getAngularVelocity(angVelB);
     461                        bodyB.internalGetAngularVelocity(angVelB);
    436462
    437463                        // solve swing limit
     
    462488                                btVector3 noTwistSwingAxis = impulse / impulseMag;
    463489
    464                                 bodyA.applyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*noTwistSwingAxis, impulseMag);
    465                                 bodyB.applyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*noTwistSwingAxis, -impulseMag);
     490                                bodyA.internalApplyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*noTwistSwingAxis, impulseMag);
     491                                bodyB.internalApplyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*noTwistSwingAxis, -impulseMag);
    466492                        }
    467493
     
    483509                                btVector3 impulse = m_twistAxis * impulseMag;
    484510
    485                                 bodyA.applyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*m_twistAxis,impulseMag);
    486                                 bodyB.applyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*m_twistAxis,-impulseMag);
     511                                bodyA.internalApplyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*m_twistAxis,impulseMag);
     512                                bodyB.internalApplyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*m_twistAxis,-impulseMag);
    487513                        }               
    488514                }
    489515        }
    490 
    491 }
    492 
    493 //-----------------------------------------------------------------------------
     516#else
     517btAssert(0);
     518#endif //__SPU__
     519}
     520
     521
     522
    494523
    495524void    btConeTwistConstraint::updateRHS(btScalar       timeStep)
     
    499528}
    500529
    501 //-----------------------------------------------------------------------------
    502 
     530
     531#ifndef __SPU__
    503532void btConeTwistConstraint::calcAngleInfo()
    504533{
     
    585614                }
    586615        }
    587 } // btConeTwistConstraint::calcAngleInfo()
    588 
     616}
     617#endif //__SPU__
    589618
    590619static btVector3 vTwist(1,0,0); // twist axis in constraint's space
    591620
    592 //-----------------------------------------------------------------------------
    593 
    594 void btConeTwistConstraint::calcAngleInfo2()
     621
     622
     623void btConeTwistConstraint::calcAngleInfo2(const btTransform& transA, const btTransform& transB, const btMatrix3x3& invInertiaWorldA,const btMatrix3x3& invInertiaWorldB)
    595624{
    596625        m_swingCorrection = btScalar(0.);
     
    598627        m_solveTwistLimit = false;
    599628        m_solveSwingLimit = false;
     629        // compute rotation of A wrt B (in constraint space)
     630        if (m_bMotorEnabled && (!m_useSolveConstraintObsolete))
     631        {       // it is assumed that setMotorTarget() was alredy called
     632                // and motor target m_qTarget is within constraint limits
     633                // TODO : split rotation to pure swing and pure twist
     634                // compute desired transforms in world
     635                btTransform trPose(m_qTarget);
     636                btTransform trA = transA * m_rbAFrame;
     637                btTransform trB = transB * m_rbBFrame;
     638                btTransform trDeltaAB = trB * trPose * trA.inverse();
     639                btQuaternion qDeltaAB = trDeltaAB.getRotation();
     640                btVector3 swingAxis =   btVector3(qDeltaAB.x(), qDeltaAB.y(), qDeltaAB.z());
     641                m_swingAxis = swingAxis;
     642                m_swingAxis.normalize();
     643                m_swingCorrection = qDeltaAB.getAngle();
     644                if(!btFuzzyZero(m_swingCorrection))
     645                {
     646                        m_solveSwingLimit = true;
     647                }
     648                return;
     649        }
     650
    600651
    601652        {
    602653                // compute rotation of A wrt B (in constraint space)
    603                 btQuaternion qA = getRigidBodyA().getCenterOfMassTransform().getRotation() * m_rbAFrame.getRotation();
    604                 btQuaternion qB = getRigidBodyB().getCenterOfMassTransform().getRotation() * m_rbBFrame.getRotation();
     654                btQuaternion qA = transA.getRotation() * m_rbAFrame.getRotation();
     655                btQuaternion qB = transB.getRotation() * m_rbBFrame.getRotation();
    605656                btQuaternion qAB = qB.inverse() * qA;
    606 
    607657                // split rotation into cone and twist
    608658                // (all this is done from B's perspective. Maybe I should be averaging axes...)
     
    642692
    643693                                m_kSwing =  btScalar(1.) /
    644                                         (getRigidBodyA().computeAngularImpulseDenominator(m_swingAxis) +
    645                                          getRigidBodyB().computeAngularImpulseDenominator(m_swingAxis));
     694                                        (computeAngularImpulseDenominator(m_swingAxis,invInertiaWorldA) +
     695                                         computeAngularImpulseDenominator(m_swingAxis,invInertiaWorldB));
    646696                        }
    647697                }
     
    651701                        // or you're trying to set at least one of the swing limits too small. (if so, do you really want a conetwist constraint?)
    652702                        // anyway, we have either hinge or fixed joint
    653                         btVector3 ivA = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(0);
    654                         btVector3 jvA = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(1);
    655                         btVector3 kvA = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(2);
    656                         btVector3 ivB = getRigidBodyB().getCenterOfMassTransform().getBasis() * m_rbBFrame.getBasis().getColumn(0);
     703                        btVector3 ivA = transA.getBasis() * m_rbAFrame.getBasis().getColumn(0);
     704                        btVector3 jvA = transA.getBasis() * m_rbAFrame.getBasis().getColumn(1);
     705                        btVector3 kvA = transA.getBasis() * m_rbAFrame.getBasis().getColumn(2);
     706                        btVector3 ivB = transB.getBasis() * m_rbBFrame.getBasis().getColumn(0);
    657707                        btVector3 target;
    658708                        btScalar x = ivB.dot(ivA);
     
    745795
    746796                                m_kTwist = btScalar(1.) /
    747                                         (getRigidBodyA().computeAngularImpulseDenominator(m_twistAxis) +
    748                                          getRigidBodyB().computeAngularImpulseDenominator(m_twistAxis));
     797                                        (computeAngularImpulseDenominator(m_twistAxis,invInertiaWorldA) +
     798                                         computeAngularImpulseDenominator(m_twistAxis,invInertiaWorldB));
    749799                        }
    750800
     
    757807                }
    758808        }
    759 } // btConeTwistConstraint::calcAngleInfo2()
     809}
    760810
    761811
     
    9821032}
    9831033
    984 
    985 //-----------------------------------------------------------------------------
    986 //-----------------------------------------------------------------------------
    987 //-----------------------------------------------------------------------------
    988 
    989 
     1034///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     1035///If no axis is provided, it uses the default axis for this constraint.
     1036void btConeTwistConstraint::setParam(int num, btScalar value, int axis)
     1037{
     1038        switch(num)
     1039        {
     1040                case BT_CONSTRAINT_ERP :
     1041                case BT_CONSTRAINT_STOP_ERP :
     1042                        if((axis >= 0) && (axis < 3))
     1043                        {
     1044                                m_linERP = value;
     1045                                m_flags |= BT_CONETWIST_FLAGS_LIN_ERP;
     1046                        }
     1047                        else
     1048                        {
     1049                                m_biasFactor = value;
     1050                        }
     1051                        break;
     1052                case BT_CONSTRAINT_CFM :
     1053                case BT_CONSTRAINT_STOP_CFM :
     1054                        if((axis >= 0) && (axis < 3))
     1055                        {
     1056                                m_linCFM = value;
     1057                                m_flags |= BT_CONETWIST_FLAGS_LIN_CFM;
     1058                        }
     1059                        else
     1060                        {
     1061                                m_angCFM = value;
     1062                                m_flags |= BT_CONETWIST_FLAGS_ANG_CFM;
     1063                        }
     1064                        break;
     1065                default:
     1066                        btAssertConstrParams(0);
     1067                        break;
     1068        }
     1069}
     1070
     1071///return the local value of parameter
     1072btScalar btConeTwistConstraint::getParam(int num, int axis) const
     1073{
     1074        btScalar retVal = 0;
     1075        switch(num)
     1076        {
     1077                case BT_CONSTRAINT_ERP :
     1078                case BT_CONSTRAINT_STOP_ERP :
     1079                        if((axis >= 0) && (axis < 3))
     1080                        {
     1081                                btAssertConstrParams(m_flags & BT_CONETWIST_FLAGS_LIN_ERP);
     1082                                retVal = m_linERP;
     1083                        }
     1084                        else if((axis >= 3) && (axis < 6))
     1085                        {
     1086                                retVal = m_biasFactor;
     1087                        }
     1088                        else
     1089                        {
     1090                                btAssertConstrParams(0);
     1091                        }
     1092                        break;
     1093                case BT_CONSTRAINT_CFM :
     1094                case BT_CONSTRAINT_STOP_CFM :
     1095                        if((axis >= 0) && (axis < 3))
     1096                        {
     1097                                btAssertConstrParams(m_flags & BT_CONETWIST_FLAGS_LIN_CFM);
     1098                                retVal = m_linCFM;
     1099                        }
     1100                        else if((axis >= 3) && (axis < 6))
     1101                        {
     1102                                btAssertConstrParams(m_flags & BT_CONETWIST_FLAGS_ANG_CFM);
     1103                                retVal = m_angCFM;
     1104                        }
     1105                        else
     1106                        {
     1107                                btAssertConstrParams(0);
     1108                        }
     1109                        break;
     1110                default :
     1111                        btAssertConstrParams(0);
     1112        }
     1113        return retVal;
     1114}
     1115
     1116
     1117
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h

    r5781 r8284  
    1818
    1919
     20/*
     21Overview:
     22
     23btConeTwistConstraint can be used to simulate ragdoll joints (upper arm, leg etc).
     24It is a fixed translation, 3 degree-of-freedom (DOF) rotational "joint".
     25It divides the 3 rotational DOFs into swing (movement within a cone) and twist.
     26Swing is divided into swing1 and swing2 which can have different limits, giving an elliptical shape.
     27(Note: the cone's base isn't flat, so this ellipse is "embedded" on the surface of a sphere.)
     28
     29In the contraint's frame of reference:
     30twist is along the x-axis,
     31and swing 1 and 2 are along the z and y axes respectively.
     32*/
     33
     34
     35
    2036#ifndef CONETWISTCONSTRAINT_H
    2137#define CONETWISTCONSTRAINT_H
     
    2743class btRigidBody;
    2844
     45enum btConeTwistFlags
     46{
     47        BT_CONETWIST_FLAGS_LIN_CFM = 1,
     48        BT_CONETWIST_FLAGS_LIN_ERP = 2,
     49        BT_CONETWIST_FLAGS_ANG_CFM = 4
     50};
    2951
    3052///btConeTwistConstraint can be used to simulate ragdoll joints (upper arm, leg etc)
     
    84106        btVector3        m_accMotorImpulse;
    85107       
     108        // parameters
     109        int                     m_flags;
     110        btScalar        m_linCFM;
     111        btScalar        m_linERP;
     112        btScalar        m_angCFM;
     113       
     114protected:
     115
     116        void init();
     117
     118        void computeConeLimitInfo(const btQuaternion& qCone, // in
     119                btScalar& swingAngle, btVector3& vSwingAxis, btScalar& swingLimit); // all outs
     120
     121        void computeTwistLimitInfo(const btQuaternion& qTwist, // in
     122                btScalar& twistAngle, btVector3& vTwistAxis); // all outs
     123
     124        void adjustSwingAxisToUseEllipseNormal(btVector3& vSwingAxis) const;
     125
     126
    86127public:
    87128
     
    90131        btConeTwistConstraint(btRigidBody& rbA,const btTransform& rbAFrame);
    91132
    92         btConeTwistConstraint();
    93 
    94133        virtual void    buildJacobian();
    95134
    96135        virtual void getInfo1 (btConstraintInfo1* info);
     136
     137        void    getInfo1NonVirtual(btConstraintInfo1* info);
    97138       
    98139        virtual void getInfo2 (btConstraintInfo2* info);
    99140       
    100 
    101         virtual void    solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar        timeStep);
     141        void    getInfo2NonVirtual(btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btMatrix3x3& invInertiaWorldA,const btMatrix3x3& invInertiaWorldB);
     142
     143        virtual void    solveConstraintObsolete(btRigidBody& bodyA,btRigidBody& bodyB,btScalar  timeStep);
    102144
    103145        void    updateRHS(btScalar      timeStep);
     
    142184        }
    143185
    144         void    setLimit(btScalar _swingSpan1,btScalar _swingSpan2,btScalar _twistSpan,  btScalar _softness = 1.f, btScalar _biasFactor = 0.3f, btScalar _relaxationFactor = 1.0f)
     186        // setLimit(), a few notes:
     187        // _softness:
     188        //              0->1, recommend ~0.8->1.
     189        //              describes % of limits where movement is free.
     190        //              beyond this softness %, the limit is gradually enforced until the "hard" (1.0) limit is reached.
     191        // _biasFactor:
     192        //              0->1?, recommend 0.3 +/-0.3 or so.
     193        //              strength with which constraint resists zeroth order (angular, not angular velocity) limit violation.
     194        // __relaxationFactor:
     195        //              0->1, recommend to stay near 1.
     196        //              the lower the value, the less the constraint will fight velocities which violate the angular limits.
     197        void    setLimit(btScalar _swingSpan1,btScalar _swingSpan2,btScalar _twistSpan, btScalar _softness = 1.f, btScalar _biasFactor = 0.3f, btScalar _relaxationFactor = 1.0f)
    145198        {
    146199                m_swingSpan1 = _swingSpan1;
     
    172225
    173226        void calcAngleInfo();
    174         void calcAngleInfo2();
     227        void calcAngleInfo2(const btTransform& transA, const btTransform& transB,const btMatrix3x3& invInertiaWorldA,const btMatrix3x3& invInertiaWorldB);
    175228
    176229        inline btScalar getSwingSpan1()
     
    213266        btVector3 GetPointForAngle(btScalar fAngleInRadians, btScalar fLength) const;
    214267
    215 
    216 
    217 protected:
    218         void init();
    219 
    220         void computeConeLimitInfo(const btQuaternion& qCone, // in
    221                 btScalar& swingAngle, btVector3& vSwingAxis, btScalar& swingLimit); // all outs
    222 
    223         void computeTwistLimitInfo(const btQuaternion& qTwist, // in
    224                 btScalar& twistAngle, btVector3& vTwistAxis); // all outs
    225 
    226         void adjustSwingAxisToUseEllipseNormal(btVector3& vSwingAxis) const;
     268        ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     269        ///If no axis is provided, it uses the default axis for this constraint.
     270        virtual void setParam(int num, btScalar value, int axis = -1);
     271        ///return the local value of parameter
     272        virtual btScalar getParam(int num, int axis = -1) const;
     273
     274        virtual int     calculateSerializeBufferSize() const;
     275
     276        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     277        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     278
    227279};
    228280
     281///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     282struct  btConeTwistConstraintData
     283{
     284        btTypedConstraintData   m_typeConstraintData;
     285        btTransformFloatData m_rbAFrame;
     286        btTransformFloatData m_rbBFrame;
     287
     288        //limits
     289        float   m_swingSpan1;
     290        float   m_swingSpan2;
     291        float   m_twistSpan;
     292        float   m_limitSoftness;
     293        float   m_biasFactor;
     294        float   m_relaxationFactor;
     295
     296        float   m_damping;
     297               
     298        char m_pad[4];
     299
     300};
     301       
     302
     303
     304SIMD_FORCE_INLINE int   btConeTwistConstraint::calculateSerializeBufferSize() const
     305{
     306        return sizeof(btConeTwistConstraintData);
     307
     308}
     309
     310
     311        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     312SIMD_FORCE_INLINE const char*   btConeTwistConstraint::serialize(void* dataBuffer, btSerializer* serializer) const
     313{
     314        btConeTwistConstraintData* cone = (btConeTwistConstraintData*) dataBuffer;
     315        btTypedConstraint::serialize(&cone->m_typeConstraintData,serializer);
     316
     317        m_rbAFrame.serializeFloat(cone->m_rbAFrame);
     318        m_rbBFrame.serializeFloat(cone->m_rbBFrame);
     319       
     320        cone->m_swingSpan1 = float(m_swingSpan1);
     321        cone->m_swingSpan2 = float(m_swingSpan2);
     322        cone->m_twistSpan = float(m_twistSpan);
     323        cone->m_limitSoftness = float(m_limitSoftness);
     324        cone->m_biasFactor = float(m_biasFactor);
     325        cone->m_relaxationFactor = float(m_relaxationFactor);
     326        cone->m_damping = float(m_damping);
     327
     328        return "btConeTwistConstraintData";
     329}
     330
     331
    229332#endif //CONETWISTCONSTRAINT_H
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btContactConstraint.cpp

    r5781 r8284  
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
     16
     17#include "btContactConstraint.h"
     18#include "BulletDynamics/Dynamics/btRigidBody.h"
     19#include "LinearMath/btVector3.h"
     20#include "btJacobianEntry.h"
     21#include "btContactSolverInfo.h"
     22#include "LinearMath/btMinMax.h"
     23#include "BulletCollision/NarrowPhaseCollision/btManifoldPoint.h"
     24
     25
     26
     27btContactConstraint::btContactConstraint(btPersistentManifold* contactManifold,btRigidBody& rbA,btRigidBody& rbB)
     28:btTypedConstraint(CONTACT_CONSTRAINT_TYPE,rbA,rbB),
     29        m_contactManifold(*contactManifold)
     30{
     31
     32}
     33
     34btContactConstraint::~btContactConstraint()
     35{
     36
     37}
     38
     39void    btContactConstraint::setContactManifold(btPersistentManifold* contactManifold)
     40{
     41        m_contactManifold = *contactManifold;
     42}
     43
     44void btContactConstraint::getInfo1 (btConstraintInfo1* info)
     45{
     46
     47}
     48
     49void btContactConstraint::getInfo2 (btConstraintInfo2* info)
     50{
     51
     52}
     53
     54void    btContactConstraint::buildJacobian()
     55{
     56
     57}
     58
     59
     60
    1561
    1662
     
    86132
    87133
    88 //response  between two dynamic objects with friction
    89 btScalar resolveSingleCollision(
    90         btRigidBody& body1,
    91         btRigidBody& body2,
    92         btManifoldPoint& contactPoint,
    93         const btContactSolverInfo& solverInfo)
    94 {
    95134
    96         const btVector3& pos1_ = contactPoint.getPositionWorldOnA();
    97         const btVector3& pos2_ = contactPoint.getPositionWorldOnB();
    98         const btVector3& normal = contactPoint.m_normalWorldOnB;
    99 
    100         //constant over all iterations
    101         btVector3 rel_pos1 = pos1_ - body1.getCenterOfMassPosition();
    102         btVector3 rel_pos2 = pos2_ - body2.getCenterOfMassPosition();
    103        
    104         btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1);
    105         btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2);
    106         btVector3 vel = vel1 - vel2;
    107         btScalar rel_vel;
    108         rel_vel = normal.dot(vel);
    109        
    110         btScalar Kfps = btScalar(1.) / solverInfo.m_timeStep ;
    111 
    112         // btScalar damping = solverInfo.m_damping ;
    113         btScalar Kerp = solverInfo.m_erp;
    114         btScalar Kcor = Kerp *Kfps;
    115 
    116         btConstraintPersistentData* cpd = (btConstraintPersistentData*) contactPoint.m_userPersistentData;
    117         btAssert(cpd);
    118         btScalar distance = cpd->m_penetration;
    119         btScalar positionalError = Kcor *-distance;
    120         btScalar velocityError = cpd->m_restitution - rel_vel;// * damping;
    121 
    122         btScalar penetrationImpulse = positionalError * cpd->m_jacDiagABInv;
    123 
    124         btScalar        velocityImpulse = velocityError * cpd->m_jacDiagABInv;
    125 
    126         btScalar normalImpulse = penetrationImpulse+velocityImpulse;
    127        
    128         // See Erin Catto's GDC 2006 paper: Clamp the accumulated impulse
    129         btScalar oldNormalImpulse = cpd->m_appliedImpulse;
    130         btScalar sum = oldNormalImpulse + normalImpulse;
    131         cpd->m_appliedImpulse = btScalar(0.) > sum ? btScalar(0.): sum;
    132 
    133         normalImpulse = cpd->m_appliedImpulse - oldNormalImpulse;
    134 
    135 #ifdef USE_INTERNAL_APPLY_IMPULSE
    136         if (body1.getInvMass())
    137         {
    138                 body1.internalApplyImpulse(contactPoint.m_normalWorldOnB*body1.getInvMass(),cpd->m_angularComponentA,normalImpulse);
    139         }
    140         if (body2.getInvMass())
    141         {
    142                 body2.internalApplyImpulse(contactPoint.m_normalWorldOnB*body2.getInvMass(),cpd->m_angularComponentB,-normalImpulse);
    143         }
    144 #else //USE_INTERNAL_APPLY_IMPULSE
    145         body1.applyImpulse(normal*(normalImpulse), rel_pos1);
    146         body2.applyImpulse(-normal*(normalImpulse), rel_pos2);
    147 #endif //USE_INTERNAL_APPLY_IMPULSE
    148 
    149         return normalImpulse;
    150 }
    151 
    152 
    153 btScalar resolveSingleFriction(
    154         btRigidBody& body1,
    155         btRigidBody& body2,
    156         btManifoldPoint& contactPoint,
    157         const btContactSolverInfo& solverInfo)
    158 {
    159 
    160         (void)solverInfo;
    161 
    162         const btVector3& pos1 = contactPoint.getPositionWorldOnA();
    163         const btVector3& pos2 = contactPoint.getPositionWorldOnB();
    164 
    165         btVector3 rel_pos1 = pos1 - body1.getCenterOfMassPosition();
    166         btVector3 rel_pos2 = pos2 - body2.getCenterOfMassPosition();
    167        
    168         btConstraintPersistentData* cpd = (btConstraintPersistentData*) contactPoint.m_userPersistentData;
    169         btAssert(cpd);
    170 
    171         btScalar combinedFriction = cpd->m_friction;
    172        
    173         btScalar limit = cpd->m_appliedImpulse * combinedFriction;
    174        
    175         if (cpd->m_appliedImpulse>btScalar(0.))
    176         //friction
    177         {
    178                 //apply friction in the 2 tangential directions
    179                
    180                 // 1st tangent
    181                 btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1);
    182                 btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2);
    183                 btVector3 vel = vel1 - vel2;
    184        
    185                 btScalar j1,j2;
    186 
    187                 {
    188                                
    189                         btScalar vrel = cpd->m_frictionWorldTangential0.dot(vel);
    190 
    191                         // calculate j that moves us to zero relative velocity
    192                         j1 = -vrel * cpd->m_jacDiagABInvTangent0;
    193                         btScalar oldTangentImpulse = cpd->m_accumulatedTangentImpulse0;
    194                         cpd->m_accumulatedTangentImpulse0 = oldTangentImpulse + j1;
    195                         btSetMin(cpd->m_accumulatedTangentImpulse0, limit);
    196                         btSetMax(cpd->m_accumulatedTangentImpulse0, -limit);
    197                         j1 = cpd->m_accumulatedTangentImpulse0 - oldTangentImpulse;
    198 
    199                 }
    200                 {
    201                         // 2nd tangent
    202 
    203                         btScalar vrel = cpd->m_frictionWorldTangential1.dot(vel);
    204                        
    205                         // calculate j that moves us to zero relative velocity
    206                         j2 = -vrel * cpd->m_jacDiagABInvTangent1;
    207                         btScalar oldTangentImpulse = cpd->m_accumulatedTangentImpulse1;
    208                         cpd->m_accumulatedTangentImpulse1 = oldTangentImpulse + j2;
    209                         btSetMin(cpd->m_accumulatedTangentImpulse1, limit);
    210                         btSetMax(cpd->m_accumulatedTangentImpulse1, -limit);
    211                         j2 = cpd->m_accumulatedTangentImpulse1 - oldTangentImpulse;
    212                 }
    213 
    214 #ifdef USE_INTERNAL_APPLY_IMPULSE
    215         if (body1.getInvMass())
    216         {
    217                 body1.internalApplyImpulse(cpd->m_frictionWorldTangential0*body1.getInvMass(),cpd->m_frictionAngularComponent0A,j1);
    218                 body1.internalApplyImpulse(cpd->m_frictionWorldTangential1*body1.getInvMass(),cpd->m_frictionAngularComponent1A,j2);
    219         }
    220         if (body2.getInvMass())
    221         {
    222                 body2.internalApplyImpulse(cpd->m_frictionWorldTangential0*body2.getInvMass(),cpd->m_frictionAngularComponent0B,-j1);
    223                 body2.internalApplyImpulse(cpd->m_frictionWorldTangential1*body2.getInvMass(),cpd->m_frictionAngularComponent1B,-j2);   
    224         }
    225 #else //USE_INTERNAL_APPLY_IMPULSE
    226         body1.applyImpulse((j1 * cpd->m_frictionWorldTangential0)+(j2 * cpd->m_frictionWorldTangential1), rel_pos1);
    227         body2.applyImpulse((j1 * -cpd->m_frictionWorldTangential0)+(j2 * -cpd->m_frictionWorldTangential1), rel_pos2);
    228 #endif //USE_INTERNAL_APPLY_IMPULSE
    229 
    230 
    231         }
    232         return cpd->m_appliedImpulse;
    233 }
    234 
    235 
    236 btScalar resolveSingleFrictionOriginal(
    237         btRigidBody& body1,
    238         btRigidBody& body2,
    239         btManifoldPoint& contactPoint,
    240         const btContactSolverInfo& solverInfo);
    241 
    242 btScalar resolveSingleFrictionOriginal(
    243         btRigidBody& body1,
    244         btRigidBody& body2,
    245         btManifoldPoint& contactPoint,
    246         const btContactSolverInfo& solverInfo)
    247 {
    248 
    249         (void)solverInfo;
    250 
    251         const btVector3& pos1 = contactPoint.getPositionWorldOnA();
    252         const btVector3& pos2 = contactPoint.getPositionWorldOnB();
    253 
    254         btVector3 rel_pos1 = pos1 - body1.getCenterOfMassPosition();
    255         btVector3 rel_pos2 = pos2 - body2.getCenterOfMassPosition();
    256        
    257         btConstraintPersistentData* cpd = (btConstraintPersistentData*) contactPoint.m_userPersistentData;
    258         btAssert(cpd);
    259 
    260         btScalar combinedFriction = cpd->m_friction;
    261        
    262         btScalar limit = cpd->m_appliedImpulse * combinedFriction;
    263         //if (contactPoint.m_appliedImpulse>btScalar(0.))
    264         //friction
    265         {
    266                 //apply friction in the 2 tangential directions
    267                
    268                 {
    269                         // 1st tangent
    270                         btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1);
    271                         btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2);
    272                         btVector3 vel = vel1 - vel2;
    273                        
    274                         btScalar vrel = cpd->m_frictionWorldTangential0.dot(vel);
    275 
    276                         // calculate j that moves us to zero relative velocity
    277                         btScalar j = -vrel * cpd->m_jacDiagABInvTangent0;
    278                         btScalar total = cpd->m_accumulatedTangentImpulse0 + j;
    279                         btSetMin(total, limit);
    280                         btSetMax(total, -limit);
    281                         j = total - cpd->m_accumulatedTangentImpulse0;
    282                         cpd->m_accumulatedTangentImpulse0 = total;
    283                         body1.applyImpulse(j * cpd->m_frictionWorldTangential0, rel_pos1);
    284                         body2.applyImpulse(j * -cpd->m_frictionWorldTangential0, rel_pos2);
    285                 }
    286 
    287                                
    288                 {
    289                         // 2nd tangent
    290                         btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1);
    291                         btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2);
    292                         btVector3 vel = vel1 - vel2;
    293 
    294                         btScalar vrel = cpd->m_frictionWorldTangential1.dot(vel);
    295                        
    296                         // calculate j that moves us to zero relative velocity
    297                         btScalar j = -vrel * cpd->m_jacDiagABInvTangent1;
    298                         btScalar total = cpd->m_accumulatedTangentImpulse1 + j;
    299                         btSetMin(total, limit);
    300                         btSetMax(total, -limit);
    301                         j = total - cpd->m_accumulatedTangentImpulse1;
    302                         cpd->m_accumulatedTangentImpulse1 = total;
    303                         body1.applyImpulse(j * cpd->m_frictionWorldTangential1, rel_pos1);
    304                         body2.applyImpulse(j * -cpd->m_frictionWorldTangential1, rel_pos2);
    305                 }
    306         }
    307         return cpd->m_appliedImpulse;
    308 }
    309 
    310 
    311 //velocity + friction
    312 //response  between two dynamic objects with friction
    313 btScalar resolveSingleCollisionCombined(
    314         btRigidBody& body1,
    315         btRigidBody& body2,
    316         btManifoldPoint& contactPoint,
    317         const btContactSolverInfo& solverInfo)
    318 {
    319 
    320         const btVector3& pos1 = contactPoint.getPositionWorldOnA();
    321         const btVector3& pos2 = contactPoint.getPositionWorldOnB();
    322         const btVector3& normal = contactPoint.m_normalWorldOnB;
    323 
    324         btVector3 rel_pos1 = pos1 - body1.getCenterOfMassPosition();
    325         btVector3 rel_pos2 = pos2 - body2.getCenterOfMassPosition();
    326        
    327         btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1);
    328         btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2);
    329         btVector3 vel = vel1 - vel2;
    330         btScalar rel_vel;
    331         rel_vel = normal.dot(vel);
    332        
    333         btScalar Kfps = btScalar(1.) / solverInfo.m_timeStep ;
    334 
    335         //btScalar damping = solverInfo.m_damping ;
    336         btScalar Kerp = solverInfo.m_erp;
    337         btScalar Kcor = Kerp *Kfps;
    338 
    339         btConstraintPersistentData* cpd = (btConstraintPersistentData*) contactPoint.m_userPersistentData;
    340         btAssert(cpd);
    341         btScalar distance = cpd->m_penetration;
    342         btScalar positionalError = Kcor *-distance;
    343         btScalar velocityError = cpd->m_restitution - rel_vel;// * damping;
    344 
    345         btScalar penetrationImpulse = positionalError * cpd->m_jacDiagABInv;
    346 
    347         btScalar        velocityImpulse = velocityError * cpd->m_jacDiagABInv;
    348 
    349         btScalar normalImpulse = penetrationImpulse+velocityImpulse;
    350        
    351         // See Erin Catto's GDC 2006 paper: Clamp the accumulated impulse
    352         btScalar oldNormalImpulse = cpd->m_appliedImpulse;
    353         btScalar sum = oldNormalImpulse + normalImpulse;
    354         cpd->m_appliedImpulse = btScalar(0.) > sum ? btScalar(0.): sum;
    355 
    356         normalImpulse = cpd->m_appliedImpulse - oldNormalImpulse;
    357 
    358 
    359 #ifdef USE_INTERNAL_APPLY_IMPULSE
    360         if (body1.getInvMass())
    361         {
    362                 body1.internalApplyImpulse(contactPoint.m_normalWorldOnB*body1.getInvMass(),cpd->m_angularComponentA,normalImpulse);
    363         }
    364         if (body2.getInvMass())
    365         {
    366                 body2.internalApplyImpulse(contactPoint.m_normalWorldOnB*body2.getInvMass(),cpd->m_angularComponentB,-normalImpulse);
    367         }
    368 #else //USE_INTERNAL_APPLY_IMPULSE
    369         body1.applyImpulse(normal*(normalImpulse), rel_pos1);
    370         body2.applyImpulse(-normal*(normalImpulse), rel_pos2);
    371 #endif //USE_INTERNAL_APPLY_IMPULSE
    372 
    373         {
    374                 //friction
    375                 btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1);
    376                 btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2);
    377                 btVector3 vel = vel1 - vel2;
    378          
    379                 rel_vel = normal.dot(vel);
    380 
    381 
    382                 btVector3 lat_vel = vel - normal * rel_vel;
    383                 btScalar lat_rel_vel = lat_vel.length();
    384 
    385                 btScalar combinedFriction = cpd->m_friction;
    386 
    387                 if (cpd->m_appliedImpulse > 0)
    388                 if (lat_rel_vel > SIMD_EPSILON)
    389                 {
    390                         lat_vel /= lat_rel_vel;
    391                         btVector3 temp1 = body1.getInvInertiaTensorWorld() * rel_pos1.cross(lat_vel);
    392                         btVector3 temp2 = body2.getInvInertiaTensorWorld() * rel_pos2.cross(lat_vel);
    393                         btScalar friction_impulse = lat_rel_vel /
    394                                 (body1.getInvMass() + body2.getInvMass() + lat_vel.dot(temp1.cross(rel_pos1) + temp2.cross(rel_pos2)));
    395                         btScalar normal_impulse = cpd->m_appliedImpulse * combinedFriction;
    396 
    397                         btSetMin(friction_impulse, normal_impulse);
    398                         btSetMax(friction_impulse, -normal_impulse);
    399                         body1.applyImpulse(lat_vel * -friction_impulse, rel_pos1);
    400                         body2.applyImpulse(lat_vel * friction_impulse, rel_pos2);
    401                 }
    402         }
    403 
    404 
    405 
    406         return normalImpulse;
    407 }
    408 
    409 btScalar resolveSingleFrictionEmpty(
    410         btRigidBody& body1,
    411         btRigidBody& body2,
    412         btManifoldPoint& contactPoint,
    413         const btContactSolverInfo& solverInfo);
    414 
    415 btScalar resolveSingleFrictionEmpty(
    416         btRigidBody& body1,
    417         btRigidBody& body2,
    418         btManifoldPoint& contactPoint,
    419         const btContactSolverInfo& solverInfo)
    420 {
    421         (void)contactPoint;
    422         (void)body1;
    423         (void)body2;
    424         (void)solverInfo;
    425 
    426 
    427         return btScalar(0.);
    428 }
    429 
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btContactConstraint.h

    r5781 r8284  
    1717#define CONTACT_CONSTRAINT_H
    1818
    19 ///@todo: make into a proper class working with the iterative constraint solver
     19#include "LinearMath/btVector3.h"
     20#include "btJacobianEntry.h"
     21#include "btTypedConstraint.h"
     22#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
    2023
    21 class btRigidBody;
    22 #include "LinearMath/btVector3.h"
    23 #include "LinearMath/btScalar.h"
    24 struct btContactSolverInfo;
    25 class btManifoldPoint;
     24///btContactConstraint can be automatically created to solve contact constraints using the unified btTypedConstraint interface
     25ATTRIBUTE_ALIGNED16(class) btContactConstraint : public btTypedConstraint
     26{
     27protected:
    2628
    27 enum {
    28         DEFAULT_CONTACT_SOLVER_TYPE=0,
    29         CONTACT_SOLVER_TYPE1,
    30         CONTACT_SOLVER_TYPE2,
    31         USER_CONTACT_SOLVER_TYPE1,
    32         MAX_CONTACT_SOLVER_TYPES
     29        btPersistentManifold m_contactManifold;
     30
     31public:
     32
     33
     34        btContactConstraint(btPersistentManifold* contactManifold,btRigidBody& rbA,btRigidBody& rbB);
     35
     36        void    setContactManifold(btPersistentManifold* contactManifold);
     37
     38        btPersistentManifold* getContactManifold()
     39        {
     40                return &m_contactManifold;
     41        }
     42
     43        const btPersistentManifold* getContactManifold() const
     44        {
     45                return &m_contactManifold;
     46        }
     47
     48        virtual ~btContactConstraint();
     49
     50        virtual void getInfo1 (btConstraintInfo1* info);
     51
     52        virtual void getInfo2 (btConstraintInfo2* info);
     53
     54        ///obsolete methods
     55        virtual void    buildJacobian();
     56
     57
    3358};
    3459
    3560
    36 typedef btScalar (*ContactSolverFunc)(btRigidBody& body1,
    37                                                                          btRigidBody& body2,
    38                                                                          class btManifoldPoint& contactPoint,
    39                                                                          const btContactSolverInfo& info);
    40 
    41 ///stores some extra information to each contact point. It is not in the contact point, because that want to keep the collision detection independent from the constraint solver.
    42 struct btConstraintPersistentData
    43 {
    44         inline btConstraintPersistentData()
    45         :m_appliedImpulse(btScalar(0.)),
    46         m_prevAppliedImpulse(btScalar(0.)),
    47         m_accumulatedTangentImpulse0(btScalar(0.)),
    48         m_accumulatedTangentImpulse1(btScalar(0.)),
    49         m_jacDiagABInv(btScalar(0.)),
    50         m_persistentLifeTime(0),
    51         m_restitution(btScalar(0.)),
    52         m_friction(btScalar(0.)),
    53         m_penetration(btScalar(0.)),
    54         m_contactSolverFunc(0),
    55         m_frictionSolverFunc(0)
    56         {
    57         }
    58        
    59                                        
    60                                 /// total applied impulse during most recent frame
    61                         btScalar        m_appliedImpulse;
    62                         btScalar        m_prevAppliedImpulse;
    63                         btScalar        m_accumulatedTangentImpulse0;
    64                         btScalar        m_accumulatedTangentImpulse1;
    65                        
    66                         btScalar        m_jacDiagABInv;
    67                         btScalar        m_jacDiagABInvTangent0;
    68                         btScalar        m_jacDiagABInvTangent1;
    69                         int             m_persistentLifeTime;
    70                         btScalar        m_restitution;
    71                         btScalar        m_friction;
    72                         btScalar        m_penetration;
    73                         btVector3       m_frictionWorldTangential0;
    74                         btVector3       m_frictionWorldTangential1;
    75 
    76                         btVector3       m_frictionAngularComponent0A;
    77                         btVector3       m_frictionAngularComponent0B;
    78                         btVector3       m_frictionAngularComponent1A;
    79                         btVector3       m_frictionAngularComponent1B;
    80 
    81                         //some data doesn't need to be persistent over frames: todo: clean/reuse this
    82                         btVector3       m_angularComponentA;
    83                         btVector3       m_angularComponentB;
    84                
    85                         ContactSolverFunc       m_contactSolverFunc;
    86                         ContactSolverFunc       m_frictionSolverFunc;
    87 
    88 };
    89 
    90 ///bilateral constraint between two dynamic objects
    91 ///positive distance = separation, negative distance = penetration
     61///resolveSingleBilateral is an obsolete methods used for vehicle friction between two dynamic objects
    9262void resolveSingleBilateral(btRigidBody& body1, const btVector3& pos1,
    9363                      btRigidBody& body2, const btVector3& pos2,
     
    9565
    9666
    97 ///contact constraint resolution:
    98 ///calculate and apply impulse to satisfy non-penetration and non-negative relative velocity constraint
    99 ///positive distance = separation, negative distance = penetration
    100 btScalar resolveSingleCollision(
    101         btRigidBody& body1,
    102         btRigidBody& body2,
    103                 btManifoldPoint& contactPoint,
    104                  const btContactSolverInfo& info);
    105 
    106 btScalar resolveSingleFriction(
    107         btRigidBody& body1,
    108         btRigidBody& body2,
    109         btManifoldPoint& contactPoint,
    110         const btContactSolverInfo& solverInfo
    111                 );
    112 
    113 
    114 
    115 btScalar resolveSingleCollisionCombined(
    116         btRigidBody& body1,
    117         btRigidBody& body2,
    118         btManifoldPoint& contactPoint,
    119         const btContactSolverInfo& solverInfo
    120                 );
    12167
    12268#endif //CONTACT_CONSTRAINT_H
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btContactSolverInfo.h

    r5781 r8284  
    3636
    3737        btScalar        m_tau;
    38         btScalar        m_damping;
     38        btScalar        m_damping;//global non-contact constraint damping, can be locally overridden by constraints during 'getInfo2'.
    3939        btScalar        m_friction;
    4040        btScalar        m_timeStep;
     
    5353        int                     m_solverMode;
    5454        int     m_restingContactRestitutionThreshold;
     55        int                     m_minimumSolverBatchSize;
    5556
    5657
     
    7879                m_linearSlop = btScalar(0.0);
    7980                m_warmstartingFactor=btScalar(0.85);
    80                 m_solverMode = SOLVER_USE_WARMSTARTING | SOLVER_SIMD ;//SOLVER_RANDMIZE_ORDER
     81                m_solverMode = SOLVER_USE_WARMSTARTING | SOLVER_SIMD;// | SOLVER_RANDMIZE_ORDER;
    8182                m_restingContactRestitutionThreshold = 2;//resting contact lifetime threshold to disable restitution
     83                m_minimumSolverBatchSize = 128; //try to combine islands until the amount of constraints reaches this limit
    8284        }
    8385};
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.cpp

    r5781 r8284  
    2323#include "BulletDynamics/Dynamics/btRigidBody.h"
    2424#include "LinearMath/btTransformUtil.h"
     25#include "LinearMath/btTransformUtil.h"
    2526#include <new>
    2627
    2728
     29
    2830#define D6_USE_OBSOLETE_METHOD false
    29 //-----------------------------------------------------------------------------
    30 
    31 btGeneric6DofConstraint::btGeneric6DofConstraint()
    32 :btTypedConstraint(D6_CONSTRAINT_TYPE),
    33 m_useLinearReferenceFrameA(true),
    34 m_useSolveConstraintObsolete(D6_USE_OBSOLETE_METHOD)
    35 {
    36 }
    37 
    38 //-----------------------------------------------------------------------------
     31#define D6_USE_FRAME_OFFSET true
     32
     33
     34
     35
     36
    3937
    4038btGeneric6DofConstraint::btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB, bool useLinearReferenceFrameA)
     
    4341, m_frameInB(frameInB),
    4442m_useLinearReferenceFrameA(useLinearReferenceFrameA),
     43m_useOffsetForConstraintFrame(D6_USE_FRAME_OFFSET),
     44m_flags(0),
    4545m_useSolveConstraintObsolete(D6_USE_OBSOLETE_METHOD)
    4646{
    47 
    48 }
    49 //-----------------------------------------------------------------------------
     47        calculateTransforms();
     48}
     49
     50
     51
     52btGeneric6DofConstraint::btGeneric6DofConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameB)
     53        : btTypedConstraint(D6_CONSTRAINT_TYPE, getFixedBody(), rbB),
     54                m_frameInB(frameInB),
     55                m_useLinearReferenceFrameA(useLinearReferenceFrameB),
     56                m_useOffsetForConstraintFrame(D6_USE_FRAME_OFFSET),
     57                m_flags(0),
     58                m_useSolveConstraintObsolete(false)
     59{
     60        ///not providing rigidbody A means implicitly using worldspace for body A
     61        m_frameInA = rbB.getCenterOfMassTransform() * m_frameInB;
     62        calculateTransforms();
     63}
     64
     65
    5066
    5167
    5268#define GENERIC_D6_DISABLE_WARMSTARTING 1
    5369
    54 //-----------------------------------------------------------------------------
     70
    5571
    5672btScalar btGetMatrixElem(const btMatrix3x3& mat, int index);
     
    6278}
    6379
    64 //-----------------------------------------------------------------------------
     80
    6581
    6682///MatrixToEulerXYZ from http://www.geometrictools.com/LibFoundation/Mathematics/Wm4Matrix3.inl.html
     
    111127                return 0;
    112128        }
    113 
    114129        if (test_value < m_loLimit)
    115130        {
     
    130145}
    131146
    132 //-----------------------------------------------------------------------------
     147
    133148
    134149btScalar btRotationalLimitMotor::solveAngularLimits(
    135150        btScalar timeStep,btVector3& axis,btScalar jacDiagABInv,
    136         btRigidBody * body0, btSolverBody& bodyA, btRigidBody * body1, btSolverBody& bodyB)
     151        btRigidBody * body0, btRigidBody * body1 )
    137152{
    138153        if (needApplyTorques()==false) return 0.0f;
     
    144159        if (m_currentLimit!=0)
    145160        {
    146                 target_velocity = -m_ERP*m_currentLimitError/(timeStep);
     161                target_velocity = -m_stopERP*m_currentLimitError/(timeStep);
    147162                maxMotorForce = m_maxLimitForce;
    148163        }
     
    153168
    154169        btVector3 angVelA;
    155         bodyA.getAngularVelocity(angVelA);
     170        body0->internalGetAngularVelocity(angVelA);
    156171        btVector3 angVelB;
    157         bodyB.getAngularVelocity(angVelB);
     172        body1->internalGetAngularVelocity(angVelB);
    158173
    159174        btVector3 vel_diff;
     
    192207
    193208        // sort with accumulated impulses
    194         btScalar        lo = btScalar(-1e30);
    195         btScalar        hi = btScalar(1e30);
     209        btScalar        lo = btScalar(-BT_LARGE_FLOAT);
     210        btScalar        hi = btScalar(BT_LARGE_FLOAT);
    196211
    197212        btScalar oldaccumImpulse = m_accumulatedImpulse;
     
    206221        //body1->applyTorqueImpulse(-motorImp);
    207222
    208         bodyA.applyImpulse(btVector3(0,0,0), body0->getInvInertiaTensorWorld()*axis,clippedMotorImpulse);
    209         bodyB.applyImpulse(btVector3(0,0,0), body1->getInvInertiaTensorWorld()*axis,-clippedMotorImpulse);
     223        body0->internalApplyImpulse(btVector3(0,0,0), body0->getInvInertiaTensorWorld()*axis,clippedMotorImpulse);
     224        body1->internalApplyImpulse(btVector3(0,0,0), body1->getInvInertiaTensorWorld()*axis,-clippedMotorImpulse);
    210225
    211226
     
    250265        m_currentLimitError[limitIndex] = btScalar(0.f);
    251266        return 0;
    252 } // btTranslationalLimitMotor::testLimitValue()
    253 
    254 //-----------------------------------------------------------------------------
     267}
     268
     269
    255270
    256271btScalar btTranslationalLimitMotor::solveLinearAxis(
    257272        btScalar timeStep,
    258273        btScalar jacDiagABInv,
    259         btRigidBody& body1,btSolverBody& bodyA,const btVector3 &pointInA,
    260         btRigidBody& body2,btSolverBody& bodyB,const btVector3 &pointInB,
     274        btRigidBody& body1,const btVector3 &pointInA,
     275        btRigidBody& body2,const btVector3 &pointInB,
    261276        int limit_index,
    262277        const btVector3 & axis_normal_on_a,
     
    271286
    272287        btVector3 vel1;
    273         bodyA.getVelocityInLocalPointObsolete(rel_pos1,vel1);
     288        body1.internalGetVelocityInLocalPointObsolete(rel_pos1,vel1);
    274289        btVector3 vel2;
    275         bodyB.getVelocityInLocalPointObsolete(rel_pos2,vel2);
     290        body2.internalGetVelocityInLocalPointObsolete(rel_pos2,vel2);
    276291        btVector3 vel = vel1 - vel2;
    277292
     
    284299        //positional error (zeroth order error)
    285300        btScalar depth = -(pointInA - pointInB).dot(axis_normal_on_a);
    286         btScalar        lo = btScalar(-1e30);
    287         btScalar        hi = btScalar(1e30);
     301        btScalar        lo = btScalar(-BT_LARGE_FLOAT);
     302        btScalar        hi = btScalar(BT_LARGE_FLOAT);
    288303
    289304        btScalar minLimit = m_lowerLimit[limit_index];
     
    331346        btVector3 ftorqueAxis1 = rel_pos1.cross(axis_normal_on_a);
    332347        btVector3 ftorqueAxis2 = rel_pos2.cross(axis_normal_on_a);
    333         bodyA.applyImpulse(axis_normal_on_a*body1.getInvMass(), body1.getInvInertiaTensorWorld()*ftorqueAxis1,normalImpulse);
    334         bodyB.applyImpulse(axis_normal_on_a*body2.getInvMass(), body2.getInvInertiaTensorWorld()*ftorqueAxis2,-normalImpulse);
     348        body1.internalApplyImpulse(axis_normal_on_a*body1.getInvMass(), body1.getInvInertiaTensorWorld()*ftorqueAxis1,normalImpulse);
     349        body2.internalApplyImpulse(axis_normal_on_a*body2.getInvMass(), body2.getInvInertiaTensorWorld()*ftorqueAxis2,-normalImpulse);
    335350
    336351
     
    373388}
    374389
    375 //-----------------------------------------------------------------------------
    376 
    377390void btGeneric6DofConstraint::calculateTransforms()
    378391{
    379         m_calculatedTransformA = m_rbA.getCenterOfMassTransform() * m_frameInA;
    380         m_calculatedTransformB = m_rbB.getCenterOfMassTransform() * m_frameInB;
     392        calculateTransforms(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
     393}
     394
     395void btGeneric6DofConstraint::calculateTransforms(const btTransform& transA,const btTransform& transB)
     396{
     397        m_calculatedTransformA = transA * m_frameInA;
     398        m_calculatedTransformB = transB * m_frameInB;
    381399        calculateLinearInfo();
    382400        calculateAngleInfo();
    383 }
    384 
    385 //-----------------------------------------------------------------------------
     401        if(m_useOffsetForConstraintFrame)
     402        {       //  get weight factors depending on masses
     403                btScalar miA = getRigidBodyA().getInvMass();
     404                btScalar miB = getRigidBodyB().getInvMass();
     405                m_hasStaticBody = (miA < SIMD_EPSILON) || (miB < SIMD_EPSILON);
     406                btScalar miS = miA + miB;
     407                if(miS > btScalar(0.f))
     408                {
     409                        m_factA = miB / miS;
     410                }
     411                else
     412                {
     413                        m_factA = btScalar(0.5f);
     414                }
     415                m_factB = btScalar(1.0f) - m_factA;
     416        }
     417}
     418
     419
    386420
    387421void btGeneric6DofConstraint::buildLinearJacobian(
     
    401435}
    402436
    403 //-----------------------------------------------------------------------------
     437
    404438
    405439void btGeneric6DofConstraint::buildAngularJacobian(
     
    414448}
    415449
    416 //-----------------------------------------------------------------------------
     450
    417451
    418452bool btGeneric6DofConstraint::testAngularLimitMotor(int axis_index)
    419453{
    420454        btScalar angle = m_calculatedAxisAngleDiff[axis_index];
     455        angle = btAdjustAngleToLimits(angle, m_angularLimits[axis_index].m_loLimit, m_angularLimits[axis_index].m_hiLimit);
     456        m_angularLimits[axis_index].m_currentPosition = angle;
    421457        //test limits
    422458        m_angularLimits[axis_index].testLimitValue(angle);
     
    424460}
    425461
    426 //-----------------------------------------------------------------------------
     462
    427463
    428464void btGeneric6DofConstraint::buildJacobian()
    429465{
     466#ifndef __SPU__
    430467        if (m_useSolveConstraintObsolete)
    431468        {
     
    439476                }
    440477                //calculates transform
    441                 calculateTransforms();
     478                calculateTransforms(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
    442479
    443480                //  const btVector3& pivotAInW = m_calculatedTransformA.getOrigin();
     
    482519
    483520        }
    484 }
    485 
    486 //-----------------------------------------------------------------------------
     521#endif //__SPU__
     522
     523}
     524
    487525
    488526void btGeneric6DofConstraint::getInfo1 (btConstraintInfo1* info)
     
    495533        {
    496534                //prepare constraint
    497                 calculateTransforms();
     535                calculateTransforms(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
    498536                info->m_numConstraintRows = 0;
    499537                info->nub = 6;
     
    520558}
    521559
    522 //-----------------------------------------------------------------------------
     560void btGeneric6DofConstraint::getInfo1NonVirtual (btConstraintInfo1* info)
     561{
     562        if (m_useSolveConstraintObsolete)
     563        {
     564                info->m_numConstraintRows = 0;
     565                info->nub = 0;
     566        } else
     567        {
     568                //pre-allocate all 6
     569                info->m_numConstraintRows = 6;
     570                info->nub = 0;
     571        }
     572}
     573
    523574
    524575void btGeneric6DofConstraint::getInfo2 (btConstraintInfo2* info)
    525576{
    526577        btAssert(!m_useSolveConstraintObsolete);
    527         int row = setLinearLimits(info);
    528         setAngularLimits(info, row);
    529 }
    530 
    531 //-----------------------------------------------------------------------------
    532 
    533 int btGeneric6DofConstraint::setLinearLimits(btConstraintInfo2* info)
    534 {
    535         btGeneric6DofConstraint * d6constraint = this;
    536         int row = 0;
     578
     579        const btTransform& transA = m_rbA.getCenterOfMassTransform();
     580        const btTransform& transB = m_rbB.getCenterOfMassTransform();
     581        const btVector3& linVelA = m_rbA.getLinearVelocity();
     582        const btVector3& linVelB = m_rbB.getLinearVelocity();
     583        const btVector3& angVelA = m_rbA.getAngularVelocity();
     584        const btVector3& angVelB = m_rbB.getAngularVelocity();
     585
     586        if(m_useOffsetForConstraintFrame)
     587        { // for stability better to solve angular limits first
     588                int row = setAngularLimits(info, 0,transA,transB,linVelA,linVelB,angVelA,angVelB);
     589                setLinearLimits(info, row, transA,transB,linVelA,linVelB,angVelA,angVelB);
     590        }
     591        else
     592        { // leave old version for compatibility
     593                int row = setLinearLimits(info, 0, transA,transB,linVelA,linVelB,angVelA,angVelB);
     594                setAngularLimits(info, row,transA,transB,linVelA,linVelB,angVelA,angVelB);
     595        }
     596
     597}
     598
     599
     600void btGeneric6DofConstraint::getInfo2NonVirtual (btConstraintInfo2* info, const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB)
     601{
     602       
     603        btAssert(!m_useSolveConstraintObsolete);
     604        //prepare constraint
     605        calculateTransforms(transA,transB);
     606
     607        int i;
     608        for (i=0;i<3 ;i++ )
     609        {
     610                testAngularLimitMotor(i);
     611        }
     612
     613        if(m_useOffsetForConstraintFrame)
     614        { // for stability better to solve angular limits first
     615                int row = setAngularLimits(info, 0,transA,transB,linVelA,linVelB,angVelA,angVelB);
     616                setLinearLimits(info, row, transA,transB,linVelA,linVelB,angVelA,angVelB);
     617        }
     618        else
     619        { // leave old version for compatibility
     620                int row = setLinearLimits(info, 0, transA,transB,linVelA,linVelB,angVelA,angVelB);
     621                setAngularLimits(info, row,transA,transB,linVelA,linVelB,angVelA,angVelB);
     622        }
     623}
     624
     625
     626
     627int btGeneric6DofConstraint::setLinearLimits(btConstraintInfo2* info, int row, const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB)
     628{
     629//      int row = 0;
    537630        //solve linear limits
    538631        btRotationalLimitMotor limot;
     
    543636                        limot.m_bounce = btScalar(0.f);
    544637                        limot.m_currentLimit = m_linearLimits.m_currentLimit[i];
     638                        limot.m_currentPosition = m_linearLimits.m_currentLinearDiff[i];
    545639                        limot.m_currentLimitError  = m_linearLimits.m_currentLimitError[i];
    546640                        limot.m_damping  = m_linearLimits.m_damping;
    547641                        limot.m_enableMotor  = m_linearLimits.m_enableMotor[i];
    548                         limot.m_ERP  = m_linearLimits.m_restitution;
    549642                        limot.m_hiLimit  = m_linearLimits.m_upperLimit[i];
    550643                        limot.m_limitSoftness  = m_linearLimits.m_limitSoftness;
     
    554647                        limot.m_targetVelocity  = m_linearLimits.m_targetVelocity[i];
    555648                        btVector3 axis = m_calculatedTransformA.getBasis().getColumn(i);
    556                         row += get_limit_motor_info2(&limot, &m_rbA, &m_rbB, info, row, axis, 0);
     649                        int flags = m_flags >> (i * BT_6DOF_FLAGS_AXIS_SHIFT);
     650                        limot.m_normalCFM       = (flags & BT_6DOF_FLAGS_CFM_NORM) ? m_linearLimits.m_normalCFM[i] : info->cfm[0];
     651                        limot.m_stopCFM         = (flags & BT_6DOF_FLAGS_CFM_STOP) ? m_linearLimits.m_stopCFM[i] : info->cfm[0];
     652                        limot.m_stopERP         = (flags & BT_6DOF_FLAGS_ERP_STOP) ? m_linearLimits.m_stopERP[i] : info->erp;
     653                        if(m_useOffsetForConstraintFrame)
     654                        {
     655                                int indx1 = (i + 1) % 3;
     656                                int indx2 = (i + 2) % 3;
     657                                int rotAllowed = 1; // rotations around orthos to current axis
     658                                if(m_angularLimits[indx1].m_currentLimit && m_angularLimits[indx2].m_currentLimit)
     659                                {
     660                                        rotAllowed = 0;
     661                                }
     662                                row += get_limit_motor_info2(&limot, transA,transB,linVelA,linVelB,angVelA,angVelB, info, row, axis, 0, rotAllowed);
     663                        }
     664                        else
     665                        {
     666                                row += get_limit_motor_info2(&limot, transA,transB,linVelA,linVelB,angVelA,angVelB, info, row, axis, 0);
     667                        }
    557668                }
    558669        }
     
    560671}
    561672
    562 //-----------------------------------------------------------------------------
    563 
    564 int btGeneric6DofConstraint::setAngularLimits(btConstraintInfo2 *info, int row_offset)
     673
     674
     675int btGeneric6DofConstraint::setAngularLimits(btConstraintInfo2 *info, int row_offset, const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB)
    565676{
    566677        btGeneric6DofConstraint * d6constraint = this;
     
    572683                {
    573684                        btVector3 axis = d6constraint->getAxis(i);
    574                         row += get_limit_motor_info2(
    575                                 d6constraint->getRotationalLimitMotor(i),
    576                                 &m_rbA,
    577                                 &m_rbB,
    578                                 info,row,axis,1);
     685                        int flags = m_flags >> ((i + 3) * BT_6DOF_FLAGS_AXIS_SHIFT);
     686                        if(!(flags & BT_6DOF_FLAGS_CFM_NORM))
     687                        {
     688                                m_angularLimits[i].m_normalCFM = info->cfm[0];
     689                        }
     690                        if(!(flags & BT_6DOF_FLAGS_CFM_STOP))
     691                        {
     692                                m_angularLimits[i].m_stopCFM = info->cfm[0];
     693                        }
     694                        if(!(flags & BT_6DOF_FLAGS_ERP_STOP))
     695                        {
     696                                m_angularLimits[i].m_stopERP = info->erp;
     697                        }
     698                        row += get_limit_motor_info2(d6constraint->getRotationalLimitMotor(i),
     699                                                                                                transA,transB,linVelA,linVelB,angVelA,angVelB, info,row,axis,1);
    579700                }
    580701        }
     
    583704}
    584705
    585 //-----------------------------------------------------------------------------
    586 
    587 void btGeneric6DofConstraint::solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar  timeStep)
    588 {
    589         if (m_useSolveConstraintObsolete)
    590         {
    591 
    592 
    593                 m_timeStep = timeStep;
    594 
    595                 //calculateTransforms();
    596 
    597                 int i;
    598 
    599                 // linear
    600 
    601                 btVector3 pointInA = m_calculatedTransformA.getOrigin();
    602                 btVector3 pointInB = m_calculatedTransformB.getOrigin();
    603 
    604                 btScalar jacDiagABInv;
    605                 btVector3 linear_axis;
    606                 for (i=0;i<3;i++)
    607                 {
    608                         if (m_linearLimits.isLimited(i))
    609                         {
    610                                 jacDiagABInv = btScalar(1.) / m_jacLinear[i].getDiagonal();
    611 
    612                                 if (m_useLinearReferenceFrameA)
    613                                         linear_axis = m_calculatedTransformA.getBasis().getColumn(i);
    614                                 else
    615                                         linear_axis = m_calculatedTransformB.getBasis().getColumn(i);
    616 
    617                                 m_linearLimits.solveLinearAxis(
    618                                         m_timeStep,
    619                                         jacDiagABInv,
    620                                         m_rbA,bodyA,pointInA,
    621                                         m_rbB,bodyB,pointInB,
    622                                         i,linear_axis, m_AnchorPos);
    623 
    624                         }
    625                 }
    626 
    627                 // angular
    628                 btVector3 angular_axis;
    629                 btScalar angularJacDiagABInv;
    630                 for (i=0;i<3;i++)
    631                 {
    632                         if (m_angularLimits[i].needApplyTorques())
    633                         {
    634 
    635                                 // get axis
    636                                 angular_axis = getAxis(i);
    637 
    638                                 angularJacDiagABInv = btScalar(1.) / m_jacAng[i].getDiagonal();
    639 
    640                                 m_angularLimits[i].solveAngularLimits(m_timeStep,angular_axis,angularJacDiagABInv, &m_rbA,bodyA,&m_rbB,bodyB);
    641                         }
    642                 }
    643         }
    644 }
    645 
    646 //-----------------------------------------------------------------------------
     706
     707
    647708
    648709void    btGeneric6DofConstraint::updateRHS(btScalar     timeStep)
     
    652713}
    653714
    654 //-----------------------------------------------------------------------------
     715
    655716
    656717btVector3 btGeneric6DofConstraint::getAxis(int axis_index) const
     
    659720}
    660721
    661 //-----------------------------------------------------------------------------
    662 
    663 btScalar btGeneric6DofConstraint::getAngle(int axis_index) const
    664 {
    665         return m_calculatedAxisAngleDiff[axis_index];
    666 }
    667 
    668 //-----------------------------------------------------------------------------
     722
     723btScalar        btGeneric6DofConstraint::getRelativePivotPosition(int axisIndex) const
     724{
     725        return m_calculatedLinearDiff[axisIndex];
     726}
     727
     728
     729btScalar btGeneric6DofConstraint::getAngle(int axisIndex) const
     730{
     731        return m_calculatedAxisAngleDiff[axisIndex];
     732}
     733
     734
    669735
    670736void btGeneric6DofConstraint::calcAnchorPos(void)
     
    685751        m_AnchorPos = pA * weight + pB * (btScalar(1.0) - weight);
    686752        return;
    687 } // btGeneric6DofConstraint::calcAnchorPos()
    688 
    689 //-----------------------------------------------------------------------------
     753}
     754
     755
    690756
    691757void btGeneric6DofConstraint::calculateLinearInfo()
     
    695761        for(int i = 0; i < 3; i++)
    696762        {
     763                m_linearLimits.m_currentLinearDiff[i] = m_calculatedLinearDiff[i];
    697764                m_linearLimits.testLimitValue(i, m_calculatedLinearDiff[i]);
    698765        }
    699 } // btGeneric6DofConstraint::calculateLinearInfo()
    700 
    701 //-----------------------------------------------------------------------------
     766}
     767
     768
    702769
    703770int btGeneric6DofConstraint::get_limit_motor_info2(
    704771        btRotationalLimitMotor * limot,
    705         btRigidBody * body0, btRigidBody * body1,
    706         btConstraintInfo2 *info, int row, btVector3& ax1, int rotational)
     772        const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB,
     773        btConstraintInfo2 *info, int row, btVector3& ax1, int rotational,int rotAllowed)
    707774{
    708775    int srow = row * info->rowskip;
     
    722789            J2[srow+2] = -ax1[2];
    723790        }
    724         if((!rotational) && limit)
     791        if((!rotational))
    725792        {
    726                         btVector3 ltd;  // Linear Torque Decoupling vector
    727                         btVector3 c = m_calculatedTransformB.getOrigin() - body0->getCenterOfMassPosition();
    728                         ltd = c.cross(ax1);
    729             info->m_J1angularAxis[srow+0] = ltd[0];
    730             info->m_J1angularAxis[srow+1] = ltd[1];
    731             info->m_J1angularAxis[srow+2] = ltd[2];
    732 
    733                         c = m_calculatedTransformB.getOrigin() - body1->getCenterOfMassPosition();
    734                         ltd = -c.cross(ax1);
    735                         info->m_J2angularAxis[srow+0] = ltd[0];
    736             info->m_J2angularAxis[srow+1] = ltd[1];
    737             info->m_J2angularAxis[srow+2] = ltd[2];
     793                        if (m_useOffsetForConstraintFrame)
     794                        {
     795                                btVector3 tmpA, tmpB, relA, relB;
     796                                // get vector from bodyB to frameB in WCS
     797                                relB = m_calculatedTransformB.getOrigin() - transB.getOrigin();
     798                                // get its projection to constraint axis
     799                                btVector3 projB = ax1 * relB.dot(ax1);
     800                                // get vector directed from bodyB to constraint axis (and orthogonal to it)
     801                                btVector3 orthoB = relB - projB;
     802                                // same for bodyA
     803                                relA = m_calculatedTransformA.getOrigin() - transA.getOrigin();
     804                                btVector3 projA = ax1 * relA.dot(ax1);
     805                                btVector3 orthoA = relA - projA;
     806                                // get desired offset between frames A and B along constraint axis
     807                                btScalar desiredOffs = limot->m_currentPosition - limot->m_currentLimitError;
     808                                // desired vector from projection of center of bodyA to projection of center of bodyB to constraint axis
     809                                btVector3 totalDist = projA + ax1 * desiredOffs - projB;
     810                                // get offset vectors relA and relB
     811                                relA = orthoA + totalDist * m_factA;
     812                                relB = orthoB - totalDist * m_factB;
     813                                tmpA = relA.cross(ax1);
     814                                tmpB = relB.cross(ax1);
     815                                if(m_hasStaticBody && (!rotAllowed))
     816                                {
     817                                        tmpA *= m_factA;
     818                                        tmpB *= m_factB;
     819                                }
     820                                int i;
     821                                for (i=0; i<3; i++) info->m_J1angularAxis[srow+i] = tmpA[i];
     822                                for (i=0; i<3; i++) info->m_J2angularAxis[srow+i] = -tmpB[i];
     823                        } else
     824                        {
     825                                btVector3 ltd;  // Linear Torque Decoupling vector
     826                                btVector3 c = m_calculatedTransformB.getOrigin() - transA.getOrigin();
     827                                ltd = c.cross(ax1);
     828                                info->m_J1angularAxis[srow+0] = ltd[0];
     829                                info->m_J1angularAxis[srow+1] = ltd[1];
     830                                info->m_J1angularAxis[srow+2] = ltd[2];
     831
     832                                c = m_calculatedTransformB.getOrigin() - transB.getOrigin();
     833                                ltd = -c.cross(ax1);
     834                                info->m_J2angularAxis[srow+0] = ltd[0];
     835                                info->m_J2angularAxis[srow+1] = ltd[1];
     836                                info->m_J2angularAxis[srow+2] = ltd[2];
     837                        }
    738838        }
    739839        // if we're limited low and high simultaneously, the joint motor is
     
    743843        if (powered)
    744844        {
    745             info->cfm[srow] = 0.0f;
     845                        info->cfm[srow] = limot->m_normalCFM;
    746846            if(!limit)
    747847            {
    748                 info->m_constraintError[srow] += limot->m_targetVelocity;
     848                                btScalar tag_vel = rotational ? limot->m_targetVelocity : -limot->m_targetVelocity;
     849
     850                                btScalar mot_fact = getMotorFactor(     limot->m_currentPosition,
     851                                                                                                        limot->m_loLimit,
     852                                                                                                        limot->m_hiLimit,
     853                                                                                                        tag_vel,
     854                                                                                                        info->fps * limot->m_stopERP);
     855                                info->m_constraintError[srow] += mot_fact * limot->m_targetVelocity;
    749856                info->m_lowerLimit[srow] = -limot->m_maxMotorForce;
    750857                info->m_upperLimit[srow] = limot->m_maxMotorForce;
     
    753860        if(limit)
    754861        {
    755             btScalar k = info->fps * limot->m_ERP;
     862            btScalar k = info->fps * limot->m_stopERP;
    756863                        if(!rotational)
    757864                        {
     
    762869                                info->m_constraintError[srow] += -k * limot->m_currentLimitError;
    763870                        }
    764             info->cfm[srow] = 0.0f;
     871                        info->cfm[srow] = limot->m_stopCFM;
    765872            if (limot->m_loLimit == limot->m_hiLimit)
    766873            {   // limited low and high simultaneously
     
    787894                    if (rotational)
    788895                    {
    789                         vel = body0->getAngularVelocity().dot(ax1);
    790                         if (body1)
    791                             vel -= body1->getAngularVelocity().dot(ax1);
     896                        vel = angVelA.dot(ax1);
     897//make sure that if no body -> angVelB == zero vec
     898//                        if (body1)
     899                            vel -= angVelB.dot(ax1);
    792900                    }
    793901                    else
    794902                    {
    795                         vel = body0->getLinearVelocity().dot(ax1);
    796                         if (body1)
    797                             vel -= body1->getLinearVelocity().dot(ax1);
     903                        vel = linVelA.dot(ax1);
     904//make sure that if no body -> angVelB == zero vec
     905//                        if (body1)
     906                            vel -= linVelB.dot(ax1);
    798907                    }
    799908                    // only apply bounce if the velocity is incoming, and if the
     
    825934}
    826935
    827 //-----------------------------------------------------------------------------
    828 //-----------------------------------------------------------------------------
    829 //-----------------------------------------------------------------------------
     936
     937
     938
     939
     940
     941        ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     942        ///If no axis is provided, it uses the default axis for this constraint.
     943void btGeneric6DofConstraint::setParam(int num, btScalar value, int axis)
     944{
     945        if((axis >= 0) && (axis < 3))
     946        {
     947                switch(num)
     948                {
     949                        case BT_CONSTRAINT_STOP_ERP :
     950                                m_linearLimits.m_stopERP[axis] = value;
     951                                m_flags |= BT_6DOF_FLAGS_ERP_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
     952                                break;
     953                        case BT_CONSTRAINT_STOP_CFM :
     954                                m_linearLimits.m_stopCFM[axis] = value;
     955                                m_flags |= BT_6DOF_FLAGS_CFM_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
     956                                break;
     957                        case BT_CONSTRAINT_CFM :
     958                                m_linearLimits.m_normalCFM[axis] = value;
     959                                m_flags |= BT_6DOF_FLAGS_CFM_NORM << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
     960                                break;
     961                        default :
     962                                btAssertConstrParams(0);
     963                }
     964        }
     965        else if((axis >=3) && (axis < 6))
     966        {
     967                switch(num)
     968                {
     969                        case BT_CONSTRAINT_STOP_ERP :
     970                                m_angularLimits[axis - 3].m_stopERP = value;
     971                                m_flags |= BT_6DOF_FLAGS_ERP_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
     972                                break;
     973                        case BT_CONSTRAINT_STOP_CFM :
     974                                m_angularLimits[axis - 3].m_stopCFM = value;
     975                                m_flags |= BT_6DOF_FLAGS_CFM_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
     976                                break;
     977                        case BT_CONSTRAINT_CFM :
     978                                m_angularLimits[axis - 3].m_normalCFM = value;
     979                                m_flags |= BT_6DOF_FLAGS_CFM_NORM << (axis * BT_6DOF_FLAGS_AXIS_SHIFT);
     980                                break;
     981                        default :
     982                                btAssertConstrParams(0);
     983                }
     984        }
     985        else
     986        {
     987                btAssertConstrParams(0);
     988        }
     989}
     990
     991        ///return the local value of parameter
     992btScalar btGeneric6DofConstraint::getParam(int num, int axis) const
     993{
     994        btScalar retVal = 0;
     995        if((axis >= 0) && (axis < 3))
     996        {
     997                switch(num)
     998                {
     999                        case BT_CONSTRAINT_STOP_ERP :
     1000                                btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_ERP_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
     1001                                retVal = m_linearLimits.m_stopERP[axis];
     1002                                break;
     1003                        case BT_CONSTRAINT_STOP_CFM :
     1004                                btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_CFM_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
     1005                                retVal = m_linearLimits.m_stopCFM[axis];
     1006                                break;
     1007                        case BT_CONSTRAINT_CFM :
     1008                                btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_CFM_NORM << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
     1009                                retVal = m_linearLimits.m_normalCFM[axis];
     1010                                break;
     1011                        default :
     1012                                btAssertConstrParams(0);
     1013                }
     1014        }
     1015        else if((axis >=3) && (axis < 6))
     1016        {
     1017                switch(num)
     1018                {
     1019                        case BT_CONSTRAINT_STOP_ERP :
     1020                                btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_ERP_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
     1021                                retVal = m_angularLimits[axis - 3].m_stopERP;
     1022                                break;
     1023                        case BT_CONSTRAINT_STOP_CFM :
     1024                                btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_CFM_STOP << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
     1025                                retVal = m_angularLimits[axis - 3].m_stopCFM;
     1026                                break;
     1027                        case BT_CONSTRAINT_CFM :
     1028                                btAssertConstrParams(m_flags & (BT_6DOF_FLAGS_CFM_NORM << (axis * BT_6DOF_FLAGS_AXIS_SHIFT)));
     1029                                retVal = m_angularLimits[axis - 3].m_normalCFM;
     1030                                break;
     1031                        default :
     1032                                btAssertConstrParams(0);
     1033                }
     1034        }
     1035        else
     1036        {
     1037                btAssertConstrParams(0);
     1038        }
     1039        return retVal;
     1040}
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h

    r5781 r8284  
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
     16/// 2009 March: btGeneric6DofConstraint refactored by Roman Ponomarev
     17/// Added support for generic constraint solver through getInfo1/getInfo2 methods
     18
    1519/*
    16202007-09-09
     
    4650    btScalar m_damping;//!< Damping.
    4751    btScalar m_limitSoftness;//! Relaxation factor
    48     btScalar m_ERP;//!< Error tolerance factor when joint is at limit
     52    btScalar m_normalCFM;//!< Constraint force mixing factor
     53    btScalar m_stopERP;//!< Error tolerance factor when joint is at limit
     54    btScalar m_stopCFM;//!< Constraint force mixing factor when joint is at limit
    4955    btScalar m_bounce;//!< restitution factor
    5056    bool m_enableMotor;
     
    5561    //!@{
    5662    btScalar m_currentLimitError;//!  How much is violated this limit
     63    btScalar m_currentPosition;     //!  current value of angle
    5764    int m_currentLimit;//!< 0=free, 1=at lo limit, 2=at hi limit
    5865    btScalar m_accumulatedImpulse;
     
    6572        m_maxMotorForce = 0.1f;
    6673        m_maxLimitForce = 300.0f;
    67         m_loLimit = -SIMD_INFINITY;
    68         m_hiLimit = SIMD_INFINITY;
    69         m_ERP = 0.5f;
     74        m_loLimit = 1.0f;
     75        m_hiLimit = -1.0f;
     76                m_normalCFM = 0.f;
     77                m_stopERP = 0.2f;
     78                m_stopCFM = 0.f;
    7079        m_bounce = 0.0f;
    7180        m_damping = 1.0f;
     
    8392        m_loLimit = limot.m_loLimit;
    8493        m_hiLimit = limot.m_hiLimit;
    85         m_ERP = limot.m_ERP;
     94                m_normalCFM = limot.m_normalCFM;
     95                m_stopERP = limot.m_stopERP;
     96                m_stopCFM =     limot.m_stopCFM;
    8697        m_bounce = limot.m_bounce;
    8798        m_currentLimit = limot.m_currentLimit;
     
    113124
    114125        //! apply the correction impulses for two bodies
    115     btScalar solveAngularLimits(btScalar timeStep,btVector3& axis, btScalar jacDiagABInv,btRigidBody * body0, btSolverBody& bodyA,btRigidBody * body1,btSolverBody& bodyB);
     126    btScalar solveAngularLimits(btScalar timeStep,btVector3& axis, btScalar jacDiagABInv,btRigidBody * body0, btRigidBody * body1);
    116127
    117128};
     
    130141    btScalar    m_damping;//!< Damping for linear limit
    131142    btScalar    m_restitution;//! Bounce parameter for linear limit
     143        btVector3       m_normalCFM;//!< Constraint force mixing factor
     144    btVector3   m_stopERP;//!< Error tolerance factor when joint is at limit
     145        btVector3       m_stopCFM;//!< Constraint force mixing factor when joint is at limit
    132146    //!@}
    133147        bool            m_enableMotor[3];
     
    135149    btVector3   m_maxMotorForce;//!< max force on motor
    136150    btVector3   m_currentLimitError;//!  How much is violated this limit
     151    btVector3   m_currentLinearDiff;//!  Current relative offset of constraint frames
    137152    int                 m_currentLimit[3];//!< 0=free, 1=at lower limit, 2=at upper limit
    138153
     
    142157        m_upperLimit.setValue(0.f,0.f,0.f);
    143158        m_accumulatedImpulse.setValue(0.f,0.f,0.f);
     159                m_normalCFM.setValue(0.f, 0.f, 0.f);
     160                m_stopERP.setValue(0.2f, 0.2f, 0.2f);
     161                m_stopCFM.setValue(0.f, 0.f, 0.f);
    144162
    145163        m_limitSoftness = 0.7f;
     
    163181        m_damping = other.m_damping;
    164182        m_restitution = other.m_restitution;
     183                m_normalCFM = other.m_normalCFM;
     184                m_stopERP = other.m_stopERP;
     185                m_stopCFM = other.m_stopCFM;
     186
    165187                for(int i=0; i < 3; i++)
    166188                {
     
    193215        btScalar timeStep,
    194216        btScalar jacDiagABInv,
    195         btRigidBody& body1,btSolverBody& bodyA,const btVector3 &pointInA,
    196         btRigidBody& body2,btSolverBody& bodyB,const btVector3 &pointInB,
     217        btRigidBody& body1,const btVector3 &pointInA,
     218        btRigidBody& body2,const btVector3 &pointInB,
    197219        int limit_index,
    198220        const btVector3 & axis_normal_on_a,
     
    201223
    202224};
     225
     226enum bt6DofFlags
     227{
     228        BT_6DOF_FLAGS_CFM_NORM = 1,
     229        BT_6DOF_FLAGS_CFM_STOP = 2,
     230        BT_6DOF_FLAGS_ERP_STOP = 4
     231};
     232#define BT_6DOF_FLAGS_AXIS_SHIFT 3 // bits per axis
     233
    203234
    204235/// btGeneric6DofConstraint between two rigidbodies each with a pivotpoint that descibes the axis location in local space
     
    216247<li> Angulars limits have these possible ranges:
    217248<table border=1 >
    218 <tr
    219 
     249<tr>
    220250        <td><b>AXIS</b></td>
    221251        <td><b>MIN ANGLE</b></td>
    222252        <td><b>MAX ANGLE</b></td>
     253</tr><tr>
    223254        <td>X</td>
    224                 <td>-PI</td>
    225                 <td>PI</td>
     255        <td>-PI</td>
     256        <td>PI</td>
     257</tr><tr>
    226258        <td>Y</td>
    227                 <td>-PI/2</td>
    228                 <td>PI/2</td>
     259        <td>-PI/2</td>
     260        <td>PI/2</td>
     261</tr><tr>
    229262        <td>Z</td>
    230                 <td>-PI/2</td>
    231                 <td>PI/2</td>
     263        <td>-PI</td>
     264        <td>PI</td>
    232265</tr>
    233266</table>
     
    273306    btVector3 m_calculatedAxis[3];
    274307    btVector3 m_calculatedLinearDiff;
     308        btScalar        m_factA;
     309        btScalar        m_factB;
     310        bool            m_hasStaticBody;
    275311   
    276312        btVector3 m_AnchorPos; // point betwen pivots of bodies A and B to solve linear axes
    277313
    278314    bool        m_useLinearReferenceFrameA;
     315        bool    m_useOffsetForConstraintFrame;
    279316   
     317        int             m_flags;
     318
    280319    //!@}
    281320
     
    288327
    289328
    290         int setAngularLimits(btConstraintInfo2 *info, int row_offset);
    291 
    292         int setLinearLimits(btConstraintInfo2 *info);
     329        int setAngularLimits(btConstraintInfo2 *info, int row_offset,const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB);
     330
     331        int setLinearLimits(btConstraintInfo2 *info, int row, const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB);
    293332
    294333    void buildLinearJacobian(
     
    312351
    313352    btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA);
    314 
    315     btGeneric6DofConstraint();
    316 
     353    btGeneric6DofConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameB);
     354   
    317355        //! Calcs global transform of the offsets
    318356        /*!
     
    320358        \sa btGeneric6DofConstraint.getCalculatedTransformA , btGeneric6DofConstraint.getCalculatedTransformB, btGeneric6DofConstraint.calculateAngleInfo
    321359        */
    322     void calculateTransforms();
     360    void calculateTransforms(const btTransform& transA,const btTransform& transB);
     361
     362        void calculateTransforms();
    323363
    324364        //! Gets the global transform of the offset for body A
     
    367407        virtual void getInfo1 (btConstraintInfo1* info);
    368408
     409        void getInfo1NonVirtual (btConstraintInfo1* info);
     410
    369411        virtual void getInfo2 (btConstraintInfo2* info);
    370412
    371     virtual     void    solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar        timeStep);
     413        void getInfo2NonVirtual (btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB);
     414
    372415
    373416    void        updateRHS(btScalar      timeStep);
     
    381424    //! Get the relative Euler angle
    382425    /*!
    383         \pre btGeneric6DofConstraint.buildJacobian must be called previously.
     426        \pre btGeneric6DofConstraint::calculateTransforms() must be called previously.
    384427        */
    385428    btScalar getAngle(int axis_index) const;
     429
     430        //! Get the relative position of the constraint pivot
     431    /*!
     432        \pre btGeneric6DofConstraint::calculateTransforms() must be called previously.
     433        */
     434        btScalar getRelativePivotPosition(int axis_index) const;
     435
    386436
    387437        //! Test angular limit.
    388438        /*!
    389439        Calculates angular correction and returns true if limit needs to be corrected.
    390         \pre btGeneric6DofConstraint.buildJacobian must be called previously.
     440        \pre btGeneric6DofConstraint::calculateTransforms() must be called previously.
    391441        */
    392442    bool testAngularLimitMotor(int axis_index);
     
    404454    void        setAngularLowerLimit(const btVector3& angularLower)
    405455    {
    406         m_angularLimits[0].m_loLimit = angularLower.getX();
    407         m_angularLimits[1].m_loLimit = angularLower.getY();
    408         m_angularLimits[2].m_loLimit = angularLower.getZ();
     456                for(int i = 0; i < 3; i++)
     457                        m_angularLimits[i].m_loLimit = btNormalizeAngle(angularLower[i]);
    409458    }
    410459
    411460    void        setAngularUpperLimit(const btVector3& angularUpper)
    412461    {
    413         m_angularLimits[0].m_hiLimit = angularUpper.getX();
    414         m_angularLimits[1].m_hiLimit = angularUpper.getY();
    415         m_angularLimits[2].m_hiLimit = angularUpper.getZ();
     462                for(int i = 0; i < 3; i++)
     463                        m_angularLimits[i].m_hiLimit = btNormalizeAngle(angularUpper[i]);
    416464    }
    417465
     
    438486        else
    439487        {
     488                        lo = btNormalizeAngle(lo);
     489                        hi = btNormalizeAngle(hi);
    440490                m_angularLimits[axis-3].m_loLimit = lo;
    441491                m_angularLimits[axis-3].m_hiLimit = hi;
     
    460510    }
    461511
    462     const btRigidBody& getRigidBodyA() const
    463     {
    464         return m_rbA;
    465     }
    466     const btRigidBody& getRigidBodyB() const
    467     {
    468         return m_rbB;
    469     }
    470 
    471512        virtual void calcAnchorPos(void); // overridable
    472513
    473514        int get_limit_motor_info2(      btRotationalLimitMotor * limot,
    474                                                                 btRigidBody * body0, btRigidBody * body1,
    475                                                                 btConstraintInfo2 *info, int row, btVector3& ax1, int rotational);
    476 
    477 
     515                                                                const btTransform& transA,const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB,const btVector3& angVelA,const btVector3& angVelB,
     516                                                                btConstraintInfo2 *info, int row, btVector3& ax1, int rotational, int rotAllowed = false);
     517
     518        // access for UseFrameOffset
     519        bool getUseFrameOffset() { return m_useOffsetForConstraintFrame; }
     520        void setUseFrameOffset(bool frameOffsetOnOff) { m_useOffsetForConstraintFrame = frameOffsetOnOff; }
     521
     522        ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     523        ///If no axis is provided, it uses the default axis for this constraint.
     524        virtual void setParam(int num, btScalar value, int axis = -1);
     525        ///return the local value of parameter
     526        virtual btScalar getParam(int num, int axis = -1) const;
     527
     528        virtual int     calculateSerializeBufferSize() const;
     529
     530        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     531        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     532
     533       
    478534};
    479535
     536///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     537struct btGeneric6DofConstraintData
     538{
     539        btTypedConstraintData   m_typeConstraintData;
     540        btTransformFloatData m_rbAFrame; // constraint axii. Assumes z is hinge axis.
     541        btTransformFloatData m_rbBFrame;
     542       
     543        btVector3FloatData      m_linearUpperLimit;
     544        btVector3FloatData      m_linearLowerLimit;
     545
     546        btVector3FloatData      m_angularUpperLimit;
     547        btVector3FloatData      m_angularLowerLimit;
     548       
     549        int     m_useLinearReferenceFrameA;
     550        int m_useOffsetForConstraintFrame;
     551};
     552
     553SIMD_FORCE_INLINE       int     btGeneric6DofConstraint::calculateSerializeBufferSize() const
     554{
     555        return sizeof(btGeneric6DofConstraintData);
     556}
     557
     558        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     559SIMD_FORCE_INLINE       const char*     btGeneric6DofConstraint::serialize(void* dataBuffer, btSerializer* serializer) const
     560{
     561
     562        btGeneric6DofConstraintData* dof = (btGeneric6DofConstraintData*)dataBuffer;
     563        btTypedConstraint::serialize(&dof->m_typeConstraintData,serializer);
     564
     565        m_frameInA.serializeFloat(dof->m_rbAFrame);
     566        m_frameInB.serializeFloat(dof->m_rbBFrame);
     567
     568               
     569        int i;
     570        for (i=0;i<3;i++)
     571        {
     572                dof->m_angularLowerLimit.m_floats[i] =  float(m_angularLimits[i].m_loLimit);
     573                dof->m_angularUpperLimit.m_floats[i] =  float(m_angularLimits[i].m_hiLimit);
     574                dof->m_linearLowerLimit.m_floats[i] = float(m_linearLimits.m_lowerLimit[i]);
     575                dof->m_linearUpperLimit.m_floats[i] = float(m_linearLimits.m_upperLimit[i]);
     576        }
     577       
     578        dof->m_useLinearReferenceFrameA = m_useLinearReferenceFrameA? 1 : 0;
     579        dof->m_useOffsetForConstraintFrame = m_useOffsetForConstraintFrame ? 1 : 0;
     580
     581        return "btGeneric6DofConstraintData";
     582}
     583
     584
     585
     586
     587
    480588#endif //GENERIC_6DOF_CONSTRAINT_H
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btHingeConstraint.cpp

    r5781 r8284  
    2222#include "btSolverBody.h"
    2323
    24 //-----------------------------------------------------------------------------
    25 
     24
     25
     26//#define HINGE_USE_OBSOLETE_SOLVER false
    2627#define HINGE_USE_OBSOLETE_SOLVER false
    2728
    28 //-----------------------------------------------------------------------------
    29 
    30 
    31 btHingeConstraint::btHingeConstraint()
    32 : btTypedConstraint (HINGE_CONSTRAINT_TYPE),
    33 m_enableAngularMotor(false),
    34 m_useSolveConstraintObsolete(HINGE_USE_OBSOLETE_SOLVER),
    35 m_useReferenceFrameA(false)
    36 {
    37         m_referenceSign = m_useReferenceFrameA ? btScalar(-1.f) : btScalar(1.f);
    38 }
    39 
    40 //-----------------------------------------------------------------------------
     29#define HINGE_USE_FRAME_OFFSET true
     30
     31#ifndef __SPU__
     32
     33
     34
     35
    4136
    4237btHingeConstraint::btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB,
    43                                                                          btVector3& axisInA,btVector3& axisInB, bool useReferenceFrameA)
     38                                                                         const btVector3& axisInA,const btVector3& axisInB, bool useReferenceFrameA)
    4439                                                                         :btTypedConstraint(HINGE_CONSTRAINT_TYPE, rbA,rbB),
    4540                                                                         m_angularOnly(false),
    4641                                                                         m_enableAngularMotor(false),
    4742                                                                         m_useSolveConstraintObsolete(HINGE_USE_OBSOLETE_SOLVER),
    48                                                                          m_useReferenceFrameA(useReferenceFrameA)
     43                                                                         m_useOffsetForConstraintFrame(HINGE_USE_FRAME_OFFSET),
     44                                                                         m_useReferenceFrameA(useReferenceFrameA),
     45                                                                         m_flags(0)
    4946{
    5047        m_rbAFrame.getOrigin() = pivotInA;
     
    8077       
    8178        //start with free
    82         m_lowerLimit = btScalar(1e30);
    83         m_upperLimit = btScalar(-1e30);
     79        m_lowerLimit = btScalar(1.0f);
     80        m_upperLimit = btScalar(-1.0f);
    8481        m_biasFactor = 0.3f;
    8582        m_relaxationFactor = 1.0f;
     
    8986}
    9087
    91 //-----------------------------------------------------------------------------
    92 
    93 btHingeConstraint::btHingeConstraint(btRigidBody& rbA,const btVector3& pivotInA,btVector3& axisInA, bool useReferenceFrameA)
     88
     89
     90btHingeConstraint::btHingeConstraint(btRigidBody& rbA,const btVector3& pivotInA,const btVector3& axisInA, bool useReferenceFrameA)
    9491:btTypedConstraint(HINGE_CONSTRAINT_TYPE, rbA), m_angularOnly(false), m_enableAngularMotor(false),
    9592m_useSolveConstraintObsolete(HINGE_USE_OBSOLETE_SOLVER),
    96 m_useReferenceFrameA(useReferenceFrameA)
     93m_useOffsetForConstraintFrame(HINGE_USE_FRAME_OFFSET),
     94m_useReferenceFrameA(useReferenceFrameA),
     95m_flags(0)
    9796{
    9897
     
    120119       
    121120        //start with free
    122         m_lowerLimit = btScalar(1e30);
    123         m_upperLimit = btScalar(-1e30);
     121        m_lowerLimit = btScalar(1.0f);
     122        m_upperLimit = btScalar(-1.0f);
    124123        m_biasFactor = 0.3f;
    125124        m_relaxationFactor = 1.0f;
     
    129128}
    130129
    131 //-----------------------------------------------------------------------------
     130
    132131
    133132btHingeConstraint::btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB,
     
    137136m_enableAngularMotor(false),
    138137m_useSolveConstraintObsolete(HINGE_USE_OBSOLETE_SOLVER),
    139 m_useReferenceFrameA(useReferenceFrameA)
     138m_useOffsetForConstraintFrame(HINGE_USE_FRAME_OFFSET),
     139m_useReferenceFrameA(useReferenceFrameA),
     140m_flags(0)
    140141{
    141142        //start with free
    142         m_lowerLimit = btScalar(1e30);
    143         m_upperLimit = btScalar(-1e30);
     143        m_lowerLimit = btScalar(1.0f);
     144        m_upperLimit = btScalar(-1.0f);
    144145        m_biasFactor = 0.3f;
    145146        m_relaxationFactor = 1.0f;
     
    149150}                       
    150151
    151 //-----------------------------------------------------------------------------
     152
    152153
    153154btHingeConstraint::btHingeConstraint(btRigidBody& rbA, const btTransform& rbAFrame, bool useReferenceFrameA)
     
    156157m_enableAngularMotor(false),
    157158m_useSolveConstraintObsolete(HINGE_USE_OBSOLETE_SOLVER),
    158 m_useReferenceFrameA(useReferenceFrameA)
     159m_useOffsetForConstraintFrame(HINGE_USE_FRAME_OFFSET),
     160m_useReferenceFrameA(useReferenceFrameA),
     161m_flags(0)
    159162{
    160163        ///not providing rigidbody B means implicitly using worldspace for body B
     
    163166
    164167        //start with free
    165         m_lowerLimit = btScalar(1e30);
    166         m_upperLimit = btScalar(-1e30);
     168        m_lowerLimit = btScalar(1.0f);
     169        m_upperLimit = btScalar(-1.0f);
    167170        m_biasFactor = 0.3f;
    168171        m_relaxationFactor = 1.0f;
     
    172175}
    173176
    174 //-----------------------------------------------------------------------------
     177
    175178
    176179void    btHingeConstraint::buildJacobian()
     
    179182        {
    180183                m_appliedImpulse = btScalar(0.);
     184                m_accMotorImpulse = btScalar(0.);
    181185
    182186                if (!m_angularOnly)
     
    222226                btPlaneSpace1(m_rbAFrame.getBasis().getColumn(2),jointAxis0local,jointAxis1local);
    223227
    224                 getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(2);
    225228                btVector3 jointAxis0 = getRigidBodyA().getCenterOfMassTransform().getBasis() * jointAxis0local;
    226229                btVector3 jointAxis1 = getRigidBodyA().getCenterOfMassTransform().getBasis() * jointAxis1local;
     
    249252
    250253                        // test angular limit
    251                         testLimit();
     254                        testLimit(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
    252255
    253256                //Compute K = J*W*J' for hinge axis
     
    259262}
    260263
    261 //-----------------------------------------------------------------------------
     264
     265#endif //__SPU__
     266
    262267
    263268void btHingeConstraint::getInfo1(btConstraintInfo1* info)
     
    272277                info->m_numConstraintRows = 5; // Fixed 3 linear + 2 angular
    273278                info->nub = 1;
     279                //always add the row, to avoid computation (data is not available yet)
    274280                //prepare constraint
    275                 testLimit();
     281                testLimit(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
    276282                if(getSolveLimit() || getEnableAngularMotor())
    277283                {
     
    279285                        info->nub--;
    280286                }
    281         }
    282 } // btHingeConstraint::getInfo1 ()
    283 
    284 //-----------------------------------------------------------------------------
     287
     288        }
     289}
     290
     291void btHingeConstraint::getInfo1NonVirtual(btConstraintInfo1* info)
     292{
     293        if (m_useSolveConstraintObsolete)
     294        {
     295                info->m_numConstraintRows = 0;
     296                info->nub = 0;
     297        }
     298        else
     299        {
     300                //always add the 'limit' row, to avoid computation (data is not available yet)
     301                info->m_numConstraintRows = 6; // Fixed 3 linear + 2 angular
     302                info->nub = 0;
     303        }
     304}
    285305
    286306void btHingeConstraint::getInfo2 (btConstraintInfo2* info)
    287307{
     308        if(m_useOffsetForConstraintFrame)
     309        {
     310                getInfo2InternalUsingFrameOffset(info, m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform(),m_rbA.getAngularVelocity(),m_rbB.getAngularVelocity());
     311        }
     312        else
     313        {
     314                getInfo2Internal(info, m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform(),m_rbA.getAngularVelocity(),m_rbB.getAngularVelocity());
     315        }
     316}
     317
     318
     319void    btHingeConstraint::getInfo2NonVirtual (btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btVector3& angVelA,const btVector3& angVelB)
     320{
     321        ///the regular (virtual) implementation getInfo2 already performs 'testLimit' during getInfo1, so we need to do it now
     322        testLimit(transA,transB);
     323
     324        getInfo2Internal(info,transA,transB,angVelA,angVelB);
     325}
     326
     327
     328void btHingeConstraint::getInfo2Internal(btConstraintInfo2* info, const btTransform& transA,const btTransform& transB,const btVector3& angVelA,const btVector3& angVelB)
     329{
     330
    288331        btAssert(!m_useSolveConstraintObsolete);
    289         int i, s = info->rowskip;
     332        int i, skip = info->rowskip;
    290333        // transforms in world space
    291         btTransform trA = m_rbA.getCenterOfMassTransform()*m_rbAFrame;
    292         btTransform trB = m_rbB.getCenterOfMassTransform()*m_rbBFrame;
     334        btTransform trA = transA*m_rbAFrame;
     335        btTransform trB = transB*m_rbBFrame;
    293336        // pivot point
    294337        btVector3 pivotAInW = trA.getOrigin();
    295338        btVector3 pivotBInW = trB.getOrigin();
     339#if 0
     340        if (0)
     341        {
     342                for (i=0;i<6;i++)
     343                {
     344                        info->m_J1linearAxis[i*skip]=0;
     345                        info->m_J1linearAxis[i*skip+1]=0;
     346                        info->m_J1linearAxis[i*skip+2]=0;
     347
     348                        info->m_J1angularAxis[i*skip]=0;
     349                        info->m_J1angularAxis[i*skip+1]=0;
     350                        info->m_J1angularAxis[i*skip+2]=0;
     351
     352                        info->m_J2angularAxis[i*skip]=0;
     353                        info->m_J2angularAxis[i*skip+1]=0;
     354                        info->m_J2angularAxis[i*skip+2]=0;
     355
     356                        info->m_constraintError[i*skip]=0.f;
     357                }
     358        }
     359#endif //#if 0
    296360        // linear (all fixed)
    297     info->m_J1linearAxis[0] = 1;
    298     info->m_J1linearAxis[s + 1] = 1;
    299     info->m_J1linearAxis[2 * s + 2] = 1;
    300         btVector3 a1 = pivotAInW - m_rbA.getCenterOfMassTransform().getOrigin();
     361
     362        if (!m_angularOnly)
     363        {
     364                info->m_J1linearAxis[0] = 1;
     365                info->m_J1linearAxis[skip + 1] = 1;
     366                info->m_J1linearAxis[2 * skip + 2] = 1;
     367        }       
     368
     369
     370
     371
     372        btVector3 a1 = pivotAInW - transA.getOrigin();
    301373        {
    302374                btVector3* angular0 = (btVector3*)(info->m_J1angularAxis);
    303                 btVector3* angular1 = (btVector3*)(info->m_J1angularAxis + s);
    304                 btVector3* angular2 = (btVector3*)(info->m_J1angularAxis + 2 * s);
     375                btVector3* angular1 = (btVector3*)(info->m_J1angularAxis + skip);
     376                btVector3* angular2 = (btVector3*)(info->m_J1angularAxis + 2 * skip);
    305377                btVector3 a1neg = -a1;
    306378                a1neg.getSkewSymmetricMatrix(angular0,angular1,angular2);
    307379        }
    308         btVector3 a2 = pivotBInW - m_rbB.getCenterOfMassTransform().getOrigin();
     380        btVector3 a2 = pivotBInW - transB.getOrigin();
    309381        {
    310382                btVector3* angular0 = (btVector3*)(info->m_J2angularAxis);
    311                 btVector3* angular1 = (btVector3*)(info->m_J2angularAxis + s);
    312                 btVector3* angular2 = (btVector3*)(info->m_J2angularAxis + 2 * s);
     383                btVector3* angular1 = (btVector3*)(info->m_J2angularAxis + skip);
     384                btVector3* angular2 = (btVector3*)(info->m_J2angularAxis + 2 * skip);
    313385                a2.getSkewSymmetricMatrix(angular0,angular1,angular2);
    314386        }
    315387        // linear RHS
    316388    btScalar k = info->fps * info->erp;
    317         for(i = 0; i < 3; i++)
    318     {
    319         info->m_constraintError[i * s] = k * (pivotBInW[i] - pivotAInW[i]);
    320     }
     389        if (!m_angularOnly)
     390        {
     391                for(i = 0; i < 3; i++)
     392                {
     393                        info->m_constraintError[i * skip] = k * (pivotBInW[i] - pivotAInW[i]);
     394                }
     395        }
    321396        // make rotations around X and Y equal
    322397        // the hinge axis should be the only unconstrained
     
    403478                }
    404479                info->m_constraintError[srow] = btScalar(0.0f);
     480                btScalar currERP = (m_flags & BT_HINGE_FLAGS_ERP_STOP) ? m_stopERP : info->erp;
    405481                if(powered)
    406482                {
    407             info->cfm[srow] = btScalar(0.0);
    408                         btScalar mot_fact = getMotorFactor(m_hingeAngle, lostop, histop, m_motorTargetVelocity, info->fps * info->erp);
     483                        if(m_flags & BT_HINGE_FLAGS_CFM_NORM)
     484                        {
     485                                info->cfm[srow] = m_normalCFM;
     486                        }
     487                        btScalar mot_fact = getMotorFactor(m_hingeAngle, lostop, histop, m_motorTargetVelocity, info->fps * currERP);
    409488                        info->m_constraintError[srow] += mot_fact * m_motorTargetVelocity * m_referenceSign;
    410489                        info->m_lowerLimit[srow] = - m_maxMotorImpulse;
     
    413492                if(limit)
    414493                {
    415                         k = info->fps * info->erp;
     494                        k = info->fps * currERP;
    416495                        info->m_constraintError[srow] += k * limit_err;
    417                         info->cfm[srow] = btScalar(0.0);
     496                        if(m_flags & BT_HINGE_FLAGS_CFM_STOP)
     497                        {
     498                                info->cfm[srow] = m_stopCFM;
     499                        }
    418500                        if(lostop == histop)
    419501                        {
     
    436518                        if(bounce > btScalar(0.0))
    437519                        {
    438                                 btScalar vel = m_rbA.getAngularVelocity().dot(ax1);
    439                                 vel -= m_rbB.getAngularVelocity().dot(ax1);
     520                                btScalar vel = angVelA.dot(ax1);
     521                                vel -= angVelB.dot(ax1);
    440522                                // only apply bounce if the velocity is incoming, and if the
    441523                                // resulting c[] exceeds what we already have.
     
    468550}
    469551
    470 //-----------------------------------------------------------------------------
    471 
    472 void    btHingeConstraint::solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar     timeStep)
    473 {
    474 
    475         ///for backwards compatibility during the transition to 'getInfo/getInfo2'
    476         if (m_useSolveConstraintObsolete)
    477         {
    478 
    479                 btVector3 pivotAInW = m_rbA.getCenterOfMassTransform()*m_rbAFrame.getOrigin();
    480                 btVector3 pivotBInW = m_rbB.getCenterOfMassTransform()*m_rbBFrame.getOrigin();
    481 
    482                 btScalar tau = btScalar(0.3);
    483 
    484                 //linear part
    485                 if (!m_angularOnly)
    486                 {
    487                         btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition();
    488                         btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition();
    489 
    490                         btVector3 vel1,vel2;
    491                         bodyA.getVelocityInLocalPointObsolete(rel_pos1,vel1);
    492                         bodyB.getVelocityInLocalPointObsolete(rel_pos2,vel2);
    493                         btVector3 vel = vel1 - vel2;
    494 
    495                         for (int i=0;i<3;i++)
    496                         {               
    497                                 const btVector3& normal = m_jac[i].m_linearJointAxis;
    498                                 btScalar jacDiagABInv = btScalar(1.) / m_jac[i].getDiagonal();
    499 
    500                                 btScalar rel_vel;
    501                                 rel_vel = normal.dot(vel);
    502                                 //positional error (zeroth order error)
    503                                 btScalar depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal
    504                                 btScalar impulse = depth*tau/timeStep  * jacDiagABInv -  rel_vel * jacDiagABInv;
    505                                 m_appliedImpulse += impulse;
    506                                 btVector3 impulse_vector = normal * impulse;
    507                                 btVector3 ftorqueAxis1 = rel_pos1.cross(normal);
    508                                 btVector3 ftorqueAxis2 = rel_pos2.cross(normal);
    509                                 bodyA.applyImpulse(normal*m_rbA.getInvMass(), m_rbA.getInvInertiaTensorWorld()*ftorqueAxis1,impulse);
    510                                 bodyB.applyImpulse(normal*m_rbB.getInvMass(), m_rbB.getInvInertiaTensorWorld()*ftorqueAxis2,-impulse);
    511                         }
    512                 }
    513 
    514                
    515                 {
    516                         ///solve angular part
    517 
    518                         // get axes in world space
    519                         btVector3 axisA =  getRigidBodyA().getCenterOfMassTransform().getBasis() *  m_rbAFrame.getBasis().getColumn(2);
    520                         btVector3 axisB =  getRigidBodyB().getCenterOfMassTransform().getBasis() *  m_rbBFrame.getBasis().getColumn(2);
    521 
    522                         btVector3 angVelA;
    523                         bodyA.getAngularVelocity(angVelA);
    524                         btVector3 angVelB;
    525                         bodyB.getAngularVelocity(angVelB);
    526 
    527                         btVector3 angVelAroundHingeAxisA = axisA * axisA.dot(angVelA);
    528                         btVector3 angVelAroundHingeAxisB = axisB * axisB.dot(angVelB);
    529 
    530                         btVector3 angAorthog = angVelA - angVelAroundHingeAxisA;
    531                         btVector3 angBorthog = angVelB - angVelAroundHingeAxisB;
    532                         btVector3 velrelOrthog = angAorthog-angBorthog;
    533                         {
    534                                
    535 
    536                                 //solve orthogonal angular velocity correction
    537                                 btScalar relaxation = btScalar(1.);
    538                                 btScalar len = velrelOrthog.length();
    539                                 if (len > btScalar(0.00001))
    540                                 {
    541                                         btVector3 normal = velrelOrthog.normalized();
    542                                         btScalar denom = getRigidBodyA().computeAngularImpulseDenominator(normal) +
    543                                                 getRigidBodyB().computeAngularImpulseDenominator(normal);
    544                                         // scale for mass and relaxation
    545                                         //velrelOrthog *= (btScalar(1.)/denom) * m_relaxationFactor;
    546 
    547                                         bodyA.applyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*velrelOrthog,-(btScalar(1.)/denom));
    548                                         bodyB.applyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*velrelOrthog,(btScalar(1.)/denom));
    549 
    550                                 }
    551 
    552                                 //solve angular positional correction
    553                                 btVector3 angularError =  axisA.cross(axisB) *(btScalar(1.)/timeStep);
    554                                 btScalar len2 = angularError.length();
    555                                 if (len2>btScalar(0.00001))
    556                                 {
    557                                         btVector3 normal2 = angularError.normalized();
    558                                         btScalar denom2 = getRigidBodyA().computeAngularImpulseDenominator(normal2) +
    559                                                         getRigidBodyB().computeAngularImpulseDenominator(normal2);
    560                                         //angularError *= (btScalar(1.)/denom2) * relaxation;
    561                                        
    562                                         bodyA.applyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*angularError,(btScalar(1.)/denom2));
    563                                         bodyB.applyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*angularError,-(btScalar(1.)/denom2));
    564 
    565                                 }
    566                                
    567                                
    568 
    569 
    570 
    571                                 // solve limit
    572                                 if (m_solveLimit)
    573                                 {
    574                                         btScalar amplitude = ( (angVelB - angVelA).dot( axisA )*m_relaxationFactor + m_correction* (btScalar(1.)/timeStep)*m_biasFactor  ) * m_limitSign;
    575 
    576                                         btScalar impulseMag = amplitude * m_kHinge;
    577 
    578                                         // Clamp the accumulated impulse
    579                                         btScalar temp = m_accLimitImpulse;
    580                                         m_accLimitImpulse = btMax(m_accLimitImpulse + impulseMag, btScalar(0) );
    581                                         impulseMag = m_accLimitImpulse - temp;
    582 
    583 
    584                                        
    585                                         bodyA.applyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*axisA,impulseMag * m_limitSign);
    586                                         bodyB.applyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*axisA,-(impulseMag * m_limitSign));
    587 
    588                                 }
    589                         }
    590 
    591                         //apply motor
    592                         if (m_enableAngularMotor)
    593                         {
    594                                 //todo: add limits too
    595                                 btVector3 angularLimit(0,0,0);
    596 
    597                                 btVector3 velrel = angVelAroundHingeAxisA - angVelAroundHingeAxisB;
    598                                 btScalar projRelVel = velrel.dot(axisA);
    599 
    600                                 btScalar desiredMotorVel = m_motorTargetVelocity;
    601                                 btScalar motor_relvel = desiredMotorVel - projRelVel;
    602 
    603                                 btScalar unclippedMotorImpulse = m_kHinge * motor_relvel;;
    604                                 //todo: should clip against accumulated impulse
    605                                 btScalar clippedMotorImpulse = unclippedMotorImpulse > m_maxMotorImpulse ? m_maxMotorImpulse : unclippedMotorImpulse;
    606                                 clippedMotorImpulse = clippedMotorImpulse < -m_maxMotorImpulse ? -m_maxMotorImpulse : clippedMotorImpulse;
    607                                 btVector3 motorImp = clippedMotorImpulse * axisA;
    608                        
    609                                 bodyA.applyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*axisA,clippedMotorImpulse);
    610                                 bodyB.applyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*axisA,-clippedMotorImpulse);
    611                                
    612                         }
    613                 }
    614         }
    615 
    616 }
    617 
    618 //-----------------------------------------------------------------------------
     552
     553
     554
     555
    619556
    620557void    btHingeConstraint::updateRHS(btScalar   timeStep)
     
    624561}
    625562
    626 //-----------------------------------------------------------------------------
    627563
    628564btScalar btHingeConstraint::getHingeAngle()
    629565{
    630         const btVector3 refAxis0  = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(0);
    631         const btVector3 refAxis1  = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(1);
    632         const btVector3 swingAxis = getRigidBodyB().getCenterOfMassTransform().getBasis() * m_rbBFrame.getBasis().getColumn(1);
    633         btScalar angle = btAtan2Fast(swingAxis.dot(refAxis0), swingAxis.dot(refAxis1));
     566        return getHingeAngle(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
     567}
     568
     569btScalar btHingeConstraint::getHingeAngle(const btTransform& transA,const btTransform& transB)
     570{
     571        const btVector3 refAxis0  = transA.getBasis() * m_rbAFrame.getBasis().getColumn(0);
     572        const btVector3 refAxis1  = transA.getBasis() * m_rbAFrame.getBasis().getColumn(1);
     573        const btVector3 swingAxis = transB.getBasis() * m_rbBFrame.getBasis().getColumn(1);
     574//      btScalar angle = btAtan2Fast(swingAxis.dot(refAxis0), swingAxis.dot(refAxis1));
     575        btScalar angle = btAtan2(swingAxis.dot(refAxis0), swingAxis.dot(refAxis1));
    634576        return m_referenceSign * angle;
    635577}
    636578
    637 //-----------------------------------------------------------------------------
    638 
     579
     580#if 0
    639581void btHingeConstraint::testLimit()
    640582{
     
    660602        }
    661603        return;
    662 } // btHingeConstraint::testLimit()
    663 
    664 //-----------------------------------------------------------------------------
    665 //-----------------------------------------------------------------------------
    666 //-----------------------------------------------------------------------------
     604}
     605#else
     606
     607
     608void btHingeConstraint::testLimit(const btTransform& transA,const btTransform& transB)
     609{
     610        // Compute limit information
     611        m_hingeAngle = getHingeAngle(transA,transB);
     612        m_correction = btScalar(0.);
     613        m_limitSign = btScalar(0.);
     614        m_solveLimit = false;
     615        if (m_lowerLimit <= m_upperLimit)
     616        {
     617                m_hingeAngle = btAdjustAngleToLimits(m_hingeAngle, m_lowerLimit, m_upperLimit);
     618                if (m_hingeAngle <= m_lowerLimit)
     619                {
     620                        m_correction = (m_lowerLimit - m_hingeAngle);
     621                        m_limitSign = 1.0f;
     622                        m_solveLimit = true;
     623                }
     624                else if (m_hingeAngle >= m_upperLimit)
     625                {
     626                        m_correction = m_upperLimit - m_hingeAngle;
     627                        m_limitSign = -1.0f;
     628                        m_solveLimit = true;
     629                }
     630        }
     631        return;
     632}
     633#endif
     634
     635static btVector3 vHinge(0, 0, btScalar(1));
     636
     637void btHingeConstraint::setMotorTarget(const btQuaternion& qAinB, btScalar dt)
     638{
     639        // convert target from body to constraint space
     640        btQuaternion qConstraint = m_rbBFrame.getRotation().inverse() * qAinB * m_rbAFrame.getRotation();
     641        qConstraint.normalize();
     642
     643        // extract "pure" hinge component
     644        btVector3 vNoHinge = quatRotate(qConstraint, vHinge); vNoHinge.normalize();
     645        btQuaternion qNoHinge = shortestArcQuat(vHinge, vNoHinge);
     646        btQuaternion qHinge = qNoHinge.inverse() * qConstraint;
     647        qHinge.normalize();
     648
     649        // compute angular target, clamped to limits
     650        btScalar targetAngle = qHinge.getAngle();
     651        if (targetAngle > SIMD_PI) // long way around. flip quat and recalculate.
     652        {
     653                qHinge = operator-(qHinge);
     654                targetAngle = qHinge.getAngle();
     655        }
     656        if (qHinge.getZ() < 0)
     657                targetAngle = -targetAngle;
     658
     659        setMotorTarget(targetAngle, dt);
     660}
     661
     662void btHingeConstraint::setMotorTarget(btScalar targetAngle, btScalar dt)
     663{
     664        if (m_lowerLimit < m_upperLimit)
     665        {
     666                if (targetAngle < m_lowerLimit)
     667                        targetAngle = m_lowerLimit;
     668                else if (targetAngle > m_upperLimit)
     669                        targetAngle = m_upperLimit;
     670        }
     671
     672        // compute angular velocity
     673        btScalar curAngle  = getHingeAngle(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
     674        btScalar dAngle = targetAngle - curAngle;
     675        m_motorTargetVelocity = dAngle / dt;
     676}
     677
     678
     679
     680void btHingeConstraint::getInfo2InternalUsingFrameOffset(btConstraintInfo2* info, const btTransform& transA,const btTransform& transB,const btVector3& angVelA,const btVector3& angVelB)
     681{
     682        btAssert(!m_useSolveConstraintObsolete);
     683        int i, s = info->rowskip;
     684        // transforms in world space
     685        btTransform trA = transA*m_rbAFrame;
     686        btTransform trB = transB*m_rbBFrame;
     687        // pivot point
     688        btVector3 pivotAInW = trA.getOrigin();
     689        btVector3 pivotBInW = trB.getOrigin();
     690#if 1
     691        // difference between frames in WCS
     692        btVector3 ofs = trB.getOrigin() - trA.getOrigin();
     693        // now get weight factors depending on masses
     694        btScalar miA = getRigidBodyA().getInvMass();
     695        btScalar miB = getRigidBodyB().getInvMass();
     696        bool hasStaticBody = (miA < SIMD_EPSILON) || (miB < SIMD_EPSILON);
     697        btScalar miS = miA + miB;
     698        btScalar factA, factB;
     699        if(miS > btScalar(0.f))
     700        {
     701                factA = miB / miS;
     702        }
     703        else
     704        {
     705                factA = btScalar(0.5f);
     706        }
     707        factB = btScalar(1.0f) - factA;
     708        // get the desired direction of hinge axis
     709        // as weighted sum of Z-orthos of frameA and frameB in WCS
     710        btVector3 ax1A = trA.getBasis().getColumn(2);
     711        btVector3 ax1B = trB.getBasis().getColumn(2);
     712        btVector3 ax1 = ax1A * factA + ax1B * factB;
     713        ax1.normalize();
     714        // fill first 3 rows
     715        // we want: velA + wA x relA == velB + wB x relB
     716        btTransform bodyA_trans = transA;
     717        btTransform bodyB_trans = transB;
     718        int s0 = 0;
     719        int s1 = s;
     720        int s2 = s * 2;
     721        int nrow = 2; // last filled row
     722        btVector3 tmpA, tmpB, relA, relB, p, q;
     723        // get vector from bodyB to frameB in WCS
     724        relB = trB.getOrigin() - bodyB_trans.getOrigin();
     725        // get its projection to hinge axis
     726        btVector3 projB = ax1 * relB.dot(ax1);
     727        // get vector directed from bodyB to hinge axis (and orthogonal to it)
     728        btVector3 orthoB = relB - projB;
     729        // same for bodyA
     730        relA = trA.getOrigin() - bodyA_trans.getOrigin();
     731        btVector3 projA = ax1 * relA.dot(ax1);
     732        btVector3 orthoA = relA - projA;
     733        btVector3 totalDist = projA - projB;
     734        // get offset vectors relA and relB
     735        relA = orthoA + totalDist * factA;
     736        relB = orthoB - totalDist * factB;
     737        // now choose average ortho to hinge axis
     738        p = orthoB * factA + orthoA * factB;
     739        btScalar len2 = p.length2();
     740        if(len2 > SIMD_EPSILON)
     741        {
     742                p /= btSqrt(len2);
     743        }
     744        else
     745        {
     746                p = trA.getBasis().getColumn(1);
     747        }
     748        // make one more ortho
     749        q = ax1.cross(p);
     750        // fill three rows
     751        tmpA = relA.cross(p);
     752        tmpB = relB.cross(p);
     753    for (i=0; i<3; i++) info->m_J1angularAxis[s0+i] = tmpA[i];
     754    for (i=0; i<3; i++) info->m_J2angularAxis[s0+i] = -tmpB[i];
     755        tmpA = relA.cross(q);
     756        tmpB = relB.cross(q);
     757        if(hasStaticBody && getSolveLimit())
     758        { // to make constraint between static and dynamic objects more rigid
     759                // remove wA (or wB) from equation if angular limit is hit
     760                tmpB *= factB;
     761                tmpA *= factA;
     762        }
     763        for (i=0; i<3; i++) info->m_J1angularAxis[s1+i] = tmpA[i];
     764    for (i=0; i<3; i++) info->m_J2angularAxis[s1+i] = -tmpB[i];
     765        tmpA = relA.cross(ax1);
     766        tmpB = relB.cross(ax1);
     767        if(hasStaticBody)
     768        { // to make constraint between static and dynamic objects more rigid
     769                // remove wA (or wB) from equation
     770                tmpB *= factB;
     771                tmpA *= factA;
     772        }
     773        for (i=0; i<3; i++) info->m_J1angularAxis[s2+i] = tmpA[i];
     774    for (i=0; i<3; i++) info->m_J2angularAxis[s2+i] = -tmpB[i];
     775
     776        btScalar k = info->fps * info->erp;
     777
     778        if (!m_angularOnly)
     779        {
     780                for (i=0; i<3; i++) info->m_J1linearAxis[s0+i] = p[i];
     781                for (i=0; i<3; i++) info->m_J1linearAxis[s1+i] = q[i];
     782                for (i=0; i<3; i++) info->m_J1linearAxis[s2+i] = ax1[i];
     783       
     784        // compute three elements of right hand side
     785       
     786                btScalar rhs = k * p.dot(ofs);
     787                info->m_constraintError[s0] = rhs;
     788                rhs = k * q.dot(ofs);
     789                info->m_constraintError[s1] = rhs;
     790                rhs = k * ax1.dot(ofs);
     791                info->m_constraintError[s2] = rhs;
     792        }
     793        // the hinge axis should be the only unconstrained
     794        // rotational axis, the angular velocity of the two bodies perpendicular to
     795        // the hinge axis should be equal. thus the constraint equations are
     796        //    p*w1 - p*w2 = 0
     797        //    q*w1 - q*w2 = 0
     798        // where p and q are unit vectors normal to the hinge axis, and w1 and w2
     799        // are the angular velocity vectors of the two bodies.
     800        int s3 = 3 * s;
     801        int s4 = 4 * s;
     802        info->m_J1angularAxis[s3 + 0] = p[0];
     803        info->m_J1angularAxis[s3 + 1] = p[1];
     804        info->m_J1angularAxis[s3 + 2] = p[2];
     805        info->m_J1angularAxis[s4 + 0] = q[0];
     806        info->m_J1angularAxis[s4 + 1] = q[1];
     807        info->m_J1angularAxis[s4 + 2] = q[2];
     808
     809        info->m_J2angularAxis[s3 + 0] = -p[0];
     810        info->m_J2angularAxis[s3 + 1] = -p[1];
     811        info->m_J2angularAxis[s3 + 2] = -p[2];
     812        info->m_J2angularAxis[s4 + 0] = -q[0];
     813        info->m_J2angularAxis[s4 + 1] = -q[1];
     814        info->m_J2angularAxis[s4 + 2] = -q[2];
     815        // compute the right hand side of the constraint equation. set relative
     816        // body velocities along p and q to bring the hinge back into alignment.
     817        // if ax1A,ax1B are the unit length hinge axes as computed from bodyA and
     818        // bodyB, we need to rotate both bodies along the axis u = (ax1 x ax2).
     819        // if "theta" is the angle between ax1 and ax2, we need an angular velocity
     820        // along u to cover angle erp*theta in one step :
     821        //   |angular_velocity| = angle/time = erp*theta / stepsize
     822        //                      = (erp*fps) * theta
     823        //    angular_velocity  = |angular_velocity| * (ax1 x ax2) / |ax1 x ax2|
     824        //                      = (erp*fps) * theta * (ax1 x ax2) / sin(theta)
     825        // ...as ax1 and ax2 are unit length. if theta is smallish,
     826        // theta ~= sin(theta), so
     827        //    angular_velocity  = (erp*fps) * (ax1 x ax2)
     828        // ax1 x ax2 is in the plane space of ax1, so we project the angular
     829        // velocity to p and q to find the right hand side.
     830        k = info->fps * info->erp;
     831        btVector3 u = ax1A.cross(ax1B);
     832        info->m_constraintError[s3] = k * u.dot(p);
     833        info->m_constraintError[s4] = k * u.dot(q);
     834#endif
     835        // check angular limits
     836        nrow = 4; // last filled row
     837        int srow;
     838        btScalar limit_err = btScalar(0.0);
     839        int limit = 0;
     840        if(getSolveLimit())
     841        {
     842                limit_err = m_correction * m_referenceSign;
     843                limit = (limit_err > btScalar(0.0)) ? 1 : 2;
     844        }
     845        // if the hinge has joint limits or motor, add in the extra row
     846        int powered = 0;
     847        if(getEnableAngularMotor())
     848        {
     849                powered = 1;
     850        }
     851        if(limit || powered)
     852        {
     853                nrow++;
     854                srow = nrow * info->rowskip;
     855                info->m_J1angularAxis[srow+0] = ax1[0];
     856                info->m_J1angularAxis[srow+1] = ax1[1];
     857                info->m_J1angularAxis[srow+2] = ax1[2];
     858
     859                info->m_J2angularAxis[srow+0] = -ax1[0];
     860                info->m_J2angularAxis[srow+1] = -ax1[1];
     861                info->m_J2angularAxis[srow+2] = -ax1[2];
     862
     863                btScalar lostop = getLowerLimit();
     864                btScalar histop = getUpperLimit();
     865                if(limit && (lostop == histop))
     866                {  // the joint motor is ineffective
     867                        powered = 0;
     868                }
     869                info->m_constraintError[srow] = btScalar(0.0f);
     870                btScalar currERP = (m_flags & BT_HINGE_FLAGS_ERP_STOP) ? m_stopERP : info->erp;
     871                if(powered)
     872                {
     873                        if(m_flags & BT_HINGE_FLAGS_CFM_NORM)
     874                        {
     875                                info->cfm[srow] = m_normalCFM;
     876                        }
     877                        btScalar mot_fact = getMotorFactor(m_hingeAngle, lostop, histop, m_motorTargetVelocity, info->fps * currERP);
     878                        info->m_constraintError[srow] += mot_fact * m_motorTargetVelocity * m_referenceSign;
     879                        info->m_lowerLimit[srow] = - m_maxMotorImpulse;
     880                        info->m_upperLimit[srow] =   m_maxMotorImpulse;
     881                }
     882                if(limit)
     883                {
     884                        k = info->fps * currERP;
     885                        info->m_constraintError[srow] += k * limit_err;
     886                        if(m_flags & BT_HINGE_FLAGS_CFM_STOP)
     887                        {
     888                                info->cfm[srow] = m_stopCFM;
     889                        }
     890                        if(lostop == histop)
     891                        {
     892                                // limited low and high simultaneously
     893                                info->m_lowerLimit[srow] = -SIMD_INFINITY;
     894                                info->m_upperLimit[srow] = SIMD_INFINITY;
     895                        }
     896                        else if(limit == 1)
     897                        { // low limit
     898                                info->m_lowerLimit[srow] = 0;
     899                                info->m_upperLimit[srow] = SIMD_INFINITY;
     900                        }
     901                        else
     902                        { // high limit
     903                                info->m_lowerLimit[srow] = -SIMD_INFINITY;
     904                                info->m_upperLimit[srow] = 0;
     905                        }
     906                        // bounce (we'll use slider parameter abs(1.0 - m_dampingLimAng) for that)
     907                        btScalar bounce = m_relaxationFactor;
     908                        if(bounce > btScalar(0.0))
     909                        {
     910                                btScalar vel = angVelA.dot(ax1);
     911                                vel -= angVelB.dot(ax1);
     912                                // only apply bounce if the velocity is incoming, and if the
     913                                // resulting c[] exceeds what we already have.
     914                                if(limit == 1)
     915                                {       // low limit
     916                                        if(vel < 0)
     917                                        {
     918                                                btScalar newc = -bounce * vel;
     919                                                if(newc > info->m_constraintError[srow])
     920                                                {
     921                                                        info->m_constraintError[srow] = newc;
     922                                                }
     923                                        }
     924                                }
     925                                else
     926                                {       // high limit - all those computations are reversed
     927                                        if(vel > 0)
     928                                        {
     929                                                btScalar newc = -bounce * vel;
     930                                                if(newc < info->m_constraintError[srow])
     931                                                {
     932                                                        info->m_constraintError[srow] = newc;
     933                                                }
     934                                        }
     935                                }
     936                        }
     937                        info->m_constraintError[srow] *= m_biasFactor;
     938                } // if(limit)
     939        } // if angular limit or powered
     940}
     941
     942
     943///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     944///If no axis is provided, it uses the default axis for this constraint.
     945void btHingeConstraint::setParam(int num, btScalar value, int axis)
     946{
     947        if((axis == -1) || (axis == 5))
     948        {
     949                switch(num)
     950                {       
     951                        case BT_CONSTRAINT_STOP_ERP :
     952                                m_stopERP = value;
     953                                m_flags |= BT_HINGE_FLAGS_ERP_STOP;
     954                                break;
     955                        case BT_CONSTRAINT_STOP_CFM :
     956                                m_stopCFM = value;
     957                                m_flags |= BT_HINGE_FLAGS_CFM_STOP;
     958                                break;
     959                        case BT_CONSTRAINT_CFM :
     960                                m_normalCFM = value;
     961                                m_flags |= BT_HINGE_FLAGS_CFM_NORM;
     962                                break;
     963                        default :
     964                                btAssertConstrParams(0);
     965                }
     966        }
     967        else
     968        {
     969                btAssertConstrParams(0);
     970        }
     971}
     972
     973///return the local value of parameter
     974btScalar btHingeConstraint::getParam(int num, int axis) const
     975{
     976        btScalar retVal = 0;
     977        if((axis == -1) || (axis == 5))
     978        {
     979                switch(num)
     980                {       
     981                        case BT_CONSTRAINT_STOP_ERP :
     982                                btAssertConstrParams(m_flags & BT_HINGE_FLAGS_ERP_STOP);
     983                                retVal = m_stopERP;
     984                                break;
     985                        case BT_CONSTRAINT_STOP_CFM :
     986                                btAssertConstrParams(m_flags & BT_HINGE_FLAGS_CFM_STOP);
     987                                retVal = m_stopCFM;
     988                                break;
     989                        case BT_CONSTRAINT_CFM :
     990                                btAssertConstrParams(m_flags & BT_HINGE_FLAGS_CFM_NORM);
     991                                retVal = m_normalCFM;
     992                                break;
     993                        default :
     994                                btAssertConstrParams(0);
     995                }
     996        }
     997        else
     998        {
     999                btAssertConstrParams(0);
     1000        }
     1001        return retVal;
     1002}
     1003
     1004
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btHingeConstraint.h

    r5781 r8284  
    2525class btRigidBody;
    2626
     27#ifdef BT_USE_DOUBLE_PRECISION
     28#define btHingeConstraintData   btHingeConstraintDoubleData
     29#define btHingeConstraintDataName       "btHingeConstraintDoubleData"
     30#else
     31#define btHingeConstraintData   btHingeConstraintFloatData
     32#define btHingeConstraintDataName       "btHingeConstraintFloatData"
     33#endif //BT_USE_DOUBLE_PRECISION
     34
     35
     36enum btHingeFlags
     37{
     38        BT_HINGE_FLAGS_CFM_STOP = 1,
     39        BT_HINGE_FLAGS_ERP_STOP = 2,
     40        BT_HINGE_FLAGS_CFM_NORM = 4
     41};
     42
     43
    2744/// hinge constraint between two rigidbodies each with a pivotpoint that descibes the axis location in local space
    2845/// axis defines the orientation of the hinge axis
    29 class btHingeConstraint : public btTypedConstraint
     46ATTRIBUTE_ALIGNED16(class) btHingeConstraint : public btTypedConstraint
    3047{
    3148#ifdef IN_PARALLELL_SOLVER
     
    6178        bool            m_solveLimit;
    6279        bool            m_useSolveConstraintObsolete;
     80        bool            m_useOffsetForConstraintFrame;
    6381        bool            m_useReferenceFrameA;
    6482
     83        btScalar        m_accMotorImpulse;
     84
     85        int                     m_flags;
     86        btScalar        m_normalCFM;
     87        btScalar        m_stopCFM;
     88        btScalar        m_stopERP;
     89
    6590       
    6691public:
    6792
    68         btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB, btVector3& axisInA,btVector3& axisInB, bool useReferenceFrameA = false);
    69 
    70         btHingeConstraint(btRigidBody& rbA,const btVector3& pivotInA,btVector3& axisInA, bool useReferenceFrameA = false);
     93        btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB, const btVector3& axisInA,const btVector3& axisInB, bool useReferenceFrameA = false);
     94
     95        btHingeConstraint(btRigidBody& rbA,const btVector3& pivotInA,const btVector3& axisInA, bool useReferenceFrameA = false);
    7196       
    7297        btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btTransform& rbAFrame, const btTransform& rbBFrame, bool useReferenceFrameA = false);
     
    7499        btHingeConstraint(btRigidBody& rbA,const btTransform& rbAFrame, bool useReferenceFrameA = false);
    75100
    76         btHingeConstraint();
    77101
    78102        virtual void    buildJacobian();
     
    80104        virtual void getInfo1 (btConstraintInfo1* info);
    81105
     106        void getInfo1NonVirtual(btConstraintInfo1* info);
     107
    82108        virtual void getInfo2 (btConstraintInfo2* info);
    83        
    84         virtual void    solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar        timeStep);
     109
     110        void    getInfo2NonVirtual(btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btVector3& angVelA,const btVector3& angVelB);
     111
     112        void    getInfo2Internal(btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btVector3& angVelA,const btVector3& angVelB);
     113        void    getInfo2InternalUsingFrameOffset(btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btVector3& angVelA,const btVector3& angVelB);
     114               
    85115
    86116        void    updateRHS(btScalar      timeStep);
     
    117147        }
    118148
     149        // extra motor API, including ability to set a target rotation (as opposed to angular velocity)
     150        // note: setMotorTarget sets angular velocity under the hood, so you must call it every tick to
     151        //       maintain a given angular target.
     152        void enableMotor(bool enableMotor)      { m_enableAngularMotor = enableMotor; }
     153        void setMaxMotorImpulse(btScalar maxMotorImpulse) { m_maxMotorImpulse = maxMotorImpulse; }
     154        void setMotorTarget(const btQuaternion& qAinB, btScalar dt); // qAinB is rotation of body A wrt body B.
     155        void setMotorTarget(btScalar targetAngle, btScalar dt);
     156
     157
    119158        void    setLimit(btScalar low,btScalar high,btScalar _softness = 0.9f, btScalar _biasFactor = 0.3f, btScalar _relaxationFactor = 1.0f)
    120159        {
    121                 m_lowerLimit = low;
    122                 m_upperLimit = high;
     160                m_lowerLimit = btNormalizeAngle(low);
     161                m_upperLimit = btNormalizeAngle(high);
    123162
    124163                m_limitSoftness =  _softness;
     
    128167        }
    129168
     169        void    setAxis(btVector3& axisInA)
     170        {
     171                btVector3 rbAxisA1, rbAxisA2;
     172                btPlaneSpace1(axisInA, rbAxisA1, rbAxisA2);
     173                btVector3 pivotInA = m_rbAFrame.getOrigin();
     174//              m_rbAFrame.getOrigin() = pivotInA;
     175                m_rbAFrame.getBasis().setValue( rbAxisA1.getX(),rbAxisA2.getX(),axisInA.getX(),
     176                                                                                rbAxisA1.getY(),rbAxisA2.getY(),axisInA.getY(),
     177                                                                                rbAxisA1.getZ(),rbAxisA2.getZ(),axisInA.getZ() );
     178
     179                btVector3 axisInB = m_rbA.getCenterOfMassTransform().getBasis() * axisInA;
     180
     181                btQuaternion rotationArc = shortestArcQuat(axisInA,axisInB);
     182                btVector3 rbAxisB1 =  quatRotate(rotationArc,rbAxisA1);
     183                btVector3 rbAxisB2 = axisInB.cross(rbAxisB1);
     184
     185
     186                m_rbBFrame.getOrigin() = m_rbA.getCenterOfMassTransform()(pivotInA);
     187                m_rbBFrame.getBasis().setValue( rbAxisB1.getX(),rbAxisB2.getX(),axisInB.getX(),
     188                                                                                rbAxisB1.getY(),rbAxisB2.getY(),axisInB.getY(),
     189                                                                                rbAxisB1.getZ(),rbAxisB2.getZ(),axisInB.getZ() );
     190        }
     191
    130192        btScalar        getLowerLimit() const
    131193        {
     
    141203        btScalar getHingeAngle();
    142204
    143         void testLimit();
    144 
    145 
    146         const btTransform& getAFrame() { return m_rbAFrame; }; 
    147         const btTransform& getBFrame() { return m_rbBFrame; };
     205        btScalar getHingeAngle(const btTransform& transA,const btTransform& transB);
     206
     207        void testLimit(const btTransform& transA,const btTransform& transB);
     208
     209
     210        const btTransform& getAFrame() const { return m_rbAFrame; };   
     211        const btTransform& getBFrame() const { return m_rbBFrame; };
     212
     213        btTransform& getAFrame() { return m_rbAFrame; };       
     214        btTransform& getBFrame() { return m_rbBFrame; };
    148215
    149216        inline int getSolveLimit()
     
    173240                return m_maxMotorImpulse;
    174241        }
     242        // access for UseFrameOffset
     243        bool getUseFrameOffset() { return m_useOffsetForConstraintFrame; }
     244        void setUseFrameOffset(bool frameOffsetOnOff) { m_useOffsetForConstraintFrame = frameOffsetOnOff; }
     245
     246
     247        ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     248        ///If no axis is provided, it uses the default axis for this constraint.
     249        virtual void    setParam(int num, btScalar value, int axis = -1);
     250        ///return the local value of parameter
     251        virtual btScalar getParam(int num, int axis = -1) const;
     252
     253        virtual int     calculateSerializeBufferSize() const;
     254
     255        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     256        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     257
    175258
    176259};
    177260
     261///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     262struct  btHingeConstraintDoubleData
     263{
     264        btTypedConstraintData   m_typeConstraintData;
     265        btTransformDoubleData m_rbAFrame; // constraint axii. Assumes z is hinge axis.
     266        btTransformDoubleData m_rbBFrame;
     267        int                     m_useReferenceFrameA;
     268        int                     m_angularOnly;
     269        int                     m_enableAngularMotor;
     270        float   m_motorTargetVelocity;
     271        float   m_maxMotorImpulse;
     272
     273        float   m_lowerLimit;
     274        float   m_upperLimit;
     275        float   m_limitSoftness;
     276        float   m_biasFactor;
     277        float   m_relaxationFactor;
     278
     279};
     280///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     281struct  btHingeConstraintFloatData
     282{
     283        btTypedConstraintData   m_typeConstraintData;
     284        btTransformFloatData m_rbAFrame; // constraint axii. Assumes z is hinge axis.
     285        btTransformFloatData m_rbBFrame;
     286        int                     m_useReferenceFrameA;
     287        int                     m_angularOnly;
     288       
     289        int                     m_enableAngularMotor;
     290        float   m_motorTargetVelocity;
     291        float   m_maxMotorImpulse;
     292
     293        float   m_lowerLimit;
     294        float   m_upperLimit;
     295        float   m_limitSoftness;
     296        float   m_biasFactor;
     297        float   m_relaxationFactor;
     298
     299};
     300
     301
     302
     303SIMD_FORCE_INLINE       int     btHingeConstraint::calculateSerializeBufferSize() const
     304{
     305        return sizeof(btHingeConstraintData);
     306}
     307
     308        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     309SIMD_FORCE_INLINE       const char*     btHingeConstraint::serialize(void* dataBuffer, btSerializer* serializer) const
     310{
     311        btHingeConstraintData* hingeData = (btHingeConstraintData*)dataBuffer;
     312        btTypedConstraint::serialize(&hingeData->m_typeConstraintData,serializer);
     313
     314        m_rbAFrame.serialize(hingeData->m_rbAFrame);
     315        m_rbBFrame.serialize(hingeData->m_rbBFrame);
     316
     317        hingeData->m_angularOnly = m_angularOnly;
     318        hingeData->m_enableAngularMotor = m_enableAngularMotor;
     319        hingeData->m_maxMotorImpulse = float(m_maxMotorImpulse);
     320        hingeData->m_motorTargetVelocity = float(m_motorTargetVelocity);
     321        hingeData->m_useReferenceFrameA = m_useReferenceFrameA;
     322       
     323        hingeData->m_lowerLimit = float(m_lowerLimit);
     324        hingeData->m_upperLimit = float(m_upperLimit);
     325        hingeData->m_limitSoftness = float(m_limitSoftness);
     326        hingeData->m_biasFactor = float(m_biasFactor);
     327        hingeData->m_relaxationFactor = float(m_relaxationFactor);
     328
     329        return btHingeConstraintDataName;
     330}
     331
    178332#endif //HINGECONSTRAINT_H
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btJacobianEntry.h

    r5781 r8284  
    2929/// it can be used in combination with a constraint solver
    3030/// Can be used to relate the effect of an impulse to the constraint error
    31 class btJacobianEntry
     31ATTRIBUTE_ALIGNED16(class) btJacobianEntry
    3232{
    3333public:
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.cpp

    r5781 r8284  
    2121
    2222
    23 btPoint2PointConstraint::btPoint2PointConstraint()
    24 :btTypedConstraint(POINT2POINT_CONSTRAINT_TYPE),
    25 m_useSolveConstraintObsolete(false)
    26 {
    27 }
     23
    2824
    2925btPoint2PointConstraint::btPoint2PointConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB)
    3026:btTypedConstraint(POINT2POINT_CONSTRAINT_TYPE,rbA,rbB),m_pivotInA(pivotInA),m_pivotInB(pivotInB),
     27m_flags(0),
    3128m_useSolveConstraintObsolete(false)
    3229{
     
    3734btPoint2PointConstraint::btPoint2PointConstraint(btRigidBody& rbA,const btVector3& pivotInA)
    3835:btTypedConstraint(POINT2POINT_CONSTRAINT_TYPE,rbA),m_pivotInA(pivotInA),m_pivotInB(rbA.getCenterOfMassTransform()(pivotInA)),
     36m_flags(0),
    3937m_useSolveConstraintObsolete(false)
    4038{
     
    4442void    btPoint2PointConstraint::buildJacobian()
    4543{
     44
    4645        ///we need it for both methods
    4746        {
     
    6766        }
    6867
    69 }
    70 
     68
     69}
    7170
    7271void btPoint2PointConstraint::getInfo1 (btConstraintInfo1* info)
     72{
     73        getInfo1NonVirtual(info);
     74}
     75
     76void btPoint2PointConstraint::getInfo1NonVirtual (btConstraintInfo1* info)
    7377{
    7478        if (m_useSolveConstraintObsolete)
     
    8387}
    8488
     89
     90
     91
    8592void btPoint2PointConstraint::getInfo2 (btConstraintInfo2* info)
    8693{
     94        getInfo2NonVirtual(info, m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
     95}
     96
     97void btPoint2PointConstraint::getInfo2NonVirtual (btConstraintInfo2* info, const btTransform& body0_trans, const btTransform& body1_trans)
     98{
    8799        btAssert(!m_useSolveConstraintObsolete);
    88100
    89101         //retrieve matrices
    90         btTransform body0_trans;
    91         body0_trans = m_rbA.getCenterOfMassTransform();
    92     btTransform body1_trans;
    93         body1_trans = m_rbB.getCenterOfMassTransform();
    94102
    95103        // anchor points in global coordinates with respect to body PORs.
     
    97105    // set jacobian
    98106    info->m_J1linearAxis[0] = 1;
    99     info->m_J1linearAxis[info->rowskip+1] = 1;
    100     info->m_J1linearAxis[2*info->rowskip+2] = 1;
     107        info->m_J1linearAxis[info->rowskip+1] = 1;
     108        info->m_J1linearAxis[2*info->rowskip+2] = 1;
    101109
    102110        btVector3 a1 = body0_trans.getBasis()*getPivotInA();
     
    127135
    128136    // set right hand side
    129     btScalar k = info->fps * info->erp;
     137        btScalar currERP = (m_flags & BT_P2P_FLAGS_ERP) ? m_erp : info->erp;
     138    btScalar k = info->fps * currERP;
    130139    int j;
    131 
    132140        for (j=0; j<3; j++)
    133141    {
    134         info->m_constraintError[j*info->rowskip] = k * (a2[j] + body1_trans.getOrigin()[j] -                     a1[j] - body0_trans.getOrigin()[j]);
     142        info->m_constraintError[j*info->rowskip] = k * (a2[j] + body1_trans.getOrigin()[j] - a1[j] - body0_trans.getOrigin()[j]);
    135143                //printf("info->m_constraintError[%d]=%f\n",j,info->m_constraintError[j]);
    136144    }
     145        if(m_flags & BT_P2P_FLAGS_CFM)
     146        {
     147                for (j=0; j<3; j++)
     148                {
     149                        info->cfm[j*info->rowskip] = m_cfm;
     150                }
     151        }
    137152
    138153        btScalar impulseClamp = m_setting.m_impulseClamp;//
     
    145160                }
    146161        }
    147        
    148 }
    149 
    150 
    151 void    btPoint2PointConstraint::solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar       timeStep)
    152 {
    153         if (m_useSolveConstraintObsolete)
    154         {
    155                 btVector3 pivotAInW = m_rbA.getCenterOfMassTransform()*m_pivotInA;
    156                 btVector3 pivotBInW = m_rbB.getCenterOfMassTransform()*m_pivotInB;
    157 
    158 
    159                 btVector3 normal(0,0,0);
    160                
    161 
    162         //      btVector3 angvelA = m_rbA.getCenterOfMassTransform().getBasis().transpose() * m_rbA.getAngularVelocity();
    163         //      btVector3 angvelB = m_rbB.getCenterOfMassTransform().getBasis().transpose() * m_rbB.getAngularVelocity();
    164 
    165                 for (int i=0;i<3;i++)
    166                 {               
    167                         normal[i] = 1;
    168                         btScalar jacDiagABInv = btScalar(1.) / m_jac[i].getDiagonal();
    169 
    170                         btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition();
    171                         btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition();
    172                         //this jacobian entry could be re-used for all iterations
    173                        
    174                         btVector3 vel1,vel2;
    175                         bodyA.getVelocityInLocalPointObsolete(rel_pos1,vel1);
    176                         bodyB.getVelocityInLocalPointObsolete(rel_pos2,vel2);
    177                         btVector3 vel = vel1 - vel2;
    178                        
    179                         btScalar rel_vel;
    180                         rel_vel = normal.dot(vel);
    181 
    182                 /*
    183                         //velocity error (first order error)
    184                         btScalar rel_vel = m_jac[i].getRelativeVelocity(m_rbA.getLinearVelocity(),angvelA,
    185                                                                                                                         m_rbB.getLinearVelocity(),angvelB);
    186                 */
    187                
    188                         //positional error (zeroth order error)
    189                         btScalar depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal
    190                        
    191                         btScalar deltaImpulse = depth*m_setting.m_tau/timeStep  * jacDiagABInv -  m_setting.m_damping * rel_vel * jacDiagABInv;
    192 
    193                         btScalar impulseClamp = m_setting.m_impulseClamp;
    194                        
    195                         const btScalar sum = btScalar(m_appliedImpulse) + deltaImpulse;
    196                         if (sum < -impulseClamp)
    197                         {
    198                                 deltaImpulse = -impulseClamp-m_appliedImpulse;
    199                                 m_appliedImpulse = -impulseClamp;
    200                         }
    201                         else if (sum > impulseClamp)
    202                         {
    203                                 deltaImpulse = impulseClamp-m_appliedImpulse;
    204                                 m_appliedImpulse = impulseClamp;
    205                         }
    206                         else
    207                         {
    208                                 m_appliedImpulse = sum;
    209                         }
    210 
    211                        
    212                         btVector3 impulse_vector = normal * deltaImpulse;
    213                        
    214                         btVector3 ftorqueAxis1 = rel_pos1.cross(normal);
    215                         btVector3 ftorqueAxis2 = rel_pos2.cross(normal);
    216                         bodyA.applyImpulse(normal*m_rbA.getInvMass(), m_rbA.getInvInertiaTensorWorld()*ftorqueAxis1,deltaImpulse);
    217                         bodyB.applyImpulse(normal*m_rbB.getInvMass(), m_rbB.getInvInertiaTensorWorld()*ftorqueAxis2,-deltaImpulse);
    218 
    219 
    220                         normal[i] = 0;
    221                 }
    222         }
    223 }
     162        info->m_damping = m_setting.m_damping;
     163       
     164}
     165
     166
    224167
    225168void    btPoint2PointConstraint::updateRHS(btScalar     timeStep)
     
    229172}
    230173
     174///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     175///If no axis is provided, it uses the default axis for this constraint.
     176void btPoint2PointConstraint::setParam(int num, btScalar value, int axis)
     177{
     178        if(axis != -1)
     179        {
     180                btAssertConstrParams(0);
     181        }
     182        else
     183        {
     184                switch(num)
     185                {
     186                        case BT_CONSTRAINT_ERP :
     187                        case BT_CONSTRAINT_STOP_ERP :
     188                                m_erp = value;
     189                                m_flags |= BT_P2P_FLAGS_ERP;
     190                                break;
     191                        case BT_CONSTRAINT_CFM :
     192                        case BT_CONSTRAINT_STOP_CFM :
     193                                m_cfm = value;
     194                                m_flags |= BT_P2P_FLAGS_CFM;
     195                                break;
     196                        default:
     197                                btAssertConstrParams(0);
     198                }
     199        }
     200}
     201
     202///return the local value of parameter
     203btScalar btPoint2PointConstraint::getParam(int num, int axis) const
     204{
     205        btScalar retVal(SIMD_INFINITY);
     206        if(axis != -1)
     207        {
     208                btAssertConstrParams(0);
     209        }
     210        else
     211        {
     212                switch(num)
     213                {
     214                        case BT_CONSTRAINT_ERP :
     215                        case BT_CONSTRAINT_STOP_ERP :
     216                                btAssertConstrParams(m_flags & BT_P2P_FLAGS_ERP);
     217                                retVal = m_erp;
     218                                break;
     219                        case BT_CONSTRAINT_CFM :
     220                        case BT_CONSTRAINT_STOP_CFM :
     221                                btAssertConstrParams(m_flags & BT_P2P_FLAGS_CFM);
     222                                retVal = m_cfm;
     223                                break;
     224                        default:
     225                                btAssertConstrParams(0);
     226                }
     227        }
     228        return retVal;
     229}
     230       
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h

    r5781 r8284  
    2323class btRigidBody;
    2424
     25
     26#ifdef BT_USE_DOUBLE_PRECISION
     27#define btPoint2PointConstraintData     btPoint2PointConstraintDoubleData
     28#define btPoint2PointConstraintDataName "btPoint2PointConstraintDoubleData"
     29#else
     30#define btPoint2PointConstraintData     btPoint2PointConstraintFloatData
     31#define btPoint2PointConstraintDataName "btPoint2PointConstraintFloatData"
     32#endif //BT_USE_DOUBLE_PRECISION
     33
    2534struct  btConstraintSetting
    2635{
     
    3645};
    3746
     47enum btPoint2PointFlags
     48{
     49        BT_P2P_FLAGS_ERP = 1,
     50        BT_P2P_FLAGS_CFM = 2
     51};
     52
    3853/// point to point constraint between two rigidbodies each with a pivotpoint that descibes the 'ballsocket' location in local space
    39 class btPoint2PointConstraint : public btTypedConstraint
     54ATTRIBUTE_ALIGNED16(class) btPoint2PointConstraint : public btTypedConstraint
    4055{
    4156#ifdef IN_PARALLELL_SOLVER
     
    4762        btVector3       m_pivotInB;
    4863       
    49        
     64        int                     m_flags;
     65        btScalar        m_erp;
     66        btScalar        m_cfm;
    5067       
    5168public:
     
    6077        btPoint2PointConstraint(btRigidBody& rbA,const btVector3& pivotInA);
    6178
    62         btPoint2PointConstraint();
    6379
    6480        virtual void    buildJacobian();
     
    6682        virtual void getInfo1 (btConstraintInfo1* info);
    6783
     84        void getInfo1NonVirtual (btConstraintInfo1* info);
     85
    6886        virtual void getInfo2 (btConstraintInfo2* info);
    6987
    70 
    71         virtual void    solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar        timeStep);
     88        void getInfo2NonVirtual (btConstraintInfo2* info, const btTransform& body0_trans, const btTransform& body1_trans);
    7289
    7390        void    updateRHS(btScalar      timeStep);
     
    93110        }
    94111
     112        ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     113        ///If no axis is provided, it uses the default axis for this constraint.
     114        virtual void    setParam(int num, btScalar value, int axis = -1);
     115        ///return the local value of parameter
     116        virtual btScalar getParam(int num, int axis = -1) const;
     117
     118        virtual int     calculateSerializeBufferSize() const;
     119
     120        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     121        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     122
    95123
    96124};
    97125
     126///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     127struct  btPoint2PointConstraintFloatData
     128{
     129        btTypedConstraintData   m_typeConstraintData;
     130        btVector3FloatData      m_pivotInA;
     131        btVector3FloatData      m_pivotInB;
     132};
     133
     134///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     135struct  btPoint2PointConstraintDoubleData
     136{
     137        btTypedConstraintData   m_typeConstraintData;
     138        btVector3DoubleData     m_pivotInA;
     139        btVector3DoubleData     m_pivotInB;
     140};
     141
     142
     143SIMD_FORCE_INLINE       int     btPoint2PointConstraint::calculateSerializeBufferSize() const
     144{
     145        return sizeof(btPoint2PointConstraintData);
     146
     147}
     148
     149        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     150SIMD_FORCE_INLINE       const char*     btPoint2PointConstraint::serialize(void* dataBuffer, btSerializer* serializer) const
     151{
     152        btPoint2PointConstraintData* p2pData = (btPoint2PointConstraintData*)dataBuffer;
     153
     154        btTypedConstraint::serialize(&p2pData->m_typeConstraintData,serializer);
     155        m_pivotInA.serialize(p2pData->m_pivotInA);
     156        m_pivotInB.serialize(p2pData->m_pivotInB);
     157
     158        return btPoint2PointConstraintDataName;
     159}
     160
    98161#endif //POINT2POINTCONSTRAINT_H
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.cpp

    r5781 r8284  
    3535#include <string.h> //for memset
    3636
     37int             gNumSplitImpulseRecoveries = 0;
     38
    3739btSequentialImpulseConstraintSolver::btSequentialImpulseConstraintSolver()
    3840:m_btSeed2(0)
     
    5658
    5759// Project Gauss Seidel or the equivalent Sequential Impulse
    58 void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGenericSIMD(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& c)
     60void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGenericSIMD(btRigidBody& body1,btRigidBody& body2,const btSolverConstraint& c)
    5961{
    6062#ifdef USE_SIMD
     
    6365        __m128  upperLimit1 = _mm_set1_ps(c.m_upperLimit);
    6466        __m128 deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhs), _mm_mul_ps(_mm_set1_ps(c.m_appliedImpulse),_mm_set1_ps(c.m_cfm)));
    65         __m128 deltaVel1Dotn    =       _mm_add_ps(_vmathVfDot3(c.m_contactNormal.mVec128,body1.m_deltaLinearVelocity.mVec128), _vmathVfDot3(c.m_relpos1CrossNormal.mVec128,body1.m_deltaAngularVelocity.mVec128));
    66         __m128 deltaVel2Dotn    =       _mm_sub_ps(_vmathVfDot3(c.m_relpos2CrossNormal.mVec128,body2.m_deltaAngularVelocity.mVec128),_vmathVfDot3((c.m_contactNormal).mVec128,body2.m_deltaLinearVelocity.mVec128));
     67        __m128 deltaVel1Dotn    =       _mm_add_ps(_vmathVfDot3(c.m_contactNormal.mVec128,body1.internalGetDeltaLinearVelocity().mVec128), _vmathVfDot3(c.m_relpos1CrossNormal.mVec128,body1.internalGetDeltaAngularVelocity().mVec128));
     68        __m128 deltaVel2Dotn    =       _mm_sub_ps(_vmathVfDot3(c.m_relpos2CrossNormal.mVec128,body2.internalGetDeltaAngularVelocity().mVec128),_vmathVfDot3((c.m_contactNormal).mVec128,body2.internalGetDeltaLinearVelocity().mVec128));
    6769        deltaImpulse    =       _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel1Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
    6870        deltaImpulse    =       _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel2Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
     
    7779        deltaImpulse = _mm_or_ps( _mm_and_ps(resultUpperLess, deltaImpulse), _mm_andnot_ps(resultUpperLess, upperMinApplied) );
    7880        c.m_appliedImpulse = _mm_or_ps( _mm_and_ps(resultUpperLess, c.m_appliedImpulse), _mm_andnot_ps(resultUpperLess, upperLimit1) );
    79         __m128  linearComponentA = _mm_mul_ps(c.m_contactNormal.mVec128,_mm_set1_ps(body1.m_invMass));
    80         __m128  linearComponentB = _mm_mul_ps((c.m_contactNormal).mVec128,_mm_set1_ps(body2.m_invMass));
     81        __m128  linearComponentA = _mm_mul_ps(c.m_contactNormal.mVec128,body1.internalGetInvMass().mVec128);
     82        __m128  linearComponentB = _mm_mul_ps((c.m_contactNormal).mVec128,body2.internalGetInvMass().mVec128);
    8183        __m128 impulseMagnitude = deltaImpulse;
    82         body1.m_deltaLinearVelocity.mVec128 = _mm_add_ps(body1.m_deltaLinearVelocity.mVec128,_mm_mul_ps(linearComponentA,impulseMagnitude));
    83         body1.m_deltaAngularVelocity.mVec128 = _mm_add_ps(body1.m_deltaAngularVelocity.mVec128 ,_mm_mul_ps(c.m_angularComponentA.mVec128,impulseMagnitude));
    84         body2.m_deltaLinearVelocity.mVec128 = _mm_sub_ps(body2.m_deltaLinearVelocity.mVec128,_mm_mul_ps(linearComponentB,impulseMagnitude));
    85         body2.m_deltaAngularVelocity.mVec128 = _mm_add_ps(body2.m_deltaAngularVelocity.mVec128 ,_mm_mul_ps(c.m_angularComponentB.mVec128,impulseMagnitude));
     84        body1.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(body1.internalGetDeltaLinearVelocity().mVec128,_mm_mul_ps(linearComponentA,impulseMagnitude));
     85        body1.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(body1.internalGetDeltaAngularVelocity().mVec128 ,_mm_mul_ps(c.m_angularComponentA.mVec128,impulseMagnitude));
     86        body2.internalGetDeltaLinearVelocity().mVec128 = _mm_sub_ps(body2.internalGetDeltaLinearVelocity().mVec128,_mm_mul_ps(linearComponentB,impulseMagnitude));
     87        body2.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(body2.internalGetDeltaAngularVelocity().mVec128 ,_mm_mul_ps(c.m_angularComponentB.mVec128,impulseMagnitude));
    8688#else
    8789        resolveSingleConstraintRowGeneric(body1,body2,c);
     
    9092
    9193// Project Gauss Seidel or the equivalent Sequential Impulse
    92  void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGeneric(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& c)
     94 void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGeneric(btRigidBody& body1,btRigidBody& body2,const btSolverConstraint& c)
    9395{
    9496        btScalar deltaImpulse = c.m_rhs-btScalar(c.m_appliedImpulse)*c.m_cfm;
    95         const btScalar deltaVel1Dotn    =       c.m_contactNormal.dot(body1.m_deltaLinearVelocity)      + c.m_relpos1CrossNormal.dot(body1.m_deltaAngularVelocity);
    96         const btScalar deltaVel2Dotn    =       -c.m_contactNormal.dot(body2.m_deltaLinearVelocity) + c.m_relpos2CrossNormal.dot(body2.m_deltaAngularVelocity);
    97 
    98         const btScalar delta_rel_vel    =       deltaVel1Dotn-deltaVel2Dotn;
     97        const btScalar deltaVel1Dotn    =       c.m_contactNormal.dot(body1.internalGetDeltaLinearVelocity())   + c.m_relpos1CrossNormal.dot(body1.internalGetDeltaAngularVelocity());
     98        const btScalar deltaVel2Dotn    =       -c.m_contactNormal.dot(body2.internalGetDeltaLinearVelocity()) + c.m_relpos2CrossNormal.dot(body2.internalGetDeltaAngularVelocity());
     99
     100//      const btScalar delta_rel_vel    =       deltaVel1Dotn-deltaVel2Dotn;
    99101        deltaImpulse    -=      deltaVel1Dotn*c.m_jacDiagABInv;
    100102        deltaImpulse    -=      deltaVel2Dotn*c.m_jacDiagABInv;
     
    115117                c.m_appliedImpulse = sum;
    116118        }
    117         if (body1.m_invMass)
    118                 body1.applyImpulse(c.m_contactNormal*body1.m_invMass,c.m_angularComponentA,deltaImpulse);
    119         if (body2.m_invMass)
    120                 body2.applyImpulse(-c.m_contactNormal*body2.m_invMass,c.m_angularComponentB,deltaImpulse);
    121 }
    122 
    123  void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimitSIMD(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& c)
     119                body1.internalApplyImpulse(c.m_contactNormal*body1.internalGetInvMass(),c.m_angularComponentA,deltaImpulse);
     120                body2.internalApplyImpulse(-c.m_contactNormal*body2.internalGetInvMass(),c.m_angularComponentB,deltaImpulse);
     121}
     122
     123 void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimitSIMD(btRigidBody& body1,btRigidBody& body2,const btSolverConstraint& c)
    124124{
    125125#ifdef USE_SIMD
     
    128128        __m128  upperLimit1 = _mm_set1_ps(c.m_upperLimit);
    129129        __m128 deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhs), _mm_mul_ps(_mm_set1_ps(c.m_appliedImpulse),_mm_set1_ps(c.m_cfm)));
    130         __m128 deltaVel1Dotn    =       _mm_add_ps(_vmathVfDot3(c.m_contactNormal.mVec128,body1.m_deltaLinearVelocity.mVec128), _vmathVfDot3(c.m_relpos1CrossNormal.mVec128,body1.m_deltaAngularVelocity.mVec128));
    131         __m128 deltaVel2Dotn    =       _mm_sub_ps(_vmathVfDot3(c.m_relpos2CrossNormal.mVec128,body2.m_deltaAngularVelocity.mVec128),_vmathVfDot3((c.m_contactNormal).mVec128,body2.m_deltaLinearVelocity.mVec128));
     130        __m128 deltaVel1Dotn    =       _mm_add_ps(_vmathVfDot3(c.m_contactNormal.mVec128,body1.internalGetDeltaLinearVelocity().mVec128), _vmathVfDot3(c.m_relpos1CrossNormal.mVec128,body1.internalGetDeltaAngularVelocity().mVec128));
     131        __m128 deltaVel2Dotn    =       _mm_sub_ps(_vmathVfDot3(c.m_relpos2CrossNormal.mVec128,body2.internalGetDeltaAngularVelocity().mVec128),_vmathVfDot3((c.m_contactNormal).mVec128,body2.internalGetDeltaLinearVelocity().mVec128));
    132132        deltaImpulse    =       _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel1Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
    133133        deltaImpulse    =       _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel2Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
     
    139139        deltaImpulse = _mm_or_ps( _mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse) );
    140140        c.m_appliedImpulse = _mm_or_ps( _mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum) );
    141         __m128  linearComponentA = _mm_mul_ps(c.m_contactNormal.mVec128,_mm_set1_ps(body1.m_invMass));
    142         __m128  linearComponentB = _mm_mul_ps((c.m_contactNormal).mVec128,_mm_set1_ps(body2.m_invMass));
     141        __m128  linearComponentA = _mm_mul_ps(c.m_contactNormal.mVec128,body1.internalGetInvMass().mVec128);
     142        __m128  linearComponentB = _mm_mul_ps((c.m_contactNormal).mVec128,body2.internalGetInvMass().mVec128);
    143143        __m128 impulseMagnitude = deltaImpulse;
    144         body1.m_deltaLinearVelocity.mVec128 = _mm_add_ps(body1.m_deltaLinearVelocity.mVec128,_mm_mul_ps(linearComponentA,impulseMagnitude));
    145         body1.m_deltaAngularVelocity.mVec128 = _mm_add_ps(body1.m_deltaAngularVelocity.mVec128 ,_mm_mul_ps(c.m_angularComponentA.mVec128,impulseMagnitude));
    146         body2.m_deltaLinearVelocity.mVec128 = _mm_sub_ps(body2.m_deltaLinearVelocity.mVec128,_mm_mul_ps(linearComponentB,impulseMagnitude));
    147         body2.m_deltaAngularVelocity.mVec128 = _mm_add_ps(body2.m_deltaAngularVelocity.mVec128 ,_mm_mul_ps(c.m_angularComponentB.mVec128,impulseMagnitude));
     144        body1.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(body1.internalGetDeltaLinearVelocity().mVec128,_mm_mul_ps(linearComponentA,impulseMagnitude));
     145        body1.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(body1.internalGetDeltaAngularVelocity().mVec128 ,_mm_mul_ps(c.m_angularComponentA.mVec128,impulseMagnitude));
     146        body2.internalGetDeltaLinearVelocity().mVec128 = _mm_sub_ps(body2.internalGetDeltaLinearVelocity().mVec128,_mm_mul_ps(linearComponentB,impulseMagnitude));
     147        body2.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(body2.internalGetDeltaAngularVelocity().mVec128 ,_mm_mul_ps(c.m_angularComponentB.mVec128,impulseMagnitude));
    148148#else
    149149        resolveSingleConstraintRowLowerLimit(body1,body2,c);
     
    152152
    153153// Project Gauss Seidel or the equivalent Sequential Impulse
    154  void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimit(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& c)
     154 void btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimit(btRigidBody& body1,btRigidBody& body2,const btSolverConstraint& c)
    155155{
    156156        btScalar deltaImpulse = c.m_rhs-btScalar(c.m_appliedImpulse)*c.m_cfm;
    157         const btScalar deltaVel1Dotn    =       c.m_contactNormal.dot(body1.m_deltaLinearVelocity)      + c.m_relpos1CrossNormal.dot(body1.m_deltaAngularVelocity);
    158         const btScalar deltaVel2Dotn    =       -c.m_contactNormal.dot(body2.m_deltaLinearVelocity) + c.m_relpos2CrossNormal.dot(body2.m_deltaAngularVelocity);
     157        const btScalar deltaVel1Dotn    =       c.m_contactNormal.dot(body1.internalGetDeltaLinearVelocity())   + c.m_relpos1CrossNormal.dot(body1.internalGetDeltaAngularVelocity());
     158        const btScalar deltaVel2Dotn    =       -c.m_contactNormal.dot(body2.internalGetDeltaLinearVelocity()) + c.m_relpos2CrossNormal.dot(body2.internalGetDeltaAngularVelocity());
    159159
    160160        deltaImpulse    -=      deltaVel1Dotn*c.m_jacDiagABInv;
     
    170170                c.m_appliedImpulse = sum;
    171171        }
    172         if (body1.m_invMass)
    173                 body1.applyImpulse(c.m_contactNormal*body1.m_invMass,c.m_angularComponentA,deltaImpulse);
    174         if (body2.m_invMass)
    175                 body2.applyImpulse(-c.m_contactNormal*body2.m_invMass,c.m_angularComponentB,deltaImpulse);
     172        body1.internalApplyImpulse(c.m_contactNormal*body1.internalGetInvMass(),c.m_angularComponentA,deltaImpulse);
     173        body2.internalApplyImpulse(-c.m_contactNormal*body2.internalGetInvMass(),c.m_angularComponentB,deltaImpulse);
     174}
     175
     176
     177void    btSequentialImpulseConstraintSolver::resolveSplitPenetrationImpulseCacheFriendly(
     178        btRigidBody& body1,
     179        btRigidBody& body2,
     180        const btSolverConstraint& c)
     181{
     182                if (c.m_rhsPenetration)
     183        {
     184                        gNumSplitImpulseRecoveries++;
     185                        btScalar deltaImpulse = c.m_rhsPenetration-btScalar(c.m_appliedPushImpulse)*c.m_cfm;
     186                        const btScalar deltaVel1Dotn    =       c.m_contactNormal.dot(body1.internalGetPushVelocity())  + c.m_relpos1CrossNormal.dot(body1.internalGetTurnVelocity());
     187                        const btScalar deltaVel2Dotn    =       -c.m_contactNormal.dot(body2.internalGetPushVelocity()) + c.m_relpos2CrossNormal.dot(body2.internalGetTurnVelocity());
     188
     189                        deltaImpulse    -=      deltaVel1Dotn*c.m_jacDiagABInv;
     190                        deltaImpulse    -=      deltaVel2Dotn*c.m_jacDiagABInv;
     191                        const btScalar sum = btScalar(c.m_appliedPushImpulse) + deltaImpulse;
     192                        if (sum < c.m_lowerLimit)
     193                        {
     194                                deltaImpulse = c.m_lowerLimit-c.m_appliedPushImpulse;
     195                                c.m_appliedPushImpulse = c.m_lowerLimit;
     196                        }
     197                        else
     198                        {
     199                                c.m_appliedPushImpulse = sum;
     200                        }
     201                        body1.internalApplyPushImpulse(c.m_contactNormal*body1.internalGetInvMass(),c.m_angularComponentA,deltaImpulse);
     202                        body2.internalApplyPushImpulse(-c.m_contactNormal*body2.internalGetInvMass(),c.m_angularComponentB,deltaImpulse);
     203        }
     204}
     205
     206 void btSequentialImpulseConstraintSolver::resolveSplitPenetrationSIMD(btRigidBody& body1,btRigidBody& body2,const btSolverConstraint& c)
     207{
     208#ifdef USE_SIMD
     209        if (!c.m_rhsPenetration)
     210                return;
     211
     212        gNumSplitImpulseRecoveries++;
     213
     214        __m128 cpAppliedImp = _mm_set1_ps(c.m_appliedPushImpulse);
     215        __m128  lowerLimit1 = _mm_set1_ps(c.m_lowerLimit);
     216        __m128  upperLimit1 = _mm_set1_ps(c.m_upperLimit);
     217        __m128 deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhsPenetration), _mm_mul_ps(_mm_set1_ps(c.m_appliedPushImpulse),_mm_set1_ps(c.m_cfm)));
     218        __m128 deltaVel1Dotn    =       _mm_add_ps(_vmathVfDot3(c.m_contactNormal.mVec128,body1.internalGetPushVelocity().mVec128), _vmathVfDot3(c.m_relpos1CrossNormal.mVec128,body1.internalGetTurnVelocity().mVec128));
     219        __m128 deltaVel2Dotn    =       _mm_sub_ps(_vmathVfDot3(c.m_relpos2CrossNormal.mVec128,body2.internalGetTurnVelocity().mVec128),_vmathVfDot3((c.m_contactNormal).mVec128,body2.internalGetPushVelocity().mVec128));
     220        deltaImpulse    =       _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel1Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
     221        deltaImpulse    =       _mm_sub_ps(deltaImpulse,_mm_mul_ps(deltaVel2Dotn,_mm_set1_ps(c.m_jacDiagABInv)));
     222        btSimdScalar sum = _mm_add_ps(cpAppliedImp,deltaImpulse);
     223        btSimdScalar resultLowerLess,resultUpperLess;
     224        resultLowerLess = _mm_cmplt_ps(sum,lowerLimit1);
     225        resultUpperLess = _mm_cmplt_ps(sum,upperLimit1);
     226        __m128 lowMinApplied = _mm_sub_ps(lowerLimit1,cpAppliedImp);
     227        deltaImpulse = _mm_or_ps( _mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse) );
     228        c.m_appliedImpulse = _mm_or_ps( _mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum) );
     229        __m128  linearComponentA = _mm_mul_ps(c.m_contactNormal.mVec128,body1.internalGetInvMass().mVec128);
     230        __m128  linearComponentB = _mm_mul_ps((c.m_contactNormal).mVec128,body2.internalGetInvMass().mVec128);
     231        __m128 impulseMagnitude = deltaImpulse;
     232        body1.internalGetPushVelocity().mVec128 = _mm_add_ps(body1.internalGetPushVelocity().mVec128,_mm_mul_ps(linearComponentA,impulseMagnitude));
     233        body1.internalGetTurnVelocity().mVec128 = _mm_add_ps(body1.internalGetTurnVelocity().mVec128 ,_mm_mul_ps(c.m_angularComponentA.mVec128,impulseMagnitude));
     234        body2.internalGetPushVelocity().mVec128 = _mm_sub_ps(body2.internalGetPushVelocity().mVec128,_mm_mul_ps(linearComponentB,impulseMagnitude));
     235        body2.internalGetTurnVelocity().mVec128 = _mm_add_ps(body2.internalGetTurnVelocity().mVec128 ,_mm_mul_ps(c.m_angularComponentB.mVec128,impulseMagnitude));
     236#else
     237        resolveSplitPenetrationImpulseCacheFriendly(body1,body2,c);
     238#endif
    176239}
    177240
     
    215278
    216279
    217 
     280#if 0
    218281void    btSequentialImpulseConstraintSolver::initSolverBody(btSolverBody* solverBody, btCollisionObject* collisionObject)
    219282{
    220283        btRigidBody* rb = collisionObject? btRigidBody::upcast(collisionObject) : 0;
    221284
    222         solverBody->m_deltaLinearVelocity.setValue(0.f,0.f,0.f);
    223         solverBody->m_deltaAngularVelocity.setValue(0.f,0.f,0.f);
     285        solverBody->internalGetDeltaLinearVelocity().setValue(0.f,0.f,0.f);
     286        solverBody->internalGetDeltaAngularVelocity().setValue(0.f,0.f,0.f);
     287        solverBody->internalGetPushVelocity().setValue(0.f,0.f,0.f);
     288        solverBody->internalGetTurnVelocity().setValue(0.f,0.f,0.f);
    224289
    225290        if (rb)
    226291        {
    227                 solverBody->m_invMass = rb->getInvMass();
     292                solverBody->internalGetInvMass() = btVector3(rb->getInvMass(),rb->getInvMass(),rb->getInvMass())*rb->getLinearFactor();
    228293                solverBody->m_originalBody = rb;
    229294                solverBody->m_angularFactor = rb->getAngularFactor();
    230295        } else
    231296        {
    232                 solverBody->m_invMass = 0.f;
     297                solverBody->internalGetInvMass().setValue(0,0,0);
    233298                solverBody->m_originalBody = 0;
    234                 solverBody->m_angularFactor = 1.f;
    235         }
    236 }
    237 
    238 
    239 int             gNumSplitImpulseRecoveries = 0;
     299                solverBody->m_angularFactor.setValue(1,1,1);
     300        }
     301}
     302#endif
     303
     304
     305
     306
    240307
    241308btScalar btSequentialImpulseConstraintSolver::restitutionCurve(btScalar rel_vel, btScalar restitution)
     
    263330
    264331
    265 
    266 btSolverConstraint&     btSequentialImpulseConstraintSolver::addFrictionConstraint(const btVector3& normalAxis,int solverBodyIdA,int solverBodyIdB,int frictionIndex,btManifoldPoint& cp,const btVector3& rel_pos1,const btVector3& rel_pos2,btCollisionObject* colObj0,btCollisionObject* colObj1, btScalar relaxation)
     332void btSequentialImpulseConstraintSolver::setupFrictionConstraint(btSolverConstraint& solverConstraint, const btVector3& normalAxis,btRigidBody* solverBodyA,btRigidBody* solverBodyB,btManifoldPoint& cp,const btVector3& rel_pos1,const btVector3& rel_pos2,btCollisionObject* colObj0,btCollisionObject* colObj1, btScalar relaxation, btScalar desiredVelocity, btScalar cfmSlip)
    267333{
    268334
     
    271337        btRigidBody* body1=btRigidBody::upcast(colObj1);
    272338
    273         btSolverConstraint& solverConstraint = m_tmpSolverContactFrictionConstraintPool.expand();
    274         memset(&solverConstraint,0xff,sizeof(btSolverConstraint));
    275339        solverConstraint.m_contactNormal = normalAxis;
    276340
    277         solverConstraint.m_solverBodyIdA = solverBodyIdA;
    278         solverConstraint.m_solverBodyIdB = solverBodyIdB;
    279         solverConstraint.m_frictionIndex = frictionIndex;
     341        solverConstraint.m_solverBodyA = body0 ? body0 : &getFixedBody();
     342        solverConstraint.m_solverBodyB = body1 ? body1 : &getFixedBody();
    280343
    281344        solverConstraint.m_friction = cp.m_combinedFriction;
     
    283346
    284347        solverConstraint.m_appliedImpulse = 0.f;
    285         //      solverConstraint.m_appliedPushImpulse = 0.f;
     348        solverConstraint.m_appliedPushImpulse = 0.f;
    286349
    287350        {
     
    338401                rel_vel = vel1Dotn+vel2Dotn;
    339402
    340                 btScalar positionalError = 0.f;
    341 
    342                 btSimdScalar velocityError =  - rel_vel;
     403//              btScalar positionalError = 0.f;
     404
     405                btSimdScalar velocityError =  desiredVelocity - rel_vel;
    343406                btSimdScalar    velocityImpulse = velocityError * btSimdScalar(solverConstraint.m_jacDiagABInv);
    344407                solverConstraint.m_rhs = velocityImpulse;
    345                 solverConstraint.m_cfm = 0.f;
     408                solverConstraint.m_cfm = cfmSlip;
    346409                solverConstraint.m_lowerLimit = 0;
    347410                solverConstraint.m_upperLimit = 1e10f;
    348411        }
    349 
     412}
     413
     414
     415
     416btSolverConstraint&     btSequentialImpulseConstraintSolver::addFrictionConstraint(const btVector3& normalAxis,btRigidBody* solverBodyA,btRigidBody* solverBodyB,int frictionIndex,btManifoldPoint& cp,const btVector3& rel_pos1,const btVector3& rel_pos2,btCollisionObject* colObj0,btCollisionObject* colObj1, btScalar relaxation, btScalar desiredVelocity, btScalar cfmSlip)
     417{
     418        btSolverConstraint& solverConstraint = m_tmpSolverContactFrictionConstraintPool.expandNonInitializing();
     419        solverConstraint.m_frictionIndex = frictionIndex;
     420        setupFrictionConstraint(solverConstraint, normalAxis, solverBodyA, solverBodyB, cp, rel_pos1, rel_pos2,
     421                                                        colObj0, colObj1, relaxation, desiredVelocity, cfmSlip);
    350422        return solverConstraint;
    351423}
     
    353425int     btSequentialImpulseConstraintSolver::getOrInitSolverBody(btCollisionObject& body)
    354426{
     427#if 0
    355428        int solverBodyIdA = -1;
    356429
     
    374447        }
    375448        return solverBodyIdA;
     449#endif
     450        return 0;
    376451}
    377452#include <stdio.h>
    378453
    379454
    380 
    381 void    btSequentialImpulseConstraintSolver::convertContact(btPersistentManifold* manifold,const btContactSolverInfo& infoGlobal)
    382 {
    383         btCollisionObject* colObj0=0,*colObj1=0;
    384 
    385         colObj0 = (btCollisionObject*)manifold->getBody0();
    386         colObj1 = (btCollisionObject*)manifold->getBody1();
    387 
    388         int solverBodyIdA=-1;
    389         int solverBodyIdB=-1;
    390 
    391         if (manifold->getNumContacts())
    392         {
    393                 solverBodyIdA = getOrInitSolverBody(*colObj0);
    394                 solverBodyIdB = getOrInitSolverBody(*colObj1);
    395         }
    396 
    397         ///avoid collision response between two static objects
    398         if (!solverBodyIdA && !solverBodyIdB)
    399                 return;
    400 
    401         btVector3 rel_pos1;
    402         btVector3 rel_pos2;
    403         btScalar relaxation;
    404 
    405         for (int j=0;j<manifold->getNumContacts();j++)
    406         {
    407 
    408                 btManifoldPoint& cp = manifold->getContactPoint(j);
    409 
    410                 if (cp.getDistance() <= manifold->getContactProcessingThreshold())
    411                 {
     455void btSequentialImpulseConstraintSolver::setupContactConstraint(btSolverConstraint& solverConstraint,
     456                                                                                                                                 btCollisionObject* colObj0, btCollisionObject* colObj1,
     457                                                                                                                                 btManifoldPoint& cp, const btContactSolverInfo& infoGlobal,
     458                                                                                                                                 btVector3& vel, btScalar& rel_vel, btScalar& relaxation,
     459                                                                                                                                 btVector3& rel_pos1, btVector3& rel_pos2)
     460{
     461                        btRigidBody* rb0 = btRigidBody::upcast(colObj0);
     462                        btRigidBody* rb1 = btRigidBody::upcast(colObj1);
    412463
    413464                        const btVector3& pos1 = cp.getPositionWorldOnA();
    414465                        const btVector3& pos2 = cp.getPositionWorldOnB();
    415466
     467//                      btVector3 rel_pos1 = pos1 - colObj0->getWorldTransform().getOrigin();
     468//                      btVector3 rel_pos2 = pos2 - colObj1->getWorldTransform().getOrigin();
    416469                        rel_pos1 = pos1 - colObj0->getWorldTransform().getOrigin();
    417470                        rel_pos2 = pos2 - colObj1->getWorldTransform().getOrigin();
    418471
    419 
    420472                        relaxation = 1.f;
    421                         btScalar rel_vel;
    422                         btVector3 vel;
    423 
    424                         int frictionIndex = m_tmpSolverContactConstraintPool.size();
    425 
    426                         {
    427                                 btSolverConstraint& solverConstraint = m_tmpSolverContactConstraintPool.expand();
    428                                 btRigidBody* rb0 = btRigidBody::upcast(colObj0);
    429                                 btRigidBody* rb1 = btRigidBody::upcast(colObj1);
    430 
    431                                 solverConstraint.m_solverBodyIdA = solverBodyIdA;
    432                                 solverConstraint.m_solverBodyIdB = solverBodyIdB;
    433 
    434                                 solverConstraint.m_originalContactPoint = &cp;
    435 
    436                                 btVector3 torqueAxis0 = rel_pos1.cross(cp.m_normalWorldOnB);
    437                                 solverConstraint.m_angularComponentA = rb0 ? rb0->getInvInertiaTensorWorld()*torqueAxis0*rb0->getAngularFactor() : btVector3(0,0,0);
    438                                 btVector3 torqueAxis1 = rel_pos2.cross(cp.m_normalWorldOnB);           
    439                                 solverConstraint.m_angularComponentB = rb1 ? rb1->getInvInertiaTensorWorld()*-torqueAxis1*rb1->getAngularFactor() : btVector3(0,0,0);
     473
     474                        btVector3 torqueAxis0 = rel_pos1.cross(cp.m_normalWorldOnB);
     475                        solverConstraint.m_angularComponentA = rb0 ? rb0->getInvInertiaTensorWorld()*torqueAxis0*rb0->getAngularFactor() : btVector3(0,0,0);
     476                        btVector3 torqueAxis1 = rel_pos2.cross(cp.m_normalWorldOnB);           
     477                        solverConstraint.m_angularComponentB = rb1 ? rb1->getInvInertiaTensorWorld()*-torqueAxis1*rb1->getAngularFactor() : btVector3(0,0,0);
     478
    440479                                {
    441480#ifdef COMPUTE_IMPULSE_DENOM
     
    467506
    468507
    469                                 btVector3 vel1 = rb0 ? rb0->getVelocityInLocalPoint(rel_pos1) : btVector3(0,0,0);
    470                                 btVector3 vel2 = rb1 ? rb1->getVelocityInLocalPoint(rel_pos2) : btVector3(0,0,0);
    471 
    472                                 vel  = vel1 - vel2;
    473 
    474                                 rel_vel = cp.m_normalWorldOnB.dot(vel);
     508
     509
     510                        btVector3 vel1 = rb0 ? rb0->getVelocityInLocalPoint(rel_pos1) : btVector3(0,0,0);
     511                        btVector3 vel2 = rb1 ? rb1->getVelocityInLocalPoint(rel_pos2) : btVector3(0,0,0);
     512                        vel  = vel1 - vel2;
     513                        rel_vel = cp.m_normalWorldOnB.dot(vel);
    475514
    476515                                btScalar penetration = cp.getDistance()+infoGlobal.m_linearSlop;
     
    499538                                        solverConstraint.m_appliedImpulse = cp.m_appliedImpulse * infoGlobal.m_warmstartingFactor;
    500539                                        if (rb0)
    501                                                 m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].applyImpulse(solverConstraint.m_contactNormal*rb0->getInvMass(),solverConstraint.m_angularComponentA,solverConstraint.m_appliedImpulse);
     540                                                rb0->internalApplyImpulse(solverConstraint.m_contactNormal*rb0->getInvMass()*rb0->getLinearFactor(),solverConstraint.m_angularComponentA,solverConstraint.m_appliedImpulse);
    502541                                        if (rb1)
    503                                                 m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].applyImpulse(solverConstraint.m_contactNormal*rb1->getInvMass(),-solverConstraint.m_angularComponentB,-solverConstraint.m_appliedImpulse);
     542                                                rb1->internalApplyImpulse(solverConstraint.m_contactNormal*rb1->getInvMass()*rb1->getLinearFactor(),-solverConstraint.m_angularComponentB,-(btScalar)solverConstraint.m_appliedImpulse);
    504543                                } else
    505544                                {
     
    507546                                }
    508547
    509                                 //                                                      solverConstraint.m_appliedPushImpulse = 0.f;
     548                                solverConstraint.m_appliedPushImpulse = 0.f;
    510549
    511550                                {
     
    523562                                        btScalar  penetrationImpulse = positionalError*solverConstraint.m_jacDiagABInv;
    524563                                        btScalar velocityImpulse = velocityError *solverConstraint.m_jacDiagABInv;
    525                                         solverConstraint.m_rhs = penetrationImpulse+velocityImpulse;
     564                                        if (!infoGlobal.m_splitImpulse || (penetration > infoGlobal.m_splitImpulsePenetrationThreshold))
     565                                        {
     566                                                //combine position and velocity into rhs
     567                                                solverConstraint.m_rhs = penetrationImpulse+velocityImpulse;
     568                                                solverConstraint.m_rhsPenetration = 0.f;
     569                                        } else
     570                                        {
     571                                                //split position and velocity into rhs and m_rhsPenetration
     572                                                solverConstraint.m_rhs = velocityImpulse;
     573                                                solverConstraint.m_rhsPenetration = penetrationImpulse;
     574                                        }
    526575                                        solverConstraint.m_cfm = 0.f;
    527576                                        solverConstraint.m_lowerLimit = 0;
     
    530579
    531580
    532                                 /////setup the friction constraints
    533 
    534 
    535 
    536                                 if (1)
    537                                 {
    538                                         solverConstraint.m_frictionIndex = m_tmpSolverContactFrictionConstraintPool.size();
    539                                         if (!(infoGlobal.m_solverMode & SOLVER_ENABLE_FRICTION_DIRECTION_CACHING) || !cp.m_lateralFrictionInitialized)
    540                                         {
    541                                                 cp.m_lateralFrictionDir1 = vel - cp.m_normalWorldOnB * rel_vel;
    542                                                 btScalar lat_rel_vel = cp.m_lateralFrictionDir1.length2();
    543                                                 if (!(infoGlobal.m_solverMode & SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION) && lat_rel_vel > SIMD_EPSILON)
    544                                                 {
    545                                                         cp.m_lateralFrictionDir1 /= btSqrt(lat_rel_vel);
    546                                                         applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir1);
    547                                                         applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir1);
    548                                                         addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
    549                                                         if((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
    550                                                         {
    551                                                                 cp.m_lateralFrictionDir2 = cp.m_lateralFrictionDir1.cross(cp.m_normalWorldOnB);
    552                                                                 cp.m_lateralFrictionDir2.normalize();//??
    553                                                                 applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir2);
    554                                                                 applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir2);
    555                                                                 addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
    556                                                         }
    557                                                         cp.m_lateralFrictionInitialized = true;
    558                                                 } else
    559                                                 {
    560                                                         //re-calculate friction direction every frame, todo: check if this is really needed
    561                                                         btPlaneSpace1(cp.m_normalWorldOnB,cp.m_lateralFrictionDir1,cp.m_lateralFrictionDir2);
    562                                                         applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir1);
    563                                                         applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir1);
    564 
    565                                                         addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
    566                                                         if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
    567                                                         {
    568                                                                 applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir2);
    569                                                                 applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir2);
    570                                                                 addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
    571                                                         }
    572                                                         cp.m_lateralFrictionInitialized = true;
    573                                                 }
    574 
    575                                         } else
    576                                         {
    577                                                 addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
    578                                                 if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
    579                                                         addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
    580                                         }
    581 
     581
     582
     583}
     584
     585
     586
     587void btSequentialImpulseConstraintSolver::setFrictionConstraintImpulse( btSolverConstraint& solverConstraint,
     588                                                                                                                                                btRigidBody* rb0, btRigidBody* rb1,
     589                                                                                                                                 btManifoldPoint& cp, const btContactSolverInfo& infoGlobal)
     590{
    582591                                        if (infoGlobal.m_solverMode & SOLVER_USE_FRICTION_WARMSTARTING)
    583592                                        {
     
    588597                                                                frictionConstraint1.m_appliedImpulse = cp.m_appliedImpulseLateral1 * infoGlobal.m_warmstartingFactor;
    589598                                                                if (rb0)
    590                                                                         m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].applyImpulse(frictionConstraint1.m_contactNormal*rb0->getInvMass(),frictionConstraint1.m_angularComponentA,frictionConstraint1.m_appliedImpulse);
     599                                                                        rb0->internalApplyImpulse(frictionConstraint1.m_contactNormal*rb0->getInvMass()*rb0->getLinearFactor(),frictionConstraint1.m_angularComponentA,frictionConstraint1.m_appliedImpulse);
    591600                                                                if (rb1)
    592                                                                         m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].applyImpulse(frictionConstraint1.m_contactNormal*rb1->getInvMass(),-frictionConstraint1.m_angularComponentB,-frictionConstraint1.m_appliedImpulse);
     601                                                                        rb1->internalApplyImpulse(frictionConstraint1.m_contactNormal*rb1->getInvMass()*rb1->getLinearFactor(),-frictionConstraint1.m_angularComponentB,-(btScalar)frictionConstraint1.m_appliedImpulse);
    593602                                                        } else
    594603                                                        {
     
    604613                                                                frictionConstraint2.m_appliedImpulse = cp.m_appliedImpulseLateral2 * infoGlobal.m_warmstartingFactor;
    605614                                                                if (rb0)
    606                                                                         m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].applyImpulse(frictionConstraint2.m_contactNormal*rb0->getInvMass(),frictionConstraint2.m_angularComponentA,frictionConstraint2.m_appliedImpulse);
     615                                                                        rb0->internalApplyImpulse(frictionConstraint2.m_contactNormal*rb0->getInvMass(),frictionConstraint2.m_angularComponentA,frictionConstraint2.m_appliedImpulse);
    607616                                                                if (rb1)
    608                                                                         m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].applyImpulse(frictionConstraint2.m_contactNormal*rb1->getInvMass(),-frictionConstraint2.m_angularComponentB,-frictionConstraint2.m_appliedImpulse);
     617                                                                        rb1->internalApplyImpulse(frictionConstraint2.m_contactNormal*rb1->getInvMass(),-frictionConstraint2.m_angularComponentB,-(btScalar)frictionConstraint2.m_appliedImpulse);
    609618                                                        } else
    610619                                                        {
     
    622631                                                }
    623632                                        }
     633}
     634
     635
     636
     637
     638void    btSequentialImpulseConstraintSolver::convertContact(btPersistentManifold* manifold,const btContactSolverInfo& infoGlobal)
     639{
     640        btCollisionObject* colObj0=0,*colObj1=0;
     641
     642        colObj0 = (btCollisionObject*)manifold->getBody0();
     643        colObj1 = (btCollisionObject*)manifold->getBody1();
     644
     645
     646        btRigidBody* solverBodyA = btRigidBody::upcast(colObj0);
     647        btRigidBody* solverBodyB = btRigidBody::upcast(colObj1);
     648
     649        ///avoid collision response between two static objects
     650        if ((!solverBodyA || !solverBodyA->getInvMass()) && (!solverBodyB || !solverBodyB->getInvMass()))
     651                return;
     652
     653        for (int j=0;j<manifold->getNumContacts();j++)
     654        {
     655
     656                btManifoldPoint& cp = manifold->getContactPoint(j);
     657
     658                if (cp.getDistance() <= manifold->getContactProcessingThreshold())
     659                {
     660                        btVector3 rel_pos1;
     661                        btVector3 rel_pos2;
     662                        btScalar relaxation;
     663                        btScalar rel_vel;
     664                        btVector3 vel;
     665
     666                        int frictionIndex = m_tmpSolverContactConstraintPool.size();
     667                        btSolverConstraint& solverConstraint = m_tmpSolverContactConstraintPool.expandNonInitializing();
     668                        btRigidBody* rb0 = btRigidBody::upcast(colObj0);
     669                        btRigidBody* rb1 = btRigidBody::upcast(colObj1);
     670                        solverConstraint.m_solverBodyA = rb0? rb0 : &getFixedBody();
     671                        solverConstraint.m_solverBodyB = rb1? rb1 : &getFixedBody();
     672                        solverConstraint.m_originalContactPoint = &cp;
     673
     674                        setupContactConstraint(solverConstraint, colObj0, colObj1, cp, infoGlobal, vel, rel_vel, relaxation, rel_pos1, rel_pos2);
     675
     676//                      const btVector3& pos1 = cp.getPositionWorldOnA();
     677//                      const btVector3& pos2 = cp.getPositionWorldOnB();
     678
     679                        /////setup the friction constraints
     680
     681                        solverConstraint.m_frictionIndex = m_tmpSolverContactFrictionConstraintPool.size();
     682
     683                        if (!(infoGlobal.m_solverMode & SOLVER_ENABLE_FRICTION_DIRECTION_CACHING) || !cp.m_lateralFrictionInitialized)
     684                        {
     685                                cp.m_lateralFrictionDir1 = vel - cp.m_normalWorldOnB * rel_vel;
     686                                btScalar lat_rel_vel = cp.m_lateralFrictionDir1.length2();
     687                                if (!(infoGlobal.m_solverMode & SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION) && lat_rel_vel > SIMD_EPSILON)
     688                                {
     689                                        cp.m_lateralFrictionDir1 /= btSqrt(lat_rel_vel);
     690                                        if((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
     691                                        {
     692                                                cp.m_lateralFrictionDir2 = cp.m_lateralFrictionDir1.cross(cp.m_normalWorldOnB);
     693                                                cp.m_lateralFrictionDir2.normalize();//??
     694                                                applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir2);
     695                                                applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir2);
     696                                                addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyA,solverBodyB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
     697                                        }
     698
     699                                        applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir1);
     700                                        applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir1);
     701                                        addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyA,solverBodyB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
     702                                        cp.m_lateralFrictionInitialized = true;
     703                                } else
     704                                {
     705                                        //re-calculate friction direction every frame, todo: check if this is really needed
     706                                        btPlaneSpace1(cp.m_normalWorldOnB,cp.m_lateralFrictionDir1,cp.m_lateralFrictionDir2);
     707                                        if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
     708                                        {
     709                                                applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir2);
     710                                                applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir2);
     711                                                addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyA,solverBodyB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
     712                                        }
     713
     714                                        applyAnisotropicFriction(colObj0,cp.m_lateralFrictionDir1);
     715                                        applyAnisotropicFriction(colObj1,cp.m_lateralFrictionDir1);
     716                                        addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyA,solverBodyB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation);
     717
     718                                        cp.m_lateralFrictionInitialized = true;
    624719                                }
    625                         }
    626 
    627 
    628                 }
    629         }
    630 }
    631 
    632 
    633 btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCollisionObject** /*bodies */,int /*numBodies */,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc)
     720
     721                        } else
     722                        {
     723                                addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyA,solverBodyB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation,cp.m_contactMotion1, cp.m_contactCFM1);
     724                                if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
     725                                        addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyA,solverBodyB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation, cp.m_contactMotion2, cp.m_contactCFM2);
     726                        }
     727                       
     728                        setFrictionConstraintImpulse( solverConstraint, rb0, rb1, cp, infoGlobal);
     729
     730                }
     731        }
     732}
     733
     734
     735btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc)
    634736{
    635737        BT_PROFILE("solveGroupCacheFriendlySetup");
     
    644746        }
    645747
     748        if (infoGlobal.m_splitImpulse)
     749        {
     750                for (int i = 0; i < numBodies; i++)
     751                {
     752                        btRigidBody* body = btRigidBody::upcast(bodies[i]);
     753                        if (body)
     754                        {       
     755                                body->internalGetDeltaLinearVelocity().setZero();
     756                                body->internalGetDeltaAngularVelocity().setZero();
     757                                body->internalGetPushVelocity().setZero();
     758                                body->internalGetTurnVelocity().setZero();
     759                        }
     760                }
     761        }
     762        else
     763        {
     764                for (int i = 0; i < numBodies; i++)
     765                {
     766                        btRigidBody* body = btRigidBody::upcast(bodies[i]);
     767                        if (body)
     768                        {       
     769                                body->internalGetDeltaLinearVelocity().setZero();
     770                                body->internalGetDeltaAngularVelocity().setZero();
     771                        }
     772                }
     773        }
     774
    646775        if (1)
    647776        {
     
    653782                }
    654783        }
    655 
    656         btSolverBody& fixedBody = m_tmpSolverBodyPool.expand();
    657         initSolverBody(&fixedBody,0);
    658 
    659784        //btRigidBody* rb0=0,*rb1=0;
    660785
     
    665790                        int totalNumRows = 0;
    666791                        int i;
     792                       
     793                        m_tmpConstraintSizesPool.resize(numConstraints);
    667794                        //calculate the total number of contraint rows
    668795                        for (i=0;i<numConstraints;i++)
    669796                        {
    670 
    671                                 btTypedConstraint::btConstraintInfo1 info1;
     797                                btTypedConstraint::btConstraintInfo1& info1 = m_tmpConstraintSizesPool[i];
    672798                                constraints[i]->getInfo1(&info1);
    673799                                totalNumRows += info1.m_numConstraintRows;
     
    675801                        m_tmpSolverNonContactConstraintPool.resize(totalNumRows);
    676802
    677                         btTypedConstraint::btConstraintInfo1 info1;
    678                         info1.m_numConstraintRows = 0;
    679 
    680 
     803                       
    681804                        ///setup the btSolverConstraints
    682805                        int currentRow = 0;
    683806
    684                         for (i=0;i<numConstraints;i++,currentRow+=info1.m_numConstraintRows)
     807                        for (i=0;i<numConstraints;i++)
    685808                        {
    686                                 constraints[i]->getInfo1(&info1);
     809                                const btTypedConstraint::btConstraintInfo1& info1 = m_tmpConstraintSizesPool[i];
     810                               
    687811                                if (info1.m_numConstraintRows)
    688812                                {
     
    697821                                        btRigidBody& rbB = constraint->getRigidBodyB();
    698822
    699                                         int solverBodyIdA = getOrInitSolverBody(rbA);
    700                                         int solverBodyIdB = getOrInitSolverBody(rbB);
    701 
    702                                         btSolverBody* bodyAPtr = &m_tmpSolverBodyPool[solverBodyIdA];
    703                                         btSolverBody* bodyBPtr = &m_tmpSolverBodyPool[solverBodyIdB];
    704 
     823                                       
    705824                                        int j;
    706825                                        for ( j=0;j<info1.m_numConstraintRows;j++)
     
    711830                                                currentConstraintRow[j].m_appliedImpulse = 0.f;
    712831                                                currentConstraintRow[j].m_appliedPushImpulse = 0.f;
    713                                                 currentConstraintRow[j].m_solverBodyIdA = solverBodyIdA;
    714                                                 currentConstraintRow[j].m_solverBodyIdB = solverBodyIdB;
     832                                                currentConstraintRow[j].m_solverBodyA = &rbA;
     833                                                currentConstraintRow[j].m_solverBodyB = &rbB;
    715834                                        }
    716835
    717                                         bodyAPtr->m_deltaLinearVelocity.setValue(0.f,0.f,0.f);
    718                                         bodyAPtr->m_deltaAngularVelocity.setValue(0.f,0.f,0.f);
    719                                         bodyBPtr->m_deltaLinearVelocity.setValue(0.f,0.f,0.f);
    720                                         bodyBPtr->m_deltaAngularVelocity.setValue(0.f,0.f,0.f);
     836                                        rbA.internalGetDeltaLinearVelocity().setValue(0.f,0.f,0.f);
     837                                        rbA.internalGetDeltaAngularVelocity().setValue(0.f,0.f,0.f);
     838                                        rbB.internalGetDeltaLinearVelocity().setValue(0.f,0.f,0.f);
     839                                        rbB.internalGetDeltaAngularVelocity().setValue(0.f,0.f,0.f);
    721840
    722841
     
    733852                                        btAssert(info2.rowskip*sizeof(btScalar)== sizeof(btSolverConstraint));
    734853                                        info2.m_constraintError = &currentConstraintRow->m_rhs;
     854                                        currentConstraintRow->m_cfm = infoGlobal.m_globalCfm;
     855                                        info2.m_damping = infoGlobal.m_damping;
    735856                                        info2.cfm = &currentConstraintRow->m_cfm;
    736857                                        info2.m_lowerLimit = &currentConstraintRow->m_lowerLimit;
    737858                                        info2.m_upperLimit = &currentConstraintRow->m_upperLimit;
     859                                        info2.m_numIterations = infoGlobal.m_numIterations;
    738860                                        constraints[i]->getInfo2(&info2);
    739861
     
    742864                                        {
    743865                                                btSolverConstraint& solverConstraint = currentConstraintRow[j];
     866                                                solverConstraint.m_originalContactPoint = constraint;
    744867
    745868                                                {
     
    778901                                                        btScalar restitution = 0.f;
    779902                                                        btScalar positionalError = solverConstraint.m_rhs;//already filled in by getConstraintInfo2
    780                                                         btScalar        velocityError = restitution - rel_vel;// * damping;
     903                                                        btScalar        velocityError = restitution - rel_vel * info2.m_damping;
    781904                                                        btScalar        penetrationImpulse = positionalError*solverConstraint.m_jacDiagABInv;
    782905                                                        btScalar        velocityImpulse = velocityError *solverConstraint.m_jacDiagABInv;
     
    787910                                        }
    788911                                }
     912                                currentRow+=m_tmpConstraintSizesPool[i].m_numConstraintRows;
    789913                        }
    790914                }
     
    793917                        int i;
    794918                        btPersistentManifold* manifold = 0;
    795                         btCollisionObject* colObj0=0,*colObj1=0;
     919//                      btCollisionObject* colObj0=0,*colObj1=0;
    796920
    797921
     
    830954}
    831955
    832 btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlyIterations(btCollisionObject** /*bodies */,int /*numBodies*/,btPersistentManifold** /*manifoldPtr*/, int /*numManifolds*/,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* /*debugDrawer*/,btStackAlloc* /*stackAlloc*/)
    833 {
    834         BT_PROFILE("solveGroupCacheFriendlyIterations");
     956btScalar btSequentialImpulseConstraintSolver::solveSingleIteration(int iteration, btCollisionObject** /*bodies */,int /*numBodies*/,btPersistentManifold** /*manifoldPtr*/, int /*numManifolds*/,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* /*debugDrawer*/,btStackAlloc* /*stackAlloc*/)
     957{
    835958
    836959        int numConstraintPool = m_tmpSolverContactConstraintPool.size();
    837960        int numFrictionPool = m_tmpSolverContactFrictionConstraintPool.size();
    838961
     962        int j;
     963
     964        if (infoGlobal.m_solverMode & SOLVER_RANDMIZE_ORDER)
     965        {
     966                if ((iteration & 7) == 0) {
     967                        for (j=0; j<numConstraintPool; ++j) {
     968                                int tmp = m_orderTmpConstraintPool[j];
     969                                int swapi = btRandInt2(j+1);
     970                                m_orderTmpConstraintPool[j] = m_orderTmpConstraintPool[swapi];
     971                                m_orderTmpConstraintPool[swapi] = tmp;
     972                        }
     973
     974                        for (j=0; j<numFrictionPool; ++j) {
     975                                int tmp = m_orderFrictionConstraintPool[j];
     976                                int swapi = btRandInt2(j+1);
     977                                m_orderFrictionConstraintPool[j] = m_orderFrictionConstraintPool[swapi];
     978                                m_orderFrictionConstraintPool[swapi] = tmp;
     979                        }
     980                }
     981        }
     982
     983        if (infoGlobal.m_solverMode & SOLVER_SIMD)
     984        {
     985                ///solve all joint constraints, using SIMD, if available
     986                for (j=0;j<m_tmpSolverNonContactConstraintPool.size();j++)
     987                {
     988                        btSolverConstraint& constraint = m_tmpSolverNonContactConstraintPool[j];
     989                        resolveSingleConstraintRowGenericSIMD(*constraint.m_solverBodyA,*constraint.m_solverBodyB,constraint);
     990                }
     991
     992                for (j=0;j<numConstraints;j++)
     993                {
     994                        constraints[j]->solveConstraintObsolete(constraints[j]->getRigidBodyA(),constraints[j]->getRigidBodyB(),infoGlobal.m_timeStep);
     995                }
     996
     997                ///solve all contact constraints using SIMD, if available
     998                int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
     999                for (j=0;j<numPoolConstraints;j++)
     1000                {
     1001                        const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
     1002                        resolveSingleConstraintRowLowerLimitSIMD(*solveManifold.m_solverBodyA,*solveManifold.m_solverBodyB,solveManifold);
     1003
     1004                }
     1005                ///solve all friction constraints, using SIMD, if available
     1006                int numFrictionPoolConstraints = m_tmpSolverContactFrictionConstraintPool.size();
     1007                for (j=0;j<numFrictionPoolConstraints;j++)
     1008                {
     1009                        btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[j]];
     1010                        btScalar totalImpulse = m_tmpSolverContactConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
     1011
     1012                        if (totalImpulse>btScalar(0))
     1013                        {
     1014                                solveManifold.m_lowerLimit = -(solveManifold.m_friction*totalImpulse);
     1015                                solveManifold.m_upperLimit = solveManifold.m_friction*totalImpulse;
     1016
     1017                                resolveSingleConstraintRowGenericSIMD(*solveManifold.m_solverBodyA,     *solveManifold.m_solverBodyB,solveManifold);
     1018                        }
     1019                }
     1020        } else
     1021        {
     1022
     1023                ///solve all joint constraints
     1024                for (j=0;j<m_tmpSolverNonContactConstraintPool.size();j++)
     1025                {
     1026                        btSolverConstraint& constraint = m_tmpSolverNonContactConstraintPool[j];
     1027                        resolveSingleConstraintRowGeneric(*constraint.m_solverBodyA,*constraint.m_solverBodyB,constraint);
     1028                }
     1029
     1030                for (j=0;j<numConstraints;j++)
     1031                {
     1032                        constraints[j]->solveConstraintObsolete(constraints[j]->getRigidBodyA(),constraints[j]->getRigidBodyB(),infoGlobal.m_timeStep);
     1033                }
     1034                ///solve all contact constraints
     1035                int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
     1036                for (j=0;j<numPoolConstraints;j++)
     1037                {
     1038                        const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
     1039                        resolveSingleConstraintRowLowerLimit(*solveManifold.m_solverBodyA,*solveManifold.m_solverBodyB,solveManifold);
     1040                }
     1041                ///solve all friction constraints
     1042                int numFrictionPoolConstraints = m_tmpSolverContactFrictionConstraintPool.size();
     1043                for (j=0;j<numFrictionPoolConstraints;j++)
     1044                {
     1045                        btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[j]];
     1046                        btScalar totalImpulse = m_tmpSolverContactConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
     1047
     1048                        if (totalImpulse>btScalar(0))
     1049                        {
     1050                                solveManifold.m_lowerLimit = -(solveManifold.m_friction*totalImpulse);
     1051                                solveManifold.m_upperLimit = solveManifold.m_friction*totalImpulse;
     1052
     1053                                resolveSingleConstraintRowGeneric(*solveManifold.m_solverBodyA,*solveManifold.m_solverBodyB,solveManifold);
     1054                        }
     1055                }
     1056        }
     1057        return 0.f;
     1058}
     1059
     1060
     1061void btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySplitImpulseIterations(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc)
     1062{
     1063        int iteration;
     1064        if (infoGlobal.m_splitImpulse)
     1065        {
     1066                if (infoGlobal.m_solverMode & SOLVER_SIMD)
     1067                {
     1068                        for ( iteration = 0;iteration<infoGlobal.m_numIterations;iteration++)
     1069                        {
     1070                                {
     1071                                        int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
     1072                                        int j;
     1073                                        for (j=0;j<numPoolConstraints;j++)
     1074                                        {
     1075                                                const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
     1076
     1077                                                resolveSplitPenetrationSIMD(*solveManifold.m_solverBodyA,*solveManifold.m_solverBodyB,solveManifold);
     1078                                        }
     1079                                }
     1080                        }
     1081                }
     1082                else
     1083                {
     1084                        for ( iteration = 0;iteration<infoGlobal.m_numIterations;iteration++)
     1085                        {
     1086                                {
     1087                                        int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
     1088                                        int j;
     1089                                        for (j=0;j<numPoolConstraints;j++)
     1090                                        {
     1091                                                const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
     1092
     1093                                                resolveSplitPenetrationImpulseCacheFriendly(*solveManifold.m_solverBodyA,*solveManifold.m_solverBodyB,solveManifold);
     1094                                        }
     1095                                }
     1096                        }
     1097                }
     1098        }
     1099}
     1100
     1101btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlyIterations(btCollisionObject** bodies ,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc)
     1102{
     1103        BT_PROFILE("solveGroupCacheFriendlyIterations");
     1104
     1105       
    8391106        //should traverse the contacts random order...
    8401107        int iteration;
     
    8421109                for ( iteration = 0;iteration<infoGlobal.m_numIterations;iteration++)
    8431110                {                       
    844 
    845                         int j;
    846                         if (infoGlobal.m_solverMode & SOLVER_RANDMIZE_ORDER)
    847                         {
    848                                 if ((iteration & 7) == 0) {
    849                                         for (j=0; j<numConstraintPool; ++j) {
    850                                                 int tmp = m_orderTmpConstraintPool[j];
    851                                                 int swapi = btRandInt2(j+1);
    852                                                 m_orderTmpConstraintPool[j] = m_orderTmpConstraintPool[swapi];
    853                                                 m_orderTmpConstraintPool[swapi] = tmp;
    854                                         }
    855 
    856                                         for (j=0; j<numFrictionPool; ++j) {
    857                                                 int tmp = m_orderFrictionConstraintPool[j];
    858                                                 int swapi = btRandInt2(j+1);
    859                                                 m_orderFrictionConstraintPool[j] = m_orderFrictionConstraintPool[swapi];
    860                                                 m_orderFrictionConstraintPool[swapi] = tmp;
    861                                         }
    862                                 }
    863                         }
    864 
    865                         if (infoGlobal.m_solverMode & SOLVER_SIMD)
    866                         {
    867                                 ///solve all joint constraints, using SIMD, if available
    868                                 for (j=0;j<m_tmpSolverNonContactConstraintPool.size();j++)
    869                                 {
    870                                         btSolverConstraint& constraint = m_tmpSolverNonContactConstraintPool[j];
    871                                         resolveSingleConstraintRowGenericSIMD(m_tmpSolverBodyPool[constraint.m_solverBodyIdA],m_tmpSolverBodyPool[constraint.m_solverBodyIdB],constraint);
    872                                 }
    873 
    874                                 for (j=0;j<numConstraints;j++)
    875                                 {
    876                                         int bodyAid = getOrInitSolverBody(constraints[j]->getRigidBodyA());
    877                                         int bodyBid = getOrInitSolverBody(constraints[j]->getRigidBodyB());
    878                                         btSolverBody& bodyA = m_tmpSolverBodyPool[bodyAid];
    879                                         btSolverBody& bodyB = m_tmpSolverBodyPool[bodyBid];
    880                                         constraints[j]->solveConstraintObsolete(bodyA,bodyB,infoGlobal.m_timeStep);
    881                                 }
    882 
    883                                 ///solve all contact constraints using SIMD, if available
    884                                 int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
    885                                 for (j=0;j<numPoolConstraints;j++)
    886                                 {
    887                                         const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
    888                                         resolveSingleConstraintRowLowerLimitSIMD(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA],m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB],solveManifold);
    889 
    890                                 }
    891                                 ///solve all friction constraints, using SIMD, if available
    892                                 int numFrictionPoolConstraints = m_tmpSolverContactFrictionConstraintPool.size();
    893                                 for (j=0;j<numFrictionPoolConstraints;j++)
    894                                 {
    895                                         btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[j]];
    896                                         btScalar totalImpulse = m_tmpSolverContactConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
    897 
    898                                         if (totalImpulse>btScalar(0))
    899                                         {
    900                                                 solveManifold.m_lowerLimit = -(solveManifold.m_friction*totalImpulse);
    901                                                 solveManifold.m_upperLimit = solveManifold.m_friction*totalImpulse;
    902 
    903                                                 resolveSingleConstraintRowGenericSIMD(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA],       m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB],solveManifold);
    904                                         }
    905                                 }
    906                         } else
    907                         {
    908 
    909                                 ///solve all joint constraints
    910                                 for (j=0;j<m_tmpSolverNonContactConstraintPool.size();j++)
    911                                 {
    912                                         btSolverConstraint& constraint = m_tmpSolverNonContactConstraintPool[j];
    913                                         resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[constraint.m_solverBodyIdA],m_tmpSolverBodyPool[constraint.m_solverBodyIdB],constraint);
    914                                 }
    915 
    916                                 for (j=0;j<numConstraints;j++)
    917                                 {
    918                                         int bodyAid = getOrInitSolverBody(constraints[j]->getRigidBodyA());
    919                                         int bodyBid = getOrInitSolverBody(constraints[j]->getRigidBodyB());
    920                                         btSolverBody& bodyA = m_tmpSolverBodyPool[bodyAid];
    921                                         btSolverBody& bodyB = m_tmpSolverBodyPool[bodyBid];
    922 
    923                                         constraints[j]->solveConstraintObsolete(bodyA,bodyB,infoGlobal.m_timeStep);
    924                                 }
    925 
    926                                 ///solve all contact constraints
    927                                 int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
    928                                 for (j=0;j<numPoolConstraints;j++)
    929                                 {
    930                                         const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
    931                                         resolveSingleConstraintRowLowerLimit(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA],m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB],solveManifold);
    932                                 }
    933                                 ///solve all friction constraints
    934                                 int numFrictionPoolConstraints = m_tmpSolverContactFrictionConstraintPool.size();
    935                                 for (j=0;j<numFrictionPoolConstraints;j++)
    936                                 {
    937                                         btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[j]];
    938                                         btScalar totalImpulse = m_tmpSolverContactConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
    939 
    940                                         if (totalImpulse>btScalar(0))
    941                                         {
    942                                                 solveManifold.m_lowerLimit = -(solveManifold.m_friction*totalImpulse);
    943                                                 solveManifold.m_upperLimit = solveManifold.m_friction*totalImpulse;
    944 
    945                                                 resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA],                                                   m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB],solveManifold);
    946                                         }
    947                                 }
    948                         }
    949 
    950 
    951 
    952                 }
     1111                        solveSingleIteration(iteration, bodies ,numBodies,manifoldPtr, numManifolds,constraints,numConstraints,infoGlobal,debugDrawer,stackAlloc);
     1112                }
     1113               
     1114                solveGroupCacheFriendlySplitImpulseIterations(bodies ,numBodies,manifoldPtr, numManifolds,constraints,numConstraints,infoGlobal,debugDrawer,stackAlloc);
    9531115        }
    9541116        return 0.f;
    9551117}
    9561118
    957 
    958 
    959 /// btSequentialImpulseConstraintSolver Sequentially applies impulses
    960 btScalar btSequentialImpulseConstraintSolver::solveGroup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc,btDispatcher* /*dispatcher*/)
    961 {
    962 
    963        
    964 
    965         BT_PROFILE("solveGroup");
    966         //we only implement SOLVER_CACHE_FRIENDLY now
    967         //you need to provide at least some bodies
    968         btAssert(bodies);
    969         btAssert(numBodies);
    970 
    971         int i;
    972 
    973         solveGroupCacheFriendlySetup( bodies, numBodies, manifoldPtr,  numManifolds,constraints, numConstraints,infoGlobal,debugDrawer, stackAlloc);
    974         solveGroupCacheFriendlyIterations(bodies, numBodies, manifoldPtr,  numManifolds,constraints, numConstraints,infoGlobal,debugDrawer, stackAlloc);
    975 
     1119btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlyFinish(btCollisionObject** bodies ,int numBodies,btPersistentManifold** /*manifoldPtr*/, int /*numManifolds*/,btTypedConstraint** /*constraints*/,int /* numConstraints*/,const btContactSolverInfo& infoGlobal,btIDebugDraw* /*debugDrawer*/,btStackAlloc* /*stackAlloc*/)
     1120{
    9761121        int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
    977         int j;
     1122        int i,j;
    9781123
    9791124        for (j=0;j<numPoolConstraints;j++)
     
    9931138        }
    9941139
     1140        numPoolConstraints = m_tmpSolverNonContactConstraintPool.size();
     1141        for (j=0;j<numPoolConstraints;j++)
     1142        {
     1143                const btSolverConstraint& solverConstr = m_tmpSolverNonContactConstraintPool[j];
     1144                btTypedConstraint* constr = (btTypedConstraint*)solverConstr.m_originalContactPoint;
     1145                btScalar sum = constr->internalGetAppliedImpulse();
     1146                sum += solverConstr.m_appliedImpulse;
     1147                constr->internalSetAppliedImpulse(sum);
     1148        }
     1149
     1150
    9951151        if (infoGlobal.m_splitImpulse)
    9961152        {               
    997                 for ( i=0;i<m_tmpSolverBodyPool.size();i++)
    998                 {
    999                         m_tmpSolverBodyPool[i].writebackVelocity(infoGlobal.m_timeStep);
     1153                for ( i=0;i<numBodies;i++)
     1154                {
     1155                        btRigidBody* body = btRigidBody::upcast(bodies[i]);
     1156                        if (body)
     1157                                body->internalWritebackVelocity(infoGlobal.m_timeStep);
    10001158                }
    10011159        } else
    10021160        {
    1003                 for ( i=0;i<m_tmpSolverBodyPool.size();i++)
    1004                 {
    1005                         m_tmpSolverBodyPool[i].writebackVelocity();
    1006                 }
    1007         }
    1008 
    1009 
    1010         m_tmpSolverBodyPool.resize(0);
     1161                for ( i=0;i<numBodies;i++)
     1162                {
     1163                        btRigidBody* body = btRigidBody::upcast(bodies[i]);
     1164                        if (body)
     1165                                body->internalWritebackVelocity();
     1166                }
     1167        }
     1168
     1169
    10111170        m_tmpSolverContactConstraintPool.resize(0);
    10121171        m_tmpSolverNonContactConstraintPool.resize(0);
     
    10181177
    10191178
    1020 
    1021 
    1022 
    1023 
    1024 
     1179/// btSequentialImpulseConstraintSolver Sequentially applies impulses
     1180btScalar btSequentialImpulseConstraintSolver::solveGroup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc,btDispatcher* /*dispatcher*/)
     1181{
     1182
     1183        BT_PROFILE("solveGroup");
     1184        //you need to provide at least some bodies
     1185        btAssert(bodies);
     1186        btAssert(numBodies);
     1187
     1188        solveGroupCacheFriendlySetup( bodies, numBodies, manifoldPtr,  numManifolds,constraints, numConstraints,infoGlobal,debugDrawer, stackAlloc);
     1189
     1190        solveGroupCacheFriendlyIterations(bodies, numBodies, manifoldPtr,  numManifolds,constraints, numConstraints,infoGlobal,debugDrawer, stackAlloc);
     1191
     1192        solveGroupCacheFriendlyFinish(bodies, numBodies, manifoldPtr,  numManifolds,constraints, numConstraints,infoGlobal,debugDrawer, stackAlloc);
     1193       
     1194        return 0.f;
     1195}
    10251196
    10261197void    btSequentialImpulseConstraintSolver::reset()
     
    10291200}
    10301201
    1031 
     1202btRigidBody& btSequentialImpulseConstraintSolver::getFixedBody()
     1203{
     1204        static btRigidBody s_fixed(0, 0,0);
     1205        s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.)));
     1206        return s_fixed;
     1207}
     1208
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h

    r5781 r8284  
    2222#include "btSolverBody.h"
    2323#include "btSolverConstraint.h"
    24 
    25 
     24#include "btTypedConstraint.h"
     25#include "BulletCollision/NarrowPhaseCollision/btManifoldPoint.h"
    2626
    2727///The btSequentialImpulseConstraintSolver is a fast SIMD implementation of the Projected Gauss Seidel (iterative LCP) method.
     
    3030protected:
    3131
    32         btAlignedObjectArray<btSolverBody>      m_tmpSolverBodyPool;
    3332        btConstraintArray                       m_tmpSolverContactConstraintPool;
    3433        btConstraintArray                       m_tmpSolverNonContactConstraintPool;
     
    3635        btAlignedObjectArray<int>       m_orderTmpConstraintPool;
    3736        btAlignedObjectArray<int>       m_orderFrictionConstraintPool;
     37        btAlignedObjectArray<btTypedConstraint::btConstraintInfo1> m_tmpConstraintSizesPool;
    3838
    39         btSolverConstraint&     addFrictionConstraint(const btVector3& normalAxis,int solverBodyIdA,int solverBodyIdB,int frictionIndex,btManifoldPoint& cp,const btVector3& rel_pos1,const btVector3& rel_pos2,btCollisionObject* colObj0,btCollisionObject* colObj1, btScalar relaxation);
     39        void setupFrictionConstraint(   btSolverConstraint& solverConstraint, const btVector3& normalAxis,btRigidBody* solverBodyA,btRigidBody* solverBodyIdB,
     40                                                                        btManifoldPoint& cp,const btVector3& rel_pos1,const btVector3& rel_pos2,
     41                                                                        btCollisionObject* colObj0,btCollisionObject* colObj1, btScalar relaxation,
     42                                                                        btScalar desiredVelocity=0., btScalar cfmSlip=0.);
     43
     44        btSolverConstraint&     addFrictionConstraint(const btVector3& normalAxis,btRigidBody* solverBodyA,btRigidBody* solverBodyB,int frictionIndex,btManifoldPoint& cp,const btVector3& rel_pos1,const btVector3& rel_pos2,btCollisionObject* colObj0,btCollisionObject* colObj1, btScalar relaxation, btScalar desiredVelocity=0., btScalar cfmSlip=0.);
    4045       
     46        void setupContactConstraint(btSolverConstraint& solverConstraint, btCollisionObject* colObj0, btCollisionObject* colObj1, btManifoldPoint& cp,
     47                                                                const btContactSolverInfo& infoGlobal, btVector3& vel, btScalar& rel_vel, btScalar& relaxation,
     48                                                                btVector3& rel_pos1, btVector3& rel_pos2);
     49
     50        void setFrictionConstraintImpulse( btSolverConstraint& solverConstraint, btRigidBody* rb0, btRigidBody* rb1,
     51                                                                                 btManifoldPoint& cp, const btContactSolverInfo& infoGlobal);
     52
    4153        ///m_btSeed2 is used for re-arranging the constraint rows. improves convergence/quality of friction
    4254        unsigned long   m_btSeed2;
    4355
    44         void    initSolverBody(btSolverBody* solverBody, btCollisionObject* collisionObject);
     56//      void    initSolverBody(btSolverBody* solverBody, btCollisionObject* collisionObject);
    4557        btScalar restitutionCurve(btScalar rel_vel, btScalar restitution);
    4658
    4759        void    convertContact(btPersistentManifold* manifold,const btContactSolverInfo& infoGlobal);
    4860
     61
     62        void    resolveSplitPenetrationSIMD(
     63        btRigidBody& body1,
     64        btRigidBody& body2,
     65        const btSolverConstraint& contactConstraint);
     66
    4967        void    resolveSplitPenetrationImpulseCacheFriendly(
    50         btSolverBody& body1,
    51         btSolverBody& body2,
    52         const btSolverConstraint& contactConstraint,
    53         const btContactSolverInfo& solverInfo);
     68        btRigidBody& body1,
     69        btRigidBody& body2,
     70        const btSolverConstraint& contactConstraint);
    5471
    5572        //internal method
    5673        int     getOrInitSolverBody(btCollisionObject& body);
    5774
    58         void    resolveSingleConstraintRowGeneric(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& contactConstraint);
     75        void    resolveSingleConstraintRowGeneric(btRigidBody& body1,btRigidBody& body2,const btSolverConstraint& contactConstraint);
    5976
    60         void    resolveSingleConstraintRowGenericSIMD(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& contactConstraint);
     77        void    resolveSingleConstraintRowGenericSIMD(btRigidBody& body1,btRigidBody& body2,const btSolverConstraint& contactConstraint);
    6178       
    62         void    resolveSingleConstraintRowLowerLimit(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& contactConstraint);
     79        void    resolveSingleConstraintRowLowerLimit(btRigidBody& body1,btRigidBody& body2,const btSolverConstraint& contactConstraint);
    6380       
    64         void    resolveSingleConstraintRowLowerLimitSIMD(btSolverBody& body1,btSolverBody& body2,const btSolverConstraint& contactConstraint);
     81        void    resolveSingleConstraintRowLowerLimitSIMD(btRigidBody& body1,btRigidBody& body2,const btSolverConstraint& contactConstraint);
    6582               
     83protected:
     84        static btRigidBody& getFixedBody();
     85       
     86        virtual void solveGroupCacheFriendlySplitImpulseIterations(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc);
     87        virtual btScalar solveGroupCacheFriendlyFinish(btCollisionObject** bodies ,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc);
     88        btScalar solveSingleIteration(int iteration, btCollisionObject** bodies ,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc);
     89
     90        virtual btScalar solveGroupCacheFriendlySetup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc);
     91        virtual btScalar solveGroupCacheFriendlyIterations(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc);
     92
     93
    6694public:
    6795
     
    72100        virtual btScalar solveGroup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifold,int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& info, btIDebugDraw* debugDrawer, btStackAlloc* stackAlloc,btDispatcher* dispatcher);
    73101       
    74         btScalar solveGroupCacheFriendlySetup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc);
    75         btScalar solveGroupCacheFriendlyIterations(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc);
    76102
     103       
    77104        ///clear internal cached data and reset random seed
    78105        virtual void    reset();
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp

    r5781 r8284  
    1919*/
    2020
    21 //-----------------------------------------------------------------------------
     21
    2222
    2323#include "btSliderConstraint.h"
     
    2626#include <new>
    2727
    28 //-----------------------------------------------------------------------------
     28#define USE_OFFSET_FOR_CONSTANT_FRAME true
    2929
    3030void btSliderConstraint::initParams()
     
    3737        m_restitutionDirLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
    3838        m_dampingDirLin = btScalar(0.);
     39        m_cfmDirLin = SLIDER_CONSTRAINT_DEF_CFM;
    3940        m_softnessDirAng = SLIDER_CONSTRAINT_DEF_SOFTNESS;
    4041        m_restitutionDirAng = SLIDER_CONSTRAINT_DEF_RESTITUTION;
    4142        m_dampingDirAng = btScalar(0.);
     43        m_cfmDirAng = SLIDER_CONSTRAINT_DEF_CFM;
    4244        m_softnessOrthoLin = SLIDER_CONSTRAINT_DEF_SOFTNESS;
    4345        m_restitutionOrthoLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
    4446        m_dampingOrthoLin = SLIDER_CONSTRAINT_DEF_DAMPING;
     47        m_cfmOrthoLin = SLIDER_CONSTRAINT_DEF_CFM;
    4548        m_softnessOrthoAng = SLIDER_CONSTRAINT_DEF_SOFTNESS;
    4649        m_restitutionOrthoAng = SLIDER_CONSTRAINT_DEF_RESTITUTION;
    4750        m_dampingOrthoAng = SLIDER_CONSTRAINT_DEF_DAMPING;
     51        m_cfmOrthoAng = SLIDER_CONSTRAINT_DEF_CFM;
    4852        m_softnessLimLin = SLIDER_CONSTRAINT_DEF_SOFTNESS;
    4953        m_restitutionLimLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
    5054        m_dampingLimLin = SLIDER_CONSTRAINT_DEF_DAMPING;
     55        m_cfmLimLin = SLIDER_CONSTRAINT_DEF_CFM;
    5156        m_softnessLimAng = SLIDER_CONSTRAINT_DEF_SOFTNESS;
    5257        m_restitutionLimAng = SLIDER_CONSTRAINT_DEF_RESTITUTION;
    5358        m_dampingLimAng = SLIDER_CONSTRAINT_DEF_DAMPING;
     59        m_cfmLimAng = SLIDER_CONSTRAINT_DEF_CFM;
    5460
    5561        m_poweredLinMotor = false;
     
    6369        m_accumulatedAngMotorImpulse = btScalar(0.0);
    6470
    65 } // btSliderConstraint::initParams()
    66 
    67 //-----------------------------------------------------------------------------
    68 
    69 btSliderConstraint::btSliderConstraint()
    70         :btTypedConstraint(SLIDER_CONSTRAINT_TYPE),
    71                 m_useLinearReferenceFrameA(true),
    72                 m_useSolveConstraintObsolete(false)
    73 //              m_useSolveConstraintObsolete(true)
     71        m_flags = 0;
     72        m_flags = 0;
     73
     74        m_useOffsetForConstraintFrame = USE_OFFSET_FOR_CONSTANT_FRAME;
     75
     76        calculateTransforms(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
     77}
     78
     79
     80
     81
     82
     83btSliderConstraint::btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB, bool useLinearReferenceFrameA)
     84        : btTypedConstraint(SLIDER_CONSTRAINT_TYPE, rbA, rbB),
     85                m_useSolveConstraintObsolete(false),
     86                m_frameInA(frameInA),
     87        m_frameInB(frameInB),
     88                m_useLinearReferenceFrameA(useLinearReferenceFrameA)
    7489{
    7590        initParams();
    76 } // btSliderConstraint::btSliderConstraint()
    77 
    78 //-----------------------------------------------------------------------------
    79 
    80 btSliderConstraint::btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB, bool useLinearReferenceFrameA)
    81         : btTypedConstraint(SLIDER_CONSTRAINT_TYPE, rbA, rbB)
    82         , m_frameInA(frameInA)
    83         , m_frameInB(frameInB),
    84                 m_useLinearReferenceFrameA(useLinearReferenceFrameA),
    85                 m_useSolveConstraintObsolete(false)
    86 //              m_useSolveConstraintObsolete(true)
    87 {
     91}
     92
     93
     94
     95btSliderConstraint::btSliderConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameA)
     96        : btTypedConstraint(SLIDER_CONSTRAINT_TYPE, getFixedBody(), rbB),
     97                m_useSolveConstraintObsolete(false),
     98                m_frameInB(frameInB),
     99                m_useLinearReferenceFrameA(useLinearReferenceFrameA)
     100{
     101        ///not providing rigidbody A means implicitly using worldspace for body A
     102        m_frameInA = rbB.getCenterOfMassTransform() * m_frameInB;
     103//      m_frameInA.getOrigin() = m_rbA.getCenterOfMassTransform()(m_frameInA.getOrigin());
     104
    88105        initParams();
    89 } // btSliderConstraint::btSliderConstraint()
    90 
    91 //-----------------------------------------------------------------------------
    92 
    93 void btSliderConstraint::buildJacobian()
    94 {
    95         if (!m_useSolveConstraintObsolete)
    96         {
    97                 return;
    98         }
    99         if(m_useLinearReferenceFrameA)
    100         {
    101                 buildJacobianInt(m_rbA, m_rbB, m_frameInA, m_frameInB);
     106}
     107
     108
     109
     110
     111
     112
     113void btSliderConstraint::getInfo1(btConstraintInfo1* info)
     114{
     115        if (m_useSolveConstraintObsolete)
     116        {
     117                info->m_numConstraintRows = 0;
     118                info->nub = 0;
    102119        }
    103120        else
    104121        {
    105                 buildJacobianInt(m_rbB, m_rbA, m_frameInB, m_frameInA);
    106         }
    107 } // btSliderConstraint::buildJacobian()
    108 
    109 //-----------------------------------------------------------------------------
    110 
    111 void btSliderConstraint::buildJacobianInt(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB)
    112 {
    113         //calculate transforms
    114     m_calculatedTransformA = rbA.getCenterOfMassTransform() * frameInA;
    115     m_calculatedTransformB = rbB.getCenterOfMassTransform() * frameInB;
     122                info->m_numConstraintRows = 4; // Fixed 2 linear + 2 angular
     123                info->nub = 2;
     124                //prepare constraint
     125                calculateTransforms(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform());
     126                testAngLimits();
     127                testLinLimits();
     128                if(getSolveLinLimit() || getPoweredLinMotor())
     129                {
     130                        info->m_numConstraintRows++; // limit 3rd linear as well
     131                        info->nub--;
     132                }
     133                if(getSolveAngLimit() || getPoweredAngMotor())
     134                {
     135                        info->m_numConstraintRows++; // limit 3rd angular as well
     136                        info->nub--;
     137                }
     138        }
     139}
     140
     141void btSliderConstraint::getInfo1NonVirtual(btConstraintInfo1* info)
     142{
     143
     144        info->m_numConstraintRows = 6; // Fixed 2 linear + 2 angular + 1 limit (even if not used)
     145        info->nub = 0;
     146}
     147
     148void btSliderConstraint::getInfo2(btConstraintInfo2* info)
     149{
     150        getInfo2NonVirtual(info,m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform(), m_rbA.getLinearVelocity(),m_rbB.getLinearVelocity(), m_rbA.getInvMass(),m_rbB.getInvMass());
     151}
     152
     153
     154
     155
     156
     157
     158
     159void btSliderConstraint::calculateTransforms(const btTransform& transA,const btTransform& transB)
     160{
     161        if(m_useLinearReferenceFrameA || (!m_useSolveConstraintObsolete))
     162        {
     163                m_calculatedTransformA = transA * m_frameInA;
     164                m_calculatedTransformB = transB * m_frameInB;
     165        }
     166        else
     167        {
     168                m_calculatedTransformA = transB * m_frameInB;
     169                m_calculatedTransformB = transA * m_frameInA;
     170        }
    116171        m_realPivotAInW = m_calculatedTransformA.getOrigin();
    117172        m_realPivotBInW = m_calculatedTransformB.getOrigin();
    118173        m_sliderAxis = m_calculatedTransformA.getBasis().getColumn(0); // along X
    119         m_delta = m_realPivotBInW - m_realPivotAInW;
     174        if(m_useLinearReferenceFrameA || m_useSolveConstraintObsolete)
     175        {
     176                m_delta = m_realPivotBInW - m_realPivotAInW;
     177        }
     178        else
     179        {
     180                m_delta = m_realPivotAInW - m_realPivotBInW;
     181        }
    120182        m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis;
    121         m_relPosA = m_projPivotInW - rbA.getCenterOfMassPosition();
    122         m_relPosB = m_realPivotBInW - rbB.getCenterOfMassPosition();
    123183    btVector3 normalWorld;
    124184    int i;
     
    127187    {
    128188                normalWorld = m_calculatedTransformA.getBasis().getColumn(i);
    129                 new (&m_jacLin[i]) btJacobianEntry(
    130                         rbA.getCenterOfMassTransform().getBasis().transpose(),
    131                         rbB.getCenterOfMassTransform().getBasis().transpose(),
    132                         m_relPosA,
    133                         m_relPosB,
    134                         normalWorld,
    135                         rbA.getInvInertiaDiagLocal(),
    136                         rbA.getInvMass(),
    137                         rbB.getInvInertiaDiagLocal(),
    138                         rbB.getInvMass()
    139                         );
    140                 m_jacLinDiagABInv[i] = btScalar(1.) / m_jacLin[i].getDiagonal();
    141189                m_depth[i] = m_delta.dot(normalWorld);
    142190    }
    143         testLinLimits();
    144     // angular part
    145     for(i = 0; i < 3; i++)
    146     {
    147                 normalWorld = m_calculatedTransformA.getBasis().getColumn(i);
    148                 new (&m_jacAng[i])      btJacobianEntry(
    149                         normalWorld,
    150             rbA.getCenterOfMassTransform().getBasis().transpose(),
    151             rbB.getCenterOfMassTransform().getBasis().transpose(),
    152             rbA.getInvInertiaDiagLocal(),
    153             rbB.getInvInertiaDiagLocal()
    154                         );
    155         }
    156         testAngLimits();
    157         btVector3 axisA = m_calculatedTransformA.getBasis().getColumn(0);
    158         m_kAngle = btScalar(1.0 )/ (rbA.computeAngularImpulseDenominator(axisA) + rbB.computeAngularImpulseDenominator(axisA));
    159         // clear accumulator for motors
    160         m_accumulatedLinMotorImpulse = btScalar(0.0);
    161         m_accumulatedAngMotorImpulse = btScalar(0.0);
    162 } // btSliderConstraint::buildJacobianInt()
    163 
    164 //-----------------------------------------------------------------------------
    165 
    166 void btSliderConstraint::getInfo1(btConstraintInfo1* info)
    167 {
    168         if (m_useSolveConstraintObsolete)
    169         {
    170                 info->m_numConstraintRows = 0;
    171                 info->nub = 0;
     191}
     192 
     193
     194
     195void btSliderConstraint::testLinLimits(void)
     196{
     197        m_solveLinLim = false;
     198        m_linPos = m_depth[0];
     199        if(m_lowerLinLimit <= m_upperLinLimit)
     200        {
     201                if(m_depth[0] > m_upperLinLimit)
     202                {
     203                        m_depth[0] -= m_upperLinLimit;
     204                        m_solveLinLim = true;
     205                }
     206                else if(m_depth[0] < m_lowerLinLimit)
     207                {
     208                        m_depth[0] -= m_lowerLinLimit;
     209                        m_solveLinLim = true;
     210                }
     211                else
     212                {
     213                        m_depth[0] = btScalar(0.);
     214                }
    172215        }
    173216        else
    174217        {
    175                 info->m_numConstraintRows = 4; // Fixed 2 linear + 2 angular
    176                 info->nub = 2;
    177                 //prepare constraint
    178                 calculateTransforms();
    179                 testLinLimits();
    180                 if(getSolveLinLimit() || getPoweredLinMotor())
    181                 {
    182                         info->m_numConstraintRows++; // limit 3rd linear as well
    183                         info->nub--;
    184                 }
    185                 testAngLimits();
    186                 if(getSolveAngLimit() || getPoweredAngMotor())
    187                 {
    188                         info->m_numConstraintRows++; // limit 3rd angular as well
    189                         info->nub--;
    190                 }
    191         }
    192 } // btSliderConstraint::getInfo1()
    193 
    194 //-----------------------------------------------------------------------------
    195 
    196 void btSliderConstraint::getInfo2(btConstraintInfo2* info)
    197 {
     218                m_depth[0] = btScalar(0.);
     219        }
     220}
     221
     222
     223
     224void btSliderConstraint::testAngLimits(void)
     225{
     226        m_angDepth = btScalar(0.);
     227        m_solveAngLim = false;
     228        if(m_lowerAngLimit <= m_upperAngLimit)
     229        {
     230                const btVector3 axisA0 = m_calculatedTransformA.getBasis().getColumn(1);
     231                const btVector3 axisA1 = m_calculatedTransformA.getBasis().getColumn(2);
     232                const btVector3 axisB0 = m_calculatedTransformB.getBasis().getColumn(1);
     233//              btScalar rot = btAtan2Fast(axisB0.dot(axisA1), axisB0.dot(axisA0)); 
     234                btScalar rot = btAtan2(axisB0.dot(axisA1), axisB0.dot(axisA0)); 
     235                rot = btAdjustAngleToLimits(rot, m_lowerAngLimit, m_upperAngLimit);
     236                m_angPos = rot;
     237                if(rot < m_lowerAngLimit)
     238                {
     239                        m_angDepth = rot - m_lowerAngLimit;
     240                        m_solveAngLim = true;
     241                }
     242                else if(rot > m_upperAngLimit)
     243                {
     244                        m_angDepth = rot - m_upperAngLimit;
     245                        m_solveAngLim = true;
     246                }
     247        }
     248}
     249
     250btVector3 btSliderConstraint::getAncorInA(void)
     251{
     252        btVector3 ancorInA;
     253        ancorInA = m_realPivotAInW + (m_lowerLinLimit + m_upperLinLimit) * btScalar(0.5) * m_sliderAxis;
     254        ancorInA = m_rbA.getCenterOfMassTransform().inverse() * ancorInA;
     255        return ancorInA;
     256}
     257
     258
     259
     260btVector3 btSliderConstraint::getAncorInB(void)
     261{
     262        btVector3 ancorInB;
     263        ancorInB = m_frameInB.getOrigin();
     264        return ancorInB;
     265}
     266
     267
     268void btSliderConstraint::getInfo2NonVirtual(btConstraintInfo2* info, const btTransform& transA,const btTransform& transB, const btVector3& linVelA,const btVector3& linVelB, btScalar rbAinvMass,btScalar rbBinvMass  )
     269{
     270        const btTransform& trA = getCalculatedTransformA();
     271        const btTransform& trB = getCalculatedTransformB();
     272       
    198273        btAssert(!m_useSolveConstraintObsolete);
    199274        int i, s = info->rowskip;
    200         const btTransform& trA = getCalculatedTransformA();
    201         const btTransform& trB = getCalculatedTransformB();
     275       
    202276        btScalar signFact = m_useLinearReferenceFrameA ? btScalar(1.0f) : btScalar(-1.0f);
    203         // make rotations around Y and Z equal
     277       
     278        // difference between frames in WCS
     279        btVector3 ofs = trB.getOrigin() - trA.getOrigin();
     280        // now get weight factors depending on masses
     281        btScalar miA = rbAinvMass;
     282        btScalar miB = rbBinvMass;
     283        bool hasStaticBody = (miA < SIMD_EPSILON) || (miB < SIMD_EPSILON);
     284        btScalar miS = miA + miB;
     285        btScalar factA, factB;
     286        if(miS > btScalar(0.f))
     287        {
     288                factA = miB / miS;
     289        }
     290        else
     291        {
     292                factA = btScalar(0.5f);
     293        }
     294        factB = btScalar(1.0f) - factA;
     295        btVector3 ax1, p, q;
     296        btVector3 ax1A = trA.getBasis().getColumn(0);
     297        btVector3 ax1B = trB.getBasis().getColumn(0);
     298        if(m_useOffsetForConstraintFrame)
     299        {
     300                // get the desired direction of slider axis
     301                // as weighted sum of X-orthos of frameA and frameB in WCS
     302                ax1 = ax1A * factA + ax1B * factB;
     303                ax1.normalize();
     304                // construct two orthos to slider axis
     305                btPlaneSpace1 (ax1, p, q);
     306        }
     307        else
     308        { // old way - use frameA
     309                ax1 = trA.getBasis().getColumn(0);
     310                // get 2 orthos to slider axis (Y, Z)
     311                p = trA.getBasis().getColumn(1);
     312                q = trA.getBasis().getColumn(2);
     313        }
     314        // make rotations around these orthos equal
    204315        // the slider axis should be the only unconstrained
    205316        // rotational axis, the angular velocity of the two bodies perpendicular to
     
    209320        // where p and q are unit vectors normal to the slider axis, and w1 and w2
    210321        // are the angular velocity vectors of the two bodies.
    211         // get slider axis (X)
    212         btVector3 ax1 = trA.getBasis().getColumn(0);
    213         // get 2 orthos to slider axis (Y, Z)
    214         btVector3 p = trA.getBasis().getColumn(1);
    215         btVector3 q = trA.getBasis().getColumn(2);
    216         // set the two slider rows
    217322        info->m_J1angularAxis[0] = p[0];
    218323        info->m_J1angularAxis[1] = p[1];
     
    230335        // compute the right hand side of the constraint equation. set relative
    231336        // body velocities along p and q to bring the slider back into alignment.
    232         // if ax1,ax2 are the unit length slider axes as computed from body1 and
    233         // body2, we need to rotate both bodies along the axis u = (ax1 x ax2).
     337        // if ax1A,ax1B are the unit length slider axes as computed from bodyA and
     338        // bodyB, we need to rotate both bodies along the axis u = (ax1 x ax2).
    234339        // if "theta" is the angle between ax1 and ax2, we need an angular velocity
    235340        // along u to cover angle erp*theta in one step :
     
    243348        // ax1 x ax2 is in the plane space of ax1, so we project the angular
    244349        // velocity to p and q to find the right hand side.
    245         btScalar k = info->fps * info->erp * getSoftnessOrthoAng();
    246     btVector3 ax2 = trB.getBasis().getColumn(0);
    247         btVector3 u = ax1.cross(ax2);
     350//      btScalar k = info->fps * info->erp * getSoftnessOrthoAng();
     351        btScalar currERP = (m_flags & BT_SLIDER_FLAGS_ERP_ORTANG) ? m_softnessOrthoAng : m_softnessOrthoAng * info->erp;
     352        btScalar k = info->fps * currERP;
     353
     354        btVector3 u = ax1A.cross(ax1B);
    248355        info->m_constraintError[0] = k * u.dot(p);
    249356        info->m_constraintError[s] = k * u.dot(q);
    250         // pull out pos and R for both bodies. also get the connection
    251         // vector c = pos2-pos1.
    252         // next two rows. we want: vel2 = vel1 + w1 x c ... but this would
    253         // result in three equations, so we project along the planespace vectors
    254         // so that sliding along the slider axis is disregarded. for symmetry we
    255         // also consider rotation around center of mass of two bodies (factA and factB).
    256         btTransform bodyA_trans = m_rbA.getCenterOfMassTransform();
    257         btTransform bodyB_trans = m_rbB.getCenterOfMassTransform();
    258         int s2 = 2 * s, s3 = 3 * s;
    259         btVector3 c;
    260         btScalar miA = m_rbA.getInvMass();
    261         btScalar miB = m_rbB.getInvMass();
    262         btScalar miS = miA + miB;
    263         btScalar factA, factB;
    264         if(miS > btScalar(0.f))
    265         {
    266                 factA = miB / miS;
    267         }
    268         else
    269         {
    270                 factA = btScalar(0.5f);
    271         }
    272         if(factA > 0.99f) factA = 0.99f;
    273         if(factA < 0.01f) factA = 0.01f;
    274         factB = btScalar(1.0f) - factA;
    275         c = bodyB_trans.getOrigin() - bodyA_trans.getOrigin();
    276         btVector3 tmp = c.cross(p);
    277         for (i=0; i<3; i++) info->m_J1angularAxis[s2+i] = factA*tmp[i];
    278         for (i=0; i<3; i++) info->m_J2angularAxis[s2+i] = factB*tmp[i];
    279         tmp = c.cross(q);
    280         for (i=0; i<3; i++) info->m_J1angularAxis[s3+i] = factA*tmp[i];
    281         for (i=0; i<3; i++) info->m_J2angularAxis[s3+i] = factB*tmp[i];
    282 
    283         for (i=0; i<3; i++) info->m_J1linearAxis[s2+i] = p[i];
    284         for (i=0; i<3; i++) info->m_J1linearAxis[s3+i] = q[i];
    285         // compute two elements of right hand side. we want to align the offset
    286         // point (in body 2's frame) with the center of body 1.
    287         btVector3 ofs; // offset point in global coordinates
    288         ofs = trB.getOrigin() - trA.getOrigin();
    289         k = info->fps * info->erp * getSoftnessOrthoLin();
    290         info->m_constraintError[s2] = k * p.dot(ofs);
    291         info->m_constraintError[s3] = k * q.dot(ofs);
    292         int nrow = 3; // last filled row
     357        if(m_flags & BT_SLIDER_FLAGS_CFM_ORTANG)
     358        {
     359                info->cfm[0] = m_cfmOrthoAng;
     360                info->cfm[s] = m_cfmOrthoAng;
     361        }
     362
     363        int nrow = 1; // last filled row
    293364        int srow;
    294         // check linear limits linear
    295         btScalar limit_err = btScalar(0.0);
    296         int limit = 0;
     365        btScalar limit_err;
     366        int limit;
     367        int powered;
     368
     369        // next two rows.
     370        // we want: velA + wA x relA == velB + wB x relB ... but this would
     371        // result in three equations, so we project along two orthos to the slider axis
     372
     373        btTransform bodyA_trans = transA;
     374        btTransform bodyB_trans = transB;
     375        nrow++;
     376        int s2 = nrow * s;
     377        nrow++;
     378        int s3 = nrow * s;
     379        btVector3 tmpA(0,0,0), tmpB(0,0,0), relA(0,0,0), relB(0,0,0), c(0,0,0);
     380        if(m_useOffsetForConstraintFrame)
     381        {
     382                // get vector from bodyB to frameB in WCS
     383                relB = trB.getOrigin() - bodyB_trans.getOrigin();
     384                // get its projection to slider axis
     385                btVector3 projB = ax1 * relB.dot(ax1);
     386                // get vector directed from bodyB to slider axis (and orthogonal to it)
     387                btVector3 orthoB = relB - projB;
     388                // same for bodyA
     389                relA = trA.getOrigin() - bodyA_trans.getOrigin();
     390                btVector3 projA = ax1 * relA.dot(ax1);
     391                btVector3 orthoA = relA - projA;
     392                // get desired offset between frames A and B along slider axis
     393                btScalar sliderOffs = m_linPos - m_depth[0];
     394                // desired vector from projection of center of bodyA to projection of center of bodyB to slider axis
     395                btVector3 totalDist = projA + ax1 * sliderOffs - projB;
     396                // get offset vectors relA and relB
     397                relA = orthoA + totalDist * factA;
     398                relB = orthoB - totalDist * factB;
     399                // now choose average ortho to slider axis
     400                p = orthoB * factA + orthoA * factB;
     401                btScalar len2 = p.length2();
     402                if(len2 > SIMD_EPSILON)
     403                {
     404                        p /= btSqrt(len2);
     405                }
     406                else
     407                {
     408                        p = trA.getBasis().getColumn(1);
     409                }
     410                // make one more ortho
     411                q = ax1.cross(p);
     412                // fill two rows
     413                tmpA = relA.cross(p);
     414                tmpB = relB.cross(p);
     415                for (i=0; i<3; i++) info->m_J1angularAxis[s2+i] = tmpA[i];
     416                for (i=0; i<3; i++) info->m_J2angularAxis[s2+i] = -tmpB[i];
     417                tmpA = relA.cross(q);
     418                tmpB = relB.cross(q);
     419                if(hasStaticBody && getSolveAngLimit())
     420                { // to make constraint between static and dynamic objects more rigid
     421                        // remove wA (or wB) from equation if angular limit is hit
     422                        tmpB *= factB;
     423                        tmpA *= factA;
     424                }
     425                for (i=0; i<3; i++) info->m_J1angularAxis[s3+i] = tmpA[i];
     426                for (i=0; i<3; i++) info->m_J2angularAxis[s3+i] = -tmpB[i];
     427                for (i=0; i<3; i++) info->m_J1linearAxis[s2+i] = p[i];
     428                for (i=0; i<3; i++) info->m_J1linearAxis[s3+i] = q[i];
     429        }
     430        else
     431        {       // old way - maybe incorrect if bodies are not on the slider axis
     432                // see discussion "Bug in slider constraint" http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=9&t=4024&start=0
     433                c = bodyB_trans.getOrigin() - bodyA_trans.getOrigin();
     434                btVector3 tmp = c.cross(p);
     435                for (i=0; i<3; i++) info->m_J1angularAxis[s2+i] = factA*tmp[i];
     436                for (i=0; i<3; i++) info->m_J2angularAxis[s2+i] = factB*tmp[i];
     437                tmp = c.cross(q);
     438                for (i=0; i<3; i++) info->m_J1angularAxis[s3+i] = factA*tmp[i];
     439                for (i=0; i<3; i++) info->m_J2angularAxis[s3+i] = factB*tmp[i];
     440
     441                for (i=0; i<3; i++) info->m_J1linearAxis[s2+i] = p[i];
     442                for (i=0; i<3; i++) info->m_J1linearAxis[s3+i] = q[i];
     443        }
     444        // compute two elements of right hand side
     445
     446        //      k = info->fps * info->erp * getSoftnessOrthoLin();
     447        currERP = (m_flags & BT_SLIDER_FLAGS_ERP_ORTLIN) ? m_softnessOrthoLin : m_softnessOrthoLin * info->erp;
     448        k = info->fps * currERP;
     449
     450        btScalar rhs = k * p.dot(ofs);
     451        info->m_constraintError[s2] = rhs;
     452        rhs = k * q.dot(ofs);
     453        info->m_constraintError[s3] = rhs;
     454        if(m_flags & BT_SLIDER_FLAGS_CFM_ORTLIN)
     455        {
     456                info->cfm[s2] = m_cfmOrthoLin;
     457                info->cfm[s3] = m_cfmOrthoLin;
     458        }
     459
     460
     461        // check linear limits
     462        limit_err = btScalar(0.0);
     463        limit = 0;
    297464        if(getSolveLinLimit())
    298465        {
     
    300467                limit = (limit_err > btScalar(0.0)) ? 2 : 1;
    301468        }
    302         int powered = 0;
     469        powered = 0;
    303470        if(getPoweredLinMotor())
    304471        {
     
    320487                // a torque couple will result in limited slider-jointed free
    321488                // bodies from gaining angular momentum.
    322                 // the solution used here is to apply the constraint forces at the center of mass of the two bodies
    323                 btVector3 ltd;  // Linear Torque Decoupling vector (a torque)
    324 //              c = btScalar(0.5) * c;
    325                 ltd = c.cross(ax1);
    326                 info->m_J1angularAxis[srow+0] = factA*ltd[0];
    327                 info->m_J1angularAxis[srow+1] = factA*ltd[1];
    328                 info->m_J1angularAxis[srow+2] = factA*ltd[2];
    329                 info->m_J2angularAxis[srow+0] = factB*ltd[0];
    330                 info->m_J2angularAxis[srow+1] = factB*ltd[1];
    331                 info->m_J2angularAxis[srow+2] = factB*ltd[2];
     489                if(m_useOffsetForConstraintFrame)
     490                {
     491                        // this is needed only when bodyA and bodyB are both dynamic.
     492                        if(!hasStaticBody)
     493                        {
     494                                tmpA = relA.cross(ax1);
     495                                tmpB = relB.cross(ax1);
     496                                info->m_J1angularAxis[srow+0] = tmpA[0];
     497                                info->m_J1angularAxis[srow+1] = tmpA[1];
     498                                info->m_J1angularAxis[srow+2] = tmpA[2];
     499                                info->m_J2angularAxis[srow+0] = -tmpB[0];
     500                                info->m_J2angularAxis[srow+1] = -tmpB[1];
     501                                info->m_J2angularAxis[srow+2] = -tmpB[2];
     502                        }
     503                }
     504                else
     505                { // The old way. May be incorrect if bodies are not on the slider axis
     506                        btVector3 ltd;  // Linear Torque Decoupling vector (a torque)
     507                        ltd = c.cross(ax1);
     508                        info->m_J1angularAxis[srow+0] = factA*ltd[0];
     509                        info->m_J1angularAxis[srow+1] = factA*ltd[1];
     510                        info->m_J1angularAxis[srow+2] = factA*ltd[2];
     511                        info->m_J2angularAxis[srow+0] = factB*ltd[0];
     512                        info->m_J2angularAxis[srow+1] = factB*ltd[1];
     513                        info->m_J2angularAxis[srow+2] = factB*ltd[2];
     514                }
    332515                // right-hand part
    333516                btScalar lostop = getLowerLinLimit();
     
    340523                info->m_lowerLimit[srow] = 0.;
    341524                info->m_upperLimit[srow] = 0.;
     525                currERP = (m_flags & BT_SLIDER_FLAGS_ERP_LIMLIN) ? m_softnessLimLin : info->erp;
    342526                if(powered)
    343527                {
    344             info->cfm[nrow] = btScalar(0.0);
     528                        if(m_flags & BT_SLIDER_FLAGS_CFM_DIRLIN)
     529                        {
     530                                info->cfm[srow] = m_cfmDirLin;
     531                        }
    345532                        btScalar tag_vel = getTargetLinMotorVelocity();
    346                         btScalar mot_fact = getMotorFactor(m_linPos, m_lowerLinLimit, m_upperLinLimit, tag_vel, info->fps * info->erp);
    347 //                      info->m_constraintError[srow] += mot_fact * getTargetLinMotorVelocity();
     533                        btScalar mot_fact = getMotorFactor(m_linPos, m_lowerLinLimit, m_upperLinLimit, tag_vel, info->fps * currERP);
    348534                        info->m_constraintError[srow] -= signFact * mot_fact * getTargetLinMotorVelocity();
    349535                        info->m_lowerLimit[srow] += -getMaxLinMotorForce() * info->fps;
     
    352538                if(limit)
    353539                {
    354                         k = info->fps * info->erp;
     540                        k = info->fps * currERP;
    355541                        info->m_constraintError[srow] += k * limit_err;
    356                         info->cfm[srow] = btScalar(0.0); // stop_cfm;
     542                        if(m_flags & BT_SLIDER_FLAGS_CFM_LIMLIN)
     543                        {
     544                                info->cfm[srow] = m_cfmLimLin;
     545                        }
    357546                        if(lostop == histop)
    358547                        {       // limited low and high simultaneously
     
    374563                        if(bounce > btScalar(0.0))
    375564                        {
    376                                 btScalar vel = m_rbA.getLinearVelocity().dot(ax1);
    377                                 vel -= m_rbB.getLinearVelocity().dot(ax1);
     565                                btScalar vel = linVelA.dot(ax1);
     566                                vel -= linVelB.dot(ax1);
    378567                                vel *= signFact;
    379568                                // only apply bounce if the velocity is incoming, and if the
     
    437626                        powered = 0;
    438627                }
     628                currERP = (m_flags & BT_SLIDER_FLAGS_ERP_LIMANG) ? m_softnessLimAng : info->erp;
    439629                if(powered)
    440630                {
    441             info->cfm[srow] = btScalar(0.0);
    442                         btScalar mot_fact = getMotorFactor(m_angPos, m_lowerAngLimit, m_upperAngLimit, getTargetAngMotorVelocity(), info->fps * info->erp);
     631                        if(m_flags & BT_SLIDER_FLAGS_CFM_DIRANG)
     632                        {
     633                                info->cfm[srow] = m_cfmDirAng;
     634                        }
     635                        btScalar mot_fact = getMotorFactor(m_angPos, m_lowerAngLimit, m_upperAngLimit, getTargetAngMotorVelocity(), info->fps * currERP);
    443636                        info->m_constraintError[srow] = mot_fact * getTargetAngMotorVelocity();
    444637                        info->m_lowerLimit[srow] = -getMaxAngMotorForce() * info->fps;
     
    447640                if(limit)
    448641                {
    449                         k = info->fps * info->erp;
     642                        k = info->fps * currERP;
    450643                        info->m_constraintError[srow] += k * limit_err;
    451                         info->cfm[srow] = btScalar(0.0); // stop_cfm;
     644                        if(m_flags & BT_SLIDER_FLAGS_CFM_LIMANG)
     645                        {
     646                                info->cfm[srow] = m_cfmLimAng;
     647                        }
    452648                        if(lostop == histop)
    453649                        {
     
    500696                } // if(limit)
    501697        } // if angular limit or powered
    502 } // btSliderConstraint::getInfo2()
    503 
    504 //-----------------------------------------------------------------------------
    505 
    506 void btSliderConstraint::solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar timeStep)
    507 {
    508         if (m_useSolveConstraintObsolete)
    509         {
    510                 m_timeStep = timeStep;
    511                 if(m_useLinearReferenceFrameA)
    512                 {
    513                         solveConstraintInt(m_rbA,bodyA, m_rbB,bodyB);
     698}
     699
     700
     701///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     702///If no axis is provided, it uses the default axis for this constraint.
     703void btSliderConstraint::setParam(int num, btScalar value, int axis)
     704{
     705        switch(num)
     706        {
     707        case BT_CONSTRAINT_STOP_ERP :
     708                if(axis < 1)
     709                {
     710                        m_softnessLimLin = value;
     711                        m_flags |= BT_SLIDER_FLAGS_ERP_LIMLIN;
     712                }
     713                else if(axis < 3)
     714                {
     715                        m_softnessOrthoLin = value;
     716                        m_flags |= BT_SLIDER_FLAGS_ERP_ORTLIN;
     717                }
     718                else if(axis == 3)
     719                {
     720                        m_softnessLimAng = value;
     721                        m_flags |= BT_SLIDER_FLAGS_ERP_LIMANG;
     722                }
     723                else if(axis < 6)
     724                {
     725                        m_softnessOrthoAng = value;
     726                        m_flags |= BT_SLIDER_FLAGS_ERP_ORTANG;
    514727                }
    515728                else
    516729                {
    517                         solveConstraintInt(m_rbB,bodyB, m_rbA,bodyA);
    518                 }
    519         }
    520 } // btSliderConstraint::solveConstraint()
    521 
    522 //-----------------------------------------------------------------------------
    523 
    524 void btSliderConstraint::solveConstraintInt(btRigidBody& rbA, btSolverBody& bodyA,btRigidBody& rbB, btSolverBody& bodyB)
    525 {
    526     int i;
    527     // linear
    528     btVector3 velA;
    529         bodyA.getVelocityInLocalPointObsolete(m_relPosA,velA);
    530     btVector3 velB;
    531         bodyB.getVelocityInLocalPointObsolete(m_relPosB,velB);
    532     btVector3 vel = velA - velB;
    533         for(i = 0; i < 3; i++)
    534     {
    535                 const btVector3& normal = m_jacLin[i].m_linearJointAxis;
    536                 btScalar rel_vel = normal.dot(vel);
    537                 // calculate positional error
    538                 btScalar depth = m_depth[i];
    539                 // get parameters
    540                 btScalar softness = (i) ? m_softnessOrthoLin : (m_solveLinLim ? m_softnessLimLin : m_softnessDirLin);
    541                 btScalar restitution = (i) ? m_restitutionOrthoLin : (m_solveLinLim ? m_restitutionLimLin : m_restitutionDirLin);
    542                 btScalar damping = (i) ? m_dampingOrthoLin : (m_solveLinLim ? m_dampingLimLin : m_dampingDirLin);
    543                 // calcutate and apply impulse
    544                 btScalar normalImpulse = softness * (restitution * depth / m_timeStep - damping * rel_vel) * m_jacLinDiagABInv[i];
    545                 btVector3 impulse_vector = normal * normalImpulse;
    546                
    547                 //rbA.applyImpulse( impulse_vector, m_relPosA);
    548                 //rbB.applyImpulse(-impulse_vector, m_relPosB);
    549                 {
    550                         btVector3 ftorqueAxis1 = m_relPosA.cross(normal);
    551                         btVector3 ftorqueAxis2 = m_relPosB.cross(normal);
    552                         bodyA.applyImpulse(normal*rbA.getInvMass(), rbA.getInvInertiaTensorWorld()*ftorqueAxis1,normalImpulse);
    553                         bodyB.applyImpulse(normal*rbB.getInvMass(), rbB.getInvInertiaTensorWorld()*ftorqueAxis2,-normalImpulse);
    554                 }
    555 
    556 
    557 
    558                 if(m_poweredLinMotor && (!i))
    559                 { // apply linear motor
    560                         if(m_accumulatedLinMotorImpulse < m_maxLinMotorForce)
    561                         {
    562                                 btScalar desiredMotorVel = m_targetLinMotorVelocity;
    563                                 btScalar motor_relvel = desiredMotorVel + rel_vel;
    564                                 normalImpulse = -motor_relvel * m_jacLinDiagABInv[i];
    565                                 // clamp accumulated impulse
    566                                 btScalar new_acc = m_accumulatedLinMotorImpulse + btFabs(normalImpulse);
    567                                 if(new_acc  > m_maxLinMotorForce)
    568                                 {
    569                                         new_acc = m_maxLinMotorForce;
    570                                 }
    571                                 btScalar del = new_acc  - m_accumulatedLinMotorImpulse;
    572                                 if(normalImpulse < btScalar(0.0))
    573                                 {
    574                                         normalImpulse = -del;
    575                                 }
    576                                 else
    577                                 {
    578                                         normalImpulse = del;
    579                                 }
    580                                 m_accumulatedLinMotorImpulse = new_acc;
    581                                 // apply clamped impulse
    582                                 impulse_vector = normal * normalImpulse;
    583                                 //rbA.applyImpulse( impulse_vector, m_relPosA);
    584                                 //rbB.applyImpulse(-impulse_vector, m_relPosB);
    585 
    586                                 {
    587                                         btVector3 ftorqueAxis1 = m_relPosA.cross(normal);
    588                                         btVector3 ftorqueAxis2 = m_relPosB.cross(normal);
    589                                         bodyA.applyImpulse(normal*rbA.getInvMass(), rbA.getInvInertiaTensorWorld()*ftorqueAxis1,normalImpulse);
    590                                         bodyB.applyImpulse(normal*rbB.getInvMass(), rbB.getInvInertiaTensorWorld()*ftorqueAxis2,-normalImpulse);
    591                                 }
    592 
    593 
    594 
    595                         }
    596                 }
    597     }
    598         // angular
    599         // get axes in world space
    600         btVector3 axisA =  m_calculatedTransformA.getBasis().getColumn(0);
    601         btVector3 axisB =  m_calculatedTransformB.getBasis().getColumn(0);
    602 
    603         btVector3 angVelA;
    604         bodyA.getAngularVelocity(angVelA);
    605         btVector3 angVelB;
    606         bodyB.getAngularVelocity(angVelB);
    607 
    608         btVector3 angVelAroundAxisA = axisA * axisA.dot(angVelA);
    609         btVector3 angVelAroundAxisB = axisB * axisB.dot(angVelB);
    610 
    611         btVector3 angAorthog = angVelA - angVelAroundAxisA;
    612         btVector3 angBorthog = angVelB - angVelAroundAxisB;
    613         btVector3 velrelOrthog = angAorthog-angBorthog;
    614         //solve orthogonal angular velocity correction
    615         btScalar len = velrelOrthog.length();
    616         btScalar orthorImpulseMag = 0.f;
    617 
    618         if (len > btScalar(0.00001))
    619         {
    620                 btVector3 normal = velrelOrthog.normalized();
    621                 btScalar denom = rbA.computeAngularImpulseDenominator(normal) + rbB.computeAngularImpulseDenominator(normal);
    622                 //velrelOrthog *= (btScalar(1.)/denom) * m_dampingOrthoAng * m_softnessOrthoAng;
    623                 orthorImpulseMag = (btScalar(1.)/denom) * m_dampingOrthoAng * m_softnessOrthoAng;
    624         }
    625         //solve angular positional correction
    626         btVector3 angularError = axisA.cross(axisB) *(btScalar(1.)/m_timeStep);
    627         btVector3 angularAxis = angularError;
    628         btScalar angularImpulseMag = 0;
    629 
    630         btScalar len2 = angularError.length();
    631         if (len2>btScalar(0.00001))
    632         {
    633                 btVector3 normal2 = angularError.normalized();
    634                 btScalar denom2 = rbA.computeAngularImpulseDenominator(normal2) + rbB.computeAngularImpulseDenominator(normal2);
    635                 angularImpulseMag = (btScalar(1.)/denom2) * m_restitutionOrthoAng * m_softnessOrthoAng;
    636                 angularError *= angularImpulseMag;
    637         }
    638         // apply impulse
    639         //rbA.applyTorqueImpulse(-velrelOrthog+angularError);
    640         //rbB.applyTorqueImpulse(velrelOrthog-angularError);
    641 
    642         bodyA.applyImpulse(btVector3(0,0,0), rbA.getInvInertiaTensorWorld()*velrelOrthog,-orthorImpulseMag);
    643         bodyB.applyImpulse(btVector3(0,0,0), rbB.getInvInertiaTensorWorld()*velrelOrthog,orthorImpulseMag);
    644         bodyA.applyImpulse(btVector3(0,0,0), rbA.getInvInertiaTensorWorld()*angularAxis,angularImpulseMag);
    645         bodyB.applyImpulse(btVector3(0,0,0), rbB.getInvInertiaTensorWorld()*angularAxis,-angularImpulseMag);
    646 
    647 
    648         btScalar impulseMag;
    649         //solve angular limits
    650         if(m_solveAngLim)
    651         {
    652                 impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingLimAng + m_angDepth * m_restitutionLimAng / m_timeStep;
    653                 impulseMag *= m_kAngle * m_softnessLimAng;
    654         }
    655         else
    656         {
    657                 impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingDirAng + m_angDepth * m_restitutionDirAng / m_timeStep;
    658                 impulseMag *= m_kAngle * m_softnessDirAng;
    659         }
    660         btVector3 impulse = axisA * impulseMag;
    661         //rbA.applyTorqueImpulse(impulse);
    662         //rbB.applyTorqueImpulse(-impulse);
    663 
    664         bodyA.applyImpulse(btVector3(0,0,0), rbA.getInvInertiaTensorWorld()*axisA,impulseMag);
    665         bodyB.applyImpulse(btVector3(0,0,0), rbB.getInvInertiaTensorWorld()*axisA,-impulseMag);
    666 
    667 
    668 
    669         //apply angular motor
    670         if(m_poweredAngMotor)
    671         {
    672                 if(m_accumulatedAngMotorImpulse < m_maxAngMotorForce)
    673                 {
    674                         btVector3 velrel = angVelAroundAxisA - angVelAroundAxisB;
    675                         btScalar projRelVel = velrel.dot(axisA);
    676 
    677                         btScalar desiredMotorVel = m_targetAngMotorVelocity;
    678                         btScalar motor_relvel = desiredMotorVel - projRelVel;
    679 
    680                         btScalar angImpulse = m_kAngle * motor_relvel;
    681                         // clamp accumulated impulse
    682                         btScalar new_acc = m_accumulatedAngMotorImpulse + btFabs(angImpulse);
    683                         if(new_acc  > m_maxAngMotorForce)
    684                         {
    685                                 new_acc = m_maxAngMotorForce;
    686                         }
    687                         btScalar del = new_acc  - m_accumulatedAngMotorImpulse;
    688                         if(angImpulse < btScalar(0.0))
    689                         {
    690                                 angImpulse = -del;
    691                         }
    692                         else
    693                         {
    694                                 angImpulse = del;
    695                         }
    696                         m_accumulatedAngMotorImpulse = new_acc;
    697                         // apply clamped impulse
    698                         btVector3 motorImp = angImpulse * axisA;
    699                         //rbA.applyTorqueImpulse(motorImp);
    700                         //rbB.applyTorqueImpulse(-motorImp);
    701 
    702                         bodyA.applyImpulse(btVector3(0,0,0), rbA.getInvInertiaTensorWorld()*axisA,angImpulse);
    703                         bodyB.applyImpulse(btVector3(0,0,0), rbB.getInvInertiaTensorWorld()*axisA,-angImpulse);
    704                 }
    705         }
    706 } // btSliderConstraint::solveConstraint()
    707 
    708 //-----------------------------------------------------------------------------
    709 
    710 //-----------------------------------------------------------------------------
    711 
    712 void btSliderConstraint::calculateTransforms(void){
    713         if(m_useLinearReferenceFrameA || (!m_useSolveConstraintObsolete))
    714         {
    715                 m_calculatedTransformA = m_rbA.getCenterOfMassTransform() * m_frameInA;
    716                 m_calculatedTransformB = m_rbB.getCenterOfMassTransform() * m_frameInB;
    717         }
    718         else
    719         {
    720                 m_calculatedTransformA = m_rbB.getCenterOfMassTransform() * m_frameInB;
    721                 m_calculatedTransformB = m_rbA.getCenterOfMassTransform() * m_frameInA;
    722         }
    723         m_realPivotAInW = m_calculatedTransformA.getOrigin();
    724         m_realPivotBInW = m_calculatedTransformB.getOrigin();
    725         m_sliderAxis = m_calculatedTransformA.getBasis().getColumn(0); // along X
    726         if(m_useLinearReferenceFrameA || m_useSolveConstraintObsolete)
    727         {
    728                 m_delta = m_realPivotBInW - m_realPivotAInW;
    729         }
    730         else
    731         {
    732                 m_delta = m_realPivotAInW - m_realPivotBInW;
    733         }
    734         m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis;
    735     btVector3 normalWorld;
    736     int i;
    737     //linear part
    738     for(i = 0; i < 3; i++)
    739     {
    740                 normalWorld = m_calculatedTransformA.getBasis().getColumn(i);
    741                 m_depth[i] = m_delta.dot(normalWorld);
    742     }
    743 } // btSliderConstraint::calculateTransforms()
    744  
    745 //-----------------------------------------------------------------------------
    746 
    747 void btSliderConstraint::testLinLimits(void)
    748 {
    749         m_solveLinLim = false;
    750         m_linPos = m_depth[0];
    751         if(m_lowerLinLimit <= m_upperLinLimit)
    752         {
    753                 if(m_depth[0] > m_upperLinLimit)
    754                 {
    755                         m_depth[0] -= m_upperLinLimit;
    756                         m_solveLinLim = true;
    757                 }
    758                 else if(m_depth[0] < m_lowerLinLimit)
    759                 {
    760                         m_depth[0] -= m_lowerLinLimit;
    761                         m_solveLinLim = true;
     730                        btAssertConstrParams(0);
     731                }
     732                break;
     733        case BT_CONSTRAINT_CFM :
     734                if(axis < 1)
     735                {
     736                        m_cfmDirLin = value;
     737                        m_flags |= BT_SLIDER_FLAGS_CFM_DIRLIN;
     738                }
     739                else if(axis == 3)
     740                {
     741                        m_cfmDirAng = value;
     742                        m_flags |= BT_SLIDER_FLAGS_CFM_DIRANG;
    762743                }
    763744                else
    764745                {
    765                         m_depth[0] = btScalar(0.);
    766                 }
    767         }
    768         else
    769         {
    770                 m_depth[0] = btScalar(0.);
    771         }
    772 } // btSliderConstraint::testLinLimits()
    773 
    774 //-----------------------------------------------------------------------------
    775 
    776 void btSliderConstraint::testAngLimits(void)
    777 {
    778         m_angDepth = btScalar(0.);
    779         m_solveAngLim = false;
    780         if(m_lowerAngLimit <= m_upperAngLimit)
    781         {
    782                 const btVector3 axisA0 = m_calculatedTransformA.getBasis().getColumn(1);
    783                 const btVector3 axisA1 = m_calculatedTransformA.getBasis().getColumn(2);
    784                 const btVector3 axisB0 = m_calculatedTransformB.getBasis().getColumn(1);
    785                 btScalar rot = btAtan2Fast(axisB0.dot(axisA1), axisB0.dot(axisA0)); 
    786                 m_angPos = rot;
    787                 if(rot < m_lowerAngLimit)
    788                 {
    789                         m_angDepth = rot - m_lowerAngLimit;
    790                         m_solveAngLim = true;
    791                 }
    792                 else if(rot > m_upperAngLimit)
    793                 {
    794                         m_angDepth = rot - m_upperAngLimit;
    795                         m_solveAngLim = true;
    796                 }
    797         }
    798 } // btSliderConstraint::testAngLimits()
    799        
    800 //-----------------------------------------------------------------------------
    801 
    802 btVector3 btSliderConstraint::getAncorInA(void)
    803 {
    804         btVector3 ancorInA;
    805         ancorInA = m_realPivotAInW + (m_lowerLinLimit + m_upperLinLimit) * btScalar(0.5) * m_sliderAxis;
    806         ancorInA = m_rbA.getCenterOfMassTransform().inverse() * ancorInA;
    807         return ancorInA;
    808 } // btSliderConstraint::getAncorInA()
    809 
    810 //-----------------------------------------------------------------------------
    811 
    812 btVector3 btSliderConstraint::getAncorInB(void)
    813 {
    814         btVector3 ancorInB;
    815         ancorInB = m_frameInB.getOrigin();
    816         return ancorInB;
    817 } // btSliderConstraint::getAncorInB();
     746                        btAssertConstrParams(0);
     747                }
     748                break;
     749        case BT_CONSTRAINT_STOP_CFM :
     750                if(axis < 1)
     751                {
     752                        m_cfmLimLin = value;
     753                        m_flags |= BT_SLIDER_FLAGS_CFM_LIMLIN;
     754                }
     755                else if(axis < 3)
     756                {
     757                        m_cfmOrthoLin = value;
     758                        m_flags |= BT_SLIDER_FLAGS_CFM_ORTLIN;
     759                }
     760                else if(axis == 3)
     761                {
     762                        m_cfmLimAng = value;
     763                        m_flags |= BT_SLIDER_FLAGS_CFM_LIMANG;
     764                }
     765                else if(axis < 6)
     766                {
     767                        m_cfmOrthoAng = value;
     768                        m_flags |= BT_SLIDER_FLAGS_CFM_ORTANG;
     769                }
     770                else
     771                {
     772                        btAssertConstrParams(0);
     773                }
     774                break;
     775        }
     776}
     777
     778///return the local value of parameter
     779btScalar btSliderConstraint::getParam(int num, int axis) const
     780{
     781        btScalar retVal(SIMD_INFINITY);
     782        switch(num)
     783        {
     784        case BT_CONSTRAINT_STOP_ERP :
     785                if(axis < 1)
     786                {
     787                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_ERP_LIMLIN);
     788                        retVal = m_softnessLimLin;
     789                }
     790                else if(axis < 3)
     791                {
     792                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_ERP_ORTLIN);
     793                        retVal = m_softnessOrthoLin;
     794                }
     795                else if(axis == 3)
     796                {
     797                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_ERP_LIMANG);
     798                        retVal = m_softnessLimAng;
     799                }
     800                else if(axis < 6)
     801                {
     802                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_ERP_ORTANG);
     803                        retVal = m_softnessOrthoAng;
     804                }
     805                else
     806                {
     807                        btAssertConstrParams(0);
     808                }
     809                break;
     810        case BT_CONSTRAINT_CFM :
     811                if(axis < 1)
     812                {
     813                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_DIRLIN);
     814                        retVal = m_cfmDirLin;
     815                }
     816                else if(axis == 3)
     817                {
     818                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_DIRANG);
     819                        retVal = m_cfmDirAng;
     820                }
     821                else
     822                {
     823                        btAssertConstrParams(0);
     824                }
     825                break;
     826        case BT_CONSTRAINT_STOP_CFM :
     827                if(axis < 1)
     828                {
     829                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_LIMLIN);
     830                        retVal = m_cfmLimLin;
     831                }
     832                else if(axis < 3)
     833                {
     834                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_ORTLIN);
     835                        retVal = m_cfmOrthoLin;
     836                }
     837                else if(axis == 3)
     838                {
     839                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_LIMANG);
     840                        retVal = m_cfmLimAng;
     841                }
     842                else if(axis < 6)
     843                {
     844                        btAssertConstrParams(m_flags & BT_SLIDER_FLAGS_CFM_ORTANG);
     845                        retVal = m_cfmOrthoAng;
     846                }
     847                else
     848                {
     849                        btAssertConstrParams(0);
     850                }
     851                break;
     852        }
     853        return retVal;
     854}
     855
     856
     857
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btSliderConstraint.h

    r5781 r8284  
    2626#define SLIDER_CONSTRAINT_H
    2727
    28 //-----------------------------------------------------------------------------
     28
    2929
    3030#include "LinearMath/btVector3.h"
     
    3232#include "btTypedConstraint.h"
    3333
    34 //-----------------------------------------------------------------------------
     34
    3535
    3636class btRigidBody;
    3737
    38 //-----------------------------------------------------------------------------
     38
    3939
    4040#define SLIDER_CONSTRAINT_DEF_SOFTNESS          (btScalar(1.0))
    4141#define SLIDER_CONSTRAINT_DEF_DAMPING           (btScalar(1.0))
    4242#define SLIDER_CONSTRAINT_DEF_RESTITUTION       (btScalar(0.7))
    43 
    44 //-----------------------------------------------------------------------------
     43#define SLIDER_CONSTRAINT_DEF_CFM                       (btScalar(0.f))
     44
     45
     46enum btSliderFlags
     47{
     48        BT_SLIDER_FLAGS_CFM_DIRLIN = (1 << 0),
     49        BT_SLIDER_FLAGS_ERP_DIRLIN = (1 << 1),
     50        BT_SLIDER_FLAGS_CFM_DIRANG = (1 << 2),
     51        BT_SLIDER_FLAGS_ERP_DIRANG = (1 << 3),
     52        BT_SLIDER_FLAGS_CFM_ORTLIN = (1 << 4),
     53        BT_SLIDER_FLAGS_ERP_ORTLIN = (1 << 5),
     54        BT_SLIDER_FLAGS_CFM_ORTANG = (1 << 6),
     55        BT_SLIDER_FLAGS_ERP_ORTANG = (1 << 7),
     56        BT_SLIDER_FLAGS_CFM_LIMLIN = (1 << 8),
     57        BT_SLIDER_FLAGS_ERP_LIMLIN = (1 << 9),
     58        BT_SLIDER_FLAGS_CFM_LIMANG = (1 << 10),
     59        BT_SLIDER_FLAGS_ERP_LIMANG = (1 << 11)
     60};
     61
    4562
    4663class btSliderConstraint : public btTypedConstraint
     
    4966        ///for backwards compatibility during the transition to 'getInfo/getInfo2'
    5067        bool            m_useSolveConstraintObsolete;
     68        bool            m_useOffsetForConstraintFrame;
    5169        btTransform     m_frameInA;
    5270    btTransform m_frameInB;
     
    6886        btScalar m_restitutionDirLin;
    6987        btScalar m_dampingDirLin;
     88        btScalar m_cfmDirLin;
     89
    7090        btScalar m_softnessDirAng;
    7191        btScalar m_restitutionDirAng;
    7292        btScalar m_dampingDirAng;
     93        btScalar m_cfmDirAng;
     94
    7395        btScalar m_softnessLimLin;
    7496        btScalar m_restitutionLimLin;
    7597        btScalar m_dampingLimLin;
     98        btScalar m_cfmLimLin;
     99
    76100        btScalar m_softnessLimAng;
    77101        btScalar m_restitutionLimAng;
    78102        btScalar m_dampingLimAng;
     103        btScalar m_cfmLimAng;
     104
    79105        btScalar m_softnessOrthoLin;
    80106        btScalar m_restitutionOrthoLin;
    81107        btScalar m_dampingOrthoLin;
     108        btScalar m_cfmOrthoLin;
     109
    82110        btScalar m_softnessOrthoAng;
    83111        btScalar m_restitutionOrthoAng;
    84112        btScalar m_dampingOrthoAng;
     113        btScalar m_cfmOrthoAng;
    85114       
    86115        // for interlal use
    87116        bool m_solveLinLim;
    88117        bool m_solveAngLim;
     118
     119        int m_flags;
    89120
    90121        btJacobianEntry m_jacLin[3];
     
    127158        // constructors
    128159    btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA);
    129     btSliderConstraint();
     160    btSliderConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameA);
     161
    130162        // overrides
    131     virtual void        buildJacobian();
     163
    132164    virtual void getInfo1 (btConstraintInfo1* info);
     165
     166        void getInfo1NonVirtual(btConstraintInfo1* info);
    133167       
    134168        virtual void getInfo2 (btConstraintInfo2* info);
    135169
    136     virtual     void    solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar        timeStep);
    137        
     170        void getInfo2NonVirtual(btConstraintInfo2* info, const btTransform& transA, const btTransform& transB,const btVector3& linVelA,const btVector3& linVelB, btScalar rbAinvMass,btScalar rbBinvMass);
     171
    138172
    139173        // access
     
    151185    void setUpperLinLimit(btScalar upperLimit) { m_upperLinLimit = upperLimit; }
    152186    btScalar getLowerAngLimit() { return m_lowerAngLimit; }
    153     void setLowerAngLimit(btScalar lowerLimit) { m_lowerAngLimit = lowerLimit; }
     187    void setLowerAngLimit(btScalar lowerLimit) { m_lowerAngLimit = btNormalizeAngle(lowerLimit); }
    154188    btScalar getUpperAngLimit() { return m_upperAngLimit; }
    155     void setUpperAngLimit(btScalar upperLimit) { m_upperAngLimit = upperLimit; }
     189    void setUpperAngLimit(btScalar upperLimit) { m_upperAngLimit = btNormalizeAngle(upperLimit); }
    156190        bool getUseLinearReferenceFrameA() { return m_useLinearReferenceFrameA; }
    157191        btScalar getSoftnessDirLin() { return m_softnessDirLin; }
     
    211245        bool getSolveAngLimit() { return m_solveAngLim; }
    212246        btScalar getAngDepth() { return m_angDepth; }
    213         // internal
    214     void        buildJacobianInt(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB);
    215     void        solveConstraintInt(btRigidBody& rbA, btSolverBody& bodyA,btRigidBody& rbB, btSolverBody& bodyB);
    216247        // shared code used by ODE solver
    217         void    calculateTransforms(void);
    218         void    testLinLimits(void);
    219         void    testLinLimits2(btConstraintInfo2* info);
    220         void    testAngLimits(void);
     248        void    calculateTransforms(const btTransform& transA,const btTransform& transB);
     249        void    testLinLimits();
     250        void    testAngLimits();
    221251        // access for PE Solver
    222         btVector3 getAncorInA(void);
    223         btVector3 getAncorInB(void);
     252        btVector3 getAncorInA();
     253        btVector3 getAncorInB();
     254        // access for UseFrameOffset
     255        bool getUseFrameOffset() { return m_useOffsetForConstraintFrame; }
     256        void setUseFrameOffset(bool frameOffsetOnOff) { m_useOffsetForConstraintFrame = frameOffsetOnOff; }
     257
     258        ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     259        ///If no axis is provided, it uses the default axis for this constraint.
     260        virtual void    setParam(int num, btScalar value, int axis = -1);
     261        ///return the local value of parameter
     262        virtual btScalar getParam(int num, int axis = -1) const;
     263
     264        virtual int     calculateSerializeBufferSize() const;
     265
     266        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     267        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     268
     269
    224270};
    225271
    226 //-----------------------------------------------------------------------------
     272///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     273struct btSliderConstraintData
     274{
     275        btTypedConstraintData   m_typeConstraintData;
     276        btTransformFloatData m_rbAFrame; // constraint axii. Assumes z is hinge axis.
     277        btTransformFloatData m_rbBFrame;
     278       
     279        float   m_linearUpperLimit;
     280        float   m_linearLowerLimit;
     281
     282        float   m_angularUpperLimit;
     283        float   m_angularLowerLimit;
     284
     285        int     m_useLinearReferenceFrameA;
     286        int m_useOffsetForConstraintFrame;
     287
     288};
     289
     290
     291SIMD_FORCE_INLINE               int     btSliderConstraint::calculateSerializeBufferSize() const
     292{
     293        return sizeof(btSliderConstraintData);
     294}
     295
     296        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     297SIMD_FORCE_INLINE       const char*     btSliderConstraint::serialize(void* dataBuffer, btSerializer* serializer) const
     298{
     299
     300        btSliderConstraintData* sliderData = (btSliderConstraintData*) dataBuffer;
     301        btTypedConstraint::serialize(&sliderData->m_typeConstraintData,serializer);
     302
     303        m_frameInA.serializeFloat(sliderData->m_rbAFrame);
     304        m_frameInB.serializeFloat(sliderData->m_rbBFrame);
     305
     306        sliderData->m_linearUpperLimit = float(m_upperLinLimit);
     307        sliderData->m_linearLowerLimit = float(m_lowerLinLimit);
     308
     309        sliderData->m_angularUpperLimit = float(m_upperAngLimit);
     310        sliderData->m_angularLowerLimit = float(m_lowerAngLimit);
     311
     312        sliderData->m_useLinearReferenceFrameA = m_useLinearReferenceFrameA;
     313        sliderData->m_useOffsetForConstraintFrame = m_useOffsetForConstraintFrame;
     314
     315        return "btSliderConstraintData";
     316}
     317
     318
    227319
    228320#endif //SLIDER_CONSTRAINT_H
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btSolverBody.h

    r5781 r8284  
    106106
    107107///The btSolverBody is an internal datastructure for the constraint solver. Only necessary data is packed to increase cache coherence/performance.
    108 ATTRIBUTE_ALIGNED16 (struct)    btSolverBody
     108ATTRIBUTE_ALIGNED64 (struct)    btSolverBodyObsolete
    109109{
    110110        BT_DECLARE_ALIGNED_ALLOCATOR();
    111111        btVector3               m_deltaLinearVelocity;
    112112        btVector3               m_deltaAngularVelocity;
    113         btScalar                m_angularFactor;
    114         btScalar                m_invMass;
    115         btScalar                m_friction;
     113        btVector3               m_angularFactor;
     114        btVector3               m_invMass;
    116115        btRigidBody*    m_originalBody;
    117116        btVector3               m_pushVelocity;
    118         //btVector3             m_turnVelocity;
     117        btVector3               m_turnVelocity;
    119118
    120119       
     
    146145        }
    147146
    148        
    149 /*
     147        SIMD_FORCE_INLINE void internalApplyPushImpulse(const btVector3& linearComponent, const btVector3& angularComponent,btScalar impulseMagnitude)
     148        {
     149                if (m_originalBody)
     150                {
     151                        m_pushVelocity += linearComponent*impulseMagnitude;
     152                        m_turnVelocity += angularComponent*(impulseMagnitude*m_angularFactor);
     153                }
     154        }
    150155       
    151156        void    writebackVelocity()
    152157        {
    153                 if (m_invMass)
     158                if (m_originalBody)
    154159                {
    155160                        m_originalBody->setLinearVelocity(m_originalBody->getLinearVelocity()+ m_deltaLinearVelocity);
     
    159164                }
    160165        }
    161         */
    162166
    163         void    writebackVelocity(btScalar timeStep=0)
     167
     168        void    writebackVelocity(btScalar timeStep)
    164169        {
    165                 if (m_invMass)
     170        (void) timeStep;
     171                if (m_originalBody)
    166172                {
    167                         m_originalBody->setLinearVelocity(m_originalBody->getLinearVelocity()+m_deltaLinearVelocity);
     173                        m_originalBody->setLinearVelocity(m_originalBody->getLinearVelocity()+ m_deltaLinearVelocity);
    168174                        m_originalBody->setAngularVelocity(m_originalBody->getAngularVelocity()+m_deltaAngularVelocity);
     175                       
     176                        //correct the position/orientation based on push/turn recovery
     177                        btTransform newTransform;
     178                        btTransformUtil::integrateTransform(m_originalBody->getWorldTransform(),m_pushVelocity,m_turnVelocity,timeStep,newTransform);
     179                        m_originalBody->setWorldTransform(newTransform);
     180                       
    169181                        //m_originalBody->setCompanionId(-1);
    170182                }
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btSolverConstraint.h

    r5781 r8284  
    2727
    2828///1D constraint along a normal axis between bodyA and bodyB. It can be combined to solve contact and friction constraints.
    29 ATTRIBUTE_ALIGNED16 (struct)    btSolverConstraint
     29ATTRIBUTE_ALIGNED64 (struct)    btSolverConstraint
    3030{
    3131        BT_DECLARE_ALIGNED_ALLOCATOR();
     
    5959        union
    6060        {
    61                 int                     m_solverBodyIdA;
    62                 btScalar        m_unusedPadding2;
     61                btRigidBody*    m_solverBodyA;
     62                int                             m_companionIdA;
    6363        };
    6464        union
    6565        {
    66                 int                     m_solverBodyIdB;
    67                 btScalar        m_unusedPadding3;
     66                btRigidBody*    m_solverBodyB;
     67                int                             m_companionIdB;
    6868        };
    6969       
     
    7878        btScalar                m_lowerLimit;
    7979        btScalar                m_upperLimit;
     80
     81        btScalar                m_rhsPenetration;
    8082
    8183        enum            btSolverConstraintType
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btTypedConstraint.cpp

    r5781 r8284  
    1717#include "btTypedConstraint.h"
    1818#include "BulletDynamics/Dynamics/btRigidBody.h"
     19#include "LinearMath/btSerializer.h"
    1920
    20 static btRigidBody s_fixed(0, 0,0);
    2121
    2222#define DEFAULT_DEBUGDRAW_SIZE btScalar(0.3f)
    2323
    24 btTypedConstraint::btTypedConstraint(btTypedConstraintType type)
    25 :m_userConstraintType(-1),
     24btTypedConstraint::btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA)
     25:btTypedObject(type),
     26m_userConstraintType(-1),
    2627m_userConstraintId(-1),
    27 m_constraintType (type),
    28 m_rbA(s_fixed),
    29 m_rbB(s_fixed),
     28m_needsFeedback(false),
     29m_rbA(rbA),
     30m_rbB(getFixedBody()),
    3031m_appliedImpulse(btScalar(0.)),
    3132m_dbgDrawSize(DEFAULT_DEBUGDRAW_SIZE)
    3233{
    33         s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.)));
    34 }
    35 btTypedConstraint::btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA)
    36 :m_userConstraintType(-1),
    37 m_userConstraintId(-1),
    38 m_constraintType (type),
    39 m_rbA(rbA),
    40 m_rbB(s_fixed),
    41 m_appliedImpulse(btScalar(0.)),
    42 m_dbgDrawSize(DEFAULT_DEBUGDRAW_SIZE)
    43 {
    44                 s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.)));
    45 
    4634}
    4735
    4836
    4937btTypedConstraint::btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA,btRigidBody& rbB)
    50 :m_userConstraintType(-1),
     38:btTypedObject(type),
     39m_userConstraintType(-1),
    5140m_userConstraintId(-1),
    52 m_constraintType (type),
     41m_needsFeedback(false),
    5342m_rbA(rbA),
    5443m_rbB(rbB),
     
    5645m_dbgDrawSize(DEFAULT_DEBUGDRAW_SIZE)
    5746{
    58                 s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.)));
    59 
    6047}
    6148
    6249
    63 //-----------------------------------------------------------------------------
     50
    6451
    6552btScalar btTypedConstraint::getMotorFactor(btScalar pos, btScalar lowLim, btScalar uppLim, btScalar vel, btScalar timeFact)
     
    11097        }
    11198        return lim_fact;
    112 } // btTypedConstraint::getMotorFactor()
     99}
    113100
     101///fills the dataBuffer and returns the struct name (and 0 on failure)
     102const char*     btTypedConstraint::serialize(void* dataBuffer, btSerializer* serializer) const
     103{
     104        btTypedConstraintData* tcd = (btTypedConstraintData*) dataBuffer;
    114105
     106        tcd->m_rbA = (btRigidBodyData*)serializer->getUniquePointer(&m_rbA);
     107        tcd->m_rbB = (btRigidBodyData*)serializer->getUniquePointer(&m_rbB);
     108        char* name = (char*) serializer->findNameForPointer(this);
     109        tcd->m_name = (char*)serializer->getUniquePointer(name);
     110        if (tcd->m_name)
     111        {
     112                serializer->serializeName(name);
     113        }
     114
     115        tcd->m_objectType = m_objectType;
     116        tcd->m_needsFeedback = m_needsFeedback;
     117        tcd->m_userConstraintId =m_userConstraintId;
     118        tcd->m_userConstraintType =m_userConstraintType;
     119
     120        tcd->m_appliedImpulse = float(m_appliedImpulse);
     121        tcd->m_dbgDrawSize = float(m_dbgDrawSize );
     122
     123        tcd->m_disableCollisionsBetweenLinkedBodies = false;
     124
     125        int i;
     126        for (i=0;i<m_rbA.getNumConstraintRefs();i++)
     127                if (m_rbA.getConstraintRef(i) == this)
     128                        tcd->m_disableCollisionsBetweenLinkedBodies = true;
     129        for (i=0;i<m_rbB.getNumConstraintRefs();i++)
     130                if (m_rbB.getConstraintRef(i) == this)
     131                        tcd->m_disableCollisionsBetweenLinkedBodies = true;
     132
     133        return "btTypedConstraintData";
     134}
     135
     136btRigidBody& btTypedConstraint::getFixedBody()
     137{
     138        static btRigidBody s_fixed(0, 0,0);
     139        s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.)));
     140        return s_fixed;
     141}
     142
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/ConstraintSolver/btTypedConstraint.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2010 Erwin Coumans  http://continuousphysics.com/Bullet/
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2020#include "LinearMath/btScalar.h"
    2121#include "btSolverConstraint.h"
    22 struct  btSolverBody;
    23 
    24 
    25 
     22#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
     23
     24class btSerializer;
    2625
    2726enum btTypedConstraintType
    2827{
    29         POINT2POINT_CONSTRAINT_TYPE,
     28        POINT2POINT_CONSTRAINT_TYPE=MAX_CONTACT_MANIFOLD_TYPE+1,
    3029        HINGE_CONSTRAINT_TYPE,
    3130        CONETWIST_CONSTRAINT_TYPE,
    3231        D6_CONSTRAINT_TYPE,
    33         SLIDER_CONSTRAINT_TYPE
     32        SLIDER_CONSTRAINT_TYPE,
     33        CONTACT_CONSTRAINT_TYPE
    3434};
    3535
     36
     37enum btConstraintParams
     38{
     39        BT_CONSTRAINT_ERP=1,
     40        BT_CONSTRAINT_STOP_ERP,
     41        BT_CONSTRAINT_CFM,
     42        BT_CONSTRAINT_STOP_CFM
     43};
     44
     45#if 1
     46        #define btAssertConstrParams(_par) btAssert(_par)
     47#else
     48        #define btAssertConstrParams(_par)
     49#endif
     50
     51
    3652///TypedConstraint is the baseclass for Bullet constraints and vehicles
    37 class btTypedConstraint
     53class btTypedConstraint : public btTypedObject
    3854{
    3955        int     m_userConstraintType;
    40         int     m_userConstraintId;
    41 
    42         btTypedConstraintType m_constraintType;
     56
     57        union
     58        {
     59                int     m_userConstraintId;
     60                void* m_userConstraintPtr;
     61        };
     62
     63        bool m_needsFeedback;
    4364
    4465        btTypedConstraint&      operator=(btTypedConstraint&    other)
     
    5576        btScalar        m_dbgDrawSize;
    5677
     78        ///internal method used by the constraint solver, don't use them directly
     79        btScalar getMotorFactor(btScalar pos, btScalar lowLim, btScalar uppLim, btScalar vel, btScalar timeFact);
     80       
     81        static btRigidBody& getFixedBody();
    5782
    5883public:
    5984
    60         btTypedConstraint(btTypedConstraintType type);
    6185        virtual ~btTypedConstraint() {};
    6286        btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA);
     
    94118                // the constraint.
    95119                int *findex;
     120                // number of solver iterations
     121                int m_numIterations;
     122
     123                //damping of the velocity
     124                btScalar        m_damping;
    96125        };
    97126
    98 
    99         virtual void    buildJacobian() = 0;
    100 
     127        ///internal method used by the constraint solver, don't use them directly
     128        virtual void    buildJacobian() {};
     129
     130        ///internal method used by the constraint solver, don't use them directly
    101131        virtual void    setupSolverConstraint(btConstraintArray& ca, int solverBodyA,int solverBodyB, btScalar timeStep)
    102132        {
    103         }
     133        (void)ca;
     134        (void)solverBodyA;
     135        (void)solverBodyB;
     136        (void)timeStep;
     137        }
     138       
     139        ///internal method used by the constraint solver, don't use them directly
    104140        virtual void getInfo1 (btConstraintInfo1* info)=0;
    105141
     142        ///internal method used by the constraint solver, don't use them directly
    106143        virtual void getInfo2 (btConstraintInfo2* info)=0;
    107144
    108         virtual void    solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar        timeStep) = 0;
    109 
    110         btScalar getMotorFactor(btScalar pos, btScalar lowLim, btScalar uppLim, btScalar vel, btScalar timeFact);
     145        ///internal method used by the constraint solver, don't use them directly
     146        void    internalSetAppliedImpulse(btScalar appliedImpulse)
     147        {
     148                m_appliedImpulse = appliedImpulse;
     149        }
     150        ///internal method used by the constraint solver, don't use them directly
     151        btScalar        internalGetAppliedImpulse()
     152        {
     153                return m_appliedImpulse;
     154        }
     155
     156        ///internal method used by the constraint solver, don't use them directly
     157        virtual void    solveConstraintObsolete(btRigidBody& /*bodyA*/,btRigidBody& /*bodyB*/,btScalar  /*timeStep*/) {};
     158
    111159       
    112160        const btRigidBody& getRigidBodyA() const
     
    148196        }
    149197
     198        void    setUserConstraintPtr(void* ptr)
     199        {
     200                m_userConstraintPtr = ptr;
     201        }
     202
     203        void*   getUserConstraintPtr()
     204        {
     205                return m_userConstraintPtr;
     206        }
     207
    150208        int getUid() const
    151209        {
     
    153211        }
    154212
     213        bool    needsFeedback() const
     214        {
     215                return m_needsFeedback;
     216        }
     217
     218        ///enableFeedback will allow to read the applied linear and angular impulse
     219        ///use getAppliedImpulse, getAppliedLinearImpulse and getAppliedAngularImpulse to read feedback information
     220        void    enableFeedback(bool needsFeedback)
     221        {
     222                m_needsFeedback = needsFeedback;
     223        }
     224
     225        ///getAppliedImpulse is an estimated total applied impulse.
     226        ///This feedback could be used to determine breaking constraints or playing sounds.
    155227        btScalar        getAppliedImpulse() const
    156228        {
     229                btAssert(m_needsFeedback);
    157230                return m_appliedImpulse;
    158231        }
     
    160233        btTypedConstraintType getConstraintType () const
    161234        {
    162                 return m_constraintType;
     235                return btTypedConstraintType(m_objectType);
    163236        }
    164237       
     
    171244                return m_dbgDrawSize;
    172245        }
    173        
     246
     247        ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
     248        ///If no axis is provided, it uses the default axis for this constraint.
     249        virtual void    setParam(int num, btScalar value, int axis = -1) = 0;
     250
     251        ///return the local value of parameter
     252        virtual btScalar getParam(int num, int axis = -1) const = 0;
     253       
     254        virtual int     calculateSerializeBufferSize() const;
     255
     256        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     257        virtual const char*     serialize(void* dataBuffer, btSerializer* serializer) const;
     258
    174259};
    175260
     261// returns angle in range [-SIMD_2_PI, SIMD_2_PI], closest to one of the limits
     262// all arguments should be normalized angles (i.e. in range [-SIMD_PI, SIMD_PI])
     263SIMD_FORCE_INLINE btScalar btAdjustAngleToLimits(btScalar angleInRadians, btScalar angleLowerLimitInRadians, btScalar angleUpperLimitInRadians)
     264{
     265        if(angleLowerLimitInRadians >= angleUpperLimitInRadians)
     266        {
     267                return angleInRadians;
     268        }
     269        else if(angleInRadians < angleLowerLimitInRadians)
     270        {
     271                btScalar diffLo = btFabs(btNormalizeAngle(angleLowerLimitInRadians - angleInRadians));
     272                btScalar diffHi = btFabs(btNormalizeAngle(angleUpperLimitInRadians - angleInRadians));
     273                return (diffLo < diffHi) ? angleInRadians : (angleInRadians + SIMD_2_PI);
     274        }
     275        else if(angleInRadians > angleUpperLimitInRadians)
     276        {
     277                btScalar diffHi = btFabs(btNormalizeAngle(angleInRadians - angleUpperLimitInRadians));
     278                btScalar diffLo = btFabs(btNormalizeAngle(angleInRadians - angleLowerLimitInRadians));
     279                return (diffLo < diffHi) ? (angleInRadians - SIMD_2_PI) : angleInRadians;
     280        }
     281        else
     282        {
     283                return angleInRadians;
     284        }
     285}
     286
     287///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     288struct  btTypedConstraintData
     289{
     290        btRigidBodyData         *m_rbA;
     291        btRigidBodyData         *m_rbB;
     292        char    *m_name;
     293
     294        int     m_objectType;
     295        int     m_userConstraintType;
     296        int     m_userConstraintId;
     297        int     m_needsFeedback;
     298
     299        float   m_appliedImpulse;
     300        float   m_dbgDrawSize;
     301
     302        int     m_disableCollisionsBetweenLinkedBodies;
     303        char    m_pad4[4];
     304       
     305};
     306
     307SIMD_FORCE_INLINE       int     btTypedConstraint::calculateSerializeBufferSize() const
     308{
     309        return sizeof(btTypedConstraintData);
     310}
     311
     312
     313
     314
    176315#endif //TYPED_CONSTRAINT_H
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/Bullet-C-API.cpp

    r5781 r8284  
    4444#include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h"
    4545#include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h"
    46 #include "LinearMath/btStackAlloc.h"
     46
    4747
    4848/*
     
    182182{
    183183        //capsule is convex hull of 2 spheres, so use btMultiSphereShape
    184         btVector3 inertiaHalfExtents(radius,height,radius);
     184       
    185185        const int numSpheres = 2;
    186186        btVector3 positions[numSpheres] = {btVector3(0,height,0),btVector3(0,-height,0)};
    187187        btScalar radi[numSpheres] = {radius,radius};
    188188        void* mem = btAlignedAlloc(sizeof(btMultiSphereShape),16);
    189         return (plCollisionShapeHandle) new (mem)btMultiSphereShape(inertiaHalfExtents,positions,radi,numSpheres);
     189        return (plCollisionShapeHandle) new (mem)btMultiSphereShape(positions,radi,numSpheres);
    190190}
    191191plCollisionShapeHandle plNewConeShape(plReal radius, plReal height)
     
    294294        worldTrans.setRotation(orn);
    295295        body->setWorldTransform(worldTrans);
     296}
     297
     298void    plSetOpenGLMatrix(plRigidBodyHandle object, plReal* matrix)
     299{
     300        btRigidBody* body = reinterpret_cast< btRigidBody* >(object);
     301        btAssert(body);
     302        btTransform& worldTrans = body->getWorldTransform();
     303        worldTrans.setFromOpenGLMatrix(matrix);
    296304}
    297305
     
    366374        btGjkPairDetector::ClosestPointInput input;
    367375       
    368         btStackAlloc gStackAlloc(1024*1024*2);
    369  
    370         input.m_stackAlloc = &gStackAlloc;
    371        
     376               
    372377        btTransform tr;
    373378        tr.setIdentity();
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/btActionInterface.h

    r5781 r8284  
    2121
    2222#include "LinearMath/btScalar.h"
     23#include "btRigidBody.h"
    2324
    2425///Basic interface to allow actions such as vehicles and characters to be updated inside a btDynamicsWorld
    2526class btActionInterface
    2627{
    27         public:
     28protected:
     29
     30        static btRigidBody& getFixedBody();
     31       
     32       
     33public:
    2834
    2935        virtual ~btActionInterface()
     
    3844
    3945#endif //_BT_ACTION_INTERFACE_H
     46
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/btContinuousDynamicsWorld.cpp

    r5781 r8284  
    4949        startProfiling(timeStep);
    5050       
     51        if(0 != m_internalPreTickCallback) {
     52                (*m_internalPreTickCallback)(this, timeStep);
     53        }
     54
    5155
    5256        ///update aabbs information
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.cpp

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    2020#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
    2121#include "BulletCollision/BroadphaseCollision/btSimpleBroadphase.h"
     22#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
    2223#include "BulletCollision/CollisionShapes/btCollisionShape.h"
    2324#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
     
    3637#include "BulletDynamics/ConstraintSolver/btSliderConstraint.h"
    3738
    38 //for debug rendering
    39 #include "BulletCollision/CollisionShapes/btBoxShape.h"
    40 #include "BulletCollision/CollisionShapes/btCapsuleShape.h"
    41 #include "BulletCollision/CollisionShapes/btCompoundShape.h"
    42 #include "BulletCollision/CollisionShapes/btConeShape.h"
    43 #include "BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h"
    44 #include "BulletCollision/CollisionShapes/btCylinderShape.h"
    45 #include "BulletCollision/CollisionShapes/btMultiSphereShape.h"
    46 #include "BulletCollision/CollisionShapes/btPolyhedralConvexShape.h"
     39#include "LinearMath/btIDebugDraw.h"
    4740#include "BulletCollision/CollisionShapes/btSphereShape.h"
    48 #include "BulletCollision/CollisionShapes/btTriangleCallback.h"
    49 #include "BulletCollision/CollisionShapes/btTriangleMeshShape.h"
    50 #include "BulletCollision/CollisionShapes/btStaticPlaneShape.h"
    51 #include "LinearMath/btIDebugDraw.h"
    5241
    5342
     
    5645#include "LinearMath/btMotionState.h"
    5746
    58 
     47#include "LinearMath/btSerializer.h"
    5948
    6049
     
    6453m_constraintSolver(constraintSolver),
    6554m_gravity(0,-10,0),
    66 m_localTime(btScalar(1.)/btScalar(60.)),
     55m_localTime(0),
     56m_synchronizeAllMotionStates(false),
    6757m_profileTimings(0)
    6858{
     
    10494void    btDiscreteDynamicsWorld::saveKinematicState(btScalar timeStep)
    10595{
    106 
     96///would like to iterate over m_nonStaticRigidBodies, but unfortunately old API allows
     97///to switch status _after_ adding kinematic objects to the world
     98///fix it for Bullet 3.x release
    10799        for (int i=0;i<m_collisionObjects.size();i++)
    108100        {
    109101                btCollisionObject* colObj = m_collisionObjects[i];
    110102                btRigidBody* body = btRigidBody::upcast(colObj);
    111                 if (body)
    112                 {
    113                                 if (body->getActivationState() != ISLAND_SLEEPING)
    114                                 {
    115                                         if (body->isKinematicObject())
    116                                         {
    117                                                 //to calculate velocities next frame
    118                                                 body->saveKinematicState(timeStep);
    119                                         }
    120                                 }
    121                 }
    122         }
     103                if (body && body->getActivationState() != ISLAND_SLEEPING)
     104                {
     105                        if (body->isKinematicObject())
     106                        {
     107                                //to calculate velocities next frame
     108                                body->saveKinematicState(timeStep);
     109                        }
     110                }
     111        }
     112
    123113}
    124114
     
    127117        BT_PROFILE("debugDrawWorld");
    128118
    129         if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints)
    130         {
    131                 int numManifolds = getDispatcher()->getNumManifolds();
    132                 btVector3 color(0,0,0);
    133                 for (int i=0;i<numManifolds;i++)
    134                 {
    135                         btPersistentManifold* contactManifold = getDispatcher()->getManifoldByIndexInternal(i);
    136                         //btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
    137                         //btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
    138 
    139                         int numContacts = contactManifold->getNumContacts();
    140                         for (int j=0;j<numContacts;j++)
    141                         {
    142                                 btManifoldPoint& cp = contactManifold->getContactPoint(j);
    143                                 getDebugDrawer()->drawContactPoint(cp.m_positionWorldOnB,cp.m_normalWorldOnB,cp.getDistance(),cp.getLifeTime(),color);
    144                         }
    145                 }
    146         }
     119        btCollisionWorld::debugDrawWorld();
     120
    147121        bool drawConstraints = false;
    148122        if (getDebugDrawer())
     
    169143                int i;
    170144
    171                 for (  i=0;i<m_collisionObjects.size();i++)
    172                 {
    173                         btCollisionObject* colObj = m_collisionObjects[i];
    174                         if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawWireframe)
    175                         {
    176                                 btVector3 color(btScalar(255.),btScalar(255.),btScalar(255.));
    177                                 switch(colObj->getActivationState())
    178                                 {
    179                                 case  ACTIVE_TAG:
    180                                         color = btVector3(btScalar(255.),btScalar(255.),btScalar(255.)); break;
    181                                 case ISLAND_SLEEPING:
    182                                         color =  btVector3(btScalar(0.),btScalar(255.),btScalar(0.));break;
    183                                 case WANTS_DEACTIVATION:
    184                                         color = btVector3(btScalar(0.),btScalar(255.),btScalar(255.));break;
    185                                 case DISABLE_DEACTIVATION:
    186                                         color = btVector3(btScalar(255.),btScalar(0.),btScalar(0.));break;
    187                                 case DISABLE_SIMULATION:
    188                                         color = btVector3(btScalar(255.),btScalar(255.),btScalar(0.));break;
    189                                 default:
    190                                         {
    191                                                 color = btVector3(btScalar(255.),btScalar(0.),btScalar(0.));
    192                                         }
    193                                 };
    194 
    195                                 debugDrawObject(colObj->getWorldTransform(),colObj->getCollisionShape(),color);
    196                         }
    197                         if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawAabb))
    198                         {
    199                                 btVector3 minAabb,maxAabb;
    200                                 btVector3 colorvec(1,0,0);
    201                                 colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb,maxAabb);
    202                                 m_debugDrawer->drawAabb(minAabb,maxAabb,colorvec);
    203                         }
    204 
    205                 }
    206        
    207145                if (getDebugDrawer() && getDebugDrawer()->getDebugMode())
    208146                {
     
    218156{
    219157        ///@todo: iterate over awake simulation islands!
    220         for ( int i=0;i<m_collisionObjects.size();i++)
    221         {
    222                 btCollisionObject* colObj = m_collisionObjects[i];
    223                
    224                 btRigidBody* body = btRigidBody::upcast(colObj);
    225                 if (body)
    226                 {
    227                         body->clearForces();
    228                 }
     158        for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
     159        {
     160                btRigidBody* body = m_nonStaticRigidBodies[i];
     161                //need to check if next line is ok
     162                //it might break backward compatibility (people applying forces on sleeping objects get never cleared and accumulate on wake-up
     163                body->clearForces();
    229164        }
    230165}       
     
    234169{
    235170        ///@todo: iterate over awake simulation islands!
    236         for ( int i=0;i<m_collisionObjects.size();i++)
    237         {
    238                 btCollisionObject* colObj = m_collisionObjects[i];
    239                
    240                 btRigidBody* body = btRigidBody::upcast(colObj);
    241                 if (body && body->isActive())
     171        for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
     172        {
     173                btRigidBody* body = m_nonStaticRigidBodies[i];
     174                if (body->isActive())
    242175                {
    243176                        body->applyGravity();
     
    270203{
    271204        BT_PROFILE("synchronizeMotionStates");
    272         {
    273                 //todo: iterate over awake simulation islands!
     205        if (m_synchronizeAllMotionStates)
     206        {
     207                //iterate  over all collision objects
    274208                for ( int i=0;i<m_collisionObjects.size();i++)
    275209                {
    276210                        btCollisionObject* colObj = m_collisionObjects[i];
    277                        
    278211                        btRigidBody* body = btRigidBody::upcast(colObj);
    279212                        if (body)
    280213                                synchronizeSingleMotionState(body);
    281214                }
    282         }
    283 /*
    284         if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawWireframe)
    285         {
    286                 for ( int i=0;i<this->m_vehicles.size();i++)
    287                 {
    288                         for (int v=0;v<m_vehicles[i]->getNumWheels();v++)
    289                         {
    290                                 //synchronize the wheels with the (interpolated) chassis worldtransform
    291                                 m_vehicles[i]->updateWheelTransform(v,true);
    292                         }
    293                 }
    294         }
    295         */
    296 
    297 
     215        } else
     216        {
     217                //iterate over all active rigid bodies
     218                for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
     219                {
     220                        btRigidBody* body = m_nonStaticRigidBodies[i];
     221                        if (body->isActive())
     222                                synchronizeSingleMotionState(body);
     223                }
     224        }
    298225}
    299226
     
    341268        {
    342269
    343                 saveKinematicState(fixedTimeStep);
    344 
    345                 applyGravity();
    346 
    347270                //clamp the number of substeps, to prevent simulation grinding spiralling down to a halt
    348271                int clampedSimulationSteps = (numSimulationSubSteps > maxSubSteps)? maxSubSteps : numSimulationSubSteps;
    349272
     273                saveKinematicState(fixedTimeStep*clampedSimulationSteps);
     274
     275                applyGravity();
     276
     277               
     278
    350279                for (int i=0;i<clampedSimulationSteps;i++)
    351280                {
     
    354283                }
    355284
    356         }
    357 
    358         synchronizeMotionStates();
     285        } else
     286        {
     287                synchronizeMotionStates();
     288        }
    359289
    360290        clearForces();
     
    372302        BT_PROFILE("internalSingleStepSimulation");
    373303
     304        if(0 != m_internalPreTickCallback) {
     305                (*m_internalPreTickCallback)(this, timeStep);
     306        }       
     307
    374308        ///apply gravity, predict motion
    375309        predictUnconstraintMotion(timeStep);
     
    412346{
    413347        m_gravity = gravity;
    414         for ( int i=0;i<m_collisionObjects.size();i++)
    415         {
    416                 btCollisionObject* colObj = m_collisionObjects[i];
    417                 btRigidBody* body = btRigidBody::upcast(colObj);
    418                 if (body)
     348        for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
     349        {
     350                btRigidBody* body = m_nonStaticRigidBodies[i];
     351                if (body->isActive() && !(body->getFlags() &BT_DISABLE_WORLD_GRAVITY))
    419352                {
    420353                        body->setGravity(gravity);
     
    428361}
    429362
     363void    btDiscreteDynamicsWorld::addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup,short int collisionFilterMask)
     364{
     365        btCollisionWorld::addCollisionObject(collisionObject,collisionFilterGroup,collisionFilterMask);
     366}
     367
     368void    btDiscreteDynamicsWorld::removeCollisionObject(btCollisionObject* collisionObject)
     369{
     370        btRigidBody* body = btRigidBody::upcast(collisionObject);
     371        if (body)
     372                removeRigidBody(body);
     373        else
     374                btCollisionWorld::removeCollisionObject(collisionObject);
     375}
    430376
    431377void    btDiscreteDynamicsWorld::removeRigidBody(btRigidBody* body)
    432378{
    433         removeCollisionObject(body);
    434 }
     379        m_nonStaticRigidBodies.remove(body);
     380        btCollisionWorld::removeCollisionObject(body);
     381}
     382
    435383
    436384void    btDiscreteDynamicsWorld::addRigidBody(btRigidBody* body)
    437385{
    438         if (!body->isStaticOrKinematicObject())
     386        if (!body->isStaticOrKinematicObject() && !(body->getFlags() &BT_DISABLE_WORLD_GRAVITY))
    439387        {
    440388                body->setGravity(m_gravity);
     
    443391        if (body->getCollisionShape())
    444392        {
     393                if (!body->isStaticObject())
     394                {
     395                        m_nonStaticRigidBodies.push_back(body);
     396                } else
     397                {
     398                        body->setActivationState(ISLAND_SLEEPING);
     399                }
     400
    445401                bool isDynamic = !(body->isStaticObject() || body->isKinematicObject());
    446402                short collisionFilterGroup = isDynamic? short(btBroadphaseProxy::DefaultFilter) : short(btBroadphaseProxy::StaticFilter);
     
    453409void    btDiscreteDynamicsWorld::addRigidBody(btRigidBody* body, short group, short mask)
    454410{
    455         if (!body->isStaticOrKinematicObject())
     411        if (!body->isStaticOrKinematicObject() && !(body->getFlags() &BT_DISABLE_WORLD_GRAVITY))
    456412        {
    457413                body->setGravity(m_gravity);
     
    460416        if (body->getCollisionShape())
    461417        {
     418                if (!body->isStaticObject())
     419                {
     420                        m_nonStaticRigidBodies.push_back(body);
     421                }
     422                 else
     423                {
     424                        body->setActivationState(ISLAND_SLEEPING);
     425                }
    462426                addCollisionObject(body,group,mask);
    463427        }
     
    480444        BT_PROFILE("updateActivationState");
    481445
    482         for ( int i=0;i<m_collisionObjects.size();i++)
    483         {
    484                 btCollisionObject* colObj = m_collisionObjects[i];
    485                 btRigidBody* body = btRigidBody::upcast(colObj);
     446        for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
     447        {
     448                btRigidBody* body = m_nonStaticRigidBodies[i];
    486449                if (body)
    487450                {
     
    586549                }
    587550};
    588 
    589551
    590552
     
    604566                btStackAlloc*                   m_stackAlloc;
    605567                btDispatcher*                   m_dispatcher;
     568               
     569                btAlignedObjectArray<btCollisionObject*> m_bodies;
     570                btAlignedObjectArray<btPersistentManifold*> m_manifolds;
     571                btAlignedObjectArray<btTypedConstraint*> m_constraints;
     572
    606573
    607574                InplaceSolverIslandCallback(
     
    624591                }
    625592
     593
    626594                InplaceSolverIslandCallback& operator=(InplaceSolverIslandCallback& other)
    627595                {
     
    664632                                }
    665633
    666                                 ///only call solveGroup if there is some work: avoid virtual function call, its overhead can be excessive
    667                                 if (numManifolds + numCurConstraints)
    668                                 {
    669                                         m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,m_solverInfo,m_debugDrawer,m_stackAlloc,m_dispatcher);
    670                                 }
    671                
    672                         }
     634                                if (m_solverInfo.m_minimumSolverBatchSize<=1)
     635                                {
     636                                        ///only call solveGroup if there is some work: avoid virtual function call, its overhead can be excessive
     637                                        if (numManifolds + numCurConstraints)
     638                                        {
     639                                                m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,m_solverInfo,m_debugDrawer,m_stackAlloc,m_dispatcher);
     640                                        }
     641                                } else
     642                                {
     643                                       
     644                                        for (i=0;i<numBodies;i++)
     645                                                m_bodies.push_back(bodies[i]);
     646                                        for (i=0;i<numManifolds;i++)
     647                                                m_manifolds.push_back(manifolds[i]);
     648                                        for (i=0;i<numCurConstraints;i++)
     649                                                m_constraints.push_back(startConstraint[i]);
     650                                        if ((m_constraints.size()+m_manifolds.size())>m_solverInfo.m_minimumSolverBatchSize)
     651                                        {
     652                                                processConstraints();
     653                                        } else
     654                                        {
     655                                                //printf("deferred\n");
     656                                        }
     657                                }
     658                        }
     659                }
     660                void    processConstraints()
     661                {
     662                        if (m_manifolds.size() + m_constraints.size()>0)
     663                        {
     664                                m_solver->solveGroup( &m_bodies[0],m_bodies.size(), &m_manifolds[0], m_manifolds.size(), &m_constraints[0], m_constraints.size() ,m_solverInfo,m_debugDrawer,m_stackAlloc,m_dispatcher);
     665                        }
     666                        m_bodies.resize(0);
     667                        m_manifolds.resize(0);
     668                        m_constraints.resize(0);
     669
    673670                }
    674671
    675672        };
     673
     674       
    676675
    677676        //sorted version of all btTypedConstraint, based on islandId
     
    699698        m_islandManager->buildAndProcessIslands(getCollisionWorld()->getDispatcher(),getCollisionWorld(),&solverCallback);
    700699
     700        solverCallback.processConstraints();
     701
    701702        m_constraintSolver->allSolved(solverInfo, m_debugDrawer, m_stackAlloc);
    702703}
     
    741742
    742743
    743 #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
     744
    744745
    745746class btClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback
     
    754755        btClosestNotMeConvexResultCallback (btCollisionObject* me,const btVector3& fromA,const btVector3& toA,btOverlappingPairCache* pairCache,btDispatcher* dispatcher) :
    755756          btCollisionWorld::ClosestConvexResultCallback(fromA,toA),
     757                m_me(me),
    756758                m_allowedPenetration(0.0f),
    757                 m_me(me),
    758759                m_pairCache(pairCache),
    759760                m_dispatcher(dispatcher)
     
    829830        BT_PROFILE("integrateTransforms");
    830831        btTransform predictedTrans;
    831         for ( int i=0;i<m_collisionObjects.size();i++)
    832         {
    833                 btCollisionObject* colObj = m_collisionObjects[i];
    834                 btRigidBody* body = btRigidBody::upcast(colObj);
    835                 if (body)
    836                 {
    837                         body->setHitFraction(1.f);
    838 
    839                         if (body->isActive() && (!body->isStaticOrKinematicObject()))
    840                         {
    841                                 body->predictIntegratedTransform(timeStep, predictedTrans);
    842                                 btScalar squareMotion = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin()).length2();
    843 
    844                                 if (body->getCcdSquareMotionThreshold() && body->getCcdSquareMotionThreshold() < squareMotion)
    845                                 {
    846                                         BT_PROFILE("CCD motion clamping");
    847                                         if (body->getCollisionShape()->isConvex())
    848                                         {
    849                                                 gNumClampedCcdMotions++;
    850                                                
    851                                                 btClosestNotMeConvexResultCallback sweepResults(body,body->getWorldTransform().getOrigin(),predictedTrans.getOrigin(),getBroadphase()->getOverlappingPairCache(),getDispatcher());
    852                                                 btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape());
    853                                                 btSphereShape tmpSphere(body->getCcdSweptSphereRadius());//btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape());
    854 
    855                                                 sweepResults.m_collisionFilterGroup = body->getBroadphaseProxy()->m_collisionFilterGroup;
    856                                                 sweepResults.m_collisionFilterMask  = body->getBroadphaseProxy()->m_collisionFilterMask;
    857 
    858                                                 convexSweepTest(&tmpSphere,body->getWorldTransform(),predictedTrans,sweepResults);
    859                                                 if (sweepResults.hasHit() && (sweepResults.m_closestHitFraction < 1.f))
    860                                                 {
    861                                                         body->setHitFraction(sweepResults.m_closestHitFraction);
    862                                                         body->predictIntegratedTransform(timeStep*body->getHitFraction(), predictedTrans);
    863                                                         body->setHitFraction(0.f);
     832        for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
     833        {
     834                btRigidBody* body = m_nonStaticRigidBodies[i];
     835                body->setHitFraction(1.f);
     836
     837                if (body->isActive() && (!body->isStaticOrKinematicObject()))
     838                {
     839                        body->predictIntegratedTransform(timeStep, predictedTrans);
     840                        btScalar squareMotion = (predictedTrans.getOrigin()-body->getWorldTransform().getOrigin()).length2();
     841
     842                        if (body->getCcdSquareMotionThreshold() && body->getCcdSquareMotionThreshold() < squareMotion)
     843                        {
     844                                BT_PROFILE("CCD motion clamping");
     845                                if (body->getCollisionShape()->isConvex())
     846                                {
     847                                        gNumClampedCcdMotions++;
     848                                       
     849                                        btClosestNotMeConvexResultCallback sweepResults(body,body->getWorldTransform().getOrigin(),predictedTrans.getOrigin(),getBroadphase()->getOverlappingPairCache(),getDispatcher());
     850                                        //btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape());
     851                                        btSphereShape tmpSphere(body->getCcdSweptSphereRadius());//btConvexShape* convexShape = static_cast<btConvexShape*>(body->getCollisionShape());
     852
     853                                        sweepResults.m_collisionFilterGroup = body->getBroadphaseProxy()->m_collisionFilterGroup;
     854                                        sweepResults.m_collisionFilterMask  = body->getBroadphaseProxy()->m_collisionFilterMask;
     855
     856                                        convexSweepTest(&tmpSphere,body->getWorldTransform(),predictedTrans,sweepResults);
     857                                        if (sweepResults.hasHit() && (sweepResults.m_closestHitFraction < 1.f))
     858                                        {
     859                                                body->setHitFraction(sweepResults.m_closestHitFraction);
     860                                                body->predictIntegratedTransform(timeStep*body->getHitFraction(), predictedTrans);
     861                                                body->setHitFraction(0.f);
    864862//                                                      printf("clamped integration to hit fraction = %f\n",fraction);
    865                                                 }
    866863                                        }
    867864                                }
    868                                
    869                                 body->proceedToTransform( predictedTrans);
    870                         }
     865                        }
     866                       
     867                        body->proceedToTransform( predictedTrans);
    871868                }
    872869        }
     
    880877{
    881878        BT_PROFILE("predictUnconstraintMotion");
    882         for ( int i=0;i<m_collisionObjects.size();i++)
    883         {
    884                 btCollisionObject* colObj = m_collisionObjects[i];
    885                 btRigidBody* body = btRigidBody::upcast(colObj);
    886                 if (body)
    887                 {
    888                         if (!body->isStaticOrKinematicObject())
    889                         {
    890                                
    891                                 body->integrateVelocities( timeStep);
    892                                 //damping
    893                                 body->applyDamping(timeStep);
    894 
    895                                 body->predictIntegratedTransform(timeStep,body->getInterpolationWorldTransform());
    896                         }
     879        for ( int i=0;i<m_nonStaticRigidBodies.size();i++)
     880        {
     881                btRigidBody* body = m_nonStaticRigidBodies[i];
     882                if (!body->isStaticOrKinematicObject())
     883                {
     884                        body->integrateVelocities( timeStep);
     885                        //damping
     886                        body->applyDamping(timeStep);
     887
     888                        body->predictIntegratedTransform(timeStep,body->getInterpolationWorldTransform());
    897889                }
    898890        }
     
    914906
    915907       
    916 
    917 class DebugDrawcallback : public btTriangleCallback, public btInternalTriangleIndexCallback
    918 {
    919         btIDebugDraw*   m_debugDrawer;
    920         btVector3       m_color;
    921         btTransform     m_worldTrans;
    922 
    923 public:
    924 
    925         DebugDrawcallback(btIDebugDraw* debugDrawer,const btTransform& worldTrans,const btVector3& color) :
    926                 m_debugDrawer(debugDrawer),
    927                 m_color(color),
    928                 m_worldTrans(worldTrans)
    929         {
    930         }
    931 
    932         virtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int  triangleIndex)
    933         {
    934                 processTriangle(triangle,partId,triangleIndex);
    935         }
    936 
    937         virtual void processTriangle(btVector3* triangle,int partId, int triangleIndex)
    938         {
    939                 (void)partId;
    940                 (void)triangleIndex;
    941 
    942                 btVector3 wv0,wv1,wv2;
    943                 wv0 = m_worldTrans*triangle[0];
    944                 wv1 = m_worldTrans*triangle[1];
    945                 wv2 = m_worldTrans*triangle[2];
    946                 m_debugDrawer->drawLine(wv0,wv1,m_color);
    947                 m_debugDrawer->drawLine(wv1,wv2,m_color);
    948                 m_debugDrawer->drawLine(wv2,wv0,m_color);
    949         }
    950 };
    951 
    952 void btDiscreteDynamicsWorld::debugDrawSphere(btScalar radius, const btTransform& transform, const btVector3& color)
    953 {
    954         btVector3 start = transform.getOrigin();
    955 
    956         const btVector3 xoffs = transform.getBasis() * btVector3(radius,0,0);
    957         const btVector3 yoffs = transform.getBasis() * btVector3(0,radius,0);
    958         const btVector3 zoffs = transform.getBasis() * btVector3(0,0,radius);
    959 
    960         // XY
    961         getDebugDrawer()->drawLine(start-xoffs, start+yoffs, color);
    962         getDebugDrawer()->drawLine(start+yoffs, start+xoffs, color);
    963         getDebugDrawer()->drawLine(start+xoffs, start-yoffs, color);
    964         getDebugDrawer()->drawLine(start-yoffs, start-xoffs, color);
    965 
    966         // XZ
    967         getDebugDrawer()->drawLine(start-xoffs, start+zoffs, color);
    968         getDebugDrawer()->drawLine(start+zoffs, start+xoffs, color);
    969         getDebugDrawer()->drawLine(start+xoffs, start-zoffs, color);
    970         getDebugDrawer()->drawLine(start-zoffs, start-xoffs, color);
    971 
    972         // YZ
    973         getDebugDrawer()->drawLine(start-yoffs, start+zoffs, color);
    974         getDebugDrawer()->drawLine(start+zoffs, start+yoffs, color);
    975         getDebugDrawer()->drawLine(start+yoffs, start-zoffs, color);
    976         getDebugDrawer()->drawLine(start-zoffs, start-yoffs, color);
    977 }
    978 
    979 void btDiscreteDynamicsWorld::debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color)
    980 {
    981         // Draw a small simplex at the center of the object
    982         {
    983                 btVector3 start = worldTransform.getOrigin();
    984                 getDebugDrawer()->drawLine(start, start+worldTransform.getBasis() * btVector3(1,0,0), btVector3(1,0,0));
    985                 getDebugDrawer()->drawLine(start, start+worldTransform.getBasis() * btVector3(0,1,0), btVector3(0,1,0));
    986                 getDebugDrawer()->drawLine(start, start+worldTransform.getBasis() * btVector3(0,0,1), btVector3(0,0,1));
    987         }
    988 
    989         if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE)
    990         {
    991                 const btCompoundShape* compoundShape = static_cast<const btCompoundShape*>(shape);
    992                 for (int i=compoundShape->getNumChildShapes()-1;i>=0;i--)
    993                 {
    994                         btTransform childTrans = compoundShape->getChildTransform(i);
    995                         const btCollisionShape* colShape = compoundShape->getChildShape(i);
    996                         debugDrawObject(worldTransform*childTrans,colShape,color);
    997                 }
    998 
    999         } else
    1000         {
    1001                 switch (shape->getShapeType())
    1002                 {
    1003 
    1004                 case SPHERE_SHAPE_PROXYTYPE:
    1005                         {
    1006                                 const btSphereShape* sphereShape = static_cast<const btSphereShape*>(shape);
    1007                                 btScalar radius = sphereShape->getMargin();//radius doesn't include the margin, so draw with margin
    1008                                
    1009                                 debugDrawSphere(radius, worldTransform, color);
    1010                                 break;
    1011                         }
    1012                 case MULTI_SPHERE_SHAPE_PROXYTYPE:
    1013                         {
    1014                                 const btMultiSphereShape* multiSphereShape = static_cast<const btMultiSphereShape*>(shape);
    1015 
    1016                                 for (int i = multiSphereShape->getSphereCount()-1; i>=0;i--)
    1017                                 {
    1018                                         btTransform childTransform = worldTransform;
    1019                                         childTransform.getOrigin() += multiSphereShape->getSpherePosition(i);
    1020                                         debugDrawSphere(multiSphereShape->getSphereRadius(i), childTransform, color);
    1021                                 }
    1022 
    1023                                 break;
    1024                         }
    1025                 case CAPSULE_SHAPE_PROXYTYPE:
    1026                         {
    1027                                 const btCapsuleShape* capsuleShape = static_cast<const btCapsuleShape*>(shape);
    1028 
    1029                                 btScalar radius = capsuleShape->getRadius();
    1030                                 btScalar halfHeight = capsuleShape->getHalfHeight();
    1031                                
    1032                                 int upAxis = capsuleShape->getUpAxis();
    1033 
    1034                                
    1035                                 btVector3 capStart(0.f,0.f,0.f);
    1036                                 capStart[upAxis] = -halfHeight;
    1037 
    1038                                 btVector3 capEnd(0.f,0.f,0.f);
    1039                                 capEnd[upAxis] = halfHeight;
    1040 
    1041                                 // Draw the ends
    1042                                 {
    1043                                        
    1044                                         btTransform childTransform = worldTransform;
    1045                                         childTransform.getOrigin() = worldTransform * capStart;
    1046                                         debugDrawSphere(radius, childTransform, color);
    1047                                 }
    1048 
    1049                                 {
    1050                                         btTransform childTransform = worldTransform;
    1051                                         childTransform.getOrigin() = worldTransform * capEnd;
    1052                                         debugDrawSphere(radius, childTransform, color);
    1053                                 }
    1054 
    1055                                 // Draw some additional lines
    1056                                 btVector3 start = worldTransform.getOrigin();
    1057 
    1058                                
    1059                                 capStart[(upAxis+1)%3] = radius;
    1060                                 capEnd[(upAxis+1)%3] = radius;
    1061                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color);
    1062                                 capStart[(upAxis+1)%3] = -radius;
    1063                                 capEnd[(upAxis+1)%3] = -radius;
    1064                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color);
    1065 
    1066                                 capStart[(upAxis+1)%3] = 0.f;
    1067                                 capEnd[(upAxis+1)%3] = 0.f;
    1068 
    1069                                 capStart[(upAxis+2)%3] = radius;
    1070                                 capEnd[(upAxis+2)%3] = radius;
    1071                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color);
    1072                                 capStart[(upAxis+2)%3] = -radius;
    1073                                 capEnd[(upAxis+2)%3] = -radius;
    1074                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color);
    1075 
    1076                                
    1077                                 break;
    1078                         }
    1079                 case CONE_SHAPE_PROXYTYPE:
    1080                         {
    1081                                 const btConeShape* coneShape = static_cast<const btConeShape*>(shape);
    1082                                 btScalar radius = coneShape->getRadius();//+coneShape->getMargin();
    1083                                 btScalar height = coneShape->getHeight();//+coneShape->getMargin();
    1084                                 btVector3 start = worldTransform.getOrigin();
    1085 
    1086                                 int upAxis= coneShape->getConeUpIndex();
    1087                                
    1088 
    1089                                 btVector3       offsetHeight(0,0,0);
    1090                                 offsetHeight[upAxis] = height * btScalar(0.5);
    1091                                 btVector3       offsetRadius(0,0,0);
    1092                                 offsetRadius[(upAxis+1)%3] = radius;
    1093                                 btVector3       offset2Radius(0,0,0);
    1094                                 offset2Radius[(upAxis+2)%3] = radius;
    1095 
    1096                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight+offsetRadius),color);
    1097                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight-offsetRadius),color);
    1098                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight+offset2Radius),color);
    1099                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight-offset2Radius),color);
    1100 
    1101 
    1102 
    1103                                 break;
    1104 
    1105                         }
    1106                 case CYLINDER_SHAPE_PROXYTYPE:
    1107                         {
    1108                                 const btCylinderShape* cylinder = static_cast<const btCylinderShape*>(shape);
    1109                                 int upAxis = cylinder->getUpAxis();
    1110                                 btScalar radius = cylinder->getRadius();
    1111                                 btScalar halfHeight = cylinder->getHalfExtentsWithMargin()[upAxis];
    1112                                 btVector3 start = worldTransform.getOrigin();
    1113                                 btVector3       offsetHeight(0,0,0);
    1114                                 offsetHeight[upAxis] = halfHeight;
    1115                                 btVector3       offsetRadius(0,0,0);
    1116                                 offsetRadius[(upAxis+1)%3] = radius;
    1117                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight+offsetRadius),start+worldTransform.getBasis() * (-offsetHeight+offsetRadius),color);
    1118                                 getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight-offsetRadius),start+worldTransform.getBasis() * (-offsetHeight-offsetRadius),color);
    1119                                 break;
    1120                         }
    1121 
    1122                         case STATIC_PLANE_PROXYTYPE:
    1123                                 {
    1124                                         const btStaticPlaneShape* staticPlaneShape = static_cast<const btStaticPlaneShape*>(shape);
    1125                                         btScalar planeConst = staticPlaneShape->getPlaneConstant();
    1126                                         const btVector3& planeNormal = staticPlaneShape->getPlaneNormal();
    1127                                         btVector3 planeOrigin = planeNormal * planeConst;
    1128                                         btVector3 vec0,vec1;
    1129                                         btPlaneSpace1(planeNormal,vec0,vec1);
    1130                                         btScalar vecLen = 100.f;
    1131                                         btVector3 pt0 = planeOrigin + vec0*vecLen;
    1132                                         btVector3 pt1 = planeOrigin - vec0*vecLen;
    1133                                         btVector3 pt2 = planeOrigin + vec1*vecLen;
    1134                                         btVector3 pt3 = planeOrigin - vec1*vecLen;
    1135                                         getDebugDrawer()->drawLine(worldTransform*pt0,worldTransform*pt1,color);
    1136                                         getDebugDrawer()->drawLine(worldTransform*pt2,worldTransform*pt3,color);
    1137                                         break;
    1138 
    1139                                 }
    1140                 default:
    1141                         {
    1142 
    1143                                 if (shape->isConcave())
    1144                                 {
    1145                                         btConcaveShape* concaveMesh = (btConcaveShape*) shape;
    1146                                        
    1147                                         ///@todo pass camera, for some culling? no -> we are not a graphics lib
    1148                                         btVector3 aabbMax(btScalar(1e30),btScalar(1e30),btScalar(1e30));
    1149                                         btVector3 aabbMin(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
    1150 
    1151                                         DebugDrawcallback drawCallback(getDebugDrawer(),worldTransform,color);
    1152                                         concaveMesh->processAllTriangles(&drawCallback,aabbMin,aabbMax);
    1153 
    1154                                 }
    1155 
    1156                                 if (shape->getShapeType() == CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE)
    1157                                 {
    1158                                         btConvexTriangleMeshShape* convexMesh = (btConvexTriangleMeshShape*) shape;
    1159                                         //todo: pass camera for some culling                   
    1160                                         btVector3 aabbMax(btScalar(1e30),btScalar(1e30),btScalar(1e30));
    1161                                         btVector3 aabbMin(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30));
    1162                                         //DebugDrawcallback drawCallback;
    1163                                         DebugDrawcallback drawCallback(getDebugDrawer(),worldTransform,color);
    1164                                         convexMesh->getMeshInterface()->InternalProcessAllTriangles(&drawCallback,aabbMin,aabbMax);
    1165                                 }
    1166 
    1167 
    1168                                 /// for polyhedral shapes
    1169                                 if (shape->isPolyhedral())
    1170                                 {
    1171                                         btPolyhedralConvexShape* polyshape = (btPolyhedralConvexShape*) shape;
    1172 
    1173                                         int i;
    1174                                         for (i=0;i<polyshape->getNumEdges();i++)
    1175                                         {
    1176                                                 btVector3 a,b;
    1177                                                 polyshape->getEdge(i,a,b);
    1178                                                 btVector3 wa = worldTransform * a;
    1179                                                 btVector3 wb = worldTransform * b;
    1180                                                 getDebugDrawer()->drawLine(wa,wb,color);
    1181 
    1182                                         }
    1183 
    1184                                        
    1185                                 }
    1186                         }
    1187                 }
    1188         }
    1189 }
    1190 
    1191908
    1192909void btDiscreteDynamicsWorld::debugDrawConstraint(btTypedConstraint* constraint)
     
    13501067                                if(drawLimits)
    13511068                                {
    1352                                         btTransform tr = pSlider->getCalculatedTransformA();
     1069                                        btTransform tr = pSlider->getUseLinearReferenceFrameA() ? pSlider->getCalculatedTransformA() : pSlider->getCalculatedTransformB();
    13531070                                        btVector3 li_min = tr * btVector3(pSlider->getLowerLinLimit(), 0.f, 0.f);
    13541071                                        btVector3 li_max = tr * btVector3(pSlider->getUpperLinLimit(), 0.f, 0.f);
     
    13671084        }
    13681085        return;
    1369 } // btDiscreteDynamicsWorld::debugDrawConstraint()
     1086}
    13701087
    13711088
     
    14031120
    14041121
     1122
     1123void    btDiscreteDynamicsWorld::serializeRigidBodies(btSerializer* serializer)
     1124{
     1125        int i;
     1126        //serialize all collision objects
     1127        for (i=0;i<m_collisionObjects.size();i++)
     1128        {
     1129                btCollisionObject* colObj = m_collisionObjects[i];
     1130                if (colObj->getInternalType() & btCollisionObject::CO_RIGID_BODY)
     1131                {
     1132                        int len = colObj->calculateSerializeBufferSize();
     1133                        btChunk* chunk = serializer->allocate(len,1);
     1134                        const char* structType = colObj->serialize(chunk->m_oldPtr, serializer);
     1135                        serializer->finalizeChunk(chunk,structType,BT_RIGIDBODY_CODE,colObj);
     1136                }
     1137        }
     1138
     1139        for (i=0;i<m_constraints.size();i++)
     1140        {
     1141                btTypedConstraint* constraint = m_constraints[i];
     1142                int size = constraint->calculateSerializeBufferSize();
     1143                btChunk* chunk = serializer->allocate(size,1);
     1144                const char* structType = constraint->serialize(chunk->m_oldPtr,serializer);
     1145                serializer->finalizeChunk(chunk,structType,BT_CONSTRAINT_CODE,constraint);
     1146        }
     1147}
     1148
     1149
     1150void    btDiscreteDynamicsWorld::serialize(btSerializer* serializer)
     1151{
     1152
     1153        serializer->startSerialization();
     1154
     1155        serializeRigidBodies(serializer);
     1156
     1157        serializeCollisionObjects(serializer);
     1158
     1159        serializer->finishSerialization();
     1160}
     1161
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h

    r5781 r8284  
    11/*
    22Bullet Continuous Collision Detection and Physics Library
    3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
    44
    55This software is provided 'as-is', without any express or implied warranty.
     
    13133. This notice may not be removed or altered from any source distribution.
    1414*/
     15
    1516
    1617#ifndef BT_DISCRETE_DYNAMICS_WORLD_H
     
    4243        btAlignedObjectArray<btTypedConstraint*> m_constraints;
    4344
     45        btAlignedObjectArray<btRigidBody*> m_nonStaticRigidBodies;
     46
    4447        btVector3       m_gravity;
    4548
     
    5053        bool    m_ownsIslandManager;
    5154        bool    m_ownsConstraintSolver;
     55        bool    m_synchronizeAllMotionStates;
    5256
    5357        btAlignedObjectArray<btActionInterface*>        m_actions;
     
    7478        virtual void    saveKinematicState(btScalar timeStep);
    7579
    76         void    debugDrawSphere(btScalar radius, const btTransform& transform, const btVector3& color);
    77 
     80        void    serializeRigidBodies(btSerializer* serializer);
    7881
    7982public:
     
    121124        virtual btVector3 getGravity () const;
    122125
     126        virtual void    addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup=btBroadphaseProxy::StaticFilter,short int collisionFilterMask=btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
     127
    123128        virtual void    addRigidBody(btRigidBody* body);
    124129
     
    127132        virtual void    removeRigidBody(btRigidBody* body);
    128133
    129         void    debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color);
     134        ///removeCollisionObject will first check if it is a rigid body, if so call removeRigidBody otherwise call btCollisionWorld::removeCollisionObject
     135        virtual void    removeCollisionObject(btCollisionObject* collisionObject);
     136
    130137
    131138        void    debugDrawConstraint(btTypedConstraint* constraint);
     
    175182        virtual void    removeCharacter(btActionInterface* character);
    176183
     184        void    setSynchronizeAllMotionStates(bool synchronizeAll)
     185        {
     186                m_synchronizeAllMotionStates = synchronizeAll;
     187        }
     188        bool getSynchronizeAllMotionStates() const
     189        {
     190                return m_synchronizeAllMotionStates;
     191        }
     192
     193        ///Preliminary serialization test for Bullet 2.76. Loading those files requires a separate parser (see Bullet/Demos/SerializeDemo)
     194        virtual void    serialize(btSerializer* serializer);
     195
    177196};
    178197
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/btDynamicsWorld.h

    r5781 r8284  
    4242protected:
    4343                btInternalTickCallback m_internalTickCallback;
     44                btInternalTickCallback m_internalPreTickCallback;
    4445                void*   m_worldUserInfo;
    4546
     
    5051
    5152                btDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* broadphase,btCollisionConfiguration* collisionConfiguration)
    52                 :btCollisionWorld(dispatcher,broadphase,collisionConfiguration), m_internalTickCallback(0), m_worldUserInfo(0)
     53                :btCollisionWorld(dispatcher,broadphase,collisionConfiguration), m_internalTickCallback(0),m_internalPreTickCallback(0), m_worldUserInfo(0)
    5354                {
    5455                }
     
    103104
    104105                /// Set the callback for when an internal tick (simulation substep) happens, optional user info
    105                 void setInternalTickCallback(btInternalTickCallback cb, void* worldUserInfo=0)
     106                void setInternalTickCallback(btInternalTickCallback cb, void* worldUserInfo=0,bool isPreTick=false)
    106107                {
    107                         m_internalTickCallback = cb;
     108                        if (isPreTick)
     109                        {
     110                                m_internalPreTickCallback = cb;
     111                        } else
     112                        {
     113                                m_internalTickCallback = cb;
     114                        }
    108115                        m_worldUserInfo = worldUserInfo;
    109116                }
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/btRigidBody.cpp

    r5781 r8284  
    2020#include "LinearMath/btMotionState.h"
    2121#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
     22#include "LinearMath/btSerializer.h"
    2223
    2324//'temporarily' global variables
     
    4546        m_linearVelocity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
    4647        m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
    47         m_angularFactor = btScalar(1.);
     48        m_angularFactor.setValue(1,1,1);
     49        m_linearFactor.setValue(1,1,1);
    4850        m_gravity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
    4951        m_gravity_acceleration.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
     
    8688        updateInertiaTensor();
    8789
     90        m_rigidbodyFlags = 0;
     91
     92
     93        m_deltaLinearVelocity.setZero();
     94        m_deltaAngularVelocity.setZero();
     95        m_invMass = m_inverseMass*m_linearFactor;
     96        m_pushVelocity.setZero();
     97        m_turnVelocity.setZero();
     98
     99       
     100
    88101}
    89102
     
    136149void btRigidBody::setDamping(btScalar lin_damping, btScalar ang_damping)
    137150{
    138         m_linearDamping = GEN_clamped(lin_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
    139         m_angularDamping = GEN_clamped(ang_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
     151        m_linearDamping = btClamped(lin_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
     152        m_angularDamping = btClamped(ang_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
    140153}
    141154
     
    227240                m_inverseMass = btScalar(1.0) / mass;
    228241        }
     242
     243        //Fg = m * a
     244        m_gravity = mass * m_gravity_acceleration;
    229245       
    230246        m_invInertiaLocal.setValue(inertia.x() != btScalar(0.0) ? btScalar(1.0) / inertia.x(): btScalar(0.0),
     
    232248                                   inertia.z() != btScalar(0.0) ? btScalar(1.0) / inertia.z(): btScalar(0.0));
    233249
     250        m_invMass = m_linearFactor*m_inverseMass;
    234251}
    235252
     
    301318}
    302319
     320void    btRigidBody::internalWritebackVelocity(btScalar timeStep)
     321{
     322    (void) timeStep;
     323        if (m_inverseMass)
     324        {
     325                setLinearVelocity(getLinearVelocity()+ m_deltaLinearVelocity);
     326                setAngularVelocity(getAngularVelocity()+m_deltaAngularVelocity);
     327               
     328                //correct the position/orientation based on push/turn recovery
     329                btTransform newTransform;
     330                btTransformUtil::integrateTransform(getWorldTransform(),m_pushVelocity,m_turnVelocity,timeStep,newTransform);
     331                setWorldTransform(newTransform);
     332                //m_originalBody->setCompanionId(-1);
     333        }
     334//      m_deltaLinearVelocity.setZero();
     335//      m_deltaAngularVelocity .setZero();
     336//      m_pushVelocity.setZero();
     337//      m_turnVelocity.setZero();
     338}
     339
     340
     341
    303342void btRigidBody::addConstraintRef(btTypedConstraint* c)
    304343{
     
    315354        m_checkCollideWith = m_constraintRefs.size() > 0;
    316355}
     356
     357int     btRigidBody::calculateSerializeBufferSize()     const
     358{
     359        int sz = sizeof(btRigidBodyData);
     360        return sz;
     361}
     362
     363        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     364const char*     btRigidBody::serialize(void* dataBuffer, class btSerializer* serializer) const
     365{
     366        btRigidBodyData* rbd = (btRigidBodyData*) dataBuffer;
     367
     368        btCollisionObject::serialize(&rbd->m_collisionObjectData, serializer);
     369
     370        m_invInertiaTensorWorld.serialize(rbd->m_invInertiaTensorWorld);
     371        m_linearVelocity.serialize(rbd->m_linearVelocity);
     372        m_angularVelocity.serialize(rbd->m_angularVelocity);
     373        rbd->m_inverseMass = m_inverseMass;
     374        m_angularFactor.serialize(rbd->m_angularFactor);
     375        m_linearFactor.serialize(rbd->m_linearFactor);
     376        m_gravity.serialize(rbd->m_gravity);
     377        m_gravity_acceleration.serialize(rbd->m_gravity_acceleration);
     378        m_invInertiaLocal.serialize(rbd->m_invInertiaLocal);
     379        m_totalForce.serialize(rbd->m_totalForce);
     380        m_totalTorque.serialize(rbd->m_totalTorque);
     381        rbd->m_linearDamping = m_linearDamping;
     382        rbd->m_angularDamping = m_angularDamping;
     383        rbd->m_additionalDamping = m_additionalDamping;
     384        rbd->m_additionalDampingFactor = m_additionalDampingFactor;
     385        rbd->m_additionalLinearDampingThresholdSqr = m_additionalLinearDampingThresholdSqr;
     386        rbd->m_additionalAngularDampingThresholdSqr = m_additionalAngularDampingThresholdSqr;
     387        rbd->m_additionalAngularDampingFactor = m_additionalAngularDampingFactor;
     388        rbd->m_linearSleepingThreshold=m_linearSleepingThreshold;
     389        rbd->m_angularSleepingThreshold = m_angularSleepingThreshold;
     390
     391        return btRigidBodyDataName;
     392}
     393
     394
     395
     396void btRigidBody::serializeSingleObject(class btSerializer* serializer) const
     397{
     398        btChunk* chunk = serializer->allocate(calculateSerializeBufferSize(),1);
     399        const char* structType = serialize(chunk->m_oldPtr, serializer);
     400        serializer->finalizeChunk(chunk,structType,BT_RIGIDBODY_CODE,(void*)this);
     401}
     402
     403
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/btRigidBody.h

    r5781 r8284  
    2929extern btScalar gDeactivationTime;
    3030extern bool gDisableDeactivation;
     31
     32#ifdef BT_USE_DOUBLE_PRECISION
     33#define btRigidBodyData btRigidBodyDoubleData
     34#define btRigidBodyDataName     "btRigidBodyDoubleData"
     35#else
     36#define btRigidBodyData btRigidBodyFloatData
     37#define btRigidBodyDataName     "btRigidBodyFloatData"
     38#endif //BT_USE_DOUBLE_PRECISION
     39
     40
     41enum    btRigidBodyFlags
     42{
     43        BT_DISABLE_WORLD_GRAVITY = 1
     44};
    3145
    3246
     
    4660        btVector3               m_angularVelocity;
    4761        btScalar                m_inverseMass;
    48         btScalar                m_angularFactor;
     62        btVector3               m_linearFactor;
    4963
    5064        btVector3               m_gravity;     
     
    7286        //keep track of typed constraints referencing this rigid body
    7387        btAlignedObjectArray<btTypedConstraint*> m_constraintRefs;
     88
     89        int                             m_rigidbodyFlags;
     90       
     91        int                             m_debugBodyId;
     92
     93
     94protected:
     95
     96        ATTRIBUTE_ALIGNED64(btVector3           m_deltaLinearVelocity);
     97        btVector3               m_deltaAngularVelocity;
     98        btVector3               m_angularFactor;
     99        btVector3               m_invMass;
     100        btVector3               m_pushVelocity;
     101        btVector3               m_turnVelocity;
     102
    74103
    75104public:
     
    111140                btScalar                        m_additionalAngularDampingFactor;
    112141
    113                
    114142                btRigidBodyConstructionInfo(    btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia=btVector3(0,0,0)):
    115143                m_mass(mass),
     
    161189        static const btRigidBody*       upcast(const btCollisionObject* colObj)
    162190        {
    163                 if (colObj->getInternalType()==btCollisionObject::CO_RIGID_BODY)
     191                if (colObj->getInternalType()&btCollisionObject::CO_RIGID_BODY)
    164192                        return (const btRigidBody*)colObj;
    165193                return 0;
     
    167195        static btRigidBody*     upcast(btCollisionObject* colObj)
    168196        {
    169                 if (colObj->getInternalType()==btCollisionObject::CO_RIGID_BODY)
     197                if (colObj->getInternalType()&btCollisionObject::CO_RIGID_BODY)
    170198                        return (btRigidBody*)colObj;
    171199                return 0;
     
    220248        void                    setMassProps(btScalar mass, const btVector3& inertia);
    221249       
     250        const btVector3& getLinearFactor() const
     251        {
     252                return m_linearFactor;
     253        }
     254        void setLinearFactor(const btVector3& linearFactor)
     255        {
     256                m_linearFactor = linearFactor;
     257                m_invMass = m_linearFactor*m_inverseMass;
     258        }
    222259        btScalar                getInvMass() const { return m_inverseMass; }
    223260        const btMatrix3x3& getInvInertiaTensorWorld() const {
     
    231268        void                    applyCentralForce(const btVector3& force)
    232269        {
    233                 m_totalForce += force;
     270                m_totalForce += force*m_linearFactor;
    234271        }
    235272
     
    262299        void    applyTorque(const btVector3& torque)
    263300        {
    264                 m_totalTorque += torque;
     301                m_totalTorque += torque*m_angularFactor;
    265302        }
    266303       
     
    268305        {
    269306                applyCentralForce(force);
    270                 applyTorque(rel_pos.cross(force)*m_angularFactor);
     307                applyTorque(rel_pos.cross(force*m_linearFactor));
    271308        }
    272309       
    273310        void applyCentralImpulse(const btVector3& impulse)
    274311        {
    275                 m_linearVelocity += impulse * m_inverseMass;
     312                m_linearVelocity += impulse *m_linearFactor * m_inverseMass;
    276313        }
    277314       
    278315        void applyTorqueImpulse(const btVector3& torque)
    279316        {
    280                         m_angularVelocity += m_invInertiaTensorWorld * torque;
     317                        m_angularVelocity += m_invInertiaTensorWorld * torque * m_angularFactor;
    281318        }
    282319       
     
    288325                        if (m_angularFactor)
    289326                        {
    290                                 applyTorqueImpulse(rel_pos.cross(impulse)*m_angularFactor);
     327                                applyTorqueImpulse(rel_pos.cross(impulse*m_linearFactor));
    291328                        }
    292329                }
    293330        }
    294331
    295         //Optimization for the iterative solver: avoid calculating constant terms involving inertia, normal, relative position
    296         SIMD_FORCE_INLINE void internalApplyImpulse(const btVector3& linearComponent, const btVector3& angularComponent,btScalar impulseMagnitude)
    297         {
    298                 if (m_inverseMass != btScalar(0.))
    299                 {
    300                         m_linearVelocity += linearComponent*impulseMagnitude;
    301                         if (m_angularFactor)
    302                         {
    303                                 m_angularVelocity += angularComponent*impulseMagnitude*m_angularFactor;
    304                         }
    305                 }
    306         }
    307        
    308332        void clearForces()
    309333        {
     
    451475        int     m_frictionSolverType;
    452476
     477        void    setAngularFactor(const btVector3& angFac)
     478        {
     479                m_angularFactor = angFac;
     480        }
     481
    453482        void    setAngularFactor(btScalar angFac)
    454483        {
    455                 m_angularFactor = angFac;
    456         }
    457         btScalar        getAngularFactor() const
     484                m_angularFactor.setValue(angFac,angFac,angFac);
     485        }
     486        const btVector3&        getAngularFactor() const
    458487        {
    459488                return m_angularFactor;
     
    481510        }
    482511
    483         int     m_debugBodyId;
     512        void    setFlags(int flags)
     513        {
     514                m_rigidbodyFlags = flags;
     515        }
     516
     517        int getFlags() const
     518        {
     519                return m_rigidbodyFlags;
     520        }
     521
     522        const btVector3& getDeltaLinearVelocity() const
     523        {
     524                return m_deltaLinearVelocity;
     525        }
     526
     527        const btVector3& getDeltaAngularVelocity() const
     528        {
     529                return m_deltaAngularVelocity;
     530        }
     531
     532        const btVector3& getPushVelocity() const
     533        {
     534                return m_pushVelocity;
     535        }
     536
     537        const btVector3& getTurnVelocity() const
     538        {
     539                return m_turnVelocity;
     540        }
     541
     542
     543        ////////////////////////////////////////////////
     544        ///some internal methods, don't use them
     545               
     546        btVector3& internalGetDeltaLinearVelocity()
     547        {
     548                return m_deltaLinearVelocity;
     549        }
     550
     551        btVector3& internalGetDeltaAngularVelocity()
     552        {
     553                return m_deltaAngularVelocity;
     554        }
     555
     556        const btVector3& internalGetAngularFactor() const
     557        {
     558                return m_angularFactor;
     559        }
     560
     561        const btVector3& internalGetInvMass() const
     562        {
     563                return m_invMass;
     564        }
     565       
     566        btVector3& internalGetPushVelocity()
     567        {
     568                return m_pushVelocity;
     569        }
     570
     571        btVector3& internalGetTurnVelocity()
     572        {
     573                return m_turnVelocity;
     574        }
     575
     576        SIMD_FORCE_INLINE void  internalGetVelocityInLocalPointObsolete(const btVector3& rel_pos, btVector3& velocity ) const
     577        {
     578                velocity = getLinearVelocity()+m_deltaLinearVelocity + (getAngularVelocity()+m_deltaAngularVelocity).cross(rel_pos);
     579        }
     580
     581        SIMD_FORCE_INLINE void  internalGetAngularVelocity(btVector3& angVel) const
     582        {
     583                angVel = getAngularVelocity()+m_deltaAngularVelocity;
     584        }
     585
     586
     587        //Optimization for the iterative solver: avoid calculating constant terms involving inertia, normal, relative position
     588        SIMD_FORCE_INLINE void internalApplyImpulse(const btVector3& linearComponent, const btVector3& angularComponent,const btScalar impulseMagnitude)
     589        {
     590                if (m_inverseMass)
     591                {
     592                        m_deltaLinearVelocity += linearComponent*impulseMagnitude;
     593                        m_deltaAngularVelocity += angularComponent*(impulseMagnitude*m_angularFactor);
     594                }
     595        }
     596
     597        SIMD_FORCE_INLINE void internalApplyPushImpulse(const btVector3& linearComponent, const btVector3& angularComponent,btScalar impulseMagnitude)
     598        {
     599                if (m_inverseMass)
     600                {
     601                        m_pushVelocity += linearComponent*impulseMagnitude;
     602                        m_turnVelocity += angularComponent*(impulseMagnitude*m_angularFactor);
     603                }
     604        }
     605       
     606        void    internalWritebackVelocity()
     607        {
     608                if (m_inverseMass)
     609                {
     610                        setLinearVelocity(getLinearVelocity()+ m_deltaLinearVelocity);
     611                        setAngularVelocity(getAngularVelocity()+m_deltaAngularVelocity);
     612                        //m_deltaLinearVelocity.setZero();
     613                        //m_deltaAngularVelocity .setZero();
     614                        //m_originalBody->setCompanionId(-1);
     615                }
     616        }
     617
     618
     619        void    internalWritebackVelocity(btScalar timeStep);
     620       
     621
     622        ///////////////////////////////////////////////
     623
     624        virtual int     calculateSerializeBufferSize()  const;
     625
     626        ///fills the dataBuffer and returns the struct name (and 0 on failure)
     627        virtual const char*     serialize(void* dataBuffer,  class btSerializer* serializer) const;
     628
     629        virtual void serializeSingleObject(class btSerializer* serializer) const;
     630
    484631};
    485632
     633//@todo add m_optionalMotionState and m_constraintRefs to btRigidBodyData
     634///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     635struct  btRigidBodyFloatData
     636{
     637        btCollisionObjectFloatData      m_collisionObjectData;
     638        btMatrix3x3FloatData            m_invInertiaTensorWorld;
     639        btVector3FloatData              m_linearVelocity;
     640        btVector3FloatData              m_angularVelocity;
     641        btVector3FloatData              m_angularFactor;
     642        btVector3FloatData              m_linearFactor;
     643        btVector3FloatData              m_gravity;     
     644        btVector3FloatData              m_gravity_acceleration;
     645        btVector3FloatData              m_invInertiaLocal;
     646        btVector3FloatData              m_totalForce;
     647        btVector3FloatData              m_totalTorque;
     648        float                                   m_inverseMass;
     649        float                                   m_linearDamping;
     650        float                                   m_angularDamping;
     651        float                                   m_additionalDampingFactor;
     652        float                                   m_additionalLinearDampingThresholdSqr;
     653        float                                   m_additionalAngularDampingThresholdSqr;
     654        float                                   m_additionalAngularDampingFactor;
     655        float                                   m_linearSleepingThreshold;
     656        float                                   m_angularSleepingThreshold;
     657        int                                             m_additionalDamping;
     658};
     659
     660///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
     661struct  btRigidBodyDoubleData
     662{
     663        btCollisionObjectDoubleData     m_collisionObjectData;
     664        btMatrix3x3DoubleData           m_invInertiaTensorWorld;
     665        btVector3DoubleData             m_linearVelocity;
     666        btVector3DoubleData             m_angularVelocity;
     667        btVector3DoubleData             m_angularFactor;
     668        btVector3DoubleData             m_linearFactor;
     669        btVector3DoubleData             m_gravity;     
     670        btVector3DoubleData             m_gravity_acceleration;
     671        btVector3DoubleData             m_invInertiaLocal;
     672        btVector3DoubleData             m_totalForce;
     673        btVector3DoubleData             m_totalTorque;
     674        double                                  m_inverseMass;
     675        double                                  m_linearDamping;
     676        double                                  m_angularDamping;
     677        double                                  m_additionalDampingFactor;
     678        double                                  m_additionalLinearDampingThresholdSqr;
     679        double                                  m_additionalAngularDampingThresholdSqr;
     680        double                                  m_additionalAngularDampingFactor;
     681        double                                  m_linearSleepingThreshold;
     682        double                                  m_angularSleepingThreshold;
     683        int                                             m_additionalDamping;
     684        char    m_padding[4];
     685};
     686
    486687
    487688
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/btSimpleDynamicsWorld.cpp

    r5781 r8284  
    133133void    btSimpleDynamicsWorld::removeRigidBody(btRigidBody* body)
    134134{
    135         removeCollisionObject(body);
    136 }
     135        btCollisionWorld::removeCollisionObject(body);
     136}
     137
     138void    btSimpleDynamicsWorld::removeCollisionObject(btCollisionObject* collisionObject)
     139{
     140        btRigidBody* body = btRigidBody::upcast(collisionObject);
     141        if (body)
     142                removeRigidBody(body);
     143        else
     144                btCollisionWorld::removeCollisionObject(collisionObject);
     145}
     146
    137147
    138148void    btSimpleDynamicsWorld::addRigidBody(btRigidBody* body)
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Dynamics/btSimpleDynamicsWorld.h

    r5781 r8284  
    5858
    5959        virtual void    removeRigidBody(btRigidBody* body);
     60
     61        ///removeCollisionObject will first check if it is a rigid body, if so call removeRigidBody otherwise call btCollisionWorld::removeCollisionObject
     62        virtual void    removeCollisionObject(btCollisionObject* collisionObject);
    6063       
    6164        virtual void    updateAabbs();
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Vehicle/btRaycastVehicle.cpp

    r5781 r8284  
    2323#include "BulletDynamics/ConstraintSolver/btContactConstraint.h"
    2424
    25 static btRigidBody s_fixedObject( 0,0,0);
     25btRigidBody& btActionInterface::getFixedBody()
     26{
     27        static btRigidBody s_fixed(0, 0,0);
     28        s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.)));
     29        return s_fixed;
     30}
    2631
    2732btRaycastVehicle::btRaycastVehicle(const btVehicleTuning& tuning,btRigidBody* chassis,  btVehicleRaycaster* raycaster )
     
    7176        ci.m_bIsFrontWheel = isFrontWheel;
    7277        ci.m_maxSuspensionTravelCm = tuning.m_maxSuspensionTravelCm;
     78        ci.m_maxSuspensionForce = tuning.m_maxSuspensionForce;
    7379
    7480        m_wheelInfo.push_back( btWheelInfo(ci));
     
    187193                wheel.m_raycastInfo.m_isInContact = true;
    188194               
    189                 wheel.m_raycastInfo.m_groundObject = &s_fixedObject;///@todo for driving on dynamic/movable objects!;
     195                wheel.m_raycastInfo.m_groundObject = &getFixedBody();///@todo for driving on dynamic/movable objects!;
    190196                //wheel.m_raycastInfo.m_groundObject = object;
    191197
     
    302308                btScalar suspensionForce = wheel.m_wheelsSuspensionForce;
    303309               
    304                 btScalar gMaxSuspensionForce = btScalar(6000.);
    305                 if (suspensionForce > gMaxSuspensionForce)
    306                 {
    307                         suspensionForce = gMaxSuspensionForce;
     310                if (suspensionForce > wheel.m_maxSuspensionForce)
     311                {
     312                        suspensionForce = wheel.m_maxSuspensionForce;
    308313                }
    309314                btVector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step;
     
    690695                                        btVector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel];
    691696
    692                                         rel_pos[m_indexForwardAxis] *= wheelInfo.m_rollInfluence;
     697                                        rel_pos[m_indexUpAxis] *= wheelInfo.m_rollInfluence;
    693698                                        m_chassisBody->applyImpulse(sideImp,rel_pos);
    694699
     
    709714        for (int v=0;v<this->getNumWheels();v++)
    710715        {
    711                 btVector3 wheelColor(0,255,255);
     716                btVector3 wheelColor(0,1,1);
    712717                if (getWheelInfo(v).m_raycastInfo.m_isInContact)
    713718                {
    714                         wheelColor.setValue(0,0,255);
     719                        wheelColor.setValue(0,0,1);
    715720                } else
    716721                {
    717                         wheelColor.setValue(255,0,255);
     722                        wheelColor.setValue(1,0,1);
    718723                }
    719724
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Vehicle/btRaycastVehicle.h

    r5781 r8284  
    3030                btAlignedObjectArray<btScalar>  m_forwardImpulse;
    3131                btAlignedObjectArray<btScalar>  m_sideImpulse;
     32       
     33                ///backwards compatibility
     34                int     m_userConstraintType;
     35                int     m_userConstraintId;
    3236
    3337public:
     
    4145                                m_suspensionDamping(btScalar(0.88)),
    4246                                m_maxSuspensionTravelCm(btScalar(500.)),
    43                                 m_frictionSlip(btScalar(10.5))
     47                                m_frictionSlip(btScalar(10.5)),
     48                                m_maxSuspensionForce(btScalar(6000.))
    4449                        {
    4550                        }
     
    4954                        btScalar        m_maxSuspensionTravelCm;
    5055                        btScalar        m_frictionSlip;
     56                        btScalar        m_maxSuspensionForce;
    5157
    5258                };
     
    7985        virtual void updateAction( btCollisionWorld* collisionWorld, btScalar step)
    8086        {
     87        (void) collisionWorld;
    8188                updateVehicle(step);
    8289        }
     
    189196
    190197
     198        ///backwards compatibility
     199        int getUserConstraintType() const
     200        {
     201                return m_userConstraintType ;
     202        }
     203
     204        void    setUserConstraintType(int userConstraintType)
     205        {
     206                m_userConstraintType = userConstraintType;
     207        };
     208
     209        void    setUserConstraintId(int uid)
     210        {
     211                m_userConstraintId = uid;
     212        }
     213
     214        int getUserConstraintId() const
     215        {
     216                return m_userConstraintId;
     217        }
    191218
    192219};
  • code/branches/kicklib2/src/external/bullet/BulletDynamics/Vehicle/btWheelInfo.h

    r5781 r8284  
    3030        btScalar                m_wheelsDampingRelaxation;
    3131        btScalar                m_frictionSlip;
     32        btScalar                m_maxSuspensionForce;
    3233        bool m_bIsFrontWheel;
    3334       
     
    6970        btScalar        m_deltaRotation;
    7071        btScalar        m_rollInfluence;
     72        btScalar        m_maxSuspensionForce;
    7173
    7274        btScalar        m_engineForce;
     
    100102                m_rollInfluence = btScalar(0.1);
    101103                m_bIsFrontWheel = ci.m_bIsFrontWheel;
     104                m_maxSuspensionForce = ci.m_maxSuspensionForce;
    102105
    103106        }
  • code/branches/kicklib2/src/external/bullet/BulletLicense.txt

    r5781 r8284  
    11/*
    2 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
     2Copyright (c) 2003-2010 Erwin Coumans  http://continuousphysics.com/Bullet/
    33
    44This software is provided 'as-is', without any express or implied warranty.
     
    1414
    1515
    16 Free for commercial use, but please mail bullet@erwincoumans.com to report projects, and join the forum at
    17 www.continuousphysics.com/Bullet/phpBB2
     16Free for commercial use, please report projects in the forum at http://www.bulletphysics.org
     17
     18In case you want to display a Bullet logo in your software: you can download the Bullet logo in various vector formats and high resolution at the download section in http://bullet.googlecode.com
  • code/branches/kicklib2/src/external/bullet/CMakeLists.txt

    r5929 r8284  
    3131  NO_DLL_INTERFACE
    3232  VERSION
    33     2.74
     33    2.77
    3434  SOURCE_FILES
    3535    ${BULLET_FILES}
  • code/branches/kicklib2/src/external/bullet/ChangeLog

    r5781 r8284  
    22Primary author and maintainer: Erwin Coumans
    33
    4 Todo: update changelog from April - July 2008
    5 See http://code.google.com/p/bullet/source/list for more complete log in Subversion
     4This ChangeLog is incomplete, for an up-to-date list of all fixed issues see http://bullet.googlecode.com
     5using http://tinyurl.com/yabmjjj
     6
     7
     82010 September 21
     9        - Bullet 2.77 release based on revision 2218
     10        - Added Visual Studio project files for OpenCL and Direct Compute in msvc folder
     11       
     122010 September 7
     13        - autotools now uses CamelCase naming for libraryes just like cmake:
     14        libbulletdynamics -> libBulletDynamics, libbulletmath -> libLinearMath
     15
     162010 July 21
     17        - Preparing for Bullet 2.77 release, around revision r2135
     18        - Added an OpenCL particle demo, running on NVidia, AMD and MiniCL
     19        Thanks to NVidia for the original particle demo from their OpenCL SDK
     20        - Added GPU deformable object solvers for OpenCL and DirectCompute, and a DirectX 11 cloth demo
     21        Thanks to AMD
     22        - Create a separate library for MiniCL,
     23        MiniCL is a rudimentary OpenCL wrapper that allows to compile OpenCL kernels for multi-core CPU, using Win32 Threads or Posix
     24        - Moved vectormath into Bullet/src, and added a SSE implementation
     25        - Added a btParallelConstraintSolver, mainly for PlayStation 3 Cell SPUs (although it runs fine on CPU too)
     26
     272010 March 6
     28        - Dynamica Maya plugin (and COLLADA support) is moved to http://dynamica.googlecode.com
     29
     302010 February
     31        - Bullet 2.76 release, revision 2010
     32        - support for the .bullet binary file format
     33        - btInternalEdgeUtility to adjust unwanted collisions against internal triangle edges
     34        - Improved Maya Dynamica plugin with better constraint authoring and .bullet file export
     35
     36
     372009 September 17
     38        - Minor update to Bullet 2.75 release, revision 1776
     39        - Support for btConvex2dShape, check out Bullet/Demos/Box2dDemo
     40        - Fixes in build systems
     41        - Minor fix in btGjkPairDetector
     42        - Initialize world transform for btCollisionShape in constructor
     43
     44
     452009 September 6
     46        - Bullet 2.75 release
     47        - Added SPH fluid simulation in Extras, not integrated with rigid body / soft body yet
     48        Thanks to Rama Hoetzlein to make this contribution available under the ZLib license
     49        - add special capsule-capsule collider code in btConvexConvexCollisionAlgorithm, to speed up capsule-ragdolls
     50        - soft body improvement: faster building of bending constraints
     51        - soft body improvement: allow to disable/enable cluster self-collision
     52        - soft body fix: 'exploding' soft bodies when using cluster collision
     53        - fix some degenerate cases in continuous convex cast, could impact ray cast/convex cast
     54        Thanks to Jacob Langford for the report and reproduction cases, see http://code.google.com/p/bullet/issues/detail?id=250&can=1&start=200
     55        - re-enabled split impulse
     56        - added btHinge2Constraint, btUniversalConstraint, btGeneric6DofSpringConstraint
     57        - demonstrate 2D physics with 2D/3D object interaction
     58       
     59
     602008 December 2
     61        - Fix contact refresh issues with btCompoundShape, introduced with btDbvt acceleration structure in btCompoundCollisionAlgorithm
     62        - Made btSequentialImpulseConstraintSolver 100% compatible with ODE quickstep
     63        constraints can use 'solveConstraint' method or 'getInfo/getInfo2'
     64
     652008 November 30
     66        - Add highly optimized SIMD branchless PGS/SI solver innerloop
    667
    7682008 November 12
  • code/branches/kicklib2/src/external/bullet/LinearMath/CMakeLists.txt

    r5929 r8284  
    22
    33COMPILATION_BEGIN BulletLinearMathCompilation.cpp
    4                 btConvexHull.cpp
    5                 btQuickprof.cpp
    6                 btGeometryUtil.cpp
    7                 btAlignedAllocator.cpp
     4        btAlignedAllocator.cpp
     5        btConvexHull.cpp
     6        btGeometryUtil.cpp
     7        btQuickprof.cpp
     8        btSerializer.cpp
    89COMPILATION_END
    910
    10                 # Headers
    11                 btAlignedObjectArray.h
    12                 btList.h
    13                 btPoolAllocator.h
    14                 btRandom.h
    15                 btVector3.h
    16                 btDefaultMotionState.h
    17                 btMatrix3x3.h
    18                 btQuadWord.h
    19                 btHashMap.h
    20                 btScalar.h
    21                 btAabbUtil2.h
    22                 btConvexHull.h
    23                 btMinMax.h
    24                 btQuaternion.h
    25                 btStackAlloc.h
    26                 btGeometryUtil.h
    27                 btMotionState.h
    28                 btTransform.h
    29                 btAlignedAllocator.h
    30                 btIDebugDraw.h
    31                 btQuickprof.h
    32                 btTransformUtil.h
     11        # Headers
     12        btAabbUtil2.h
     13        btAlignedAllocator.h
     14        btAlignedObjectArray.h
     15        btConvexHull.h
     16        btDefaultMotionState.h
     17        btGeometryUtil.h
     18        btHashMap.h
     19        btIDebugDraw.h
     20        btList.h
     21        btMatrix3x3.h
     22        btMinMax.h
     23        btMotionState.h
     24        btPoolAllocator.h
     25        btQuadWord.h
     26        btQuaternion.h
     27        btQuickprof.h
     28        btRandom.h
     29        btScalar.h
     30        btSerializer.h
     31        btStackAlloc.h
     32        btTransform.h
     33        btTransformUtil.h
     34        btVector3.h
    3335)
  • code/branches/kicklib2/src/external/bullet/LinearMath/btAlignedAllocator.cpp

    r5781 r8284  
    161161{
    162162        gNumAlignedAllocs++;
    163   void* ptr;
    164 #if defined (BT_HAS_ALIGNED_ALLOCATOR) || defined(__CELLOS_LV2__)
     163        void* ptr;
    165164        ptr = sAlignedAllocFunc(size, alignment);
    166 #else
    167   char *real;
    168   unsigned long offset;
    169 
    170   real = (char *)sAllocFunc(size + sizeof(void *) + (alignment-1));
    171   if (real) {
    172     offset = (alignment - (unsigned long)(real + sizeof(void *))) & (alignment-1);
    173     ptr = (void *)((real + sizeof(void *)) + offset);
    174     *((void **)(ptr)-1) = (void *)(real);
    175   } else {
    176     ptr = (void *)(real);
    177   }
    178 #endif  // defined (BT_HAS_ALIGNED_ALLOCATOR) || defined(__CELLOS_LV2__)
    179165//      printf("btAlignedAllocInternal %d, %x\n",size,ptr);
    180166        return ptr;
     
    190176        gNumAlignedFree++;
    191177//      printf("btAlignedFreeInternal %x\n",ptr);
    192 #if defined (BT_HAS_ALIGNED_ALLOCATOR) || defined(__CELLOS_LV2__)
    193178        sAlignedFreeFunc(ptr);
    194 #else
    195   void* real;
    196 
    197   if (ptr) {
    198     real = *((void **)(ptr)-1);
    199     sFreeFunc(real);
    200   }
    201 #endif  // defined (BT_HAS_ALIGNED_ALLOCATOR) || defined(__CELLOS_LV2__)
    202179}
    203180
  • code/branches/kicklib2/src/external/bullet/LinearMath/btAlignedObjectArray.h

    r5781 r8284  
    139139                }
    140140               
     141                SIMD_FORCE_INLINE const T& at(int n) const
     142                {
     143                        return m_data[n];
     144                }
     145
     146                SIMD_FORCE_INLINE T& at(int n)
     147                {
     148                        return m_data[n];
     149                }
     150
    141151                SIMD_FORCE_INLINE const T& operator[](int n) const
    142152                {
     
    172182                        int curSize = size();
    173183
    174                         if (newsize < size())
    175                         {
    176                                 for(int i = curSize; i < newsize; i++)
     184                        if (newsize < curSize)
     185                        {
     186                                for(int i = newsize; i < curSize; i++)
    177187                                {
    178188                                        m_data[i].~T();
     
    196206                }
    197207       
     208                SIMD_FORCE_INLINE       T&  expandNonInitializing( )
     209                {       
     210                        int sz = size();
     211                        if( sz == capacity() )
     212                        {
     213                                reserve( allocSize(size()) );
     214                        }
     215                        m_size++;
     216
     217                        return m_data[sz];             
     218                }
     219
    198220
    199221                SIMD_FORCE_INLINE       T&  expand( const T& fillValue=T())
     
    438460        }
    439461
     462        void copyFromArray(const btAlignedObjectArray& otherArray)
     463        {
     464                int otherSize = otherArray.size();
     465                resize (otherSize);
     466                otherArray.copy(0, otherSize, m_data);
     467        }
     468
    440469};
    441470
  • code/branches/kicklib2/src/external/bullet/LinearMath/btConvexHull.cpp

    r5781 r8284  
    1717
    1818#include "btConvexHull.h"
    19 #include "LinearMath/btAlignedObjectArray.h"
    20 #include "LinearMath/btMinMax.h"
    21 #include "LinearMath/btVector3.h"
     19#include "btAlignedObjectArray.h"
     20#include "btMinMax.h"
     21#include "btVector3.h"
    2222
    2323
     
    9797                                static btVector3 dif;
    9898                dif = p1-p0;
    99                                 btScalar dn= dot(plane.normal,dif);
    100                                 btScalar t = -(plane.dist+dot(plane.normal,p0) )/dn;
     99                                btScalar dn= btDot(plane.normal,dif);
     100                                btScalar t = -(plane.dist+btDot(plane.normal,p0) )/dn;
    101101                                return p0 + (dif*t);
    102102}
     
    104104btVector3 PlaneProject(const btPlane &plane, const btVector3 &point)
    105105{
    106         return point - plane.normal * (dot(point,plane.normal)+plane.dist);
     106        return point - plane.normal * (btDot(point,plane.normal)+plane.dist);
    107107}
    108108
     
    111111        // return the normal of the triangle
    112112        // inscribed by v0, v1, and v2
    113         btVector3 cp=cross(v1-v0,v2-v1);
     113        btVector3 cp=btCross(v1-v0,v2-v1);
    114114        btScalar m=cp.length();
    115115        if(m==0) return btVector3(1,0,0);
     
    121121{
    122122        static btVector3 cp;
    123         cp = cross(udir,vdir).normalized();
    124 
    125         btScalar distu = -dot(cp,ustart);
    126         btScalar distv = -dot(cp,vstart);
     123        cp = btCross(udir,vdir).normalized();
     124
     125        btScalar distu = -btDot(cp,ustart);
     126        btScalar distv = -btDot(cp,vstart);
    127127        btScalar dist = (btScalar)fabs(distu-distv);
    128128        if(upoint)
    129129                {
    130130                btPlane plane;
    131                 plane.normal = cross(vdir,cp).normalized();
    132                 plane.dist = -dot(plane.normal,vstart);
     131                plane.normal = btCross(vdir,cp).normalized();
     132                plane.dist = -btDot(plane.normal,vstart);
    133133                *upoint = PlaneLineIntersection(plane,ustart,ustart+udir);
    134134        }
     
    136136                {
    137137                btPlane plane;
    138                 plane.normal = cross(udir,cp).normalized();
    139                 plane.dist = -dot(plane.normal,ustart);
     138                plane.normal = btCross(udir,cp).normalized();
     139                plane.dist = -btDot(plane.normal,ustart);
    140140                *vpoint = PlaneLineIntersection(plane,vstart,vstart+vdir);
    141141        }
     
    171171int PlaneTest(const btPlane &p, const btVector3 &v);
    172172int PlaneTest(const btPlane &p, const btVector3 &v) {
    173         btScalar a  = dot(v,p.normal)+p.dist;
     173        btScalar a  = btDot(v,p.normal)+p.dist;
    174174        int   flag = (a>planetestepsilon)?OVER:((a<-planetestepsilon)?UNDER:COPLANAR);
    175175        return flag;
     
    229229                if(allow[i])
    230230                {
    231                         if(m==-1 || dot(p[i],dir)>dot(p[m],dir))
     231                        if(m==-1 || btDot(p[i],dir)>btDot(p[m],dir))
    232232                                m=i;
    233233                }
     
    239239btVector3 orth(const btVector3 &v)
    240240{
    241         btVector3 a=cross(v,btVector3(0,0,1));
    242         btVector3 b=cross(v,btVector3(0,1,0));
     241        btVector3 a=btCross(v,btVector3(0,0,1));
     242        btVector3 b=btCross(v,btVector3(0,1,0));
    243243        if (a.length() > b.length())
    244244        {
     
    259259                if(allow[m]==3) return m;
    260260                T u = orth(dir);
    261                 T v = cross(u,dir);
     261                T v = btCross(u,dir);
    262262                int ma=-1;
    263263                for(btScalar x = btScalar(0.0) ; x<= btScalar(360.0) ; x+= btScalar(45.0))
     
    314314{
    315315        btVector3 n=TriNormal(vertices[t[0]],vertices[t[1]],vertices[t[2]]);
    316         return (dot(n,p-vertices[t[0]]) > epsilon); // EPSILON???
     316        return (btDot(n,p-vertices[t[0]]) > epsilon); // EPSILON???
    317317}
    318318int hasedge(const int3 &t, int a,int b);
     
    496496        if(p0==p1 || basis[0]==btVector3(0,0,0))
    497497                return int4(-1,-1,-1,-1);
    498         basis[1] = cross(btVector3(     btScalar(1),btScalar(0.02), btScalar(0)),basis[0]);
    499         basis[2] = cross(btVector3(btScalar(-0.02),     btScalar(1), btScalar(0)),basis[0]);
     498        basis[1] = btCross(btVector3(     btScalar(1),btScalar(0.02), btScalar(0)),basis[0]);
     499        basis[2] = btCross(btVector3(btScalar(-0.02),     btScalar(1), btScalar(0)),basis[0]);
    500500        if (basis[1].length() > basis[2].length())
    501501        {
     
    513513                return int4(-1,-1,-1,-1);
    514514        basis[1] = verts[p2] - verts[p0];
    515         basis[2] = cross(basis[1],basis[0]).normalized();
     515        basis[2] = btCross(basis[1],basis[0]).normalized();
    516516        int p3 = maxdirsterid(verts,verts_count,basis[2],allow);
    517517        if(p3==p0||p3==p1||p3==p2) p3 = maxdirsterid(verts,verts_count,-basis[2],allow);
     
    519519                return int4(-1,-1,-1,-1);
    520520        btAssert(!(p0==p1||p0==p2||p0==p3||p1==p2||p1==p3||p2==p3));
    521         if(dot(verts[p3]-verts[p0],cross(verts[p1]-verts[p0],verts[p2]-verts[p0])) <0) {Swap(p2,p3);}
     521        if(btDot(verts[p3]-verts[p0],btCross(verts[p1]-verts[p0],verts[p2]-verts[p0])) <0) {Swap(p2,p3);}
    522522        return int4(p0,p1,p2,p3);
    523523}
     
    565565                btVector3 n=TriNormal(verts[(*t)[0]],verts[(*t)[1]],verts[(*t)[2]]);
    566566                t->vmax = maxdirsterid(verts,verts_count,n,allow);
    567                 t->rise = dot(n,verts[t->vmax]-verts[(*t)[0]]);
     567                t->rise = btDot(n,verts[t->vmax]-verts[(*t)[0]]);
    568568        }
    569569        btHullTriangle *te;
     
    593593                        if(!hasvert(*m_tris[j],v)) break;
    594594                        int3 nt=*m_tris[j];
    595                         if(above(verts,nt,center,btScalar(0.01)*epsilon)  || cross(verts[nt[1]]-verts[nt[0]],verts[nt[2]]-verts[nt[1]]).length()< epsilon*epsilon*btScalar(0.1) )
     595                        if(above(verts,nt,center,btScalar(0.01)*epsilon)  || btCross(verts[nt[1]]-verts[nt[0]],verts[nt[2]]-verts[nt[1]]).length()< epsilon*epsilon*btScalar(0.1) )
    596596                        {
    597597                                btHullTriangle *nb = m_tris[m_tris[j]->n[0]];
     
    615615                        else
    616616                        {
    617                                 t->rise = dot(n,verts[t->vmax]-verts[(*t)[0]]);
     617                                t->rise = btDot(n,verts[t->vmax]-verts[(*t)[0]]);
    618618                        }
    619619                }
     
    877877        vcount = 0;
    878878
    879         btScalar recip[3];
     879        btScalar recip[3]={0.f,0.f,0.f};
    880880
    881881        if ( scale )
     
    10121012                                btScalar z = v[2];
    10131013
    1014                                 btScalar dx = fabsf(x - px );
    1015                                 btScalar dy = fabsf(y - py );
    1016                                 btScalar dz = fabsf(z - pz );
     1014                                btScalar dx = btFabs(x - px );
     1015                                btScalar dy = btFabs(y - py );
     1016                                btScalar dz = btFabs(z - pz );
    10171017
    10181018                                if ( dx < normalepsilon && dy < normalepsilon && dz < normalepsilon )
     
    11361136        ocount = 0;
    11371137
    1138         for (i=0; i<indexcount; i++)
     1138        for (i=0; i<int (indexcount); i++)
    11391139        {
    11401140                unsigned int v = indices[i]; // original array index
     
    11571157                        for (int k=0;k<m_vertexIndexMapping.size();k++)
    11581158                        {
    1159                                 if (tmpIndices[k]==v)
     1159                                if (tmpIndices[k]==int(v))
    11601160                                        m_vertexIndexMapping[k]=ocount;
    11611161                        }
  • code/branches/kicklib2/src/external/bullet/LinearMath/btConvexHull.h

    r5781 r8284  
    2020#define CD_HULL_H
    2121
    22 #include "LinearMath/btVector3.h"
    23 #include "LinearMath/btAlignedObjectArray.h"
     22#include "btVector3.h"
     23#include "btAlignedObjectArray.h"
    2424
    2525typedef btAlignedObjectArray<unsigned int> TUIntArray;
  • code/branches/kicklib2/src/external/bullet/LinearMath/btDefaultMotionState.h

    r5781 r8284  
    11#ifndef DEFAULT_MOTION_STATE_H
    22#define DEFAULT_MOTION_STATE_H
     3
     4#include "btMotionState.h"
    35
    46///The btDefaultMotionState provides a common implementation to synchronize world transforms with offsets.
  • code/branches/kicklib2/src/external/bullet/LinearMath/btHashMap.h

    r5781 r8284  
    44#include "btAlignedObjectArray.h"
    55
     6///very basic hashable string implementation, compatible with btHashMap
     7struct btHashString
     8{
     9        const char* m_string;
     10        unsigned int    m_hash;
     11
     12        SIMD_FORCE_INLINE       unsigned int getHash()const
     13        {
     14                return m_hash;
     15        }
     16
     17        btHashString(const char* name)
     18                :m_string(name)
     19        {
     20                /* magic numbers from http://www.isthe.com/chongo/tech/comp/fnv/ */
     21                static const unsigned int  InitialFNV = 2166136261u;
     22                static const unsigned int FNVMultiple = 16777619u;
     23
     24                /* Fowler / Noll / Vo (FNV) Hash */
     25                unsigned int hash = InitialFNV;
     26               
     27                for(int i = 0; m_string[i]; i++)
     28                {
     29                        hash = hash ^ (m_string[i]);       /* xor  the low 8 bits */
     30                        hash = hash * FNVMultiple;  /* multiply by the magic number */
     31                }
     32                m_hash = hash;
     33        }
     34
     35        int portableStringCompare(const char* src,      const char* dst) const
     36        {
     37                        int ret = 0 ;
     38
     39                        while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst)
     40                                        ++src, ++dst;
     41
     42                        if ( ret < 0 )
     43                                        ret = -1 ;
     44                        else if ( ret > 0 )
     45                                        ret = 1 ;
     46
     47                        return( ret );
     48        }
     49
     50        bool equals(const btHashString& other) const
     51        {
     52                return (m_string == other.m_string) ||
     53                        (0==portableStringCompare(m_string,other.m_string));
     54
     55        }
     56
     57};
     58
    659const int BT_HASH_NULL=0xffffffff;
     60
     61
     62class btHashInt
     63{
     64        int     m_uid;
     65public:
     66        btHashInt(int uid)      :m_uid(uid)
     67        {
     68        }
     69
     70        int     getUid1() const
     71        {
     72                return m_uid;
     73        }
     74
     75        void    setUid1(int uid)
     76        {
     77                m_uid = uid;
     78        }
     79
     80        bool equals(const btHashInt& other) const
     81        {
     82                return getUid1() == other.getUid1();
     83        }
     84        //to our success
     85        SIMD_FORCE_INLINE       unsigned int getHash()const
     86        {
     87                int key = m_uid;
     88                // Thomas Wang's hash
     89                key += ~(key << 15);    key ^=  (key >> 10);    key +=  (key << 3);     key ^=  (key >> 6);     key += ~(key << 11);    key ^=  (key >> 16);
     90                return key;
     91        }
     92};
     93
     94
     95
     96class btHashPtr
     97{
     98
     99        union
     100        {
     101                const void*     m_pointer;
     102                int     m_hashValues[2];
     103        };
     104
     105public:
     106
     107        btHashPtr(const void* ptr)
     108                :m_pointer(ptr)
     109        {
     110        }
     111
     112        const void*     getPointer() const
     113        {
     114                return m_pointer;
     115        }
     116
     117        bool equals(const btHashPtr& other) const
     118        {
     119                return getPointer() == other.getPointer();
     120        }
     121
     122        //to our success
     123        SIMD_FORCE_INLINE       unsigned int getHash()const
     124        {
     125                const bool VOID_IS_8 = ((sizeof(void*)==8));
     126               
     127                int key = VOID_IS_8? m_hashValues[0]+m_hashValues[1] : m_hashValues[0];
     128       
     129                // Thomas Wang's hash
     130                key += ~(key << 15);    key ^=  (key >> 10);    key +=  (key << 3);     key ^=  (key >> 6);     key += ~(key << 11);    key ^=  (key >> 16);
     131                return key;
     132        }
     133
     134       
     135};
     136
     137
     138template <class Value>
     139class btHashKeyPtr
     140{
     141        int     m_uid;
     142public:
     143
     144        btHashKeyPtr(int uid)    :m_uid(uid)
     145        {
     146        }
     147
     148        int     getUid1() const
     149        {
     150                return m_uid;
     151        }
     152
     153        bool equals(const btHashKeyPtr<Value>& other) const
     154        {
     155                return getUid1() == other.getUid1();
     156        }
     157
     158        //to our success
     159        SIMD_FORCE_INLINE       unsigned int getHash()const
     160        {
     161                int key = m_uid;
     162                // Thomas Wang's hash
     163                key += ~(key << 15);    key ^=  (key >> 10);    key +=  (key << 3);     key ^=  (key >> 6);     key += ~(key << 11);    key ^=  (key >> 16);
     164                return key;
     165        }
     166
     167       
     168};
     169
    7170
    8171template <class Value>
     
    12175public:
    13176
    14         btHashKey(int uid)
    15                 :m_uid(uid)
    16         {
    17         }
    18 
    19         int     getUid() const
     177        btHashKey(int uid)      :m_uid(uid)
     178        {
     179        }
     180
     181        int     getUid1() const
    20182        {
    21183                return m_uid;
    22184        }
    23185
     186        bool equals(const btHashKey<Value>& other) const
     187        {
     188                return getUid1() == other.getUid1();
     189        }
    24190        //to our success
    25191        SIMD_FORCE_INLINE       unsigned int getHash()const
     
    27193                int key = m_uid;
    28194                // Thomas Wang's hash
    29                 key += ~(key << 15);
    30                 key ^=  (key >> 10);
    31                 key +=  (key << 3);
    32                 key ^=  (key >> 6);
    33                 key += ~(key << 11);
    34                 key ^=  (key >> 16);
     195                key += ~(key << 15);    key ^=  (key >> 10);    key +=  (key << 3);     key ^=  (key >> 6);     key += ~(key << 11);    key ^=  (key >> 16);
    35196                return key;
    36197        }
    37 
    38         btHashKey       getKey(const Value& value) const
    39         {
    40                 return btHashKey(value.getUid());
    41         }
    42 };
    43 
    44 
    45 template <class Value>
    46 class btHashKeyPtr
    47 {
    48         int     m_uid;
    49 public:
    50 
    51         btHashKeyPtr(int uid)
    52                 :m_uid(uid)
    53         {
    54         }
    55 
    56         int     getUid() const
    57         {
    58                 return m_uid;
    59         }
    60 
    61         //to our success
    62         SIMD_FORCE_INLINE       unsigned int getHash()const
    63         {
    64                 int key = m_uid;
    65                 // Thomas Wang's hash
    66                 key += ~(key << 15);
    67                 key ^=  (key >> 10);
    68                 key +=  (key << 3);
    69                 key ^=  (key >> 6);
    70                 key += ~(key << 11);
    71                 key ^=  (key >> 16);
    72                 return key;
    73         }
    74 
    75         btHashKeyPtr    getKey(const Value& value) const
    76         {
    77                 return btHashKeyPtr(value->getUid());
    78         }
    79 };
     198};
     199
    80200
    81201///The btHashMap template class implements a generic and lightweight hashmap.
     
    85205{
    86206
     207protected:
    87208        btAlignedObjectArray<int>               m_hashTable;
    88209        btAlignedObjectArray<int>               m_next;
     210       
    89211        btAlignedObjectArray<Value>             m_valueArray;
    90 
    91 
    92 
    93         void    growTables(const Key& key)
     212        btAlignedObjectArray<Key>               m_keyArray;
     213
     214        void    growTables(const Key& /*key*/)
    94215        {
    95216                int newCapacity = m_valueArray.capacity();
     
    116237                        for(i=0;i<curHashtableSize;i++)
    117238                        {
    118                                 const Value& value = m_valueArray[i];
    119 
    120                                 int     hashValue = key.getKey(value).getHash() & (m_valueArray.capacity()-1);  // New hash value with new mask
     239                                //const Value& value = m_valueArray[i];
     240                                //const Key& key = m_keyArray[i];
     241
     242                                int     hashValue = m_keyArray[i].getHash() & (m_valueArray.capacity()-1);      // New hash value with new mask
    121243                                m_next[i] = m_hashTable[hashValue];
    122244                                m_hashTable[hashValue] = i;
     
    131253        void insert(const Key& key, const Value& value) {
    132254                int hash = key.getHash() & (m_valueArray.capacity()-1);
    133                 //don't add it if it is already there
    134                 if (find(key))
    135                 {
     255
     256                //replace value if the key is already there
     257                int index = findIndex(key);
     258                if (index != BT_HASH_NULL)
     259                {
     260                        m_valueArray[index]=value;
    136261                        return;
    137262                }
     263
    138264                int count = m_valueArray.size();
    139265                int oldCapacity = m_valueArray.capacity();
    140266                m_valueArray.push_back(value);
     267                m_keyArray.push_back(key);
     268
    141269                int newCapacity = m_valueArray.capacity();
    142270                if (oldCapacity < newCapacity)
     
    192320                {
    193321                        m_valueArray.pop_back();
     322                        m_keyArray.pop_back();
    194323                        return;
    195324                }
    196325
    197326                // Remove the last pair from the hash table.
    198                 const Value* lastValue = &m_valueArray[lastPairIndex];
    199                 int lastHash = key.getKey(*lastValue).getHash() & (m_valueArray.capacity()-1);
     327                int lastHash = m_keyArray[lastPairIndex].getHash() & (m_valueArray.capacity()-1);
    200328
    201329                index = m_hashTable[lastHash];
     
    221349                // Copy the last pair into the remove pair's spot.
    222350                m_valueArray[pairIndex] = m_valueArray[lastPairIndex];
     351                m_keyArray[pairIndex] = m_keyArray[lastPairIndex];
    223352
    224353                // Insert the last pair into the hash table
     
    227356
    228357                m_valueArray.pop_back();
     358                m_keyArray.pop_back();
    229359
    230360        }
     
    277407        int     findIndex(const Key& key) const
    278408        {
    279                 int hash = key.getHash() & (m_valueArray.capacity()-1);
    280 
    281                 if (hash >= m_hashTable.size())
     409                unsigned int hash = key.getHash() & (m_valueArray.capacity()-1);
     410
     411                if (hash >= (unsigned int)m_hashTable.size())
    282412                {
    283413                        return BT_HASH_NULL;
     
    285415
    286416                int index = m_hashTable[hash];
    287                 while ((index != BT_HASH_NULL) && (key.getUid() == key.getKey(m_valueArray[index]).getUid()) == false)
     417                while ((index != BT_HASH_NULL) && key.equals(m_keyArray[index]) == false)
    288418                {
    289419                        index = m_next[index];
     
    297427                m_next.clear();
    298428                m_valueArray.clear();
     429                m_keyArray.clear();
    299430        }
    300431
  • code/branches/kicklib2/src/external/bullet/LinearMath/btIDebugDraw.h

    r5781 r8284  
    11/*
    2 Copyright (c) 2005 Gino van den Bergen / Erwin Coumans http://continuousphysics.com
    3 
    4 Permission is hereby granted, free of charge, to any person or organization
    5 obtaining a copy of the software and accompanying documentation covered by
    6 this license (the "Software") to use, reproduce, display, distribute,
    7 execute, and transmit the Software, and to prepare derivative works of the
    8 Software, and to permit third-parties to whom the Software is furnished to
    9 do so, all subject to the following:
    10 
    11 The copyright notices in the Software and this entire statement, including
    12 the above license grant, this restriction and the following disclaimer,
    13 must be included in all copies of the Software, in whole or in part, and
    14 all derivative works of the Software, unless such copies or derivative
    15 works are solely in the form of machine-executable object code generated by
    16 a source language processor.
    17 
    18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    20 FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
    21 SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
    22 FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
    23 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    24 DEALINGS IN THE SOFTWARE.
     2Bullet Continuous Collision Detection and Physics Library
     3Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org
     4
     5This software is provided 'as-is', without any express or implied warranty.
     6In no event will the authors be held liable for any damages arising from the use of this software.
     7Permission is granted to anyone to use this software for any purpose,
     8including commercial applications, and to alter it and redistribute it freely,
     9subject to the following restrictions:
     10
     111. 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.
     122. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
     133. This notice may not be removed or altered from any source distribution.
    2514*/
    2615
     
    3625///Typical use case: create a debug drawer object, and assign it to a btCollisionWorld or btDynamicsWorld using setDebugDrawer and call debugDrawWorld.
    3726///A class that implements the btIDebugDraw interface has to implement the drawLine method at a minimum.
     27///For color arguments the X,Y,Z components refer to Red, Green and Blue each in the range [0..1]
    3828class   btIDebugDraw
    3929{
     
    5646                DBG_DrawConstraints = (1 << 11),
    5747                DBG_DrawConstraintLimits = (1 << 12),
     48                DBG_FastWireframe = (1<<13),
    5849                DBG_MAX_DEBUG_DRAW_MODE
    5950        };
     
    6152        virtual ~btIDebugDraw() {};
    6253
     54        virtual void    drawLine(const btVector3& from,const btVector3& to,const btVector3& color)=0;
     55               
    6356        virtual void    drawLine(const btVector3& from,const btVector3& to, const btVector3& fromColor, const btVector3& toColor)
    6457        {
     58        (void) toColor;
    6559                drawLine (from, to, fromColor);
    6660        }
    6761
    68         virtual void    drawBox (const btVector3& boxMin, const btVector3& boxMax, const btVector3& color, btScalar alpha)
    69         {
    70         }
    71 
     62        virtual void    drawSphere(btScalar radius, const btTransform& transform, const btVector3& color)
     63        {
     64                btVector3 start = transform.getOrigin();
     65
     66                const btVector3 xoffs = transform.getBasis() * btVector3(radius,0,0);
     67                const btVector3 yoffs = transform.getBasis() * btVector3(0,radius,0);
     68                const btVector3 zoffs = transform.getBasis() * btVector3(0,0,radius);
     69
     70                // XY
     71                drawLine(start-xoffs, start+yoffs, color);
     72                drawLine(start+yoffs, start+xoffs, color);
     73                drawLine(start+xoffs, start-yoffs, color);
     74                drawLine(start-yoffs, start-xoffs, color);
     75
     76                // XZ
     77                drawLine(start-xoffs, start+zoffs, color);
     78                drawLine(start+zoffs, start+xoffs, color);
     79                drawLine(start+xoffs, start-zoffs, color);
     80                drawLine(start-zoffs, start-xoffs, color);
     81
     82                // YZ
     83                drawLine(start-yoffs, start+zoffs, color);
     84                drawLine(start+zoffs, start+yoffs, color);
     85                drawLine(start+yoffs, start-zoffs, color);
     86                drawLine(start-zoffs, start-yoffs, color);
     87        }
     88       
    7289        virtual void    drawSphere (const btVector3& p, btScalar radius, const btVector3& color)
    7390        {
    74         }
    75 
    76         virtual void    drawLine(const btVector3& from,const btVector3& to,const btVector3& color)=0;
     91                btTransform tr;
     92                tr.setIdentity();
     93                tr.setOrigin(p);
     94                drawSphere(radius,tr,color);
     95        }
    7796       
    7897        virtual void    drawTriangle(const btVector3& v0,const btVector3& v1,const btVector3& v2,const btVector3& /*n0*/,const btVector3& /*n1*/,const btVector3& /*n2*/,const btVector3& color, btScalar alpha)
     
    97116        virtual int             getDebugMode() const = 0;
    98117
    99         inline void drawAabb(const btVector3& from,const btVector3& to,const btVector3& color)
     118        virtual void drawAabb(const btVector3& from,const btVector3& to,const btVector3& color)
    100119        {
    101120
     
    126145                }
    127146        }
    128         void drawTransform(const btTransform& transform, btScalar orthoLen)
     147        virtual void drawTransform(const btTransform& transform, btScalar orthoLen)
    129148        {
    130149                btVector3 start = transform.getOrigin();
     
    134153        }
    135154
    136         void drawArc(const btVector3& center, const btVector3& normal, const btVector3& axis, btScalar radiusA, btScalar radiusB, btScalar minAngle, btScalar maxAngle,
     155        virtual void drawArc(const btVector3& center, const btVector3& normal, const btVector3& axis, btScalar radiusA, btScalar radiusB, btScalar minAngle, btScalar maxAngle,
    137156                                const btVector3& color, bool drawSect, btScalar stepDegrees = btScalar(10.f))
    138157        {
     
    159178                }
    160179        }
    161         void drawSpherePatch(const btVector3& center, const btVector3& up, const btVector3& axis, btScalar radius,
     180        virtual void drawSpherePatch(const btVector3& center, const btVector3& up, const btVector3& axis, btScalar radius,
    162181                btScalar minTh, btScalar maxTh, btScalar minPs, btScalar maxPs, const btVector3& color, btScalar stepDegrees = btScalar(10.f))
    163182        {
     
    261280        }
    262281       
    263         void drawBox(const btVector3& bbMin, const btVector3& bbMax, const btVector3& color)
     282        virtual void drawBox(const btVector3& bbMin, const btVector3& bbMax, const btVector3& color)
    264283        {
    265284                drawLine(btVector3(bbMin[0], bbMin[1], bbMin[2]), btVector3(bbMax[0], bbMin[1], bbMin[2]), color);
     
    276295                drawLine(btVector3(bbMin[0], bbMax[1], bbMax[2]), btVector3(bbMin[0], bbMin[1], bbMax[2]), color);
    277296        }
    278         void drawBox(const btVector3& bbMin, const btVector3& bbMax, const btTransform& trans, const btVector3& color)
     297        virtual void drawBox(const btVector3& bbMin, const btVector3& bbMax, const btTransform& trans, const btVector3& color)
    279298        {
    280299                drawLine(trans * btVector3(bbMin[0], bbMin[1], bbMin[2]), trans * btVector3(bbMax[0], bbMin[1], bbMin[2]), color);
  • code/branches/kicklib2/src/external/bullet/LinearMath/btMatrix3x3.h

    r5781 r8284  
    1414
    1515
    16 #ifndef btMatrix3x3_H
    17 #define btMatrix3x3_H
    18 
    19 #include "btScalar.h"
     16#ifndef BT_MATRIX3x3_H
     17#define BT_MATRIX3x3_H
    2018
    2119#include "btVector3.h"
    2220#include "btQuaternion.h"
    2321
     22#ifdef BT_USE_DOUBLE_PRECISION
     23#define btMatrix3x3Data btMatrix3x3DoubleData
     24#else
     25#define btMatrix3x3Data btMatrix3x3FloatData
     26#endif //BT_USE_DOUBLE_PRECISION
    2427
    2528
    2629/**@brief The btMatrix3x3 class implements a 3x3 rotation matrix, to perform linear algebra in combination with btQuaternion, btTransform and btVector3.
    27  * Make sure to only include a pure orthogonal matrix without scaling. */
     30* Make sure to only include a pure orthogonal matrix without scaling. */
    2831class btMatrix3x3 {
    29         public:
    30   /** @brief No initializaion constructor */
    31                 btMatrix3x3 () {}
    32                
    33 //              explicit btMatrix3x3(const btScalar *m) { setFromOpenGLSubMatrix(m); }
    34                
    35   /**@brief Constructor from Quaternion */
    36                 explicit btMatrix3x3(const btQuaternion& q) { setRotation(q); }
    37                 /*
    38                 template <typename btScalar>
    39                 Matrix3x3(const btScalar& yaw, const btScalar& pitch, const btScalar& roll)
    40                 {
    41                         setEulerYPR(yaw, pitch, roll);
    42                 }
    43                 */
    44   /** @brief Constructor with row major formatting */
    45                 btMatrix3x3(const btScalar& xx, const btScalar& xy, const btScalar& xz,
    46                                   const btScalar& yx, const btScalar& yy, const btScalar& yz,
    47                                   const btScalar& zx, const btScalar& zy, const btScalar& zz)
    48                 {
    49                         setValue(xx, xy, xz,
    50                                          yx, yy, yz,
    51                                          zx, zy, zz);
    52                 }
    53   /** @brief Copy constructor */
    54                 SIMD_FORCE_INLINE btMatrix3x3 (const btMatrix3x3& other)
    55                 {
    56                         m_el[0] = other.m_el[0];
    57                         m_el[1] = other.m_el[1];
    58                         m_el[2] = other.m_el[2];
    59                 }
    60   /** @brief Assignment Operator */
    61                 SIMD_FORCE_INLINE btMatrix3x3& operator=(const btMatrix3x3& other)
    62                 {
    63                         m_el[0] = other.m_el[0];
    64                         m_el[1] = other.m_el[1];
    65                         m_el[2] = other.m_el[2];
    66                         return *this;
    67                 }
    68 
    69   /** @brief Get a column of the matrix as a vector
    70    *  @param i Column number 0 indexed */
    71                 SIMD_FORCE_INLINE btVector3 getColumn(int i) const
    72                 {
    73                         return btVector3(m_el[0][i],m_el[1][i],m_el[2][i]);
    74                 }
    75                
    76 
    77   /** @brief Get a row of the matrix as a vector
    78    *  @param i Row number 0 indexed */
    79                 SIMD_FORCE_INLINE const btVector3& getRow(int i) const
    80                 {
    81                         btFullAssert(0 <= i && i < 3);
    82                         return m_el[i];
    83                 }
    84 
    85   /** @brief Get a mutable reference to a row of the matrix as a vector
    86    *  @param i Row number 0 indexed */
    87                 SIMD_FORCE_INLINE btVector3&  operator[](int i)
    88                 {
    89                         btFullAssert(0 <= i && i < 3);
    90                         return m_el[i];
    91                 }
    92                
    93   /** @brief Get a const reference to a row of the matrix as a vector
    94    *  @param i Row number 0 indexed */
    95                 SIMD_FORCE_INLINE const btVector3& operator[](int i) const
    96                 {
    97                         btFullAssert(0 <= i && i < 3);
    98                         return m_el[i];
    99                 }
    100                
    101   /** @brief Multiply by the target matrix on the right
    102    *  @param m Rotation matrix to be applied
    103    * Equivilant to this = this * m */
    104                 btMatrix3x3& operator*=(const btMatrix3x3& m);
    105                
    106   /** @brief Set from a carray of btScalars
    107    *  @param m A pointer to the beginning of an array of 9 btScalars */
     32
     33        ///Data storage for the matrix, each vector is a row of the matrix
     34        btVector3 m_el[3];
     35
     36public:
     37        /** @brief No initializaion constructor */
     38        btMatrix3x3 () {}
     39
     40        //              explicit btMatrix3x3(const btScalar *m) { setFromOpenGLSubMatrix(m); }
     41
     42        /**@brief Constructor from Quaternion */
     43        explicit btMatrix3x3(const btQuaternion& q) { setRotation(q); }
     44        /*
     45        template <typename btScalar>
     46        Matrix3x3(const btScalar& yaw, const btScalar& pitch, const btScalar& roll)
     47        {
     48        setEulerYPR(yaw, pitch, roll);
     49        }
     50        */
     51        /** @brief Constructor with row major formatting */
     52        btMatrix3x3(const btScalar& xx, const btScalar& xy, const btScalar& xz,
     53                const btScalar& yx, const btScalar& yy, const btScalar& yz,
     54                const btScalar& zx, const btScalar& zy, const btScalar& zz)
     55        {
     56                setValue(xx, xy, xz,
     57                        yx, yy, yz,
     58                        zx, zy, zz);
     59        }
     60        /** @brief Copy constructor */
     61        SIMD_FORCE_INLINE btMatrix3x3 (const btMatrix3x3& other)
     62        {
     63                m_el[0] = other.m_el[0];
     64                m_el[1] = other.m_el[1];
     65                m_el[2] = other.m_el[2];
     66        }
     67        /** @brief Assignment Operator */
     68        SIMD_FORCE_INLINE btMatrix3x3& operator=(const btMatrix3x3& other)
     69        {
     70                m_el[0] = other.m_el[0];
     71                m_el[1] = other.m_el[1];
     72                m_el[2] = other.m_el[2];
     73                return *this;
     74        }
     75
     76        /** @brief Get a column of the matrix as a vector
     77        *  @param i Column number 0 indexed */
     78        SIMD_FORCE_INLINE btVector3 getColumn(int i) const
     79        {
     80                return btVector3(m_el[0][i],m_el[1][i],m_el[2][i]);
     81        }
     82
     83
     84        /** @brief Get a row of the matrix as a vector
     85        *  @param i Row number 0 indexed */
     86        SIMD_FORCE_INLINE const btVector3& getRow(int i) const
     87        {
     88                btFullAssert(0 <= i && i < 3);
     89                return m_el[i];
     90        }
     91
     92        /** @brief Get a mutable reference to a row of the matrix as a vector
     93        *  @param i Row number 0 indexed */
     94        SIMD_FORCE_INLINE btVector3&  operator[](int i)
     95        {
     96                btFullAssert(0 <= i && i < 3);
     97                return m_el[i];
     98        }
     99
     100        /** @brief Get a const reference to a row of the matrix as a vector
     101        *  @param i Row number 0 indexed */
     102        SIMD_FORCE_INLINE const btVector3& operator[](int i) const
     103        {
     104                btFullAssert(0 <= i && i < 3);
     105                return m_el[i];
     106        }
     107
     108        /** @brief Multiply by the target matrix on the right
     109        *  @param m Rotation matrix to be applied
     110        * Equivilant to this = this * m */
     111        btMatrix3x3& operator*=(const btMatrix3x3& m);
     112
     113        /** @brief Set from a carray of btScalars
     114        *  @param m A pointer to the beginning of an array of 9 btScalars */
    108115        void setFromOpenGLSubMatrix(const btScalar *m)
    109                 {
    110                         m_el[0].setValue(m[0],m[4],m[8]);
    111                         m_el[1].setValue(m[1],m[5],m[9]);
    112                         m_el[2].setValue(m[2],m[6],m[10]);
    113 
    114                 }
    115   /** @brief Set the values of the matrix explicitly (row major)
    116    *  @param xx Top left
    117    *  @param xy Top Middle
    118    *  @param xz Top Right
    119    *  @param yx Middle Left
    120    *  @param yy Middle Middle
    121    *  @param yz Middle Right
    122    *  @param zx Bottom Left
    123    *  @param zy Bottom Middle
    124    *  @param zz Bottom Right*/
    125                 void setValue(const btScalar& xx, const btScalar& xy, const btScalar& xz,
    126                                           const btScalar& yx, const btScalar& yy, const btScalar& yz,
    127                                           const btScalar& zx, const btScalar& zy, const btScalar& zz)
    128                 {
    129                         m_el[0].setValue(xx,xy,xz);
    130                         m_el[1].setValue(yx,yy,yz);
    131                         m_el[2].setValue(zx,zy,zz);
    132                 }
    133 
    134   /** @brief Set the matrix from a quaternion
    135    *  @param q The Quaternion to match */ 
    136                 void setRotation(const btQuaternion& q)
    137                 {
    138                         btScalar d = q.length2();
    139                         btFullAssert(d != btScalar(0.0));
    140                         btScalar s = btScalar(2.0) / d;
    141                         btScalar xs = q.x() * s,   ys = q.y() * s,   zs = q.z() * s;
    142                         btScalar wx = q.w() * xs,  wy = q.w() * ys,  wz = q.w() * zs;
    143                         btScalar xx = q.x() * xs,  xy = q.x() * ys,  xz = q.x() * zs;
    144                         btScalar yy = q.y() * ys,  yz = q.y() * zs,  zz = q.z() * zs;
    145                         setValue(btScalar(1.0) - (yy + zz), xy - wz, xz + wy,
    146                                          xy + wz, btScalar(1.0) - (xx + zz), yz - wx,
    147                                          xz - wy, yz + wx, btScalar(1.0) - (xx + yy));
    148                 }
    149                
    150 
    151   /** @brief Set the matrix from euler angles using YPR around YXZ respectively
    152    *  @param yaw Yaw about Y axis
    153    *  @param pitch Pitch about X axis
    154    *  @param roll Roll about Z axis
    155    */
    156                 void setEulerYPR(const btScalar& yaw, const btScalar& pitch, const btScalar& roll)
    157                 {
    158                         setEulerZYX(roll, pitch, yaw);
    159                 }
     116        {
     117                m_el[0].setValue(m[0],m[4],m[8]);
     118                m_el[1].setValue(m[1],m[5],m[9]);
     119                m_el[2].setValue(m[2],m[6],m[10]);
     120
     121        }
     122        /** @brief Set the values of the matrix explicitly (row major)
     123        *  @param xx Top left
     124        *  @param xy Top Middle
     125        *  @param xz Top Right
     126        *  @param yx Middle Left
     127        *  @param yy Middle Middle
     128        *  @param yz Middle Right
     129        *  @param zx Bottom Left
     130        *  @param zy Bottom Middle
     131        *  @param zz Bottom Right*/
     132        void setValue(const btScalar& xx, const btScalar& xy, const btScalar& xz,
     133                const btScalar& yx, const btScalar& yy, const btScalar& yz,
     134                const btScalar& zx, const btScalar& zy, const btScalar& zz)
     135        {
     136                m_el[0].setValue(xx,xy,xz);
     137                m_el[1].setValue(yx,yy,yz);
     138                m_el[2].setValue(zx,zy,zz);
     139        }
     140
     141        /** @brief Set the matrix from a quaternion
     142        *  @param q The Quaternion to match */ 
     143        void setRotation(const btQuaternion& q)
     144        {
     145                btScalar d = q.length2();
     146                btFullAssert(d != btScalar(0.0));
     147                btScalar s = btScalar(2.0) / d;
     148                btScalar xs = q.x() * s,   ys = q.y() * s,   zs = q.z() * s;
     149                btScalar wx = q.w() * xs,  wy = q.w() * ys,  wz = q.w() * zs;
     150                btScalar xx = q.x() * xs,  xy = q.x() * ys,  xz = q.x() * zs;
     151                btScalar yy = q.y() * ys,  yz = q.y() * zs,  zz = q.z() * zs;
     152                setValue(btScalar(1.0) - (yy + zz), xy - wz, xz + wy,
     153                        xy + wz, btScalar(1.0) - (xx + zz), yz - wx,
     154                        xz - wy, yz + wx, btScalar(1.0) - (xx + yy));
     155        }
     156
     157
     158        /** @brief Set the matrix from euler angles using YPR around YXZ respectively
     159        *  @param yaw Yaw about Y axis
     160        *  @param pitch Pitch about X axis
     161        *  @param roll Roll about Z axis
     162        */
     163        void setEulerYPR(const btScalar& yaw, const btScalar& pitch, const btScalar& roll)
     164        {
     165                setEulerZYX(roll, pitch, yaw);
     166        }
    160167
    161168        /** @brief Set the matrix from euler angles YPR around ZYX axes
    162          * @param eulerX Roll about X axis
    163          * @param eulerY Pitch around Y axis
    164          * @param eulerZ Yaw aboud Z axis
    165          *
    166          * These angles are used to produce a rotation matrix. The euler
    167          * angles are applied in ZYX order. I.e a vector is first rotated
    168          * about X then Y and then Z
    169          **/
     169        * @param eulerX Roll about X axis
     170        * @param eulerY Pitch around Y axis
     171        * @param eulerZ Yaw aboud Z axis
     172        *
     173        * These angles are used to produce a rotation matrix. The euler
     174        * angles are applied in ZYX order. I.e a vector is first rotated
     175        * about X then Y and then Z
     176        **/
    170177        void setEulerZYX(btScalar eulerX,btScalar eulerY,btScalar eulerZ) {
    171   ///@todo proposed to reverse this since it's labeled zyx but takes arguments xyz and it will match all other parts of the code
     178                ///@todo proposed to reverse this since it's labeled zyx but takes arguments xyz and it will match all other parts of the code
    172179                btScalar ci ( btCos(eulerX));
    173180                btScalar cj ( btCos(eulerY));
     
    180187                btScalar sc = si * ch;
    181188                btScalar ss = si * sh;
    182                
     189
    183190                setValue(cj * ch, sj * sc - cs, sj * cc + ss,
    184                                  cj * sh, sj * ss + cc, sj * cs - sc,
    185                                  -sj,      cj * si,      cj * ci);
    186         }
    187 
    188   /**@brief Set the matrix to the identity */
    189                 void setIdentity()
     191                        cj * sh, sj * ss + cc, sj * cs - sc,
     192                        -sj,      cj * si,      cj * ci);
     193        }
     194
     195        /**@brief Set the matrix to the identity */
     196        void setIdentity()
     197        {
     198                setValue(btScalar(1.0), btScalar(0.0), btScalar(0.0),
     199                        btScalar(0.0), btScalar(1.0), btScalar(0.0),
     200                        btScalar(0.0), btScalar(0.0), btScalar(1.0));
     201        }
     202
     203        static const btMatrix3x3&       getIdentity()
     204        {
     205                static const btMatrix3x3 identityMatrix(btScalar(1.0), btScalar(0.0), btScalar(0.0),
     206                        btScalar(0.0), btScalar(1.0), btScalar(0.0),
     207                        btScalar(0.0), btScalar(0.0), btScalar(1.0));
     208                return identityMatrix;
     209        }
     210
     211        /**@brief Fill the values of the matrix into a 9 element array
     212        * @param m The array to be filled */
     213        void getOpenGLSubMatrix(btScalar *m) const
     214        {
     215                m[0]  = btScalar(m_el[0].x());
     216                m[1]  = btScalar(m_el[1].x());
     217                m[2]  = btScalar(m_el[2].x());
     218                m[3]  = btScalar(0.0);
     219                m[4]  = btScalar(m_el[0].y());
     220                m[5]  = btScalar(m_el[1].y());
     221                m[6]  = btScalar(m_el[2].y());
     222                m[7]  = btScalar(0.0);
     223                m[8]  = btScalar(m_el[0].z());
     224                m[9]  = btScalar(m_el[1].z());
     225                m[10] = btScalar(m_el[2].z());
     226                m[11] = btScalar(0.0);
     227        }
     228
     229        /**@brief Get the matrix represented as a quaternion
     230        * @param q The quaternion which will be set */
     231        void getRotation(btQuaternion& q) const
     232        {
     233                btScalar trace = m_el[0].x() + m_el[1].y() + m_el[2].z();
     234                btScalar temp[4];
     235
     236                if (trace > btScalar(0.0))
     237                {
     238                        btScalar s = btSqrt(trace + btScalar(1.0));
     239                        temp[3]=(s * btScalar(0.5));
     240                        s = btScalar(0.5) / s;
     241
     242                        temp[0]=((m_el[2].y() - m_el[1].z()) * s);
     243                        temp[1]=((m_el[0].z() - m_el[2].x()) * s);
     244                        temp[2]=((m_el[1].x() - m_el[0].y()) * s);
     245                }
     246                else
     247                {
     248                        int i = m_el[0].x() < m_el[1].y() ?
     249                                (m_el[1].y() < m_el[2].z() ? 2 : 1) :
     250                                (m_el[0].x() < m_el[2].z() ? 2 : 0);
     251                        int j = (i + 1) % 3; 
     252                        int k = (i + 2) % 3;
     253
     254                        btScalar s = btSqrt(m_el[i][i] - m_el[j][j] - m_el[k][k] + btScalar(1.0));
     255                        temp[i] = s * btScalar(0.5);
     256                        s = btScalar(0.5) / s;
     257
     258                        temp[3] = (m_el[k][j] - m_el[j][k]) * s;
     259                        temp[j] = (m_el[j][i] + m_el[i][j]) * s;
     260                        temp[k] = (m_el[k][i] + m_el[i][k]) * s;
     261                }
     262                q.setValue(temp[0],temp[1],temp[2],temp[3]);
     263        }
     264
     265        /**@brief Get the matrix represented as euler angles around YXZ, roundtrip with setEulerYPR
     266        * @param yaw Yaw around Y axis
     267        * @param pitch Pitch around X axis
     268        * @param roll around Z axis */ 
     269        void getEulerYPR(btScalar& yaw, btScalar& pitch, btScalar& roll) const
     270        {
     271
     272                // first use the normal calculus
     273                yaw = btScalar(btAtan2(m_el[1].x(), m_el[0].x()));
     274                pitch = btScalar(btAsin(-m_el[2].x()));
     275                roll = btScalar(btAtan2(m_el[2].y(), m_el[2].z()));
     276
     277                // on pitch = +/-HalfPI
     278                if (btFabs(pitch)==SIMD_HALF_PI)
     279                {
     280                        if (yaw>0)
     281                                yaw-=SIMD_PI;
     282                        else
     283                                yaw+=SIMD_PI;
     284
     285                        if (roll>0)
     286                                roll-=SIMD_PI;
     287                        else
     288                                roll+=SIMD_PI;
     289                }
     290        };
     291
     292
     293        /**@brief Get the matrix represented as euler angles around ZYX
     294        * @param yaw Yaw around X axis
     295        * @param pitch Pitch around Y axis
     296        * @param roll around X axis
     297        * @param solution_number Which solution of two possible solutions ( 1 or 2) are possible values*/       
     298        void getEulerZYX(btScalar& yaw, btScalar& pitch, btScalar& roll, unsigned int solution_number = 1) const
     299        {
     300                struct Euler
     301                {
     302                        btScalar yaw;
     303                        btScalar pitch;
     304                        btScalar roll;
     305                };
     306
     307                Euler euler_out;
     308                Euler euler_out2; //second solution
     309                //get the pointer to the raw data
     310
     311                // Check that pitch is not at a singularity
     312                if (btFabs(m_el[2].x()) >= 1)
     313                {
     314                        euler_out.yaw = 0;
     315                        euler_out2.yaw = 0;
     316
     317                        // From difference of angles formula
     318                        btScalar delta = btAtan2(m_el[0].x(),m_el[0].z());
     319                        if (m_el[2].x() > 0)  //gimbal locked up
     320                        {
     321                                euler_out.pitch = SIMD_PI / btScalar(2.0);
     322                                euler_out2.pitch = SIMD_PI / btScalar(2.0);
     323                                euler_out.roll = euler_out.pitch + delta;
     324                                euler_out2.roll = euler_out.pitch + delta;
     325                        }
     326                        else // gimbal locked down
     327                        {
     328                                euler_out.pitch = -SIMD_PI / btScalar(2.0);
     329                                euler_out2.pitch = -SIMD_PI / btScalar(2.0);
     330                                euler_out.roll = -euler_out.pitch + delta;
     331                                euler_out2.roll = -euler_out.pitch + delta;
     332                        }
     333                }
     334                else
     335                {
     336                        euler_out.pitch = - btAsin(m_el[2].x());
     337                        euler_out2.pitch = SIMD_PI - euler_out.pitch;
     338
     339                        euler_out.roll = btAtan2(m_el[2].y()/btCos(euler_out.pitch),
     340                                m_el[2].z()/btCos(euler_out.pitch));
     341                        euler_out2.roll = btAtan2(m_el[2].y()/btCos(euler_out2.pitch),
     342                                m_el[2].z()/btCos(euler_out2.pitch));
     343
     344                        euler_out.yaw = btAtan2(m_el[1].x()/btCos(euler_out.pitch),
     345                                m_el[0].x()/btCos(euler_out.pitch));
     346                        euler_out2.yaw = btAtan2(m_el[1].x()/btCos(euler_out2.pitch),
     347                                m_el[0].x()/btCos(euler_out2.pitch));
     348                }
     349
     350                if (solution_number == 1)
    190351                {
    191                         setValue(btScalar(1.0), btScalar(0.0), btScalar(0.0),
    192                                          btScalar(0.0), btScalar(1.0), btScalar(0.0),
    193                                          btScalar(0.0), btScalar(0.0), btScalar(1.0));
     352                        yaw = euler_out.yaw;
     353                        pitch = euler_out.pitch;
     354                        roll = euler_out.roll;
    194355                }
    195 
    196                 static const btMatrix3x3&       getIdentity()
     356                else
     357                {
     358                        yaw = euler_out2.yaw;
     359                        pitch = euler_out2.pitch;
     360                        roll = euler_out2.roll;
     361                }
     362        }
     363
     364        /**@brief Create a scaled copy of the matrix
     365        * @param s Scaling vector The elements of the vector will scale each column */
     366
     367        btMatrix3x3 scaled(const btVector3& s) const
     368        {
     369                return btMatrix3x3(m_el[0].x() * s.x(), m_el[0].y() * s.y(), m_el[0].z() * s.z(),
     370                        m_el[1].x() * s.x(), m_el[1].y() * s.y(), m_el[1].z() * s.z(),
     371                        m_el[2].x() * s.x(), m_el[2].y() * s.y(), m_el[2].z() * s.z());
     372        }
     373
     374        /**@brief Return the determinant of the matrix */
     375        btScalar            determinant() const;
     376        /**@brief Return the adjoint of the matrix */
     377        btMatrix3x3 adjoint() const;
     378        /**@brief Return the matrix with all values non negative */
     379        btMatrix3x3 absolute() const;
     380        /**@brief Return the transpose of the matrix */
     381        btMatrix3x3 transpose() const;
     382        /**@brief Return the inverse of the matrix */
     383        btMatrix3x3 inverse() const;
     384
     385        btMatrix3x3 transposeTimes(const btMatrix3x3& m) const;
     386        btMatrix3x3 timesTranspose(const btMatrix3x3& m) const;
     387
     388        SIMD_FORCE_INLINE btScalar tdotx(const btVector3& v) const
     389        {
     390                return m_el[0].x() * v.x() + m_el[1].x() * v.y() + m_el[2].x() * v.z();
     391        }
     392        SIMD_FORCE_INLINE btScalar tdoty(const btVector3& v) const
     393        {
     394                return m_el[0].y() * v.x() + m_el[1].y() * v.y() + m_el[2].y() * v.z();
     395        }
     396        SIMD_FORCE_INLINE btScalar tdotz(const btVector3& v) const
     397        {
     398                return m_el[0].z() * v.x() + m_el[1].z() * v.y() + m_el[2].z() * v.z();
     399        }
     400
     401
     402        /**@brief diagonalizes this matrix by the Jacobi method.
     403        * @param rot stores the rotation from the coordinate system in which the matrix is diagonal to the original
     404        * coordinate system, i.e., old_this = rot * new_this * rot^T.
     405        * @param threshold See iteration
     406        * @param iteration The iteration stops when all off-diagonal elements are less than the threshold multiplied
     407        * by the sum of the absolute values of the diagonal, or when maxSteps have been executed.
     408        *
     409        * Note that this matrix is assumed to be symmetric.
     410        */
     411        void diagonalize(btMatrix3x3& rot, btScalar threshold, int maxSteps)
     412        {
     413                rot.setIdentity();
     414                for (int step = maxSteps; step > 0; step--)
    197415                {
    198                         static const btMatrix3x3 identityMatrix(btScalar(1.0), btScalar(0.0), btScalar(0.0),
    199                                          btScalar(0.0), btScalar(1.0), btScalar(0.0),
    200                                          btScalar(0.0), btScalar(0.0), btScalar(1.0));
    201                         return identityMatrix;
    202                 }
    203 
    204   /**@brief Fill the values of the matrix into a 9 element array
    205    * @param m The array to be filled */
    206                 void getOpenGLSubMatrix(btScalar *m) const
    207                 {
    208                         m[0]  = btScalar(m_el[0].x());
    209                         m[1]  = btScalar(m_el[1].x());
    210                         m[2]  = btScalar(m_el[2].x());
    211                         m[3]  = btScalar(0.0);
    212                         m[4]  = btScalar(m_el[0].y());
    213                         m[5]  = btScalar(m_el[1].y());
    214                         m[6]  = btScalar(m_el[2].y());
    215                         m[7]  = btScalar(0.0);
    216                         m[8]  = btScalar(m_el[0].z());
    217                         m[9]  = btScalar(m_el[1].z());
    218                         m[10] = btScalar(m_el[2].z());
    219                         m[11] = btScalar(0.0);
    220                 }
    221 
    222   /**@brief Get the matrix represented as a quaternion
    223    * @param q The quaternion which will be set */
    224                 void getRotation(btQuaternion& q) const
    225                 {
    226                         btScalar trace = m_el[0].x() + m_el[1].y() + m_el[2].z();
    227                         btScalar temp[4];
    228                        
    229                         if (trace > btScalar(0.0))
    230                         {
    231                                 btScalar s = btSqrt(trace + btScalar(1.0));
    232                                 temp[3]=(s * btScalar(0.5));
    233                                 s = btScalar(0.5) / s;
    234                                
    235                                 temp[0]=((m_el[2].y() - m_el[1].z()) * s);
    236                                 temp[1]=((m_el[0].z() - m_el[2].x()) * s);
    237                                 temp[2]=((m_el[1].x() - m_el[0].y()) * s);
    238                         }
    239                         else
    240                         {
    241                                 int i = m_el[0].x() < m_el[1].y() ?
    242                                         (m_el[1].y() < m_el[2].z() ? 2 : 1) :
    243                                         (m_el[0].x() < m_el[2].z() ? 2 : 0);
    244                                 int j = (i + 1) % 3; 
    245                                 int k = (i + 2) % 3;
    246                                
    247                                 btScalar s = btSqrt(m_el[i][i] - m_el[j][j] - m_el[k][k] + btScalar(1.0));
    248                                 temp[i] = s * btScalar(0.5);
    249                                 s = btScalar(0.5) / s;
    250                                
    251                                 temp[3] = (m_el[k][j] - m_el[j][k]) * s;
    252                                 temp[j] = (m_el[j][i] + m_el[i][j]) * s;
    253                                 temp[k] = (m_el[k][i] + m_el[i][k]) * s;
    254                         }
    255                         q.setValue(temp[0],temp[1],temp[2],temp[3]);
    256                 }
    257 
    258   /**@brief Get the matrix represented as euler angles around YXZ, roundtrip with setEulerYPR
    259    * @param yaw Yaw around Y axis
    260    * @param pitch Pitch around X axis
    261    * @param roll around Z axis */       
    262                 void getEulerYPR(btScalar& yaw, btScalar& pitch, btScalar& roll) const
    263                 {
    264                        
    265                         // first use the normal calculus
    266                         yaw = btScalar(btAtan2(m_el[1].x(), m_el[0].x()));
    267                         pitch = btScalar(btAsin(-m_el[2].x()));
    268                         roll = btScalar(btAtan2(m_el[2].y(), m_el[2].z()));
    269 
    270                         // on pitch = +/-HalfPI
    271                         if (btFabs(pitch)==SIMD_HALF_PI)
    272                         {
    273                                 if (yaw>0)
    274                                         yaw-=SIMD_PI;
    275                                 else
    276                                         yaw+=SIMD_PI;
    277 
    278                                 if (roll>0)
    279                                         roll-=SIMD_PI;
    280                                 else
    281                                         roll+=SIMD_PI;
    282                         }
    283                 };
    284 
    285 
    286   /**@brief Get the matrix represented as euler angles around ZYX
    287    * @param yaw Yaw around X axis
    288    * @param pitch Pitch around Y axis
    289    * @param roll around X axis
    290    * @param solution_number Which solution of two possible solutions ( 1 or 2) are possible values*/   
    291   void getEulerZYX(btScalar& yaw, btScalar& pitch, btScalar& roll, unsigned int solution_number = 1) const
    292   {
    293     struct Euler{btScalar yaw, pitch, roll;};
    294     Euler euler_out;
    295     Euler euler_out2; //second solution
    296     //get the pointer to the raw data
    297    
    298     // Check that pitch is not at a singularity
    299     if (btFabs(m_el[2].x()) >= 1)
    300     {
    301       euler_out.yaw = 0;
    302       euler_out2.yaw = 0;
    303        
    304       // From difference of angles formula
    305       btScalar delta = btAtan2(m_el[0].x(),m_el[0].z());
    306       if (m_el[2].x() > 0)  //gimbal locked up
    307       {
    308         euler_out.pitch = SIMD_PI / btScalar(2.0);
    309         euler_out2.pitch = SIMD_PI / btScalar(2.0);
    310         euler_out.roll = euler_out.pitch + delta;
    311         euler_out2.roll = euler_out.pitch + delta;
    312       }
    313       else // gimbal locked down
    314       {
    315         euler_out.pitch = -SIMD_PI / btScalar(2.0);
    316         euler_out2.pitch = -SIMD_PI / btScalar(2.0);
    317         euler_out.roll = -euler_out.pitch + delta;
    318         euler_out2.roll = -euler_out.pitch + delta;
    319       }
    320     }
    321     else
    322     {
    323       euler_out.pitch = - btAsin(m_el[2].x());
    324       euler_out2.pitch = SIMD_PI - euler_out.pitch;
    325        
    326       euler_out.roll = btAtan2(m_el[2].y()/btCos(euler_out.pitch),
    327                                m_el[2].z()/btCos(euler_out.pitch));
    328       euler_out2.roll = btAtan2(m_el[2].y()/btCos(euler_out2.pitch),
    329                                 m_el[2].z()/btCos(euler_out2.pitch));
    330        
    331       euler_out.yaw = btAtan2(m_el[1].x()/btCos(euler_out.pitch),
    332                               m_el[0].x()/btCos(euler_out.pitch));
    333       euler_out2.yaw = btAtan2(m_el[1].x()/btCos(euler_out2.pitch),
    334                                m_el[0].x()/btCos(euler_out2.pitch));
    335     }
    336    
    337     if (solution_number == 1)
    338     {
    339                 yaw = euler_out.yaw;
    340                 pitch = euler_out.pitch;
    341                 roll = euler_out.roll;
    342     }
    343     else
    344     {
    345                 yaw = euler_out2.yaw;
    346                 pitch = euler_out2.pitch;
    347                 roll = euler_out2.roll;
    348     }
    349   }
    350 
    351   /**@brief Create a scaled copy of the matrix
    352    * @param s Scaling vector The elements of the vector will scale each column */
    353                
    354                 btMatrix3x3 scaled(const btVector3& s) const
    355                 {
    356                         return btMatrix3x3(m_el[0].x() * s.x(), m_el[0].y() * s.y(), m_el[0].z() * s.z(),
    357                                                                          m_el[1].x() * s.x(), m_el[1].y() * s.y(), m_el[1].z() * s.z(),
    358                                                                          m_el[2].x() * s.x(), m_el[2].y() * s.y(), m_el[2].z() * s.z());
    359                 }
    360 
    361   /**@brief Return the determinant of the matrix */
    362                 btScalar            determinant() const;
    363   /**@brief Return the adjoint of the matrix */
    364                 btMatrix3x3 adjoint() const;
    365   /**@brief Return the matrix with all values non negative */
    366                 btMatrix3x3 absolute() const;
    367   /**@brief Return the transpose of the matrix */
    368                 btMatrix3x3 transpose() const;
    369   /**@brief Return the inverse of the matrix */
    370                 btMatrix3x3 inverse() const;
    371                
    372                 btMatrix3x3 transposeTimes(const btMatrix3x3& m) const;
    373                 btMatrix3x3 timesTranspose(const btMatrix3x3& m) const;
    374                
    375                 SIMD_FORCE_INLINE btScalar tdotx(const btVector3& v) const
    376                 {
    377                         return m_el[0].x() * v.x() + m_el[1].x() * v.y() + m_el[2].x() * v.z();
    378                 }
    379                 SIMD_FORCE_INLINE btScalar tdoty(const btVector3& v) const
    380                 {
    381                         return m_el[0].y() * v.x() + m_el[1].y() * v.y() + m_el[2].y() * v.z();
    382                 }
    383                 SIMD_FORCE_INLINE btScalar tdotz(const btVector3& v) const
    384                 {
    385                         return m_el[0].z() * v.x() + m_el[1].z() * v.y() + m_el[2].z() * v.z();
    386                 }
    387                
    388 
    389   /**@brief diagonalizes this matrix by the Jacobi method.
    390    * @param rot stores the rotation from the coordinate system in which the matrix is diagonal to the original
    391    * coordinate system, i.e., old_this = rot * new_this * rot^T.
    392    * @param threshold See iteration
    393    * @param iteration The iteration stops when all off-diagonal elements are less than the threshold multiplied
    394    * by the sum of the absolute values of the diagonal, or when maxSteps have been executed.
    395    *
    396    * Note that this matrix is assumed to be symmetric.
    397    */
    398                 void diagonalize(btMatrix3x3& rot, btScalar threshold, int maxSteps)
    399                 {
    400                  rot.setIdentity();
    401                  for (int step = maxSteps; step > 0; step--)
    402                  {
    403416                        // find off-diagonal element [p][q] with largest magnitude
    404417                        int p = 0;
     
    409422                        if (v > max)
    410423                        {
    411                            q = 2;
    412                            r = 1;
    413                            max = v;
     424                                q = 2;
     425                                r = 1;
     426                                max = v;
    414427                        }
    415428                        v = btFabs(m_el[1][2]);
    416429                        if (v > max)
    417430                        {
    418                            p = 1;
    419                            q = 2;
    420                            r = 0;
    421                            max = v;
     431                                p = 1;
     432                                q = 2;
     433                                r = 0;
     434                                max = v;
    422435                        }
    423436
     
    425438                        if (max <= t)
    426439                        {
    427                            if (max <= SIMD_EPSILON * t)
    428                            {
    429                                   return;
    430                            }
    431                            step = 1;
     440                                if (max <= SIMD_EPSILON * t)
     441                                {
     442                                        return;
     443                                }
     444                                step = 1;
    432445                        }
    433446
     
    440453                        if (theta2 * theta2 < btScalar(10 / SIMD_EPSILON))
    441454                        {
    442                            t = (theta >= 0) ? 1 / (theta + btSqrt(1 + theta2))
    443                                                                                 : 1 / (theta - btSqrt(1 + theta2));
    444                            cos = 1 / btSqrt(1 + t * t);
    445                            sin = cos * t;
     455                                t = (theta >= 0) ? 1 / (theta + btSqrt(1 + theta2))
     456                                        : 1 / (theta - btSqrt(1 + theta2));
     457                                cos = 1 / btSqrt(1 + t * t);
     458                                sin = cos * t;
    446459                        }
    447460                        else
    448461                        {
    449                            // approximation for large theta-value, i.e., a nearly diagonal matrix
    450                            t = 1 / (theta * (2 + btScalar(0.5) / theta2));
    451                            cos = 1 - btScalar(0.5) * t * t;
    452                            sin = cos * t;
     462                                // approximation for large theta-value, i.e., a nearly diagonal matrix
     463                                t = 1 / (theta * (2 + btScalar(0.5) / theta2));
     464                                cos = 1 - btScalar(0.5) * t * t;
     465                                sin = cos * t;
    453466                        }
    454467
     
    465478                        for (int i = 0; i < 3; i++)
    466479                        {
    467                            btVector3& row = rot[i];
    468                            mrp = row[p];
    469                            mrq = row[q];
    470                            row[p] = cos * mrp - sin * mrq;
    471                            row[q] = cos * mrq + sin * mrp;
    472                         }
    473                  }
     480                                btVector3& row = rot[i];
     481                                mrp = row[p];
     482                                mrq = row[q];
     483                                row[p] = cos * mrp - sin * mrq;
     484                                row[q] = cos * mrq + sin * mrp;
     485                        }
    474486                }
    475 
    476 
    477                
    478         protected:
    479   /**@brief Calculate the matrix cofactor
    480    * @param r1 The first row to use for calculating the cofactor
    481    * @param c1 The first column to use for calculating the cofactor
    482    * @param r1 The second row to use for calculating the cofactor
    483    * @param c1 The second column to use for calculating the cofactor
    484    * See http://en.wikipedia.org/wiki/Cofactor_(linear_algebra) for more details
    485    */
    486                 btScalar cofac(int r1, int c1, int r2, int c2) const
    487                 {
    488                         return m_el[r1][c1] * m_el[r2][c2] - m_el[r1][c2] * m_el[r2][c1];
    489                 }
    490   ///Data storage for the matrix, each vector is a row of the matrix
    491                 btVector3 m_el[3];
    492         };
     487        }
     488
     489
     490
     491
     492        /**@brief Calculate the matrix cofactor
     493        * @param r1 The first row to use for calculating the cofactor
     494        * @param c1 The first column to use for calculating the cofactor
     495        * @param r1 The second row to use for calculating the cofactor
     496        * @param c1 The second column to use for calculating the cofactor
     497        * See http://en.wikipedia.org/wiki/Cofactor_(linear_algebra) for more details
     498        */
     499        btScalar cofac(int r1, int c1, int r2, int c2) const
     500        {
     501                return m_el[r1][c1] * m_el[r2][c2] - m_el[r1][c2] * m_el[r2][c1];
     502        }
     503
     504        void    serialize(struct        btMatrix3x3Data& dataOut) const;
     505
     506        void    serializeFloat(struct   btMatrix3x3FloatData& dataOut) const;
     507
     508        void    deSerialize(const struct        btMatrix3x3Data& dataIn);
     509
     510        void    deSerializeFloat(const struct   btMatrix3x3FloatData& dataIn);
     511
     512        void    deSerializeDouble(const struct  btMatrix3x3DoubleData& dataIn);
     513
     514};
     515
     516
     517SIMD_FORCE_INLINE btMatrix3x3&
     518btMatrix3x3::operator*=(const btMatrix3x3& m)
     519{
     520        setValue(m.tdotx(m_el[0]), m.tdoty(m_el[0]), m.tdotz(m_el[0]),
     521                m.tdotx(m_el[1]), m.tdoty(m_el[1]), m.tdotz(m_el[1]),
     522                m.tdotx(m_el[2]), m.tdoty(m_el[2]), m.tdotz(m_el[2]));
     523        return *this;
     524}
     525
     526SIMD_FORCE_INLINE btScalar
     527btMatrix3x3::determinant() const
     528{
     529        return btTriple((*this)[0], (*this)[1], (*this)[2]);
     530}
     531
     532
     533SIMD_FORCE_INLINE btMatrix3x3
     534btMatrix3x3::absolute() const
     535{
     536        return btMatrix3x3(
     537                btFabs(m_el[0].x()), btFabs(m_el[0].y()), btFabs(m_el[0].z()),
     538                btFabs(m_el[1].x()), btFabs(m_el[1].y()), btFabs(m_el[1].z()),
     539                btFabs(m_el[2].x()), btFabs(m_el[2].y()), btFabs(m_el[2].z()));
     540}
     541
     542SIMD_FORCE_INLINE btMatrix3x3
     543btMatrix3x3::transpose() const
     544{
     545        return btMatrix3x3(m_el[0].x(), m_el[1].x(), m_el[2].x(),
     546                m_el[0].y(), m_el[1].y(), m_el[2].y(),
     547                m_el[0].z(), m_el[1].z(), m_el[2].z());
     548}
     549
     550SIMD_FORCE_INLINE btMatrix3x3
     551btMatrix3x3::adjoint() const
     552{
     553        return btMatrix3x3(cofac(1, 1, 2, 2), cofac(0, 2, 2, 1), cofac(0, 1, 1, 2),
     554                cofac(1, 2, 2, 0), cofac(0, 0, 2, 2), cofac(0, 2, 1, 0),
     555                cofac(1, 0, 2, 1), cofac(0, 1, 2, 0), cofac(0, 0, 1, 1));
     556}
     557
     558SIMD_FORCE_INLINE btMatrix3x3
     559btMatrix3x3::inverse() const
     560{
     561        btVector3 co(cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1));
     562        btScalar det = (*this)[0].dot(co);
     563        btFullAssert(det != btScalar(0.0));
     564        btScalar s = btScalar(1.0) / det;
     565        return btMatrix3x3(co.x() * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s,
     566                co.y() * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s,
     567                co.z() * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s);
     568}
     569
     570SIMD_FORCE_INLINE btMatrix3x3
     571btMatrix3x3::transposeTimes(const btMatrix3x3& m) const
     572{
     573        return btMatrix3x3(
     574                m_el[0].x() * m[0].x() + m_el[1].x() * m[1].x() + m_el[2].x() * m[2].x(),
     575                m_el[0].x() * m[0].y() + m_el[1].x() * m[1].y() + m_el[2].x() * m[2].y(),
     576                m_el[0].x() * m[0].z() + m_el[1].x() * m[1].z() + m_el[2].x() * m[2].z(),
     577                m_el[0].y() * m[0].x() + m_el[1].y() * m[1].x() + m_el[2].y() * m[2].x(),
     578                m_el[0].y() * m[0].y() + m_el[1].y() * m[1].y() + m_el[2].y() * m[2].y(),
     579                m_el[0].y() * m[0].z() + m_el[1].y() * m[1].z() + m_el[2].y() * m[2].z(),
     580                m_el[0].z() * m[0].x() + m_el[1].z() * m[1].x() + m_el[2].z() * m[2].x(),
     581                m_el[0].z() * m[0].y() + m_el[1].z() * m[1].y() + m_el[2].z() * m[2].y(),
     582                m_el[0].z() * m[0].z() + m_el[1].z() * m[1].z() + m_el[2].z() * m[2].z());
     583}
     584
     585SIMD_FORCE_INLINE btMatrix3x3
     586btMatrix3x3::timesTranspose(const btMatrix3x3& m) const
     587{
     588        return btMatrix3x3(
     589                m_el[0].dot(m[0]), m_el[0].dot(m[1]), m_el[0].dot(m[2]),
     590                m_el[1].dot(m[0]), m_el[1].dot(m[1]), m_el[1].dot(m[2]),
     591                m_el[2].dot(m[0]), m_el[2].dot(m[1]), m_el[2].dot(m[2]));
     592
     593}
     594
     595SIMD_FORCE_INLINE btVector3
     596operator*(const btMatrix3x3& m, const btVector3& v)
     597{
     598        return btVector3(m[0].dot(v), m[1].dot(v), m[2].dot(v));
     599}
     600
     601
     602SIMD_FORCE_INLINE btVector3
     603operator*(const btVector3& v, const btMatrix3x3& m)
     604{
     605        return btVector3(m.tdotx(v), m.tdoty(v), m.tdotz(v));
     606}
     607
     608SIMD_FORCE_INLINE btMatrix3x3
     609operator*(const btMatrix3x3& m1, const btMatrix3x3& m2)
     610{
     611        return btMatrix3x3(
     612                m2.tdotx( m1[0]), m2.tdoty( m1[0]), m2.tdotz( m1[0]),
     613                m2.tdotx( m1[1]), m2.tdoty( m1[1]), m2.tdotz( m1[1]),
     614                m2.tdotx( m1[2]), m2.tdoty( m1[2]), m2.tdotz( m1[2]));
     615}
     616
     617/*
     618SIMD_FORCE_INLINE btMatrix3x3 btMultTransposeLeft(const btMatrix3x3& m1, const btMatrix3x3& m2) {
     619return btMatrix3x3(
     620m1[0][0] * m2[0][0] + m1[1][0] * m2[1][0] + m1[2][0] * m2[2][0],
     621m1[0][0] * m2[0][1] + m1[1][0] * m2[1][1] + m1[2][0] * m2[2][1],
     622m1[0][0] * m2[0][2] + m1[1][0] * m2[1][2] + m1[2][0] * m2[2][2],
     623m1[0][1] * m2[0][0] + m1[1][1] * m2[1][0] + m1[2][1] * m2[2][0],
     624m1[0][1] * m2[0][1] + m1[1][1] * m2[1][1] + m1[2][1] * m2[2][1],
     625m1[0][1] * m2[0][2] + m1[1][1] * m2[1][2] + m1[2][1] * m2[2][2],
     626m1[0][2] * m2[0][0] + m1[1][2] * m2[1][0] + m1[2][2] * m2[2][0],
     627m1[0][2] * m2[0][1] + m1[1][2] * m2[1][1] + m1[2][2] * m2[2][1],
     628m1[0][2] * m2[0][2] + m1[1][2] * m2[1][2] + m1[2][2] * m2[2][2]);
     629}
     630*/
     631
     632/**@brief Equality operator between two matrices
     633* It will test all elements are equal.  */
     634SIMD_FORCE_INLINE bool operator==(const btMatrix3x3& m1, const btMatrix3x3& m2)
     635{
     636        return ( m1[0][0] == m2[0][0] && m1[1][0] == m2[1][0] && m1[2][0] == m2[2][0] &&
     637                m1[0][1] == m2[0][1] && m1[1][1] == m2[1][1] && m1[2][1] == m2[2][1] &&
     638                m1[0][2] == m2[0][2] && m1[1][2] == m2[1][2] && m1[2][2] == m2[2][2] );
     639}
     640
     641///for serialization
     642struct  btMatrix3x3FloatData
     643{
     644        btVector3FloatData m_el[3];
     645};
     646
     647///for serialization
     648struct  btMatrix3x3DoubleData
     649{
     650        btVector3DoubleData m_el[3];
     651};
     652
     653
    493654       
    494         SIMD_FORCE_INLINE btMatrix3x3&
    495         btMatrix3x3::operator*=(const btMatrix3x3& m)
    496         {
    497                 setValue(m.tdotx(m_el[0]), m.tdoty(m_el[0]), m.tdotz(m_el[0]),
    498                                  m.tdotx(m_el[1]), m.tdoty(m_el[1]), m.tdotz(m_el[1]),
    499                                  m.tdotx(m_el[2]), m.tdoty(m_el[2]), m.tdotz(m_el[2]));
    500                 return *this;
    501         }
    502        
    503         SIMD_FORCE_INLINE btScalar
    504         btMatrix3x3::determinant() const
    505         {
    506                 return triple((*this)[0], (*this)[1], (*this)[2]);
    507         }
    508        
    509 
    510         SIMD_FORCE_INLINE btMatrix3x3
    511         btMatrix3x3::absolute() const
    512         {
    513                 return btMatrix3x3(
    514                         btFabs(m_el[0].x()), btFabs(m_el[0].y()), btFabs(m_el[0].z()),
    515                         btFabs(m_el[1].x()), btFabs(m_el[1].y()), btFabs(m_el[1].z()),
    516                         btFabs(m_el[2].x()), btFabs(m_el[2].y()), btFabs(m_el[2].z()));
    517         }
    518 
    519         SIMD_FORCE_INLINE btMatrix3x3
    520         btMatrix3x3::transpose() const
    521         {
    522                 return btMatrix3x3(m_el[0].x(), m_el[1].x(), m_el[2].x(),
    523                                                                  m_el[0].y(), m_el[1].y(), m_el[2].y(),
    524                                                                  m_el[0].z(), m_el[1].z(), m_el[2].z());
    525         }
    526        
    527         SIMD_FORCE_INLINE btMatrix3x3
    528         btMatrix3x3::adjoint() const
    529         {
    530                 return btMatrix3x3(cofac(1, 1, 2, 2), cofac(0, 2, 2, 1), cofac(0, 1, 1, 2),
    531                                                                  cofac(1, 2, 2, 0), cofac(0, 0, 2, 2), cofac(0, 2, 1, 0),
    532                                                                  cofac(1, 0, 2, 1), cofac(0, 1, 2, 0), cofac(0, 0, 1, 1));
    533         }
    534        
    535         SIMD_FORCE_INLINE btMatrix3x3
    536         btMatrix3x3::inverse() const
    537         {
    538                 btVector3 co(cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1));
    539                 btScalar det = (*this)[0].dot(co);
    540                 btFullAssert(det != btScalar(0.0));
    541                 btScalar s = btScalar(1.0) / det;
    542                 return btMatrix3x3(co.x() * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s,
    543                                                                  co.y() * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s,
    544                                                                  co.z() * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s);
    545         }
    546        
    547         SIMD_FORCE_INLINE btMatrix3x3
    548         btMatrix3x3::transposeTimes(const btMatrix3x3& m) const
    549         {
    550                 return btMatrix3x3(
    551                         m_el[0].x() * m[0].x() + m_el[1].x() * m[1].x() + m_el[2].x() * m[2].x(),
    552                         m_el[0].x() * m[0].y() + m_el[1].x() * m[1].y() + m_el[2].x() * m[2].y(),
    553                         m_el[0].x() * m[0].z() + m_el[1].x() * m[1].z() + m_el[2].x() * m[2].z(),
    554                         m_el[0].y() * m[0].x() + m_el[1].y() * m[1].x() + m_el[2].y() * m[2].x(),
    555                         m_el[0].y() * m[0].y() + m_el[1].y() * m[1].y() + m_el[2].y() * m[2].y(),
    556                         m_el[0].y() * m[0].z() + m_el[1].y() * m[1].z() + m_el[2].y() * m[2].z(),
    557                         m_el[0].z() * m[0].x() + m_el[1].z() * m[1].x() + m_el[2].z() * m[2].x(),
    558                         m_el[0].z() * m[0].y() + m_el[1].z() * m[1].y() + m_el[2].z() * m[2].y(),
    559                         m_el[0].z() * m[0].z() + m_el[1].z() * m[1].z() + m_el[2].z() * m[2].z());
    560         }
    561        
    562         SIMD_FORCE_INLINE btMatrix3x3
    563         btMatrix3x3::timesTranspose(const btMatrix3x3& m) const
    564         {
    565                 return btMatrix3x3(
    566                         m_el[0].dot(m[0]), m_el[0].dot(m[1]), m_el[0].dot(m[2]),
    567                         m_el[1].dot(m[0]), m_el[1].dot(m[1]), m_el[1].dot(m[2]),
    568                         m_el[2].dot(m[0]), m_el[2].dot(m[1]), m_el[2].dot(m[2]));
    569                
    570         }
    571 
    572         SIMD_FORCE_INLINE btVector3
    573         operator*(const btMatrix3x3& m, const btVector3& v)
    574         {
    575                 return btVector3(m[0].dot(v), m[1].dot(v), m[2].dot(v));
    576         }
    577        
    578 
    579         SIMD_FORCE_INLINE btVector3
    580         operator*(const btVector3& v, const btMatrix3x3& m)
    581         {
    582                 return btVector3(m.tdotx(v), m.tdoty(v), m.tdotz(v));
    583         }
    584 
    585         SIMD_FORCE_INLINE btMatrix3x3
    586         operator*(const btMatrix3x3& m1, const btMatrix3x3& m2)
    587         {
    588                 return btMatrix3x3(
    589                         m2.tdotx( m1[0]), m2.tdoty( m1[0]), m2.tdotz( m1[0]),
    590                         m2.tdotx( m1[1]), m2.tdoty( m1[1]), m2.tdotz( m1[1]),
    591                         m2.tdotx( m1[2]), m2.tdoty( m1[2]), m2.tdotz( m1[2]));
    592         }
    593 
    594 /*
    595         SIMD_FORCE_INLINE btMatrix3x3 btMultTransposeLeft(const btMatrix3x3& m1, const btMatrix3x3& m2) {
    596     return btMatrix3x3(
    597         m1[0][0] * m2[0][0] + m1[1][0] * m2[1][0] + m1[2][0] * m2[2][0],
    598         m1[0][0] * m2[0][1] + m1[1][0] * m2[1][1] + m1[2][0] * m2[2][1],
    599         m1[0][0] * m2[0][2] + m1[1][0] * m2[1][2] + m1[2][0] * m2[2][2],
    600         m1[0][1] * m2[0][0] + m1[1][1] * m2[1][0] + m1[2][1] * m2[2][0],
    601         m1[0][1] * m2[0][1] + m1[1][1] * m2[1][1] + m1[2][1] * m2[2][1],
    602         m1[0][1] * m2[0][2] + m1[1][1] * m2[1][2] + m1[2][1] * m2[2][2],
    603         m1[0][2] * m2[0][0] + m1[1][2] * m2[1][0] + m1[2][2] * m2[2][0],
    604         m1[0][2] * m2[0][1] + m1[1][2] * m2[1][1] + m1[2][2] * m2[2][1],
    605         m1[0][2] * m2[0][2] + m1[1][2] * m2[1][2] + m1[2][2] * m2[2][2]);
    606 }
    607 */
    608 
    609 /**@brief Equality operator between two matrices
    610  * It will test all elements are equal.  */
    611 SIMD_FORCE_INLINE bool operator==(const btMatrix3x3& m1, const btMatrix3x3& m2)
    612 {
    613    return ( m1[0][0] == m2[0][0] && m1[1][0] == m2[1][0] && m1[2][0] == m2[2][0] &&
    614             m1[0][1] == m2[0][1] && m1[1][1] == m2[1][1] && m1[2][1] == m2[2][1] &&
    615             m1[0][2] == m2[0][2] && m1[1][2] == m2[1][2] && m1[2][2] == m2[2][2] );
    616 }
    617 
    618 #endif
     655
     656SIMD_FORCE_INLINE       void    btMatrix3x3::serialize(struct   btMatrix3x3Data& dataOut) const
     657{
     658        for (int i=0;i<3;i++)
     659                m_el[i].serialize(dataOut.m_el[i]);
     660}
     661
     662SIMD_FORCE_INLINE       void    btMatrix3x3::serializeFloat(struct      btMatrix3x3FloatData& dataOut) const
     663{
     664        for (int i=0;i<3;i++)
     665                m_el[i].serializeFloat(dataOut.m_el[i]);
     666}
     667
     668
     669SIMD_FORCE_INLINE       void    btMatrix3x3::deSerialize(const struct   btMatrix3x3Data& dataIn)
     670{
     671        for (int i=0;i<3;i++)
     672                m_el[i].deSerialize(dataIn.m_el[i]);
     673}
     674
     675SIMD_FORCE_INLINE       void    btMatrix3x3::deSerializeFloat(const struct      btMatrix3x3FloatData& dataIn)
     676{
     677        for (int i=0;i<3;i++)
     678                m_el[i].deSerializeFloat(dataIn.m_el[i]);
     679}
     680
     681SIMD_FORCE_INLINE       void    btMatrix3x3::deSerializeDouble(const struct     btMatrix3x3DoubleData& dataIn)
     682{
     683        for (int i=0;i<3;i++)
     684                m_el[i].deSerializeDouble(dataIn.m_el[i]);
     685}
     686
     687#endif //BT_MATRIX3x3_H
     688
  • code/branches/kicklib2/src/external/bullet/LinearMath/btMinMax.h

    r5781 r8284  
    1818#define GEN_MINMAX_H
    1919
     20#include "LinearMath/btScalar.h"
     21
    2022template <class T>
    2123SIMD_FORCE_INLINE const T& btMin(const T& a, const T& b)
     
    3133
    3234template <class T>
    33 SIMD_FORCE_INLINE const T& GEN_clamped(const T& a, const T& lb, const T& ub)
     35SIMD_FORCE_INLINE const T& btClamped(const T& a, const T& lb, const T& ub)
    3436{
    3537        return a < lb ? lb : (ub < a ? ub : a);
     
    5557
    5658template <class T>
    57 SIMD_FORCE_INLINE void GEN_clamp(T& a, const T& lb, const T& ub)
     59SIMD_FORCE_INLINE void btClamp(T& a, const T& lb, const T& ub)
    5860{
    5961        if (a < lb)
  • code/branches/kicklib2/src/external/bullet/LinearMath/btPoolAllocator.h

    r5781 r8284  
    5858        }
    5959
     60        int getUsedCount() const
     61        {
     62                return m_maxElements - m_freeCount;
     63        }
     64
    6065        void*   allocate(int size)
    6166        {
     
    97102        }
    98103
     104        unsigned char*  getPoolAddress()
     105        {
     106                return m_pool;
     107        }
     108
     109        const unsigned char*    getPoolAddress() const
     110        {
     111                return m_pool;
     112        }
    99113
    100114};
  • code/branches/kicklib2/src/external/bullet/LinearMath/btQuaternion.h

    r5781 r8284  
    210210        }
    211211
    212 
    213   /**@brief Return the inverse of this quaternion */
     212        /**@brief Return the axis of the rotation represented by this quaternion */
     213        btVector3 getAxis() const
     214        {
     215                btScalar s_squared = btScalar(1.) - btPow(m_floats[3], btScalar(2.));
     216                if (s_squared < btScalar(10.) * SIMD_EPSILON) //Check for divide by zero
     217                        return btVector3(1.0, 0.0, 0.0);  // Arbitrary
     218                btScalar s = btSqrt(s_squared);
     219                return btVector3(m_floats[0] / s, m_floats[1] / s, m_floats[2] / s);
     220        }
     221
     222        /**@brief Return the inverse of this quaternion */
    214223        btQuaternion inverse() const
    215224        {
     
    253262        }
    254263
     264        /**@todo document this and it's use */
     265        SIMD_FORCE_INLINE btQuaternion nearest( const btQuaternion& qd) const
     266        {
     267                btQuaternion diff,sum;
     268                diff = *this - qd;
     269                sum = *this + qd;
     270                if( diff.dot(diff) < sum.dot(sum) )
     271                        return qd;
     272                return (-qd);
     273        }
     274
     275
    255276  /**@brief Return the quaternion which is the result of Spherical Linear Interpolation between this and the other quaternion
    256277   * @param q The other quaternion to interpolate with
     
    265286                        btScalar s0 = btSin((btScalar(1.0) - t) * theta);
    266287                        btScalar s1 = btSin(t * theta);   
    267                         return btQuaternion((m_floats[0] * s0 + q.x() * s1) * d,
    268                                 (m_floats[1] * s0 + q.y() * s1) * d,
    269                                 (m_floats[2] * s0 + q.z() * s1) * d,
    270                                 (m_floats[3] * s0 + q.m_floats[3] * s1) * d);
     288                        if (dot(q) < 0) // Take care of long angle case see http://en.wikipedia.org/wiki/Slerp
     289                          return btQuaternion((m_floats[0] * s0 + -q.x() * s1) * d,
     290                                              (m_floats[1] * s0 + -q.y() * s1) * d,
     291                                              (m_floats[2] * s0 + -q.z() * s1) * d,
     292                                              (m_floats[3] * s0 + -q.m_floats[3] * s1) * d);
     293                        else
     294                          return btQuaternion((m_floats[0] * s0 + q.x() * s1) * d,
     295                                              (m_floats[1] * s0 + q.y() * s1) * d,
     296                                              (m_floats[2] * s0 + q.z() * s1) * d,
     297                                              (m_floats[3] * s0 + q.m_floats[3] * s1) * d);
     298                       
    271299                }
    272300                else
     
    379407
    380408        if (d < -1.0 + SIMD_EPSILON)
    381                 return btQuaternion(0.0f,1.0f,0.0f,0.0f); // just pick any vector
     409        {
     410                btVector3 n,unused;
     411                btPlaneSpace1(v0,n,unused);
     412                return btQuaternion(n.x(),n.y(),n.z(),0.0f); // just pick any vector that is orthogonal to v0
     413        }
    382414
    383415        btScalar  s = btSqrt((1.0f + d) * 2.0f);
  • code/branches/kicklib2/src/external/bullet/LinearMath/btQuickprof.cpp

    r5781 r8284  
    11/*
    22
    3 /***************************************************************************************************
     3***************************************************************************************************
    44**
    55** profile.cpp
     
    1414// Ogre (www.ogre3d.org).
    1515
    16 #include "LinearMath/btQuickprof.h"
    17 
    18 
    19 #ifdef USE_BT_CLOCK
     16#include "btQuickprof.h"
     17
     18#ifndef BT_NO_PROFILE
     19
    2020
    2121static btClock gProfileClock;
     22
     23
     24#ifdef __CELLOS_LV2__
     25#include <sys/sys_time.h>
     26#include <sys/time_util.h>
     27#include <stdio.h>
     28#endif
     29
     30#if defined (SUNOS) || defined (__SUNOS__)
     31#include <stdio.h>
     32#endif
     33
     34#if defined(WIN32) || defined(_WIN32)
     35
     36#define BT_USE_WINDOWS_TIMERS
     37#define WIN32_LEAN_AND_MEAN
     38#define NOWINRES
     39#define NOMCX
     40#define NOIME
     41
     42#ifdef _XBOX
     43        #include <Xtl.h>
     44#else //_XBOX
     45        #include <windows.h>
     46#endif //_XBOX
     47
     48#include <time.h>
     49
     50
     51#else //_WIN32
     52#include <sys/time.h>
     53#endif //_WIN32
     54
     55#define mymin(a,b) (a > b ? a : b)
     56
     57struct btClockData
     58{
     59
     60#ifdef BT_USE_WINDOWS_TIMERS
     61        LARGE_INTEGER mClockFrequency;
     62        DWORD mStartTick;
     63        LONGLONG mPrevElapsedTime;
     64        LARGE_INTEGER mStartTime;
     65#else
     66#ifdef __CELLOS_LV2__
     67        uint64_t        mStartTime;
     68#else
     69        struct timeval mStartTime;
     70#endif
     71#endif //__CELLOS_LV2__
     72
     73};
     74
     75///The btClock is a portable basic clock that measures accurate time in seconds, use for profiling.
     76btClock::btClock()
     77{
     78        m_data = new btClockData;
     79#ifdef BT_USE_WINDOWS_TIMERS
     80        QueryPerformanceFrequency(&m_data->mClockFrequency);
     81#endif
     82        reset();
     83}
     84
     85btClock::~btClock()
     86{
     87        delete m_data;
     88}
     89
     90btClock::btClock(const btClock& other)
     91{
     92        m_data = new btClockData;
     93        *m_data = *other.m_data;
     94}
     95
     96btClock& btClock::operator=(const btClock& other)
     97{
     98        *m_data = *other.m_data;
     99        return *this;
     100}
     101
     102
     103        /// Resets the initial reference time.
     104void btClock::reset()
     105{
     106#ifdef BT_USE_WINDOWS_TIMERS
     107        QueryPerformanceCounter(&m_data->mStartTime);
     108        m_data->mStartTick = GetTickCount();
     109        m_data->mPrevElapsedTime = 0;
     110#else
     111#ifdef __CELLOS_LV2__
     112
     113        typedef uint64_t  ClockSize;
     114        ClockSize newTime;
     115        //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory");
     116        SYS_TIMEBASE_GET( newTime );
     117        m_data->mStartTime = newTime;
     118#else
     119        gettimeofday(&m_data->mStartTime, 0);
     120#endif
     121#endif
     122}
     123
     124/// Returns the time in ms since the last call to reset or since
     125/// the btClock was created.
     126unsigned long int btClock::getTimeMilliseconds()
     127{
     128#ifdef BT_USE_WINDOWS_TIMERS
     129        LARGE_INTEGER currentTime;
     130        QueryPerformanceCounter(&currentTime);
     131        LONGLONG elapsedTime = currentTime.QuadPart -
     132                m_data->mStartTime.QuadPart;
     133                // Compute the number of millisecond ticks elapsed.
     134        unsigned long msecTicks = (unsigned long)(1000 * elapsedTime /
     135                m_data->mClockFrequency.QuadPart);
     136                // Check for unexpected leaps in the Win32 performance counter. 
     137        // (This is caused by unexpected data across the PCI to ISA
     138                // bridge, aka south bridge.  See Microsoft KB274323.)
     139                unsigned long elapsedTicks = GetTickCount() - m_data->mStartTick;
     140                signed long msecOff = (signed long)(msecTicks - elapsedTicks);
     141                if (msecOff < -100 || msecOff > 100)
     142                {
     143                        // Adjust the starting time forwards.
     144                        LONGLONG msecAdjustment = mymin(msecOff *
     145                                m_data->mClockFrequency.QuadPart / 1000, elapsedTime -
     146                                m_data->mPrevElapsedTime);
     147                        m_data->mStartTime.QuadPart += msecAdjustment;
     148                        elapsedTime -= msecAdjustment;
     149
     150                        // Recompute the number of millisecond ticks elapsed.
     151                        msecTicks = (unsigned long)(1000 * elapsedTime /
     152                                m_data->mClockFrequency.QuadPart);
     153                }
     154
     155                // Store the current elapsed time for adjustments next time.
     156                m_data->mPrevElapsedTime = elapsedTime;
     157
     158                return msecTicks;
     159#else
     160
     161#ifdef __CELLOS_LV2__
     162                uint64_t freq=sys_time_get_timebase_frequency();
     163                double dFreq=((double) freq) / 1000.0;
     164                typedef uint64_t  ClockSize;
     165                ClockSize newTime;
     166                SYS_TIMEBASE_GET( newTime );
     167                //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory");
     168
     169                return (unsigned long int)((double(newTime-m_data->mStartTime)) / dFreq);
     170#else
     171
     172                struct timeval currentTime;
     173                gettimeofday(&currentTime, 0);
     174                return (currentTime.tv_sec - m_data->mStartTime.tv_sec) * 1000 +
     175                        (currentTime.tv_usec - m_data->mStartTime.tv_usec) / 1000;
     176#endif //__CELLOS_LV2__
     177#endif
     178}
     179
     180        /// Returns the time in us since the last call to reset or since
     181        /// the Clock was created.
     182unsigned long int btClock::getTimeMicroseconds()
     183{
     184#ifdef BT_USE_WINDOWS_TIMERS
     185                LARGE_INTEGER currentTime;
     186                QueryPerformanceCounter(&currentTime);
     187                LONGLONG elapsedTime = currentTime.QuadPart -
     188                        m_data->mStartTime.QuadPart;
     189
     190                // Compute the number of millisecond ticks elapsed.
     191                unsigned long msecTicks = (unsigned long)(1000 * elapsedTime /
     192                        m_data->mClockFrequency.QuadPart);
     193
     194                // Check for unexpected leaps in the Win32 performance counter. 
     195                // (This is caused by unexpected data across the PCI to ISA
     196                // bridge, aka south bridge.  See Microsoft KB274323.)
     197                unsigned long elapsedTicks = GetTickCount() - m_data->mStartTick;
     198                signed long msecOff = (signed long)(msecTicks - elapsedTicks);
     199                if (msecOff < -100 || msecOff > 100)
     200                {
     201                        // Adjust the starting time forwards.
     202                        LONGLONG msecAdjustment = mymin(msecOff *
     203                                m_data->mClockFrequency.QuadPart / 1000, elapsedTime -
     204                                m_data->mPrevElapsedTime);
     205                        m_data->mStartTime.QuadPart += msecAdjustment;
     206                        elapsedTime -= msecAdjustment;
     207                }
     208
     209                // Store the current elapsed time for adjustments next time.
     210                m_data->mPrevElapsedTime = elapsedTime;
     211
     212                // Convert to microseconds.
     213                unsigned long usecTicks = (unsigned long)(1000000 * elapsedTime /
     214                        m_data->mClockFrequency.QuadPart);
     215
     216                return usecTicks;
     217#else
     218
     219#ifdef __CELLOS_LV2__
     220                uint64_t freq=sys_time_get_timebase_frequency();
     221                double dFreq=((double) freq)/ 1000000.0;
     222                typedef uint64_t  ClockSize;
     223                ClockSize newTime;
     224                //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory");
     225                SYS_TIMEBASE_GET( newTime );
     226
     227                return (unsigned long int)((double(newTime-m_data->mStartTime)) / dFreq);
     228#else
     229
     230                struct timeval currentTime;
     231                gettimeofday(&currentTime, 0);
     232                return (currentTime.tv_sec - m_data->mStartTime.tv_sec) * 1000000 +
     233                        (currentTime.tv_usec - m_data->mStartTime.tv_usec);
     234#endif//__CELLOS_LV2__
     235#endif
     236}
     237
     238
     239
     240
    22241
    23242inline void Profile_Get_Ticks(unsigned long int * ticks)
     
    343562
    344563
    345 #endif //USE_BT_CLOCK
    346 
     564
     565#endif //BT_NO_PROFILE
  • code/branches/kicklib2/src/external/bullet/LinearMath/btQuickprof.h

    r5781 r8284  
    1919//#define BT_NO_PROFILE 1
    2020#ifndef BT_NO_PROFILE
    21 
     21#include <stdio.h>//@todo remove this, backwards compatibility
    2222#include "btScalar.h"
    23 #include "LinearMath/btAlignedAllocator.h"
     23#include "btAlignedAllocator.h"
    2424#include <new>
    2525
     
    2727
    2828
    29 //if you don't need btClock, you can comment next line
     29
    3030#define USE_BT_CLOCK 1
    3131
    3232#ifdef USE_BT_CLOCK
    33 #ifdef __CELLOS_LV2__
    34 #include <sys/sys_time.h>
    35 #include <sys/time_util.h>
    36 #include <stdio.h>
    37 #endif
    38 
    39 #if defined (SUNOS) || defined (__SUNOS__)
    40 #include <stdio.h>
    41 #endif
    42 
    43 #if defined(WIN32) || defined(_WIN32)
    44 
    45 #define USE_WINDOWS_TIMERS
    46 #define WIN32_LEAN_AND_MEAN
    47 #define NOWINRES
    48 #define NOMCX
    49 #define NOIME
    50 #ifdef _XBOX
    51 #include <Xtl.h>
    52 #else
    53 #include <windows.h>
    54 #endif
    55 #include <time.h>
    56 
    57 #else
    58 #include <sys/time.h>
    59 #endif
    60 
    61 #define mymin(a,b) (a > b ? a : b)
    6233
    6334///The btClock is a portable basic clock that measures accurate time in seconds, use for profiling.
     
    6536{
    6637public:
    67         btClock()
    68         {
    69 #ifdef USE_WINDOWS_TIMERS
    70                 QueryPerformanceFrequency(&mClockFrequency);
    71 #endif
    72                 reset();
    73         }
     38        btClock();
    7439
    75         ~btClock()
    76         {
    77         }
     40        btClock(const btClock& other);
     41        btClock& operator=(const btClock& other);
     42
     43        ~btClock();
    7844
    7945        /// Resets the initial reference time.
    80         void reset()
    81         {
    82 #ifdef USE_WINDOWS_TIMERS
    83                 QueryPerformanceCounter(&mStartTime);
    84                 mStartTick = GetTickCount();
    85                 mPrevElapsedTime = 0;
    86 #else
    87 #ifdef __CELLOS_LV2__
    88 
    89                 typedef uint64_t  ClockSize;
    90                 ClockSize newTime;
    91                 //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory");
    92                 SYS_TIMEBASE_GET( newTime );
    93                 mStartTime = newTime;
    94 #else
    95                 gettimeofday(&mStartTime, 0);
    96 #endif
    97 
    98 #endif
    99         }
     46        void reset();
    10047
    10148        /// Returns the time in ms since the last call to reset or since
    10249        /// the btClock was created.
    103         unsigned long int getTimeMilliseconds()
    104         {
    105 #ifdef USE_WINDOWS_TIMERS
    106                 LARGE_INTEGER currentTime;
    107                 QueryPerformanceCounter(&currentTime);
    108                 LONGLONG elapsedTime = currentTime.QuadPart -
    109                         mStartTime.QuadPart;
    110 
    111                 // Compute the number of millisecond ticks elapsed.
    112                 unsigned long msecTicks = (unsigned long)(1000 * elapsedTime /
    113                         mClockFrequency.QuadPart);
    114 
    115                 // Check for unexpected leaps in the Win32 performance counter. 
    116                 // (This is caused by unexpected data across the PCI to ISA
    117                 // bridge, aka south bridge.  See Microsoft KB274323.)
    118                 unsigned long elapsedTicks = GetTickCount() - mStartTick;
    119                 signed long msecOff = (signed long)(msecTicks - elapsedTicks);
    120                 if (msecOff < -100 || msecOff > 100)
    121                 {
    122                         // Adjust the starting time forwards.
    123                         LONGLONG msecAdjustment = mymin(msecOff *
    124                                 mClockFrequency.QuadPart / 1000, elapsedTime -
    125                                 mPrevElapsedTime);
    126                         mStartTime.QuadPart += msecAdjustment;
    127                         elapsedTime -= msecAdjustment;
    128 
    129                         // Recompute the number of millisecond ticks elapsed.
    130                         msecTicks = (unsigned long)(1000 * elapsedTime /
    131                                 mClockFrequency.QuadPart);
    132                 }
    133 
    134                 // Store the current elapsed time for adjustments next time.
    135                 mPrevElapsedTime = elapsedTime;
    136 
    137                 return msecTicks;
    138 #else
    139 
    140 #ifdef __CELLOS_LV2__
    141                 uint64_t freq=sys_time_get_timebase_frequency();
    142                 double dFreq=((double) freq) / 1000.0;
    143                 typedef uint64_t  ClockSize;
    144                 ClockSize newTime;
    145                 SYS_TIMEBASE_GET( newTime );
    146                 //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory");
    147 
    148                 return (unsigned long int)((double(newTime-mStartTime)) / dFreq);
    149 #else
    150 
    151                 struct timeval currentTime;
    152                 gettimeofday(&currentTime, 0);
    153                 return (currentTime.tv_sec - mStartTime.tv_sec) * 1000 +
    154                         (currentTime.tv_usec - mStartTime.tv_usec) / 1000;
    155 #endif //__CELLOS_LV2__
    156 #endif
    157         }
     50        unsigned long int getTimeMilliseconds();
    15851
    15952        /// Returns the time in us since the last call to reset or since
    16053        /// the Clock was created.
    161         unsigned long int getTimeMicroseconds()
    162         {
    163 #ifdef USE_WINDOWS_TIMERS
    164                 LARGE_INTEGER currentTime;
    165                 QueryPerformanceCounter(&currentTime);
    166                 LONGLONG elapsedTime = currentTime.QuadPart -
    167                         mStartTime.QuadPart;
    168 
    169                 // Compute the number of millisecond ticks elapsed.
    170                 unsigned long msecTicks = (unsigned long)(1000 * elapsedTime /
    171                         mClockFrequency.QuadPart);
    172 
    173                 // Check for unexpected leaps in the Win32 performance counter. 
    174                 // (This is caused by unexpected data across the PCI to ISA
    175                 // bridge, aka south bridge.  See Microsoft KB274323.)
    176                 unsigned long elapsedTicks = GetTickCount() - mStartTick;
    177                 signed long msecOff = (signed long)(msecTicks - elapsedTicks);
    178                 if (msecOff < -100 || msecOff > 100)
    179                 {
    180                         // Adjust the starting time forwards.
    181                         LONGLONG msecAdjustment = mymin(msecOff *
    182                                 mClockFrequency.QuadPart / 1000, elapsedTime -
    183                                 mPrevElapsedTime);
    184                         mStartTime.QuadPart += msecAdjustment;
    185                         elapsedTime -= msecAdjustment;
    186                 }
    187 
    188                 // Store the current elapsed time for adjustments next time.
    189                 mPrevElapsedTime = elapsedTime;
    190 
    191                 // Convert to microseconds.
    192                 unsigned long usecTicks = (unsigned long)(1000000 * elapsedTime /
    193                         mClockFrequency.QuadPart);
    194 
    195                 return usecTicks;
    196 #else
    197 
    198 #ifdef __CELLOS_LV2__
    199                 uint64_t freq=sys_time_get_timebase_frequency();
    200                 double dFreq=((double) freq)/ 1000000.0;
    201                 typedef uint64_t  ClockSize;
    202                 ClockSize newTime;
    203                 //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory");
    204                 SYS_TIMEBASE_GET( newTime );
    205 
    206                 return (unsigned long int)((double(newTime-mStartTime)) / dFreq);
    207 #else
    208 
    209                 struct timeval currentTime;
    210                 gettimeofday(&currentTime, 0);
    211                 return (currentTime.tv_sec - mStartTime.tv_sec) * 1000000 +
    212                         (currentTime.tv_usec - mStartTime.tv_usec);
    213 #endif//__CELLOS_LV2__
    214 #endif
    215         }
    216 
     54        unsigned long int getTimeMicroseconds();
    21755private:
    218 #ifdef USE_WINDOWS_TIMERS
    219         LARGE_INTEGER mClockFrequency;
    220         DWORD mStartTick;
    221         LONGLONG mPrevElapsedTime;
    222         LARGE_INTEGER mStartTime;
    223 #else
    224 #ifdef __CELLOS_LV2__
    225         uint64_t        mStartTime;
    226 #else
    227         struct timeval mStartTime;
    228 #endif
    229 #endif //__CELLOS_LV2__
    230 
     56        struct btClockData* m_data;
    23157};
    23258
  • code/branches/kicklib2/src/external/bullet/LinearMath/btScalar.h

    r5781 r8284  
    11/*
    2 Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans  http://continuousphysics.com/Bullet/
     2Copyright (c) 2003-2009 Erwin Coumans  http://bullet.googlecode.com
    33
    44This software is provided 'as-is', without any express or implied warranty.
     
    1818#define SIMD___SCALAR_H
    1919
     20#ifdef BT_MANAGED_CODE
     21//Aligned data types not supported in managed code
     22#pragma unmanaged
     23#endif
     24
     25
    2026#include <math.h>
    21 
    2227#include <stdlib.h>//size_t for MSVC 6.0
    23 
    2428#include <cstdlib>
    2529#include <cfloat>
    2630#include <float.h>
    2731
    28 #define BT_BULLET_VERSION 274
     32/* SVN $Revision$ on $Date$ from http://bullet.googlecode.com*/
     33#define BT_BULLET_VERSION 277
    2934
    3035inline int      btGetVersion()
     
    3843
    3944
    40 #ifdef WIN32
     45#ifdef _WIN32
    4146
    4247                #if defined(__MINGW32__) || defined(__CYGWIN__) || (defined (_MSC_VER) && _MSC_VER < 1300)
     
    4449                        #define SIMD_FORCE_INLINE inline
    4550                        #define ATTRIBUTE_ALIGNED16(a) a
     51                        #define ATTRIBUTE_ALIGNED64(a) a
    4652                        #define ATTRIBUTE_ALIGNED128(a) a
    4753                #else
     
    5460                        #define SIMD_FORCE_INLINE __forceinline
    5561                        #define ATTRIBUTE_ALIGNED16(a) __declspec(align(16)) a
     62                        #define ATTRIBUTE_ALIGNED64(a) __declspec(align(64)) a
    5663                        #define ATTRIBUTE_ALIGNED128(a) __declspec (align(128)) a
    5764                #ifdef _XBOX
     
    6370                #else
    6471
    65 #if (defined (WIN32) && (_MSC_VER) && _MSC_VER >= 1400) && (!defined (BT_USE_DOUBLE_PRECISION))
     72#if (defined (_WIN32) && (_MSC_VER) && _MSC_VER >= 1400) && (!defined (BT_USE_DOUBLE_PRECISION))
    6673                        #define BT_USE_SSE
    6774                        #include <emmintrin.h>
     
    8794       
    8895#if defined     (__CELLOS_LV2__)
    89                 #define SIMD_FORCE_INLINE inline
     96                #define SIMD_FORCE_INLINE inline __attribute__((always_inline))
    9097                #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
     98                #define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
     99                #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
     100                #ifndef assert
     101                #include <assert.h>
     102                #endif
     103#ifdef BT_DEBUG
     104#ifdef __SPU__
     105#include <spu_printf.h>
     106#define printf spu_printf
     107        #define btAssert(x) {if(!(x)){printf("Assert "__FILE__ ":%u ("#x")\n", __LINE__);spu_hcmpeq(0,0);}}
     108#else
     109        #define btAssert assert
     110#endif
     111       
     112#else
     113                #define btAssert(x)
     114#endif
     115                //btFullAssert is optional, slows down a lot
     116                #define btFullAssert(x)
     117
     118                #define btLikely(_c)  _c
     119                #define btUnlikely(_c) _c
     120
     121#else
     122
     123#ifdef USE_LIBSPE2
     124
     125                #define SIMD_FORCE_INLINE __inline
     126                #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
     127                #define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
    91128                #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
    92129                #ifndef assert
     
    101138                #define btFullAssert(x)
    102139
    103                 #define btLikely(_c)  _c
    104                 #define btUnlikely(_c) _c
    105 
    106 #else
    107 
    108 #ifdef USE_LIBSPE2
    109 
    110                 #define SIMD_FORCE_INLINE __inline
    111                 #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
    112                 #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
    113                 #ifndef assert
    114                 #include <assert.h>
    115                 #endif
    116 #ifdef BT_DEBUG
    117                 #define btAssert assert
    118 #else
    119                 #define btAssert(x)
    120 #endif
    121                 //btFullAssert is optional, slows down a lot
    122                 #define btFullAssert(x)
    123 
    124140
    125141                #define btLikely(_c)   __builtin_expect((_c), 1)
     
    130146        //non-windows systems
    131147
     148#if (defined (__APPLE__) && defined (__i386__) && (!defined (BT_USE_DOUBLE_PRECISION)))
     149        #define BT_USE_SSE
     150        #include <emmintrin.h>
     151
     152        #define SIMD_FORCE_INLINE inline
     153///@todo: check out alignment methods for other platforms/compilers
     154        #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
     155        #define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
     156        #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
     157        #ifndef assert
     158        #include <assert.h>
     159        #endif
     160
     161        #if defined(DEBUG) || defined (_DEBUG)
     162                #define btAssert assert
     163        #else
     164                #define btAssert(x)
     165        #endif
     166
     167        //btFullAssert is optional, slows down a lot
     168        #define btFullAssert(x)
     169        #define btLikely(_c)  _c
     170        #define btUnlikely(_c) _c
     171
     172#else
     173
    132174                #define SIMD_FORCE_INLINE inline
    133175                ///@todo: check out alignment methods for other platforms/compilers
    134176                ///#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
     177                ///#define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
    135178                ///#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
    136179                #define ATTRIBUTE_ALIGNED16(a) a
     180                #define ATTRIBUTE_ALIGNED64(a) a
    137181                #define ATTRIBUTE_ALIGNED128(a) a
    138182                #ifndef assert
     
    150194                #define btLikely(_c)  _c
    151195                #define btUnlikely(_c) _c
    152 
     196#endif //__APPLE__
    153197
    154198#endif // LIBSPE2
     
    157201#endif
    158202
    159 /// older compilers (gcc 3.x) and Sun needs double version of sqrt etc.
    160 /// exclude Apple Intel (i's assumed to be a Macbook or new Intel Dual Core Processor)
    161 #if defined (__sun) || defined (__sun__) || defined (__sparc) || (defined (__APPLE__) && ! defined (__i386__))
    162 //use slow double float precision operation on those platforms
    163 #ifndef BT_USE_DOUBLE_PRECISION
    164 #define BT_FORCE_DOUBLE_FUNCTIONS
    165 #endif
    166 #endif
    167203
    168204///The btScalar type abstracts floating point numbers, to easily switch between double and single floating point precision.
    169205#if defined(BT_USE_DOUBLE_PRECISION)
    170206typedef double btScalar;
     207//this number could be bigger in double precision
     208#define BT_LARGE_FLOAT 1e30
    171209#else
    172210typedef float btScalar;
     211//keep BT_LARGE_FLOAT*BT_LARGE_FLOAT < FLT_MAX
     212#define BT_LARGE_FLOAT 1e18f
    173213#endif
    174214
     
    194234SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sin(x); }
    195235SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tan(x); }
    196 SIMD_FORCE_INLINE btScalar btAcos(btScalar x) { return acos(x); }
    197 SIMD_FORCE_INLINE btScalar btAsin(btScalar x) { return asin(x); }
     236SIMD_FORCE_INLINE btScalar btAcos(btScalar x) { if (x<btScalar(-1))     x=btScalar(-1); if (x>btScalar(1))      x=btScalar(1); return acos(x); }
     237SIMD_FORCE_INLINE btScalar btAsin(btScalar x) { if (x<btScalar(-1))     x=btScalar(-1); if (x>btScalar(1))      x=btScalar(1); return asin(x); }
    198238SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atan(x); }
    199239SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2(x, y); }
     
    201241SIMD_FORCE_INLINE btScalar btLog(btScalar x) { return log(x); }
    202242SIMD_FORCE_INLINE btScalar btPow(btScalar x,btScalar y) { return pow(x,y); }
     243SIMD_FORCE_INLINE btScalar btFmod(btScalar x,btScalar y) { return fmod(x,y); }
    203244
    204245#else
     
    213254        *tfptr = (0xbfcdd90a - *tfptr)>>1; /* estimate of 1/sqrt(y) */
    214255        x =  tempf;
    215         z =  y*btScalar(0.5);                        /* hoist out the “/2”    */
     256        z =  y*btScalar(0.5);
    216257        x = (btScalar(1.5)*x)-(x*x)*(x*z);         /* iteration formula     */
    217258        x = (btScalar(1.5)*x)-(x*x)*(x*z);
     
    229270SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tanf(x); }
    230271SIMD_FORCE_INLINE btScalar btAcos(btScalar x) {
    231         btAssert(x <= btScalar(1.));
     272        if (x<btScalar(-1))     
     273                x=btScalar(-1);
     274        if (x>btScalar(1))     
     275                x=btScalar(1);
    232276        return acosf(x);
    233277}
    234 SIMD_FORCE_INLINE btScalar btAsin(btScalar x) { return asinf(x); }
     278SIMD_FORCE_INLINE btScalar btAsin(btScalar x) {
     279        if (x<btScalar(-1))     
     280                x=btScalar(-1);
     281        if (x>btScalar(1))     
     282                x=btScalar(1);
     283        return asinf(x);
     284}
    235285SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atanf(x); }
    236286SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2f(x, y); }
     
    242292  SIMD_FORCE_INLINE btScalar btPow(btScalar x,btScalar y) { return powf(x,y); }
    243293  #endif
     294SIMD_FORCE_INLINE btScalar btFmod(btScalar x,btScalar y) { return fmodf(x,y); }
    244295       
    245296#endif
     
    250301#define SIMD_RADS_PER_DEG (SIMD_2_PI / btScalar(360.0))
    251302#define SIMD_DEGS_PER_RAD  (btScalar(360.0) / SIMD_2_PI)
     303#define SIMDSQRT12 btScalar(0.7071067811865475244008443621048490)
     304
     305#define btRecipSqrt(x) ((btScalar)(btScalar(1.0)/btSqrt(btScalar(x))))          /* reciprocal square root */
     306
    252307
    253308#ifdef BT_USE_DOUBLE_PRECISION
     
    440495}
    441496
    442 
     497// returns normalized value in range [-SIMD_PI, SIMD_PI]
     498SIMD_FORCE_INLINE btScalar btNormalizeAngle(btScalar angleInRadians)
     499{
     500        angleInRadians = btFmod(angleInRadians, SIMD_2_PI);
     501        if(angleInRadians < -SIMD_PI)
     502        {
     503                return angleInRadians + SIMD_2_PI;
     504        }
     505        else if(angleInRadians > SIMD_PI)
     506        {
     507                return angleInRadians - SIMD_2_PI;
     508        }
     509        else
     510        {
     511                return angleInRadians;
     512        }
     513}
     514
     515///rudimentary class to provide type info
     516struct btTypedObject
     517{
     518        btTypedObject(int objectType)
     519                :m_objectType(objectType)
     520        {
     521        }
     522        int     m_objectType;
     523        inline int getObjectType() const
     524        {
     525                return m_objectType;
     526        }
     527};
    443528#endif //SIMD___SCALAR_H
  • code/branches/kicklib2/src/external/bullet/LinearMath/btTransform.h

    r5781 r8284  
    1818#define btTransform_H
    1919
    20 #include "btVector3.h"
     20
    2121#include "btMatrix3x3.h"
     22
     23#ifdef BT_USE_DOUBLE_PRECISION
     24#define btTransformData btTransformDoubleData
     25#else
     26#define btTransformData btTransformFloatData
     27#endif
     28
     29
    2230
    2331
     
    2634class btTransform {
    2735       
     36  ///Storage for the rotation
     37        btMatrix3x3 m_basis;
     38  ///Storage for the translation
     39        btVector3   m_origin;
    2840
    2941public:
     
    196208                return identityTransform;
    197209        }
    198        
    199 private:
    200   ///Storage for the rotation
    201         btMatrix3x3 m_basis;
    202   ///Storage for the translation
    203         btVector3   m_origin;
     210
     211        void    serialize(struct        btTransformData& dataOut) const;
     212
     213        void    serializeFloat(struct   btTransformFloatData& dataOut) const;
     214
     215        void    deSerialize(const struct        btTransformData& dataIn);
     216
     217        void    deSerializeDouble(const struct  btTransformDoubleData& dataIn);
     218
     219        void    deSerializeFloat(const struct   btTransformFloatData& dataIn);
     220
    204221};
    205222
     
    235252
    236253
     254///for serialization
     255struct  btTransformFloatData
     256{
     257        btMatrix3x3FloatData    m_basis;
     258        btVector3FloatData      m_origin;
     259};
     260
     261struct  btTransformDoubleData
     262{
     263        btMatrix3x3DoubleData   m_basis;
     264        btVector3DoubleData     m_origin;
     265};
     266
     267
     268
     269SIMD_FORCE_INLINE       void    btTransform::serialize(btTransformData& dataOut) const
     270{
     271        m_basis.serialize(dataOut.m_basis);
     272        m_origin.serialize(dataOut.m_origin);
     273}
     274
     275SIMD_FORCE_INLINE       void    btTransform::serializeFloat(btTransformFloatData& dataOut) const
     276{
     277        m_basis.serializeFloat(dataOut.m_basis);
     278        m_origin.serializeFloat(dataOut.m_origin);
     279}
     280
     281
     282SIMD_FORCE_INLINE       void    btTransform::deSerialize(const btTransformData& dataIn)
     283{
     284        m_basis.deSerialize(dataIn.m_basis);
     285        m_origin.deSerialize(dataIn.m_origin);
     286}
     287
     288SIMD_FORCE_INLINE       void    btTransform::deSerializeFloat(const btTransformFloatData& dataIn)
     289{
     290        m_basis.deSerializeFloat(dataIn.m_basis);
     291        m_origin.deSerializeFloat(dataIn.m_origin);
     292}
     293
     294SIMD_FORCE_INLINE       void    btTransform::deSerializeDouble(const btTransformDoubleData& dataIn)
     295{
     296        m_basis.deSerializeDouble(dataIn.m_basis);
     297        m_origin.deSerializeDouble(dataIn.m_origin);
     298}
     299
     300
    237301#endif
    238302
  • code/branches/kicklib2/src/external/bullet/LinearMath/btTransformUtil.h

    r5781 r8284  
    2222
    2323
    24 #define SIMDSQRT12 btScalar(0.7071067811865475244008443621048490)
    25 
    26 #define btRecipSqrt(x) ((btScalar)(btScalar(1.0)/btSqrt(btScalar(x))))          /* reciprocal square root */
    2724
    2825SIMD_FORCE_INLINE btVector3 btAabbSupport(const btVector3& halfExtents,const btVector3& supportDir)
     
    3431
    3532
    36 SIMD_FORCE_INLINE void btPlaneSpace1 (const btVector3& n, btVector3& p, btVector3& q)
    37 {
    38   if (btFabs(n.z()) > SIMDSQRT12) {
    39     // choose p in y-z plane
    40     btScalar a = n[1]*n[1] + n[2]*n[2];
    41     btScalar k = btRecipSqrt (a);
    42     p.setValue(0,-n[2]*k,n[1]*k);
    43     // set q = n x p
    44     q.setValue(a*k,-n[0]*p[2],n[0]*p[1]);
    45   }
    46   else {
    47     // choose p in x-y plane
    48     btScalar a = n.x()*n.x() + n.y()*n.y();
    49     btScalar k = btRecipSqrt (a);
    50     p.setValue(-n.y()*k,n.x()*k,0);
    51     // set q = n x p
    52     q.setValue(-n.z()*p.y(),n.z()*p.x(),a*k);
    53   }
    54 }
     33
    5534
    5635
     
    11897        static void calculateDiffAxisAngleQuaternion(const btQuaternion& orn0,const btQuaternion& orn1a,btVector3& axis,btScalar& angle)
    11998        {
    120                 btQuaternion orn1 = orn0.farthest(orn1a);
     99                btQuaternion orn1 = orn0.nearest(orn1a);
    121100                btQuaternion dorn = orn1 * orn0.inverse();
    122                 ///floating point inaccuracy can lead to w component > 1..., which breaks
    123                 dorn.normalize();
    124101                angle = dorn.getAngle();
    125102                axis = btVector3(dorn.x(),dorn.y(),dorn.z());
     
    210187                        btScalar maxAngularProjectedVelocity = angVelA.length() * m_boundingRadiusA + angVelB.length() * m_boundingRadiusB;
    211188                        btVector3 relLinVel = (linVelB-linVelA);
    212                         btScalar relLinVelocLength = (linVelB-linVelA).dot(m_separatingNormal);
     189                        btScalar relLinVelocLength = relLinVel.dot(m_separatingNormal);
    213190                        if (relLinVelocLength<0.f)
    214191                        {
     
    228205        void    initSeparatingDistance(const btVector3& separatingVector,btScalar separatingDistance,const btTransform& transA,const btTransform& transB)
    229206        {
    230                 m_separatingNormal = separatingVector;
    231207                m_separatingDistance = separatingDistance;
    232                
    233                 const btVector3& toPosA = transA.getOrigin();
    234                 const btVector3& toPosB = transB.getOrigin();
    235                 btQuaternion toOrnA = transA.getRotation();
    236                 btQuaternion toOrnB = transB.getRotation();
    237                 m_posA = toPosA;
    238                 m_posB = toPosB;
    239                 m_ornA = toOrnA;
    240                 m_ornB = toOrnB;
     208
     209                if (m_separatingDistance>0.f)
     210                {
     211                        m_separatingNormal = separatingVector;
     212                       
     213                        const btVector3& toPosA = transA.getOrigin();
     214                        const btVector3& toPosB = transB.getOrigin();
     215                        btQuaternion toOrnA = transA.getRotation();
     216                        btQuaternion toOrnB = transB.getRotation();
     217                        m_posA = toPosA;
     218                        m_posB = toPosB;
     219                        m_ornA = toOrnA;
     220                        m_ornB = toOrnB;
     221                }
    241222        }
    242223
  • code/branches/kicklib2/src/external/bullet/LinearMath/btVector3.h

    r5781 r8284  
    2020
    2121#include "btScalar.h"
    22 #include "btScalar.h"
    2322#include "btMinMax.h"
     23
     24#ifdef BT_USE_DOUBLE_PRECISION
     25#define btVector3Data btVector3DoubleData
     26#define btVector3DataName "btVector3DoubleData"
     27#else
     28#define btVector3Data btVector3FloatData
     29#define btVector3DataName "btVector3FloatData"
     30#endif //BT_USE_DOUBLE_PRECISION
     31
     32
     33
     34
    2435/**@brief btVector3 can be used to represent 3D points and vectors.
    2536 * It has an un-used w component to suit 16-byte alignment when btVector3 is stored in containers. This extra component can be used by derived classes (Quaternion?) or by user
    2637 * Ideally, this class should be replaced by a platform optimized SIMD version that keeps the data in registers
    2738 */
    28 
    2939ATTRIBUTE_ALIGNED16(class) btVector3
    3040{
     
    3242
    3343#if defined (__SPU__) && defined (__CELLOS_LV2__)
    34         union {
    35                 vec_float4 mVec128;
    3644                btScalar        m_floats[4];
    37         };
    3845public:
    39         vec_float4      get128() const
    40         {
    41                 return mVec128;
     46        SIMD_FORCE_INLINE const vec_float4&     get128() const
     47        {
     48                return *((const vec_float4*)&m_floats[0]);
    4249        }
    4350public:
    4451#else //__CELLOS_LV2__ __SPU__
    45 #ifdef BT_USE_SSE // WIN32
     52#ifdef BT_USE_SSE // _WIN32
    4653        union {
    4754                __m128 mVec128;
     
    142149        SIMD_FORCE_INLINE btScalar distance(const btVector3& v) const;
    143150
     151        SIMD_FORCE_INLINE btVector3& safeNormalize()
     152        {
     153                btVector3 absVec = this->absolute();
     154                int maxIndex = absVec.maxAxis();
     155                if (absVec[maxIndex]>0)
     156                {
     157                        *this /= absVec[maxIndex];
     158                        return *this /= length();
     159                }
     160                setValue(1,0,0);
     161                return *this;
     162        }
     163
    144164  /**@brief Normalize this vector
    145165   * x^2 + y^2 + z^2 = 1 */
     
    152172        SIMD_FORCE_INLINE btVector3 normalized() const;
    153173
    154   /**@brief Rotate this vector
     174  /**@brief Return a rotated version of this vector
    155175   * @param wAxis The axis to rotate about
    156176   * @param angle The angle to rotate by */
    157         SIMD_FORCE_INLINE btVector3 rotate( const btVector3& wAxis, const btScalar angle );
     177        SIMD_FORCE_INLINE btVector3 rotate( const btVector3& wAxis, const btScalar angle ) const;
    158178
    159179  /**@brief Return the angle between this and another vector
     
    307327                        m_floats[1]=y;
    308328                        m_floats[2]=z;
    309                         m_floats[3] = 0.f;
     329                        m_floats[3] = btScalar(0.);
    310330                }
    311331
     
    316336                        v2->setValue(-y()       ,x()    ,0.);
    317337                }
     338
     339                void    setZero()
     340                {
     341                        setValue(btScalar(0.),btScalar(0.),btScalar(0.));
     342                }
     343
     344                SIMD_FORCE_INLINE bool isZero() const
     345                {
     346                        return m_floats[0] == btScalar(0) && m_floats[1] == btScalar(0) && m_floats[2] == btScalar(0);
     347                }
     348
     349                SIMD_FORCE_INLINE bool fuzzyZero() const
     350                {
     351                        return length2() < SIMD_EPSILON;
     352                }
     353
     354                SIMD_FORCE_INLINE       void    serialize(struct        btVector3Data& dataOut) const;
     355
     356                SIMD_FORCE_INLINE       void    deSerialize(const struct        btVector3Data& dataIn);
     357
     358                SIMD_FORCE_INLINE       void    serializeFloat(struct   btVector3FloatData& dataOut) const;
     359
     360                SIMD_FORCE_INLINE       void    deSerializeFloat(const struct   btVector3FloatData& dataIn);
     361
     362                SIMD_FORCE_INLINE       void    serializeDouble(struct  btVector3DoubleData& dataOut) const;
     363
     364                SIMD_FORCE_INLINE       void    deSerializeDouble(const struct  btVector3DoubleData& dataIn);
    318365
    319366};
     
    377424/**@brief Return the dot product between two vectors */
    378425SIMD_FORCE_INLINE btScalar
    379 dot(const btVector3& v1, const btVector3& v2)
     426btDot(const btVector3& v1, const btVector3& v2)
    380427{
    381428        return v1.dot(v2);
     
    385432/**@brief Return the distance squared between two vectors */
    386433SIMD_FORCE_INLINE btScalar
    387 distance2(const btVector3& v1, const btVector3& v2)
     434btDistance2(const btVector3& v1, const btVector3& v2)
    388435{
    389436        return v1.distance2(v2);
     
    393440/**@brief Return the distance between two vectors */
    394441SIMD_FORCE_INLINE btScalar
    395 distance(const btVector3& v1, const btVector3& v2)
     442btDistance(const btVector3& v1, const btVector3& v2)
    396443{
    397444        return v1.distance(v2);
     
    400447/**@brief Return the angle between two vectors */
    401448SIMD_FORCE_INLINE btScalar
    402 angle(const btVector3& v1, const btVector3& v2)
     449btAngle(const btVector3& v1, const btVector3& v2)
    403450{
    404451        return v1.angle(v2);
     
    407454/**@brief Return the cross product of two vectors */
    408455SIMD_FORCE_INLINE btVector3
    409 cross(const btVector3& v1, const btVector3& v2)
     456btCross(const btVector3& v1, const btVector3& v2)
    410457{
    411458        return v1.cross(v2);
     
    413460
    414461SIMD_FORCE_INLINE btScalar
    415 triple(const btVector3& v1, const btVector3& v2, const btVector3& v3)
     462btTriple(const btVector3& v1, const btVector3& v2, const btVector3& v3)
    416463{
    417464        return v1.triple(v2, v3);
     
    445492}
    446493
    447 SIMD_FORCE_INLINE btVector3 btVector3::rotate( const btVector3& wAxis, const btScalar angle )
     494SIMD_FORCE_INLINE btVector3 btVector3::rotate( const btVector3& wAxis, const btScalar angle ) const
    448495{
    449496        // wAxis must be a unit lenght vector
     
    489536        {
    490537                int maxIndex = -1;
    491                 btScalar maxVal = btScalar(-1e30);
     538                btScalar maxVal = btScalar(-BT_LARGE_FLOAT);
    492539                if (m_floats[0] > maxVal)
    493540                {
     
    522569        {
    523570                int minIndex = -1;
    524                 btScalar minVal = btScalar(1e30);
     571                btScalar minVal = btScalar(BT_LARGE_FLOAT);
    525572                if (m_floats[0] < minVal)
    526573                {
     
    585632                }
    586633
    587 
    588  
    589634
    590635};
     
    636681}
    637682
     683template <class T>
     684SIMD_FORCE_INLINE void btPlaneSpace1 (const T& n, T& p, T& q)
     685{
     686  if (btFabs(n[2]) > SIMDSQRT12) {
     687    // choose p in y-z plane
     688    btScalar a = n[1]*n[1] + n[2]*n[2];
     689    btScalar k = btRecipSqrt (a);
     690    p[0] = 0;
     691        p[1] = -n[2]*k;
     692        p[2] = n[1]*k;
     693    // set q = n x p
     694    q[0] = a*k;
     695        q[1] = -n[0]*p[2];
     696        q[2] = n[0]*p[1];
     697  }
     698  else {
     699    // choose p in x-y plane
     700    btScalar a = n[0]*n[0] + n[1]*n[1];
     701    btScalar k = btRecipSqrt (a);
     702    p[0] = -n[1]*k;
     703        p[1] = n[0]*k;
     704        p[2] = 0;
     705    // set q = n x p
     706    q[0] = -n[2]*p[1];
     707        q[1] = n[2]*p[0];
     708        q[2] = a*k;
     709  }
     710}
     711
     712
     713struct  btVector3FloatData
     714{
     715        float   m_floats[4];
     716};
     717
     718struct  btVector3DoubleData
     719{
     720        double  m_floats[4];
     721
     722};
     723
     724SIMD_FORCE_INLINE       void    btVector3::serializeFloat(struct        btVector3FloatData& dataOut) const
     725{
     726        ///could also do a memcpy, check if it is worth it
     727        for (int i=0;i<4;i++)
     728                dataOut.m_floats[i] = float(m_floats[i]);
     729}
     730
     731SIMD_FORCE_INLINE void  btVector3::deSerializeFloat(const struct        btVector3FloatData& dataIn)
     732{
     733        for (int i=0;i<4;i++)
     734                m_floats[i] = btScalar(dataIn.m_floats[i]);
     735}
     736
     737
     738SIMD_FORCE_INLINE       void    btVector3::serializeDouble(struct       btVector3DoubleData& dataOut) const
     739{
     740        ///could also do a memcpy, check if it is worth it
     741        for (int i=0;i<4;i++)
     742                dataOut.m_floats[i] = double(m_floats[i]);
     743}
     744
     745SIMD_FORCE_INLINE void  btVector3::deSerializeDouble(const struct       btVector3DoubleData& dataIn)
     746{
     747        for (int i=0;i<4;i++)
     748                m_floats[i] = btScalar(dataIn.m_floats[i]);
     749}
     750
     751
     752SIMD_FORCE_INLINE       void    btVector3::serialize(struct     btVector3Data& dataOut) const
     753{
     754        ///could also do a memcpy, check if it is worth it
     755        for (int i=0;i<4;i++)
     756                dataOut.m_floats[i] = m_floats[i];
     757}
     758
     759SIMD_FORCE_INLINE void  btVector3::deSerialize(const struct     btVector3Data& dataIn)
     760{
     761        for (int i=0;i<4;i++)
     762                m_floats[i] = dataIn.m_floats[i];
     763}
     764
     765
    638766#endif //SIMD__VECTOR3_H
  • code/branches/kicklib2/src/external/bullet/NEWS

    r5781 r8284  
    11
    2 For news, visit the Bullet Physics Forum at
    3 http://www.continuousphysics.com/Bullet/phpBB2/viewforum.php?f=9
     2For news, visit the Bullet Physics forums at
     3http://www.bulletphysics.org
    44
  • code/branches/kicklib2/src/external/bullet/README

    r5781 r8284  
    22Bullet is a 3D Collision Detection and Rigid Body Dynamics Library for games and animation.
    33Free for commercial use, including Playstation 3, open source under the ZLib License.
    4 Discrete and continuous collision detection, integrated into Blender 3D, and COLLADA 1.4 Physics import.
    54
    65See the Bullet_User_Manual.pdf for more info and visit the Bullet Physics Forum at
    7 http://bulletphysics.com
     6http://bulletphysics.org
  • code/branches/kicklib2/src/external/bullet/VERSION

    r5781 r8284  
    1 2.73
     12.77
  • code/branches/kicklib2/src/external/bullet/btBulletCollisionCommon.h

    r5781 r8284  
    6262#include "LinearMath/btQuickprof.h"
    6363#include "LinearMath/btIDebugDraw.h"
     64#include "LinearMath/btSerializer.h"
     65
    6466
    6567#endif //BULLET_COLLISION_COMMON_H
  • code/branches/kicklib2/src/external/bullet/btBulletDynamicsCommon.h

    r5781 r8284  
    3131#include "BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h"
    3232#include "BulletDynamics/ConstraintSolver/btSliderConstraint.h"
     33#include "BulletDynamics/ConstraintSolver/btGeneric6DofSpringConstraint.h"
     34#include "BulletDynamics/ConstraintSolver/btUniversalConstraint.h"
     35#include "BulletDynamics/ConstraintSolver/btHinge2Constraint.h"
    3336
    3437#include "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h"
  • code/branches/kicklib2/src/external/bullet/changes_orxonox.diff

    r5781 r8284  
    1 Index: btScalar.h
    2 ===================================================================
    3 --- btScalar.h  (revision 2882)
    4 +++ btScalar.h  (working copy)
    5 @@ -236,7 +236,11 @@
     1--- LinearMath/btScalar.h       Tue Aug 10 13:19:44 2010
     2+++ LinearMath/btScalar.h       Sun Feb 27 01:27:34 2011
     3@@ -286,7 +286,11 @@
    64 SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2f(x, y); }
    75 SIMD_FORCE_INLINE btScalar btExp(btScalar x) { return expf(x); }
     
    1311+  SIMD_FORCE_INLINE btScalar btPow(btScalar x,btScalar y) { return powf(x,y); }
    1412+  #endif
    15 
     13 SIMD_FORCE_INLINE btScalar btFmod(btScalar x,btScalar y) { return fmodf(x,y); }
     14       
    1615 #endif
    17 
  • code/branches/kicklib2/src/external/ogreceguirenderer/CMakeLists.txt

    r7163 r8284  
    3434  DEFINE_SYMBOL
    3535    "OGRE_GUIRENDERER_EXPORTS"
    36   VERSION
    37     1.4.9
    3836  LINK_LIBRARIES
     37    ${Boost_SYSTEM_LIBRARY}
     38    ${Boost_THREAD_LIBRARY}
     39    ${Boost_DATE_TIME_LIBRARY}
    3940    ${OGRE_LIBRARY}
    4041    ${CEGUI_LIBRARY}
  • code/branches/kicklib2/src/external/ois/CMakeLists.txt

    r5929 r8284  
    3131  OISKeyboard.h
    3232  OISMouse.h
     33  OISMultiTouch.h
    3334  OISObject.h
    3435  OISPrereqs.h
    3536
    36 COMPILATION_BEGIN OISCompilation.cpp
     37#COMPILATION_BEGIN OISCompilation.cpp
    3738  OISEffect.cpp
    3839  OISException.cpp
     
    4243  OISKeyboard.cpp
    4344  OISObject.cpp
    44 COMPILATION_END
     45#COMPILATION_END
    4546)
    4647IF(WIN32)
     
    5253ENDIF()
    5354
    54 INCLUDE_DIRECTORIES(.)
     55# Some unexplained hackery for Visual Studio 2005
     56ADD_COMPILER_FLAGS("-D_WIN32_DCOM" MSVC8)
     57
     58# MinGW doesn't come with some required Windows headers
     59IF(MINGW)
     60  INCLUDE_DIRECTORIES(${WMI_INCLUDE_DIR})
     61ENDIF()
    5562
    5663ORXONOX_ADD_LIBRARY(ois_orxonox
     
    5966    "OIS_NONCLIENT_BUILD"
    6067  VERSION
    61     1.2
     68    1.3
    6269  SOURCE_FILES
    6370    ${OIS_FILES}
     
    6572
    6673IF(WIN32)
    67   TARGET_LINK_LIBRARIES(ois_orxonox ${DIRECTX_LIBRARIES})
     74  TARGET_LINK_LIBRARIES(ois_orxonox ${DIRECTX_LIBRARIES} ${WMI_LIBRARY})
     75ELSEIF(APPLE)
     76  TARGET_LINK_LIBRARIES(ois_orxonox "/System/Library/Frameworks/IOKit.framework" "/System/Library/Frameworks/Carbon.framework")
    6877ENDIF()
  • code/branches/kicklib2/src/external/ois/OIS.h

    r5781 r8284  
    2929#include "OISKeyboard.h"
    3030#include "OISJoyStick.h"
     31#include "OISMultiTouch.h"
    3132#include "OISInputManager.h"
    3233#include "OISFactoryCreator.h"
  • code/branches/kicklib2/src/external/ois/OISConfig.h

    r5781 r8284  
    7070@remarks
    7171        Build in support for Win32 XInput (Xbox 360 Controller)
    72 @notes
    73         Not Yet Implemented
    7472*/
    7573//#define OIS_WIN32_XINPUT_SUPPORT
  • code/branches/kicklib2/src/external/ois/OISInputManager.cpp

    r5781 r8284  
    3737#elif defined OIS_APPLE_PLATFORM
    3838#  include "mac/MacInputManager.h"
     39#elif defined OIS_IPHONE_PLATFORM
     40#  include "iphone/iPhoneInputManager.h"
    3941#elif defined OIS_XBOX_PLATFORM
    4042#  include "xbox/XBoxInputManager.h"
     
    5961        m_wiiMoteSupport(0)
    6062{
     63    mFactories.clear();
     64    mFactoryObjects.clear();
    6165}
    6266
     
    111115#elif defined OIS_APPLE_PLATFORM
    112116        im = new MacInputManager();
     117#elif defined OIS_IPHONE_PLATFORM
     118        im = new iPhoneInputManager();
    113119#else
    114120        OIS_EXCEPT(E_General, "No platform library.. check build platform defines!");
  • code/branches/kicklib2/src/external/ois/OISKeyboard.h

    r5781 r8284  
    184184        {
    185185        public:
    186                 KeyEvent( Object* obj, KeyCode kc, unsigned int txt ) : EventArg(obj), key(kc), text(txt) {}
     186                KeyEvent(Object* obj, KeyCode kc, unsigned int txt) : EventArg(obj), key(kc), text(txt) {}
    187187                virtual ~KeyEvent() {}
    188188
     
    201201        public:
    202202                virtual ~KeyListener() {}
    203                 virtual bool keyPressed( const KeyEvent &arg ) = 0;
    204                 virtual bool keyReleased( const KeyEvent &arg ) = 0;           
     203                virtual bool keyPressed(const KeyEvent &arg) = 0;
     204                virtual bool keyReleased(const KeyEvent &arg) = 0;             
    205205        };
    206206
     
    220220                        A KeyCode to check
    221221                */
    222                 virtual bool isKeyDown( KeyCode key ) const = 0;
     222                virtual bool isKeyDown(KeyCode key) const = 0;
    223223
    224224                /**
     
    229229                        Send a pointer to a class derived from KeyListener or 0 to clear the callback
    230230                */
    231                 virtual void setEventCallback( KeyListener *keyListener ) { mListener = keyListener;}
     231                virtual void setEventCallback(KeyListener *keyListener) { mListener = keyListener;}
    232232
    233233                /**
     
    254254                        Off, Unicode, Ascii
    255255                */
    256                 virtual void setTextTranslation( TextTranslationMode mode );
     256                virtual void setTextTranslation(TextTranslationMode mode);
    257257
    258258                /**
     
    272272                        The string as determined from the current locale
    273273                */
    274                 virtual const std::string& getAsString( KeyCode kc ) = 0;
     274                virtual const std::string& getAsString(KeyCode kc) = 0;
    275275
    276276                //! Enum of bit position of modifer
     
    286286                        Check modifier status
    287287                */
    288                 bool isModifierDown( Modifier mod ) const;
     288                bool isModifierDown(Modifier mod) const;
    289289
    290290                /**
     
    293293                        (in the form of 1 is down and 0 is up)
    294294                */
    295                 virtual void copyKeyStates( char keys[256] ) const = 0;
     295                virtual void copyKeyStates(char keys[256]) const = 0;
    296296               
    297297        protected:
  • code/branches/kicklib2/src/external/ois/OISPrereqs.h

    r7163 r8284  
    7979#       endif
    8080#elif defined( __APPLE_CC__ ) // Apple OS X
    81 #       define OIS_APPLE_PLATFORM
    82 #       undef _OISExport
    83 #       define _OISExport __attribute__((visibility("default")))
     81    // Device                                       Simulator
     82#   if __IPHONE_OS_VERSION_MIN_REQUIRED >= 20201 || __IPHONE_OS_VERSION_MIN_REQUIRED >= 20000
     83//#   if __IPHONE_OS_VERSION_MIN_REQUIRED >= 30000 || __IPHONE_OS_VERSION_MIN_REQUIRED >= 30000
     84#       define OIS_IPHONE_PLATFORM
     85#   else
     86#       define OIS_APPLE_PLATFORM
     87#   endif
     88#   undef _OISExport
     89#   define _OISExport __attribute__((visibility("default")))
    8490#else //Probably Linux
    8591#       define OIS_LINUX_PLATFORM
     
    95101//-------------- Common Classes, Enums, and Typdef's -------------------------//
    96102#define OIS_VERSION_MAJOR 1
    97 #define OIS_VERSION_MINOR 2
     103#define OIS_VERSION_MINOR 3
    98104#define OIS_VERSION_PATCH 0
    99 #define OIS_VERSION_NAME "Smash"
     105#define OIS_VERSION_NAME "1.3.0"
    100106
    101107#define OIS_VERSION ((OIS_VERSION_MAJOR << 16) | (OIS_VERSION_MINOR << 8) | OIS_VERSION_PATCH)
     
    110116        class Mouse;
    111117        class JoyStick;
     118    class MultiTouch;
    112119        class KeyListener;
    113120        class MouseListener;
     121    class MultiTouchListener;
    114122        class JoyStickListener;
    115123        class Interface;
     
    130138    enum Type
    131139        {
    132                 OISUnknown   = 0,
    133                 OISKeyboard  = 1,
    134                 OISMouse     = 2,
    135                 OISJoyStick  = 3,
    136                 OISTablet    = 4
     140                OISUnknown       = 0,
     141                OISKeyboard      = 1,
     142                OISMouse         = 2,
     143                OISJoyStick      = 3,
     144                OISTablet        = 4,
     145                OISMultiTouch    = 5
    137146        };
    138147
  • code/branches/kicklib2/src/external/ois/ReadMe.txt

    r5781 r8284  
    55The zlib/libpng License
    66
    7 Copyright (c) 2005-2007 Phillip Castaneda (pjcast -- www.wreckedgames.com)
     7Copyright (c) 2005-2010 Phillip Castaneda (pjcast -- www.wreckedgames.com)
    88
    99This software is provided 'as-is', without any express or implied warranty. In no
     
    4646Win32/
    4747        Contains Visual Studio .Net Solution Files
    48         Contains CodeBlocks + MinGW + StlPort project files for OIS
     48        Contains CodeBlocks project files for OIS
    4949       
    5050        ---- Dependencies ------------------------------------------------------
    5151        DirectInput 8
    52         Ogre & CEGUI 0.4.0 If building CEGUIOgre OIS Demo
    5352
    54         SDL/
    55                 A test bed for an OIS InputManager with SDL as the backend. Not recommended;
    56                 however, useful for platforms with non-native OIS ports for temporary use.
    5753
    5854Linux/
    5955        ---- Dependencies ------------------------------------------------------
    6056        X11
    61         Ogre (GLX Platform) & CEGUI 0.4.0 If building CEGUIOgre OIS Demo
    62         Newer Linux Kernel (2.6+ ?) for Event API - else, use --disable-joyevents
     57        Newer Linux Kernel (2.6+ ?) for Event API
    6358
    6459        Steps to build on Linux:
     
    6964        ---- Configure build options --------------------------------------------
    7065        ./configure --help              --- List all configure options
    71         ./configure --disable-ogre      --- Disables CEGUIOgre ActionMapping Demo
    72         ./configure --disable-joyevents --- Uses /dev/input/jsX instead of
    73                                             /dev/input/eventX
     66
    7467
    7568LinuxCB/
     
    8073
    8174Mac/
    82        
    83         XCode-1.5/
    84                 Non-complete native OIS port.
    85 
    8675        XCode-2.2/
    87                 Working, complete, OIS port to OSX using SDL as a backend.
     76                Working, mostly complete OSX vackend.
  • code/branches/kicklib2/src/external/ois/VERSION

    r5781 r8284  
    1 OIS v1_2 CVS updated on 2009/01/24
    2 Note that this is not CVS HEAD, but v1_2 branch!
    3 
     1OIS SVN v1.3 branch updated on 2011/02/20 (revision 32)
     2https://wgois.svn.sourceforge.net/svnroot/wgois/ois/branches/v1-3/
  • code/branches/kicklib2/src/external/ois/changes_orxonox.diff

    r7163 r8284  
    1010                        //Ignorable Dll interface warning...
    1111 #           if !defined(OIS_MINGW_COMPILER)
     12
     13
    1214--- linux/EventHelpers.cpp      (revision 5668)
    1315+++ linux/EventHelpers.cpp      (working copy)
     
    3739+++ win32/Win32ForceFeedback.cpp
    3840@@ -25,7 +25,7 @@
    39  #include <Math.h>
     41 #include <math.h>
    4042 
    4143 // 0 = No trace; 1 = Important traces; 2 = Debug traces
     
    4547 #if (defined (_DEBUG) || defined(OIS_WIN32_JOYFF_DEBUG))
    4648   #include <iostream>
     49
     50
     51--- win32/Win32JoyStick.cpp
     52+++ win32/Win32JoyStick.cpp
     53@@ -26,6 +26,14 @@
     54 #include "OISEvents.h"
     55 #include "OISException.h"
     56 
     57+// (Orxonox): Required for MinGW to compile properly
     58+#ifdef __MINGW32__
     59+#  include <oaidl.h>
     60+#  ifndef __MINGW_EXTENSION
     61+#    define __MINGW_EXTENSION __extension__
     62+#  endif
     63+#endif
     64+
     65 #include <cassert>
     66 #include <wbemidl.h>
     67 #include <oleauto.h>
     68@@ -39,6 +47,11 @@
     69    }
     70 #endif
     71 
     72+// (Orxonox): MinGW doesn't have swscanf_s
     73+#ifdef __MINGW32__
     74+#      define swscanf_s swscanf
     75+#endif
     76+
     77 #ifdef OIS_WIN32_XINPUT_SUPPORT
     78 #      pragma comment(lib, "xinput.lib")
     79 #endif
     80@@ -583,7 +596,12 @@
     81     bool bCleanupCOM = SUCCEEDED(hr);
     82 
     83     // Create WMI
     84+    // (Orxonox): Fix for MinGW
     85+#ifdef __MINGW32__
     86+    hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pIWbemLocator);
     87+#else
     88     hr = CoCreateInstance(__uuidof(WbemLocator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID*)&pIWbemLocator);
     89+#endif
     90     if( FAILED(hr) || pIWbemLocator == NULL )
     91         goto LCleanup;
     92 
     93
     94--- mac/MacHIDManager.cpp
     95+++ mac/MacHIDManager.cpp
     96@@ -406,6 +406,7 @@
     97                        switch(iType)
     98                        {
     99                                case OISJoyStick:
     100+                {
     101                                        int totalDevs = totalDevices(iType);
     102                                        int freeDevs = freeDevices(iType);
     103                                        int devID = totalDevs - freeDevs;
     104@@ -413,6 +414,7 @@
     105                                        obj = new MacJoyStick((*it)->combinedKey, bufferMode, *it, creator, devID);
     106                                        (*it)->inUse = true;
     107                                        return obj;
     108+                }
     109                                case OISTablet:
     110                                        //Create MacTablet
     111                                        break;
  • code/branches/kicklib2/src/external/ois/linux/LinuxInputManager.cpp

    r5781 r8284  
    4040        hideMouse = true;
    4141        mGrabs = true;
    42         useXRepeat = false;
    4342        keyboardUsed = mouseUsed = false;
    4443
     
    7473
    7574        //--------- Keyboard Settings ------------//
    76         i = paramList.find("XAutoRepeatOn");
    77         if( i != paramList.end() )
    78                 if( i->second == "true" )
    79                         useXRepeat = true;
    80 
    8175        i = paramList.find("x11_keyboard_grab");
    8276        if( i != paramList.end() )
     
    172166        {
    173167                if( keyboardUsed == false )
    174                         obj = new LinuxKeyboard(this, bufferMode, grabKeyboard, useXRepeat);
     168                        obj = new LinuxKeyboard(this, bufferMode, grabKeyboard);
    175169                break;
    176170        }
  • code/branches/kicklib2/src/external/ois/linux/LinuxInputManager.h

    r5781 r8284  
    101101                bool mGrabs;
    102102                bool hideMouse;
    103 
    104                 //! By default, keyboard disables XRepeatRate
    105                 bool useXRepeat;
    106103        };
    107104}
  • code/branches/kicklib2/src/external/ois/linux/LinuxJoyStickEvents.cpp

    r5781 r8284  
    9696        //We are in non blocking mode - we just read once, and try to fill up buffer
    9797        input_event js[JOY_BUFFERSIZE];
    98         int ret = read(mJoyStick, &js, sizeof(struct input_event) * JOY_BUFFERSIZE);
    99         if( ret <= 0 )
    100                 return;
    101 
    102         //Determine how many whole events re read up
    103         ret /= sizeof(struct input_event);
    104         for(int i = 0; i < ret; ++i)
     98        while(true)
    10599        {
    106                 switch(js[i].type)
     100                int ret = read(mJoyStick, &js, sizeof(struct input_event) * JOY_BUFFERSIZE);
     101        if( ret < 0 )
     102                        break;
     103
     104                //Determine how many whole events re read up
     105                ret /= sizeof(struct input_event);
     106                for(int i = 0; i < ret; ++i)
    107107                {
    108                 case EV_KEY:  //Button
    109                 {
    110                         int button = mButtonMap[js[i].code];
    111 
    112                         #ifdef OIS_LINUX_JOY_DEBUG
    113                           cout << "\nButton Code: " << js[i].code << ", OIS Value: " << button << endl;
    114                         #endif
    115 
    116                         //Check to see whether push or released event...
    117                         if(js[i].value)
    118                         {
    119                                 mState.mButtons[button] = true;
    120                                 if( mBuffered && mListener )
    121                                         if(!mListener->buttonPressed(JoyStickEvent(this,mState), button)) return;
    122                         }
    123                         else
    124                         {
    125                                 mState.mButtons[button] = false;
    126                                 if( mBuffered && mListener )
    127                                         if(!mListener->buttonReleased(JoyStickEvent(this,mState), button)) return;
    128                         }
    129                         break;
    130                 }
    131 
    132                 case EV_ABS:  //Absolute Axis
    133                 {
    134                         //A Stick (BrakeDefine is the highest possible Axis)
    135                         if( js[i].code <= ABS_BRAKE )
    136                         {
    137                                 int axis = mAxisMap[js[i].code];
    138                                 assert( axis < 32 && "Too many axes (Max supported is 32). Report this to OIS forums!" );
    139 
    140                                 axisMoved[axis] = true;
    141 
    142                                 //check for rescaling:
    143                                 if( mRanges[axis].min == JoyStick::MIN_AXIS && mRanges[axis].max != JoyStick::MAX_AXIS )
    144                                 {       //Scale is perfect
    145                                         mState.mAxes[axis].abs = js[i].value;
     108                        switch(js[i].type)
     109                        {
     110                        case EV_KEY:  //Button
     111                        {
     112                                int button = mButtonMap[js[i].code];
     113
     114                                #ifdef OIS_LINUX_JOY_DEBUG
     115                                  cout << "\nButton Code: " << js[i].code << ", OIS Value: " << button << endl;
     116                                #endif
     117
     118                                //Check to see whether push or released event...
     119                                if(js[i].value)
     120                                {
     121                                        mState.mButtons[button] = true;
     122                                        if( mBuffered && mListener )
     123                                                if(!mListener->buttonPressed(JoyStickEvent(this,mState), button)) return;
    146124                                }
    147125                                else
    148                                 {       //Rescale
    149                                         float proportion = (float)(js[i].value-mRanges[axis].max)/(float)(mRanges[axis].min-mRanges[axis].max);
    150                                         mState.mAxes[axis].abs = (int)(32767.0f - (65535.0f * proportion));
     126                                {
     127                                        mState.mButtons[button] = false;
     128                                        if( mBuffered && mListener )
     129                                                if(!mListener->buttonReleased(JoyStickEvent(this,mState), button)) return;
    151130                                }
    152                         }
    153                         else if( js[i].code <= ABS_HAT3Y ) //A POV - Max four POVs allowed
    154                         {
    155                                 //Normalise the POV to between 0-7
    156                                 //Even is X Axis, Odd is Y Axis
    157                                 unsigned char LinuxPovNumber = js[i].code - 16;
    158                                 short OIS_POVIndex = POV_MASK[LinuxPovNumber];
    159 
    160                                 //Handle X Axis first (Even) (left right)
    161                                 if((LinuxPovNumber & 0x0001) == 0)
     131                                break;
     132                        }
     133
     134                        case EV_ABS:  //Absolute Axis
     135                        {
     136                                //A Stick (BrakeDefine is the highest possible Axis)
     137                                if( js[i].code <= ABS_BRAKE )
    162138                                {
    163                                         //Why do this? Because, we use a bit field, and when this axis is east,
    164                                         //it can't possibly be west too. So clear out the two X axes, then refil
    165                                         //it in with the new direction bit.
    166                                         //Clear the East/West Bit Flags first
    167                                         mState.mPOV[OIS_POVIndex].direction &= 0x11110011;
    168                                         if( js[i].value == -1 ) //Left
    169                                                 mState.mPOV[OIS_POVIndex].direction |= Pov::West;
    170                                         else if( js[i].value == 1 ) //Right
    171                                                 mState.mPOV[OIS_POVIndex].direction |= Pov::East;
     139                                        int axis = mAxisMap[js[i].code];
     140                                        assert( axis < 32 && "Too many axes (Max supported is 32). Report this to OIS forums!" );
     141
     142                                        axisMoved[axis] = true;
     143
     144                                        //check for rescaling:
     145                                        if( mRanges[axis].min == JoyStick::MIN_AXIS && mRanges[axis].max != JoyStick::MAX_AXIS )
     146                                        {       //Scale is perfect
     147                                                mState.mAxes[axis].abs = js[i].value;
     148                                        }
     149                                        else
     150                                        {       //Rescale
     151                                                float proportion = (float)(js[i].value-mRanges[axis].max)/(float)(mRanges[axis].min-mRanges[axis].max);
     152                                                mState.mAxes[axis].abs = (int)(32767.0f - (65535.0f * proportion));
     153                                        }
    172154                                }
    173                                 //Handle Y Axis (Odd) (up down)
    174                                 else
     155                                else if( js[i].code <= ABS_HAT3Y ) //A POV - Max four POVs allowed
    175156                                {
    176                                         //Clear the North/South Bit Flags first
    177                                         mState.mPOV[OIS_POVIndex].direction &= 0x11111100;
    178                                         if( js[i].value == -1 ) //Up
    179                                                 mState.mPOV[OIS_POVIndex].direction |= Pov::North;
    180                                         else if( js[i].value == 1 ) //Down
    181                                                 mState.mPOV[OIS_POVIndex].direction |= Pov::South;
     157                                        //Normalise the POV to between 0-7
     158                                        //Even is X Axis, Odd is Y Axis
     159                                        unsigned char LinuxPovNumber = js[i].code - 16;
     160                                        short OIS_POVIndex = POV_MASK[LinuxPovNumber];
     161
     162                                        //Handle X Axis first (Even) (left right)
     163                                        if((LinuxPovNumber & 0x0001) == 0)
     164                                        {
     165                                                //Why do this? Because, we use a bit field, and when this axis is east,
     166                                                //it can't possibly be west too. So clear out the two X axes, then refil
     167                                                //it in with the new direction bit.
     168                                                //Clear the East/West Bit Flags first
     169                                                mState.mPOV[OIS_POVIndex].direction &= 0x11110011;
     170                                                if( js[i].value == -1 ) //Left
     171                                                        mState.mPOV[OIS_POVIndex].direction |= Pov::West;
     172                                                else if( js[i].value == 1 ) //Right
     173                                                        mState.mPOV[OIS_POVIndex].direction |= Pov::East;
     174                                        }
     175                                        //Handle Y Axis (Odd) (up down)
     176                                        else
     177                                        {
     178                                                //Clear the North/South Bit Flags first
     179                                                mState.mPOV[OIS_POVIndex].direction &= 0x11111100;
     180                                                if( js[i].value == -1 ) //Up
     181                                                        mState.mPOV[OIS_POVIndex].direction |= Pov::North;
     182                                                else if( js[i].value == 1 ) //Down
     183                                                        mState.mPOV[OIS_POVIndex].direction |= Pov::South;
     184                                        }
     185
     186                                        if( mBuffered && mListener )
     187                                                if( mListener->povMoved( JoyStickEvent(this,mState), OIS_POVIndex) == false )
     188                                                        return;
    182189                                }
    183 
    184                                 if( mBuffered && mListener )
    185                                         if( mListener->povMoved( JoyStickEvent(this,mState), OIS_POVIndex) == false )
    186                                                 return;
    187                         }
    188                         break;
    189                 }
    190 
    191                
    192                 case EV_REL: //Relative Axes (Do any joystick actually have a relative axis?)
    193 #ifdef OIS_LINUX_JOY_DEBUG
    194                     cout << "\nWarning: Relatives axes not supported yet" << endl;
    195 #endif
    196                         break;
    197                 default: break;
     190                                break;
     191                        }
     192
     193                       
     194                        case EV_REL: //Relative Axes (Do any joystick actually have a relative axis?)
     195        #ifdef OIS_LINUX_JOY_DEBUG
     196                                cout << "\nWarning: Relatives axes not supported yet" << endl;
     197        #endif
     198                                break;
     199                        default: break;
     200                        }
    198201                }
    199202        }
  • code/branches/kicklib2/src/external/ois/linux/LinuxKeyboard.cpp

    r5781 r8284  
    3333#include <iostream>
    3434//-------------------------------------------------------------------//
    35 LinuxKeyboard::LinuxKeyboard(InputManager* creator, bool buffered, bool grab, bool useXRepeat)
     35LinuxKeyboard::LinuxKeyboard(InputManager* creator, bool buffered, bool grab)
    3636        : Keyboard(creator->inputSystemName(), buffered, 0, creator)
    3737{
     
    4343        grabKeyboard = grab;
    4444        keyFocusLost = false;
    45 
    46         xAutoRepeat = useXRepeat;
    47         oldXAutoRepeat = false;
    4845
    4946        //X Key Map to KeyCode
     
    213210
    214211        keyFocusLost = false;
    215 
    216         if( xAutoRepeat == false )
    217         {
    218                 //We do not want to blindly turn on autorepeat later when quiting if
    219                 //it was not on to begin with.. So, let us check and see first
    220                 XKeyboardState old;
    221                 XGetKeyboardControl( display, &old );
    222                 oldXAutoRepeat = false;
    223 
    224                 if( old.global_auto_repeat == AutoRepeatModeOn )
    225                         oldXAutoRepeat = true;
    226 
    227                 XAutoRepeatOff( display );
    228         }
    229212}
    230213
     
    234217        if( display )
    235218        {
    236                 if( oldXAutoRepeat )
    237                         XAutoRepeatOn(display);
    238 
    239219                if( grabKeyboard )
    240220                        XUngrabKeyboard(display, CurrentTime);
     
    303283
    304284        while( XPending(display) > 0 )
    305         {               XNextEvent(display, &event);            if( KeyPress == event.type )
     285        {
     286                XNextEvent(display, &event);
     287
     288                if(KeyPress == event.type)
    306289                {
    307290                        unsigned int character = 0;
    308291
    309                         if( mTextMode != Off )
     292                        if(mTextMode != Off)
    310293                        {
    311294                                unsigned char buffer[6] = {0,0,0,0,0,0};
     
    332315                        if( event.xkey.state & Mod1Mask && key == XK_Tab )
    333316                                linMan->_setGrabState(false);
    334                 }               else if( KeyRelease == event.type )
     317                }
     318                else if(KeyRelease == event.type)
    335319                {
    336                         //Mask out the modifier states X sets.. or we will get improper values
    337                         event.xkey.state &= ~ShiftMask;
    338                         event.xkey.state &= ~LockMask;
    339 
    340                         //Else, it is a valid key release
    341                         XLookupString(&event.xkey,NULL,0,&key,NULL);
    342                         _injectKeyUp(key);              }
     320                        if(!_isKeyRepeat(event))
     321                        {
     322                                //Mask out the modifier states X sets.. or we will get improper values
     323                                event.xkey.state &= ~ShiftMask;
     324                                event.xkey.state &= ~LockMask;
     325
     326                                XLookupString(&event.xkey,NULL,0,&key,NULL);
     327                                _injectKeyUp(key);
     328                        }
     329                }
    343330        }
    344331
  • code/branches/kicklib2/src/external/ois/linux/LinuxKeyboard.h

    r5781 r8284  
    3434        {
    3535        public:
    36                 LinuxKeyboard(InputManager* creator, bool buffered, bool grab, bool useXRepeat );
     36                LinuxKeyboard(InputManager* creator, bool buffered, bool grab);
    3737                virtual ~LinuxKeyboard();
    3838
     
    5959
    6060        protected:
     61                inline bool _isKeyRepeat(XEvent &event)
     62                {
     63                        //When a key is repeated, there will be two events: released, followed by another immediate pressed. So check to see if another pressed is present     
     64                        if(!XPending(display))
     65                                return false;
     66
     67                        XEvent e;
     68                        XPeekEvent(display, &e);
     69                        if(e.type == KeyPress && e.xkey.keycode == event.xkey.keycode && (e.xkey.time - event.xkey.time) < 2)
     70                        {
     71                                XNextEvent(display, &e);
     72                                return true;
     73                        }
     74
     75                        return false;
     76                }
     77
    6178                bool _injectKeyDown( KeySym key, int text );
    6279                bool _injectKeyUp( KeySym key );
     
    7592                bool keyFocusLost;
    7693
    77                 bool xAutoRepeat;
    78                 bool oldXAutoRepeat;
    79 
    8094                std::string mGetString;
    8195        };
  • code/branches/kicklib2/src/external/ois/linux/LinuxMouse.cpp

    r5781 r8284  
    173173
    174174                        //Compute this frames Relative X & Y motion
    175                         mState.X.rel = event.xmotion.x - oldXMouseX;
    176                         mState.Y.rel = event.xmotion.y - oldXMouseY;
     175                        int dx = event.xmotion.x - oldXMouseX;
     176                        int dy = event.xmotion.y - oldXMouseY;
    177177               
    178178                        //Store old values for next time to compute relative motion
     
    180180                        oldXMouseY = event.xmotion.y;
    181181
    182                         mState.X.abs += mState.X.rel;
    183                         mState.Y.abs += mState.Y.rel;
     182                        mState.X.abs += dx;
     183                        mState.Y.abs += dy;
     184                        mState.X.rel += dx;
     185                        mState.Y.rel += dy;
    184186
    185187                        //Check to see if we are grabbing the mouse to the window (requires clipping and warping)
  • code/branches/kicklib2/src/external/ois/linux/LinuxPrereqs.h

    r5781 r8284  
    3232
    3333//! Max number of elements to collect from buffered input
    34 #define JOY_BUFFERSIZE 10
     34#define JOY_BUFFERSIZE 64
    3535
    3636namespace OIS
  • code/branches/kicklib2/src/external/ois/mac/CMakeLists.txt

    r5929 r8284  
    33  MacHIDManager.h
    44  MacInputManager.h
     5  MacJoyStick.h
    56  MacKeyboard.h
    67  MacMouse.h
    78  MacPrereqs.h
    89
    9 COMPILATION_BEGIN OISMacCompilation.cpp
     10#COMPILATION_BEGIN OISMacCompilation.cpp
    1011  MacHelpers.cpp
    1112  MacHIDManager.cpp
    1213  MacInputManager.cpp
     14  MacJoyStick.cpp
    1315  MacKeyboard.cpp
    1416  MacMouse.cpp
    15 COMPILATION_END
     17#COMPILATION_END
    1618)
  • code/branches/kicklib2/src/external/ois/mac/MacHIDManager.cpp

    r5781 r8284  
    2020 
    2121 3. This notice may not be removed or altered from any source distribution.
    22 */
     22 */
    2323#include "mac/MacHIDManager.h"
     24#include "mac/MacJoyStick.h"
    2425#include "OISException.h"
    2526#include "OISObject.h"
     
    4243{
    4344        CFTypeRef temp = CFDictionaryGetValue(dict, OIS_CFString(keyName));
    44 
     45       
    4546        if(temp && CFGetTypeID(temp) == CFArrayGetTypeID())
    4647                return (CFArrayRef)temp;
     
    5354{
    5455        CFTypeRef temp = CFDictionaryGetValue(dict, OIS_CFString(keyName));
    55 
     56       
    5657        if(temp && CFGetTypeID(temp) == CFStringGetTypeID())
    5758                return (CFStringRef)temp;
     
    6465{
    6566        CFTypeRef temp = CFDictionaryGetValue(dict, OIS_CFString(keyName));
    66 
     67       
    6768        if(temp && CFGetTypeID(temp) == CFNumberGetTypeID())
    6869                return (CFNumberRef)temp;
     
    8384{
    8485        CFTypeRef temp = CFArrayGetValueAtIndex(array, idx);
    85 
     86       
    8687        if(temp && CFGetTypeID(temp) == CFDictionaryGetTypeID())
    8788                return (CFDictionaryRef)temp;
     
    9394int getInt32(CFNumberRef ref)
    9495{
    95    int r = 0;
    96    if (r)
    97       CFNumberGetValue(ref, kCFNumberIntType, &r);
    98    return r;
     96        int r = 0;
     97        if (r)
     98                CFNumberGetValue(ref, kCFNumberIntType, &r);
     99        return r;
    99100}
    100101
     
    111112//------------------------------------------------------------------------------------------------------//
    112113void MacHIDManager::initialize()
     114{
     115        //Make the search more specific by adding usage flags
     116        int usage = kHIDUsage_GD_Joystick;
     117        int page = kHIDPage_GenericDesktop;
     118       
     119        io_iterator_t iterator = lookUpDevices(usage, page);
     120       
     121        if(iterator)
     122                iterateAndOpenDevices(iterator);
     123       
     124        //Doesn't support multiple usage flags, iterate twice
     125        usage = kHIDUsage_GD_GamePad;
     126        iterator = lookUpDevices(usage, page);
     127       
     128        if(iterator)
     129                iterateAndOpenDevices(iterator);
     130}
     131
     132//------------------------------------------------------------------------------------------------------//
     133io_iterator_t MacHIDManager::lookUpDevices(int usage, int page)
    113134{
    114135        CFMutableDictionaryRef deviceLookupMap = IOServiceMatching(kIOHIDDeviceKey);
    115136        if(!deviceLookupMap)
    116137                OIS_EXCEPT(E_General, "Could not setup HID device search parameters");
    117 
    118         //Make the search more specific by adding usage flags
    119         int usage = kHIDUsage_GD_GamePad | kHIDUsage_GD_Joystick,
    120             page  = kHIDPage_GenericDesktop;
    121 
    122         CFNumberRef usageRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage),
    123                                 pageRef  = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page);
    124 
     138       
     139        CFNumberRef usageRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage);
     140        CFNumberRef pageRef  = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page);
     141       
    125142        CFDictionarySetValue(deviceLookupMap, CFSTR(kIOHIDPrimaryUsageKey), usageRef);
    126143        CFDictionarySetValue(deviceLookupMap, CFSTR(kIOHIDPrimaryUsagePageKey), pageRef);
    127 
     144       
    128145        //IOServiceGetMatchingServices consumes the map so we do not have to release it ourself
    129146        io_iterator_t iterator = 0;
    130147        IOReturn result = IOServiceGetMatchingServices(kIOMasterPortDefault, deviceLookupMap, &iterator);
    131         if (result == kIOReturnSuccess && iterator)
    132         {
    133                 io_object_t hidDevice = 0;
    134                 while ((hidDevice = IOIteratorNext(iterator)) !=0)
     148       
     149        CFRelease(usageRef);
     150        CFRelease(pageRef);
     151       
     152        if(result == kIOReturnSuccess)
     153        {
     154                return iterator;
     155        }
     156        //TODO: Throw exception instead?
     157        else
     158        {
     159                return 0;
     160        }
     161}
     162
     163//------------------------------------------------------------------------------------------------------//
     164void MacHIDManager::iterateAndOpenDevices(io_iterator_t iterator)
     165{
     166        io_object_t hidDevice = 0;
     167        while ((hidDevice = IOIteratorNext(iterator)) !=0)
     168        {
     169                //Get the current registry items property map
     170                CFMutableDictionaryRef propertyMap = 0;
     171                if (IORegistryEntryCreateCFProperties(hidDevice, &propertyMap, kCFAllocatorDefault, kNilOptions) == KERN_SUCCESS && propertyMap)
    135172                {
    136                         //Get the current registry items property map
    137                         CFMutableDictionaryRef propertyMap = 0;
    138                         if (IORegistryEntryCreateCFProperties(hidDevice, &propertyMap, kCFAllocatorDefault, kNilOptions) == KERN_SUCCESS && propertyMap)
     173                        //Go through device to find all needed info
     174                        HidInfo* hid = enumerateDeviceProperties(propertyMap);
     175                       
     176                        if(hid)
    139177                        {
    140                                 //Go through device to find all needed info
    141                                 HidInfo* hid = enumerateDeviceProperties(propertyMap);
    142                                 if(hid)
    143                                         mDeviceList.push_back(hid);
    144                                        
    145178                                //todo - we need to hold an open interface so we do not have to enumerate again later
    146179                                //should be able to watch for device removals also
    147 
    148                                 /// Testing opening / closing interface
    149                                 //IOCFPlugInInterface **pluginInterface = NULL;
    150                                 //SInt32 score = 0;
    151                                 //if (IOCreatePlugInInterfaceForService(hidDevice, kIOHIDDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &pluginInterface, &score) == kIOReturnSuccess)
    152                                 //{
    153                                 //      IOHIDDeviceInterface **interface;
    154                                 //      HRESULT pluginResult = (*pluginInterface)->QueryInterface(pluginInterface, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (void **)&(interface));
    155                                 //      if(pluginResult == S_OK)
    156                                 //              cout << "Successfully created plugin interface for device\n";
    157                                 //      else
    158                                 //              cout << "Not able to create plugin interface\n";
    159 
    160                                 //      IODestroyPlugInInterface(pluginInterface);
    161 
    162                                 //      if ((*interface)->open(interface, 0) == KERN_SUCCESS)
    163                                 //              cout << "Opened interface.\n";
    164                                 //      else
    165                                 //              cout << "Failed to open\n";
    166 
    167                                 //      (*interface)->close(interface);
    168                                 //}
    169                                 //
     180                               
     181                                // Testing opening / closing interface
     182                                IOCFPlugInInterface **pluginInterface = NULL;
     183                                SInt32 score = 0;
     184                                if (IOCreatePlugInInterfaceForService(hidDevice, kIOHIDDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &pluginInterface, &score) == kIOReturnSuccess)
     185                                {
     186                                        IOHIDDeviceInterface **interface;
     187                                       
     188                                        HRESULT pluginResult = (*pluginInterface)->QueryInterface(pluginInterface, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (void **)&(interface));
     189                                       
     190                                        if(pluginResult != S_OK)
     191                                                OIS_EXCEPT(E_General, "Not able to create plugin interface");
     192                                       
     193                                        IODestroyPlugInInterface(pluginInterface);
     194                                       
     195                                        hid->interface = interface;
     196                                       
     197                                        //Check for duplicates - some devices have multiple usage
     198                                        if(std::find(mDeviceList.begin(), mDeviceList.end(), hid) == mDeviceList.end())
     199                                                mDeviceList.push_back(hid);
     200                                }
    170201                        }
    171202                }
    172 
    173                 IOObjectRelease(iterator);
    174         }
    175 
    176         CFRelease(usageRef);
    177         CFRelease(pageRef);
     203        }
     204       
     205        IOObjectRelease(iterator);
    178206}
    179207
     
    188216        if (str)
    189217                info->vendor = CFStringGetCStringPtr(str, CFStringGetSystemEncoding());
    190 
     218       
    191219        str = getDictionaryItemAsRef<CFStringRef>(propertyMap, kIOHIDProductKey);
    192220        if (str)
    193221                info->productKey = CFStringGetCStringPtr(str, CFStringGetSystemEncoding());
    194                
     222       
    195223        info->combinedKey = info->vendor + " " + info->productKey;
    196 
     224       
    197225        //Go through all items in this device (i.e. buttons, hats, sticks, axes, etc)
    198226        CFArrayRef array = getDictionaryItemAsRef<CFArrayRef>(propertyMap, kIOHIDElementKey);
     
    200228                for (int i = 0; i < CFArrayGetCount(array); i++)
    201229                        parseDeviceProperties(getArrayItemAsRef<CFDictionaryRef>(array, i));
    202 
     230       
    203231        return info;
    204232}
     
    209237        if(!properties)
    210238                return;
    211 
     239       
    212240        CFArrayRef array = getDictionaryItemAsRef<CFArrayRef>(properties, kIOHIDElementKey);
    213241        if (array)
     
    227255                                        switch(getInt32(getDictionaryItemAsRef<CFNumberRef>(element, kIOHIDElementUsagePageKey)))
    228256                                        {
    229                                         case kHIDPage_GenericDesktop:
    230                                                 switch(getInt32(getDictionaryItemAsRef<CFNumberRef>(element, kIOHIDElementUsageKey)))
     257                                                case kHIDPage_GenericDesktop:
     258                                                        switch(getInt32(getDictionaryItemAsRef<CFNumberRef>(element, kIOHIDElementUsageKey)))
    231259                                                {
    232                                                 case kHIDUsage_GD_Pointer:
    233                                                         cout << "\tkHIDUsage_GD_Pointer\n";
    234                                                         parseDevicePropertiesGroup(element);
     260                                                        case kHIDUsage_GD_Pointer:
     261                                                                cout << "\tkHIDUsage_GD_Pointer\n";
     262                                                                parseDevicePropertiesGroup(element);
     263                                                                break;
     264                                                        case kHIDUsage_GD_X:
     265                                                        case kHIDUsage_GD_Y:
     266                                                        case kHIDUsage_GD_Z:
     267                                                        case kHIDUsage_GD_Rx:
     268                                                        case kHIDUsage_GD_Ry:
     269                                                        case kHIDUsage_GD_Rz:
     270                                                                cout << "\tAxis\n";
     271                                                                break;
     272                                                        case kHIDUsage_GD_Slider:
     273                                                        case kHIDUsage_GD_Dial:
     274                                                        case kHIDUsage_GD_Wheel:
     275                                                                cout << "\tUnsupported kHIDUsage_GD_Wheel\n";
     276                                                                break;
     277                                                        case kHIDUsage_GD_Hatswitch:
     278                                                                cout << "\tUnsupported - kHIDUsage_GD_Hatswitch\n";
     279                                                                break;
     280                                                }
    235281                                                        break;
    236                                                 case kHIDUsage_GD_X:
    237                                                 case kHIDUsage_GD_Y:
    238                                                 case kHIDUsage_GD_Z:
    239                                                 case kHIDUsage_GD_Rx:
    240                                                 case kHIDUsage_GD_Ry:
    241                                                 case kHIDUsage_GD_Rz:
    242                                                         cout << "\tAxis\n";
     282                                                case kHIDPage_Button:
     283                                                        cout << "\tkHIDPage_Button\n";
    243284                                                        break;
    244                                                 case kHIDUsage_GD_Slider:
    245                                                 case kHIDUsage_GD_Dial:
    246                                                 case kHIDUsage_GD_Wheel:
    247                                                         cout << "\tUnsupported kHIDUsage_GD_Wheel\n";
    248                                                         break;
    249                                                 case kHIDUsage_GD_Hatswitch:
    250                                                         cout << "\tUnsupported - kHIDUsage_GD_Hatswitch\n";
    251                                                         break;
    252                                                 }
    253                                                 break;
    254                                         case kHIDPage_Button:
    255                                                 cout << "\tkHIDPage_Button\n";
    256                                                 break;
    257285                                        }
    258286                                }
     
    267295        if(!properties)
    268296                return;
    269 
     297       
    270298        CFArrayRef array = getDictionaryItemAsRef<CFArrayRef>(properties, kIOHIDElementKey);
    271299        if(array)
     
    278306                                switch(getInt32(getDictionaryItemAsRef<CFNumberRef>(element, kIOHIDElementUsagePageKey)))
    279307                                {
    280                                 case kHIDPage_GenericDesktop:
    281                                         switch(getInt32(getDictionaryItemAsRef<CFNumberRef>(element, kIOHIDElementUsageKey)))
     308                                        case kHIDPage_GenericDesktop:
     309                                                switch(getInt32(getDictionaryItemAsRef<CFNumberRef>(element, kIOHIDElementUsageKey)))
    282310                                        {
    283                                         case kHIDUsage_GD_X:
    284                                         case kHIDUsage_GD_Y:
    285                                         case kHIDUsage_GD_Z:
    286                                         case kHIDUsage_GD_Rx:
    287                                         case kHIDUsage_GD_Ry:
    288                                         case kHIDUsage_GD_Rz:
    289                                                 cout << "\t\tAxis\n";
     311                                                case kHIDUsage_GD_X:
     312                                                case kHIDUsage_GD_Y:
     313                                                case kHIDUsage_GD_Z:
     314                                                case kHIDUsage_GD_Rx:
     315                                                case kHIDUsage_GD_Ry:
     316                                                case kHIDUsage_GD_Rz:
     317                                                        cout << "\t\tAxis\n";
     318                                                        break;
     319                                                case kHIDUsage_GD_Slider:
     320                                                case kHIDUsage_GD_Dial:
     321                                                case kHIDUsage_GD_Wheel:
     322                                                        cout << "\tUnsupported - kHIDUsage_GD_Wheel\n";
     323                                                        break;
     324                                                case kHIDUsage_GD_Hatswitch:
     325                                                        cout << "\tUnsupported - kHIDUsage_GD_Hatswitch\n";
     326                                                        break;
     327                                        }
    290328                                                break;
    291                                         case kHIDUsage_GD_Slider:
    292                                         case kHIDUsage_GD_Dial:
    293                                         case kHIDUsage_GD_Wheel:
    294                                                 cout << "\tUnsupported - kHIDUsage_GD_Wheel\n";
     329                                        case kHIDPage_Button:
    295330                                                break;
    296                                         case kHIDUsage_GD_Hatswitch:
    297                                                 cout << "\tUnsupported - kHIDUsage_GD_Hatswitch\n";
    298                                                 break;
    299                                         }
    300                                         break;
    301                                 case kHIDPage_Button:
    302                                         break;
    303331                                }
    304332                        }
     
    317345                        ret.insert(std::make_pair((*it)->type, (*it)->combinedKey));
    318346        }
    319 
     347       
    320348        return ret;
    321349}
     
    326354        int ret = 0;
    327355        HidInfoList::iterator it = mDeviceList.begin(), end = mDeviceList.end();
    328 
     356       
    329357        for(; it != end; ++it)
    330358        {
     
    341369        int ret = 0;
    342370        HidInfoList::iterator it = mDeviceList.begin(), end = mDeviceList.end();
    343 
     371       
    344372        for(; it != end; ++it)
    345373        {
     
    347375                        ret++;
    348376        }
    349 
     377       
    350378        return ret;
    351379}
     
    355383{
    356384        HidInfoList::iterator it = mDeviceList.begin(), end = mDeviceList.end();
    357 
     385       
    358386        for(; it != end; ++it)
    359387        {
     
    367395//--------------------------------------------------------------------------------//
    368396Object* MacHIDManager::createObject(InputManager* creator, Type iType, bool bufferMode,
    369                                                                           const std::string & vendor)
     397                                                                        const std::string & vendor)
    370398{
    371399        Object *obj = 0;
    372 
     400       
    373401        HidInfoList::iterator it = mDeviceList.begin(), end = mDeviceList.end();
    374402        for(; it != end; ++it)
     
    376404                if((*it)->inUse == false && (*it)->type == iType && (vendor == "" || (*it)->combinedKey == vendor))
    377405                {
    378                         //create device
     406                        switch(iType)
     407                        {
     408                                case OISJoyStick:
     409                {
     410                                        int totalDevs = totalDevices(iType);
     411                                        int freeDevs = freeDevices(iType);
     412                                        int devID = totalDevs - freeDevs;
     413                                       
     414                                        obj = new MacJoyStick((*it)->combinedKey, bufferMode, *it, creator, devID);
     415                                        (*it)->inUse = true;
     416                                        return obj;
     417                }
     418                                case OISTablet:
     419                                        //Create MacTablet
     420                                        break;
     421                                default:
     422                                        break;
     423                        }
    379424                }
    380425        }
    381 
    382         if( obj == 0 )
    383                 OIS_EXCEPT(E_InputDeviceNonExistant, "No devices match requested type.");
    384 
     426       
    385427        return obj;
    386428}
  • code/branches/kicklib2/src/external/ois/mac/MacHIDManager.h

    r5781 r8284  
    7070
    7171                void initialize();
     72               
     73                void iterateAndOpenDevices(io_iterator_t iterator);
     74                io_iterator_t lookUpDevices(int usage, int page);
    7275
    7376                //FactoryCreator Overrides
  • code/branches/kicklib2/src/external/ois/mac/MacInputManager.cpp

    r5781 r8284  
    188188        }
    189189        default:
     190        {
     191                obj = mHIDManager->createObject(creator, iType, bufferMode, vendor);