diff --git a/usr/Include/Core/3d/DXDiagNVUtil.h b/usr/Include/Core/3d/DXDiagNVUtil.h new file mode 100644 index 0000000..31d4d7f --- /dev/null +++ b/usr/Include/Core/3d/DXDiagNVUtil.h @@ -0,0 +1,155 @@ +/*********************************************************************NVMH4**** +Path: SDK\LIBS\src\NV_D3DCommon +File: DXDiagNVUtil.h + +Copyright NVIDIA Corporation 2002 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED +*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS +BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES +WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, +BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) +ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + + +Comments: + +This class allows you to work with DXDiag info in a few ways: +1) Use D3D9's IDxDiagContainer interface to querry for specific fields by name. + You must supply the names of fields to search for, and must sometimes supply + the result of one querry to a later querry (ie. get num display devices in order + to be able to get device video memory). + This is fast. + It requires you to know the COM names of the various IDxDiagContainer nodes. + You can generate a complete list of these names using #2) below. + +2) Use D3D9's IDxDiagContainer interface to enumerate all field names for the + COM object. The field names returned are different than what you see in a + dxdiag.exe text dump. + The field names are written using OutputDebugString(..) + ** This is slow + +The old functions for running DXDIAG.exe, saving the result to a text file, opening, + and parsing that file have been removed. + +See Microsoft's: +DXSDK\Samples\C++\Misc\DXDiagOutput demo for more code related to reading DXDiag info +DXSDK\Samples\C++\Misc\DxDiagReport + + +******************************************************************************/ + +#ifndef H_DXDIAGNVUTIL_GJ_H +#define H_DXDIAGNVUTIL_GJ_H + +#include // in DXSDK\include + +#include "3d/NV_Error.h" +#include "3d/NV_Common.h" + + +#include +#include +using namespace std; + +// forward decls for things defined externally +struct IDxDiagProvider; +struct IDxDiagContainer; + +//------------------------------------------------------------ + +class DXDiagNVUtil +{ +public: + //-------- Main interface functions ----------------------------------- + // Interface #1 (prefered) + // Call these to allocate & free the IDxDiagContainer interface + // Init will initialize the m_pDxDiagRoot variable + HRESULT InitIDxDiagContainer(); + HRESULT FreeIDxDiagContainer(); + + // ---- The functions below must be called after InitIDxDiagContainer() and before FreeIDxDiagContainer() + + // Recursive traverse all children of the pDxDiagContainer node and list their COM names + // This is provided so you can easily create and browse a full list of names + // Names are output to the debug console via OutputDebugString(..) + HRESULT ListAllDXDiagPropertyNames(); + HRESULT ListAllDXDiagPropertyNames( IDxDiagContainer * pDxDiagContainer, + WCHAR* wszParentName = NULL ); + HRESULT ListAllDXDiagPropertyNamesToTxtFile( FILE * pOpenTextFile, + bool bGetPropertyValues = false, + IDxDiagContainer * pDxDiagContainer = NULL, + WCHAR * wszParentName = NULL ); + + HRESULT GetNumDisplayDevices( DWORD * out_dwNumAdapters ); + HRESULT GetDisplayDeviceNode( DWORD dwDeviceIndex, IDxDiagContainer ** ppNode ); + HRESULT GetDisplayDeviceDescription( DWORD dwDevice, wstring * out_pwstrName ); + HRESULT GetDisplayDeviceNVDriverVersion( DWORD dwDevice, float * out_fVersion ); + HRESULT GetDisplayDeviceDriverVersionStr( DWORD dwDevice, wstring * out_pwstrVers ); + HRESULT GetDisplayDeviceMemoryInMB( DWORD dwDevice, int * out_nDisplayMemory ); + HRESULT GetDisplayDeviceAGPMemoryStatus( DWORD dwDevice, wstring * pwstrAGPEnabled, wstring * pwstrAGPExists, wstring * pwstrAGPStatus ); + HRESULT GetDisplayDeviceProp( DWORD dwDevice, LPCWSTR in_prop_name, wstring * out_pwstrProp ); + + HRESULT GetPhysicalMemoryInMB( float * out_pfMemory ); + HRESULT GetDebugLevels( wstring * pwstrLevels ); // all debug levels returned in 1 string + HRESULT GetDirectXVersion( DWORD * pdwDirectXVersionMajor, + DWORD * pdwDirectXVersionMinor, + TCHAR * pcDirectXVersionLetter ); + + // ---- Seconardy interface functions for the #1 interface + // Use these to directly querry for a field based on the COM property name. + // You can generate a full list of these names by using ListAllDXDiagPropertyNames() + // Example: + // GetProperty( L"DxDiag_SystemInfo", L"ullPhysicalMemory", & strPropVal ); + + HRESULT GetProperty( IDxDiagContainer * pContainer, LPCWSTR property_name, wstring * out_value ); + + // Get properties of containers off of the m_pDxDiagRoot node + HRESULT GetProperty( LPCWSTR container_name0, LPCWSTR property_name, wstring * out_value ); + HRESULT GetProperty( LPCWSTR container_name0, LPCWSTR container_name1, LPCWSTR property_name, wstring * out_value ); + HRESULT GetProperty( LPCWSTR container_name0, LPCWSTR container_name1, LPCWSTR container_name2, LPCWSTR property_name, wstring * out_value ); + + HRESULT GetChildContainer( LPCWSTR container_name0, IDxDiagContainer ** out_ppChild ); + HRESULT GetChildContainer( LPCWSTR container_name0, LPCWSTR container_name1, IDxDiagContainer ** out_ppChild ); + HRESULT GetChildContainer( LPCWSTR container_name0, LPCWSTR container_name1, LPCWSTR container_name2, IDxDiagContainer ** out_ppChild ); + + HRESULT GetChildByIndex( IDxDiagContainer * in_pParent, DWORD dwIndex, IDxDiagContainer ** out_ppChild ); + + // ---- End of functions that should be called between InitIDxDiagContainer() and FreeIDxDiagContainer() + + // Utility functions for converting strings, etc. + string WStringToString( const wstring * in_pwstring ); + string WStringToString( wstring & in_wstring ); + string lpcwstrToString( const LPCWSTR in_lpcwstr ); + +protected: + // data for interface #1 (preferred) + bool m_bCleanupCOM; + IDxDiagProvider * m_pDxDiagProvider; + IDxDiagContainer * m_pDxDiagRoot; // root node of the IDxDiagContainer data + + +public: + DXDiagNVUtil() + { + SetAllNull(); + }; + ~DXDiagNVUtil() + { + FreeIDxDiagContainer(); + SetAllNull(); + }; + void SetAllNull() + { + // data for interface #1 (preferred) + m_bCleanupCOM = false; + m_pDxDiagProvider = NULL; + m_pDxDiagRoot = NULL; + } +}; + + +#endif diff --git a/usr/Include/Core/3d/GetGPUAndSystemInfo.h b/usr/Include/Core/3d/GetGPUAndSystemInfo.h new file mode 100644 index 0000000..b6d1c8b --- /dev/null +++ b/usr/Include/Core/3d/GetGPUAndSystemInfo.h @@ -0,0 +1,95 @@ +/*--------------------------------------------------------------------- NVMH5 -|---------------------- +Path: Sdk\Demos\Direct3D9\src\GetGPUAndSystemInfo\ +File: GetGPUAndSystemInfo.h + +Copyright NVIDIA Corporation 2003 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND NVIDIA AND +AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA +OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER +INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF +BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS +SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +Comments: +A simple class to demonstrate the use of DXDiagNVUtil which is a convenient wrapper for +the IDxDiagContainer interface from Microsoft. + +GetGPUAndSystemInfo gets only a small fraction of the information that IDxDiagContainer +makes available. + +Since this class is simple to create and destroy, there is no specific handling for when +the D3D device is lost. Simply Free() and re Initialize() the class if that should happen. + +-------------------------------------------------------------------------------|--------------------*/ + + +#ifndef H_GETGPUANDSYSTEMINFO_GJ_H +#define H_GETGPUANDSYSTEMINFO_GJ_H + +#include "3D\DXDiagNVUtil.h" + +#include // for wstring + +struct IDirect3D9; + + +struct FloatingPointBlendModes +{ + bool m_bR16f; + bool m_bR32f; + bool m_bG16R16f; + bool m_bG32R32f; + bool m_bA16B16G16R16f; + bool m_bA32B32G32R32f; + bool m_bA8R8G8B8; // not an fp mode, but there for good measure +}; + + +class GetGPUAndSystemInfo +{ +public: + // DXDiagNVUtil is a utility class for creating and querring the IDxDiagContainer interface + DXDiagNVUtil m_DXDiagNVUtil; + + // Data fields that will be filled in by the GetData() function + DWORD m_dwNumDisplayDevices; + float m_fDriverVersion; + wstring m_wstrDeviceDesc; + int m_nDeviceMemoryMB; + float m_fSystemPhysicalMemoryMB; + string m_strAGPStatus; + string m_strMachineName; + + DWORD m_dwDXVersionMajor; + DWORD m_dwDXVersionMinor; + char m_cDXVersionLetter; + + wstring m_wstrDxDebugLevels; + + FloatingPointBlendModes m_FPBlendModes; + + // ---- Main interface functions -------- + HRESULT GetData(); + HRESULT IsFPBlendingSupported( IDirect3D9 * pD3D9, FloatingPointBlendModes * pOutResult ); + + // -------------------------------------- + +protected: + void SetAllNull() + { + }; +public: + GetGPUAndSystemInfo() + { + SetAllNull(); + }; + ~GetGPUAndSystemInfo() + { + SetAllNull(); + } +}; + + +#endif diff --git a/usr/Include/Core/3d/NVFileDialog.h b/usr/Include/Core/3d/NVFileDialog.h new file mode 100644 index 0000000..c3c0fa6 --- /dev/null +++ b/usr/Include/Core/3d/NVFileDialog.h @@ -0,0 +1,149 @@ +#ifndef _NVFILEDIALOG_H_ +#define _NVFILEDIALOG_H_ + +#pragma warning (disable : 4786) +#include +#pragma warning (disable : 4786) +#include +#pragma warning (disable : 4786) + +#include +typedef std::basic_string tstring; + +//////////// +// Helper class to assist in loading files +// +// Usage : +// +// Just create a NV*FileDialog object on the stack, and call Open +// +// NVXFileDialog aDialog; +// +// std::string theFileName; +// +// if ( aDialog.Open( theFileName ) ) +// { +// // open the filename and read it in +// } +// +// // That's it ! +// +// Use the NVTextureFileDialog for texture files, +// +// or use the NVFileDialog to do arbitrary filters +// + +class NVFileDialog +{ + private : + + OPENFILENAME mOpenFileName; + + std::vector< tstring > mFilterNames; + std::vector< tstring > mFilterStrings; + + tstring mString; + + void Init() + { + memset( &mOpenFileName, 0x00, sizeof( mOpenFileName ) ); + mOpenFileName.lStructSize = sizeof( mOpenFileName ); + + OSVERSIONINFO osinfo; + memset( &osinfo, 0x00, sizeof( osinfo ) ); + BOOL bSuccess = ::GetVersionEx( &osinfo ); + + if ( osinfo.dwMajorVersion >= 0x0500 ) + { + mOpenFileName.lStructSize += ( 3 * sizeof( DWORD ) ); + } + + mString.erase( mString.begin(), mString.end() ); + + mOpenFileName.Flags = OFN_FILEMUSTEXIST | OFN_LONGNAMES | OFN_SHAREAWARE; + + mOpenFileName.nFilterIndex = 1; + + for (unsigned int i = 0; i < mFilterNames.size(); ++i ) + { + mString += mFilterNames[ i ]; + mString += TCHAR(0x00); + mString += mFilterStrings[ i ]; + mString += TCHAR(0x00); + } + + // Last element must be double terminated + mString += TCHAR(0x00); + + mOpenFileName.lpstrFilter = mString.c_str(); + } + + public : + + ~NVFileDialog(){;} + + NVFileDialog() + { + mFilterNames.push_back(TEXT("*.*")); + mFilterStrings.push_back(TEXT("")); + } + + void SetFilters( const std::vector< tstring >& theFilterNames, + const std::vector< tstring >& theFilterStrings ) + { + assert( mFilterNames.size() == theFilterStrings.size() ); + + mFilterNames = theFilterNames; + mFilterStrings = theFilterStrings; + } + + void SetFilter( const tstring& theFilterName ) + { + mFilterNames.clear(); + mFilterStrings.clear(); + + mFilterNames.push_back( theFilterName ); + mFilterStrings.push_back( theFilterName ); + } + + virtual bool Open( tstring& theResult ) + { + Init(); + + theResult.resize(1024); + theResult[0] = 0; + mOpenFileName.lpstrFile = &theResult[ 0 ]; + mOpenFileName.nMaxFile = 1024; + + BOOL bSuccess = ::GetOpenFileName( &mOpenFileName ); + + return ( bSuccess == TRUE ); + } + +}; + +class NVXFileDialog : public NVFileDialog +{ + public : + + NVXFileDialog() + { + SetFilter(TEXT("*.x")); + } + +}; + + +class NVTextureFileDialog : public NVFileDialog +{ + public : + + NVTextureFileDialog() + { + SetFilter(TEXT("*.bmp;*.tga;*.dds")); + } + +}; + +#endif _NVFILEDIALOG_H_ + diff --git a/usr/Include/Core/3d/NV_Common.h b/usr/Include/Core/3d/NV_Common.h new file mode 100644 index 0000000..00f5278 --- /dev/null +++ b/usr/Include/Core/3d/NV_Common.h @@ -0,0 +1,465 @@ +/*--------------------------------------------------------------------- NVMH5 -|---------------------- +Path: Sdk\Libs\inc\shared\ +File: NV_Common.h + +Copyright NVIDIA Corporation 2003 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND NVIDIA AND +AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA +OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER +INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF +BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS +SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +Comments: +Useful macros, etc. + +Define these to output messages on delete and release: +#define NVMSG_SAFE_ARRAY_DELETE +#define NVMSG_SAFE_DELETE +#define NVMSG_SAFE_RELEASE + +FDebug and FMsg are defined in NV_Error.h. These functions take a variable argument list, similar to +that for fprintf(), and output the string via OutputDebugString. FDebug() outputs only for DEBUG builds. +FMsg() outputs text for bot DEBUG and RELEASE builds. + + +-------------------------------------------------------------------------------|--------------------*/ + +#pragma once + +#ifndef H_NVCOMMONHEADER_H +#define H_NVCOMMONHEADER_H + +#define INLINE __forceinline + +#ifndef MULTI_THREAD +#include +#endif + +#include +#include "3d\NV_Error.h" + + +typedef unsigned short USHORT; +typedef unsigned short ushort; + + +//---------------------------------------------------------------- +// Preferred macros + +#ifndef MSG_IF +#define MSG_IF( expr, msg ) \ +{ \ + if( expr ) { FMsg(msg); } \ +} +#endif + +#ifndef MSG_AND_RET_IF +#define MSG_AND_RET_IF( expr, msg ) \ +{ \ + if( expr ) { FMsg(msg); return; } \ +} +#endif + +#ifndef MSG_AND_RET_VAL_IF +#define MSG_AND_RET_VAL_IF( expr, msg, retval ) \ +{ \ + if( expr ) { FMsg(msg); return( retval ); } \ +} +#endif + + +// Causes a debug assertion if expr is true +#ifndef MSG_AND_BREAK_IF +#define MSG_AND_BREAK_IF( expr, msg ) \ +{ \ + if( expr ) { FMsg(msg); assert(false); } \ +} +#endif + +#ifndef MSG_BREAK_AND_RET_IF +#define MSG_BREAK_AND_RET_IF( expr, msg ) \ +{ \ + if( expr ) { FMsg(msg); assert(false); return; } \ +} +#endif + +#ifndef MSG_BREAK_AND_RET_VAL_IF +#define MSG_BREAK_AND_RET_VAL_IF( expr, msg, retval ) \ +{ \ + if( expr ) { FMsg(msg); assert(false); return(retval); } \ +} +#endif + +// Causes a debug assertion if expr is true +#ifndef BREAK_IF +#define BREAK_IF( expr ) \ +{ \ + if( expr ) { assert(false); } \ +} +#endif + +#ifndef BREAK_AND_RET_IF +#define BREAK_AND_RET_IF( expr ) \ +{ \ + if( expr ) { assert(false); return; } \ +} +#endif + +#ifndef BREAK_AND_RET_VAL_IF +#define BREAK_AND_RET_VAL_IF( expr, retval ) \ +{ \ + if( expr ) { assert( false ); return( retval ); } \ +} +#endif + +#ifndef RET_IF +#define RET_IF( expr ) \ +{ \ + if( expr ) { return; } \ +} +#endif + +#ifndef RET_VAL_IF +#define RET_VAL_IF( expr, retval ) \ +{ \ + if( expr ) { return( retval ); } \ +} +#endif + + +// Macro for checking if a variable is NULL +// This outputs the variable name and returns E_FAIL if the variable == NULL. +// Example: +// pMyPointer = NULL; +// MSGVARNAME_AND_FAIL_IF_NULL( pMyPointer ); +// outputs: +// "pMyPointer == NULL" and returns E_FAIL +#ifndef MSGVARNAME_AND_FAIL_IF_NULL +#define MSGVARNAME_AND_FAIL_IF_NULL( var ) \ +{ \ + if( (var) == NULL ) { FMsg( TEXT(#var) TEXT(" == NULL\n")); return( E_FAIL ); } \ +} +#endif + +//-------------------------------------------------------------- +// Below are macros that can be expressed with the above macros +// These are included for convenience. + +#ifndef FAIL_IF_NULL +#define FAIL_IF_NULL( x ) \ +{ \ + if( (x) == NULL ) { return( E_FAIL ); } \ +} +#endif + +#ifndef MSG_AND_FAIL_IF_NULL +#define MSG_AND_FAIL_IF_NULL( p, msg ) \ +{ \ + if( (p) == NULL ) { FMsg(msg); return( E_FAIL ); } \ +} +#endif + +#ifndef RET_IF_NULL +#define RET_IF_NULL( p ) \ +{ \ + if( (p) == NULL ) { return; } \ +} +#endif + +#ifndef RET_VAL_IF_NULL +#define RET_VAL_IF_NULL( p, retval ) \ +{ \ + if( (p) == NULL ) { return( retval ); } \ +} +#endif + +#ifndef RET_NULL_IF_NULL +#define RET_NULL_IF_NULL(p) \ +{ \ + if( (p) == NULL ) { return( NULL ); } \ +} +#endif + +#ifndef BREAK_AND_RET_VAL_IF_FAILED +#define BREAK_AND_RET_VAL_IF_FAILED( hr ) \ +{ \ + if( FAILED(hr) ) { assert(false); return( hr ); } \ +} +#endif + +#ifndef RET_VAL_IF_FAILED +#define RET_VAL_IF_FAILED( hr ) \ +{ \ + if( FAILED( hr ) ) { return( hr ); } \ +} +#endif + + +//------------------------------------------------------------------------------------------- + +// delete a pointer allocated with new [num], and set the pointer to NULL. +#ifndef SAFE_DELETE_ARRAY + #ifdef NVMSG_SAFE_ARRAY_DELETE + #define SAFE_DELETE_ARRAY(p) \ + { \ + FMsg(TEXT("SAFE_DELETE_ARRAY: %35s = 0x%8.8X\n"), TEXT(#p), p ); \ + if( p != NULL ) \ + { \ + delete [] (p); \ + p = NULL; \ + } \ + } + #else + #define SAFE_DELETE_ARRAY(p) \ + { \ + if( p != NULL ) \ + { \ + delete [] (p); \ + p = NULL; \ + } \ + } + #endif +#endif + + +#ifndef SAFE_ARRAY_DELETE + #ifdef NVMSG_SAFE_ARRAY_DELETE + #define SAFE_ARRAY_DELETE(p) \ + { \ + FMsg(TEXT("SAFE_ARRAY_DELETE: %35s = 0x%8.8X\n"), TEXT(#p), p );\ + if( p != NULL ) \ + { \ + delete [] (p); \ + p = NULL; \ + } \ + } + #else + #define SAFE_ARRAY_DELETE(p) \ + { \ + if( p != NULL ) \ + { \ + delete [] (p); \ + p = NULL; \ + } \ + } + #endif +#endif + + +// deletes all pointers in a vector of pointers, and clears the vector +#ifndef SAFE_VECTOR_DELETE +#define SAFE_VECTOR_DELETE( v ) \ +{ \ + for( UINT svecdel = 0; svecdel < (v).size(); svecdel++ ) \ + { if( (v).at( svecdel ) != NULL ) \ + { delete( (v).at( svecdel )); \ + (v).at( svecdel ) = NULL; \ + } \ + } \ + (v).clear(); \ +} +#endif + + +#ifndef SAFE_DELETE + #ifdef NVMSG_SAFE_DELETE + #define SAFE_DELETE( p ) \ + { \ + FMsg(TEXT("SAFE_DELETE: %35s = 0x%8.8X\n"), TEXT(#p), p ); \ + if( (p) != NULL) \ + { \ + delete(p); \ + (p) = NULL; \ + } \ + } +#else + #define SAFE_DELETE( p ) \ + { \ + if( (p) != NULL ) \ + { \ + delete(p); \ + (p) = NULL; \ + } \ + } +#endif +#endif + + +// Releases all pointers in a vector of pointers, and clears the vector +#ifndef SAFE_VECTOR_RELEASE +#define SAFE_VECTOR_RELEASE( v ) \ +{ \ + for( UINT svecrel = 0; svecrel < (v).size(); svecrel++ ) \ + { if( (v).at( svecrel ) != NULL ) \ + { (v).at( svecrel )->Release(); \ + (v).at( svecrel ) = NULL; \ + } \ + } \ + (v).clear(); \ +} +#endif + +// Calls the Release() member of the object pointed to, and sets the pointer to NULL +#ifndef SAFE_RELEASE + #ifdef NVMSG_SAFE_RELEASE + #define SAFE_RELEASE(p) \ + { \ + FMsg(TEXT("SAFE_RELEASE: %35s = 0x%8.8X\n"), TEXT(#p), p ); \ + if( (p) != NULL ) \ + { \ + (p)->Release(); \ + (p) = NULL; \ + } \ + } +#else + #define SAFE_RELEASE(p) \ + { \ + if( (p) != NULL ) \ + { \ + (p)->Release(); \ + (p) = NULL; \ + } \ + } +#endif +#endif + + +#ifndef SAFE_ADDREF + #ifdef NVMSG_SAFE_ADDREF + #define SAFE_ADDREF(p) \ + { \ + FMsg(TEXT("SAFE_ADDREF: %35s = 0x%8.8X\n"), TEXT(#p), p ); \ + if( (p) != NULL ) \ + { \ + (p)->AddRef(); \ + } \ + } +#else + #define SAFE_ADDREF(p) \ + { \ + if( (p) != NULL ) \ + { \ + (p)->AddRef(); \ + } \ + } +#endif +#endif + + +/////////////////////////////////////////////////////////////// + +#ifndef CHECK_BOUNDS +#define CHECK_BOUNDS( v, n, x ) \ + if( (v < n) || (v > x) ) \ + { FDebug("Variable out of bounds!\n"); \ + assert( false ); return; \ + } +#endif + + +#ifndef CHECK_BOUNDS_NULL +#define CHECK_BOUNDS_NULL( v, n, x ) \ + if( (v < n) || (v > x) ) \ + { FDebug("Variable out of bounds!\n"); \ + assert( false ); return(NULL); \ + } +#endif + +#ifndef CHECK_BOUNDS_HR +#define CHECK_BOUNDS_HR( v, n, x ) \ + if( (v < n) || (v > x) ) \ + { FDebug("Variable out of bounds!\n"); \ + assert( false ); return(E_FAIL); \ + } +#endif + +/////////////////////////////////////////////////////////////// + +#define ifnot(x) if (!(x)) +#define until(x) while(!(x)) +#define ever (;;) +#define wait do {} +#define nothing {} + +/////////////////////////////////////////////////////////////// + +// Macro to make sure that a handle is allocated. +// If in_handle is NULL, an object is created at ptr. +// handle will point to ptr; +// If in_handle is not NULL, but it's pointer is NULL, then +// an object is created at (*in_handle) +// ptr is set to same value as (*in_handle) +// handle will point to *in_handle +// class - the type of object to create +// init - text of an Initialize() function called if object is created +// + +#ifndef GUARANTEE_ALLOCATED +#define GUARANTEE_ALLOCATED( in_handle, handle, ptr, classname, init ) \ +{ \ + bool alloc; \ + alloc = false; \ + bool setptr; \ + setptr = false; \ + HRESULT hr; \ + handle = in_handle; \ + if( handle == NULL ) \ + { \ + handle = & ptr; \ + alloc = true; \ + } \ + else if( *handle == NULL ) \ + { \ + alloc = true; \ + setptr = true; \ + } \ + if( alloc == true ) \ + { \ + (*handle) = new classname; \ + FAIL_IF_NULL( (*handle) ); \ + hr = (*handle)->init; \ + BREAK_AND_RET_VAL_IF_FAILED( hr ); \ + } \ + if( setptr == true ) \ + ptr = *handle; \ +} +#endif + +#ifndef FREE_GUARANTEED_ALLOC +#define FREE_GUARANTEED_ALLOC( handle, ptr ) \ +{ \ + if( handle != NULL ) \ + { \ + if( ptr == *handle ) \ + { \ + SAFE_DELETE( (*handle) ); \ + ptr = NULL; \ + } \ + handle = NULL; \ + } \ +} +#endif + + +//---------------------------------------------------------------- +// Below are older deprecated macros. Please use the macros above instead of these. + + +#ifndef ASSERT_AND_RET_IF_FAILED +#define ASSERT_AND_RET_IF_FAILED(hres) \ +{ \ + if( FAILED(hres) ) \ + { \ + assert( false ); \ + return( hres ); \ + } \ +} +#endif + +//---------------------------------------------------------------- + +#endif // H_NVCOMMONHEADER_H + diff --git a/usr/Include/Core/3d/NV_Error.h b/usr/Include/Core/3d/NV_Error.h new file mode 100644 index 0000000..186adff --- /dev/null +++ b/usr/Include/Core/3d/NV_Error.h @@ -0,0 +1,200 @@ +/*--------------------------------------------------------------------- NVMH5 -|---------------------- +Path: Sdk\Libs\inc\shared\ +File: NV_Error.h + +Copyright NVIDIA Corporation 2003 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND NVIDIA AND +AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA +OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER +INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF +BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS +SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +Comments: +No longer requires separate .cpp file. Functions defined in the .h with the +magic of the static keyword. + +For UNICODE, both TCHAR and char * flavors are defined, so that old code not +using TCHAR args to the functions (ie, not using the TEXT() macro) do not +need to change. + +-------------------------------------------------------------------------------|--------------------*/ + +#pragma warning( disable : 4505 ) // unreferenced local function has been removed + +#ifndef H_NV_ERROR_H +#define H_NV_ERROR_H + +#pragma warning( disable : 4995 ) // old string functions marked as #pragma deprecated + +#include // for exit() +#include +#include +#include + +#if _MSC_VER >= 1000 + #pragma once +#endif // _MSC_VER >= 1000 + +//--------------------------------------------------------------- + +#ifndef OUTPUT_POINTER + #define OUTPUT_POINTER(p) { FMsg("%35s = %8.8x\n", #p, p ); } +#endif + +#ifndef NULLCHECK + #define NULLCHECK(q, msg,quit) {if(q==NULL) { DoError(msg, quit); }} +#endif + +#ifndef IFNULLRET + #define IFNULLRET(q, msg) {if(q==NULL) { FDebug(msg); return;}} +#endif + +#ifndef FAILRET + #define FAILRET(hres, msg) {if(FAILED(hres)){FDebug("*** %s HRESULT: %d\n",msg, hres);return hres;}} +#endif + +#ifndef HRESCHECK + #define HRESCHECK(q, msg) {if(FAILED(q)) { FDebug(msg); return;}} +#endif + +#ifndef NULLASSERT + #define NULLASSERT( q, msg,quit ) {if(q==NULL) { FDebug(msg); assert(false); if(quit) exit(0); }} +#endif + +///////////////////////////////////////////////////////////////// + +static void OkMsgBox( TCHAR * szCaption, TCHAR * szFormat, ... ) +{ + TCHAR buffer[256]; + va_list args; + va_start( args, szFormat ); + _vsntprintf( buffer, 256, szFormat, args ); + va_end( args ); + buffer[256-1] = '\0'; // terminate in case of overflow + MessageBox( NULL, buffer, szCaption, MB_OK ); +} + + +#ifdef _DEBUG + static void FDebug ( TCHAR * szFormat, ... ) + { + // It does not work to call FMsg( szFormat ). The variable arg list will be incorrect + static TCHAR buffer[2048]; + va_list args; + va_start( args, szFormat ); + _vsntprintf( buffer, 2048, szFormat, args ); + va_end( args ); + buffer[2048-1] = '\0'; // terminate in case of overflow + OutputDebugString( buffer ); + Sleep( 2 ); // OutputDebugString sometimes misses lines if + // called too rapidly in succession. + } + #ifdef UNICODE + static void FDebug( char * szFormat, ... ) + { + static char buffer[2048]; + va_list args; + va_start( args, szFormat ); + _vsnprintf( buffer, 2048, szFormat, args ); + va_end( args ); + buffer[2048-1] = '\0'; // terminate in case of overflow + + #ifdef UNICODE + int nLen = MultiByteToWideChar( CP_ACP, 0, buffer, -1, NULL, NULL ); + LPWSTR lpszW = new WCHAR[ nLen ]; + if( lpszW != NULL ) + { + MultiByteToWideChar( CP_ACP, 0, buffer, -1, lpszW, nLen ); + OutputDebugString( lpszW ); + delete lpszW; + lpszW = NULL; + } + #else + OutputDebugString( buffer ); + #endif + Sleep( 2 ); // OutputDebugString sometimes misses lines if + // called too rapidly in succession. + } + #endif + + #pragma warning( disable : 4100 ) // unreferenced formal parameter + inline static void NullFunc( TCHAR * szFormat, ... ) {} + #ifdef UNICODE + inline static void NullFunc( char * szFormat, ... ) {} + #endif + #pragma warning( default : 4100 ) + + #if 0 + #define WMDIAG(str) { OutputDebugString(str); } + #else + #define WMDIAG(str) {} + #endif +#else + inline static void FDebug( TCHAR * szFormat, ... ) { szFormat; } + #ifdef UNICODE + inline static void FDebug( char * szFormat, ... ) { szFormat; } + #endif + inline static void NullFunc( char * szFormat, ... ) { szFormat; } + #define WMDIAG(str) {} +#endif + +static void FMsg( TCHAR * szFormat, ... ) +{ + static TCHAR buffer[2048]; + va_list args; + va_start( args, szFormat ); + _vsntprintf( buffer, 2048, szFormat, args ); + va_end( args ); + buffer[2048-1] = '\0'; // terminate in case of overflow + OutputDebugString( buffer ); + Sleep( 2 ); // OutputDebugString sometimes misses lines if + // called too rapidly in succession. +} + +static void FMsgW( WCHAR * wszFormat, ... ) +{ + WCHAR wbuff[2048]; + va_list args; + va_start( args, wszFormat ); + _vsnwprintf( wbuff, 2048, wszFormat, args ); + va_end( args ); + wbuff[2048-1] = '\0'; // terminate in case of overflow + OutputDebugStringW( wbuff ); + Sleep( 2 ); // OutputDebugString sometimes misses lines if + // called too rapidly in succession. +} + + +#ifdef UNICODE + // You must make sure that the variable arg list is also char * and NOT WCHAR * + // This function allows FMsg("") in old non-UNICODE builds to work without requiring FMsg(TEXT("")) + static void FMsg( char * szFormat, ... ) + { + static char buffer[2048]; + va_list args; + va_start( args, szFormat ); + _vsnprintf( buffer, 2048, szFormat, args ); + va_end( args ); + buffer[2048-1] = '\0'; // terminate in case of overflow + #ifdef UNICODE + int nLen = MultiByteToWideChar( CP_ACP, 0, buffer, -1, NULL, NULL ); + LPWSTR lpszW = new WCHAR[ nLen ]; + if( lpszW != NULL ) + { + MultiByteToWideChar( CP_ACP, 0, buffer, -1, lpszW, nLen ); + OutputDebugString( lpszW ); + delete lpszW; + lpszW = NULL; + } + #else + OutputDebugString( buffer ); + #endif + Sleep( 2 ); // OutputDebugString sometimes misses lines if + // called too rapidly in succession. + } +#endif + +#endif diff --git a/usr/Include/Core/3d/NV_StringFuncs.h b/usr/Include/Core/3d/NV_StringFuncs.h new file mode 100644 index 0000000..6a764b2 --- /dev/null +++ b/usr/Include/Core/3d/NV_StringFuncs.h @@ -0,0 +1,180 @@ +/*********************************************************************NVMH4**** +Path: SDK\LIBS\inc\shared +File: NV_StringFuncs.h + +Copyright NVIDIA Corporation 2002 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED +*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS +BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES +WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, +BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) +ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + + +Comments: +A collection of useful string functions, built upon std::string + +They are not all meant to be fast. Many return vectors of strings, which will +require string copies and lots of work by the STL functions. For processing +large strings or a lot of string data you will probably want to devise your +own routines. + +A demo of using the functions is provided in: +SDK\DEMOS\common\src\NV_StringFuncs + + +******************************************************************************/ + + +#ifndef _NV_STRINGFUNCS_GJ_H +#define _NV_STRINGFUNCS_GJ_H + + +#pragma warning(disable : 4786) // STL warning +#include +#include +#include +#include +#include +#include + +// sfsizet is size type for the string class used +typedef std::string::size_type sfsizet; +typedef std::basic_string tstring; + +namespace NVStringConv +{ + // use as an alternative to wcstombs() + std::string WStringToString( const std::wstring * in_pwstring ); + std::string WStringToString( std::wstring & in_wstring ); + std::string lpcwstrToString( LPCWSTR in_lpcwstr ); + + std::wstring StringToWString( const std::string * in_pString ); + std::wstring StringToWString( std::string & in_String ); + std::wstring lpcstrToWString( LPCSTR str ); +}; // namespace NVStringConv + +///////////////////////////////////////////////////////////////////// +// macro to expand vector of anything into single string +// example c is "%u " and the % must match type held in vector +// Example: +// string dest; +// vector< int > vint; +// VEC_TO_STR( dest, vint, "%d " ); +// +#ifndef VEC_TO_STR +#define VEC_TO_STR( a, b, c ) \ +{ \ + for( int vectocnt = 0; vectocnt < b.size(); vectocnt++ ) \ + { a += StrPrintf( c, b.at(vectocnt) ); \ + } \ +} +#endif + +////////////////////////// +// Convert list of some type to vector of same type +// L is list, V is vector, T is type +// Example: +// list< string > lStr; +// vector< string > vStr; +// lStr.push_back( "a" ); +// lStr.push_back( "b" ); +// LIST_TO_VEC( lStr, vStr, std::string ); + +#ifndef LIST_TO_VEC +#define LIST_TO_VEC( L, V, T ) \ +{ \ + std::list< T >::const_iterator ltovecmacroiter; \ + for( ltovecmacroiter = L.begin(); ltovecmacroiter != L.end(); ltovecmacroiter++ ) \ + { \ + V.push_back( *ltovecmacroiter ); \ + } \ +} +#endif + +////////////////////////// +// Convert vector of some type to list of same type +// L is list, V is vector, T is type +// +#ifndef VEC_TO_LIST +#define VEC_TO_LIST( V, L, T ) \ +{ \ + for( int vtolistc=0; vtolistc < V.size(); vtolistc++ ) \ + { L.push_back( V.at(vtolistc) ); \ + } \ +} +#endif + +///////////////////////////////////////////////////////////////////// + + + // Create a string using va_args, just like printf, sprintf, etc. +std::string StrPrintf( const char * szFormat, ... ); + + +std::string StrToUpper( const std::string & strIn ); +std::string StrToLower( const std::string & strIn ); + + // Writes each string in the vector to a single output + // string, separating each by a space. +std::string StrsToString( const std::vector< std::string > & vstrIn ); + // same, but lets you specify the separator between strings +std::string StrsToString( const std::vector< std::string > & vstrIn, + const std::string & separator ); +std::string StrsToString( const std::list< std::string > & lstrIn, + const std::string & separator ); + + + // Like CString::Replace() + // Sequence and it's replacement can be different lengths or empty +std::string StrReplace( const std::string & sequence_to_replace, + const std::string & replacement_string, + const std::string & strIn ); + // same as above, only it modifies pOut and also returns pOut +std::string * StrReplace( const std::string & sequence_to_replace, + const std::string & replacement_string, + const std::string & strIn, + std::string * pOut, + bool bVerbose = false ); + + + // applies strtok repeatedly & acumulates ouput tokens + // in output string separated by spaces +std::string StrTokenize( const std::string & strIn, const std::string & delimiters ); + + // Same as above, but allows you to specify the separator between + // tokens in the output +std::string StrTokenize( const std::string & strIn, + const std::string & delimiters, + const std::string & output_separator ); + +sfsizet StrFindCaseless( const std::string & strSearchIn, sfsizet start_pos, const std::string & strSearchFor ); + +std::vector< sfsizet > StrFindAllCaseless( const std::string & strSearchIn, + sfsizet start_pos, + const std::string & strSearchFor ); + +std::vector< sfsizet > StrFindAll( const std::string & strSearchIn, + sfsizet start_pos, + const std::string & strSearchFor ); + +std::vector< std::string > StrSort( const std::vector< std::string > & vStrIn ); + +tstring GetFilenameFromFullPath( const tstring & full_path ); + + +///////////////////////////////////////////////////////////////////// +/* +More ideas for functions to implement +SortCaseless +Sort // case sensitive + +_stricmp - compare two strings without regard to case +_strrev = reverse string +*/ + +#endif diff --git a/usr/Include/Core/3d/dxstdafx.h b/usr/Include/Core/3d/dxstdafx.h new file mode 100644 index 0000000..487a837 --- /dev/null +++ b/usr/Include/Core/3d/dxstdafx.h @@ -0,0 +1,66 @@ +//-------------------------------------------------------------------------------------- +// File: DxStdAfx.h +// +// Desc: Header file that is the standard includes for the DirectX SDK samples +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +#pragma once +#ifndef DXSDK_STDAFX_H +#define DXSDK_STDAFX_H + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#define STRICT + +// Works with Windows 2000 and later and Windows 98 or later +#undef _WIN32_IE +#undef WINVER +#undef _WIN32_WINDOWS +#undef _WIN32_WINNT +#define WINVER 0x0500 +#define _WIN32_WINDOWS 0x0410 +#define _WIN32_WINNT 0x0500 + +#include +#include +#include +#include +#include // for InitCommonControls() +#include // for ExtractIcon() +#include // for placement new +#include +#include + + +// Enable extra D3D debugging in debug builds if using the debug DirectX runtime. +// This makes D3D objects work well in the debugger watch window, but slows down +// performance slightly. +#if defined(DEBUG) | defined(_DEBUG) +#define D3D_DEBUG_INFO +#endif + +// Direct3D includes +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#if defined(DEBUG) | defined(_DEBUG) + #define V(x) { hr = x; if( FAILED(hr) ) { DXUTTrace( __FILE__, (DWORD)__LINE__, hr, L#x, true ); } } + #define V_RETURN(x) { hr = x; if( FAILED(hr) ) { return DXUTTrace( __FILE__, (DWORD)__LINE__, hr, L#x, true ); } } +#else + #define V(x) { hr = x; } + #define V_RETURN(x) { hr = x; if( FAILED(hr) ) { return hr; } } +#endif + +#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } +#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } +#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } + +#endif // !defined(DXSDK_STDAFX_H) diff --git a/usr/Include/Core/3d/nvfile.h b/usr/Include/Core/3d/nvfile.h new file mode 100644 index 0000000..8466330 --- /dev/null +++ b/usr/Include/Core/3d/nvfile.h @@ -0,0 +1,47 @@ +/****************************************************************************** + + Copyright (C) 1999, 2000 NVIDIA Corporation + This file is provided without support, instruction, or implied warranty of any + kind. NVIDIA makes no guarantee of its fitness for a particular purpose and is + not liable under any circumstances for any damages or loss whatsoever arising + from the use or inability to use this file or items derived from it. + + Comments: + + + +******************************************************************************/ +#ifndef __NVFILE_H +#define __NVFILE_H + +//#include "NVDX8Macros.h" +#include "3D\nvmesh.h" +#include "3D\nvframe.h" +#include +#include +typedef std::basic_string tstring; + +//#pragma comment(lib, "d3dxof.lib") +//#pragma comment(lib, "dxguid.lib") + +class NVFile : public NVFrame +{ + HRESULT LoadMesh( IDirect3DDevice9* pDevice, LPD3DXFILEDATA pFileData, + NVFrame* pParentFrame ); + HRESULT LoadFrame( IDirect3DDevice9* pDevice, LPD3DXFILEDATA pFileData, + NVFrame* pParentFrame ); +public: + + void GetBoundingInfo(NVBounds* pBounds); + HRESULT Create( IDirect3DDevice9* pDevice, const tstring& strFilename ); + HRESULT Render( IDirect3DDevice9* pDevice ); + + NVFile() : NVFrame( _T("NVFile_Root") ) {} + + tstring m_strFilePath; +}; + +#endif + + + diff --git a/usr/Include/Core/AutoLock.h b/usr/Include/Core/AutoLock.h new file mode 100644 index 0000000..43158e0 --- /dev/null +++ b/usr/Include/Core/AutoLock.h @@ -0,0 +1,572 @@ +/******************************************************************** + created: 2005/01/07 + created: 7:1:2002 13:08 + filename: D:\public\base\AutoLock.h + file path: D:\public\base + file base: AutoLock + file ext: h + author: Günter Baumgart + + purpose: +*********************************************************************/ + +#pragma once + +#include // Required for ATLASSERT macro +#include + +namespace AutoLock +{ + // SWMR enum wait lock types + enum _LOCKTYPE { LT_WAITTOREAD = 0, LT_WAITTOWRITE = 1 } ; + +template +class CAutoLockT +{ +// Attributes +private: + T* m_pObject; // the locked object + +// Ctor/dtor +public: + // Critical Section Ctor + inline CAutoLockT( T* pObject ) throw() + : m_pObject(pObject) + { + ATLASSERT( NULL != pObject ); + m_pObject->Lock(); + } + + // Mutex Ctor + inline CAutoLockT( T* pObject, DWORD dwTimeout ) + : m_pObject(pObject) + { + ATLASSERT( NULL != pObject ); + m_pObject->Lock( dwTimeout ); + } + + // SRMR Ctor + inline CAutoLockT( T* pObject, + const _LOCKTYPE uLockType, + LPCTSTR szOperation = NULL ) throw() + : m_pObject(pObject) + { + ATLASSERT( NULL != pObject ); + m_pObject->Lock( uLockType, szOperation ); + } + + // dtor + inline ~CAutoLockT() + { + m_pObject->Unlock(); + } +}; + +//+---------------------------------------------------------------------------- +// Class: CAutoLockWaitExc +// +// Purpose: CLockableMutex::Lock() method will throw this exception when +// an error occurs. +// +// Comment: NOTE: Callers should catch this exception. +//+---------------------------------------------------------------------------- +class CAutoLockWaitExc +{ +// Ctor +public: + CAutoLockWaitExc( DWORD dwWaitResult, DWORD dwError ) + : m_dwWaitResult( dwWaitResult ) + , m_dwError( dwError ) {} + +// Public Accessors +public: + inline const DWORD GetWaitResult() { return m_dwWaitResult; }; + inline const DWORD GetLastError() { return m_dwError; }; + +// Attributes +private: + DWORD m_dwWaitResult; // WaitForSingleObject return + DWORD m_dwError; // GetLastError return code +}; + +//+---------------------------------------------------------------------------- +// Class: CAutoLockExc +// +// Purpose: CLockableMutex::Lock() method will throw this exception when +// an error occurs. +// +// Comment: NOTE: Callers should catch this exception. +//+---------------------------------------------------------------------------- +class CAutoLockExc +{ +// Ctor +public: + CAutoLockExc( DWORD dwError ) + : m_dwError( dwError ) {} + +// Public Accessors +public: + inline const DWORD GetLastError() { return m_dwError; }; + +// Attributes +private: + DWORD m_dwError; // GetLastError return code +}; + +//+---------------------------------------------------------------------------- +// Embedded Class: CAutoLockTimeoutExc +// +// Purpose: CLockableMutex::Lock() method will throw this timeout exception +// when the timeout period has been exceeded. +// +// Comment: NOTE: Callers should catch this exception. +//+---------------------------------------------------------------------------- +class CAutoLockTimeoutExc +{ +// Ctor +public: + CAutoLockTimeoutExc( DWORD dwTimeout ) : m_dwTimeout( dwTimeout ) {} + +// Public Accessors +public: + inline const DWORD GetTimeout() { return m_dwTimeout; }; + +// Attributes +private: + DWORD m_dwTimeout; // Timeout value (although passed in + // to the Lock method, we store it + // here and make it available in the + // exception for convenience +}; + +//+---------------------------------------------------------------------------- +// Class: CLockableCS +// +// Purpose: This class is intended to be used as a base class for a +// multithreaded Critical Section lockable object. +// +//+---------------------------------------------------------------------------- +class CLockableCS +{ +// Methods +public: + // Ctor / Dtor + inline CLockableCS() throw() { InitializeCriticalSection( &m_CS ); } + inline ~CLockableCS() throw() { DeleteCriticalSection( &m_CS ); } + + // Lock / Unlock + inline void Lock() throw() { EnterCriticalSection( &m_CS ); } + inline void Unlock() throw() { LeaveCriticalSection( &m_CS ); } + +// Attributes +private: + CRITICAL_SECTION m_CS; // Internal Critical Section +}; + +//+---------------------------------------------------------------------------- +// Class: CLockableMutex +// +// Purpose: This class is intended to be used as a base class for a +// Mutex lockable object. +// +// Comment: NOTE: The lock method for this class will throw a +// CMutexLockExc exception (see below for declaration). +// Callees should catch this exception when calling the Lock method. +// +// Scope: Single or Multiple Processes +//+---------------------------------------------------------------------------- + +class CLockableMutex +{ +public: + inline CLockableMutex( LPCTSTR szName ) //throw() + : m_hMutex( ::CreateMutex( NULL, FALSE, szName ) ) + , m_bAlreadyExists( FALSE ) + { + // If the call has succeeded, check if the named mutex has already existed + if( NULL != m_hMutex ) + { + m_bAlreadyExists = ( ERROR_ALREADY_EXISTS == ::GetLastError( ) ); + } + else + { + // The call has failed. + if( ERROR_ACCESS_DENIED == ::GetLastError( ) ) + { + // We'll get the Access denied error when the mutex + // exists and the user does not have sufficient permissions + // to create an existing mutex (as in above). + // So we retry using OpenMutex + + if( NULL == ( m_hMutex = ::OpenMutex( MUTEX_MODIFY_STATE, + FALSE, + szName ) )) + { + // OpenMutex failed also, so throw an exception + throw CAutoLockExc( ::GetLastError( ) ); + } + else + { + m_bAlreadyExists = TRUE; + } + } + else + { + // Other unknown error + throw CAutoLockExc( ::GetLastError( ) ); + } + } + } + + inline ~CLockableMutex() throw() + { + if(m_hMutex) ::CloseHandle( m_hMutex ); + } + + //+------------------------------------------------------------------- + // Method: AlreadyExists + // Purpose: Use this method when you want to use a mutex to limit + // an executable to a single instance. Declare a CLockableMutex + // variable and check this param to find out if it existed + // prior to instantiating this class. + // + // Params: void + // Return: void + // + // Comments: See msdn docs on CreateMutex. This + //+------------------------------------------------------------------- + const BOOL AlreadyExists() { return m_bAlreadyExists; }; + + //+------------------------------------------------------------------- + // Method: Lock + // Purpose: Used by the CAutoLockT class to limit inter-process + // access. + // + // Params: ms Timeout + // Return: void + // + // Comments: Throws CTimeoutException or CException exceptions + //+------------------------------------------------------------------- + inline void Lock( DWORD dwTimeout ) + { + DWORD dwWaitResult = 0; + dwWaitResult = ::WaitForSingleObject( m_hMutex, dwTimeout ); + switch( dwWaitResult ) + { + case WAIT_OBJECT_0: + break; + case WAIT_TIMEOUT: + throw CAutoLockTimeoutExc( dwTimeout ); + break; + default: + throw CAutoLockWaitExc( dwWaitResult, ::GetLastError() ); + } + } + + //+------------------------------------------------------------------- + // Method: Unlock + // Purpose: Used by the CAutoLockT class (CAutoLockT::dtor) to + // release the mutex + // + // Params: void + // Return: void + inline void Unlock() throw() + { + if(m_hMutex) + { + ::ReleaseMutex( m_hMutex ); + } + } + +private: + HANDLE m_hMutex; // Name Mutex Handle + BOOL m_bAlreadyExists; // TRUE if named mutex already exists +}; + +//+---------------------------------------------------------------------------- +// Class: CLockableSWMR +// +// Purpose: This class is intended to be used as a base class for a +// SWMR (Single Writer, Multiple Reader) lockable object. +// +// Acknowledgements: +// This class is base on work by Jeffrey Richter in his book +// "Programming Applications for Microsoft Windows" +// +// Usage: +// Create a class derived from this and another resource class (such as +// an std::list<> class) when you have a scenario where the list seldom +// gets updated, but is frequently read by multiple threads. Under this +// scenario, this class would be more efficient than the CLockableCS +// class because multiple threads could read simultaneously whereas a +// CLockableCS implementation would only allow a single thread to read +// or write. Conversely, because this class makes use of the kernel +// semaphore object, it is not as efficient a CLockableCS under single +// read thread scenarios. +// +// To Lock to Read: +// CAutoLock< CLockableSWMR_Derived > lock( &m_SWMR, LT_WAITTOREAD ); +// +// To Lock to Write: +// CAutoLock< CLockableSWMR_Derived > lock( &m_SWMR, LT_WAITTOWRITE ); +// +// Public Methods: +// Lock( enumLockType, ... ) +// Unlock() +// +// Private Methods: +// WaitToRead(...) +// WaitToWrite(...) + + +// Scope: Single Process +//+---------------------------------------------------------------------------- +class CLockableSWMR +{ +public: + CLockableSWMR( ) throw() + : m_hSemReaders( CreateSemaphore(NULL, 0, MAXLONG, NULL) ) + , m_hSemWriters( CreateSemaphore(NULL, 0, MAXLONG, NULL) ) + , m_nWaitingReaders( 0 ) + , m_nWaitingWriters( 0 ) + , m_nActive( 0 ) + , m_sName( _T("") ) + { + } + + CLockableSWMR( LPCTSTR szName ) throw() + : m_hSemReaders( CreateSemaphore(NULL, 0, MAXLONG, NULL) ) + , m_hSemWriters( CreateSemaphore(NULL, 0, MAXLONG, NULL) ) + , m_nWaitingReaders( 0 ) + , m_nWaitingWriters( 0 ) + , m_nActive( 0 ) + , m_sName( szName ) + { + } + + ~CLockableSWMR() throw() + { + m_nWaitingReaders = 0; + m_nWaitingWriters = 0; + m_nActive = 0; + CloseHandle(m_hSemReaders); + CloseHandle(m_hSemWriters); + } + +// Attributes +private: + CLockableCS m_InternalCS; // Ensures exclusive access + // to member variables + HANDLE m_hSemReaders; // Readers wait on if a writer has access + HANDLE m_hSemWriters; // Writers wait on if a reader has access + int m_nWaitingReaders; // # of readers waiting + int m_nWaitingWriters; // # of writers waiting + int m_nActive; // # of threads currently w/access + // (0 == no threads, + // >0 == # of readers, + // -1 == 1 writer) + + CString m_sName; // Debug diagnostic string + + // Thread tracking enum + enum _ACTIVETHREADS { AT_ONEWRITER = -1, AT_NONE = 0 }; + +// Operations +public: + //+------------------------------------------------------------------- + // Method: Lock + // Purpose: Used by the CAutoLockT class to provide thread safe access. + // + // Params: enumLockType, szOperation (debug operation string) + // Return: void + //+------------------------------------------------------------------- + void Lock(const _LOCKTYPE enumLockType, + LPCTSTR szOperation = NULL ) throw() + { + switch(enumLockType) + { + case LT_WAITTOREAD: + WaitToRead( szOperation ); + break; + case LT_WAITTOWRITE: + WaitToWrite( szOperation ); + break; + default: + ATLASSERT(0); + } + } + + //+------------------------------------------------------------------- + // Method: Unlock + // Purpose: Used by the CAutoLockT class (CAutoLockT::dtor) to + // release the CS + // + // Params: void + // Return: void + //+------------------------------------------------------------------- + void Unlock() throw() + { + HANDLE hSem = NULL; // Assume no threads are waiting + long lCount = 1; // Assume only 1 waiter wakes; + // always true for writers + + { // Lock scope + + // Ensure exclusive access to member variables + CAutoLockT< CLockableCS > lock( &m_InternalCS ); + + ATLTRACE( _T("\t\t%s: Unlock - m_nActive: %d"), + m_sName, + m_nActive); + + if (m_nActive > 0) + { + // Readers have control so a reader must be done + m_nActive--; + } + else + { + // Writers have control so a writer must be done + m_nActive++; + } + + ATLTRACE( _T("\t\t%s: Unlock - m_nActive: %d\n"), + m_sName, + m_nActive); + + if(m_nActive == 0) + { + // No thread has access, who should wake up? + // NOTE: It is possible that readers could never get access + // if there are always writers wanting to write + + if (m_nWaitingWriters > 0) + { + // Writers are waiting and they take priority over readers + m_nActive = -1; // A writer will get access + hSem = m_hSemWriters; // Writers wait on this semaphore + m_nWaitingWriters--; // One less writer will be waiting + + // NOTE: The semaphore will release only 1 writer thread + ATLTRACE( _T("\b\t\t\t\t%s: Unlock - m_nWaitingWriters: %d\n"), + m_sName, + m_nWaitingWriters); + } + else if (m_nWaitingReaders > 0) + { + // Readers are waiting and no writers are waiting + m_nActive = m_nWaitingReaders;// All readers get access + m_nWaitingReaders = 0; // No readers will be waiting + hSem = m_hSemReaders; // Readers wait on this semaphore + lCount = m_nActive; // Semaphore releases all readers + + ATLTRACE( _T("\b\t\t\t\t%s: Unlock - m_nWaitingReaders: %d\n"), + m_sName, + m_nWaitingReaders); + } + else + { + // There are no threads waiting at all; + // no semaphore gets released + ATLTRACE( _T("\b\t\t\t\t%s: Unlock - m_nR/W = 0\n"), + m_sName); + } + } + } // End of CS Lock scope + + if (NULL != hSem) + { + // Some threads are to be released + ReleaseSemaphore(hSem, lCount, NULL); + } + } + + // Implementation +private: + void WaitToRead( LPCTSTR szOperation ) + { + BOOL bResourceWritePending = FALSE; + + { // Lock scope + + // Ensure exclusive access to member variables + CAutoLockT< CLockableCS > lock( &m_InternalCS ); + + // Are there writers waiting or is a writer writing? + bResourceWritePending + = (m_nWaitingWriters || (m_nActive < AT_NONE)); + + if (bResourceWritePending) + { + // This reader must wait, + // increment the count of waiting readers + m_nWaitingReaders++; + } + else + { + ATLTRACE( _T("%s: WaitToRead - m_nActive: %d\tOp:%s\n"), + m_sName, + m_nActive, + ((szOperation) ? szOperation : _T(""))); + // This reader can read, increment the count of active readers + m_nActive++; + } + + } // End of Lock scope + + if (bResourceWritePending) + { + ATLTRACE( _T("%s: WaitToRead - m_nWaitingReaders: %d\tOp:%s\n"), + m_sName, + m_nWaitingReaders, + ((szOperation) ? szOperation : _T(""))); + // This thread must wait + WaitForSingleObject(m_hSemReaders, INFINITE); + } + } + + void WaitToWrite( LPCTSTR szOperation ) + { + BOOL bResourceOwned = FALSE; + + { // Lock scope + + // Ensure exclusive access to member variables + CAutoLockT< CLockableCS > lock( &m_InternalCS ); + + // Are there any threads accessing the resource? + bResourceOwned = (AT_NONE != m_nActive); + + if(bResourceOwned) + { + // This writer must wait; + // increment the count of waiting writers + m_nWaitingWriters++; + } + else + { + ATLTRACE( _T("%s: WaitToWrite %s - Okay TID: %d\n"), + m_sName, + ((szOperation) ? szOperation : _T("")), + GetCurrentThreadId()); + // This writer can write, prevent access to others + m_nActive = AT_ONEWRITER; + } + + } // End of lock scope + + if (bResourceOwned) + { + ATLTRACE( _T("%s: WaitToWrite %s - m_nWaitingWriters: %d TID: %d\n"), + m_sName, + ((szOperation) ? szOperation : _T("")), + m_nWaitingWriters, + GetCurrentThreadId()); + + // This thread must wait + WaitForSingleObject(m_hSemWriters, INFINITE); + } + } +}; + +} // End of namespace AutoLock \ No newline at end of file diff --git a/usr/Include/Core/Common/AutoLock.h b/usr/Include/Core/Common/AutoLock.h new file mode 100644 index 0000000..7f2a4fa --- /dev/null +++ b/usr/Include/Core/Common/AutoLock.h @@ -0,0 +1,560 @@ +#pragma once //its win32 + +#include // Required for ATLASSERT macro +#include + +namespace AutoLock +{ + // SWMR enum wait lock types + enum _LOCKTYPE { LT_WAITTOREAD = 0, LT_WAITTOWRITE = 1 } ; + +template +class CAutoLockT +{ +// Attributes +private: + T* m_pObject; // the locked object + +// Ctor/dtor +public: + // Critical Section Ctor + inline CAutoLockT( T* pObject ) throw() + : m_pObject(pObject) + { + ATLASSERT( NULL != pObject ); + m_pObject->Lock(); + } + + // Mutex Ctor + inline CAutoLockT( T* pObject, DWORD dwTimeout ) + : m_pObject(pObject) + { + ATLASSERT( NULL != pObject ); + m_pObject->Lock( dwTimeout ); + } + + // SRMR Ctor + inline CAutoLockT( T* pObject, + const _LOCKTYPE uLockType, + LPCTSTR szOperation = NULL ) throw() + : m_pObject(pObject) + { + ATLASSERT( NULL != pObject ); + m_pObject->Lock( uLockType, szOperation ); + } + + // dtor + inline ~CAutoLockT() + { + m_pObject->Unlock(); + } +}; + +//+---------------------------------------------------------------------------- +// Class: CAutoLockWaitExc +// +// Purpose: CLockableMutex::Lock() method will throw this exception when +// an error occurs. +// +// Comment: NOTE: Callers should catch this exception. +//+---------------------------------------------------------------------------- +class CAutoLockWaitExc +{ +// Ctor +public: + CAutoLockWaitExc( DWORD dwWaitResult, DWORD dwError ) + : m_dwWaitResult( dwWaitResult ) + , m_dwError( dwError ) {} + +// Public Accessors +public: + inline const DWORD GetWaitResult() { return m_dwWaitResult; }; + inline const DWORD GetLastError() { return m_dwError; }; + +// Attributes +private: + DWORD m_dwWaitResult; // WaitForSingleObject return + DWORD m_dwError; // GetLastError return code +}; + +//+---------------------------------------------------------------------------- +// Class: CAutoLockExc +// +// Purpose: CLockableMutex::Lock() method will throw this exception when +// an error occurs. +// +// Comment: NOTE: Callers should catch this exception. +//+---------------------------------------------------------------------------- +class CAutoLockExc +{ +// Ctor +public: + CAutoLockExc( DWORD dwError ) + : m_dwError( dwError ) {} + +// Public Accessors +public: + inline const DWORD GetLastError() { return m_dwError; }; + +// Attributes +private: + DWORD m_dwError; // GetLastError return code +}; + +//+---------------------------------------------------------------------------- +// Embedded Class: CAutoLockTimeoutExc +// +// Purpose: CLockableMutex::Lock() method will throw this timeout exception +// when the timeout period has been exceeded. +// +// Comment: NOTE: Callers should catch this exception. +//+---------------------------------------------------------------------------- +class CAutoLockTimeoutExc +{ +// Ctor +public: + CAutoLockTimeoutExc( DWORD dwTimeout ) : m_dwTimeout( dwTimeout ) {} + +// Public Accessors +public: + inline const DWORD GetTimeout() { return m_dwTimeout; }; + +// Attributes +private: + DWORD m_dwTimeout; // Timeout value (although passed in + // to the Lock method, we store it + // here and make it available in the + // exception for convenience +}; + +//+---------------------------------------------------------------------------- +// Class: CLockableCS +// +// Purpose: This class is intended to be used as a base class for a +// multithreaded Critical Section lockable object. +// +//+---------------------------------------------------------------------------- +class CLockableCS +{ +// Methods +public: + // Ctor / Dtor + inline CLockableCS() throw() { InitializeCriticalSection( &m_CS ); } + inline ~CLockableCS() throw() { DeleteCriticalSection( &m_CS ); } + + // Lock / Unlock + inline void Lock() throw() { EnterCriticalSection( &m_CS ); } + inline void Unlock() throw() { LeaveCriticalSection( &m_CS ); } + +// Attributes +private: + CRITICAL_SECTION m_CS; // Internal Critical Section +}; + +//+---------------------------------------------------------------------------- +// Class: CLockableMutex +// +// Purpose: This class is intended to be used as a base class for a +// Mutex lockable object. +// +// Comment: NOTE: The lock method for this class will throw a +// CMutexLockExc exception (see below for declaration). +// Callees should catch this exception when calling the Lock method. +// +// Scope: Single or Multiple Processes +//+---------------------------------------------------------------------------- + +class CLockableMutex +{ +public: + inline CLockableMutex( LPCTSTR szName ) //throw() + : m_hMutex( ::CreateMutex( NULL, FALSE, szName ) ) + , m_bAlreadyExists( FALSE ) + { + // If the call has succeeded, check if the named mutex has already existed + if( NULL != m_hMutex ) + { + m_bAlreadyExists = ( ERROR_ALREADY_EXISTS == ::GetLastError( ) ); + } + else + { + // The call has failed. + if( ERROR_ACCESS_DENIED == ::GetLastError( ) ) + { + // We'll get the Access denied error when the mutex + // exists and the user does not have sufficient permissions + // to create an existing mutex (as in above). + // So we retry using OpenMutex + + if( NULL == ( m_hMutex = ::OpenMutex( MUTEX_MODIFY_STATE, + FALSE, + szName ) )) + { + // OpenMutex failed also, so throw an exception + throw CAutoLockExc( ::GetLastError( ) ); + } + else + { + m_bAlreadyExists = TRUE; + } + } + else + { + // Other unknown error + throw CAutoLockExc( ::GetLastError( ) ); + } + } + } + + inline ~CLockableMutex() throw() + { + if(m_hMutex) ::CloseHandle( m_hMutex ); + } + + //+------------------------------------------------------------------- + // Method: AlreadyExists + // Purpose: Use this method when you want to use a mutex to limit + // an executable to a single instance. Declare a CLockableMutex + // variable and check this param to find out if it existed + // prior to instantiating this class. + // + // Params: void + // Return: void + // + // Comments: See msdn docs on CreateMutex. This + //+------------------------------------------------------------------- + const BOOL AlreadyExists() { return m_bAlreadyExists; }; + + //+------------------------------------------------------------------- + // Method: Lock + // Purpose: Used by the CAutoLockT class to limit inter-process + // access. + // + // Params: ms Timeout + // Return: void + // + // Comments: Throws CTimeoutException or CException exceptions + //+------------------------------------------------------------------- + inline void Lock( DWORD dwTimeout ) + { + DWORD dwWaitResult = 0; + dwWaitResult = ::WaitForSingleObject( m_hMutex, dwTimeout ); + switch( dwWaitResult ) + { + case WAIT_OBJECT_0: + break; + case WAIT_TIMEOUT: + throw CAutoLockTimeoutExc( dwTimeout ); + break; + default: + throw CAutoLockWaitExc( dwWaitResult, ::GetLastError() ); + } + } + + //+------------------------------------------------------------------- + // Method: Unlock + // Purpose: Used by the CAutoLockT class (CAutoLockT::dtor) to + // release the mutex + // + // Params: void + // Return: void + inline void Unlock() throw() + { + if(m_hMutex) + { + ::ReleaseMutex( m_hMutex ); + } + } + +private: + HANDLE m_hMutex; // Name Mutex Handle + BOOL m_bAlreadyExists; // TRUE if named mutex already exists +}; + +//+---------------------------------------------------------------------------- +// Class: CLockableSWMR +// +// Purpose: This class is intended to be used as a base class for a +// SWMR (Single Writer, Multiple Reader) lockable object. +// +// Acknowledgments: +// This class is base on work by Jeffrey Richter in his book +// "Programming Applications for Microsoft Windows" +// +// Usage: +// Create a class derived from this and another resource class (such as +// an std::list<> class) when you have a scenario where the list seldom +// gets updated, but is frequently read by multiple threads. Under this +// scenario, this class would be more efficient than the CLockableCS +// class because multiple threads could read simultaneously whereas a +// CLockableCS implementation would only allow a single thread to read +// or write. Conversely, because this class makes use of the kernel +// semaphore object, it is not as efficient a CLockableCS under single +// read thread scenarios. +// +// To Lock to Read: +// CAutoLock< CLockableSWMR_Derived > lock( &m_SWMR, LT_WAITTOREAD ); +// +// To Lock to Write: +// CAutoLock< CLockableSWMR_Derived > lock( &m_SWMR, LT_WAITTOWRITE ); +// +// Public Methods: +// Lock( enumLockType, ... ) +// Unlock() +// +// Private Methods: +// WaitToRead(...) +// WaitToWrite(...) + + +// Scope: Single Process +//+---------------------------------------------------------------------------- +class CLockableSWMR +{ +public: + CLockableSWMR( ) throw() + : m_hSemReaders( CreateSemaphore(NULL, 0, MAXLONG, NULL) ) + , m_hSemWriters( CreateSemaphore(NULL, 0, MAXLONG, NULL) ) + , m_nWaitingReaders( 0 ) + , m_nWaitingWriters( 0 ) + , m_nActive( 0 ) + , m_sName( _T("") ) + { + } + + CLockableSWMR( LPCTSTR szName ) throw() + : m_hSemReaders( CreateSemaphore(NULL, 0, MAXLONG, NULL) ) + , m_hSemWriters( CreateSemaphore(NULL, 0, MAXLONG, NULL) ) + , m_nWaitingReaders( 0 ) + , m_nWaitingWriters( 0 ) + , m_nActive( 0 ) + , m_sName( szName ) + { + } + + ~CLockableSWMR() throw() + { + m_nWaitingReaders = 0; + m_nWaitingWriters = 0; + m_nActive = 0; + CloseHandle(m_hSemReaders); + CloseHandle(m_hSemWriters); + } + +// Attributes +private: + CLockableCS m_InternalCS; // Ensures exclusive access + // to member variables + HANDLE m_hSemReaders; // Readers wait on if a writer has access + HANDLE m_hSemWriters; // Writers wait on if a reader has access + int m_nWaitingReaders; // # of readers waiting + int m_nWaitingWriters; // # of writers waiting + int m_nActive; // # of threads currently w/access + // (0 == no threads, + // >0 == # of readers, + // -1 == 1 writer) + + CString m_sName; // Debug diagnostic string + + // Thread tracking enum + enum _ACTIVETHREADS { AT_ONEWRITER = -1, AT_NONE = 0 }; + +// Operations +public: + //+------------------------------------------------------------------- + // Method: Lock + // Purpose: Used by the CAutoLockT class to provide thread safe access. + // + // Params: enumLockType, szOperation (debug operation string) + // Return: void + //+------------------------------------------------------------------- + void Lock(const _LOCKTYPE enumLockType, + LPCTSTR szOperation = NULL ) throw() + { + switch(enumLockType) + { + case LT_WAITTOREAD: + WaitToRead( szOperation ); + break; + case LT_WAITTOWRITE: + WaitToWrite( szOperation ); + break; + default: + ATLASSERT(0); + } + } + + //+------------------------------------------------------------------- + // Method: Unlock + // Purpose: Used by the CAutoLockT class (CAutoLockT::dtor) to + // release the CS + // + // Params: void + // Return: void + //+------------------------------------------------------------------- + void Unlock() throw() + { + HANDLE hSem = NULL; // Assume no threads are waiting + long lCount = 1; // Assume only 1 waiter wakes; + // always true for writers + + { // Lock scope + + // Ensure exclusive access to member variables + CAutoLockT< CLockableCS > lock( &m_InternalCS ); + + ATLTRACE( _T("\t\t%s: Unlock - m_nActive: %d"), + m_sName, + m_nActive); + + if (m_nActive > 0) + { + // Readers have control so a reader must be done + m_nActive--; + } + else + { + // Writers have control so a writer must be done + m_nActive++; + } + + ATLTRACE( _T("\t\t%s: Unlock - m_nActive: %d\n"), + m_sName, + m_nActive); + + if(m_nActive == 0) + { + // No thread has access, who should wake up? + // NOTE: It is possible that readers could never get access + // if there are always writers wanting to write + + if (m_nWaitingWriters > 0) + { + // Writers are waiting and they take priority over readers + m_nActive = -1; // A writer will get access + hSem = m_hSemWriters; // Writers wait on this semaphore + m_nWaitingWriters--; // One less writer will be waiting + + // NOTE: The semaphore will release only 1 writer thread + ATLTRACE( _T("\b\t\t\t\t%s: Unlock - m_nWaitingWriters: %d\n"), + m_sName, + m_nWaitingWriters); + } + else if (m_nWaitingReaders > 0) + { + // Readers are waiting and no writers are waiting + m_nActive = m_nWaitingReaders;// All readers get access + m_nWaitingReaders = 0; // No readers will be waiting + hSem = m_hSemReaders; // Readers wait on this semaphore + lCount = m_nActive; // Semaphore releases all readers + + ATLTRACE( _T("\b\t\t\t\t%s: Unlock - m_nWaitingReaders: %d\n"), + m_sName, + m_nWaitingReaders); + } + else + { + // There are no threads waiting at all; + // no semaphore gets released + ATLTRACE( _T("\b\t\t\t\t%s: Unlock - m_nR/W = 0\n"), + m_sName); + } + } + } // End of CS Lock scope + + if (NULL != hSem) + { + // Some threads are to be released + ReleaseSemaphore(hSem, lCount, NULL); + } + } + + // Implementation +private: + void WaitToRead( LPCTSTR szOperation ) + { + BOOL bResourceWritePending = FALSE; + + { // Lock scope + + // Ensure exclusive access to member variables + CAutoLockT< CLockableCS > lock( &m_InternalCS ); + + // Are there writers waiting or is a writer writing? + bResourceWritePending + = (m_nWaitingWriters || (m_nActive < AT_NONE)); + + if (bResourceWritePending) + { + // This reader must wait, + // increment the count of waiting readers + m_nWaitingReaders++; + } + else + { + ATLTRACE( _T("%s: WaitToRead - m_nActive: %d\tOp:%s\n"), + m_sName, + m_nActive, + ((szOperation) ? szOperation : _T(""))); + // This reader can read, increment the count of active readers + m_nActive++; + } + + } // End of Lock scope + + if (bResourceWritePending) + { + ATLTRACE( _T("%s: WaitToRead - m_nWaitingReaders: %d\tOp:%s\n"), + m_sName, + m_nWaitingReaders, + ((szOperation) ? szOperation : _T(""))); + // This thread must wait + WaitForSingleObject(m_hSemReaders, INFINITE); + } + } + + void WaitToWrite( LPCTSTR szOperation ) + { + BOOL bResourceOwned = FALSE; + + { // Lock scope + + // Ensure exclusive access to member variables + CAutoLockT< CLockableCS > lock( &m_InternalCS ); + + // Are there any threads accessing the resource? + bResourceOwned = (AT_NONE != m_nActive); + + if(bResourceOwned) + { + // This writer must wait; + // increment the count of waiting writers + m_nWaitingWriters++; + } + else + { + ATLTRACE( _T("%s: WaitToWrite %s - Okay TID: %d\n"), + m_sName, + ((szOperation) ? szOperation : _T("")), + GetCurrentThreadId()); + // This writer can write, prevent access to others + m_nActive = AT_ONEWRITER; + } + + } // End of lock scope + + if (bResourceOwned) + { + ATLTRACE( _T("%s: WaitToWrite %s - m_nWaitingWriters: %d TID: %d\n"), + m_sName, + ((szOperation) ? szOperation : _T("")), + m_nWaitingWriters, + GetCurrentThreadId()); + + // This thread must wait + WaitForSingleObject(m_hSemWriters, INFINITE); + } + } +}; + +} // End of namespace AutoLock \ No newline at end of file diff --git a/usr/Include/Core/Common/IParameter.h b/usr/Include/Core/Common/IParameter.h new file mode 100644 index 0000000..8e71866 --- /dev/null +++ b/usr/Include/Core/Common/IParameter.h @@ -0,0 +1,132 @@ +#ifndef __IPARAMETER_H__ +#define __IPARAMETER_H__ + + +#include "vtPhysXBase.h" + +/*! + \if internal2 + \brief Interface for parameters, implemented as singleton. + Helps to convert from PhysX to Virtools and vice versa. + + \Note This class has been introduced to collect parameter exchange related functionality. In the initial implementation of + this SDK, pFactory was responsible to perform these tasks. + + \Warning We are migrating all parameter related functions from pFactory to here. + + \endif + + */ +class MODULE_API IParameter +{ + +public: + + /*! + * \brief Default Constructor. Not been used. This is a singleton class and needs to + be instanced only the PhysicManager + */ + IParameter(); + + IParameter(PhysicManager*_pManager); + + /************************************************************************************************/ + /** @name RigidBody + */ + //@{ + + + /** + \brief Conversion for the custom structure #pBSetup. + \param[in] pObjectDescr * dst, w: target object + \param[in] CKParameter * src, r : source parameter. + + \return int + + @see + */ + int copyTo(pObjectDescr*dst,CKParameter*src); + + /** + \brief Conversion for the custom structure #pBSetup. + \param[in] CKParameter * src, r : source parameter. + \param[in] pObjectDescr * dst, w: target object + + \return int + + @see + */ + int copyTo(CKParameter*dst,pObjectDescr*src); + + /** + \brief Conversion for the custom structure #pBPivotSettings. + \param[in] CKParameter * dst, w : target parameter. + \param[in] pObjectDescr * src, w: src object + + \return int + @see + + */ + + int copyTo(pOptimization& dst,CKParameter*src); + int copyTo(CKParameter*dst,pOptimization src); + + int copyTo(pCCDSettings& dst,CKParameter*src); + int copyTo(CKParameter*dst,pCCDSettings src); + + + int copyTo(pAxisReferencedLength&dst,CKParameter*src,bool evaluate=true); + int copyTo(CKParameter*dst,pAxisReferencedLength&src,bool evaluate=true); + + + + int copyTo(pCapsuleSettingsEx& dst,CKParameter*src); + int copyTo(CKParameter*dst,pCapsuleSettingsEx src); + + + + int copyTo(pConvexCylinderSettings& dst,CKParameter*src); + int copyTo(CKParameter*dst,pConvexCylinderSettings& src); + + int copyTo(pObjectDescr&dst,CK3dEntity*src,int copyFlags); + int copyTo(pObjectDescr&dst,const pObjectDescr&src); + + + int copyTo(pMassSettings& dst,CKParameter*src); + int copyTo(CKParameter*dst,pMassSettings src); + + int copyTo(pPivotSettings& dst,CKParameter*src); + int copyTo(CKParameter*dst,pPivotSettings src); + + int copyTo(pCollisionSettings& dst,CKParameter*src); + int copyTo(CKParameter*dst,pCollisionSettings src); + + int copyTo(pWheelDescr& dst,CKParameter*src); + int copyTo(CKParameter*dst,pWheelDescr src); + + int copyTo(pVehicleBrakeTable& dst,CKParameter*src); + + int copyTo(pLinearInterpolation&dst,CKParameter*src); + + int copyTo(pGearBox *dst,CKParameter*src); + int copyTo(CKParameter*dst,pGearBox *src); + + int copyTo(pLinearInterpolation&dst,CKParameter*src,int size,float maxValue,float minValue); + + + + //@} + + + + static IParameter* Instance(); + + private: + PhysicManager* mManager; + +}; + + +#define GetIPar() IParameter::Instance() + +#endif // __IPARAMETER_H__ \ No newline at end of file diff --git a/usr/Include/Core/Common/MemoryFileMappingPrerequisites.h b/usr/Include/Core/Common/MemoryFileMappingPrerequisites.h new file mode 100644 index 0000000..e24c999 --- /dev/null +++ b/usr/Include/Core/Common/MemoryFileMappingPrerequisites.h @@ -0,0 +1,20 @@ +/******************************************************************** + created: 2009/04/13 + created: 13:4:2009 22:08 + filename: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Include\Core\Common\MemoryFileMappingPrerequisites.h + file path: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Include\Core\Common + file base: MemoryFileMappingPrerequisites + file ext: h + author: Günter Baumgart + + purpose: Forward decalarations for memory file mappings +*********************************************************************/ +#ifndef __MEMORY_FILE_MAPPING_PREREQUISITES_H__ +#define __MEMORY_FILE_MAPPING_PREREQUISITES_H__ + + +struct vtExternalEvent; +struct TSharedMemory; +struct haptekMsg; + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/MemoryFileMappingTypes.h b/usr/Include/Core/Common/MemoryFileMappingTypes.h new file mode 100644 index 0000000..f079be9 --- /dev/null +++ b/usr/Include/Core/Common/MemoryFileMappingTypes.h @@ -0,0 +1,19 @@ +#ifndef __MEMORY_FILE_MAPPING_TYPES_H__ +#define __MEMORY_FILE_MAPPING_TYPES_H__ + +enum vtEventState +{ + EEVT_STARTED, + EEVT_FINISHED +}; + +struct vtExternalEvent +{ + unsigned long timeOfCreation; + + char command[MAX_PATH]; + char commandArg[MAX_PATH]; + vtEventState state; +}; + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/Prerequisites_3thParty.h b/usr/Include/Core/Common/Prerequisites_3thParty.h new file mode 100644 index 0000000..6ce2b1c --- /dev/null +++ b/usr/Include/Core/Common/Prerequisites_3thParty.h @@ -0,0 +1,22 @@ +#ifndef __PREREQUISITES_3TH_PARTY_H__ +#define __PREREQUISITES_3TH_PARTY_H__ + + + +//################################################################ +// +// External : TINY XML +// +class TiXmlNode; +class TiXmlDocument; +class TiXmlElement; + +//################################################################ +// +// External NxuStream +// + + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/Prerequisites_All.h b/usr/Include/Core/Common/Prerequisites_All.h new file mode 100644 index 0000000..2fbf8fd --- /dev/null +++ b/usr/Include/Core/Common/Prerequisites_All.h @@ -0,0 +1,53 @@ +/******************************************************************** + created: 2009/02/16 + created: 16:2:2009 9:07 + filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\ModulePrerequisites.h + file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common + file base: ModulePrerequisites + file ext: h + author: Günter Baumgart + + purpose: Include of all prerequisites +*********************************************************************/ +#ifndef __PREREQUISITES_ALL_H__ +#define __PREREQUISITES_ALL_H__ + +//################################################################ +// +// Common forward declarations : +// + +//################################################################ +// +// Virtools related forward declarations : +// +#include "Prerequisites_Virtools.h" + +//################################################################ +// +// 3th party forward declarations : +// +// + TinyXML +// + NXUStream +// +#include "Prerequisites_3thParty.h" + +//################################################################ +// +// Main library forward declarations : +// +#include "Prerequisites_PhysX.h" + +//################################################################ +// +// Forward declarations for this module itself : +// +#include "Prerequisites_Module.h" + +#include "Timing.h" + + + + +#endif + diff --git a/usr/Include/Core/Common/Prerequisites_Module.h b/usr/Include/Core/Common/Prerequisites_Module.h new file mode 100644 index 0000000..13aa63c --- /dev/null +++ b/usr/Include/Core/Common/Prerequisites_Module.h @@ -0,0 +1,97 @@ +#ifndef __PREREQUISITES_MODULE_H__ + #define __PREREQUISITES_MODULE_H__ + +class PhysicManager; + +//################################################################ +// +// Physic Types +// +class pContactReport; +class pTriggerReport; +class pRayCastReport; +class pContactModify; + + +class pRigidBody; +class pObjectDescr; + +class pJointSettings; +class pJoint; +class pJointBall; +class pJointFixed; +class pJointPulley; + +class pJointPointOnLine; +class pJointPointInPlane; +class pJointRevolute; +class pJointDistance; +class pJointD6; +class pJointPrismatic; +class pJointCylindrical; +class pClothDesc; +class pCloth; + +class pFluid; +class pFluidDesc; +class pFluidEmitterDesc; +class pFluidEmitter; +class pFluidRenderSettings; +class pWheelContactData; +class pSerializer; +class pWorld; +class pFactory; +class pSoftBody; + + +class pWheelDescr; +class pWheel; +class pWheel1; +class pWheel2; + +class pVecicleDescr; +class pVehicle; + +class pVehicleMotor; +class pVehicleGears; +class pVehicleMotorDesc; +class pVehicleGearDesc; + + +class pBoxController; + +class pObjectDescr; + + + +class IParameter; +struct pRigidBodyRestoreInfo; + + + +namespace vtAgeia +{ + class pWorldSettings; + class pSleepingSettings; + class pShape; + class pErrorStream; + class pCollisionsListener; +} + +class pLogger; +class ContactInfo; + +namespace vtTools +{ + + namespace ParameterTools + { + class CustomStructure; + } +} + + +using namespace vtAgeia; + +#endif + diff --git a/usr/Include/Core/Common/Prerequisites_PhysX.h b/usr/Include/Core/Common/Prerequisites_PhysX.h new file mode 100644 index 0000000..35defc8 --- /dev/null +++ b/usr/Include/Core/Common/Prerequisites_PhysX.h @@ -0,0 +1,90 @@ +#ifndef __PREREQUISITES_PHYS_X_H__ +#define __PREREQUISITES_PHYS_X_H__ + +class NxCompartment; +class NxActor; +class NxActorDesc; +class NxScene; +class NxSceneDescr; +class NxUserNotify; +class NxFluidUserNotify; +class NxCloth; +class NxClothDesc; +class NxClothUserNotify; +class NxClothMeshDesc; + +class NxSoftBodyUserNotify; +class NxUserContactModify; +class NxUserTriggerReport; +class NxUserContactReport; +class NxUserActorPairFiltering; +class NxBounds3; +class NxUserScheduler; +class NxSceneDesc; +class NxBodyDesc; +class NxShapeDesc; +class NxMaterial; +class NxMaterialDesc; +class NxUserDebugRenderer; +class NxTriangleMesh; +class NxTriangleMeshDesc; +class NxConvexMesh; +class NxConvexMeshDesc; +class NxUserOutputStream; +class NxUserAllocator; +class NxJoint; +class NxD6Joint; + +class NxStream; +class NxFoundationSDK; +class NxCCDSkeleton; //this class doesn't actually exist. +class NxSimpleTriangleMesh; +class NxHeightField; +class NxHeightFieldDesc; + +class NxPhysicsSDKDesc; +class NxPhysicsSDK; +class NxMeshData; +class NxClothMesh; +class NxControllerManager; +class NxBoxController; +class NxBoxControllerDesc; +class NxCapsuleController; +class NxCapsuleControllerDesc; +class UserAllocator; +class NxRemoteDebugger; +class NxShape; +class NxContactPair; +class NxConvexShapeDesc; +class NxWheelShape; +class NxConvexShape; +class NxCapsuleShape; +class NxRaycastHit; +class NxWheelContactData; + + +#if NX_USE_CLOTH_API + class NxClothMesh; +#endif +#if NX_USE_SOFTBODY_API + class NxSoftBodyMesh; +#endif + + +//---------------------------------------------------------------- +// +//! \brief NxU Stream +// +namespace NXU +{ + + class NxActorDesc; + class NxuPhysicsCollection; + + +} + + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/Prerequisites_Virtools.h b/usr/Include/Core/Common/Prerequisites_Virtools.h new file mode 100644 index 0000000..7a6705a --- /dev/null +++ b/usr/Include/Core/Common/Prerequisites_Virtools.h @@ -0,0 +1,37 @@ +/******************************************************************** + created: 2009/02/16 + created: 16:2:2009 8:57 + filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\vtPreReqs.h + file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common + file base: vtPreReqs + file ext: h + author: Günter Baumgart + + purpose: Virtools Forward Declarations +*********************************************************************/ +#ifndef __PREREQUISITES_VIRTOOSLS_H__ +#define __PREREQUISITES_VIRTOOSLS_H__ + +//################################################################ +// +// Common Types +// + +class CKBeObject; +class CKContext; +class CKParameter; +class CKParameterIn; +class CKParameterOut; +class CKParameterManager; +class CKAttributeManager; + +//################################################################ +// +// 3D Types +// +class CKMesh; +class CK3dEntity; +class CK3dObject; +class CK3dPointCloud; + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/Stream.h b/usr/Include/Core/Common/Stream.h new file mode 100644 index 0000000..116be0b --- /dev/null +++ b/usr/Include/Core/Common/Stream.h @@ -0,0 +1,78 @@ +#ifndef STREAM_H +#define STREAM_H + +#include "NxStream.h" + +class UserStream : public NxStream + { + public: + UserStream(const char* filename, bool load); + virtual ~UserStream(); + + virtual NxU8 readByte() const; + virtual NxU16 readWord() const; + virtual NxU32 readDword() const; + virtual float readFloat() const; + virtual double readDouble() const; + virtual void readBuffer(void* buffer, NxU32 size) const; + + virtual NxStream& storeByte(NxU8 b); + virtual NxStream& storeWord(NxU16 w); + virtual NxStream& storeDword(NxU32 d); + virtual NxStream& storeFloat(NxReal f); + virtual NxStream& storeDouble(NxF64 f); + virtual NxStream& storeBuffer(const void* buffer, NxU32 size); + + FILE* fp; + }; + +class MemoryWriteBuffer : public NxStream + { + public: + MemoryWriteBuffer(); + virtual ~MemoryWriteBuffer(); + void clear(); + + virtual NxU8 readByte() const { NX_ASSERT(0); return 0; } + virtual NxU16 readWord() const { NX_ASSERT(0); return 0; } + virtual NxU32 readDword() const { NX_ASSERT(0); return 0; } + virtual float readFloat() const { NX_ASSERT(0); return 0.0f;} + virtual double readDouble() const { NX_ASSERT(0); return 0.0; } + virtual void readBuffer(void* buffer, NxU32 size) const { NX_ASSERT(0); } + + virtual NxStream& storeByte(NxU8 b); + virtual NxStream& storeWord(NxU16 w); + virtual NxStream& storeDword(NxU32 d); + virtual NxStream& storeFloat(NxReal f); + virtual NxStream& storeDouble(NxF64 f); + virtual NxStream& storeBuffer(const void* buffer, NxU32 size); + + NxU32 currentSize; + NxU32 maxSize; + NxU8* data; + }; + +class MemoryReadBuffer : public NxStream + { + public: + MemoryReadBuffer(const NxU8* data); + virtual ~MemoryReadBuffer(); + + virtual NxU8 readByte() const; + virtual NxU16 readWord() const; + virtual NxU32 readDword() const; + virtual float readFloat() const; + virtual double readDouble() const; + virtual void readBuffer(void* buffer, NxU32 size) const; + + virtual NxStream& storeByte(NxU8 b) { NX_ASSERT(0); return *this; } + virtual NxStream& storeWord(NxU16 w) { NX_ASSERT(0); return *this; } + virtual NxStream& storeDword(NxU32 d) { NX_ASSERT(0); return *this; } + virtual NxStream& storeFloat(NxReal f) { NX_ASSERT(0); return *this; } + virtual NxStream& storeDouble(NxF64 f) { NX_ASSERT(0); return *this; } + virtual NxStream& storeBuffer(const void* buffer, NxU32 size) { NX_ASSERT(0); return *this; } + + mutable const NxU8* buffer; + }; + +#endif diff --git a/usr/Include/Core/Common/cErrors.h b/usr/Include/Core/Common/cErrors.h new file mode 100644 index 0000000..f8f00e2 --- /dev/null +++ b/usr/Include/Core/Common/cErrors.h @@ -0,0 +1,18 @@ +static char* sErrorStrings[]= +{ + "OK", + "\t Intern :", + "\t No connection :", + "\t Not joined to a session:", + "\t Session needs right password:", + "\t Session is locked:", + "\t Session already exists:", + "\t Session is full:", + "\t You must be session master:", + "\t Invalid parameter :", + "\t There is not such user :", + "\t Distributed class already exists :", + "\t Couldn't connect to any server :", + "\t You already joined to a session :", + "\t No such session :" +}; \ No newline at end of file diff --git a/usr/Include/Core/Common/cooking.h b/usr/Include/Core/Common/cooking.h new file mode 100644 index 0000000..00d1f0b --- /dev/null +++ b/usr/Include/Core/Common/cooking.h @@ -0,0 +1,22 @@ +#ifndef COOKING_H + +#define COOKING_H + +#include "NxCooking.h" + +class NxPMap; +class NxTriangleMesh; +class NxUserOutputStream; + +bool hasCookingLibrary(); // check to see if the cooking library is available or not! +bool InitCooking(NxUserAllocator* allocator = NULL, NxUserOutputStream* outputStream = NULL); +void CloseCooking(); +bool CookConvexMesh(const NxConvexMeshDesc& desc, NxStream& stream); +bool CookClothMesh(const NxClothMeshDesc& desc, NxStream& stream); +bool CookTriangleMesh(const NxTriangleMeshDesc& desc, NxStream& stream); +bool CookSoftBodyMesh(const NxSoftBodyMeshDesc& desc, NxStream& stream); +bool CreatePMap(NxPMap& pmap, const NxTriangleMesh& mesh, NxU32 density, NxUserOutputStream* outputStream = NULL); +bool ReleasePMap(NxPMap& pmap); + + +#endif diff --git a/usr/Include/Core/Common/gConfig.h b/usr/Include/Core/Common/gConfig.h new file mode 100644 index 0000000..fec90ad --- /dev/null +++ b/usr/Include/Core/Common/gConfig.h @@ -0,0 +1,28 @@ +#ifndef __G_CONFIG_H__ +#define __G_CONFIG_H__ + +#ifdef _DEBUG + static bool GC_SHOWPARAMETER = true; +#else + static BOOL GC_SHOWPARAMETER = false; +#endif + + +//#define BBC_JOYSTICK +#define BBC_TOOLS +#define BB_TOOLS +#define HAS_CONFIG + +#define BBC_VEHICLES + + +#define BBC_CLOTHES +#define BBC_JOINTS + + +#define CORE_CLOTH +#define CORE_PARTICLE + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pCallbackObject.h b/usr/Include/Core/Common/pCallbackObject.h new file mode 100644 index 0000000..c92f507 --- /dev/null +++ b/usr/Include/Core/Common/pCallbackObject.h @@ -0,0 +1,168 @@ +#ifndef __P_CALLBACK_OBJECT_H__ +#define __P_CALLBACK_OBJECT_H__ + +#include +#include "vtInterfaceEnumeration.h" + +class pWheelContactModify; +class pCollisionsEntry; +class pTriggerEntry; +class pContactModifyData; +class pWheelContactModifyData; + +class MODULE_API pCallbackObject +{ + public: + + pCallbackObject() + { + preScript = -1; + postScript = -1; + callMask = 0; + overrideMask = -1; + contactScript = -1; + rayCastScript = -1; + wheelContactScript = -1; + triggerScript = -1; + + triggerEventMask = 0 ; + collisionEventMask = 0 ; + } + + int contactScript; + int rayCastScript; + int wheelContactScript; + int triggerScript; + int jointBreakScript; + + int collisionEventMask; + int contactModificationScript; + + int& getCollisionEventMask() { return collisionEventMask; } + void setCollisionEventMask(int val) { collisionEventMask = val; } + + int triggerEventMask; + + int& getTriggerEventMask() { return triggerEventMask; } + void setTriggerEventMask(int val) { triggerEventMask = val; } + + +// virtual void advanceTime(float lastDeltaMS); + + + + //---------------------------------------------------------------- + // + // generics + // + int overrideMask; + int& getOverrideMask() { return overrideMask; } + void setOverrideMask(int val) { overrideMask = val; } + + xBitSet callMask; + xBitSet& getCallMask() { return callMask; } + void setCallMask(int val) { callMask = val; } + + int preScript; + int& getPreScript() { return preScript; } + void setPreScript(int val) { preScript = val; } + + + int postScript; + int& getPostScript() { return postScript; } + void setPostScript(int val) { postScript = val; } + + virtual void processPostScript(){}; + virtual void processPreScript(){}; + + virtual int onPreProcess(){ return -1;}; + virtual int onPostProcess(){return -1;}; + + //---------------------------------------------------------------- + // + // generic contact call + // + int getContactScript() const { return contactScript; } + virtual void setContactScript(int behaviorID,int eventMask) + { + contactScript = behaviorID; + collisionEventMask = eventMask; + setFlag(getCallMask(),CB_OnContactNotify,behaviorID); + } + virtual int onContact(pCollisionsEntry *report){ return -1;}; + + + //---------------------------------------------------------------- + // + // raycast, unused ! + // + int getRayCastScript() const { return rayCastScript; } + virtual void setRayCastScript(int val) + { + rayCastScript = val; + setFlag(getCallMask(),CB_OnRayCastHit,val); + } + virtual bool onRayCastHit(NxRaycastHit *report){ return false;}; + + //---------------------------------------------------------------- + // + // trigger + // + int getTriggerScript() const { return triggerScript; } + virtual void setTriggerScript(int behaviorID,int eventMask,CK3dEntity *shapeReference = NULL) + { + triggerScript = behaviorID; + triggerEventMask = eventMask; + setFlag(getCallMask(),CB_OnTrigger,behaviorID); + + } + virtual int onTrigger(pTriggerEntry *report){ return -1;}; + + + //---------------------------------------------------------------- + // + // trigger + // + int getJointBreakScript() const { return jointBreakScript; } + virtual void setJointBreakScript(int behaviorID,CK3dEntity *shapeReference = NULL) + { + jointBreakScript = behaviorID; + setFlag(getCallMask(),CB_OnJointBreak,behaviorID); + } + virtual int onJointBreak(pBrokenJointEntry *entry){ return -1;}; + + //---------------------------------------------------------------- + // + // wheel related + // + int getWheelContactScript() const { return wheelContactScript; } + virtual void setWheelContactScript(int val) { wheelContactScript = val; } + + virtual bool onWheelContact(CK3dEntity* wheelShapeReference, VxVector& contactPoint, VxVector& contactNormal, float& contactPosition, float& normalForce, CK3dEntity* otherShapeReference, int& otherShapeMaterialIndex){return true;} + virtual bool onWheelContactModify(int& changeFlags,pWheelContactModifyData* contact){ return -1;} + + //---------------------------------------------------------------- + // + // contact modification + // + int getContactModificationScript() const { return contactModificationScript; } + virtual void setContactModificationScript(int val) + { + contactModificationScript = val; + setFlag(getCallMask(),CB_OnContactModify,val); + } + + virtual bool onContactConstraint(int& changeFlags,CK3dEntity *sourceObject,CK3dEntity *otherObject,pContactModifyData *data){ changeFlags = CMM_None; return true; }; + + + int processOptions; + virtual int& getProcessOptions() { return processOptions; } + virtual void setProcessOptions(int val) { processOptions = val; } + + + protected: + private: + + +}; +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pCallbackSignature.h b/usr/Include/Core/Common/pCallbackSignature.h new file mode 100644 index 0000000..92cdd0d --- /dev/null +++ b/usr/Include/Core/Common/pCallbackSignature.h @@ -0,0 +1,244 @@ +#ifndef __P_CALLBACK_SIGNATURE_H__ +#define __P_CALLBACK_SIGNATURE_H__ + +#include "pCommon.h" +#include "IParameter.h" +#include "vtBBHelper.h" +#include "xDebugTools.h" + +//---------------------------------------------------------------- +// +// wheel contact modify callback inputs +// +typedef enum bInputsWheelContactModifyCallback +{ + bbIWC_SrcObject, + bbIWC_Point, + bbIWC_Normal, + bbIWC_Position, + bbIWC_NormalForce, + bbIWC_OtherMaterialIndex, + bbIWC_Stub0, + bbIWC_Stub1, +}; +static BBParameter pInMapWheelContactModifyCallback[]= +{ + BB_PIN(bbIWC_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), + BB_PIN(bbIWC_Point,CKPGUID_VECTOR,"point",""), + BB_PIN(bbIWC_Normal,CKPGUID_VECTOR,"normal",""), + BB_PIN(bbIWC_Position,CKPGUID_FLOAT,"position",""), + BB_PIN(bbIWC_NormalForce,CKPGUID_FLOAT,"normalForce",""), + BB_PIN(bbIWC_OtherMaterialIndex,CKPGUID_INT,"otherMaterialIndex",""), + BB_PIN(bbIWC_Stub0,CKPGUID_INT,"stub0",""), + BB_PIN(bbIWC_Stub1,CKPGUID_INT,"stub1",""), +}; +//---------------------------------------------------------------- +// +// wheel contact modify callback outputs +// +typedef enum bOutputsWheelContactModifyCallback +{ + bbOWC_CreateContact, + bbOWC_ModificationFlags, + bbOWC_Point, + bbOWC_Normal, + bbOWC_Position, + bbOWC_NormalForce, + bbOWC_OtherMaterialIndex, + bbOWC_Stub0, + bbOWC_Stub1, +}; +static BBParameter pOutMapWheelContactModifyCallback[]= +{ + BB_PIN(bbOWC_CreateContact,CKPGUID_BOOL,"createContact",""), + BB_PIN(bbOWC_ModificationFlags,VTF_WHEEL_CONTACT_MODIFY_FLAGS,"modificationFlags",""), + BB_PIN(bbOWC_Point,CKPGUID_VECTOR,"_point",""), + BB_PIN(bbOWC_Normal,CKPGUID_VECTOR,"_normal",""), + BB_PIN(bbOWC_Position,CKPGUID_FLOAT,"_position",""), + BB_PIN(bbOWC_NormalForce,CKPGUID_FLOAT,"_normalForce",""), + BB_PIN(bbOWC_OtherMaterialIndex,CKPGUID_INT,"_otherMaterialIndex",""), + BB_PIN(bbOWC_Stub0,CKPGUID_INT,"_stub0",""), + BB_PIN(bbOWC_Stub1,CKPGUID_INT,"_stub1",""), +}; + +//---------------------------------------------------------------- +// +// contact modify callback ( has input and output ) +// +typedef enum bInputsContactModifyCallback +{ + bbICM_SrcObject, + bbICM_OtherObject, + bbICM_MinImpulse, + bbICM_MaxImpulse, + bbICM_Error, + bbICM_Target, + bbICM_LP0, + bbICM_LP1, + bbICM_LO0, + bbICM_LO1, + bbICM_SF0, + bbICM_SF1, + bbICM_DF0, + bbICM_DF1, + bbICM_Restitution, +}; +static BBParameter pInMapContactModifyCallback[]= +{ + BB_PIN(bbICM_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), + BB_PIN(bbICM_OtherObject,CKPGUID_3DENTITY,"otherObject",""), + BB_PIN(bbICM_MinImpulse,CKPGUID_FLOAT,"minImpulse",""), + BB_PIN(bbICM_MaxImpulse,CKPGUID_FLOAT,"maxImpulse",""), + BB_PIN(bbICM_Error,CKPGUID_VECTOR,"error",""), + BB_PIN(bbICM_Target,CKPGUID_VECTOR,"target",""), + BB_PIN(bbICM_LP0,CKPGUID_VECTOR,"localPosition0",""), + BB_PIN(bbICM_LP1,CKPGUID_VECTOR,"localPosition1",""), + BB_PIN(bbICM_LO0,CKPGUID_QUATERNION,"localOrientation0",""), + BB_PIN(bbICM_LO0,CKPGUID_QUATERNION,"localOrientation1",""), + BB_PIN(bbICM_SF0,CKPGUID_FLOAT,"staticFriction0",""), + BB_PIN(bbICM_SF1,CKPGUID_FLOAT,"staticFriction1",""), + BB_PIN(bbICM_DF0,CKPGUID_FLOAT,"dynamicFriction0",""), + BB_PIN(bbICM_DF0,CKPGUID_FLOAT,"dynamicFriction1",""), + BB_PIN(bbICM_DF0,CKPGUID_FLOAT,"restitution",""), +}; + + +//---------------------------------------------------------------- +// +// contact modify callback ( has input and output ) +// +typedef enum bOutputsContactModifyCallback +{ + bbOCM_ModifyFlags, + bbOCM_CreateContact, + bbOCM_MinImpulse, + bbOCM_MaxImpulse, + bbOCM_Error, + bbOCM_Target, + bbOCM_LP0, + bbOCM_LP1, + bbOCM_LO0, + bbOCM_LO1, + bbOCM_SF0, + bbOCM_SF1, + bbOCM_DF0, + bbOCM_DF1, + bbOCM_Restitution, +}; + +static BBParameter pOutMapContactModifyCallback[]= +{ + BB_PIN(bbOCM_ModifyFlags,VTF_CONTACT_MODIFY_FLAGS,"_modifyFlags",""), + BB_PIN(bbOCM_CreateContact,CKPGUID_BOOL,"createContact",""), + BB_PIN(bbOCM_MinImpulse,CKPGUID_FLOAT,"_minImpulse",""), + BB_PIN(bbOCM_MaxImpulse,CKPGUID_FLOAT,"_maxImpulse",""), + BB_PIN(bbOCM_Error,CKPGUID_VECTOR,"_error",""), + BB_PIN(bbOCM_Target,CKPGUID_VECTOR,"_target",""), + BB_PIN(bbOCM_LP0,CKPGUID_VECTOR,"_localPosition0",""), + BB_PIN(bbOCM_LP1,CKPGUID_VECTOR,"_localPosition1",""), + BB_PIN(bbOCM_LO0,CKPGUID_QUATERNION,"_localOrientation0",""), + BB_PIN(bbOCM_LO0,CKPGUID_QUATERNION,"_localOrientation1",""), + BB_PIN(bbOCM_SF0,CKPGUID_FLOAT,"_staticFriction0",""), + BB_PIN(bbOCM_SF1,CKPGUID_FLOAT,"_staticFriction1",""), + BB_PIN(bbOCM_DF0,CKPGUID_FLOAT,"_dynamicFriction0",""), + BB_PIN(bbOCM_DF0,CKPGUID_FLOAT,"_dynamicFriction1",""), + BB_PIN(bbOCM_DF0,CKPGUID_FLOAT,"_restitution",""), +}; + +//---------------------------------------------------------------- +// +// contact notify callback +// +typedef enum bInputsContactCallback +{ + bbI_SrcObject, + bbI_EventType, + bbI_NormalForce, + bbI_FForce, + bbI_Point, + bbI_PointNormalForce, + bbI_FaceNormal, + bbI_FaceIndex, + bbI_Distance, + bbI_OtherObject, +}; +static BBParameter pInMapContactCallback[]= +{ + BB_PIN(bbI_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), + BB_PIN(bbI_EventType,VTF_COLLISIONS_EVENT_MASK,"eventType",""), + BB_PIN(bbI_FaceNormal,CKPGUID_VECTOR,"sumNormalForce",""), + BB_PIN(bbI_FForce,CKPGUID_VECTOR,"sumFrictionForce",""), + BB_PIN(bbI_Point,CKPGUID_VECTOR,"point",""), + BB_PIN(bbI_PointNormalForce,CKPGUID_FLOAT,"pointNormalForce",""), + BB_PIN(bbI_FaceNormal,CKPGUID_VECTOR,"faceNormal",""), + BB_PIN(bbI_FaceIndex,CKPGUID_INT,"faceIndex",""), + BB_PIN(bbI_Distance,CKPGUID_FLOAT,"distance",""), + BB_PIN(bbI_OtherObject,CKPGUID_3DENTITY,"otherObject",""), +}; +//---------------------------------------------------------------- +// +// trigger +// +typedef enum bInputsTriggerCallback +{ + bbIT_SrcObject, + bbIT_EventType, + bbIT_OtherObject, +}; +static BBParameter pInMapTriggerCallback[]= +{ + BB_PIN(bbIT_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), + BB_PIN(bbIT_EventType,VTF_TRIGGER,"eventType",""), + BB_PIN(bbIT_OtherObject,CKPGUID_3DENTITY,"otherObject",""), +}; + +//---------------------------------------------------------------- +// +// trigger +// +typedef enum bInputsRaycastHitCallback +{ + bbRH_SrcObject, + bbRH_OtherObject, + bbRH_WorldImpact, + bbRH_WorldNormal, + bbRH_FIndex, + bbRH_FInternalIdex, + bbRH_Distance, + bbRH_UV, + bbRH_Material, + bbRH_Flags, +}; + +typedef enum bInputsJointBreakCallback +{ + bbJB_SrcObject, + bbJB_OtherObject, + bbJB_Force, + +}; + +static BBParameter pInMapRaycastHitCallback[]= +{ + BB_PIN(bbRH_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), + BB_PIN(bbRH_OtherObject,CKPGUID_3DENTITY,"otherObject",""), + BB_PIN(bbRH_WorldImpact,CKPGUID_VECTOR,"impact",""), + BB_PIN(bbRH_WorldNormal,CKPGUID_VECTOR,"normal",""), + BB_PIN(bbRH_FIndex,CKPGUID_INT,"faceIndex",""), + BB_PIN(bbRH_FInternalIdex,CKPGUID_INT,"faceInternalIndex",""), + BB_PIN(bbRH_Distance,CKPGUID_FLOAT,"distance",""), + BB_PIN(bbRH_UV,CKPGUID_2DVECTOR,"uv",""), + BB_PIN(bbRH_Material,CKPGUID_INT,"material",""), + BB_PIN(bbRH_Flags,VTF_RAY_HINTS,"flags",""), + +}; + + +static BBParameter pInMapJointBreakCallback[]= +{ + BB_PIN(bbJB_SrcObject,CKPGUID_3DENTITY,"sourceObject",""), + BB_PIN(bbJB_OtherObject,CKPGUID_3DENTITY,"otherObject",""), + BB_PIN(bbJB_Force,CKPGUID_FLOAT,"Break Force",""), +}; + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pConfig.h b/usr/Include/Core/Common/pConfig.h new file mode 100644 index 0000000..32cf6a7 --- /dev/null +++ b/usr/Include/Core/Common/pConfig.h @@ -0,0 +1,41 @@ +#ifndef __P_CONFIG_H__ +#define __P_CONFIG_H__ + + +#define SESSION_MAX 9000000 + +#define START_MONTH 7 +#define END_MONTH 12 +/* +////////////////////////////////////////////////////////////////////////// +#if defined (ReleaseDemo) + #define SESSION_LIMIT + #define MONTH_LIMIT + #ifndef AUTHOR + #define AUTHOR + #endif + #define DEMO_ONLY + +#endif + + +#if defined (ReleaseFree) + #define MONTH_LIMIT + #define AUTHOR +#endif + + +#if defined (ReleaseRedist) + #define REDIST + #undef DEMO_ONLY +#endif + + +#if defined (ReleaseDongle) + #define DONGLE_VERSION + #undef DEMO_ONLY +#endif + +*/ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pConstants.h b/usr/Include/Core/Common/pConstants.h new file mode 100644 index 0000000..fcf8436 --- /dev/null +++ b/usr/Include/Core/Common/pConstants.h @@ -0,0 +1,6 @@ +#ifndef __P_CONSTANTS_H__ +#define __P_CONSTANTS_H__ + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pCrossTypes.h b/usr/Include/Core/Common/pCrossTypes.h new file mode 100644 index 0000000..8a0eeaf --- /dev/null +++ b/usr/Include/Core/Common/pCrossTypes.h @@ -0,0 +1,13 @@ +#ifndef __PCROSS_TYPES_H__ +#define __PCROSS_TYPES_H__ + +#include "pTypes.h" +//#include "NxWheelDesc.h" +#include "VxMath.h" +#include "XString.h" +#include "CK3DEntity.h" +#include "pVTireFunction.h" + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pErrorStream.h b/usr/Include/Core/Common/pErrorStream.h new file mode 100644 index 0000000..9c3474b --- /dev/null +++ b/usr/Include/Core/Common/pErrorStream.h @@ -0,0 +1,22 @@ +#ifndef __P_ERRROR_STREAM_H__ +#define __P_ERRROR_STREAM_H__ + +#include "pTypes.h" +#include "NxUserOutputStream.h" + +namespace vtAgeia +{ + +class pErrorStream : public NxUserOutputStream +{ + +public: + pErrorStream(){} + void reportError(NxErrorCode e, const char* message, const char* file, int line); + NxAssertResponse reportAssertViolation(const char* message, const char* file, int line); + void print(const char* message); +}; + +} + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pLogger.h b/usr/Include/Core/Common/pLogger.h new file mode 100644 index 0000000..5fff1c9 --- /dev/null +++ b/usr/Include/Core/Common/pLogger.h @@ -0,0 +1,21 @@ +#ifndef __PLOGGER_H__ +#define __PLOGGER_H__ +#include "pTypes.h" + + class pLogger + { + + public: + pLogger(); + ~pLogger(); + + pErrorStream * getErrorStream() const { return mErrorStream; } + void setErrorStream(pErrorStream * val) { mErrorStream = val; } + + + protected: + pErrorStream *mErrorStream; + }; + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pMathTools.h b/usr/Include/Core/Common/pMathTools.h new file mode 100644 index 0000000..d445b4f --- /dev/null +++ b/usr/Include/Core/Common/pMathTools.h @@ -0,0 +1,46 @@ +#ifndef __XMATH_TOOLS_H__ +#define __XMATH_TOOLS_H__ + +#include "VxMath.h" +#include "NxQuat.h" + +namespace pMath +{ + +VxVector getFromStream(NxVec3 source); +VxQuaternion getFromStream(NxQuat source); + +NxVec3 getFromStream(VxVector source); +NxQuat getFromStream(VxQuaternion source); + + + + +/*__inline NxVec3 getFrom(const VxVector& sourcein) +{ + + return NxVec3(sourcein.x,sourcein.y,sourcein.z); +}*/ + +__inline NxVec3 getFrom(VxVector source) +{ + NxVec3 target(0.0f,0.0f,0.0f); + target.x = source.x; + target.y = source.y; + target.z = source.z; + return NxVec3(source.x,source.y,source.z); +} + +NxQuat getFrom(VxQuaternion source); +VxQuaternion getFrom(NxQuat source); + +__inline VxVector getFrom(NxVec3 source) +{ + VxVector result; + source.get(result.v); + return result; +} + +} + +#endif diff --git a/usr/Include/Core/Common/pMisc.h b/usr/Include/Core/Common/pMisc.h new file mode 100644 index 0000000..64ee7c5 --- /dev/null +++ b/usr/Include/Core/Common/pMisc.h @@ -0,0 +1,30 @@ +#ifndef __P_MISC_H__ +#define __P_MISC_H__ + +#include "vtPhysXBase.h" + + +namespace vtAgeia +{ + + VxVector BoxGetZero(CK3dEntity* ent); + void SetEulerDirection(CK3dEntity* ent,VxVector direction); + + XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide,int parameterSubIndex); + XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide); + + int getEnumIndex(CKParameterManager* pm,CKGUID parGuide,XString enumValue); + int getHullTypeFromShape(NxShape *shape); + CKGUID getEnumGuid(XString name); + + int getNbOfPhysicObjects(CK3dEntity *parentObject,int flags=0); + bool calculateOffsets(CK3dEntity*source,CK3dEntity*target,VxQuaternion &quat,VxVector& pos); + + bool isChildOf(CK3dEntity*parent,CK3dEntity*test); + CK3dEntity* findSimilarInSourceObject(CK3dEntity *parentOriginal,CK3dEntity* partentCopied,CK3dEntity *copiedObject,CK3dEntity*prev=NULL); + + CK3dEntity *getEntityFromShape(NxShape* shape); + + +} +#endif diff --git a/usr/Include/Core/Common/pNxSDKParameter.h b/usr/Include/Core/Common/pNxSDKParameter.h new file mode 100644 index 0000000..fca76d0 --- /dev/null +++ b/usr/Include/Core/Common/pNxSDKParameter.h @@ -0,0 +1,254 @@ +#ifndef __P_SDKP_SDK_PARAMETER_H__ +#define __P_SDKP_SDK_PARAMETER_H__ + + + + +/** \addtogroup PhysicSDK +@{ +*/ + +/** +\brief Parameters enums to be used as the 1st arg to setParameter or getParameter. + +@see PhysicManager.setParameter() PhysicManager.getParameter() +*/ +typedef enum pSDKParameter +{ + + /* RigidBody-related parameters */ + + + /** + \brief Default value for pShape::skinWidth. + + Range: [0, inf)
+ Default: 0.025
+ Unit: distance. + + @see pShape.setSkinWidth + */ + pSDKP_SkinWidth = 1, + + + /** + \brief The default linear velocity, squared, below which objects start going to sleep. + Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set. + + Range: [0, inf)
+ Default: (0.15*0.15) + + */ + pSDKP_DefaultSleepLinVelSquared = 2, + + /** + \brief The default angular velocity, squared, below which objects start going to sleep. + Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set. + + Range: [0, inf)
+ Default: (0.14*0.14) + + */ + pSDKP_DefaultSleepAngVelSquared = 3, + /** + \brief A contact with a relative velocity below this will not bounce. + + Range: (-inf, 0]
+ Default: -2 + + @see pMaterial + */ + pSDKP_BounceThreshold = 4, + + /** + \brief This lets the user scale the magnitude of the dynamic friction applied to all objects. + + Range: [0, inf)
+ Default: 1 + + @see pMaterial + */ + pSDKP_DynFrictScaling = 5, + + /** + \brief This lets the user scale the magnitude of the static friction applied to all objects. + + Range: [0, inf)
+ Default: 1 + + + @see pMaterial + */ + pSDKP_StaFrictionScaling = 6, + + /** + \brief See the comment for pRigidBody::setMaxAngularVelocity() for details. + + Range: [0, inf)
+ Default: 7 + + @see pRigidBody.setMaxAngularVelocity() + */ + pSDKP_MaxAngularVelocity = 7, + + /* Collision-related parameters: */ + + /** + \brief Enable/disable continuous collision detection (0.0f to disable) + + Range: [0, inf)
+ Default: 0.0 + + @see NxPhysicsSDK.createCCDSkeleton() + */ + pSDKP_ContinuousCD = 8, + + + + /* General parameters and new parameters */ + + /** + \brief Used to enable adaptive forces to accelerate convergence of the solver. + + Range: [0, inf)
+ Default: 1.0 + */ + pSDKP_AdaptiveForce = 68, + + /** + \brief Controls default filtering for jointed bodies. True means collision is disabled. + + Range: {true, false}
+ Default: true + + @see pSDKP_JF_CollisionEnabled + + */ + pSDKP_CollVetoJointed = 69, + + /** + \brief Controls whether two touching triggers generate a callback or not. + + Range: {true, false}
+ Default: true + + @see NxUserTriggerReport + */ + pSDKP_TriggerTriggerCallback = 70, + pSDKP_SelectHW_Algo = 71, + + /** + \brief Distance epsilon for the CCD algorithm. + + Range: [0, inf)
+ Default: 0.01 + + */ + pSDKP_CCDEpsilon = 73, + + /** + \brief Used to accelerate solver. + + Range: [0, inf)
+ Default: 0 + + */ + pSDKP_SolverConvergenceThreshold = 74, + + /** + \brief Used to accelerate HW Broad Phase. + + Range: [0, inf)
+ Default: 0.001 + + */ + pSDKP_BBoxNoiseLevel = 75, + + /** + \brief Used to set the sweep cache size. + + Range: [0, inf)
+ Default: 5.0 + + */ + pSDKP_ImplicitSweepCacheSize = 76, + + /** + \brief The default sleep energy threshold. Objects with an energy below this threshold are allowed + to go to sleep. + Note: Only used when the pSDKP_BF_ENERGY_SLEEP_TEST flag is set. + + Range: [0, inf)
+ Default: 0.005 + + */ + pSDKP_DefaultSleepEnergy = 77, + + /** + \brief Constant for the maximum number of packets per fluid. Used to compute the fluid packet buffer size in NxFluidPacketData. + + Range: [925, 925]
+ Default: 925 + + @see NxFluidPacketData + */ + pSDKP_ConstantFluidMaxPackets = 78, + + /** + \brief Constant for the maximum number of new fluid particles per frame. + Range: [4096, 4096]
+ Default: 4096 + + */ + pSDKP_ConstantFluidMaxParticlesPerStep = 79, + + /** + \brief [Experimental] Disables scene locks when creating/releasing meshes. + + Prevents the SDK from locking all scenes when creating and releasing triangle meshes, convex meshes, height field + meshes, softbody meshes and cloth meshes, which is the default behavior. Can be used to improve parallelism but beware + of possible side effects. + + \warning Experimental feature. + */ + pSDKP_AsynchronousMeshCreation = 96, + + /** + \brief Epsilon for custom force field kernels. + + This epsilon is used in custom force field kernels (NxSwTarget). Methods like recip() + or recipSqrt() evaluate to zero if their input is smaller than this epsilon. + +
+ */ + pSDKP_ForceFieldCustomKernelEpsilon = 97, + + /** + \brief Enable/disable improved spring solver for joints and wheelshapes + + This parameter allows to enable/disable an improved version of the spring solver for joints and wheelshapes. + + \warning + The parameter is introduced for legacy purposes only and will be removed in future versions (such that + the improved spring solver will always be used). + + \note + Changing the parameter will only affect newly created scenes but not existing ones. + + Range: {0: disabled, 1: enabled}
+ Default: 1 + + */ + pSDKP_ImprovedSpringSolver = 98, + + /** + \brief This is not a parameter, it just records the current number of parameters (as max(NxParameter)+1) for use in loops. + When a new parameter is added this number should be assigned to it and then incremented. + */ + pSDKP_PARAMS_NUM_VALUES = 99, + + pSDKP_PARAMS_FORCE_DWORD = 0x7fffffff +}; +/** @} */ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pObject.h b/usr/Include/Core/Common/pObject.h new file mode 100644 index 0000000..e69de29 diff --git a/usr/Include/Core/Common/pPrereqs.h b/usr/Include/Core/Common/pPrereqs.h new file mode 100644 index 0000000..9198947 --- /dev/null +++ b/usr/Include/Core/Common/pPrereqs.h @@ -0,0 +1,75 @@ +#ifndef __PPREREQS_H_ +#define __PPREREQS_H_ + +class PhysicManager; + +//################################################################ +// +// Physic Types +// +class pContactReport; +class pTriggerReport; +class pRayCastReport; + +class pRigidBody; +class pObjectDescr; + +class pJointSettings; +class pJoint; +class pJointBall; +class pJointFixed; +class pJointPulley; + +class pJointRevolute; +class pJointDistance; +class pJointD6; +class pJointPrismatic; +class pJointCylindrical; +class pClothDesc; +class pCloth; + +class pFluid; +class pFluidDesc; +class pFluidEmitterDesc; +class pFluidEmitter; +class pFluidRenderSettings; + + +class pSerializer; +class pWorld; +class pFactory; +class pSoftBody; + + +class pWheelDescr; +class pWheel; +class pWheel1; +class pWheel2; + +class pVecicleDescr; +class pVehicle; + +class pVehicleMotor; +class pVehicleGears; +class pVehicleMotorDesc; +class pVehicleGearDesc; + + +class pBoxController; + + +namespace vtAgeia +{ + class pWorldSettings; + class pSleepingSettings; + class pShape; + class pErrorStream; + class pCollisionsListener; +} + +class pLogger; + + +using namespace vtAgeia; + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pReferencedObject.h b/usr/Include/Core/Common/pReferencedObject.h new file mode 100644 index 0000000..f7ade86 --- /dev/null +++ b/usr/Include/Core/Common/pReferencedObject.h @@ -0,0 +1,96 @@ +#ifndef __P_REFERENCED_OBJECT_H__ +#define __P_REFERENCED_OBJECT_H__ + +templateclass MODULE_API pStoredObjectAssociation +{ + public: + + //xEngineObjectAssociation() : mInternalId(-1) , mClassId(-1) {}; + //xEngineObjectAssociation(EngineObject _Object,ImplementationObject _ImplObject,int _EngineObjectId) : mEngineObject(_Object) , mImplementationObject(_ImplObject) , mInternalId(_EngineObjectId) { } + //xEngineObjectAssociation< (EngineObject _Object,ImplementationObject _ImplObject,int _EngineObjectId){} + int getInternalId() const { return mInternalId; } + void setInternalId(int val) { mInternalId = val; } + + int getClassId() const { return mClassId; } + void setClassId(int val) { mClassId = val; } + + + bool existsInCore(); + + virtual void onCreate(){}; + virtual void onCopy(int oldId){}; + virtual void onRemove(){}; + virtual void onDelete(){}; + virtual void onCheck(){}; + + //operator T(){ return mObject; } + + + protected: + + private: + int mClassId; + int mInternalId; + EngineObject mEngineObject; + ImplementationObject mImplementationObject; + +}; + + +templateclass MODULE_API xImplementationObject +{ +public: + + //xLinkedObjectStorage() : mInternalId(-1) , mClassId(-1) {}; + typedef void* xImplementationObject::*StoragePtr; + xImplementationObject(){} + xImplementationObject(StoragePtr storage) + { + + } + + T getImpl() { return mObject; } + + + protected: + private: + T mObject; + StoragePtr mStorage; + +}; + + +templateclass MODULE_API xEngineObjectAssociation +{ + public: + + xEngineObjectAssociation() : + mInternalId(-1) , mClassId(-1) {}; + xEngineObjectAssociation(T _Object,int _InternalId) : + mObject(_Object) , mInternalId(_InternalId) { } + + int getInternalId() const { return mInternalId; } + void setInternalId(int val) { mInternalId = val; } + + int getClassId() const { return mClassId; } + void setClassId(int val) { mClassId = val; } + + + bool existsInCore(); + + virtual void onCreate(){}; + virtual void onCopy(int oldId){}; + virtual void onRemove(){}; + virtual void onDelete(){}; + virtual void onCheck(){}; + + //operator T(){ return mObject; } + + protected: + private: + int mClassId; + int mInternalId; + T mObject; + +}; +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pSleepingSettings.h b/usr/Include/Core/Common/pSleepingSettings.h new file mode 100644 index 0000000..74cc53d --- /dev/null +++ b/usr/Include/Core/Common/pSleepingSettings.h @@ -0,0 +1,50 @@ +/////////////////////////////////////////////////////////// +// dSleepingSettings.h +// Implementation of the Class dSleepingSettings +// Created on: 18-Jan-2008 17:15:31 +/////////////////////////////////////////////////////////// + +#if !defined(EA_7D481C15_2B93_4925_B66E_6FAF4DED2A2A__INCLUDED_) +#define EA_7D481C15_2B93_4925_B66E_6FAF4DED2A2A__INCLUDED_ + +namespace vtAgeia +{ + + +class pSleepingSettings +{ + +public: + pSleepingSettings() + { + m_AngularThresold = 0.1f; + m_LinearThresold = 0.1f; + m_SleepSteps = 0 ; + m_AutoSleepFlag = 1; + m_SleepTime = 0.0f; + } + virtual ~pSleepingSettings(){} + + int SleepSteps() const { return m_SleepSteps; } + void SleepSteps(int val) { m_SleepSteps = val; } + + float AngularThresold() const { return m_AngularThresold; } + void AngularThresold(float val) { m_AngularThresold = val; } + int AutoSleepFlag() const { return m_AutoSleepFlag; } + void AutoSleepFlag(int val) { m_AutoSleepFlag = val; } + + float LinearThresold() const { return m_LinearThresold; } + void LinearThresold(float val) { m_LinearThresold = val; } + + + + float m_AngularThresold; + int m_AutoSleepFlag; + float m_LinearThresold; + int m_SleepSteps; + float m_SleepTime; + +}; + +} +#endif // !defined(EA_7D481C15_2B93_4925_B66E_6FAF4DED2A2A__INCLUDED_) diff --git a/usr/Include/Core/Common/pTypes.h b/usr/Include/Core/Common/pTypes.h new file mode 100644 index 0000000..1b1096e --- /dev/null +++ b/usr/Include/Core/Common/pTypes.h @@ -0,0 +1,386 @@ +/******************************************************************** + created: 2009/02/17 + created: 17:2:2009 8:26 + filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\include\core\Common\pTypes.h + file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\include\core\Common + file base: pTypes + file ext: h + author: Günter Baumgart + + purpose: Type definitions, Function pointers +*********************************************************************/ +#ifndef __P_TYPES_H__ +#define __P_TYPES_H__ + +#include "vtPhysXBase.h" +#include "CKAll.h" + + +//################################################################ +// +// Common used types for rigid bodies and joints +// + + +/** +\brief Describes a joint spring. The spring is implicitly integrated, so even high spring and damper coefficients should be robust. +pSpring is registered as custom structure #pJSpring and can be accessed or modified through parameter operations.
+ +*/ +class pSpring +{ + +public: + /** + Damper coefficient + */ + float damper; + /** + Spring coefficient + */ + float spring; + /** + Target value (angle/position) of spring where the spring force is zero. + */ + float targetValue; + pSpring() + { + damper = 0.0f; + spring = 0.0f; + targetValue = 0.0f; + } + pSpring(float _damper,float _spring,float _targetValue) + { + + damper = _damper; + spring = _spring; + targetValue = _targetValue; + } +}; + + + + + +/** \addtogroup Collision +@{ +*/ + +/** +\brief 128-bit mask used for collision filtering. + +The collision filtering equation for 2 shapes S0 and S1 is: + +
 (G0 op0 K0) op2 (G1 op1 K1) == b 
+ +with + +
    +
  • G0 = pGroupsMask for shape S0. See ::setGroupsMask
  • +
  • G1 = pGroupsMask for shape S1. See ::setGroupsMask
  • +
  • K0 = filtering constant 0. See ::setFilterConstant0
  • +
  • K1 = filtering constant 1. See ::setFilterConstant1
  • +
  • b = filtering boolean. See ::setFilterBool
  • +
  • op0, op1, op2 = filtering operations. See ::setFilterOps
  • +
+ +If the filtering equation is true, collision detection is enabled. + +@see pWorld::setFilterOps() +*/ +class pGroupsMask +{ +public: + API_INLINE pGroupsMask() {} + API_INLINE ~pGroupsMask() {} + int bits0, bits1, bits2, bits3; +}; + + + +class pRay +{ + +public: + VxVector orig; + VxVector dir; + +}; + +class pRaycastHit +{ +public: + float distance; + CK3dEntity *shape; + VxVector worldImpact; + VxVector worldNormal; + int faceID; + int internalFaceID; + float u; + float v; + int materialIndex; + int flags; + + pRaycastHit() + { + distance = 0.0; + shape = NULL; + u = 0.0f; + v= 0.0f; + faceID = 0 ; + materialIndex = 0 ; + flags = 0; + + } + +}; + +/** +\brief Class for describing rigid bodies ccd settings. +*/ +class pCCDSettings +{ +public : + + bool isValid(); + bool setToDefault(); + bool evaluate(CKBeObject*referenceObject); + + float motionThresold; + int flags; + CK_ID meshReference; + float scale; + + pCCDSettings() + { + motionThresold = 0.0; + flags = 0 ; + meshReference =0; + scale = 1.0f; + } +}; + +/** + +\brief Class for describing rigid bodies or its sub shapes collisions settings. + +\sa #pRigidBody::updateCollisionSettings() +*/ +class pCollisionSettings +{ + public: + + bool isValid(); + bool setToDefault(); + /** + \brief collisions group the shape belongs to + - Range: [0,32] + - Default: 0 + */ + int collisionGroup; + /** + \brief 128-bit mask used for collision filtering + - Range: [0,4x4 bits] + - Default: all off + */ + pGroupsMask groupsMask; + /** + \brief Additional collisions offset + - Range: [0,1.0f] + - Default:0.25f + - Can NOT altered after creation + */ + float skinWidth; + + pCollisionSettings() + { + collisionGroup = 0; + skinWidth = 0.025f; + } +}; + +//@} + + + + + + +typedef std::vectorpRayCastHits; + + +/** +\brief Class for describing rigid bodies optimization. +*/ +class MODULE_API pOptimization +{ + public : + + bool isValid(); + bool setToDefault(); + + + + + /** + \brief Flags to lock a rigid body in certain degree of freedom. See also #pRigidBody::lockTransformation + */ + BodyLockFlags transformationFlags; + /** + \brief Sets the linear damping coefficient. Zero represents no damping. The damping coefficient must be nonnegative. See pRigidBody::setLinearDamping + */ + float linDamping; + /** + \brief Sets the angular damping coefficient.Zero represents no damping. The damping coefficient must be nonnegative.See pRigidBody::setAngularDamping + */ + float angDamping; + /** + \copydoc pRigidBody::setSolverIterationCount + */ + int solverIterations; + /** + \copydoc pRigidBody::setDominanceGroup + */ + int dominanceGroup; + /** + \brief Not Implemented + */ + int compartmentGroup; + /** + \copydoc pRigidBody::setSleepEnergyThreshold + */ + float sleepEnergyThreshold; + /** + \copydoc pRigidBody::setSleepLinearVelocity + */ + float linSleepVelocity; + /** + \copydoc pRigidBody::setSleepAngularVelocity + */ + float angSleepVelocity; + + pOptimization() + { + + transformationFlags = (BodyLockFlags)0; + + linDamping = angDamping = 0.0f; + solverIterations = 24 ; + dominanceGroup=0; + compartmentGroup=0; + sleepEnergyThreshold =0.0f; + linSleepVelocity = angSleepVelocity = 0.0; + } + +}; + +/** +\brief Class for describing a shape's surface properties. +*/ +class MODULE_API pMaterial +{ +public : + + bool isValid(); + + /** + \brief Flags, a combination of the bits defined by the enum ::pMaterialFlag
+ - Default: 0 + + @see MaterialFlags + */ + int flags; + + /** + \brief Coefficient of dynamic friction. If set to greater than staticFriction,
+ the effective value of staticFriction will be increased to match. if flags & MF_Anisotropic is set, then this value is used for the primary direction of anisotropy (U axis)
+ - Range: [0,+inf) + - Default: [0) + */ + float dynamicFriction; + /** + \brief Coefficient of static friction. If flags & MF_Anisotropic is set,
+ then this value is used for the primary direction of anisotropy (U axis) + */ + float staticFriction; + /** + \brief Coefficient of restitution. Makes the object bounce as little as possible, higher values up to 1.0 result in more bounce. Note that values close to or above 1 may cause stability problems and/or increasing energy. + - Range: [0,1) + - Default: [0) + */ + float restitution; + /** + \brief Anisotropic dynamic friction coefficient for along the secondary (V) axis of anisotropy. This is only used if flags & MF_Anisotropic is set. + - Range: [0,inf) + - Default: [0) + */ + float dynamicFrictionV; + /** + \brief Anisotropic static friction coefficient for along the secondary (V) axis of anisotropy. This is only used if flags & MF_Anisotropic is set. + - Range: [0,inf) + - Default: [0) + */ + float staticFrictionV; + /** + \brief Friction combine mode. See the enum CombineMode . + - Range: [CombineMode) + - Default: [CM_Average) + */ + CombineMode frictionCombineMode; + /** + \brief Restitution combine mode. See the enum CombineMode . + - Range: [CombineMode) + - Default: [CM_Average) + */ + CombineMode restitutionCombineMode; + /** + \brief shape space direction (unit vector) of anisotropy. This is only used if flags & MF_Anisotropic is set. + - Range: [vector) + - Default: [1.0f,0.0f,0.0f) + */ + VxVector dirOfAnisotropy; + + /** + \brief unique name of the material + */ + const char* name; + + /** + \brief Enumeration to identify a material setup from PhysicDefaults.xml. Is being populated automatically on reset. + - Range: [0,Number of material setups in xml file) + - Default: [NONE) + */ + int xmlLinkID; + + int getNxMaterialID() const { return mNxMaterialID; } + void setNxMaterialID(int val) { mNxMaterialID = val; } + + pMaterial() + { + setToDefault(); + } + __inline void setToDefault() + { + dynamicFriction = 0.0f; + staticFriction = 0.0f; + restitution = 0.0f; + dynamicFrictionV= 0.0f; + staticFrictionV = 0.0f; + dirOfAnisotropy = VxVector(1,0,0); + flags = 0; + frictionCombineMode = CM_Average; + restitutionCombineMode = CM_Average; + xmlLinkID =0; + name = ""; + } + + + +private : + + int mNxMaterialID; +}; + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/pVehicleAll.h b/usr/Include/Core/Common/pVehicleAll.h new file mode 100644 index 0000000..eb5694c --- /dev/null +++ b/usr/Include/Core/Common/pVehicleAll.h @@ -0,0 +1,45 @@ +#ifndef __P_VEHICLE_ALL_H__ + #define __P_VEHICLE_ALL_H__ + +#include +#include + +//using namespace std::numeric_limits; + +#define XFLT_EPSILON_MIN 0.00001f +#define XFLT_EPSILON_MAX FLT_MAX + +#define xCheckFloat(n) ((fabs(n) > XFLT_EPSILON_MIN && n < XFLT_EPSILON_MAX ) ? n : 0.0f) + + +typedef enum pVehicleProcessoptions +{ + pVPO_Lat_Damping=(1<<0), + pVPO_Long_Damping=(1<<1), + pVPO_SA_Damping=(1<<2), + pVPO_SA_Delay=(1<<3), + pVPO_SV_Tansa=(1<<4), + pVPO_SA_DownSettle=(1<<5), + pVPO_CheckLowSpeed=(1<<6), + pVPO_Wheel_LockAdjust=(1<<7), + pVPO_Wheel_UsePHYSX_Load=(1<<8), + pVPO_Wheel_UsePHYSX_CONTACT_DATA=(1<<9), + pVPO_Wheel_DoGregor=(1<<10), + pVPO_Wheel_DampVerticalVelocityReversal=(1<<11), + pVPO_Wheel_IntegrateImplicitVertical=(1<12), + pVPO_Wheel_DiffDirect=(1<<13), + pVPO_Engine_UseHardRevlimit=(1<<14), + pVPO_Forces_No_Lateral=(1<<15), + +}; + +#include "pEngine.h" +#include "pVehicleTypes.h" +#include "pGearbox.h" +#include "pDifferential.h" +#include "pSteer.h" + + + + +#endif diff --git a/usr/Include/Core/Common/qTimer.h b/usr/Include/Core/Common/qTimer.h new file mode 100644 index 0000000..4987d53 --- /dev/null +++ b/usr/Include/Core/Common/qTimer.h @@ -0,0 +1,103 @@ + +#ifndef __QLIB_TIMER_H +#define __QLIB_TIMER_H + +#include +#include +#ifdef linux + #include +#endif + +// Vertical trace resolution? +//#define USE_VTRACE + +#if defined(__sgi) + // UST nanosecond resolution? + #define USE_UST +#endif + +#if defined(linux) +// time() usage? Bad resolution and misplaced offsets within the second + #define USE_GETTIMEOFDAY +#endif + +#if defined(WIN32) + #define USE_OS_TICK // Use milliseconds NT timer +#endif + +#ifndef ulong + typedef unsigned long ulong; +#endif + + + +class MODULE_API QTimer +{ + private: +#ifdef USE_TIME + time_t base_secs; + int ticks; // Seconds (not very high frequency!) +#endif +#ifdef USE_GETTIMEOFDAY + int ticks; + struct timeval tv; // Should do microsecs + int base_usecs; // Base time in usecs + struct timeval tvBase; // Base time +#endif +#ifdef USE_OS_TICK + int ticks; + int baseTicks; +#endif + +#if defined(__sgi) + ulong base_secs,base_micros; // Intuition (Amiga) style + #ifdef USE_UST + uint64 ticks; // UST ticks go FAST! + uint64 baseUST; // UST timing + #endif + #ifdef USE_VTRACE + int baseVCount; // Vertical retraces base + int ticks; // Current #ticks recorded + #endif +#endif + + bool isRunning; // Recording time? + //QClassType ID() const { return QOBJ_TIMER; } + + protected: + void ResetBase(); // Base GLX vtrace counter + void UpdateTicks(); + + public: + QTimer(); + ~QTimer(); + + bool IsRunning(){ return isRunning; } + void Reset(); + void Start(); + void Stop(); + + // Get time + void GetTime(ulong *secs,ulong *micros); + ulong GetSeconds(); + int GetMilliSeconds(); + int GetMicroSeconds(); +#ifdef WIN32 + int GetTicks(); +#else +// SGI +#ifdef USE_UST + uint64 GetTicks(); +#else + int GetTicks(); +#endif +#endif + + // Adjust time + void AdjustMilliSeconds(int delta); + + // Higher level + void WaitForTime(int secs,int msecs=0); +}; + +#endif diff --git a/usr/Include/Core/Common/vcWarnings.h b/usr/Include/Core/Common/vcWarnings.h new file mode 100644 index 0000000..3decfc8 --- /dev/null +++ b/usr/Include/Core/Common/vcWarnings.h @@ -0,0 +1,19 @@ +#ifndef __VC_WARNINGS_H__ +#define __VC_WARNINGS_H__ + +#pragma warning( disable : 4311 ) +#pragma warning( disable : 4244 ) +#pragma warning( disable : 4267 ) +#pragma warning( disable : 4275 ) +#pragma warning( disable : 4311) +#pragma warning( disable : 4099) +#pragma warning( disable : 4996) +#pragma warning( disable : 4430) + + + + + + + +#endif diff --git a/usr/Include/Core/Common/vtAgeia.h b/usr/Include/Core/Common/vtAgeia.h new file mode 100644 index 0000000..77c1432 --- /dev/null +++ b/usr/Include/Core/Common/vtAgeia.h @@ -0,0 +1,15 @@ +#ifndef __VT_AGEIA_H__ +#define __VT_AGEIA_H__ + + +#include "pFactory.h" +#include "pWorldSettings.h" +#include "pSleepingSettings.h" +#include "pWorld.h" +#include "pRigidBody.h" +#include "pJoint.h" + + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtAgeiaTypes.h b/usr/Include/Core/Common/vtAgeiaTypes.h new file mode 100644 index 0000000..fcf4166 --- /dev/null +++ b/usr/Include/Core/Common/vtAgeiaTypes.h @@ -0,0 +1,90 @@ +/******************************************************************** + created: 2007/11/23 + created: 23:11:2007 12:21 + filename: e:\ProjectRoot\current\vt_plugins\vtOpenDynamics\Manager\vtOdeTypes.h + file path: e:\ProjectRoot\current\vt_plugins\vtOpenDynamics\Manager + file base: vtOdeTypes + file ext: h + author: mc007 + + purpose: +*********************************************************************/ +#ifndef __VTODE_TYPES_H_ + #define __VTODE_TYPES_H_ + + +#include "pSleepingSettings.h" +#include "pWorldSettings.h" + +typedef CK3dEntity* vt3DObjectType; +typedef VxVector xVector3; + +struct vtHeightFieldData +{ + + /* + int wS,dS,warp; + float w,d,thickness,scale; + int ID,tID; + float rF,gF,bF,aF; + float maxH; + CK_ID maxHReference; + dHeightfieldDataID heightFieldData; + vtHeightFieldData(float _w,float _d,float _thickness,float _scale,int _wS,int _dS,int _warp,int _ID,int _texID,float _rF,float _gF,float _bF,float _aF) : + w(_w) , d(_d) , thickness(_thickness) , scale(_scale ) ,warp(_warp) , ID(_ID) , wS(_wS) , dS(_dS) ,tID(_texID) , rF(_rF) , gF(_gF) ,bF(_bF) , aF(_aF) + { + heightFieldData = NULL; + } + + float lastH; + Vx2DVector lastHCoord; + int lastColor; +*/ + +}; +struct vtWorldInfo +{ + +/* VxVector Gravity; + float CFM; + float ERP; + float StepResFactor; + int MaxIterations; + int AutoEnableDepth; + float MaximumContactCorrectVelocity; + float ContactSurfaceLayer; + float rF,gF,bF,aF; + + vtWorldInfo() + { + Gravity.x = 0.0f; + Gravity.y = -10.0f; + Gravity.z = 0.0f; + CFM = 0.00000001f; + ERP = 0.9f; + AutoEnableDepth = 1; + MaxIterations = 100; + StepResFactor = 0.0085f; + } + + vtWorldInfo(VxVector _g,float _CFM,float _ERP,int _Auto,int _Max,float _StepResFactor,float _rF,float _gF,float _bF,float _aF) + : Gravity(_g) , CFM(_CFM) , ERP(_ERP) , AutoEnableDepth(_Auto) , MaxIterations(_Max) , StepResFactor(_StepResFactor) , rF(_rF) , gF(_gF),bF(_bF ),aF(_aF) + { + } +*/ +}; +////////////////////////////////////////////////////////////////////////// +struct vtIntersectionInfo +{ + /* + vt3DObjectType m_ObjectPart; + vt3DObjectType m_TouchedObstacle; + vt3DObjectType m_TouchedSubObstacle; + xVector3 m_position; + xVector3 m_Normal; + float m_Depth; + int m_num; + */ +}; + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtAttributeHelper.h b/usr/Include/Core/Common/vtAttributeHelper.h new file mode 100644 index 0000000..416e87f --- /dev/null +++ b/usr/Include/Core/Common/vtAttributeHelper.h @@ -0,0 +1,85 @@ +#ifndef __P_ATTRIBUTE_HELPER_H__ +#define __P_ATTRIBUTE_HELPER_H__ + +#define PHYSIC_BODY_CAT "Physic" + +#define ATT_FUNC_TABLE_SIZE 12 + +#include "vtParameterGuids.h" +#include "pManagerTypes.h" + +//################################################################ +// +// Declaration of rigid body related attribute callback function +// +int registerRigidBody(CK3dEntity *target,int attributeType,bool set,bool isPostJob); + +//################################################################ +// +// Declaration of various joint attribute callback functions +// +int registerJDistance(CK3dEntity *target,int attributeType,bool set,bool isPostJob); +int registerJFixed(CK3dEntity *target,int attributeType,bool set,bool isPostJob); +int registerJBall(CK3dEntity *target,int attributeType,bool set,bool isPostJob); + +int registerJPrismatic(CK3dEntity *target,int attributeType,bool set,bool isPostJob); +int registerJCylindrical(CK3dEntity *target,int attributeType,bool set,bool isPostJob); +int registerJPointInPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob); +int registerJPointOnLine(CK3dEntity *target,int attributeType,bool set,bool isPostJob); +int registerJRevolute(CK3dEntity *target,int attributeType,bool set,bool isPostJob); +int registerJD6(CK3dEntity *target,int attributeType,bool set,bool isPostJob); +int registerJD6Drive(CK3dEntity *target,int attributeType,bool set,bool isPostJob); +int registerJLimitPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob); + +//---------------------------------------------------------------- +// +//! \brief The global map of parameter type and registration function +// +static ObjectRegistration attributeFunctionMap[] = +{ + ObjectRegistration(VTS_PHYSIC_ACTOR,registerRigidBody), + ObjectRegistration(VTS_JOINT_DISTANCE,registerJDistance), + ObjectRegistration(VTS_JOINT_FIXED,registerJFixed), + ObjectRegistration(VTS_JOINT_BALL,registerJBall), + ObjectRegistration(VTS_JOINT_PRISMATIC,registerJPrismatic), + ObjectRegistration(VTS_JOINT_POINT_IN_PLANE,registerJPointInPlane), + ObjectRegistration(VTS_JOINT_POINT_ON_LINE,registerJPointOnLine), + ObjectRegistration(VTS_JOINT_CYLINDRICAL,registerJCylindrical), + ObjectRegistration(VTS_JOINT_REVOLUTE,registerJRevolute), + ObjectRegistration(VTS_JOINT_D6,registerJD6), + ObjectRegistration(VTS_JOINT_D6_DRIVES,registerJD6Drive), + ObjectRegistration(VTS_PHYSIC_JLIMIT_PLANE,registerJLimitPlane), +}; + + +//################################################################ +// +// Misc prototypes +// + +//---------------------------------------------------------------- +// +//! \brief This is the attribute callback function which is expected from Virtools. +// We only use this as dispatcher function because we have our own sub set. +// +void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); + + +//################################################################ +// +// OLD +// + + + +//---------------------------------------------------------------- +// +//! \brief this has become obselete +// +void recheckWorldsFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); // --> old ! + +void rigidBodyAttributeCallback(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); //-->new ! + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtCBBErrorHelper.h b/usr/Include/Core/Common/vtCBBErrorHelper.h new file mode 100644 index 0000000..cea2841 --- /dev/null +++ b/usr/Include/Core/Common/vtCBBErrorHelper.h @@ -0,0 +1,48 @@ +#ifndef __VT_C_BB_ERROR_HELPER_H__ + #define __VT_C_BB_ERROR_HELPER_H__ + +#ifndef __X_LOGGER_H__ + #include +#endif + + +#define CERROR_STRING(F) sBBErrorStrings[F] + + +#define bbSErrorME(A) { xLogger::xLog(XL_START,ELOGERROR,E_BB,CERROR_STRING(A));\ + XLOG_BB_INFO;\ + beh->ActivateOutput(0);\ + return CKBR_PARAMETERERROR ; } + +#define bbErrorME(A) { xLogger::xLog(XL_START,ELOGERROR,E_BB,A);\ + XLOG_BB_INFO;\ + beh->ActivateOutput(0);\ + return CKBR_PARAMETERERROR ; } + +#define bbWarning(A){ xLogger::xLog(XL_START,ELOGWARNING,E_BB,A);\ + XLOG_BB_INFO;\ +} + + + +/*#define XL_BB_NAME beh->GetPrototype()->GetName() +#define XL_BB_OWNER_SCRIPT beh->GetOwnerScript()->GetName() +#define XL_BB_OWNER_OBJECT beh->GetOwner() ? beh->GetOwner()->GetName() : "none" +#define XL_BB_SIGNATURE ("\n\tScript : %s\n\tBuildingBlock : %s \n\tObject :%s Error :") + + +#define XLOG_FMT(msg,extro) msg##extro +#define XLOG_MERGE(var, fmt) (#var##fmt ) +#define XLOG_MERGE2(var,fmt) (var##fmt) + +#define XLOG_BB_INFO xLogger::xLogExtro(0,XL_BB_SIGNATURE,XL_BB_OWNER_SCRIPT,XL_BB_NAME,XL_BB_OWNER_OBJECT) + +#define VTERROR_STRING(F) sErrorStrings[F] +#define bbError(F) XLOG_BB_INFO; \ + Error(beh,F,BB_OP_ERROR,VTERROR_STRING(F),TRUE,BB_O_ERROR,TRUE) +#define bbNoError(F) Error(beh,F,BB_OP_ERROR,VTERROR_STRING(F),FALSE,BB_O_ERROR,FALSE) +*/ + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtGUID.h b/usr/Include/Core/Common/vtGUID.h new file mode 100644 index 0000000..e5b758e --- /dev/null +++ b/usr/Include/Core/Common/vtGUID.h @@ -0,0 +1,99 @@ +/******************************************************************** + created: 2009/04/14 + created: 14:4:2009 10:06 + filename: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\SDK\Include\Core\Common\vtGUID.h + file path: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\SDK\Include\Core\Common + file base: vtGUID + file ext: h + author: Günter Baumgart + + purpose: Wrapper for CKGuid +*********************************************************************/ + +class vtGUID +{ +private: + CKGUID guid; + +public: + + CKGUID GetVirtoolsGUID() + { + return guid; + } + vtGUID( DWORD d1=0, DWORD d2=0 ):guid(d1,d2) {} + + XString ToString( void ) + { + XString laid; + + laid << DecimalToHex( guid.d1 ); + laid << DecimalToHex( guid.d2 ); + + return laid; + } + + bool FromString( const XString laid ) + { + + if( laid.Length() != 16 ) + return false; + + XString d1(laid); + XString d2(laid); + + d1.Crop( 0, 8 ); + d2.Crop( 8, 8 ); + + HexToDecimalHI( d1.Str(), guid.d1 ); + HexToDecimalLO( d2.Str(), guid.d2 ); + + return true; + } + + vtGUID & operator =( const CKGUID& ckguid ) + { + guid.d1 = ckguid.d1; + guid.d2 = ckguid.d2; + + return *this; + } + + operator XString() { return ToString(); } + +private: + XString DecimalToHex( int decimal ) + { + XString hexStr; + char hexstring[17]; + itoa( decimal, hexstring, 16); + + int length = strlen(hexstring); + if (length < 8) + { + int add = 8 - length; + for (int i = 0; i < add; i++) + { + hexStr << "0"; + } + } + + hexStr << hexstring; + + return hexStr; + + } + + bool HexToDecimalHI (char* HexNumber, unsigned int& Number) + { + char* pStopString; + Number = strtol (HexNumber, &pStopString, 16); + return (bool)(Number != LONG_MAX); + } + bool HexToDecimalLO(char* HexNumber, unsigned int& Number) + { + char* pStopString; + Number = strtoul(HexNumber, &pStopString, 16); + return (bool)(Number != LONG_MAX); + } +}; \ No newline at end of file diff --git a/usr/Include/Core/Common/vtInterfaceEnumeration.h b/usr/Include/Core/Common/vtInterfaceEnumeration.h new file mode 100644 index 0000000..1d72989 --- /dev/null +++ b/usr/Include/Core/Common/vtInterfaceEnumeration.h @@ -0,0 +1,773 @@ +/******************************************************************** + created: 2009/02/16 + created: 16:2:2009 20:25 + filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\vtInterfaceEnumeration.h + file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common + file base: vtInterfaceEnumeration + file ext: h + author: Günter Baumgart + + purpose: Declaration of enumerations with bindings in the interface : + + VSL + + Custom Enumeration + + Remarks The identifiers described here need to be consistent with types + registered for the interface. All types are used by this SDK + +*********************************************************************/ +#ifndef __VT_INTERFACE_ENUMERATION_H__ +#define __VT_INTERFACE_ENUMERATION_H__ + + + + + /** \addtogroup Callbacks + @{ + */ + typedef enum pCallback + { + CB_OnDelete = (1<<0), + CB_OnCopy = (1<<1), + CB_OnPreProcess = (1<<2), + CB_OnPostProcess = (1<<3), + CB_OnContactNotify = (1<<4), + CB_OnContactModify = (1<<5), + CB_OnRayCastHit = (1<<6), + CB_OnWheelContactModify = (1<<7), + CB_OnTrigger = (1<<8), + CB_OnJointBreak = (1<<9), + CB_Max, + }; + typedef enum pWheelContactModifyFlags + { + CWCM_ContactPoint = (1<<0), + CWCM_ContactNormal = (1<<1), + CWCM_ContactPosition = (1<<2), + CWCM_NormalForce = (1<<3), + CWCM_OtherMaterialIndex = (1<<4), + }; + /** @} */ + + + /** \addtogroup Collision + @{ + */ + + /** + \brief Contact pair flags. + + @see NxUserContactReport.onContactNotify() NxActor::setContactReportThreshold + */ + typedef enum pContactPairFlags + { + CPF_IgnorePair = (1<<0), //!< disable contact generation for this pair + + CPF_OnStartTouch = (1<<1), //!< pair callback will be called when the pair starts to be in contact + CPF_OnEndTouch = (1<<2), //!< pair callback will be called when the pair stops to be in contact + CPF_OnTouch = (1<<3), //!< pair callback will keep getting called while the pair is in contact + CPF_OnImpact = (1<<4), //!< [not yet implemented] pair callback will be called when it may be appropriate for the pair to play an impact sound + CPF_OnRoll = (1<<5), //!< [not yet implemented] pair callback will be called when the pair is in contact and rolling. + CPF_OnSlide = (1<<6), //!< [not yet implemented] pair callback will be called when the pair is in contact and sliding (and not rolling). + CPF_Forces = (1<<7), //!< the (summed total) friction force and normal force will be given in the nxcontactpair variable in the contact report. + CPF_OnStartTouchForceThreshold = (1<<8), //!< pair callback will be called when the contact force between two actors exceeds one of the actor-defined force thresholds + CPF_OnEndTouchForceThreshold = (1<<9), //!< pair callback will be called when the contact force between two actors falls below the actor-defined force thresholds + CPF_OnTouchForceThreshold = (1<<10), //!< pair callback will keep getting called while the contact force between two actors exceeds one of the actor-defined force thresholds + + CPF_ContactModification = (1<<16), //!< generate a callback for all associated contact constraints, making it possible to edit the constraint. this flag is not included in CPFall for performance reasons. \see nxusercontactmodify + }; + + typedef enum pContactModifyMask + { + + CMM_None = 0, //!< No changes made + + CMM_MinImpulse = (1<<0), //!< Min impulse value changed + CMM_MaxImpulse = (1<<1), //!< Max impulse value changed + CMM_Error = (1<<2), //!< Error vector changed + CMM_Target = (1<<3), //!< Target vector changed + + CMM_LocalPosition0 = (1<<4), //!< Local attachment position in shape 0 changed + CMM_LocalPosition1 = (1<<5), //!< Local attachment position in shape 1 changed + CMM_LocalOrientation0 = (1<<6), //!< Local orientation (normal, friction direction) in shape 0 changed + CMM_LocalOrientation1 = (1<<7), //!< Local orientation (normal, friction direction) in shape 1 changed + + CMM_StaticFriction0 = (1<<8), //!< Static friction parameter 0 changed. (Note: 0 does not have anything to do with shape 0/1) + CMM_StaticFriction1 = (1<<9), //!< Static friction parameter 1 changed. (Note: 1 does not have anything to do with shape 0/1) + CMM_DynamicFriction0 = (1<<10), //!< Dynamic friction parameter 0 changed. (Note: 0 does not have anything to do with shape 0/1) + CMM_DynamicFriction1 = (1<<11), //!< Dynamic friction parameter 1 changed. (Note: 1 does not have anything to do with shape 0/1) + CMM_Restitution = (1<<12), //!< Restitution value changed. + + CMM_Force32 = (1<<31) //!< Not a valid flag value, used by the enum to force the size to 32 bits. + + }; + + /** + Specifies which informations should be generated(when used as hint flags for ray casting methods). + */ + enum pRaycastBit + { + RCH_Shape = (1<<0), //!< "shape" member of #NxRaycastHit is valid + RCH_Impact = (1<<1), //!< "worldImpact" member of #NxRaycastHit is valid + RCH_Normal = (1<<2), //!< "worldNormal" member of #NxRaycastHit is valid + RCH_FaceIndex = (1<<3), //!< "faceID" member of #NxRaycastHit is valid + RCH_Distance = (1<<4), //!< "distance" member of #NxRaycastHit is valid + RCH_UV = (1<<5), //!< "u" and "v" members of #NxRaycastHit are valid + RCH_FaceNormal = (1<<6), //!< Same as RCH_NORMAL but computes a non-smoothed normal + RCH_Material= (1<<7), //!< "material" member of #NxRaycastHit is valid + }; + + /** + \brief Collision filtering operations. + + @see pGroupsMask + */ + enum pFilterOp + { + FO_And, + FO_Or, + FO_Xor, + FO_Nand, + FO_Nor, + FO_NXor, + FO_SwapAnd + }; + /** + \brief Used to specify which types(static or dynamic) of shape to test against when used with raycasting and overlap test methods in pWorld. + + */ + typedef enum pShapesType + { + /** + \brief Hits static shapes. + */ + ST_Static= 1, + + /** + \brief Hits dynamic shapes. + */ + ST_Dynamic= 2, + + /** + \brief Hits dynamic and static shapes. + */ + ST_All = ST_Dynamic|ST_Static, + }; + + + /** + \brief Flags which affect the behavior of NxShapes. + + @see pRigidBody.setTriggerFlags() + */ + typedef enum pTriggerFlags + { + /** + \brief Disables trigger callback. + */ + TF_Disable = (1<<3), + /** + \brief Trigger callback will be called when a shape enters the trigger volume. + */ + TF_OnEnter = (1<<0), + + /** + \brief Trigger callback will be called after a shape leaves the trigger volume. + */ + TF_OnLeave = (1<<1), + + /** + \brief Trigger callback will be called while a shape is intersecting the trigger volume. + */ + TF_OnStay = (1<<2) + + }; + /** @} */ + + typedef enum E_ENTITY_DATA_FLAGS + { + EDF_MATERIAL_PARAMETER, + EDF_SLEEPING_PARAMETER, + EDF_DAMPING_PARAMETER, + EDF_DEFORMABLE_PARAMETER, + EDF_OPTIMIZATION_PARAMETER, + }; + + typedef enum WORLD_DATA_FLAGS + { + WDF_HAS_SURFACE_PARAMETER = 0x0001, + WDF_HAS_SLEEPING_PARAMETER = 0x0002, + WDF_HAS_DAMPING_PARAMETER = 0x0004 + }; + + typedef enum WORLD_UPDATE_MODE + { + WUM_UPDATE_FROM_ATTRIBUTE = 0x0001 + }; + + typedef enum WORLD_UPDATE_FLAGS + { + WUF_WORLD_SETTINGS = 0x0001, + WUF_DAMPING_PARAMETER = 0x0002, + WUF_SLEEPING_PARAMETER = 0x0004, + WUF_SURFACE_SETTINGS = 0x0008, + WUF_ALL_PARAMETERS = 0x0010, + }; + + typedef enum BODY_UPDATE_FLAGS + { + BUF_PHY_PARAMETER = 0x0001, + BUF_DAMPING_PARAMETER = 0x0002, + BUF_SLEEPING_PARAMETER = 0x0004, + BUF_JOINT_PARAMETERS = 0x0008, + BUF_SURFACE_PARAMETERS = 0x0010, + BUF_ALL_PARAMETERS = 0x0020, + BUF_GEOMETRY = 0x0040, + BUF_PIVOT = 0x0080, + BUF_MASS = 0x0100, + BUF_ALL = 0x0200 + }; + + /** \addtogroup Joints + @{ + */ + //! Identifies each type of joint. + //! This enum is registered as a custom enumeration for the schematic interface as #pJointType.
+ typedef enum JType + { + JT_Any =-1,/*! + //! -during body registration.
+ //! -through invoking of #pRigidBody::addSubShape().This needs to have BF_SubShape enabled then!.
+ //! -as member of #pObjectDescr.

+ //! This enum is registered as a custom flags for the schematic : #pBFlags.
+ typedef enum BodyFlags{ + BF_Moving=1,/*!< Makes the body movable. this can not be altered after creation */ + BF_Gravity=2,/*!< Enables gravity. See #pRigidBody::enableGravity() or \ref PBSetPar */ + BF_Collision=4,/*!< Enables collisions response. See #pRigidBody::enableCollision() or \ref PBSetPar */ + BF_Kinematic=8,/*!< Act as kinematic object. See #pRigidBody::setKinematic() or \ref PBSetPar */ + BF_SubShape=16,/*! + //! -during body registration.
+ //! -as member of #pObjectDescr.

+ //! This enum is registered as a custom flags for the schematic : #pBHullType.
+ typedef enum HullType { + HT_Sphere = 0, + /*! + */ + HT_Box = 1, + /*! + */ + HT_Capsule = 2, + /*! + Assuming bodies pivot is aligned to the world frame, the entities rotation is set to 0,0,0 (degree) temporary in order to determine the capsule parameters whereas :
+ capsule length = boxMeshSize.y - boxMeshSize.x and
+ capsule radius = boxMeshSize.x / 2
+
+ */ + HT_Plane = 3, + /*!
+ */ + HT_Mesh =4, + /*! + \note This mesh type will not create contact points with another trieangle meshs. Avoid this at any cost, otherwise Virtools will crash!
+
+ */ + HT_ConvexMesh =5, + /*!
+ \note This type will create contact points with all other types! +
+ */ + HT_Heightfield=6, + /*!
+ */ + HT_Wheel=7, + /*! + */ + HT_Cloth=8, + /*! + */ + HT_ConvexCylinder=9, + /*! + */ + HT_Unknown, + /*! + */ + }; + /** @} */ + + typedef enum E_LOG_ITEMS + { + E_LI_AGEIA, + E_LI_MANAGER, + E_VSL, + E_BB, + }; + + typedef enum E_PHYSIC_ERROR + { + E_PE_OK, + E_PE_AGEIA_ERROR, + E_PE_INVALID_PARAMETER, + E_PE_INVALID_OPERATION, + }; + + typedef enum E_MANAGER_FLAGS + { + E_MF_OK, + E_MF_PSDK_LOADED, + E_MF_PSDK_FAILED, + E_MF_DEFAULT_WORLD_CREATED, + E_MF_DEFAULT_CONFIG_LOADED, + E_MF_LOADING_DEFAULT_CONFIG_FAILED, + E_MF_FACTORY_CREATED, + }; + typedef enum E_MANAGER_INIT_FLAGS + { + E_MFI_LOAD_CONFIG, + E_MFI_CREATE_FACTORY, + E_MFI_CREATE_DEFAULT_WORLD, + E_MFI_USE_XML_WORLD_SETTINGS + }; + + + /** \addtogroup RigidBody + @{ + */ + //! This enum is registered as a custom flags for the schematic : #pBForceMode.
+ //! Enumeration to force related calls. + //*! Is used for force related calls. Registered as custom enumeration #pBForceMode. */ + enum ForceMode + { + FM_Force, /*!< parameter has unit of mass * distance/ time^2, i.e. a force*/ + FM_Impulse, /*!< parameter has unit of mass * distance /time */ + FM_VelocityChange, /*!< parameter has unit of distance / time, i.e. the effect is mass independent: a velocity change.*/ + FM_SmoothImpulse, /*!< same as FM_Impulse but the effect is applied over all sub steps. Use this for motion controllers that repeatedly apply an impulse.*/ + FM_SmoothVelocityChange, /*!< same as FM_VelocityChange but the effect is applied over all substeps. Use this for motion controllers that repeatedly apply an impulse.*/ + FM_Acceleration /*!< parameter has unit of distance/ time^2, i.e. an acceleration. It gets treated just like a force except the mass is not divided out before integration.*/ + }; + + //! This enum is registered as custom hidden enumeration for pCCDSettings- + enum CCDFlags + { + CCD_Shared, /*!< Is reusing a ccd skeleton*/ + }; + + /** @} */ + + /** \addtogroup RigidBody + @{ + */ + //! Flag that determines the combine mode. When two bodies come in contact with each other, + //! they each have materials with various coefficients, but we only need a single set of coefficients for the pair. + //! Physics doesn't have any inherent combinations because the coefficients are determined empirically on a case by case basis. However, simulating this with a pairwise lookup table is often impractical. For this reason the following combine + //! behaviors are available: CM_Average CM_Min CM_Multiply CM_Max + //! The effective combine mode for the pair is max(material0.combineMode, material1.combineMode). + enum CombineMode + { + CM_Average,/*! + \note The appropriate target positions/orientations should be set. + */ + D6DT_Velocity = 1 << 1, + /*! + \note The appropriate target velocities should beset.*/ + }; + /** @} */ + + + /** \addtogroup D6 + @{ + */ + //! Enumeration is used to specify a particular degree of freedom.Registered as custom enumeration #pJD6Axis. + typedef enum D6MotionAxis + { + + D6MA_Twist,/*! + - building block \ref PVWSet + - #pWheel::setShapeFlags + + */ + /** + Flags to describe the wheels control facility. This can be done at any time with :
+ - building block \ref PVWSet + - #pWheel::setWheelFlags + */ + typedef enum VehicleFlags + { + VF_UseAdvance = (1 << 0), + }; + typedef enum WheelShapeFlags + { + /** + \brief Determines whether the suspension axis or the ground contact normal is used for the suspension constraint. + */ + WSF_WheelAxisContactNormal = 1 << 0, + + /** + \brief If set, the lateral slip velocity is used as the input to the tire function, rather than the slip angle. + + */ + WSF_InputLatSlipVelocity = 1 << 1, + + /** + \brief If set, the longitudinal slip velocity is used as the input to the tire function, rather than the slip ratio. + */ + WSF_InputLongSlipVelocity = 1 << 2, + + /** + \brief If set, does not factor out the suspension travel and wheel radius from the spring force computation. This is the legacy behavior from the raycast capsule approach. + */ + WSF_UnscaledSpringBehavior = 1 << 3, + + /** + \brief If set, the axle speed is not computed by the simulation but is rather expected to be provided by the user every simulation step via NxWheelShape::setAxleSpeed(). + */ + WSF_AxleSpeedOverride = 1 << 4, + /** + \brief If set, the wheels shape will emulate the legacy raycast capsule based wheel. + See #pVWheelFunction + */ + WSF_EmulateLegacyWheel = 1 << 5, + + /** + \brief If set, the shape will clamp the force in the friction constraints. + See #pVWheelFunction + */ + WSF_ClampedFriction = 1 << 6, + }; + + /** + Flags to describe the wheels control facility. This can be done at any time with :
+ - building block \ref PVWSet + - #pWheel::setWheelFlags + */ + typedef enum WheelFlags + { + + /** + \brief If set, the wheels shape will emulate the legacy raycast capsule based wheel. + See #pVWheelFunction + */ + WF_SteerableInput = (1 << 0), + WF_SteerableAuto = (1 << 1), + WF_AffectedByHandbrake = (1 << 2), + WF_Accelerated = (1 << 3), + WF_VehicleControlled = (1 << 4), + WF_AffectedByDifferential = (1 << 5), + WF_IgnoreTireFunction = (1 << 6), + + WF_AllWheelFlags = WF_SteerableInput + | WF_SteerableAuto + | WF_AffectedByHandbrake + | WF_Accelerated + | WF_VehicleControlled + | WF_AffectedByDifferential, + + }; + + typedef enum E_VEHICLE_STATE_FLAGS + { + E_VSF_HAS_GEARS=(1<<0), + E_VSF_HAS_MOTOR=(1<<1), + E_VSF_HAS_GROUND=(1<<2), + E_VSF_IS_BRAKING=(1<<3), + E_VSF_IS_BREAKPEDAL=(1<<4), + E_VSF_BREAKPEDAL_CHANGED=(1<<5), + E_VSF_ACC_PEDAL=(1<<6), + E_VSF_RELEASING_BRAKE_PEDAL=(1<<7), + }; + + + /** @} */ + + typedef enum pParticleRenderType + { + + PRT_Point, + PRT_Sprite, + + }; + + typedef enum E_OBJECT_CREATION_FLAGS + { + + E_OCF_ROTATION, + E_OFC_POSITION, + E_OFC_DIMENSION, + E_OFC_PERISITENT, + + }; + + typedef enum xManagerCallMask + { + XCM_PreProcess = 1 << 0 , + XCM_PostProcess = 1 << 0 + }; + + + +#endif // __VTINTERFACEENUMERATION_H__ \ No newline at end of file diff --git a/usr/Include/Core/Common/vtLogTools.h b/usr/Include/Core/Common/vtLogTools.h new file mode 100644 index 0000000..997fcf6 --- /dev/null +++ b/usr/Include/Core/Common/vtLogTools.h @@ -0,0 +1,49 @@ +#ifndef _VTLOG_TOOLS_H_ +#define _VTLOG_TOOLS_H_ + +#include "xLogger.h" + +////////////////////////////////////////////////////////////////////////// +// +// +// We different output channels for logging,debugging or assertions : +// + console +// + log file +// + std::err + +class CKContext; +class CKGUID; + +namespace vtTools +{ + + class BehaviorInfoTools + { + public : + static const char*getBuildingBlockName(CKContext *ctx,CKGUID* guid); + }; + +} + + +#define XL_BB_NAME beh->GetPrototype()->GetName() +#define XL_BB_OWNER_SCRIPT beh->GetOwnerScript()->GetName() +#define XL_BB_OWNER_OBJECT beh->GetOwner() ? beh->GetOwner()->GetName() : "none" +#define XL_BB_SIGNATURE ("\n\tScript : %s\n\tBuildingBlock : %s \n\tObject :%s Error :") + + +#define XLOG_FMT(msg,extro) msg##extro +#define XLOG_MERGE(var, fmt) (#var##fmt ) +#define XLOG_MERGE2(var,fmt) (var##fmt) + +#define XLOG_BB_INFO xLogger::xLogExtro(0,XL_BB_SIGNATURE,XL_BB_OWNER_SCRIPT,XL_BB_NAME,XL_BB_OWNER_OBJECT) + +#define VTERROR_STRING(F) sErrorStrings[F] +#define bbError(F) XLOG_BB_INFO; \ + Error(beh,F,BB_OP_ERROR,VTERROR_STRING(F),TRUE,BB_O_ERROR,TRUE) +#define bbNoError(F) Error(beh,F,BB_OP_ERROR,VTERROR_STRING(F),FALSE,BB_O_ERROR,FALSE) + +#define bbErrorMesg(F) xLogger::xLog(ELOGERROR,E_BB,F); \ + XLOG_BB_INFO; + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtModuleConstants.h b/usr/Include/Core/Common/vtModuleConstants.h new file mode 100644 index 0000000..46a7c7c --- /dev/null +++ b/usr/Include/Core/Common/vtModuleConstants.h @@ -0,0 +1,77 @@ +#ifndef __vtModuleConstants_h__ +#define __vtModuleConstants_h__ + + +//---------------------------------------------------------------- +// +// Include of system headers +// + +#include // float max + +//################################################################ +// +// Component specific names, prefixes,etc.... +// + +//---------------------------------------------------------------- +// +//! \brief Global API prefix +// +#define VTCX_API_PREFIX "vt" + +//---------------------------------------------------------------- +// +//! \brief Module name, merged with module suffix "vt" with see #VTCX_API_PREFIX +// +#define VTCMODULE_NAME VTCX_API_PREFIX("Physic") + + +//---------------------------------------------------------------- +// +//! \brief Modules attribute category prefix , using module name above +// +#define VTCMODULE_ATTRIBUTE_CATAEGORY VTCMODULE_NAME + +//---------------------------------------------------------------- +// +//! \brief Error enumerations +// +#include "vtModuleErrorCodes.h" + +//---------------------------------------------------------------- +// +//! \brief Error strings +// +#include "vtModuleErrorStrings.h" + +//---------------------------------------------------------------- +// +//! \brief Guids of the plug-in it self +// +#include "vtModuleGuids.h" + + + +//---------------------------------------------------------------- +// +//! \brief Math oriented values +// + +#define pSLEEP_INTERVAL (20.0f*0.02f) +#define pFLOAT_MAX FLT_MAX + + +//---------------------------------------------------------------- +// +//! \brief Constants for building blocks +// +#ifndef VTCX_AUTHOR + #define VTCX_AUTHOR "Guenter Baumgart" +#endif + +#ifndef VTCX_AUTHOR_GUID + #define VTCX_AUTHOR_GUID CKGUID(0x79ba75dd,0x41d77c63) +#endif + +#endif // vtModuleConstants_h__ \ No newline at end of file diff --git a/usr/Include/Core/Common/vtModuleErrorCodes.h b/usr/Include/Core/Common/vtModuleErrorCodes.h new file mode 100644 index 0000000..f60d01a --- /dev/null +++ b/usr/Include/Core/Common/vtModuleErrorCodes.h @@ -0,0 +1,26 @@ +#ifndef __VTMODULE_ERROR_CODES_H__ +#define __VTMODULE_ERROR_CODES_H__ + + +/*! + * \brief + * Error codes to identifier common errors in the SDK with automatic + * string conversion for building blocks +*/ +typedef enum E_BB_ERRORS +{ + E_PE_NONE, + E_PE_INTERN, + E_PE_PAR, + E_PE_REF, + E_PE_XML, + E_PE_FILE, + E_PE_NoBody, + E_PE_NoVeh, + E_PE_NoWheel, + E_PE_NoJoint, + E_PE_NoCloth, + E_PE_NoSDK, +}; + +#endif // __VTMODULEERRORCODES_H__ \ No newline at end of file diff --git a/usr/Include/Core/Common/vtModuleErrorStrings.h b/usr/Include/Core/Common/vtModuleErrorStrings.h new file mode 100644 index 0000000..3b381e2 --- /dev/null +++ b/usr/Include/Core/Common/vtModuleErrorStrings.h @@ -0,0 +1,50 @@ +#ifndef __VT_MODULE_ERROR_STRINGS_H__ +#define __VT_MODULE_ERROR_STRINGS_H__ + +/*! + * \brief + * String to describe the error's source + */ +static char* sLogItems[]= +{ + "AGEIA", + "MANAGER", + "VSL", +}; + +/*! + * \brief + * String to describe generic return codes + */ +static char* sErrorStrings[]= +{ + "OK", + "Ageia error", + "Invalid parameter", + "Invalid operation", +}; + +/*! + * \brief + * String to describe component specific return codes + * + */ +static char* sBBErrorStrings[]= +{ + "OK", + "\t Intern :", + "\t Parameter invalid :", + "\t Reference object invalid:", + "\t XML error:", + "\t Invalid File:", + "\t Reference object is not physicalized:", + "\t Reference object doesn't contains a vehicle controller:", + "\t Reference object is not a wheel:", + "\t Reference object is not a joint:", + "\t Reference object is not a cloth:", + "\t Couldn't initialize PhysX :", + +}; + + +#endif // __VTMODULEERRORSTRINGS_H__ \ No newline at end of file diff --git a/usr/Include/Core/Common/vtModuleGuids.h b/usr/Include/Core/Common/vtModuleGuids.h new file mode 100644 index 0000000..bed92d4 --- /dev/null +++ b/usr/Include/Core/Common/vtModuleGuids.h @@ -0,0 +1,25 @@ +#ifndef __VTMODULES_GUIDS_H__ + #define __VTMODULES_GUIDS_H__ + +#include "vtBaseMacros.h" + +//---------------------------------------------------------------- +// +//! \brief The guid of the modules manager. Used +// +// +//! \brief Manager Guid, used in plug-in registration, building blocks and many core components +// +#define GUID_MODULE_MANAGER CKGUID(0x1c0f04e8,0x442e20e5) + +//---------------------------------------------------------------- +// +//! \brief :: The guid of the modules building blocks +// If defined "WebPack", its using the guid of the built-in camera plug in. +#ifdef WebPack + #define GUID_MODULE_BUILDING_BLOCKS CKGUID(0x12d94eba,0x47057415) +#else + #define GUID_MODULE_BUILDING_BLOCKS CKGUID(0x36834d9e,0x63664944) +#endif + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtParameterGuids.h b/usr/Include/Core/Common/vtParameterGuids.h new file mode 100644 index 0000000..d67c8b2 --- /dev/null +++ b/usr/Include/Core/Common/vtParameterGuids.h @@ -0,0 +1,272 @@ +/******************************************************************** + created: 2009/02/14 + created: 14:2:2009 15:50 + filename: SDK\Include\Core\vtParameterGuids.h + file path: SDK\Include\Core + file base: vtParameterGuids + file ext: h + author: Günter Baumgart + + purpose: Unique identifiers for the entire component +*********************************************************************/ +#ifndef __VT_PARAMETER_GUIDS_H__ + #define __VT_PARAMETER_GUIDS_H__ + + +//################################################################ +// +// Common Parameter, used by joints, bodies, -or world objects +// +#define VTS_AXIS_REFERENCED_LENGTH CKGUID(0x19d6054d,0x4c2a2c99) +#define VTE_PHYSIC_DOMINANCE_GROUP CKGUID(0x2ae53cee,0x57ca74d0) + +#define VTS_SLEEPING_SETTINGS CKGUID(0x28d13431,0x24186938) + +#define VTF_TRIGGER CKGUID(0xe9c412e,0x68025071) +#define VTE_FILTER_OPS CKGUID(0x58340fe5,0x67892b1f) +#define VTE_FILTER_MASK CKGUID(0x30ff289e,0x7e57707c) +#define VTS_FILTER_GROUPS CKGUID(0x14443c3a,0x7c886162) +#define VTF_SHAPES_TYPE CKGUID(0x2ff80c77,0x7ab71a8) +#define VTF_RAY_HINTS CKGUID(0x7f5552d,0x70632e9a) +#define VTS_RAYCAST CKGUID(0x3842035f,0x1bc81c7f) +#define VTF_COLLISIONS_EVENT_MASK CKGUID(0x1beb409d,0x5028494f) + +#define VTF_WHEEL_CONTACT_MODIFY_FLAGS CKGUID(0x40495482,0x4ab3283e) + + + +//################################################################ +// +// Shape overrides +// +#define VTS_CAPSULE_SETTINGS CKGUID(0x9a441c3,0x1e1d25ce) +#define VTS_CAPSULE_SETTINGS_EX CKGUID(0x16f102dc,0x7cb97e54) +// Wheel type using a convex cylinder, a capsule and a joint spring +#define VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR CKGUID(0x65e30713,0x55ca1048) + + +//################################################################ +// +// World Related +// +#define VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS CKGUID(0x636c3e44,0x658213ea) + #define VTS_PHYSIC_DOMINANCE_ITEM CKGUID(0x7bee51cc,0xb676809) + #define VTS_PHYSIC_DOMINANCE_CONSTRAINT CKGUID(0x6f44420b,0x14b7435d) + +#define VTS_WORLD_SETTINGS CKGUID(0x5a0b56eb,0x50fc04d2) +#define VTS_PHYSIC_WORLD_PARAMETER CKGUID(0x27f223a1,0x365777f0) + +//################################################################ +// +// Rigid Body Related +// +#define VTS_PHYSIC_PARAMETER CKGUID(0x90e519f,0x7ec5345d) +#define VTS_PHYSIC_ACTOR CKGUID(0x381d7e69,0x456458fb) + +#define VTF_PHYSIC_SUBSHAPE_INHERITANCE_FLAGS CKGUID(0x55c60b24,0x4ddc754e) + +#define VTS_PHYSIC_TRANSFORMATIONS_LIMIT_PARAMETER CKGUID(0x413f3fb4,0x4f545c24) + +#define VTF_PHYSIC_BODY_COMMON_SETTINGS CKGUID(0x44bc4e8d,0x16cb3288) +#define VTE_BODY_FORCE_MODE CKGUID(0x28c8214c,0x1ab04db8) +#define VTF_PHYSIC_BODY_UPDATE_FLAGS CKGUID(0x7f824fb3,0x5496b62) +#define VTF_PHYSIC_WORLD_UPDATE_FLAGS CKGUID(0x7f824fb3,0x5496b62) +#define VTF_BODY_FLAGS CKGUID(0x2c173381,0x10f66ab3) +#define VTF_BODY_TRANS_FLAGS CKGUID(0x41242761,0x72e70c27) +#define VTE_COLLIDER_TYPE CKGUID(0x1c415d41,0x5c534d7a) +#define VTF_CONVEX_FLAGS CKGUID(0x2d9d5c3e,0x468c0266) +#define VTF_CONTACT_MODIFY_FLAGS CKGUID(0x7d5c0e7c,0x144d2596) + +//---------------------------------------------------------------- +// +// XML Setup +// + +#define VTS_PHYSIC_ACTOR_XML_SETTINGS_INTERN CKGUID(0x35977af4,0x5b430c0c) +#define VTS_PHYSIC_ACTOR_XML_SETTINGS_EXTERN CKGUID(0x57aa4cab,0x7e173b06) +#define VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS CKGUID(0x2a2c3ee5,0x33cc3c2f) +#define VTS_PHYSIC_ACTOR_XML_SETUP CKGUID(0x5e916f6,0x6e7a44ed) +#define VTF_PHYSIC_ACTOR_COPY_FLAGS CKGUID(0x7013615f,0x9aa642e) + +//---------------------------------------------------------------- +// +// Geometry +// +#define VTS_PHYSIC_PIVOT_OFFSET CKGUID(0x19e432af,0x571f5bf7) + +//---------------------------------------------------------------- +// +// Collision +// +#define VTF_PHYSIC_COLLISION_MASK CKGUID(0x7bf86391,0x1ac73b1) + +#define VTS_PHYSIC_CCD_SETTINGS CKGUID(0x37537e0c,0x55b668d6) + #define VTF_PHYSIC_CCD_FLAGS CKGUID(0x25ee18c2,0x3419342d) + +#define VTS_PHYSIC_COLLISIONS_SETTINGS CKGUID(0x8027e35,0x7c940e70) + #define VTE_PHYSIC_BODY_COLL_GROUP CKGUID(0xc1e1e0a,0x36fd0de4) + +#define VTS_PHYSIC_COLLISIONS_SETUP CKGUID(0x64043794,0x4d9f454b) + + +//---------------------------------------------------------------- +// +// Mass Configuration +// +#define VTS_PHYSIC_MASS_SETUP CKGUID(0x36855c80,0x81a0a4e) + #define VTE_PHYSIC_MASS_TYPE CKGUID(0x71921e8a,0x8e22f63) + +//---------------------------------------------------------------- +// +// Optimization +// +#define VTS_PHYSIC_SLEEP_SETTINGS CKGUID(0x41450454,0x3b4a65c2) +#define VTS_PHYSIC_DAMPING_PARAMETER CKGUID(0x17ad0411,0x3ccd0dd7) +#define VTS_PHYSIC_ACTOR_OPTIMIZATION CKGUID(0x2fca03db,0x25644fd4) + +//---------------------------------------------------------------- +// +// Material +// +#define VTS_MATERIAL CKGUID(0x4785249d,0x57af4457) +#define VTF_MATERIAL_FLAGS CKGUID(0x14ce161f,0x27cc5b83) +#define VTE_MATERIAL_COMBINE_MODE CKGUID(0x6dbf7c19,0x3dfb0e12) +#define VTE_XML_MATERIAL_TYPE CKGUID(0x57430496,0x29193343) + + + + + + +//################################################################ +// +// Joints : +// + +//---------------------------------------------------------------- +// +// Common shared types +// + + +#define VTE_JOINT_TYPE CKGUID(0x5d9c0413,0xcb96c02) +#define VTS_PHYSIC_JAMOTOR_AXIS_TYPE CKGUID(0x21352808,0x1e932c41) + +#define VTE_JOINT_MOTION_MODE CKGUID(0x6ec04e81,0xfd537e) +#define VTS_JOINT_DRIVE CKGUID(0x563c20ca,0x581e0e4b) +#define VTS_JOINT_SPRING CKGUID(0x495d0920,0x189674ba) +#define VTS_JLIMIT CKGUID(0x8d61654,0x1fd01503) +#define VTS_JOINT_SLIMIT CKGUID(0xd997313,0x28523dc0) +#define VTS_JOINT_MOTOR CKGUID(0x50ab7cc2,0x37ce0071) + +#define VTS_JOINT_D6 CKGUID(0x215a2fa1,0x7cc02701) +#define VTF_JOINT_D6_AXIS_MASK CKGUID(0x461c1af3,0x4b194a84) +#define VTS_JOINT_D6_AXIS_ITEM CKGUID(0x37d01b38,0x10a03ef) +#define VTE_JOINT_MOTION_MODE_AXIS CKGUID(0x5adb450c,0x5798057d) +#define VTE_JOINT_LIMIT_AXIS CKGUID(0x16d654a4,0x276a048f) +#define VTE_JOINT_DRIVE_AXIS CKGUID(0x1c73456a,0x7d846d2a) +#define VTE_JOINT_PROJECTION_MODE CKGUID(0x2cce3d0b,0x60603c02) +#define VTE_JOINT_TYPE CKGUID(0x16f21041,0x7a6479f3) + +//---------------------------------------------------------------- +// +// Complete Joint Setups +// + +#define VTS_JOINT_FIXED CKGUID(0x3a5163bf,0x3c315528) +#define VTS_JOINT_DISTANCE CKGUID(0x1edf6510,0xdea68b2) +#define VTS_JOINT_BALL CKGUID(0x20271cdc,0x645c4212) +#define VTS_JOINT_REVOLUTE CKGUID(0x7d45030c,0x4f6216ef) +#define VTS_JOINT_PRISMATIC CKGUID(0x37fd735c,0x6b83447d) +#define VTS_JOINT_CYLINDRICAL CKGUID(0x45e07719,0xba2297) + +#define VTS_JOINT_POINT_IN_PLANE CKGUID(0xed23f6,0x2ba449a3) +#define VTS_JOINT_POINT_ON_LINE CKGUID(0x4429006a,0x34345b66) + +#define VTS_JOINT_D6 CKGUID(0x52467f8a,0x3adc012b) +#define VTS_JOINT_D6_DRIVES CKGUID(0x46067fc4,0x56cf693e) + +#define VTS_JOINT_BREAKABLE CKGUID(0xe3d7a63,0x2cc61e4a) +#define VTS_JOINT_D6 CKGUID(0x11bd2119,0x3843102b) + +#define VTS_PHYSIC_JBALL_PARAMETER CKGUID(0x2c47770d,0x1b7173ad) +#define VTS_PHYSIC_JFIXED_PARAMETER CKGUID(0x780650ae,0x7e6406c5) +#define VTS_PHYSIC_JHINGE_PARAMETER CKGUID(0x5a805563,0x292021ce) +#define VTS_PHYSIC_JHINGE2_PARAMETER CKGUID(0x281717e5,0x353b61f2) +#define VTS_PHYSIC_JUNIVERSAL_PARAMETER CKGUID(0x7a283845,0x53144e6a) +#define VTS_PHYSIC_JSLIDER_PARAMETER CKGUID(0x67837673,0x20c04330) +#define VTS_PHYSIC_JMOTOR_PARAMETER CKGUID(0x677e7eba,0x6505310c) +#define VTS_PHYSIC_JLIMIT_PARAMETER CKGUID(0x17e57c53,0x43585c91) +#define VTE_PHYSIC_JDRIVE_TYPE CKGUID(0x75a51b10,0xe00025c) + +//---------------------------------------------------------------- +// +// Joint Misc Structures +// + +#define VTS_PHYSIC_JLIMIT_PLANE CKGUID(0x5abe5f0b,0x7ca6657e) + +//################################################################ +// +// Wheel Parameters +// +#define VTF_VSTATE_FLAGS CKGUID(0x49ce782d,0x7566828) +#define VTF_VFLAGS CKGUID(0x5cf964cf,0xd382f37) + + +#define VTF_VWSHAPE_FLAGS CKGUID(0x7da158eb,0x16e921a1) +#define VTF_VWTIRE_SETTINGS CKGUID(0x2690c24,0xde55e2b) + +#define VTE_BRAKE_XML_LINK CKGUID(0x77806807,0x4eac2b27) +#define VTE_BRAKE_LEVEL CKGUID(0x161f2b7d,0x2f657a2a) +#define VTF_BRAKE_FLAGS CKGUID(0x46535a8f,0x11815172) +#define VTS_BRAKE_TABLE CKGUID(0x59052709,0xa555846) +#define VTF_WHEEL_CONEX_SHAPE CKGUID(0x3f913a00,0x372f4a50) +#define VTS_WHEEL_CONTACT CKGUID(0x33f24aa8,0x34a57460) + +#define VTS_PHYSIC_WHEEL_DESCR CKGUID(0x5dcd09ae,0x73f72b97) +#define VTS_PHYSIC_WHEEL_FLAGS CKGUID(0x72b70c7d,0x3b60239d) + +//################################################################ +// +// Vehicle +// +#define VTS_PHYSIC_VEHICLE_DESCR CKGUID(0x54562468,0xd1a6de6) +#define VTS_PHYSIC_VEHICLE_MOTOR_DESCR CKGUID(0x19317402,0x2f4b65a1) +#define VTS_PHYSIC_GEAR_DESCR CKGUID(0x308e5c88,0x433871f9) +#define VTE_XML_VEHICLE_SETTINGS CKGUID(0x67ca76e9,0x452f7ceb) +#define VTE_XML_VMOTOR_SETTINGS CKGUID(0x6af977a6,0x11084c45) +#define VTF_VEHICLE_ENGINE_FLAGS CKGUID(0x23823b40,0x694f152c) +#define VTE_XML_VGEAR_SETTINGS CKGUID(0x9bc7981,0x4a6f7245) +#define VTE_XML_WHEEL_SETTINGS CKGUID(0x1ed80439,0x1f9825c4) +#define VTE_XML_TIRE_SETTINGS CKGUID(0x4cb47505,0x7b022333) +#define VTS_VMOTOR_ENTRY CKGUID(0x12dd3a77,0x5db358f8) +#define VTS_VMOTOR_TVALUES CKGUID(0x34af3aa2,0x23aa6422) +#define VTS_VGEAR_GRAPH_SETTINGS CKGUID(0x25016106,0x3a0024a0) +#define VTS_VGEARBOX_FLAGS CKGUID(0x47d632a5,0x50057698) +#define VTS_VGEAR_RATIO_ENTRY CKGUID(0x36b93b1c,0x79f804c2) +#define VTS_VGEAR_RATIOS CKGUID(0x5a0230db,0x441f5c18) +#define VTS_VGEAR_CURVE CKGUID(0x6352317b,0x41fe3769) +#define VTS_VGEAR_SETTINGS CKGUID(0x7dde30fb,0x701915ea) +#define VTE_VEHICLE_XML_LINK CKGUID(0x4c43611,0x736078b9) + +#define VTF_VEHICLE_PROCESS_OPTIONS CKGUID(0x24fa465f,0x1c2f5b88) + + +//################################################################ +// +// Cloth +// +#define VTE_CLOTH_FLAGS CKGUID(0x2c7d5bb6,0x6a9d7c41) +#define VTS_CLOTH_DESCR CKGUID(0x722a5c01,0x5c8d413d) +#define VTS_CLOTH_METAL_DESCR CKGUID(0x1ecb0821,0x709e7bdf) +#define VTE_CLOTH_ATTACH_FLAGS CKGUID(0x428b755b,0x36d60122) + +//################################################################ +// +// UNknow : +// +#define VTS_PHYSIC_HEIGHTFIELD_PARAMETERS CKGUID(0x37430de4,0x54d06445) + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtParameterSubItemIdentifiers_All.h b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_All.h new file mode 100644 index 0000000..f9ea737 --- /dev/null +++ b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_All.h @@ -0,0 +1,25 @@ +/******************************************************************** + created: 2009/02/16 + created: 16:2:2009 7:23 + filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\vtParameterAll.h + file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common + file base: vtParameterAll + file ext: h + author: Günter Baumgart + + purpose: +*********************************************************************/ +#ifndef __VT_PARAMETER_STRUCTS_H__ +#define __VT_PARAMETER_STRUCTS_H__ + + +//################################################################ +// +// Parameter Structures have been divided by type. +// +#include "vtParameterSubItemIdentifiers_Body.h" +#include "vtParameterSubItemIdentifiers_Joints.h" +#include "vtParameterSubItemIdentifiers_VehicleAndWheelStructs.h" +#include "vtParameterSubItemIdentifiers_World.h" + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtParameterSubItemIdentifiers_Body.h b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_Body.h new file mode 100644 index 0000000..4d718f7 --- /dev/null +++ b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_Body.h @@ -0,0 +1,336 @@ +#ifndef __VT_BODY_STRUCTS_H__ +#define __VT_BODY_STRUCTS_H__ + +////////////////////////////////////////////////////////////////////////// +// +// @todo : old custom structures, classical registered +// +typedef enum E_PHYSIC_PARAMETER_STRUCT +{ + E_PPS_HULLTYPE, + E_PPS_BODY_FLAGS, + E_PPS_DENSITY, + E_PPS_SKIN_WIDTH, + E_PPS_MASS_OFFSET, + E_PPS_SHAPE_OFFSET, + E_PPS_HIRARCHY, + E_PPS_WORLD, + E_PPS_NEW_DENSITY, + E_PPS_TOTAL_MASS, + E_PPS_COLL_GROUP +}; + +typedef enum E_MATERIAL_STRUCT +{ + E_MS_XML_TYPE, + E_MS_DFRICTION, + E_MS_SFRICTION, + E_MS_RESTITUTION, + E_MS_DFRICTIONV, + E_MS_SFRICTIONV, + E_MS_ANIS, + E_MS_FCMODE, + E_MS_RCMODE, + E_MS_FLAGS, +}; + +typedef enum E_RAY_CAST_STRUCT +{ + E_RC_WORLD, + E_RC_ORI, + E_RC_ORI_REF, + E_RC_DIR, + E_RC_DIR_REF, + E_RC_LENGTH, + E_RC_GROUPS, + E_RC_GROUPS_MASK, + E_RC_SHAPES_TYPES +}; + +typedef enum E_CLOTH_STRUCT +{ + E_CS_THICKNESS, + E_CS_DENSITY, + E_CS_BENDING_STIFFNESS, + E_CS_STRETCHING_STIFFNESS, + E_CS_DAMPING_COEFFICIENT, + E_CS_FRICTION, + E_CS_PRESSURE, + E_CS_TEAR_FACTOR, + E_CS_COLLISIONRESPONSE_COEFFICIENT, + E_CS_ATTACHMENTRESPONSE_COEFFICIENT, + E_CS_ATTACHMENT_TEAR_FACTOR, + E_CS_TO_FLUID_RESPONSE_COEFFICIENT, + E_CS_FROM_FLUIDRESPONSE_COEFFICIENT, + E_CS_MIN_ADHERE_VELOCITY, + E_CS_SOLVER_ITERATIONS, + E_CS_EXTERN_ALACCELERATION, + E_CS_WIND_ACCELERATION, + E_CS_WAKE_UP_COUNTER, + E_CS_SLEEP_LINEAR_VELOCITY, + E_CS_COLLISIONG_ROUP, + E_CS_VALID_BOUNDS, + E_CS_RELATIVE_GRID_SPACING, + E_CS_FLAGS, + E_CS_TEAR_VERTEX_COLOR, + E_CS_WORLD_REFERENCE, + E_CS_ATTACHMENT_FLAGS, +}; + +typedef enum E_WCD_STRUCT +{ + E_WCD_CPOINT, + E_WCD_CNORMAL, + E_WCD_LONG_DIR, + E_WCD_LAT_DIR, + E_WCD_CONTACT_FORCE, + E_WCD_LONG_SLIP, + E_WCD_LAT_SLIP, + E_WCD_LONG_IMPULSE, + E_WCD_LAT_IMPULSE, + E_WCD_OTHER_MATERIAL_INDEX, + E_WCD_C_POS, + E_WCD_CONTACT_ENTITY, +}; + +typedef enum E_VBT_STRUCT +{ + E_VBT_0, + E_VBT_1, + E_VBT_2, + E_VBT_3, + E_VBT_4, + E_VBT_5, + E_VBT_6, + E_VBT_7, + E_VBT_8, + E_VBT_9 +}; + +typedef enum WHEEL_DESCR_STRUCT +{ + E_WD_XML, + E_WD_SUSPENSION, + E_WD_SPRING_RES, + E_WD_DAMP, + E_WD_SPRING_BIAS, + E_WD_MAX_BFORCE, + E_WD_FSIDE, + E_WD_FFRONT, + E_WD_INVERSE_WHEEL_MASS, + E_WD_FLAGS, + E_WD_SFLAGS, + E_WD_LAT_FUNC, + E_WD_LONG_FUNC, +}; + +typedef enum E_CAPSULE_STRUCT +{ + E_CS_LENGTH_AXIS, + E_CS_RADIUS_AXIS, + E_CS_LENGTH, + E_CS_RADIUS, +}; + + +////////////////////////////////////////////////////////////////////////// +// +// New Structs +// +/** +\brief Data mask to determine which parts of a rigid bodies description have to + be evolved. +*/ +enum pObjectDescrMask +{ + /** + \brief Description has XML settings + */ + OD_XML = (1 << 0), + /** + \brief Description has pivot override + */ + OD_Pivot = (1 << 1), + /** + \brief Description has mass override + */ + OD_Mass= (1 << 2), + /** + \brief Description has collisions settings + */ + OD_Collision = (1 << 3), + /** + \brief Description has CCD settings + */ + OD_CCD = (1 << 4), + /** + \brief Description has material settings + */ + OD_Material = (1 << 5), + /** + \brief Description has optimization settings + */ + OD_Optimization = (1 << 6), + /** + \brief Description has capsule override + */ + OD_Capsule = (1 << 7), + /** + \brief Description has convex cylinder override + */ + OD_ConvexCylinder = (1 << 8), + /** + \brief Description has wheel settings + */ + OD_Wheel = (1 << 9) +}; + +enum PB_COPY_FLAGS +{ + PB_CF_PHYSICS=1, + PB_CF_SHARE_MESHES=(1<<1), + PB_CF_PIVOT_SETTINGS=(1<<2), + PB_CF_MASS_SETTINGS=(1<<3), + PB_CF_COLLISION=(1<<4), + PB_CF_CCD=(1<<5), + PB_CF_MATERIAL=(1<<6), + PB_CF_OPTIMIZATION=(1<<7), + PB_CF_CAPSULE=(1<<8), + PB_CF_CONVEX_CYLINDER=(1<<9), + PB_CF_FORCE=(1<<10), + PB_CF_VELOCITIES=(1<<11), + PB_CF_JOINTS=(1<<12), + PB_CF_LIMIT_PLANES=(1<<13), + PB_CF_SWAP_JOINTS_REFERENCES=(1<<14), + PB_CF_OVRRIDE_BODY_FLAGS=(1<<15), + PB_CF_COPY_IC=(1<<16), + PB_CF_RESTORE_IC=(1<<17), + +}; + +enum PS_B_COLLISON +{ + PS_BC_GROUP, + PS_BC_GROUPSMASK, + PS_BC_SKINWITDH, + PS_BC_CCD_SETUP +}; + +enum PS_B_CCD +{ + PS_B_CCD_MOTION_THRESHOLD, + PS_B_CCD_FLAGS, + PS_B_CCD_SCALE, + PS_B_CCD_MESH_REFERENCE, +}; + +enum PS_B_COLLISION_SETUP +{ + PS_BCS_COLLISION_COMMON, + PS_BCS_CCD, +}; + + +enum PS_B_DAMPING +{ + PS_BD_LINEAR, + PS_BD_ANGULAR, +}; + + +enum PS_B_SLEEPING +{ + PS_BS_LINEAR_SLEEP, + PS_BS_ANGULAR_SLEEP, + PS_BS_THRESHOLD, +}; + +enum PS_B_OPTIMISATION +{ + PS_BO_LOCKS, + PS_BO_DAMPING, + PS_BO_SLEEPING, + PS_BO_SOLVER_ITERATIONS, + PS_BO_DOMINANCE_GROUP, + PS_BO_COMPARTMENT_ID, + +}; +enum PS_B_PIVOT +{ + PS_BP_LINEAR, + PS_BP_ANGULAR, + PS_BP_REFERENCE, +}; + +enum PS_B_MASS +{ + PS_BM_DENSITY, + PS_BM_TOTAL_MASS, + PS_BM_PIVOT_POS, + PS_BM_PIVOT_ROTATION, + PS_BM_PIVOT_REFERENCE, +}; + +enum PS_BODY_FULL +{ + PS_BODY_XML, + PS_BODY_HULL_TYPE, + PS_BODY_FLAGS, + +}; + +enum PS_BODY_XML_SETUP +{ + PS_INTERN_LINK, + PS_EXTERN_LINK, + PS_XML_MPORT_FLAGS, +}; + +enum PS_BODY_COMMON +{ + PS_BC_HULL_TYPE, + PS_BC_DENSITY, + PS_BC_FLAGS, +/* PS_BC_TFLAGS,*/ + PS_BC_WORLD +}; + +enum PS_BODY_SETUP +{ + PS_XML_SETUP, + PS_COMMON_SETTINGS, + /*PS_PIVOT, + PS_MASS,*/ + PS_COLLISION_SETTINGS, + +}; +enum PS_AXIS_REFERENCED_LENGTH +{ + PS_ARL_VALUE, + PS_ARL_REF_OBJECT, + PS_ARL_REF_OBJECT_AXIS, +}; + +enum PS_CAPSULE +{ + PS_BCAPSULE_RADIUS_REFERENCED_VALUE, + PS_PCAPSULE_HEIGHT_REFERENCED_VALUE, +}; +enum PS_CUSTOM_CONVEX_CYLINDER_DESCR +{ + PS_CC_APPROXIMATION, + PS_CC_RADIUS_REFERENCED_VALUE, + PS_CC_HEIGHT_REFERENCED_VALUE, + PS_CC_FORWARD_AXIS, + PS_CC_FORWARD_AXIS_REF, + PS_CC_DOWN_AXIS, + PS_CC_DOWN_AXIS_REF, + PS_CC_RIGHT_AXIS, + PS_CC_RIGHT_AXIS_REF, + PS_CC_BUILD_LOWER_HALF_ONLY, + PS_CC_EXTRA_SHAPE_FLAGS +}; + + + +#endif diff --git a/usr/Include/Core/Common/vtParameterSubItemIdentifiers_Joints.h b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_Joints.h new file mode 100644 index 0000000..9cc410e --- /dev/null +++ b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_Joints.h @@ -0,0 +1,182 @@ +/******************************************************************** + created: 2009/02/17 + created: 17:2:2009 8:14 + filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\include\core\Common\vtParameterSubItemIdentifiers_Joints.h + file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\include\core\Common + file base: vtParameterSubItemIdentifiers_Joints + file ext: h + author: Günter Baumgart + + purpose: Joint parameter items for custom structures. +*********************************************************************/ +#ifndef __VTPARAMETERSUBITEMIDENTIFIERS_JOINTS_H__ +#define __VTPARAMETERSUBITEMIDENTIFIERS_JOINTS_H__ + +enum PS_JPOINT_ON_LINE_MEMBERS +{ + PS_JPOL_BODY_B, + PS_JPOL_ANCHOR, + PS_JPOL_ANCHOR_REF, + + PS_JPOL_AXIS, + PS_JPOL_AXIS_REF, + PS_JPOL_COLLISION, + + PS_JPOL_MAX_FORCE, + PS_JPOL_MAX_TORQUE, +}; + +enum PS_JPOINT_IN_PLANE_MEMBERS +{ + PS_JPIP_BODY_B, + PS_JPIP_ANCHOR, + PS_JPIP_ANCHOR_REF, + + PS_JPIP_AXIS, + PS_JPIP_AXIS_REF, + PS_JPIP_COLLISION, + + PS_JPIP_MAX_FORCE, + PS_JPIP_MAX_TORQUE, +}; + +enum PS_JREVOLUTE +{ + + PS_JREVOLUTE_BODY_B, + PS_JREVOLUTE_ANCHOR, + PS_JREVOLUTE_ANCHOR_REF, + + PS_JREVOLUTE_AXIS, + PS_JREVOLUTE_AXIS_REF, + PS_JREVOLUTE_COLLISION, + + PS_JREVOLUTE_PROJ_MODE, + PS_JREVOLUTE_PROJ_DISTANCE, + PS_JREVOLUTE_PROJ_ANGLE, + + PS_JREVOLUTE_SPRING, + PS_JREVOLUTE_LIMIT_HIGH, + PS_JREVOLUTE_LIMIT_LOW, + PS_JREVOLUTE_MOTOR, + + PS_JREVOLUTE_MAX_FORCE, + PS_JREVOLUTE_MAX_TORQUE, + +}; +enum PS_JCYLINDRICAL_MEMBERS +{ + + PS_JCYLINDRICAL_BODY_B, + PS_JCYLINDRICAL_ANCHOR, + PS_JCYLINDRICAL_ANCHOR_REF, + + PS_JCYLINDRICAL_AXIS, + PS_JCYLINDRICAL_AXIS_REF, + PS_JCYLINDRICAL_COLLISION, + + PS_JCYLINDRICAL_MAX_FORCE, + PS_JCYLINDRICAL_MAX_TORQUE, + + +}; +enum PS_JPRISMATIC_MEMBERS +{ + PS_JPRISMATIC_BODY_B, + PS_JPRISMATIC_ANCHOR, + PS_JPRISMATIC_ANCHOR_REF, + + PS_JPRISMATIC_AXIS, + PS_JPRISMATIC_AXIS_REF, + PS_JPRISMATIC_COLLISION, + PS_JPRISMATIC_MAX_FORCE, + PS_JPRISMATIC_MAX_TORQUE, +}; +enum PS_JBALL_MEMBERS +{ + PS_JBALL_BODY_B, + PS_JBALL_ANCHOR, + PS_JBALL_ANCHOR_REF, + PS_JBALL_GLOBAL_AXIS, + PS_JBALL_GLOBAL_AXIS_REF, + PS_JBALL_LIMIT_SWING_AXIS, + PS_JBALL_PROJ_MODE, + PS_JBALL_PROJ_DISTANCE, + PS_JBALL_COLLISION, + PS_JBALL_SWING_LIMIT, + PS_JBALL_TWIST_HIGH, + PS_JBALL_TWIST_LOW, + PS_JBALL_SWING_SPRING, + PS_JBALL_TWIST_SPRING, + PS_JBALL_JOINT_SPRING, + + PS_JBALL_MAX_FORCE, + PS_JBALL_MAX_TORQUE, + + +}; + +enum PS_JFIXED_MEMBERS +{ + PS_JFIXED_BODY_B, + PS_JFIXED_MAX_FORCE, + PS_JFIXED_MAX_TORQUE, +}; +enum PS_JDISTANCE_MEMBERS +{ + PS_JDISTANCE_BODY_B, + PS_JDISTANCE_LOCAL_ANCHOR_A_POS, + PS_JDISTANCE_LOCAL_ANCHOR_A_REF, + + PS_JDISTANCE_LOCAL_ANCHOR_B_POS, + PS_JDISTANCE_LOCAL_ANCHOR_B_REF, + + PS_JDISTANCE_COLL, + PS_JDISTANCE_MIN_DISTANCE, + PS_JDISTANCE_MAX_DISTANCE, + PS_JDISTANCE_SPRING, + + PS_JDISTANCE_MAX_FORCE, + PS_JDISTANCE_MAX_TORQUE, +}; + +enum PS_JLIMIT_PLANE_MEMBERS +{ + PS_JLP_BODY_B_REF, + PS_JLP_JOINT_TYPE, + PS_JLP_RESTITUTION, + PS_JLP_IS_ON_BODY_B, + PS_JLP_LIMIT_POINT, + PS_JLP_LIMIT_POINT_REF, + PS_JLP_NORMAL, + PS_JLP_NORMAL_REF, + PS_JLP_PT_IN_PLANE, + PS_JLP_PT_IN_PLANE_REF, +}; + +enum PS_D6_AXIS_ITEM +{ + PS_D6_AXIS_ITEM_MODE, + PS_D6_AXIS_ITEM_LIMIT, +}; + +enum PS_D6 +{ + PS_JD6_BODY_B, + PS_JD6_ANCHOR, + PS_JD6_ANCHOR_REF, + + PS_JD6_AXIS, + PS_JD6_AXIS_REF, + + PS_JD6_AXIS_MASK, + + PS_JD6_X, + PS_JD6_Y, + PS_JD6_Z, + PS_JD6_TWIST_SWING1, + PS_JD6_TWIST_SWING2, + PS_JD6_TWIST_LOW, + PS_JD6_TWIST_HIGH, +}; +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtParameterSubItemIdentifiers_VehicleAndWheelStructs.h b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_VehicleAndWheelStructs.h new file mode 100644 index 0000000..a1af6be --- /dev/null +++ b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_VehicleAndWheelStructs.h @@ -0,0 +1,22 @@ +#ifndef __VEHICLE_AND_WHEEL_STRUCTS_H__ +#define __VEHICLE_AND_WHEEL_STRUCTS_H__ +/* +typedef enum PS_WHEELSHAPE +{ + E_WD_XML, + E_WD_SUSPENSION, + E_WD_SPRING_RES, + E_WD_DAMP, + E_WD_SPRING_BIAS, + E_WD_MAX_BFORCE, + E_WD_FSIDE, + E_WD_FFRONT, + E_WD_APPROX, + E_WD_FLAGS, + E_WD_SFLAGS, + E_WD_LAT_FUNC, + E_WD_LONG_FUNC, +}; +*/ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtParameterSubItemIdentifiers_World.h b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_World.h new file mode 100644 index 0000000..7c5e995 --- /dev/null +++ b/usr/Include/Core/Common/vtParameterSubItemIdentifiers_World.h @@ -0,0 +1,37 @@ +#ifndef __VT_WORLD_STRUCTS_H__ +#define __VT_WORLD_STRUCTS_H__ + + + +enum PS_W_DOMINANCE_CONSTRAINT +{ + PS_WDC_A, + PS_WDC_B, +}; + + +enum PS_W_DOIMINANCE +{ + + PS_WD_GROUP_A, + PS_WD_GROUP_B, + PS_WD_CONSTRAINT, +}; + + +enum PS_W_DOIMINANCE_SETUP +{ + + PS_WDS_ITEM1, + PS_WDS_ITEM2, + PS_WDS_ITEM3, + PS_WDS_ITEM4, + PS_WDS_ITEM5, + +}; + + + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtPhysXBase.h b/usr/Include/Core/Common/vtPhysXBase.h new file mode 100644 index 0000000..f6554a8 --- /dev/null +++ b/usr/Include/Core/Common/vtPhysXBase.h @@ -0,0 +1,119 @@ +/******************************************************************** + created: 2009/02/16 + created: 16:2:2009 11:07 + filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\vtPhysXBase.h + file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common + file base: vtPhysXBase + file ext: h + author: Günter Baumgart + + purpose: Minimal includes for the whole component. + + + Generic macros and constants, functions + + Virtools specific forward decalarations + + Generic base types such as std::vector + + Component specific forward decalarations + + Disabling Module specific Visual Studio compiler Warnings + + Prerequisites + + Virtools Base Types ( XString, CKGUID, HashTable ) + + Constants + + warning: The order of the includes must stay ! + + remarks: - This module is using the concept of forward declaration + - This header is the base for all other headers. + - Do not introduce any platform specific dependencies( ie: windows.h ) + +*********************************************************************/ + + + +#ifndef __VT_PHYSX_BASE_H__ +#define __VT_PHYSX_BASE_H__ + +//################################################################ +// +// Generic +// + +//---------------------------------------------------------------- +// +// Include of base types, not involving external dependencies to std,etc.. +// +#include + + +//---------------------------------------------------------------- +// +// Class to encapsulate a set of flags in a word, using shift operators +// +#include + + +//---------------------------------------------------------------- +// +// Macros for generic DLL exports +// +#include + +//---------------------------------------------------------------- +// +// Include of Virtools related macros +// +#include + + +//################################################################ +// +// Component specific constants,strings, error codes +// + +//---------------------------------------------------------------- +// +// + API Prefix +// + Error Codes +// + Error Strings +// +#include "vtModuleConstants.h" + +//---------------------------------------------------------------- +// +// Virtools Guids of the plug-in ( manager + building block only !!! ) +// +// GUIDS for custom enumerations, structures are included by the managers +// parameter_x.cpp explicitly ! +// +#include "vtModuleGuids.h" + +//---------------------------------------------------------------- +// +// Enumerations to identifier a custom structure's sub item +// +#include "vtParameterSubItemIdentifiers_All.h" + + +//---------------------------------------------------------------- +// +// Enumerations used by the SDK and the Virtools Interface ( Schematics, VSL) +// +#include "vtInterfaceEnumeration.h" + + +//################################################################ +// +// Compiler specific warnings +// +#include "vcWarnings.h" + + +//################################################################ +// +// Prerequisites +// +#include "Prerequisites_All.h" + + + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/vtStructHelper.h b/usr/Include/Core/Common/vtStructHelper.h new file mode 100644 index 0000000..1283a91 --- /dev/null +++ b/usr/Include/Core/Common/vtStructHelper.h @@ -0,0 +1,138 @@ +#ifndef __VT_STRUCT_HELPER_H__ +#define __VT_STRUCT_HELPER_H__ + + + + +namespace vtTools +{ + + namespace ParameterTools + { + + struct StructurMember + { + CKGUID guid; XString name; XString defaultValue; + CKObject *par; + StructurMember() + { + guid = CKGUID(0,0); name = ""; defaultValue = ""; + } + + StructurMember(CKGUID _guid,XString _name,XString _defaultValue) : + guid(_guid) , name(_name) , defaultValue(_defaultValue) + { + } + + }; + + class CustomStructure + { + + public : + CustomStructure(){} + CustomStructure(XString name,CKGUID guid,StructurMember members[],int size) : mGuid(guid) , mName(name) + { + + for (int i = 0 ; i < size ; i ++) + { + + StructurMember *p=new StructurMember(members[i].guid,members[i].name,members[i].defaultValue); + getArray().push_back(p); + } + + } + std::vectorpars; + std::vector&getArray() + { + return pars; + } + + CKGUID mGuid; + XString mName; + }; + + class StructHelper + { + + public : + + static XArraygetMemberGuids(CustomStructure _inStructure) + { + XArrayresult; + + int size = _inStructure.getArray().size(); + for (int i = 0 ; i < size ; i ++) + { + StructurMember *m=_inStructure.getArray().at(i); + result.PushBack(m->guid); + } + return result; + } + static XString getLabelNames(CustomStructure _inStructure) + { + XString result; + + int size = _inStructure.getArray().size(); + for (int i = 0 ; i < size ; i ++) + { + StructurMember *m=_inStructure.getArray().at(i); + result << m->name.CStr(); + + if (i != size -1) + { + result << ","; + } + } + return result; + } + + static XString getDefaultValue(CustomStructure _inStructure) + { + XString result; + + int size = _inStructure.getArray().size(); + for (int i = 0 ; i < size ; i ++) + { + StructurMember *m=_inStructure.getArray().at(i); + result << m->defaultValue.CStr(); + if (i != size -1) + { + result << ";"; + } + } + return result; + } + }; + + } +} + +#define STRUCT_ATTRIBUTE(G,N,D) vtTools::ParameterTools::StructurMember(G,N,D) +#define DECLARE_STRUCT(T,N,G,A,S) CustomStructure cs##T(N,G,A,S) + +#define STRUCT_SIZE(SOURCE_MAP) (sizeof(SOURCE_MAP) / sizeof(SOURCE_MAP[0])) +#define STRUCT_MEMBER_NAMES(SRC) vtTools::ParameterTools::StructHelper::getLabelNames(cs##SRC) +#define STRUCT_MEMBER_GUIDS(SRC) vtTools::ParameterTools::StructHelper::getMemberGuids(cs##SRC) +#define STRUCT_MEMBER_DEFAULTS(SRC) vtTools::ParameterTools::StructHelper::getDefaultValue(cs##SRC) + + +#define REGISTER_CUSTOM_STRUCT(NAME,ENUM_TYPE,GUID,MEMBER_ARRAY,HIDDEN) DECLARE_STRUCT(ENUM_TYPE,NAME,GUID,MEMBER_ARRAY,STRUCT_SIZE(MEMBER_ARRAY)); \ + XArray ListGuid##ENUM_TYPE = STRUCT_MEMBER_GUIDS(ENUM_TYPE);\ + pm->RegisterNewStructure(GUID,NAME,STRUCT_MEMBER_NAMES(ENUM_TYPE).Str(),ListGuid##ENUM_TYPE);\ + CKParameterTypeDesc* param_type##ENUM_TYPE=pm->GetParameterTypeDescription(GUID);\ + if (param_type##ENUM_TYPE && HIDDEN) param_type##ENUM_TYPE->dwFlags|=CKPARAMETERTYPE_HIDDEN;\ + _getCustomStructures().Insert(GUID,(CustomStructure*)&MEMBER_ARRAY) + + + + + +#define REGISTER_STRUCT_AS_ATTRIBUTE(NAME,ENUM_TYPE,CATEGORY,GUID,CLASS,MEMBER_ARRAY,USE_DEFAULTS) int att##ENUM_TYPE = attman->RegisterNewAttributeType(NAME,GUID,CLASS);\ + attman->SetAttributeCategory(att##ENUM_TYPE,CATEGORY);\ + if(USE_DEFAULTS)\ + attman->SetAttributeDefaultValue(att##ENUM_TYPE,STRUCT_MEMBER_DEFAULTS(ENUM_TYPE).Str()); + + + +#endif diff --git a/usr/Include/Core/Common/xBaseTypes.h b/usr/Include/Core/Common/xBaseTypes.h new file mode 100644 index 0000000..099c9c6 --- /dev/null +++ b/usr/Include/Core/Common/xBaseTypes.h @@ -0,0 +1,49 @@ +/******************************************************************** + created: 2009/02/17 + created: 17:2:2009 8:23 + filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common\xBaseTypes.h + file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\Common + file base: xBaseTypes + file ext: h + author: Günter Baumgart + + purpose: Type definitions, Arrays, ... +*********************************************************************/ +#ifndef __X_BASE_TYPES_H__ +#define __X_BASE_TYPES_H__ + + +//################################################################ +// +// Float, Integers, Boolean +// + +#ifndef u32 + typedef unsigned int u32; +#endif + +namespace xBase +{ + typedef float xReal32; + typedef int xS32; + typedef unsigned int xU32; + typedef bool xBool; + typedef unsigned short xU16; +} + +using xBase::xS32; +using xBase::xU32; +using xBase::xReal32; +using xBase::xBool; +using xBase::xU16; + +//################################################################ +// +// Containers +// + +#include +#include +#include + +#endif // __XBASETYPES_H__ \ No newline at end of file diff --git a/usr/Include/Core/Common/xEnumerations.h b/usr/Include/Core/Common/xEnumerations.h new file mode 100644 index 0000000..33e8dd9 --- /dev/null +++ b/usr/Include/Core/Common/xEnumerations.h @@ -0,0 +1,5 @@ +#ifndef __VTODE_ENUMS_H_ +#define __VTODE_ENUMS_H_ + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/Common/xTime.h b/usr/Include/Core/Common/xTime.h new file mode 100644 index 0000000..6987dda --- /dev/null +++ b/usr/Include/Core/Common/xTime.h @@ -0,0 +1,42 @@ +// racer/time.h + +#ifndef __X_TIME_H__ +#define __X_TIME_H__ +#include +#include + + +class MODULE_API xTime +// A notion of simulation time +{ + protected: + float span; // Time of integration (in seconds) + int spanMS; // Time of integration in milliseconds + QTimer *tmr; // Actual real timer + int curRealTime; // Last recorded REAL time in msecs + int curSimTime; // Time calculated in the sim + int lastSimTime; // Last point of simulation + + public: + xTime(); + ~xTime(); + + // Attribs + int GetRealTime(){ return curRealTime; } + int GetSimTime(){ return curSimTime; } + int GetLastSimTime(){ return lastSimTime; } + int GetSpanMS(){ return spanMS; } + inline float GetSpan(){ return span; } + + void AddSimTime(int msecs); + void SetLastSimTime(){ lastSimTime=curSimTime; } + void SetSpan(int ms); + + // Methods + void Start(); + void Stop(); + void Reset(); + void Update(); +}; + +#endif diff --git a/usr/Include/Core/InfoZip.cpp b/usr/Include/Core/InfoZip.cpp new file mode 100644 index 0000000..6f4c4a0 --- /dev/null +++ b/usr/Include/Core/InfoZip.cpp @@ -0,0 +1,332 @@ +#include "..\stdafx.h" +#include "InfoZip.h" +#include + +#ifdef _DEBUG +#undef THIS_FILE +static char THIS_FILE[]=__FILE__; +#define new DEBUG_NEW +#endif + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +CInfoZip::CInfoZip(){ + + m_ZipDllHandle = NULL; + m_ZipDllExec = NULL; + m_GetZipDllVersion = NULL; + + m_UnzipDllHandle = NULL; + m_UnzipDllExec = NULL; + m_GetUnzipDllVersion = NULL; +} + +CInfoZip::~CInfoZip(){ + //Finalize(); +} + +int CInfoZip::GetZipDllVersion() +{ + if (GetInitializedZip()) + return m_GetZipDllVersion(); + else + { + SetLastError(ZERROR_NOT_INITIALIZED); + return 0; + } +} + +int CInfoZip::GetUnzipDllVersion() +{ + if (GetInitializedUnzip()) + return m_GetUnzipDllVersion(); + else + { + SetLastError(ZERROR_NOT_INITIALIZED); + return 0; + } +} + +void CInfoZip::SetLastError(UINT uiError) +{ + m_uiLastError = uiError; +} + +UINT CInfoZip::GetLastError() +{ + return m_uiLastError; +} + + + +BOOL CInfoZip::GetInitialized() +{ + return GetInitializedZip() && GetInitializedUnzip(); +} +void CInfoZip::SetDefaultValues(CZipParams * pParams){ + + pParams->m_hwndHandle = NULL; + pParams->m_pCaller = NULL; + pParams->m_liVersion = GetZipDllVersion(); + pParams->m_pfCallbackFunction = DefaultZipCallback; + pParams->m_bTraceEnabled = FALSE; + + /*============== Begin Zip Flag section ============== */ + pParams->m_pszZipPassword = NULL; + pParams->m_bSuffix = FALSE; + pParams->m_bEncrypt = FALSE; + pParams->m_bSystem = TRUE; + pParams->m_bVolume = FALSE; + pParams->m_bExtra = FALSE; + pParams->m_bNoDirEntries = FALSE; + pParams->m_bDate = FALSE; + pParams->m_bVerboseEnabled = FALSE; + pParams->m_bQuiet = FALSE; + pParams->m_bLevel = 5; + pParams->m_bComprSpecial = FALSE; + pParams->m_bCRLF_LF = FALSE; + pParams->m_bJunkDir = FALSE; + pParams->m_bRecurse = FALSE; + pParams->m_bGrow = TRUE; + pParams->m_bForce = FALSE; + pParams->m_bMove = FALSE; + pParams->m_bDeleteEntries = FALSE; + pParams->m_bUpdate = FALSE; + pParams->m_bFreshen = FALSE; + pParams->m_bJunkSFX = FALSE; + pParams->m_bLatestTime = FALSE; + /*============== End Zip Flag section ============== */ + + for (int j=0; j<8; j++) + pParams->m_cDate[j] = 0; + pParams->m_liFileCount = 0; + pParams->m_pszArchiveFileName = NULL; + pParams->m_liSeven = 7; + +// char *PFileNames[MAX_PATH+1]; +} + +BOOL CInfoZip::Execute(CZipParams * pParams) +{ + if (!GetInitializedZip()) + return FALSE; + + m_ZipDllExec(pParams); + return TRUE; +} + +BOOL CInfoZip::AddFiles(const char *pszArchive, char ** paFiles, int iFileCount) +{ + CZipParams zpParams; + SetDefaultValues(&zpParams); + +// seting archive name + zpParams.m_pszArchiveFileName = (char*)malloc(strlen(pszArchive)+1); + ZeroMemory(zpParams.m_pszArchiveFileName, strlen(pszArchive)+1); + strcpy(zpParams.m_pszArchiveFileName, pszArchive); + +// seting file count + zpParams.m_liFileCount = iFileCount; + +// seting file names + for (int i=0; im_liErrorCode) + { + char pszErrorCode[1024]; + sprintf(pszErrorCode, "Zip error %d:\n%s", pData->m_liErrorCode, pData->m_pszFileNameOrMsg); + AfxMessageBox(pszErrorCode); + } + return FALSE; +} + +void CInfoZip::ReleaseParams(CZipParams * pParams) +{ + free(pParams->m_pszArchiveFileName); + for (int i=0; im_liFileCount; i++) + free(pParams->m_pszFileNames[i]); +} + +BOOL CInfoZip::GetInitializedZip() +{ + return m_ZipDllHandle && m_GetZipDllVersion && m_ZipDllExec; +} + +BOOL CInfoZip::GetInitializedUnzip() +{ + return m_UnzipDllHandle && m_GetUnzipDllVersion && m_UnzipDllExec; +} + +BOOL CInfoZip::InitializeZip(char *tempfile){ + BOOL bInitialized = GetInitializedZip(); + if (GetInitializedUnzip()) + return TRUE; + + m_ZipDllHandle = LoadLibrary(tempfile); + if (!m_ZipDllHandle) + { + SetLastError(ZERROR_DLL_NOT_FOUND); + return FALSE; + } + + m_GetZipDllVersion = (CGetZipDllVersion)GetProcAddress(m_ZipDllHandle, "GetZipDllVersion"); + if (!m_GetZipDllVersion) + { + SetLastError(ZERROR_DLL_FOUNCTION_NOT_FOUND); + return FALSE; + } + + m_ZipDllExec = (CZipDllExec)GetProcAddress(m_ZipDllHandle, "ZipDllExec"); + if (!m_ZipDllExec) + { + SetLastError(ZERROR_DLL_FOUNCTION_NOT_FOUND); + return FALSE; + } + + return TRUE; +} + +BOOL CInfoZip::InitializeUnzip() +{ + BOOL bInitialized = GetInitializedUnzip(); + if (GetInitializedUnzip()) + return TRUE; + + m_UnzipDllHandle = LoadLibrary("UNZDLL.DLL"); + if (!m_UnzipDllHandle) + { + SetLastError(ZERROR_DLL_NOT_FOUND); + return FALSE; + } + + m_GetUnzipDllVersion = (CGetUnzipDllVersion)GetProcAddress(m_UnzipDllHandle, "GetUnzDllVersion"); + if (!m_GetUnzipDllVersion) + { + SetLastError(ZERROR_DLL_FOUNCTION_NOT_FOUND); + return FALSE; + } + + m_UnzipDllExec = (CUnzipDllExec)GetProcAddress(m_UnzipDllHandle, "UnzDllExec"); + if (!m_UnzipDllExec) + { + SetLastError(ZERROR_DLL_FOUNCTION_NOT_FOUND); + return FALSE; + } + + return TRUE; +} + +BOOL CInfoZip::FinalizeZip(char *tempfile){ + if (GetInitializedZip()){ + FreeLibrary(m_ZipDllHandle); + m_ZipDllHandle = NULL; + m_ZipDllExec = NULL; + m_GetZipDllVersion = NULL; + DeleteFile(tempfile); + } + return TRUE; +} + +BOOL CInfoZip::FinalizeUnzip() +{ + if (GetInitializedUnzip()) + { + FreeLibrary(m_UnzipDllHandle); + m_UnzipDllHandle = NULL; + m_UnzipDllExec = NULL; + m_GetUnzipDllVersion = NULL; + + } + return TRUE; +} + +BOOL CInfoZip::Execute(CUnzipParams * pParams) +{ + if (!GetInitializedUnzip()) + return FALSE; + + m_UnzipDllExec(pParams); + return TRUE; +} + +void CInfoZip::ReleaseParams(CUnzipParams * pParams) +{ + free(pParams->m_pszArchiveFileName); + for (int i=0; im_liFileCount; i++) + free(pParams->m_pszFileNames[i]); +} + +void CInfoZip::SetDefaultValues(CUnzipParams * pParams) +{ + pParams->m_wndHandle = NULL; + pParams->m_pCaller = NULL; + pParams->m_liVersion = GetUnzipDllVersion(); + pParams->m_pfCallbackFunction = DefaultZipCallback; + pParams->m_bTraceEnabled = FALSE; + + pParams->m_bPromptToOverwrite = FALSE; + pParams->m_bTest = FALSE; + pParams->m_bComments = FALSE; + pParams->m_bConvert = FALSE; + + pParams->m_bQuiet = FALSE; + pParams->m_bVerboseEnabled = FALSE; + pParams->m_bUpdate = FALSE; + pParams->m_bFreshen = FALSE; + pParams->m_bDirectories = TRUE; + pParams->m_bOverwrite = TRUE; + + pParams->m_liFileCount = 0; + pParams->m_pszArchiveFileName = NULL; + pParams->m_liSeven = 7; + pParams->m_pszZipPassword = NULL; + + +} + +BOOL CInfoZip::ExtractFiles(const char * pszArchive, const char * pszTargetFolder) +{ + char pszCurrentDir[MAX_PATH+1]; + ZeroMemory(pszCurrentDir, MAX_PATH+1); + GetCurrentDirectory(MAX_PATH+1, pszCurrentDir); + SetCurrentDirectory(pszTargetFolder); + + CUnzipParams uzpParams; + SetDefaultValues(&uzpParams); + +// seting archive name + uzpParams.m_pszArchiveFileName = (char*)malloc(strlen(pszArchive)+1); + ZeroMemory(uzpParams.m_pszArchiveFileName, strlen(pszArchive)+1); + strcpy(uzpParams.m_pszArchiveFileName, pszArchive); + +// seting file count + uzpParams.m_liFileCount = 1; + +// seting file names + uzpParams.m_pszFileNames[0] = (char*)malloc(MAX_PATH+1); + ZeroMemory(uzpParams.m_pszFileNames[0], MAX_PATH+1); + strcpy(uzpParams.m_pszFileNames[0], "*.*"); + +// executing command + int iProcessedCount = m_UnzipDllExec(&uzpParams); + ReleaseParams(&uzpParams); + + SetCurrentDirectory(pszCurrentDir); + return TRUE; +} diff --git a/usr/Include/Core/InfoZip.h b/usr/Include/Core/InfoZip.h new file mode 100644 index 0000000..e0968c1 --- /dev/null +++ b/usr/Include/Core/InfoZip.h @@ -0,0 +1,58 @@ +#include "ZipDll.h" +#include "UnzipDll.h" +#include "CKAll.h" + +//#include "..\Manager\ZipManager.h" + +#define ZERROR_NONE 0 +#define ZERROR_DLL_NOT_FOUND 1 +#define ZERROR_DLL_FOUNCTION_NOT_FOUND 2 +#define ZERROR_NOT_INITIALIZED 3 + +class CInfoZip { +public: + + + CInfoZip(); + virtual ~CInfoZip(); + + BOOL ExtractFiles(const char* pszArchive, const char* pszTargetFolder); + void SetDefaultValues(CUnzipParams *pParams); + void ReleaseParams(CUnzipParams *pParams); + BOOL Execute(CUnzipParams *pParams); + BOOL FinalizeUnzip(); + BOOL FinalizeZip(char *tempfile); + BOOL InitializeUnzip(); + BOOL InitializeZip(char *tempfile); + BOOL GetInitializedUnzip(); + BOOL GetInitializedZip(); + void ReleaseParams(CZipParams *pParams); + BOOL AddFiles(const char *pszArchive, char **paFiles, int iFileCount); + BOOL Execute(CZipParams *pParams); + void SetDefaultValues(CZipParams *pZipParms); + BOOL GetInitialized(); + UINT GetLastError(); + int GetZipDllVersion(); + int GetUnzipDllVersion(); + + CZipDllExec m_ZipDllExec; + + + + void SetLastError(UINT uiError); + UINT m_uiLastError; + HINSTANCE m_ZipDllHandle; + HINSTANCE m_UnzipDllHandle; + + CUnzipDllExec m_UnzipDllExec; + CGetZipDllVersion m_GetZipDllVersion; + + + +private: + +}; + +BOOL __stdcall DefaultZipCallback(CZipCallbackData *pData); + + diff --git a/usr/Include/Core/Manager/CKPhysicsManager.h b/usr/Include/Core/Manager/CKPhysicsManager.h new file mode 100644 index 0000000..1733f6a --- /dev/null +++ b/usr/Include/Core/Manager/CKPhysicsManager.h @@ -0,0 +1,41 @@ +#ifndef CKPhysicManager_H + #define CKPhysicManager_H "$Id:$" + + +#include "vtPhysXBase.h" +#include "CKBaseManager.h" + +class MODULE_API CKPhysicManager :public CKBaseManager { +public: + + +#ifdef DOCJETDUMMY // Docjet secret macro +#else + + + virtual CKERROR OnCKInit()=0; + virtual CKERROR PostClearAll()=0; + virtual CKERROR PreSave()=0; + virtual CKERROR OnCKReset()=0; + virtual CKERROR PreProcess()=0; + + virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_PostClearAll| + CKMANAGER_FUNC_OnCKInit| + CKMANAGER_FUNC_PreSave| + CKMANAGER_FUNC_PostLoad| + CKMANAGER_FUNC_OnCKReset| + CKMANAGER_FUNC_PreProcess; + } + virtual void _RegisterParameters()=0; + virtual void _RegisterVSL()=0; + + CKPhysicManager(CKContext *Context,CKGUID guid,char* name); + virtual ~CKPhysicManager() {} + + + +#endif // Docjet secret macro +}; + +// CK2 VERSION ... +#endif diff --git a/usr/Include/Core/Manager/DataManager.h b/usr/Include/Core/Manager/DataManager.h new file mode 100644 index 0000000..473fead --- /dev/null +++ b/usr/Include/Core/Manager/DataManager.h @@ -0,0 +1,218 @@ +#ifndef DataManager_H +#define DataManager_H "$Id:$" + +#include "CKBaseManager.h" + +// define whether we use the manager to relay data or the global variable +#define USE_MANAGER + + +// [4/13/2009 macro willson] new headers for external access added + +#include "gConfig.h" + +//---------------------------------------------------------------- +// +// External access +// +#ifdef G_EXTERNAL_ACCESS + + + + #include //! @todo : HANDLE type + + #include "MemoryFileMappingTypes.h" //! todo : use forwards + +#endif // G_EXTERNAL_ACCESS + + + +//---------------------------------------------------------------- +// +// unique object identifiers +// +#define DataManagerGUID CKGUID(0x5164ef93, 0x384edab9) + +class DataManager : public CKBaseManager +{ +//############################################################## +// Public Part +//############################################################## +public : + DataManager(CKContext* Context); + ~DataManager(); + + VxVector _vPos; + + +#ifdef G_EXTERNAL_ACCESS + + // [4/13/2009 macro willson] + //---------------------------------------------------------------- + // + // External access : data members + // + HANDLE m_hMMFile; + vtExternalEvent *m_pData; + + //---------------------------------------------------------------- + // + // External access : functions + // + + + /*! + + \brief initiates shared memory helper objects. Must be called due CKInit + */ + int _initSharedMemory(int); + + /* + \brief handles messages. Must be called in a PreProcess. + */ + int _SharedMemoryTick(int); + + + /* + \brief Might be silly. Just to clean up. Must be called in PostProcess. + */ + int _SharedMemoryTickPost(int); + + + + //---------------------------------------------------------------- +#endif + + + // [4/13/2009 macro willson] : enabled for external access + /*! + \brief Called at the end of each process loop. + */ + virtual CKERROR PostProcess(); + + //--- Called at the beginning of each process loop. + virtual CKERROR PreProcess(); + + // -- Called once at CKPlay. Needed to initiate shared memory + CKERROR OnCKInit(); + + //- set function mask for pre and post process callbacks + virtual CKDWORD GetValidFunctionsMask() + { + return CKMANAGER_FUNC_OnCKInit|CKMANAGER_FUNC_PostProcess|CKMANAGER_FUNC_PreProcess; + + } + + // [4/14/2009 macro willson] : end external access ---------------------------------------------------------------- + + + + +//-------------------------------------------------------------- +// Unused methods +//-------------------------------------------------------------- + +/* + + + + + +//--- Called after the composition has been restarted. + virtual CKERROR OnCKPostReset(); + +//--- Called before the composition is reset. + virtual CKERROR OnCKReset(); + +//--- Called when the process loop is started. + virtual CKERROR OnCKPlay(); + +//--- Called when the process loop is paused. + virtual CKERROR OnCKPause(); + +//--- Called before a scene becomes active. + virtual CKERROR PreLaunchScene(CKScene* OldScene, CKScene* NewScene); + +//--- Called after a scene became active. + virtual CKERROR PostLaunchScene(CKScene* OldScene, CKScene* NewScene); + +//--- Called at the beginning of a copy. + virtual CKERROR OnPreCopy(CKDependenciesContext& context); + +//--- Called at the end of a copy. + virtual CKERROR OnPostCopy(CKDependenciesContext& context); + +//--- Called when objects are added to a scene. + virtual CKERROR SequenceAddedToScene(CKScene* scn, CK_ID* objids, int count); + +//--- Called when objects are removed from a scene. + virtual CKERROR SequenceRemovedFromScene(CKScene* scn, CK_ID* objids, int count); + +//--- Called just before objects are deleted. + virtual CKERROR SequenceToBeDeleted(CK_ID* objids, int count); + +//--- Called after objects have been deleted. + virtual CKERROR SequenceDeleted(CK_ID* objids, int count); + +//--- Called before the rendering of the 3D objects. + virtual CKERROR OnPreRender(CKRenderContext* dev); + +//--- Called after the rendering of the 3D objects. + virtual CKERROR OnPostRender(CKRenderContext* dev); + +//--- Called after the rendering of 2D entities. + virtual CKERROR OnPostSpriteRender(CKRenderContext* dev); + +//--- Called before the backbuffer is presented. + virtual CKERROR OnPreBackToFront(CKRenderContext* dev); + +//--- Called after the backbuffer is presented. + virtual CKERROR OnPostBackToFront(CKRenderContext* dev); + +//--- Called before switching to/from fullscreen. + virtual CKERROR OnPreFullScreen(BOOL Going2Fullscreen, CKRenderContext* dev); + +//--- Called after switching to/from fullscreen. + virtual CKERROR OnPostFullScreen(BOOL Going2Fullscreen, CKRenderContext* dev); + +//--- Called at the end of the creation of a CKContext. + + +//--- Called at deletion of a CKContext. + virtual CKERROR OnCKEnd(); + +//--- Called at the beginning of a load operation. + virtual CKERROR PreLoad(); + +//--- Called to load manager data. + virtual CKERROR LoadData(CKStateChunk* chunk, CKFile* LoadedFile) { return CK_OK; } + +//--- Called at the end of a load operation. + virtual CKERROR PostLoad(); + +//--- Called at the beginning of a save operation. + virtual CKERROR PreSave(); + +//--- Called to save manager data. return NULL if nothing to save. + virtual CKStateChunk* SaveData(CKFile* SavedFile) { return NULL; } + +//--- Called at the end of a save operation. + virtual CKERROR PostSave(); + +//--- Called at the beginning of a CKContext::ClearAll operation. + virtual CKERROR PreClearAll(); + +//--- Called at the end of a CKContext::ClearAll operation. + virtual CKERROR PostClearAll(); + + +*/ +//############################################################## +// Protected Part +//############################################################## +protected : + +}; + +#endif + diff --git a/usr/Include/Core/Manager/Dll_Tools.h b/usr/Include/Core/Manager/Dll_Tools.h new file mode 100644 index 0000000..2ce06b8 --- /dev/null +++ b/usr/Include/Core/Manager/Dll_Tools.h @@ -0,0 +1,149 @@ +/******************************************************************** + created: 2003/12/01 + filename: H:\XLANG PROJECTS\BASE\INCLUDES\Dll_Tools.h + file path: H:\XLANG PROJECTS\BASE\INCLUDES + file base: Dll_Tools + file ext: h + author: Günter Baumgart + purpose: rum DLL´eln +*********************************************************************/ + + + +#ifndef __Dll_Tools_h_ +#define __Dll_Tools_h_ "$Id:$" + + + + +#include +#include +#include + + + ////////////////////////////////////////////////////////////////////////// + //ie: + // the fnc prototyp : typedef HINSTANCE(WINAPI *_ShellExec_proto)(HWND,const char *,const char*,const char*,const char *,int); + // the fill : DLL::DllFunc<_ShellExec_proto>_ShellExec(_T("shell32.dll"),"ShellExecute"); + + template class DllFunc + { + public: + + DllFunc(const char* dllName, const char* fnName ,const bool logging = TRUE ) : + + dllHandle( LoadLibrary (dllName) ) , fn(0) + { + if (!dllHandle && logging) + { + //loggin @: + return; + } + fn = ( T )GetProcAddress(dllHandle, fnName); + + if (!fn) + { + char modName[_MAX_PATH],logmsg [400],_path[_MAX_PATH]; + GetModuleFileName( GetModuleHandle(NULL) ,modName,_MAX_PATH ); + // loggin @: + sprintf ( logmsg , "%s %s %s" , modName , "couldn´t get function with prototyp : ", typeid(fn).name() ) ; + sprintf( _path , "%s%s", modName ,".log" ) ; + //loggin : + return; + } + + } + operator T(){ + return fn; + } + public: + T fn; + HMODULE dllHandle; + void *ret; + }; + + + + +#endif //__win32Tools_h_ + /* +DLL::DynamicFn<_ShellExec_proto>_ShellExec(_T("shell32.dll"),"ShellExecuteA"); + + // DLL::DynamicFn_ShellExec(_T("shell32.dll"),"ShellExecuteA"); + + return (*_ShellExec)(NULL,"open","www.gmx.net",NULL,NULL, SW_MAXIMIZE);*/ + + + /* + /******************************************************************** + created: 2003/12/01 + filename: H:\XLANG PROJECTS\BASE\INCLUDES\Dll_Tools.h + file path: H:\XLANG PROJECTS\BASE\INCLUDES + file base: Dll_Tools + file ext: h + author: Günter Baumgart + purpose: rum DLL´eln + *********************************************************************/ + + + +#ifndef __Dll_Tools_h_ +#define __Dll_Tools_h_ "$Id:$" + + + + +#include +#include +#include + + + ////////////////////////////////////////////////////////////////////////// + //ie: + // the fnc prototyp : typedef HINSTANCE(WINAPI *_ShellExec_proto)(HWND,const char *,const char*,const char*,const char *,int); + // the fill : DLL::DllFunc<_ShellExec_proto>_ShellExec(_T("shell32.dll"),"ShellExecute"); + + template class DllFunc + { + public: + + DllFunc(const char* dllName, const char* fnName ,const bool logging = TRUE ) : + + dllHandle( LoadLibrary (dllName) ) , fn(0) + { + if (!dllHandle && logging) + { + char modName[_MAX_PATH],logmsg [400],_path[_MAX_PATH]; + GetModuleFileName( GetModuleHandle(NULL) ,modName,_MAX_PATH ); + sprintf ( logmsg , "%s %s %s" , modName , "couldn´t find ", dllName ) ; + sprintf( _path , "%s%s", modName ,".log" ) ; + + return; + } + fn = ( T )GetProcAddress(dllHandle, fnName); + + if (!fn) + { + char modName[_MAX_PATH],logmsg [400],_path[_MAX_PATH]; + GetModuleFileName( GetModuleHandle(NULL) ,modName,_MAX_PATH ); + // loggin + sprintf ( logmsg , "%s %s %s" , modName , "couldn´t get function with prototyp : ", typeid(fn).name() ) ; + sprintf( _path , "%s%s", modName ,".log" ) ; + return; + } + + } + operator T(){ + return fn; + } + public: + T fn; + HMODULE dllHandle; + void *ret; + }; + + + + +#endif //__win32Tools_h_ + \ No newline at end of file diff --git a/usr/Include/Core/Manager/InitMan.h b/usr/Include/Core/Manager/InitMan.h new file mode 100644 index 0000000..6afb865 --- /dev/null +++ b/usr/Include/Core/Manager/InitMan.h @@ -0,0 +1,197 @@ +#ifndef InitMAN_H +#define InitMAN_H + + +#include "CKBaseManager.h" + + +#include +#include + + + +#define S_PARAMETER_GUID CKGUID(0x7a7104e2,0x72c56435) + +#define SFLOAT_PARAMETER_GUID CKGUID(0x6a5b2ec3,0x63f84a40) + +#define SCOLOR_PARAMETER_GUID CKGUID(0x47cc15d2,0xf366299) +#define SINT_PARAMETER_GUID CKGUID(0x31d3196f,0x787306e1) + + + +#define CKPGUID_LOOPMODE CKDEFINEGUID(0x63942d15,0x5ac51a7) + + +typedef enum QAD_OBJECT_TYPE { + + CHARACTER = 1, + PUSHBOX = 2, + BALL = 3, + STONE = 4, + COIN = 5, + FUEL = 6, + ROCKET = 7, + MOVINGBOARD = 8, + SPRINGPAIR =9, +} +QAD_OBJECT_TYPE; +////////////////////////////////////////////////////////////////////////// +#define VLEFT VxVector(-1.0f,0.0f,0.0f) +#define VRIGHT VxVector(1.0f,0.0f,0.0f) +#define VUP VxVector(1.0f,1.0f,0.0f) +#define VDOWN VxVector(0.0f,-1.0f,0.0f) +#define VZERO VxVector(0.0f,0.0f,0.0f) + +#define PHYSIC_OBJECT_2D_PARAMETER CKDEFINEGUID(0x57ba4ee6,0x4d8740a9) + +#define PHYSIC_OBJECT_SIMULATION_FILTER CKDEFINEGUID(0x248f1f51,0x72070f85) + +#define PHYSIC_OBJECT_2D_WORLDSPRING_PARAMETER CKDEFINEGUID(0x1b8e268b,0x11041fa0) + + + +////////////////////////////////////////////////////////////////////////// + +#include "typedefs.h" +#include "ZipDll.h" +#include "UnzipDll.h" +#include "ZCallBck.h" + +BOOL __stdcall DefaultZipCallback(CZipCallbackData *pData);//thanks + + +#include "sharedStructs.h" + + + +#define INIT_MAN_GUID CKGUID(0x35824c8a,0x4e320ac4) + +class InitMan : public CKBaseManager +{ + + public: + //Ctor + InitMan(CKContext* ctx); + //Dtor + ~InitMan(); + static InitMan* GetInstance(); + + + ////////////////////////////////////////////////////////////////////////// + //virtual file mapping , used for command pipe: + HANDLE m_hMMFile; + vtExternalEvent *m_pData; + + typedef XHashTablevtExternalEventQueueType; + vtExternalEventQueueType incomingEvents; + void PerformMessages(); + void InitMessages(int flags,XString name); + + // Initialization + virtual CKERROR OnCKInit(); + virtual CKERROR OnCKEnd(); + virtual CKERROR OnCKReset(); + CKERROR PreProcess(); + CKERROR PostProcess(); + virtual CKERROR PostClearAll(); + virtual CKERROR OnCKPlay(); + + + CKDWORD GetValidFunctionsMask() + { return CKMANAGER_FUNC_OnCKInit| + CKMANAGER_FUNC_OnCKEnd| + CKMANAGER_FUNC_OnCKReset| + CKMANAGER_FUNC_PreProcess| + CKMANAGER_FUNC_PostProcess| + CKMANAGER_FUNC_PostClearAll| + CKMANAGER_FUNC_OnCKPlay; + } + + + /************************************************************************/ + /* Parameter Functions */ + /************************************************************************/ + + int move_object_att; int moving_board_att; int rocket_att; int keyboard_config_att; int att_character_keyboard_config; int att_character_anim_messages; int att_character_anims; int att_character_ckof; int att_character_object_set; int att_spring_pair; + + + VxVector Position(CK3dEntity *ent); + + int att_rigid_body_2D; + int att_rigid_body_2D_worldspring; + int att_need_update; + int att_do_physics; + int att_sim_filter; + + + void RegisterVSL(); + void RegisterRacknetVSL(); + + void RegisterCEGUI_VSL(CKContext *ctx); + + void RegisterParameters(); + void RegisterParameters2(); + //void RegisterHUD(); + + + + + + /************************************************************************/ + /* zip lib */ + /************************************************************************/ + + + + ZipJobList zili; + + + bool AddFileEntry(XString ArchiveName,XString FileEntry); + + + BOOL LoadZipDll();//from the projects resource + BOOL UnLoadZipDll(); + void SetDefaultZipValues(CZipParams *pParams); + int GetZipDllVersion(); + + + /************************************************************************/ + /* decompressing funcs */ + /************************************************************************/ + + BOOL LoadUnzipDll(); + BOOL UnLoadUnZipDll(); + void SetDefaultUnZipValues(CUnzipParams * pParams); + int GetUnzipDllVersion(); + + + UINT m_uiLastError;//unused + + /************************************************************************/ + /* compress */ + /************************************************************************/ + HINSTANCE m_ZipDllHandle; + char ZipDllTempFile[MAX_PATH]; + CZipDllExec m_ZipDllExec; + CGetZipDllVersion m_GetZipDllVersion; + + + /************************************************************************/ + /* decompress */ + /************************************************************************/ + + HINSTANCE m_UnzipDllHandle; + char UnZipDllTempFile[MAX_PATH]; + CGetUnzipDllVersion m_GetUnzipDllVersion; + CUnzipDllExec m_UnzipDllExec; + + + private: + + +}; + +#define GetIManager() InitMan::GetInstance() + + +#endif diff --git a/usr/Include/Core/Manager/Path.h b/usr/Include/Core/Manager/Path.h new file mode 100644 index 0000000..2169285 --- /dev/null +++ b/usr/Include/Core/Manager/Path.h @@ -0,0 +1,237 @@ +#ifndef PATH_H +#define PATH_H + + +#include "CKALL.H" +#include "windows.h" + +#include +#include + + + + +#include "Shlwapi.h" +#pragma comment (lib,"SHLWAPI.LIB") + + + +class XPath { + +private: + + + char path_separator_; + char drive_separator_; + char extension_separator_; + +public: + + XString data_; + + //ctors + + inline XPath(); + XPath( const XPath& path ); + XPath( const XString& filepath ); + + XPath( const XString& dirpath, const XString& filename ); + XPath + ( + const XString& dirpath, + const XString& base, + const XString& extension + ); + XPath + ( + char drive, + const XString& dirpath, + const XString& filename + ); + XPath + ( + char drive, + const XString& dirpath, + const XString& base, + const XString& extension + ); + + + + //components + XString operator[]( int index ) const; + + // Testing. + bool absolute() const; + bool relative() const; + + bool directory_path() const; + bool has_directory() const; + bool has_extension() const; + bool has_drive() const; + bool is_valid(); + + + // Conversion. + operator const char*() const; + operator const XString&() const; + + // Comparison + int operator==( const XPath& path ) const; + int operator==( const XString& string ) const; + int operator!=( const XPath& path ) const; + int operator!=( const XString& string ) const; + int operator<( const XPath& path ) const; + int operator<( const XString& string ) const; + + XPath& operator=( const XString& filepath ); + XPath& operator=( const XPath& path ); + + //used for the objectmode + XPath& operator+=(CKBeObject *beo){ + + if(data_.Length() == 0)data_ = VxGetTempPath().CStr(); + data_ << beo->GetName() << ".nmo"; + return *this; + } + + + // Accessors. + char* GetFileName(); + char* GetPath(); + + + + char path_separator() const; + char drive_separator() const; + char extension_separator() const; + + int absolute_levels() const; + +protected: + + void init_separators(); + // Common finds. + size_t last_extension_separator() const; + +}; + + +/************************************************************************/ +/* protected funtions */ +/************************************************************************/ +inline void +XPath::init_separators(){ + + path_separator_ = '\\'; + drive_separator_ = ':'; + extension_separator_ = '.'; +} + +/************************************************************************/ +/* ctors //ops // converts */ +/************************************************************************/ +inline +XPath::XPath(const XString& dirpath, const XString& filename ){ + init_separators(); + data_ << dirpath < + - Range: [object range)
+ - Default: NULL
+ + \param[in] CK3dEntity * referenceB , r: the second object participating in the constraint. This can be NULL because joint constraints can be created between a rigid body and the global world frame.
+ - Range: [object range)
+ - Default: NULL
+ + \param[in] JType type, r: an additional hint to find the right joint object. Notice that one rigid body can have 1:n joints so it makes sense to pass the type to this function. By default its returning the first found joint on the given reference objects.
+ - Range: [joint type range)
+ - Default: #JT_Any
+ + \return pJoint* + + @see deleteJoint() + */ + pJoint*getJoint(CK3dEntity*referenceA,CK3dEntity*referenceB=NULL,JType type=JT_Any); + + + /** + \if internal2 + + \brief Checks 3D entities for attached joint attributes. If so, its registering the new constraint. + + \return void + + \endif + */ + void _checkObjectsByAttribute(CKScene *newScene = NULL); + int _checkResetList(); + + //@} + + void checkWorlds(); + void checkClothes(); + + void checkBodies(); + + void _RegisterObjectsByAttribute(); + + + + void createWorlds(int flags); + void destroy(); + BOOL checkDemo(CK3dEntity*); + + + + pFactory * getCurrentFactory(){ return m_currentFactory; } + void setCurrentFactory(pFactory * val) { m_currentFactory = val; } + + + /************************************************************************/ + /* xml document access */ + /************************************************************************/ + + TiXmlDocument* loadDefaults(XString filename); + TiXmlDocument* getDefaultConfig() const { return m_DefaultDocument; } + void setDefaultConfig(TiXmlDocument* val) { m_DefaultDocument = val; } + + /************************************************************************/ + /* RigidBody */ + /************************************************************************/ + + pRigidBody *getBody(CK3dEntity*ent,bool lookInSubshapes=false); + pRigidBody *getBody(CK3dEntity*ent,pWorld* world); + pRigidBody *getBody(const char*name,int flags=0); + NxShape *getSubShape(CK3dEntity*referenceObject); + + /** + \brief Returns the givens entity's rigid body object to which the sub shape belongs to. + + \param[in] CK3dEntity * ent ,the entity r: This argument must be non-zero.
+ - Range: [object range)
+ - Default: NULL
+ + \return pRigidBody* + + @see deleteJoint() + */ + pRigidBody* isSubShape(CK3dEntity*ent); + + + NxCCDSkeleton *getCCDSkeleton(CKBeObject *shapeReference); + void doInit(); + + /************************************************************************/ + /* Clothes : */ + /************************************************************************/ + pCloth *getCloth(CK_ID entityID); + + + /************************************************************************/ + /* Fluids : */ + /************************************************************************/ + pFluid *getFluid(CK3dEntity *entityReference); + pFluidEmitter *getFluidEmitter(CK3dEntity *entityReferene); + + + /** + \brief Function that lets you set global simulation parameters. + + Returns false if the value passed is out of range for usage specified by the enum. + + Sleeping: Does NOT wake any actors which may be affected. + + See #pSDKParameter for a description of parameters support by hardware. + + \param[in] paramEnum Parameter to set. See #pSDKParameter + \param[in] paramValue The value to set, see #pSDKParameter for allowable values. + \return False if the parameter is out of range. + + \note All parameters are available in the variable manager too. + + @see pSDKParameter getParameter + */ + void setParameter(pSDKParameter parm,float value); + + /** + \brief Function that lets you query global simulation parameters. + + See #pSDKParameter for a description of parameters support by hardware. + + \param[in] paramEnum The Parameter to retrieve. + \return The value of the parameter. + @see setParameter pSDKParameter + */ + float getParameter(pSDKParameter parm,float value); + + void bindVariables(); + void unBindVariables(); + + void setPSDKParameters(pSDKParameters¶m); + + + //---------------------------------------------------------------- + // + // character controller + // + + UserAllocator * getUserAllocator() const { return mUserAllocator; } + void setUserAllocator(UserAllocator * val) { mUserAllocator = val; } + + + NxControllerManager* getControllerManager() const { return mControllerManager; } + void setControllerManager(NxControllerManager* val) { mControllerManager = val; } + + void _createControllerManager(); + void _releaseControllerManager(); + +private : + + + UserAllocator *mUserAllocator; + NxControllerManager* mControllerManager; + TiXmlDocument* m_DefaultDocument; + pWorld *m_DefaultWorld; + pFactory *m_currentFactory; + pWorldMap* m_Worlds; + + + + NxPhysicsSDK* mPhysicsSDK; + pLogger*mLogger; + pWorldSettings *mDefaultWorldSettings; + xBitSet mManagerFlags; + NxRemoteDebugger* mRemoteDebugger; + + pSDKParameters m_SDKParameters; + pRemoteDebuggerSettings mRemoteDebuggerSettings; + + pRemoteDebuggerSettings& getRemoteDebuggerSettings() { return mRemoteDebuggerSettings; } + void setRemoteDebuggerSettings(pRemoteDebuggerSettings val) { mRemoteDebuggerSettings = val; } + + + IParameter *mIParameter; + + + +public: + int att_physic_object; int att_hull_type; int att_mass; int att_surface_props;int att_physic_limit; BOOL m_DelOnReset; + int att_world_object;int att_sleep_settings;int att_damping;int att_collMask;int att_update_world_flags;int att_update_body_flags; + int att_heightField;int att_JBall;int att_JFixed;int att_JHinge;int att_JHinge2;int att_JSlider;int att_JUniversal;int att_JMotor; + int att_wheelDescr; + int att_clothDescr; + int att_trigger; + int att_deformable; + int att_capsule; + + float mLastStepTime; + + + int _LogInfo; + int _LogTrace; + int _LogWarnings; + int _LogErrors; + int _LogToConsole; + +public : + + + + + float getLastTimeStep(int flags); + + + pSDKParameters& getSDKParameters() { return m_SDKParameters; } + void setSDKParameters(pSDKParameters val) { m_SDKParameters = val; } + + + NxRemoteDebugger* getRemoteDebugger(); + + + + void Update(); + void update(float stepsize); + + + static PhysicManager *GetInstance(); + static CKContext *GetContext(); + + + + static PhysicManager * Cast(CKBaseManager* iM) { return GetInstance();} + CKERROR OnCKInit(); + CKERROR PostClearAll(); + CKERROR PreSave(); + CKERROR OnCKReset(); + CKERROR OnCKEnd(); + CKERROR PreProcess(); + CKERROR SequenceToBeDeleted(CK_ID *objids,int count); + CKERROR OnCKPlay(); + CKERROR OnCKPause(); + CKERROR PostProcess(); + CKERROR SequenceAddedToScene(CKScene *scn,CK_ID *objids,int count); + CKERROR SequenceRemovedFromScene(CKScene *scn,CK_ID *objids,int count); + CKERROR PreLaunchScene(CKScene* OldScene,CKScene* NewScene); + CKERROR PostLaunchScene(CKScene* OldScene,CKScene* NewScene); + CKERROR SequenceDeleted(CK_ID *objids,int count); + CKERROR PreClearAll(); + CKERROR OnPostCopy(CKDependenciesContext& context); + + CKERROR PostLoad(); + + int _migrateOldCustomStructures(CKScene *scnene); + + + //--- Called to save manager data. return NULL if nothing to save... + virtual CKStateChunk* SaveData(CKFile* SavedFile); + void _saveUserEnumeration(CKStateChunk *chunk,CKFile* SavedFile); + + virtual CKERROR LoadData(CKStateChunk *chunk,CKFile* LoadedFile); + void _loadUserEnumeration(CKStateChunk *chunk,CKFile* LoadedFile); + + //--- Called at the end of a save operation. + CKERROR PostSave(); + float getLastDeltaTime(){return mLastStepTime;} + + + virtual CKDWORD GetValidFunctionsMask() + { + return + CKMANAGER_FUNC_PreLaunchScene| + CKMANAGER_FUNC_PostLaunchScene| + CKMANAGER_FUNC_OnSequenceRemovedFromScene| + CKMANAGER_FUNC_OnSequenceDeleted| + CKMANAGER_FUNC_OnSequenceAddedToScene| + CKMANAGER_FUNC_PreClearAll| + CKMANAGER_FUNC_PostClearAll| + CKMANAGER_FUNC_OnSequenceToBeDeleted| + CKMANAGER_FUNC_OnCKPlay| + CKMANAGER_FUNC_OnCKPause| + CKMANAGER_FUNC_OnCKInit| + CKMANAGER_FUNC_PreSave| + CKMANAGER_FUNC_PostLoad| + CKMANAGER_FUNC_OnPostCopy| + CKMANAGER_FUNC_PostSave| + CKMANAGER_FUNC_OnCKReset| + CKMANAGER_FUNC_PostProcess| + CKMANAGER_FUNC_PreProcess| + CKMANAGER_FUNC_OnCKEnd; + } + + + int processOptions; + virtual int& getProcessOptions() { return processOptions; } + virtual void setProcessOptions(int val) { processOptions = val; } + + + +}; + +#define GetPMan() PhysicManager::GetInstance() +#define ctx() PhysicManager::GetInstance()->GetContext() +#define lastStepTimeSec GetPMan()->GetContext()->GetTimeManager()->GetLastDeltaTimeFree() * 0.001f +#define lastStepTimeMS GetPMan()->GetContext()->GetTimeManager()->GetLastDeltaTimeFree() + + + +#endif + diff --git a/usr/Include/Core/Manager/pManagerTypes.h b/usr/Include/Core/Manager/pManagerTypes.h new file mode 100644 index 0000000..fd35ee6 --- /dev/null +++ b/usr/Include/Core/Manager/pManagerTypes.h @@ -0,0 +1,212 @@ +#ifndef __PMANAGERTYPES_H__ +#define __PMANAGERTYPES_H__ + +#include "pNxSDKParameter.h" + + +typedef enum pManagerFlags +{ + PMF_DONT_DELETE_SCENES=1<<1, + PMF_DONT_USE_HARDWARE=1<<2, +}; + +struct pTriggerEntry +{ + + NxShape *shapeA; + NxShape *shapeB; + int triggerEvent; + bool triggered; + CK3dEntity *triggerBody; + CK3dEntity *otherObject; + CK3dEntity *triggerShapeEnt; + + pRigidBody *triggerBodyB; + pRigidBody *otherBodyB; + + + pTriggerEntry() + { + shapeA = shapeB = NULL; + triggerShapeEnt =otherObject = triggerBody = NULL; + triggerBodyB = otherBodyB = NULL; + triggerEvent; + triggered = false; + } +}; + +typedef XArraypTriggerArray; + + +//################################################################ +// +// Help Structures, used by the manager only +// + +//---------------------------------------------------------------- +// +//! \brief Container to maintain multiple worlds +// +typedef XHashTable pWorldMap; +typedef XHashTable::Iterator pWorldMapIt; + +typedef XArraypBodyList; +typedef XArray::Iterator pBodyListIterator; + + +typedef XHashTable pRestoreMap; +typedef XHashTable::Iterator pRestoreMapIt; + + + +//---------------------------------------------------------------- +// +//! \brief Function pointer. Used in custom parameter structures to populate +// found xml types +// +typedef XString (pFactory::*PFEnumStringFunction)(const TiXmlDocument * doc); + +//---------------------------------------------------------------- +// +//! \brief Function pointer to link object registrations per attribute type +// +typedef int (*ObjectRegisterFunction)(CK3dEntity*,int,bool,bool); + +//---------------------------------------------------------------- +// +//! \brief Meta data for ObjectRegisterFunction. Used for attribute callbacks. +// +struct ObjectRegistration +{ + CKGUID guid; + ObjectRegisterFunction rFunc; + ObjectRegistration(CKGUID _guid,ObjectRegisterFunction _func) : + guid(_guid) , + rFunc(_func) + { + + } +}; + +//---------------------------------------------------------------- +// +//! \brief Meta data for attributes callbacks when the scene is playing.
+//! Virtools is not initializing the attributes parameter correctly. +// Ths structur is used to track data to the next frame. +// +struct pAttributePostObject +{ + + CK_ID objectId; + ObjectRegisterFunction func; + int attributeID; + + pAttributePostObject() : + objectId(-1) , func(NULL) , attributeID(-1){} + + pAttributePostObject(CK_ID _id,ObjectRegisterFunction _func,int _attributeID) : + objectId(_id) , + func(_func) , + attributeID(_attributeID) + { + + } + +}; +//---------------------------------------------------------------- +// +//! \brief Container type to store objects with uninitialized attribute parameters. +// +typedef XArrayPostRegistrationArrayType; +typedef XArray::Iterator PostRegistrationArrayIteratorType; + + +//---------------------------------------------------------------- +// +//! \brief Container to store custom function pointer per attribute type +// +typedef XHashTableAttributeFunctionArrayType; +typedef XHashTable::Iterator AttributeFunctionArrayIteratorType; + +//---------------------------------------------------------------- +// +//! \brief CustomParametersArrayType is responsible to track custom structures and its default value. +//! +typedef XHashTableCustomParametersArrayType; +typedef XHashTable::Iterator CustomParametersArrayIteratorType; + + + + + +struct pSDKParameters +{ + float SkinWidth; + float DefaultSleepLinVelSquared ; + float DefaultSleepAngVel_squared; + float BounceThreshold ; + float DynFrictScaling ; + float StaFrictionScaling; + float MaxAngularVelocity ; + float ContinuousCD ; + float AdaptiveForce ; + float CollVetoJointed ; + float TriggerTriggerCallback ; + float CCDEpsilon ; + float SolverConvergenceThreshold ; + float BBoxNoiseLevel ; + float ImplicitSweepCacheSize ; + float DefaultSleepEnergy ; + float ConstantFluidMaxPackets ; + float ConstantFluidMaxParticlesPerStep ; + float AsynchronousMeshCreation ; + float ForceFieldCustomKernelEpsilon ; + float ImprovedSpringSolver ; + int disablePhysics; + + pSDKParameters() + { + + SkinWidth = 0.25f; + DefaultSleepLinVelSquared = 0.15f*0.15f; + DefaultSleepAngVel_squared = 0.15f*0.15f; + BounceThreshold = -2.0f ; + DynFrictScaling =1.0f; + StaFrictionScaling = 1.0f; + MaxAngularVelocity = 7.0f ; + ContinuousCD = 0.0f; + AdaptiveForce = 1.0f; + CollVetoJointed = 1.0f; + TriggerTriggerCallback= 1.0f ; + CCDEpsilon = 0.01f; + SolverConvergenceThreshold = 0.0f ; + BBoxNoiseLevel =0.001f ; + ImplicitSweepCacheSize = 5.0f ; + DefaultSleepEnergy = 0.005f; + ConstantFluidMaxPackets = 925.0f ; + ConstantFluidMaxParticlesPerStep = 4096 ; + ImprovedSpringSolver = 1.0f; + disablePhysics = 0; + } +}; + + +class pRemoteDebuggerSettings +{ + +public : + XString mHost; + int port; + int enabled; + + pRemoteDebuggerSettings() + { + mHost= "localhost"; + port = 5425; + enabled = 0; + } +}; + + + +#endif // __PMANAGERTYPES_H__ \ No newline at end of file diff --git a/usr/Include/Core/Manager/typedefs.h b/usr/Include/Core/Manager/typedefs.h new file mode 100644 index 0000000..576d4a8 --- /dev/null +++ b/usr/Include/Core/Manager/typedefs.h @@ -0,0 +1,185 @@ +/******************************************************************** + created: 2004/11/06 + created: 6:11:2004 16:53 + filename: D:\projects new\vt tools\Manager\typedefs.h + file path: D:\projects new\vt tools\Manager + file base: typedefs + file ext: h + author: + + purpose: gBaumgart +*********************************************************************/ + + +#ifndef TYPEDEFS_H + #define TYPEDEFS_H + + #include "CKAll.h" + + + + #include + #include + #include +/* + The following template "Hashfunc" only meets the requests of std::map. the reason for it is the standard compare.(result : int, but bool is used) + + from XString.h: + + int operator == (const XBaseString& iStr) const + { return !Compare(iStr); } + + if i don´t use this help class i´ll get the following warning: + + " + D:\SDK\VC98\INCLUDE\functional(86) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning) + D:\SDK\VC98\INCLUDE\functional(86) : while compiling class-template member function 'bool __thiscall std::less::operator ()(const class XString &,const class XString &) const' + " + by call ZipJobList zili.find(XXX) + + + or use simply : + struct XStringCMP{ + bool operator() (const XString& p, const XString& q) const + { return strcmp(p.CStr(),q.CStr())<0; } + }; + */ + +template struct HashFunc{ + bool operator ()(const T& x,const T& y)const; +}; + + +//the XString special: +template <> struct HashFunc{ + bool operator ()(const XString& In1,const XString& In2)const{ + + return strcmp(In1.CStr(),In2.CStr())<0; + /* or : + size_t out = 0; + const char* key = In1.CStr(); + while (*key) out = (out <<1)^*key++;//an integer rep of a c-string + */ + } +}; + +/* + ZipJobList + +Keystring | Filelist + +...... +*/ + +typedef std::listXFileList; +typedef std::list::iterator XFileListIterator; + +typedef std::map >ZipJobList; +typedef std::map >::iterator ZiJoIt; + + +/************************************************************************/ +/* none zip stuff */ +/************************************************************************/ + +/************************************************************************/ +/* a workin array container */ +/************************************************************************/ +/* + template class fake_container{ + +public: + + //standard stuff: + typedef T value_type; + + typedef T* iterator; + + typedef const T*const_iterator; + typedef T& reference; + typedef const T& const_reference; + + + typedef const T* const_iterator; + T v[amount]; + operator T*() {return v;} + + //ops: + iterator& operator++(){return v+1;} + iterator& operator--(){return v-1;} + //.......................................................... + + //nice: + reference operator[] (ptrdiff_t i) { return v[i] ; } + const_reference operator[] (ptrdiff_t i) const { return v[i] ; } + + iterator begin() {return v;} + const_iterator begin() const {return v;} + iterator end() {return v+amount;} + const_iterator end() const {return v + amount;} + size_t size () const { return amount;} + + protected: + }; +*/ + + +/************************************************************************/ +/* tests */ +/************************************************************************/ + + +//this should become pointer array, but very strange +/* +template class Vector{ + T*v; + int sz; + + public: + Vector(); +// explicit Vector(int); + +// Vector(); +// operator T*() {return v;} + +//T& elem(int i){return v[i];} +//T& operator[](int i); +}; +*/ +//thats becomes a vector - void - pointer - special template +/* +template<> class Vector{ + void **p; + void *&operator[](int i); +}; +*/ + +/************************************************************************/ +/* the void* specialist: */ +/************************************************************************/ +/* +template class Vector : private Vector{ + + public: + typedef Vector Base; + + Vector() : Base(){} + puplicit Vector()(int i) : Base(i){} + T*elem(int i){ return static_cast(Base::elem(i));} + T*& operator[](int i){return static_cast(Base::operator [](i));} +}; + +*/ + +/* +template class Vector{ + T*v; + int sz; + + public: + Vector(); + explicit Vector(int); + operator T*() {return v;} + T& elem(int i){return v[i];} + T& operator[](int i); +}; +*/ +#endif diff --git a/usr/Include/Core/Manager/vtBaseManager.h b/usr/Include/Core/Manager/vtBaseManager.h new file mode 100644 index 0000000..addad99 --- /dev/null +++ b/usr/Include/Core/Manager/vtBaseManager.h @@ -0,0 +1,38 @@ +#ifndef VT_BASE_MANAGER_H__ +#define VT_BASE_MANAGER_H__ "$Id:$" + + +#include "BaseMacros.h" +#include "CKBaseManager.h" + + +class MODULE_API vtBaseManager : public CKBaseManager +{ + +public: + + virtual CKERROR OnCKInit()=0; + virtual CKERROR PostClearAll()=0; + virtual CKERROR PreSave()=0; + virtual CKERROR OnCKReset()=0; + virtual CKERROR PreProcess()=0; + + virtual CKDWORD GetValidFunctionsMask() { return CKMANAGER_FUNC_PostClearAll| + CKMANAGER_FUNC_OnCKInit| + CKMANAGER_FUNC_PreSave| + CKMANAGER_FUNC_PostLoad| + CKMANAGER_FUNC_OnCKReset| + CKMANAGER_FUNC_PreProcess; + } + virtual void RegisterParameters()=0; + virtual void RegisterVSL()=0; + + + vtBaseManager(CKContext *context,CKGUID guid,char* name) : CKBaseManager(context,guid,name) {}; + + ~vtBaseManager(){}; + +}; + +// CK2 VERSION ... +#endif diff --git a/usr/Include/Core/ResourceTools.h b/usr/Include/Core/ResourceTools.h new file mode 100644 index 0000000..f8e8c8c --- /dev/null +++ b/usr/Include/Core/ResourceTools.h @@ -0,0 +1,7 @@ +#include +#include "CKAll.h" + +HINSTANCE GetModulefromResource(HMODULE hModule,int name,char *tempfile); + +HMODULE GetParentModule(CK_PLUGIN_TYPE type,CKGUID guid); + diff --git a/usr/Include/Core/Timing.h b/usr/Include/Core/Timing.h new file mode 100644 index 0000000..d2dd45f --- /dev/null +++ b/usr/Include/Core/Timing.h @@ -0,0 +1,58 @@ +#ifndef TIMING_H +#define TIMING_H + +#if defined(__CELLOS_LV2__) || defined(_XBOX) || defined(LINUX) || defined(__PPCGEKKO__) + unsigned long timeGetTime(); +#elif defined(WIN32) || defined(_WIN64) + +#ifndef NOMINMAX +# define NOMINMAX +#endif + +#include + + +#endif + +#if defined(__CELLOS_LV2__) + +#include +#include + +typedef union _LARGE_INTEGER { + uint64_t QuadPart; +} LARGE_INTEGER; + +inline void QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount){ + SYS_TIMEBASE_GET(lpPerformanceCount->QuadPart); +} + +inline void QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency){ + lpFrequency->QuadPart = sys_time_get_timebase_frequency(); +} + +#endif //defined(__CELLOS_LV2__) + +#if defined(LINUX) + +#include +#include + +typedef union _LARGE_INTEGER { + uint64_t QuadPart; +} LARGE_INTEGER; + +inline void QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount){ + lpPerformanceCount->QuadPart = clock(); +} + +inline void QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency){ + lpFrequency->QuadPart = CLOCKS_PER_SEC; +} + +#endif // defined(LINUX) + + float getCurrentTime(); + float getElapsedTime(); + +#endif diff --git a/usr/Include/Core/UnzipDLL.h b/usr/Include/Core/UnzipDLL.h new file mode 100644 index 0000000..b7b344f --- /dev/null +++ b/usr/Include/Core/UnzipDLL.h @@ -0,0 +1,49 @@ +#ifndef UNZIPDLL_H + +#define UNZIPDLL_H + +#include "windows.h" +//#include "stdafx.h" +#include "ZCallBck.h" + +struct CUnzipParams +{ + HWND m_wndHandle; + void * m_pCaller; /* "self" referance of the Delphi form */ + /* This is passed back to us in the callback function + so we can direct the info to the proper form instance + - thanks to Dennis Passmore for this idea. */ + long int m_liVersion; /* version of DLL we expect to see */ + void* m_pfCallbackFunction; /* type def in ZCallBck.PAS */ + BOOL m_bTraceEnabled; + + /*============== Begin UnZip Flag section ============== */ + BOOL m_bPromptToOverwrite; // not used yet + char* m_pszZipPassword; // password pointer + BOOL m_bTest; // if true, test zipfile, don't save extracted files + BOOL m_bComments; // show zip comment (not supported yet) + BOOL m_bConvert; // if true, do ASCII/EBCDIC or EOL translation + + BOOL m_bQuiet; // DLL be quiet! + BOOL m_bVerboseEnabled; // verbose flag + BOOL m_bUpdate; // "update" (extract only newer files & brand new files) + BOOL m_bFreshen; // "freshen" (extract only newer files that already exist) + BOOL m_bDirectories; // if true, recreate dir structure + BOOL m_bOverwrite; // if true, overwrite existing (no asking) + + /* Count of filespecs to extract - don't forget to set this! */ + long int m_liFileCount; + /* ptr to zipfile name */ + char *m_pszArchiveFileName; + long int m_liSeven; /* pass a 7 here to validate struct size */ + /* Array of filenames contained in the ZIP archive */ + char* m_pszFileNames[MAX_FILES]; +}; + + +/* Main call to execute a ZIP add or Delete. This call returns the + number of files that were sucessfully operated on. */ +typedef DWORD (__stdcall *CUnzipDllExec)(CUnzipParams *pParams); +typedef DWORD (__stdcall *CGetUnzipDllVersion)(); + +#endif // UNZIPDLL_H \ No newline at end of file diff --git a/usr/Include/Core/VSLGlobalFunctions.h b/usr/Include/Core/VSLGlobalFunctions.h new file mode 100644 index 0000000..52e91f2 --- /dev/null +++ b/usr/Include/Core/VSLGlobalFunctions.h @@ -0,0 +1,25 @@ +#ifndef __VSL_GLOBAL_FUNCTIONS_H__ +#define __VSL_GLOBAL_FUNCTIONS_H__ + +#include "vtPhysXBase.h" + +/************************************************************************************************/ +/** @name Joints +*/ +//@{ + + +/** +\brief Quick access for #PhysicManager::getJoint + +\return pJoint* + +@see +*/ +pJoint*getJoint(CK3dEntity *referenceA,CK3dEntity *referenceB=NULL,JType type= JT_Any); + + +//@} + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/ZCallBck.h b/usr/Include/Core/ZCallBck.h new file mode 100644 index 0000000..8bbd721 --- /dev/null +++ b/usr/Include/Core/ZCallBck.h @@ -0,0 +1,27 @@ +#ifndef ZCALLBCK_H +#define ZCALLBCK_H + +//#include "StdAfx.h" +#include + +#define MAX_FILES 4096 + +#pragma pack (push) + +struct CZipCallbackData +{ + DWORD m_hwndHandle; + HWND m_pCaller; + long int m_liVersion; + BOOL m_bIsOperationZip; + long int m_liActionCode; + long int m_liErrorCode; + long int m_liFileSize; + char m_pszFileNameOrMsg[512]; +}; + +#pragma pack (pop) + +typedef BOOL (__stdcall *ZFunctionPtrType) (CZipCallbackData*); + +#endif ZCALLBCK_H // ZCALLBCK_H diff --git a/usr/Include/Core/ZipDLL.h b/usr/Include/Core/ZipDLL.h new file mode 100644 index 0000000..95e90ce --- /dev/null +++ b/usr/Include/Core/ZipDLL.h @@ -0,0 +1,124 @@ +#ifndef ZIPDLL_H +#define ZIPDLL_H + +#include "ZCallBck.h" +struct CZipParams { + + + + HWND m_hwndHandle; + /* "self" referance of the Delphi form */ + /* This is passed back to us in the callback function + so we can direct the info to the proper form instance + - thanks to Dennis Passmore for this idea. */ + void *m_pCaller; + long int m_liVersion; /* version of DLL we expect to see */ + ZFunctionPtrType m_pfCallbackFunction; /* type def in ZCallBck.PAS */ + BOOL m_bTraceEnabled; + + /*============== Begin Zip Flag section ============== */ + char *m_pszZipPassword; /* password pointer */ + BOOL m_bSuffix; /* not used yet */ + BOOL m_bEncrypt; /* Encrypt files to be added? */ + + /* include system and hidden files */ + BOOL m_bSystem; + + /* Include volume label */ + BOOL m_bVolume; + + /* Include extra file attributes (read-only, unix timestamps, etc) */ + BOOL m_bExtra; + + /* Do not add directory names to .ZIP archive */ + /* see also: fJunkDir */ + BOOL m_bNoDirEntries; + + /* Only add files newer a specified date */ + /* See the "Date" array below if you set this to TRUE */ + BOOL m_bDate; + + /* Give a little more information to the user via message boxes */ + BOOL m_bVerboseEnabled; + + /* Quiet operation - the DLL won't issue any messages at all. */ + /* Delphi program MUST handle ALL errors via it's callback function. */ + BOOL m_bQuiet; + + /* Compression level (0 - 9; 9=max, 0=none) */ + /* All of these levels are variations of deflate. */ + /* I strongly recommend you use one of 3 values here: + 0 = no compression, just store file + 3 = "fast" compression + 9 = "best" compression */ + long int m_bLevel; + + /* Try to compress files that appear to be already compressed + based on their extension: .zip, .arc, .gif, ... */ + BOOL m_bComprSpecial; + + /* translate text file end-of-lines */ + BOOL m_bCRLF_LF; + + /* junk the directory names */ + /* If true, this says not to save dirnames as separate entries, + in addition to being save with filenames. */ + /* see also: fNoDirEntries */ + BOOL m_bJunkDir; + + /* Recurse into subdirectories */ + BOOL m_bRecurse; + + /* Allow appending to a zip file */ + BOOL m_bGrow; + + /* Convert filenames to DOS 8x3 names - for compatibility + with PKUNZIP v2.04g, which doesn't understand long filenames */ + BOOL m_bForce; + + /* Delete orig files that were added or updated in zip file */ + /* This is a variation of Add */ + BOOL m_bMove; + + /* Delete specified files from zip file */ + BOOL m_bDeleteEntries; + + /* Update zip -- if true, rezip changed, and add new files in fspec */ + /* This is a variation of Add */ + BOOL m_bUpdate; + + /* Freshen zip -- if true, rezip all changed files in fspec */ + /* This is a variation of Add */ + BOOL m_bFreshen; + + /* junk the SFX prefix on the self-extracing .EXE archives */ + BOOL m_bJunkSFX; + + /* Set zip file time to time of newest file in it */ + BOOL m_bLatestTime; + + /*============== End Zip Flag section ============== */ + + /* Cutoff Date for Add-by-date; add files newer than this day */ + /* This is only used if the "fDate" option is TRUE */ + /* format = MMDDYY plus a trailing null */ + char m_cDate[8]; + + /* Count of files to add or delete - don't forget to set this! */ + long int m_liFileCount; + /* ptr to name of zip file */ + char *m_pszArchiveFileName; + long int m_liSeven; /* pass a 7 here to validate struct size */ + + /* Array of filenames contained in the ZIP archive */ + char* m_pszFileNames[MAX_FILES]; +}; + +/* + Main call to execute a ZIP add or Delete. This call returns the + number of files that were sucessfully operated on. +*/ +typedef DWORD (__stdcall *CZipDllExec)(CZipParams *pParams); +typedef DWORD (__stdcall *CGetZipDllVersion)(); + +#endif // ZIPDLL_H \ No newline at end of file diff --git a/usr/Include/Core/bginstancer.h b/usr/Include/Core/bginstancer.h new file mode 100644 index 0000000..0fd5370 --- /dev/null +++ b/usr/Include/Core/bginstancer.h @@ -0,0 +1,54 @@ +/******************************************************************** + created: 2006/22/06 + created: 22:06:2006 12:26 + filename: x:\junctions\ProjectRoot\current\vt_plugins\vt_toolkit\Behaviors\Generic\BGInstancer.h + file path: x:\junctions\ProjectRoot\current\vt_plugins\vt_toolkit\Behaviors\Generic + file base: BGInstancer + file ext: h + author: mc007 + + purpose: instancing of b-graphs per file +*********************************************************************/ + +#include "stdafx.h" + +#define BGWRAPPER_GUID CKGUID(0x35fb3204,0x6b59721c) + +// Parameters for BGWrapper +enum EBGWRAPPERPARAM + { + // local + EBGWRAPPERPARAM_PARAMETER_SCRIPT = 0, + EBGWRAPPERPARAM_PARAMETER_NAME = 1, + EBGWRAPPERPARAM_LOCAL_PARAMETER_COUNT, + }; + +class BGWrapper +{ + + public: + static CKObjectDeclaration* FillBehaviour( void ); + static CKERROR CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ); + static int BehaviourFunction( const CKBehaviorContext& behaviorContext ); + + private: + static CKERROR BGWrapperCB(const CKBehaviorContext& behContext); + + static BOOL HasIO(CKBehavior* pBeh); + static BOOL DeleteIO(CKBehavior* pBeh); + static BOOL CreateIO(CKBehavior* pBeh, CKBehavior* pScript); + static BOOL CheckIO(CKBehavior* pBeh, CKBehavior* pScript); + + static CKBehavior* BGLoader(CKSTRING fileName,const CKBehaviorContext& behContext); + + static void ActivateNextFrameSubBB(CKBehavior* scriptObject,BOOL &bActivateNextFrame); + static void DesactivateSubBB(CKBehavior* scriptObject); + static void OwnerSubBB(CKBehavior* scriptObject,CKBeObject*owner); + static void SetNewBG(CKBehavior *behaviour,CKBehavior *newBehavior); + static void DestroyCurrentBG(CKLevel* level,CKBehavior *behaviour,CKBehavior *scriptObject); + + + +}; + + diff --git a/usr/Include/Core/crypting.h b/usr/Include/Core/crypting.h new file mode 100644 index 0000000..f3a2c58 --- /dev/null +++ b/usr/Include/Core/crypting.h @@ -0,0 +1 @@ +int EncryptPassword(char* pcPassword); diff --git a/usr/Include/Core/gConfig.h b/usr/Include/Core/gConfig.h new file mode 100644 index 0000000..d40b95b --- /dev/null +++ b/usr/Include/Core/gConfig.h @@ -0,0 +1,22 @@ +/******************************************************************** + created: 2009/04/13 + created: 13:4:2009 21:58 + filename: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Include\Core\gConfig.h + file path: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Include\Core + file base: gConfig + file ext: h + author: Günter Baumgart + + purpose: Global configuration for this component +*********************************************************************/ +#ifndef __G_CONFIG_H__ +#define __G_CONFIG_H__ + +/*! +\brief Enables access from an external application. All related code needs to enabled + by this macro +*/ +//#define G_EXTERNAL_ACCESS + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/gblasyncblock.h b/usr/Include/Core/gblasyncblock.h new file mode 100644 index 0000000..f686b1f --- /dev/null +++ b/usr/Include/Core/gblasyncblock.h @@ -0,0 +1,24 @@ +#pragma once + +#include "stdafx.h" + +class ExeInThread +{ + public: + static CKObjectDeclaration * FillBehaviour( void ); + static int CallBack( const CKBehaviorContext& behaviorContext ); + static int BehaviourFunction( const CKBehaviorContext& behaviorContext ); + static CKERROR CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ); + + enum ThreadStatus { + Idle = 0, Requested = 2, Active = 3}; + + + friend unsigned int BlockingThreadFunction(void *arg); + + typedef struct ThreadInfo + { + CKBehavior* targetBeh; + int targetInputToActivate; + } AsyncThreadInfo; +}; diff --git a/usr/Include/Core/pCharacter/pBoxController.h b/usr/Include/Core/pCharacter/pBoxController.h new file mode 100644 index 0000000..8532109 --- /dev/null +++ b/usr/Include/Core/pCharacter/pBoxController.h @@ -0,0 +1,52 @@ +#ifndef __P_BOX_CONTROLLER_H__ +#define __P_BOX_CONTROLLER_H__ + +#include "pTypes.h" + +class BoxController; + +class pBoxController +{ +public: + + pBoxController(const NxControllerDesc& desc, NxScene* scene); + + virtual ~pBoxController(); + + void move(const VxVector& disp, int activeGroups, float minDist, int& collisionFlags, float sharpness, const pGroupsMask* groupsMask); + + //bool setPosition(const VxVector& position) { return setPos(position); } + pRigidBody* getBody() const; + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // NxpBoxController + const VxVector& getExtents() const; + bool setExtents(const VxVector& extents); + + void setStepOffset(const float offset); + + VxVector getPosition()const; + VxVector& getFilteredPosition(); + bool getWorldBox(VxBbox& box) const; + void setCollision(bool enabled); + //virtual void setInteraction(NxCCTInteractionFlag flag) { Controller::setInteraction(flag); } + //virtual NxCCTInteractionFlag getInteraction() const { return Controller::getInteraction(); } + + //vi//rtual void reportSceneChanged(); + //virtual void* getUserData() const { return userData; } + +private: + + BoxController *mBoxController; + + +}; + +#endif +//AGCOPYRIGHTBEGIN +/////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2005 AGEIA Technologies. +// All rights reserved. www.ageia.com +/////////////////////////////////////////////////////////////////////////// +//AGCOPYRIGHTEND diff --git a/usr/Include/Core/pCloth/pCloth.h b/usr/Include/Core/pCloth/pCloth.h new file mode 100644 index 0000000..56540c8 --- /dev/null +++ b/usr/Include/Core/pCloth/pCloth.h @@ -0,0 +1,870 @@ +#ifndef __P_CLOTH_H__ +#define __P_CLOTH_H__ + +#include "vtPhysXBase.h" + + + + +/** \addtogroup Cloth +@{ +*/ + + + +/** +brief2 Class for clothes. +*/ +class MODULE_API pCloth +{ +public: + + + /************************************************************************/ + /* */ + /************************************************************************/ + + void releaseReceiveBuffers(); + void allocateClothReceiveBuffers(int numVertices, int numTriangles); + + CK_ID getEntityID() const { return mEntityID; } + void setEntityID(CK_ID val) { mEntityID = val; } + + NxCloth * getCloth() const { return mCloth; } + void setCloth(NxCloth * val) { mCloth = val; } + + pCloth(); + virtual ~pCloth(); + + NxMeshData * getReceiveBuffers() const { return mReceiveBuffers; } + void setReceiveBuffers(NxMeshData * val) { mReceiveBuffers = val; } + + bool cookMesh(NxClothMeshDesc* desc); + + void releaseMeshDescBuffers(const NxClothMeshDesc* desc); + bool generateMeshDesc(pClothDesc cDesc,NxClothMeshDesc *desc, CKMesh*mesh); + + pWorld * getWorld() const { return mWorld; } + void setWorld(pWorld * val) { mWorld = val; } + + NxClothMesh * getClothMesh() const { return mClothMesh; } + void setClothMesh(NxClothMesh * val) { mClothMesh = val; } + + void updateVirtoolsMesh(); + + + + /************************************************************************/ + /* */ + /************************************************************************/ + + /** + \brief Sets the cloth bending stiffness in the range from 0 to 1. + + \param[in] stiffness The stiffness of this cloth. + @see pClothDesc.bendingStiffness getBendingStiffness() + */ + void setBendingStiffness(float stiffness); + + /** + \brief Retrieves the cloth bending stiffness. + + \return Bending stiffness of cloth. + @see pClothDesc.bendingStiffness setBendingStiffness() + */ + float getBendingStiffness() const; + + /** + \brief Sets the cloth stretching stiffness in the range from 0 to 1. + + Note: The stretching stiffness must be larger than 0. + + \param[in] stiffness Stiffness of cloth. + @see pClothDesc.stretchingStiffness getStretchingStiffness() + */ + void setStretchingStiffness(float stiffness); + + /** + \brief Retrieves the cloth stretching stiffness. + + \return stretching stiffness of cloth. + + @see pClothDesc.stretchingStiffness setStretchingStiffness() + */ + float getStretchingStiffness() const; + + /** + \brief Sets the damping coefficient in the range from 0 to 1. + + \param[in] dampingCoefficient damping coefficient of cloth. + @see pClothDesc.dampingCoefficient getDampingCoefficient() + */ + void setDampingCoefficient(float dampingCoefficient); + + /** + \brief Retrieves the damping coefficient. + + \return damping coefficient of cloth. + @see pClothDesc.dampingCoefficient setDampingCoefficient() + */ + float getDampingCoefficient() const; + + /** + \brief Sets the cloth friction coefficient in the range from 0 to 1. + + \param[in] friction The friction of the cloth. + @see pClothDesc.friction getFriction() + */ + void setFriction(float friction); + + /** + \brief Retrieves the cloth friction coefficient. + + \return Friction coefficient of cloth. + @see pClothDesc.friction setFriction() + */ + float getFriction() const; + + /** + \brief Sets the cloth pressure coefficient (must be non negative). + + \param[in] pressure The pressure applied to the cloth. + + @see pClothDesc.pressure getPressure() + */ + void setPressure(float pressure); + + /** + \brief Retrieves the cloth pressure coefficient. + + \return Pressure of cloth. + @see pClothDesc.pressure setPressure() + */ + float getPressure() const; + + /** + \brief Sets the cloth tear factor (must be larger than one). + + \param[in] factor The tear factor for the cloth + + @see pClothDesc.tearFactor getTearFactor() + */ + void setTearFactor(float factor); + + /** + \brief Retrieves the cloth tear factor. + + \return tear factor of cloth. + @see pClothDesc.tearFactor setTearFactor() + */ + float getTearFactor() const; + + /** + \brief Sets the cloth attachment tear factor (must be larger than one). + + \param[in] factor The attachment tear factor for the cloth + @see pClothDesc.attachmentTearFactor getAttachmentTearFactor() + */ + void setAttachmentTearFactor(float factor); + + /** + \brief Retrieves the attachment cloth tear factor. + + \return tear attachment factor of cloth. + @see pClothDesc.attachmentTearFactor setAttachmentTearFactor() + */ + float getAttachmentTearFactor() const; + + /** + \brief Sets the cloth thickness (must be positive). + + \param[in] thickness The thickness of the cloth. + @see pClothDesc.thickness getThickness() + */ + void setThickness(float thickness); + + /** + \brief Gets the cloth thickness. + + \return thickness of cloth. + @see pClothDesc.thickness setThickness() + */ + float getThickness() const; + + /** + \brief Gets the cloth density. + + \return density of cloth. + @see pClothDesc.density + */ + float getDensity() const; + + /** + \brief Gets the relative grid spacing for the broad phase. + The cloth is represented by a set of world aligned cubical cells in broad phase. + The size of these cells is determined by multiplying the length of the diagonal + of the AABB of the initial cloth size with this constant. + + \return relative grid spacing. + @see pClothDesc.relativeGridSpacing + */ + float getRelativeGridSpacing() const; + + /** + \brief Retrieves the cloth solver iterations. + + \return solver iterations of cloth. + @see pClothDesc.solverIterations setSolverIterations() + */ + int getSolverIterations() const; + + /** + \brief Sets the cloth solver iterations. + + \param[in] iterations The new solver iteration count for the cloth. + @see pClothDesc.solverIterations getSolverIterations() + */ + void setSolverIterations(int iterations); + + /** + \brief Returns a world space AABB enclosing all cloth points. + + \param[out] bounds Retrieves the world space bounds. + @see NxBounds3 + */ + void getWorldBounds(VxBbox & bounds) const; + + /** + \brief Attaches the cloth to a shape. All cloth points currently inside the shape are attached. + + \note This method only works with primitive and convex shapes. Since the inside of a general + triangle mesh is not clearly defined. + + \param[in] shape Shape to which the cloth should be attached to. + \param[in] attachmentFlags One or two way interaction, tearable or non-tearable + @see NxClothAttachmentFlag freeVertex() attachToCollidingShapes() + */ + void attachToShape(CKBeObject *shape, int attachmentFlags); + + /** + \brief Attaches the cloth to all shapes, currently colliding. + + \note This method only works with primitive and convex shapes. Since the inside of a general + triangle mesh is not clearly defined. + + \param[in] attachmentFlags One or two way interaction, tearable or non-tearable + @see NxClothAttachmentFlag pClothDesc.attachmentTearFactor pClothDesc.attachmentResponseCoefficient freeVertex() + */ + void attachToCollidingShapes(int attachmentFlags); + + /** + \brief Detaches the cloth from a shape it has been attached to before. + + If the cloth has not been attached to the shape before, the call has no effect. + + \param[in] shape Shape from which the cloth should be detached. + @see NxClothAttachmentFlag pClothDesc.attachmentTearFactor pClothDesc.attachmentResponseCoefficient freeVertex() attachToShape() + */ + void detachFromShape(CKBeObject *shape); + + /** + \brief Attaches a cloth vertex to a local position within a shape. + + \param[in] vertexId Index of the vertex to attach. + \param[in] shape Shape to attach the vertex to. + \param[in] localPos The position relative to the pose of the shape. + \param[in] attachmentFlags One or two way interaction, tearable or non-tearable + + Platform: + \li PC SW: Yes + \li PPU : Yes + \li PS3 : Yes + \li XB360: Yes + + @see NxShape freeVertex() NxClothAttachmentFlag attachToShape() + */ + void attachVertexToShape(int vertexId, CKBeObject *shape, const VxVector &localPos, int attachmentFlags); + + /** + \brief Attaches a cloth vertex to a position in world space. + + \param[in] vertexId Index of the vertex to attach. + \param[in] pos The position in world space. + @see pClothAttachmentFlag pClothDesc.attachmentTearFactor pClothDesc.attachmentResponseCoefficient freeVertex() attachToShape() + */ + void attachVertexToGlobalPosition(const int vertexId, const VxVector &pos); + + /** + \brief Frees a previously attached cloth point. + + \param[in] vertexId Index of the vertex to free. + @see attachVertexToGlobalPosition() attachVertexToShape() detachFromShape() + */ + void freeVertex(const int vertexId); + + /** + \brief Changes the weight of a vertex in the cloth solver for a period of time. + + If this method is called for some vertex, the cloth solver will, during a time + period of length expirationTime, assign a different weight to the vertex + while internal cloth constraints (i.e. bending & stretching) are being resolved. + + With a high dominanceWeight, the modified vertex will force neighboring vertices + to strongly accommodate their positions while its own is kept fairly constant. + The reverse holds for smaller dominanceWeights. + + Using a dominanceWeight of +infinity has a similar effect as temporarily attaching + the vertex to a global position. However, unlike using attachments, the velocity + of the vertex is kept intact when using this method. + + \note The current implementation will not support the full range of dominanceWeights. + All dominanceWeights > 0.0 are treated equally as being +infinity. + + \note An expiration time of 0.0 is legal and will result in dominance being + applied throughout one substep before being discarded immediately. + + \note Having a large number of vertices dominant at once may result in a performance penalty. + + \param[in] vertexId Index of the vertex. + \param[in] expirationTime Time period where dominance will be active for this vertex. + \param[in] dominanceWeight Dominance weight for this vertex. + + @see attachVertexToGlobalPosition() + */ + void dominateVertex(int vertexId, float expirationTime, float dominanceWeight); + + /** + \brief Return the attachment status of the given vertex. + + \param[in] vertexId Index of the vertex. + + @see getVertexAttachmentShape() getVertexAttachmentPosition() + */ + xU16 getVertexAttachmentStatus(int vertexId) const; + + /** + \brief Returns the pointer to an attached shape pointer of the given vertex. + + If the vertex is not attached or attached to a global position, NULL is returned. + + \param[in] vertexId Index of the vertex. + + @see getVertexAttachmentStatus() getVertexAttachmentPosition() + */ + NxShape* getVertexAttachmentShape(int vertexId) const; + + /** + \brief Returns the attachment position of the given vertex. + + If the vertex is attached to shape, the position local to the shape's pose is returned. + If the vertex is not attached, the return value is undefined. + + \param[in] vertexId Index of the vertex. + @see getVertexAttachmentStatus() getVertexAttachmentShape() + */ + VxVector getVertexAttachmentPosition(int vertexId) const; + + /** + \brief Attaches the cloth to an actor. + + \note Call this function only once right after the cloth is created. + Turning cloth into metal and vice versa during the simulation is not recommended. + + \note This feature is well suited for volumetric objects like barrels. + It cannot handle two dimensional flat pieces well. + + After this call, the cloth is infinitely stiff between collisions and simply + moves with the actor. At impacts with an impact impulse greater than impulseThreshold, + the cloth is plastically deformed. Thus, a cloth with a core behaves like a piece of metal. + + The core actor's geometry is adjusted automatically. Its size also depends on the + cloth thickness. Thus, it is recommended to choose small values for the thickness. + At impacts, colliding objects are moved closer to the cloth by the value provided in + penetrationDepth which causes a more dramatic collision result. + + The core actor must have at least one shape, and currently supported shapes are + spheres, capsules, boxes and compounds of spheres. + It is recommended to specify the density rather than the mass of the core body. + This way the mass and inertia tensor are updated when the core deforms. + + The maximal deviation of cloth particles from their initial positions + (modulo the global rigid body transforms translation and rotation) can be + specified via the parameter maxDeformationDistance. Setting this parameter to + zero means that the deformation is not limited. + + \param actor The core actor to attach the cloth to. + \param impulseThreshold Threshold for when deformation is allowed. + \param penetrationDepth Amount by which colliding objects are brought closer to the cloth. + \param maxDeformationDistance Maximum deviation of cloth particles from initial position. + + */ + void attachToCore(CK3dEntity *body, float impulseThreshold, float penetrationDepth, float maxDeformationDistance); + + /** + \brief Tears the cloth at a given vertex. + + First the vertex is duplicated. The triangles on one side of the split plane keep + the original vertex. For all triangles on the opposite side the original vertex is + replaced by the new one. The split plane is defined by the world location of the + vertex and the normal provided by the user. + + Note: TearVertex performs a user defined vertex split in contrast to an automatic split + that is performed when the flag NX_CLF_TEARABLE is set. Therefore, tearVertex works + even if NX_CLF_TEARABLE is not set in pClothDesc.flags. + + Note: For tearVertex to work, the clothMesh has to be cooked with the flag + NX_CLOTH_MESH_TEARABLE set in NxClothMeshDesc.flags. + + \param[in] vertexId Index of the vertex to tear. + \param[in] normal The normal of the split plane. + \return true if the split had an effect (i.e. there were triangles on both sides of the split plane) + + @see NxClothFlag, NxClothMeshFlags, pClothDesc.flags NxSimpleTriangleMesh.flags + + Platform: + \li PC SW: Yes + \li PPU : Yes + \li PS3 : Yes + \li XB360: Yes + */ + bool tearVertex(const int vertexId, const VxVector &normal); + + /** + \brief Executes a raycast against the cloth. + + \param[in] worldRay The ray in world space. + \param[out] hit The hit position. + \param[out] vertexId Index to the nearest vertex hit by the raycast. + + \return true if the ray hits the cloth. + */ + //BOOL raycast(const NxRay& worldRay, VxVector &hit, int &vertexId); + + /** + \brief Sets which collision group this cloth is part of. + + \param[in] collisionGroup The collision group for this cloth. + + @see NxCollisionGroup + */ + void setGroup(int collisionGroup); + + /** + \brief Retrieves the value set with #setGroup(). + + \return The collision group this cloth belongs to. + + @see NxCollisionGroup + */ + int getGroup() const; + + /** + \brief Sets 128-bit mask used for collision filtering. + + \param[in] groupsMask The group mask to set for the cloth. + @see getGroupsMask() NxGroupsMask + */ + void setGroupsMask(const pGroupsMask& groupsMask); + + /** + \brief Sets 128-bit mask used for collision filtering. + + \return The group mask for the cloth. + + @see setGroupsMask() NxGroupsMask + */ + const pGroupsMask getGroupsMask() const; + + + /** + \brief Sets the valid bounds of the cloth in world space. + + If the flag NX_CLF_VALIDBOUNDS is set, these bounds defines the volume + outside of which cloth particle are automatically removed from the simulation. + + \param[in] validBounds The valid bounds. + + @see pClothDesc.validBounds getValidBounds() NxBounds3 + */ + void setValidBounds(const VxBbox& validBounds); + + /** + \brief Returns the valid bounds of the cloth in world space. + + \param[out] validBounds The valid bounds. + + + @see pClothDesc.validBounds setValidBounds() NxBounds3 + */ + void getValidBounds(NxBounds3& validBounds) const; + + /** + \brief Sets the position of a particular vertex of the cloth. + + \param[in] position New position of the vertex. + \param[in] vertexId Index of the vertex. + + @see getPosition() setPositions() getPositions() setVelocity() getVelocity() getNumberOfParticles() + */ + void setPosition(const VxVector& position, int vertexId); + + /** + \brief Sets the positions of the cloth. + + The user must supply a buffer containing all positions (i.e same number of elements as number of particles). + + \param[in] buffer The user supplied buffer containing all positions for the cloth. + \param[in] byteStride The stride in bytes between the position vectors in the buffer. Default is size of VxVector. + @see getPositions() setVelocities() getVelocities() getNumberOfParticles() + */ + void setPositions(void* buffer, int byteStride = sizeof(VxVector)); + + /** + \brief Gets the position of a particular vertex of the cloth. + + \param[in] vertexId Index of the vertex. + @see setPosition() setPositions() getPositions() setVelocity() getVelocity() getNumberOfParticles() + */ + VxVector getPosition(int vertexId) const; + + /** + \brief Gets the positions of the cloth. + + The user must supply a buffer large enough to hold all positions (i.e same number of elements as number of particles). + + \param[in] buffer The user supplied buffer to hold all positions of the cloth. + \param[in] byteStride The stride in bytes between the position vectors in the buffer. Default is size of VxVector. + @see setPositions() setVelocities() getVelocities() getNumberOfParticles() + */ + void getPositions(void* buffer, int byteStride = sizeof(VxVector)); + + /** + \brief Sets the velocity of a particular vertex of the cloth. + + \param[in] position New velocity of the vertex. + \param[in] vertexId Index of the vertex. + @see setPosition() getPosition() getVelocity() setVelocities() getVelocities() getNumberOfParticles() + */ + void setVelocity(const VxVector& velocity, int vertexId); + + /** + \brief Sets the velocities of the cloth. + + The user must supply a buffer containing all velocities (i.e same number of elements as number of particles). + + \param[in] buffer The user supplied buffer containing all velocities for the cloth. + \param[in] byteStride The stride in bytes between the velocity vectors in the buffer. Default is size of VxVector. + @see getVelocities() setPositions() getPositions() getNumberOfParticles() + */ + void setVelocities(void* buffer, int byteStride = sizeof(VxVector)); + + /** + \brief Gets the velocity of a particular vertex of the cloth. + + \param[in] vertexId Index of the vertex. + @see setPosition() getPosition() setVelocity() setVelocities() getVelocities() getNumberOfParticles() + */ + VxVector getVelocity(int vertexId) const; + + + /** + \brief Sets the collision response coefficient. + + \param[in] coefficient The collision response coefficient (0 or greater). + @see pClothDesc.collisionResponseCoefficient getCollisionResponseCoefficient() + */ + void setCollisionResponseCoefficient(float coefficient); + + /** + \brief Retrieves the collision response coefficient. + + \return The collision response coefficient. + + @see pClothDesc.collisionResponseCoefficient setCollisionResponseCoefficient() + */ + float getCollisionResponseCoefficient() const; + + /** + \brief Sets the attachment response coefficient + + \param[in] coefficient The attachment response coefficient in the range from 0 to 1. + @see pClothDesc.attachmentResponseCoefficient getAttachmentResponseCoefficient() + */ + void setAttachmentResponseCoefficient(float coefficient); + + /** + \brief Retrieves the attachment response coefficient + + \return The attachment response coefficient. + + @see pClothDesc.attachmentResponseCoefficient setAttachmentResponseCoefficient() + */ + float getAttachmentResponseCoefficient() const; + + /** + \brief Sets the response coefficient for collisions from fluids to this cloth + + \param[in] coefficient The response coefficient + @see pClothDesc.fromFluidResponseCoefficient getFromFluidResponseCoefficient() + */ + void setFromFluidResponseCoefficient(float coefficient); + + /** + \brief Retrieves response coefficient for collisions from fluids to this cloth + + \return The response coefficient. + @see pClothDesc.fromFluidResponseCoefficient setFromFluidResponseCoefficient() + */ + float getFromFluidResponseCoefficient() const; + + /** + \brief Sets the response coefficient for collisions from this cloth to fluids + + \param[in] coefficient The response coefficient + + @see pClothDesc.toFluidResponseCoefficient getToFluidResponseCoefficient() + */ + void setToFluidResponseCoefficient(float coefficient); + + /** + \brief Retrieves response coefficient for collisions from this cloth to fluids + + \return The response coefficient. + + @see pClothDesc.toFluidResponseCoefficient setToFluidResponseCoefficient() + */ + float getToFluidResponseCoefficient() const; + + /** + \brief Sets an external acceleration which affects all non attached particles of the cloth + + \param[in] acceleration The acceleration vector (unit length / s^2) + @see pClothDesc.externalAcceleration getExternalAcceleration() + */ + void setExternalAcceleration(VxVector acceleration); + + /** + \brief Retrieves the external acceleration which affects all non attached particles of the cloth + + \return The acceleration vector (unit length / s^2) + + @see pClothDesc.externalAcceleration setExternalAcceleration() + */ + VxVector getExternalAcceleration() const; + + /** + \brief If the NX_CLF_ADHERE flag is set the cloth moves partially in the frame + of the attached actor. + + This feature is useful when the cloth is attached to a fast moving character. + In that case the cloth adheres to the shape it is attached to while only + velocities below the parameter minAdhereVelocity are used for secondary effects. + + \param[in] velocity The minimal velocity for cloth to adhere (unit length / s) + + @see pClothDesc.minAdhereVelocity getMinAdhereVelocity() + */ + void setMinAdhereVelocity(float velocity); + + /** + \brief If the NX_CLF_ADHERE flag is set the cloth moves partially in the frame + of the attached actor. + + This feature is useful when the cloth is attached to a fast moving character. + In that case the cloth adheres to the shape it is attached to while only + velocities below the parameter minAdhereVelocity are used for secondary effects. + + \return Returns the minimal velocity for cloth to adhere (unit length / s) + @see pClothDesc.minAdhereVelocity setMinAdhereVelocity() + */ + float getMinAdhereVelocity() const; + + /** + \brief Sets an acceleration acting normal to the cloth surface at each vertex. + + \param[in] acceleration The acceleration vector (unit length / s^2) + @see pClothDesc.windAcceleration getWindAcceleration() + */ + void setWindAcceleration(VxVector acceleration); + + /** + \brief Retrieves the acceleration acting normal to the cloth surface at each vertex. + + \return The acceleration vector (unit length / s^2) + @see pClothDesc.windAcceleration setWindAcceleration() + */ + VxVector getWindAcceleration() const; + + /** + \brief Returns true if this cloth is sleeping. + + When a cloth does not move for a period of time, it is no longer simulated in order to save time. This state + is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object, + or one of its properties is changed by the user, the entire sleep mechanism should be transparent to the user. + + If a cloth is asleep after the call to NxScene::fetchResults() returns, it is guaranteed that the position of the cloth + vertices was not changed. You can use this information to avoid updating dependent objects. + + \return True if the cloth is sleeping. + @see isSleeping() getSleepLinearVelocity() wakeUp() putToSleep() + */ + bool isSleeping() const; + + /** + \brief Returns the linear velocity below which a cloth may go to sleep. + + A cloth whose linear velocity is above this threshold will not be put to sleep. + + @see isSleeping + + \return The threshold linear velocity for sleeping. + @see isSleeping() getSleepLinearVelocity() wakeUp() putToSleep() setSleepLinearVelocity() + */ + float getSleepLinearVelocity() const; + + /** + \brief Sets the linear velocity below which a cloth may go to sleep. + + A cloth whose linear velocity is above this threshold will not be put to sleep. + + If the threshold value is negative, the velocity threshold is set using the NxPhysicsSDK's + NX_DEFAULT_SLEEP_LIN_VEL_SQUARED parameter. + + \param[in] threshold Linear velocity below which a cloth may sleep. Range: (0,inf] + @see isSleeping() getSleepLinearVelocity() wakeUp() putToSleep() + */ + void setSleepLinearVelocity(float threshold); + + /** + \brief Wakes up the cloth if it is sleeping. + + The wakeCounterValue determines how long until the cloth is put to sleep, a value of zero means + that the cloth is sleeping. wakeUp(0) is equivalent to NxCloth::putToSleep(). + + \param[in] wakeCounterValue New sleep counter value. Range: [0,inf] + @see isSleeping() getSleepLinearVelocity() putToSleep() + */ + void wakeUp(float wakeCounterValue = pSLEEP_INTERVAL); + + /** + \brief Forces the cloth to sleep. + + The cloth will fall asleep. + @see isSleeping() getSleepLinearVelocity() wakeUp() + */ + void putToSleep(); + + /** + \brief Sets the flags, a combination of the bits defined by the enum ::NxClothFlag. + + \param[in] flags #NxClothFlag combination. + @see pClothDesc.flags NxClothFlag getFlags() + */ + void setFlags(int flags); + + /** + \brief Retrieves the flags. + + \return The cloth flags. + @see pClothDesc.flags NxClothFlag setFlags() + */ + int getFlags() const; + + /** + \brief Sets a name string for the object that can be retrieved with getName(). + + This is for debugging and is not used by the SDK. The string is not copied by + the SDK, only the pointer is stored. + + \param[in] name String to set the objects name to. + @see getName() + */ + void setName(const char* name); + + /** + \brief Applies a force (or impulse) defined in the global coordinate frame, to a particular + vertex of the cloth. + + Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + + ::NxForceMode determines if the force is to be conventional or impulsive. + + \param[in] force Force/impulse to add, defined in the global frame. Range: force vector + \param[in] vertexId Number of the vertex to add the force at. Range: position vector + \param[in] mode The mode to use when applying the force/impulse + (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange) + @see ForceMode + */ + void addForceAtVertex(const VxVector& force, int vertexId, ForceMode mode = FM_Force); + + /** + \brief Applies a radial force (or impulse) at a particular position. All vertices + within radius will be affected with a quadratic drop-off. + + Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + + ::NxForceMode determines if the force is to be conventional or impulsive. + + \param[in] position Position to apply force at. + \param[in] magnitude Magnitude of the force/impulse to apply. + \param[in] radius The sphere radius in which particles will be affected. Range: position vector + \param[in] mode The mode to use when applying the force/impulse + (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange). + @see ForceMode + */ + void addForceAtPos(const VxVector& position, float magnitude, float radius, ForceMode mode = FM_Force); + + /** + \brief Applies a directed force (or impulse) at a particular position. All vertices + within radius will be affected with a quadratic drop-off. + + Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + + ::NxForceMode determines if the force is to be conventional or impulsive. + + \param[in] position Position to apply force at. + \param[in] force Force to apply. + \param[in] radius The sphere radius in which particles will be affected. Range: position vector + \param[in] mode The mode to use when applying the force/impulse + (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange). + @see ForceMode + */ + void addDirectedForceAtPos(const VxVector& position, const VxVector& force, float radius, ForceMode mode = FM_Force); + + /** + \brief Finds triangles touching the input bounds. + + \warning This method returns a pointer to an internal structure using the indices member. Hence the + user should use or copy the indices before calling any other API function. + + \param[in] bounds Bounds to test against in world space. Range: See #NxBounds3 + \param[out] nb Retrieves the number of triangle indices touching the AABB. + \param[out] indices Returns an array of touching triangle indices. + The triangle indices correspond to the triangles referenced to by pClothDesc.meshdata (#NxMeshData). + Triangle i has the vertices 3i, 3i+1 and 3i+2 in the array NxMeshData.indicesBegin. + \return True if there is an overlap. + + @see NxBounds3 pClothDesc NxMeshData + */ + bool overlapAABBTriangles(const NxBounds3& bounds, int& nb, const int*& indices) const; + + + +protected: +private: + NxMeshData *mReceiveBuffers; + + CK_ID mEntityID; + NxCloth *mCloth; + NxClothMesh *mClothMesh; + + pWorld *mWorld; +}; + +/** @} */ + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pCloth/pClothFlags.h b/usr/Include/Core/pCloth/pClothFlags.h new file mode 100644 index 0000000..9ba3a3d --- /dev/null +++ b/usr/Include/Core/pCloth/pClothFlags.h @@ -0,0 +1,237 @@ +#include "pTypes.h" + + +/** \addtogroup Cloth +@{ +*/ +//! Collection of flags describing the behavior of a cloth object. +enum pClothFlag +{ + /** + \brief Enable/disable pressure simulation. + Note: Pressure simulation only produces meaningful results for closed meshes. + */ + PCF_Pressure = (1<<0), + + /** + \brief Makes the cloth static. + */ + PCF_Static = (1<<1), + /** + \brief + PCF_Static = (1<<1),/*!cloth interaction (one way). + + With this flag set, cloth->object interaction is turned on as well. + */ + PCAF_ClothAttachmentTwoway = (1<<0), + + /** + \brief When this flag is set, the attachment is tearable. + + \note If the cloth is attached to a dynamic shape using two way interaction + half way torn attachments can generate unexpected impluses on the shape. + To prevent this, only attach one row of cloth vertices to the shape. + @see pClothDesc.attachmentTearFactor + */ + PCAF_ClothAttachmentTearable = (1<<1), +}; + +/** @} */ \ No newline at end of file diff --git a/usr/Include/Core/pCloth/pClothTypes.h b/usr/Include/Core/pCloth/pClothTypes.h new file mode 100644 index 0000000..aa0d3d7 --- /dev/null +++ b/usr/Include/Core/pCloth/pClothTypes.h @@ -0,0 +1,367 @@ +#ifndef __PCLOTHTYPES_H__ +#define __PCLOTHTYPES_H__ + + +#include "pClothFlags.h" + + +/** \addtogroup Cloth +@{ +*/ + +/** +\brief Descriptor class for pCloth. +*/ +class MODULE_API pClothDesc +{ +public: + + /** + \brief Thickness of the cloth. + + The thickness is usually a fraction of the overall extent of the cloth and + should not be set to a value greater than that. A good value is the maximal + distance between two adjacent cloth particles in their rest pose. Visual + artifacts or collision problems may appear if the thickness is too small. + + Default: 0.01
+ Range: [0,inf) + + @see pCloth.setThickness() + */ + float thickness; + + /** + \brief Density of the cloth (mass per area). + + Default: 1.0
+ Range: (0,inf) + */ + float density; + + /** + \brief Bending stiffness of the cloth in the range 0 to 1. + + Only has an effect if the flag PCF_Bending is set. + + Default: 1.0
+ Range: [0,1] + + @see PCF_Bending pCloth.setBendingStiffness() + */ + float bendingStiffness; + + /** + \brief Stretching stiffness of the cloth in the range 0 to 1. + + Note: stretching stiffness must be larger than 0. + + Default: 1.0
+ Range: (0,1] + + @see pCloth.setStretchingStiffness() + */ + float stretchingStiffness; + + /** + \brief Spring damping of the cloth in the range 0 to 1. + + Only has an effect if the flag PCF_Damping is set. + + Default: 0.5
+ Range: [0,1] + + @see PCF_Damping pCloth.setDampingCoefficient() + */ + float dampingCoefficient; + + /** + \brief Friction coefficient in the range 0 to 1. + + Defines the damping of the velocities of cloth particles that are in contact. + + Default: 0.5
+ Range: [0,1] + + @see pCloth.setFriction() + */ + float friction; + + /** + \brief If the flag PCF_Pressure is set, this variable defines the volume + of air inside the mesh as volume = pressure * restVolume. + + For pressure < 1 the mesh contracts w.r.t. the rest shape + For pressure > 1 the mesh expands w.r.t. the rest shape + + Default: 1.0
+ Range: [0,inf) + + @see PCF_pressure pCloth.setPressure() + */ + float pressure; + + /** + \brief If the flag PCF_Tearable is set, this variable defines the + elongation factor that causes the cloth to tear. + + Must be larger than 1. + Make sure meshData.maxVertices and the corresponding buffers + in meshData are substantially larger (e.g. 2x) than the number + of original vertices since tearing will generate new vertices. + + When the buffer cannot hold the new vertices anymore, tearing stops. + + Default: 1.5
+ Range: (1,inf) + + @see pCloth.setTearFactor() + */ + float tearFactor; + + /** + \brief Defines a factor for the impulse transfer from cloth to colliding rigid bodies. + + Only has an effect if PCF_CollisionTwoWay is set. + + Default: 0.2
+ Range: [0,inf) + + @see PCF_CollisionTwoWay pCloth.setCollisionResponseCoefficient() + */ + float collisionResponseCoefficient; + + /** + \brief Defines a factor for the impulse transfer from cloth to attached rigid bodies. + + Only has an effect if the mode of the attachment is set to nx_cloth_attachment_twoway. + + Default: 0.2
+ Range: [0,1] + + @see pCloth.attachToShape pCloth.attachToCollidingShapes pCloth.attachVertexToShape pCloth.setAttachmentResponseCoefficient() + */ + float attachmentResponseCoefficient; + + /** + \brief If the flag nx_cloth_attachment_tearable is set in the attachment method of pCloth, + this variable defines the elongation factor that causes the attachment to tear. + + Must be larger than 1. + + Default: 1.5
+ Range: (1,inf) + + @see pCloth.setAttachmentTearFactor() pCloth.attachToShape pCloth.attachToCollidingShapes pCloth.attachVertexToShape + + */ + float attachmentTearFactor; + + /** + \brief Defines a factor for the impulse transfer from this cloth to colliding fluids. + + Only has an effect if the PCF_FluidCollision flag is set. + + Default: 1.0
+ Range: [0,inf) + + Note: Large values can cause instabilities + + @see pClothDesc.flags pClothDesc.fromFluidResponseCoefficient + */ + float toFluidResponseCoefficient; + + /** + \brief Defines a factor for the impulse transfer from colliding fluids to this cloth. + + Only has an effect if the PCF_FluidCollision flag is set. + + Default: 1.0
+ Range: [0,inf) + + Note: Large values can cause instabilities + + @see pClothDesc.flags pClothDesc.ToFluidResponseCoefficient + */ + float fromFluidResponseCoefficient; + + /** + \brief If the PCF_Adhere flag is set the cloth moves partially in the frame + of the attached actor. + + This feature is useful when the cloth is attached to a fast moving character. + In that case the cloth adheres to the shape it is attached to while only + velocities below the parameter minAdhereVelocity are used for secondary effects. + + Default: 1.0 + Range: [0,inf) + + @see PCF_ADHERE + */ + + float minAdhereVelocity; + + /** + \brief Number of solver iterations. + + Note: Small numbers make the simulation faster while the cloth gets less stiff. + + Default: 5 + Range: [1,inf) + + @see pCloth.setSolverIterations() + */ + + unsigned int solverIterations; + + /** + \brief External acceleration which affects all non attached particles of the cloth. + + Default: (0,0,0) + + @see pCloth.setExternalAcceleration() + */ + VxVector externalAcceleration; + + /** + \brief Acceleration which acts normal to the cloth surface at each vertex. + + Default: (0,0,0) + + @see pCloth.setWindAcceleration() + */ + VxVector windAcceleration; + + /** + \brief The cloth wake up counter. + + Range: [0,inf)
+ Default: 20.0f*0.02f + + @see pCloth.wakeUp() pCloth.putToSleep() + */ + float wakeUpCounter; + + /** + \brief Maximum linear velocity at which cloth can go to sleep. + + If negative, the global default will be used. + + Range: [0,inf)
+ Default: -1.0 + + @see pCloth.setSleepLinearVelocity() pCloth.getSleepLinearVelocity() + */ + float sleepLinearVelocity; + + /** + \brief Sets which collision group this cloth is part of. + + Range: [0, 31] + Default: 0 + + pCloth.setCollisionGroup() + */ + xU16 collisionGroup; + + /** + \brief Sets the 128-bit mask used for collision filtering. + + Default: 0 + + @see NxGroupsMask pCloth.setGroupsMask() pCloth.getGroupsMask() + */ + pGroupsMask groupsMask; + + /** + \brief Force Field Material Index, index != 0 has to be created. + + Default: 0 + */ + xU16 forceFieldMaterial; + + /** + \brief If the flag PCF_ValidBounds is set, this variable defines the volume + outside of which cloth particle are automatically removed from the simulation. + + @see PCF_ValidBounds pCloth.setValidBounds() + */ + VxBbox validBounds; + + /** + \brief This parameter defines the size of grid cells for collision detection. + + The cloth is represented by a set of world aligned cubical cells in broad phase. + The size of these cells is determined by multiplying the length of the diagonal + of the AABB of the initial cloth size with this constant. + + Range: [0.01,inf)
+ Default: 0.25 + */ + float relativeGridSpacing; + + /** + \brief Flag bits. + + Default: PCF_GRAVITY + + @see NxClothFlag pCloth.setFlags() + */ + unsigned int flags; + + /** + \brief Possible debug name. The string is not copied by the SDK, only the pointer is stored. + + Default: NULL + + @see pCloth.setName() pCloth.getName() + */ + const char* name; + + + /** + \brief Vertex color to identify vertieces as tearable. + + Default: 255,255,254 + */ + VxColor tearVertexColor; + + /** + \brief Reference object to identify the world. + + Default: pDefaultWorld + */ + CK_ID worldReference; + + /** + \brief Attachment flags. + + Default: PCAF_ClothAttachmentTwoway + + @see #pClothAttachmentFlag + */ + pClothAttachmentFlag attachmentFlags; + + /** + \brief Constructor sets to default. + */ + pClothDesc(); + + + /** + \brief (Re)sets the structure to the default. + */ + void setToDefault(); + + /** + \brief Returns true if the current settings are valid + */ + bool isValid() const; + + + +}; + +/** @} */ +#endif +// __PCLOTHTYPES_H__ \ No newline at end of file diff --git a/usr/Include/Core/pCommon.h b/usr/Include/Core/pCommon.h new file mode 100644 index 0000000..06f1ed9 --- /dev/null +++ b/usr/Include/Core/pCommon.h @@ -0,0 +1,25 @@ +#ifndef __P_COMMON_H__ +#define __P_COMMON_H__ + +#include "vtPhysXBase.h" +#include "vtPhysXAll.h" + +#include "vtLogTools.h" +#include "vtCBBErrorHelper.h" +#include +#include + + +#define HAS_CONFIG +#ifdef HAS_CONFIG + #include "gConfig.h" +#endif + +using namespace vtTools::BehaviorTools; + + + + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pFactory/pFactory.h b/usr/Include/Core/pFactory/pFactory.h new file mode 100644 index 0000000..d87e6ff --- /dev/null +++ b/usr/Include/Core/pFactory/pFactory.h @@ -0,0 +1,303 @@ +#ifndef __P_FACTORY_H__ + #define __P_FACTORY_H__ + +#include "vtPhysXBase.h" +/** +\brief Singleton class to create physic objects. +*/ +class MODULE_API pFactory +{ + + +public: + //friend class PhysicManager; + virtual ~pFactory(); + + void findAttributeIdentifiersByGuid(CKGUID guid,std::vector&targetList); + + pFactory(); + pFactory(PhysicManager* prm1,TiXmlDocument*prm2); + + int reloadConfig(const char *fName); + TiXmlDocument* loadConfig(const char* filename); + + pWorldSettings *createWorldSettings(const XString nodeName="Default",const TiXmlDocument * doc = NULL); + pWorldSettings *createWorldSettings(const char* nodeName,const char *filename); + pWorldSettings*getWorldSettings(CK3dEntity*ent); + pWorld* createDefaultWorld(XString name); + const TiXmlElement*getFirstDocElement(const TiXmlElement *root); + TiXmlDocument* getDefaultDocument() const { return m_DefaultDocument; } + + TiXmlDocument* getDocument(XString filename); + NxPhysicsSDK* getPhysicSDK() { return mPhysicSDK; } + void setPhysicSDK(NxPhysicsSDK* val) { mPhysicSDK = val; } + PhysicManager * getManager() const { return mManager; } + void setManager(PhysicManager * val) { mManager = val; } + void setDefaultDocument(TiXmlDocument* val) { m_DefaultDocument = val; } + void clean(); + void destroy(); + + + ////////////////////////////////////////////////////////////////////////// + + + int copyTo(CKParameter *src,pDominanceSetupItem&dst); + + + + pSleepingSettings *CreateSleepingSettings(XString nodeName="Default", TiXmlDocument * doc = NULL); + pSleepingSettings*CreateSleepingSettings(const char* nodeName,const char *filename); + pSleepingSettings*getSleepingSettings(CK3dEntity*ent); + + pWorld *createWorld(CK3dEntity *referenceObject,pWorldSettings*worldSettings=NULL,pSleepingSettings*sleepSettings=NULL); + + pRemoteDebuggerSettings createDebuggerSettings(const TiXmlDocument * doc); + + + /************************************************************************************************/ + /** @name RigidBody + */ + //@{ + + + + pRigidBody *cloneRigidBody(CK3dEntity *src,CK3dEntity *dst,CKDependencies *deps,int copyFlags,int bodyFlags=0); + NxShape *cloneShape(CK3dEntity *src,CK3dEntity *dst,CK3dEntity*dstBodyReference,int copyFlags,int bodyFlags=0); + pJoint* cloneJoint(pJoint *src,CK3dEntity *srcReference,CK3dEntity *dstReference,int copyFlags); + int cloneLimitPlanes(pJoint *src,pJoint *dst,CK3dEntity *srcReference,CK3dEntity *dstReference); + + + + void cloneJoints(CK3dEntity *src,CK3dEntity *dst,int copyFlags); + + + pRigidBody *createRigidBodyFull(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject=NULL); + pRigidBody *createBody(CK3dEntity *referenceObject,pObjectDescr descriction,CK3dEntity *worldReferenceObject=NULL); + pRigidBody *createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject=NULL); + pRigidBody *createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,NXU::NxActorDesc *desc,int flags); + + pRigidBody *createRigidBody(CK3dEntity *referenceObject,pObjectDescr& oDescr); + pRigidBody *createBox(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags); + pRigidBody *createCapsule(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags); + + int createSubShape(CK3dEntity*target,CK3dEntity*child); + NxCCDSkeleton *createCCDSkeleton(CKBeObject *meshReference,int flags); + + + + + + + //@} + + /************************************************************************************************/ + /** @name Joints + */ + //@{ + + pJoint *createJoint(CK3dEntity*,CK3dEntity*,int); + pJointDistance*createDistanceJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor0=VxVector(0,0,0),VxVector anchor1=VxVector(0,0,0),float minDistance=0.0f,float maxDistance=0.0f,pSpring sSettings=pSpring(),bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJDistance"); + pJointD6* createD6Joint(CK3dEntity*a,CK3dEntity*b,VxVector globalAnchor=VxVector(0,0,0),VxVector globalAxis=VxVector(0,-1,0),bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f); + pJointFixed* createFixedJoint(CK3dEntity*a,CK3dEntity*b,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJFixed"); + pJointPulley*createPulleyJoint(CK3dEntity*a,CK3dEntity*b,VxVector pulley0,VxVector pulley1, VxVector anchor0, VxVector anchor1,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f); + pJointBall *createBallJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector swingAxis,VxVector globalAxis=VxVector(0,1,0),bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJBall"); + pJointPrismatic*createPrismaticJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJPrismatic"); + pJointCylindrical*createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJCylindrical"); + pJointRevolute *createRevoluteJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJRevolute"); + pJointPointInPlane *createPointInPlaneJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJPointInPlane"); + pJointPointOnLine *createPointOnLineJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision=true,float maxForce = 0.0f, float maxTorque=0.0f,const char* attributeName="pJPointOnLine"); + + + + + pJoint *GetJoint(CK3dEntity*,CK3dEntity*); + pJoint *GetJoint(CK3dEntity*,int); + pJointSettings *CreateJointSettings(const XString nodeName="Default",const TiXmlDocument * doc = NULL); + pJointSettings *CreateJointSettings(const char* nodeName,const char *filename); + + int jointCheckPreRequisites(CK3dEntity*,CK3dEntity*,int); + + //@} + + ////////////////////////////////////////////////////////////////////////// + //nx + NxShapeDesc& createShape(int hullType,CK3dEntity*ent,float density = 1.0f); + NxMaterialDesc* createMaterialFromXML(const char* nodeName="Default",const TiXmlDocument * doc = NULL); + NxMaterialDesc* createMaterialFromEntity(CKBeObject*object); + + + CKParameterOut* findSettings(pWheelDescr&dst,CKBeObject*src); + bool findSettings(pMaterial&dst,CKBeObject*src); + bool copyTo(pMaterial& dst,CKParameter*src); + bool copyTo(pMaterial& dst,NxMaterial*src); + bool copyTo(NxMaterial&dst,pMaterial*src); + bool copyTo(CKParameterOut*dst,const pMaterial&src); + bool copyTo(NxMaterialDesc&dst,const pMaterial&src); + bool loadFrom(pMaterial& dst,const char* nodeName="Default",const TiXmlDocument * doc = NULL); + bool loadMaterial(pMaterial&dst,const char* nodeName); + pMaterial loadMaterial(const char* nodeName,int& error); + + ////////////////////////////////////////////////////////////////////////// + //nx mesh : + void createMesh(NxScene *scene,CKMesh *mesh,NxTriangleMeshDesc&descr,bool hardware=false); + void createConvexMesh(NxScene *scene,CKMesh *mesh,NxConvexMeshDesc&descr,bool hardware=false); + NxShape *createShape(CK3dEntity *bodyReference,pObjectDescr descr,CK3dEntity *srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); + + + static pFactory* Instance(); + + pSpring createSpringFromParameter(CKParameter *par); + pJointLimit createLimitFromParameter(CKParameter *par); + pMotor createMotorFromParameter(CKParameter *par); + pTireFunction createTireFuncFromParameter(CKParameter *par); + pObjectDescr *createPObjectDescrFromParameter(CKParameter *par); + + + /************************************************************************/ + /* clothes : */ + /************************************************************************/ + pClothDesc *createClothDescrFromParameter(CKParameter *par); + pCloth *createCloth(CK3dEntity *srcReference,pClothDesc descr); + void copyToClothDescr(NxClothDesc* dst,pClothDesc src ); + void copyTo(pDeformableSettings &dst,CKParameter*par); + + /************************************************************************/ + /*Special Case Capsule : */ + /************************************************************************/ + bool copyTo(pCapsuleSettings&dst,CKParameter*src); + bool findSettings(pCapsuleSettings&dst,CKBeObject *src); + + bool findSettings(pCapsuleSettingsEx&dst,CKBeObject *src); + bool findSettings(pConvexCylinderSettings&dst,CKBeObject *src); + bool findSettings(pCCDSettings&dst,CKBeObject *src); + bool findSettings(pMassSettings&dst,CKBeObject *src); + bool findSettings(pPivotSettings&dst,CKBeObject *src); + bool findSettings(pOptimization&dst,CKBeObject *src); + bool findSettings(pCollisionSettings&dst,CKBeObject*src); + + + CKParameterOut* findSettingsParameter(CKBeObject *src,CKGUID guid); + + /************************************************************************/ + /* fluids : */ + /************************************************************************/ + //pFluid*createFluid(CK3dEntity *srcReference ,pFluidDesc desc); + //void copyToFluidDescr(NxFluidDesc &dst , pFluidDesc src ); + //CK3dEntity *createFluidEntity(); + //void initParticles(pFluidDesc &desc,NxParticleData&dst,CK3dEntity*srcReference,CK3dEntity*dstEntity); + //void copyToEmitterDesc(NxFluidEmitterDesc&dst,pFluidEmitterDesc src); + //CK3dPointCloud* createPointCloud(const pFluidDesc&descr); + + /************************************************************************/ + /* Vehicle */ + /************************************************************************/ + pVehicle *createVehicle(CK3dEntity *body,pVehicleDesc descr); + pVehicleMotor *createVehicleMotor(pVehicleMotorDesc descr); + pVehicleGears *createVehicleGears(pVehicleGearDesc descr); + + + + pWheel *createWheelSubShape(pRigidBody *body,CK3dEntity* subEntity,CKMesh *mesh,pObjectDescr *descr,VxVector localPos, VxQuaternion localRotation,NxShape*dstShape); + + + XString _getMaterialsAsEnumeration(const TiXmlDocument * doc); + XString _getBodyXMLInternalEnumeration(const TiXmlDocument * doc); + XString _getBodyXMLExternalEnumeration(const TiXmlDocument * doc); + + XString _getVehicleTireFunctionAsEnumeration(const TiXmlDocument * doc); + XString _getVehicleWheelAsEnumeration(const TiXmlDocument * doc); + XString _getVehicleSettingsAsEnumeration(const TiXmlDocument * doc); + XString _getVehicleMotorSettingsAsEnumeration(const TiXmlDocument * doc); + XString _getVehicleGearSettingsAsEnumeration(const TiXmlDocument * doc); + + XString _getEnumDescription(const TiXmlDocument * doc,XString identifier); + int _getEnumIdentifier(const TiXmlDocument * doc,XString type); + int _getEnumIndex(XString enumerationFull,XString enumValue); + + + NxShape *createWheelShape(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CK3dEntity*srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); + NxShape *_createWheelShape1(NxActor *actor,pWheel1 *dstWheel,pObjectDescr *descr,pWheelDescr *wheelDescr,CK3dEntity*srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); + NxShape *_createWheelShape2(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CK3dEntity*srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); + + NxShape *createWheelShape(CK3dEntity*bodyReference,pWheelDescr wheelDescr,CK3dEntity*wheelReference); + + + pWheel *createWheel(pRigidBody *body,pWheelDescr descr,CK3dEntity *wheelShapeReference); + pWheel* createWheel(CK3dEntity *bodyReference,CK3dEntity*srcReference,pWheelDescr wheelDescr,pConvexCylinderSettings convexCylinder,VxVector localPositionOffset); + NxShape *createWheelShape2(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr); + NxShape *createWheelShape1(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr); + + NxShape *_createConvexCylinder(NxActor *actor,int approximation,VxVector _forwardAxis,VxVector _downAxis,VxVector _rightAxis,float height,float radius,bool buildLowerHalf,int shapeFlags); + bool _createConvexCylinder(NxConvexShapeDesc* shape,CK3dEntity*dstBodyReference,pObjectDescr *oDescr=NULL); + + bool _createConvexCylinderMesh(NxConvexShapeDesc *dstShapeDescription,pConvexCylinderSettings& srcSettings,CK3dEntity*referenceObject); + + NxShape *_createConvexCylinder(const pConvexCylinderSettings& cylinderDescr,CK3dEntity *srcReference); + + + int loadVehicleDescrFromXML(pVehicleDesc& dst,const char* nodeName/* =NULL */,const TiXmlDocument * doc /* = NULL */ ); + + + ////////////////////////////////////////////////////////////////////////// + // + // Geometry related structures : + // + void copyTo(pAxisReferencedLength&dst,CKParameter*src,bool evaluate=true); + bool copyTo(pConvexCylinderSettings&dst,CKParameter*src,bool evaluate=true); + + ////////////////////////////////////////////////////////////////////////// + // + // wheels + int copyTo(pWheelDescr *dst,CKParameter *src); + int loadFrom(pTireFunction& dst,const char* nodeName/* = */,const TiXmlDocument * doc /* = NULL */); + int loadWheelDescrFromXML(pWheelDescr& dst,const char* nodeName/* =NULL */,const TiXmlDocument * doc /* = NULL */ ); + + bool loadFrom(pWheelDescr& dst,const char* nodeName/* =NULL */); + + int copyTo(CKParameterOut *dst,pWheelDescr *src); + int copyTo(pWheelDescr &dst,CKParameterOut *src); + + int copyTo(CKParameterOut *dst,const pTireFunction& src); + + + //contact data : + int copyTo(CKParameterOut *dst,const pWheelContactData& src); + + + + + ////////////////////////////////////////////////////////////////////////// + // + // + // collision structures + int copyTo(pGroupsMask &dst,CKParameter*src); + int copyTo(CKParameterOut*dst,pGroupsMask src); + + + CK3dEntity *getMostTopParent(CK3dEntity*ent); + +protected: + PhysicManager *mManager; + + + TiXmlDocument* m_DefaultDocument; + NxPhysicsSDK* mPhysicSDK; + + VxVector _str2Vec(XString _in); + int _str2MaterialFlag(XString _in); + int _str2WheelFlag(XString _in); + int _str2SceneFlags(XString _in); + int _str2PhysicFlags(XString _in); + int _str2WheelShapeFlag(XString _in); + XString ResolveFileName(const char *input); + int _str2CombineMode(const char*input); + + CK3dEntity *createFrame(const char* name); + + + + +}; + + +#endif // !defined(EA_10DFC1E8_486F_4770_9451_7898DBDAD59F__INCLUDED_) diff --git a/usr/Include/Core/pFluid/pFluid.h b/usr/Include/Core/pFluid/pFluid.h new file mode 100644 index 0000000..2f7ef9f --- /dev/null +++ b/usr/Include/Core/pFluid/pFluid.h @@ -0,0 +1,550 @@ +#ifndef __P_FLUID_H__ +#define __P_FLUID_H__ + +#include "pTypes.h" +#include "NxPlane.h" +#include "pFluidFlags.h" + +#include "pTypes.h" + +class CK3dPointCloud; + + +/** \addtogroup Fluid +@{ +*/ + +/** +\brief2 Describes an pFluidDesc. +*/ +class MODULE_API pFluidDesc +{ +public: + + /** + \brief Sets the maximal number of particles for the fluid used in the simulation. + + If more particles are added directly, or more particles are emitted into the + fluid after this limit is reached, they are simply ignored. + + */ + int maxParticles; + + /** + \brief Defines the number of particles which are reserved for creation at runtime. + + If pFluidDesc.flags.PFF_PriorityMode is set the oldest particles are removed until + there are no more than (maxParticles - numReserveParticles) particles left. This removal + is carried out for each simulation step, on particles which have a finite life time + (i.e. > 0.0). The deletion guarantees a reserve of numReserveParticles particles which + can be added for each simulaiton step. Note that particles which have equal lifetime can + get deleted at the same time. In order to avoid this, the particle lifetimes + can be varied randomly. + + This parameter must be smaller than pFluidDesc.maxParticles. + */ + int numReserveParticles; + + /** + \brief The particle resolution given as particles per linear meter measured when the fluid is + in its rest state (relaxed). + + Even if the particle system is simulated without particle interactions, this parameter defines the + emission density of the emitters. + + */ + float restParticlesPerMeter; + + /** + \brief Target density for the fluid (water is about 1000). + + Even if the particle system is simulated without particle interactions, this parameter defines + indirectly in combination with restParticlesPerMeter the mass of one particle + ( mass = restDensity/(restParticlesPerMeter^3) ). + + The particle mass has an impact on the repulsion effect on emitters and actors. + + */ + float restDensity; + + /** + \brief Radius of sphere of influence for particle interaction. + + This parameter is relative to the rest spacing of the particles, which is defined by the parameter + restParticlesPerMeter + + ( radius = kernelRadiusMultiplier/restParticlesPerMeter ). + + This parameter should be set around 2.0 and definitely below 2.5 for optimal performance and simulation quality. + + @see restParticlesPerMeter + */ + float kernelRadiusMultiplier; + + /** + \brief Maximal distance a particle is allowed to travel within one timestep. + + This parameter is relative to the rest spacing of the particles, which is defined by the parameter + restParticlesPerMeter: + + ( maximal travel distance = motionLimitMultiplier/restParticlesPerMeter ). + + Default value is 3.6 (i.e., 3.0 * kernelRadiusMultiplier). + + The value must not be higher than the product of packetSizeMultiplier and kernelRadiusMultiplier. + + @see restParticlesPerMeter + */ + float motionLimitMultiplier; + + /** + \brief Defines the distance between particles and collision geometry, which is maintained during simulation. + + For the actual distance, this parameter is divided by the rest spacing of the particles, which is defined by the parameter + restParticlesPerMeter: + + ( distance = collisionDistanceMultiplier/restParticlesPerMeter ). + + It has to be positive and not higher than packetSizeMultiplier*kernelRadiusMultiplier. + Default value is 0.12 (i.e., 0.1 * kernelRadiusMultiplier). + + @see restParticlesPerMeter, kernelRadiusMultiplier + */ + float collisionDistanceMultiplier; + + /** + \brief This parameter controls the parallelization of the fluid. + + The spatial domain is divided into so called packets, equal sized cubes, aligned in a grid. + + The parameter given defines the edge length of such a packet. This parameter is relative to the interaction + radius of the particles, given as kernelRadiusMultiplier/restParticlesPerMeter. + + It has to be a power of two, no less than 4. + + */ + int packetSizeMultiplier; + + /** + \brief The stiffness of the particle interaction related to the pressure. + + This factor linearly scales the force which acts on particles which are closer to each other than + the rest spacing. + + Setting this parameter appropriately is crucial for the simulation. The right value depends on many factors + such as viscosity, damping, and kernelRadiusMultiplier. Values which are too high will result in an + unstable simulation, whereas too low values will make the fluid appear "springy" (the fluid + acts more compressible). + + Must be positive. + + */ + float stiffness; + + /** + \brief The viscosity of the fluid defines its viscous behavior. + + Higher values will result in a honey-like behavior. Viscosity is an effect which depends on the + relative velocity of neighboring particles; it reduces the magnitude of the relative velocity. + + Must be positive. + + */ + float viscosity; + + /** + \brief The surfaceTension of the fluid defines an attractive force between particles + + Higher values will result in smoother surfaces. + Must be nonnegative. + + */ + float surfaceTension; + + /** + \brief Velocity damping constant, which is globally applied to each particle. + + It generally reduces the velocity of the particles. Setting the damping to 0 will leave the + particles unaffected. + + Must be nonnegative. + + */ + float damping; + + /** + \brief Defines a timespan for the particle "fade-in". + + This feature is experimental. When a particle is created it has no influence on the simulation. + It takes fadeInTime until the particle has full influence. If set to zero, the particle has full + influence on the simulation from start. + + Default: 0.0
+ Range: [0,inf) + */ + float fadeInTime; + + /** + \brief Acceleration (m/s^2) applied to all particles at all time steps. + + Useful to simulate smoke or fire. + This acceleration is additive to the scene gravity. The scene gravity can be turned off + for the fluid, using the flag PFF_DisableGravity. + + @see pFluid.getExternalAcceleration() pFluid.setExternalAcceleration() + */ + VxVector externalAcceleration; + + /** + \brief Defines the plane the fluid particles are projected to. This parameter is only used if + PFF_ProjectToPlane is set. + + Default: XY plane + + @see PFF_ProjectToPlane pFluid.getProjectionPlane() pFluid.setProjectionPlane() + */ + NxPlane projectionPlane; + + /** + \brief Defines the restitution coefficient used for collisions of the fluid particles with static shapes. + + Must be between 0 and 1. + + A value of 0 causes the colliding particle to get a zero velocity component in the + direction of the surface normal of the static shape at the collision location; i.e. + it will not bounce. + + A value of 1 causes a particle's velocity component in the direction of the surface normal to invert; + i.e. the particle bounces off the surface with the same velocity magnitude as it had before collision. + (Caution: values near 1 may have a negative impact on stability) + + */ + float restitutionForStaticShapes; + + /** + \brief Defines the dynamic friction of the fluid regarding the surface of a static shape. + + Must be between 0 and 1. + + A value of 1 will cause the particle to lose its velocity tangential to + the surface normal of the shape at the collision location; i.e. it will not slide + along the surface. + + A value of 0 will preserve the particle's velocity in the tangential surface + direction; i.e. it will slide without resistance on the surface. + + */ + float dynamicFrictionForStaticShapes; + + /** + \brief Defines the static friction of the fluid regarding the surface of a static shape. + + This feature is currently unimplemented! + + */ + float staticFrictionForStaticShapes; + + /** + \brief Defines the strength of attraction between the particles and static rigid bodies on collision. + + This feature is currently unimplemented! + + */ + float attractionForStaticShapes; + + /** + \brief Defines the restitution coefficient used for collisions of the fluid particles with dynamic shapes. + + Must be between 0 and 1. + + (Caution: values near 1 may have a negative impact on stability) + + @see restitutionForStaticShapes + */ + float restitutionForDynamicShapes; + + /** + \brief Defines the dynamic friction of the fluid regarding the surface of a dynamic shape. + + Must be between 0 and 1. + + @see dynamicFrictionForStaticShapes + */ + float dynamicFrictionForDynamicShapes; + + /** + \brief Defines the static friction of the fluid regarding the surface of a dynamic shape. + + This feature is currently unimplemented! + + */ + float staticFrictionForDynamicShapes; + + /** + \brief Defines the strength of attraction between the particles and the dynamic rigid bodies on collision. + + This feature is currently unimplemented! + + */ + float attractionForDynamicShapes; + + /** + \brief Defines a factor for the impulse transfer from fluid to colliding rigid bodies. + + Only has an effect if PFF_CollisionTwoway is set. + + Default: 0.2
+ Range: [0,inf) + + @see PFF_CollisionTwoway pFluid.setCollisionResponseCoefficient() + */ + float collisionResponseCoefficient; + + /** + \brief pFluidSimulationMethod flags. Defines whether or not particle interactions are considered + in the simulation. + + @see pFluidSimulationMethod + */ + pFluidSimulationMethod simulationMethod; + + /** + \brief pFluidCollisionMethod flags. Selects whether static collision and/or dynamic collision + with the environment is performed. + + @see pFluidCollisionMethod + */ + pFluidCollisionMethod collisionMethod; + + /** + \brief Sets which collision group this fluid is part of. + + Default: 0 + + pFluid.setCollisionGroup() + */ + int collisionGroup; + + + /** + \brief Sets the 128-bit mask used for collision filtering. + + Default: 0 + + @see NxGroupsMask pFluid.setGroupsMask() pFluid.getGroupsMask() + */ + NxGroupsMask groupsMask; + + /** + \brief Flags defining certain properties of the fluid. + + @see pFluidFlag + */ + unsigned int flags; + + void* userData; //!< Will be copied to NxFluid::userData + const char* name; //!< Possible debug name. The string is not copied by the SDK, only the pointer is stored. + + /** + \brief Constructor sets to default. + + */ + pFluidDesc(); + /** + \brief (Re)sets the structure to the default. + + */ + void setToDefault(); + /** + \brief Returns true if the current settings are valid + + */ + bool isValid() const; + + + /** + \brief Retrieve the fluid desc type. + + \return The fluid desc type. See #pFluidDescType + */ + xU16 getType() const; + + CK_ID worldReference; + +protected: + + NxFluidDescType type; + +}; + + +struct pParticle +{ + NxVec3 position; + NxVec3 velocity; + float density; + float lifetime; + unsigned int id; + NxVec3 collisionNormal; +}; + +/** +\brief The fluid class represents the main module for the particle based fluid simulation. +SPH (Smoothed Particle Hydrodynamics) is used to animate the particles. + +There are two kinds of particle interaction forces which govern the behavior of the fluid: +
    +
  1. + Pressure forces: These forces result from particle densities higher than the + "rest density" of the fluid. The rest density is given by specifying the inter-particle + distance at which the fluid is in its relaxed state. Particles which are closer than + the rest spacing are pushed away from each other. +
  2. + Viscosity forces: These forces act on neighboring particles depending on the difference + of their velocities. Particles drag other particles with them which is used to simulate the + viscous behaviour of the fluid. +
+ The fluid class manages a set of particles. + Particles can be created in two ways: +
    +
  1. + Particles can be added by the user directly. +
  2. + The user can add emitters to the fluid and configure the parameters of the emission. + (See pFluidEmitter) +
+ Particles can be removed in two ways as well: +
    +
  1. + The user can specify a lifetime for the particles. When its lifetime expires, a particle is deleted. +
  2. + Shapes can be configured to act as drains. When a particle intersects with a drain, the particle is deleted. + (See pShapeFlag) +
+ +Particles collide with static and dynamic shapes. Particles are also affected by the scene gravity and a user force, +as well as global velocity damping. In order to render a fluid, the user can supply the fluid instance with a +user buffer into which the particle state is written after each simuation step. + +For a good introduction to SPH fluid simulation, +see http://graphics.ethz.ch/~mattmuel/publications/sca03.pdf + +@see pFluidDesc, pFluidEmitter, pFluidEmitterDesc, pShapeFlag +*/ +class pFluid +{ + public: + pFluid(NxFluidDesc &desc, bool trackUserData, bool provideCollisionNormals, const VxVector& color, float particleSize); + ~pFluid(); + + NxFluid* getNxFluid() { return mFluid; } + + pParticle* getParticles() { return mParticleBuffer; } + unsigned getParticlesNum() { return mParticleBufferNum; } + + const unsigned* getCreatedIds() { return mCreatedParticleIds; } + unsigned getCreatedIdsNum() { return mCreatedParticleIdsNum; } + + const unsigned* getDeletedIds() { return mDeletedParticleIds; } + unsigned getDeletedIdsNum() { return mDeletedParticleIdsNum; } + + void setParticleSize(float size) { mParticleSize = size; } + float getParticleSize() { return mParticleSize; } + + void draw(); + + NxFluid* getFluid() const { return mFluid; } + void setFluid(NxFluid* val) { mFluid = val; } + + CK_ID getEntityID() const { return entityID; } + void setEntityID(CK_ID val) { entityID = val; } + void updateVirtoolsMesh(); + + CK3dEntity *getParticleObject(); + + pParticle* mParticleBuffer; + + + /************************************************************************/ + /* emitter operations : */ + /************************************************************************/ + + /** + \brief Creates an emitter for this fluid. + + pFluidEmitterDesc::isValid() must return true. + + \param desc The fluid emitter descriptor. See #pFluidEmitterDesc. + \return The new fluid. + + @see pFluidEmitter + */ + pFluidEmitter* createEmitter(const pFluidEmitterDesc& desc); + + /** + \brief Deletes the specified emitter. + + The emitter must belong to this fluid. Do not keep a reference to the deleted instance. + Avoid release calls while the scene is simulating (in between simulate() and fetchResults() calls). + + \param emitter The emitter to release. + + */ + void releaseEmitter(pFluidEmitter& emitter); + + /** + \brief Returns the number of emitters. + + \return The number of emitters. + */ + int getNbEmitters()const; + + + + CK3dPointCloud* mPointCloud; + + CK3dPointCloud* getPointCloud() const { return mPointCloud; } + void setPointCloud(CK3dPointCloud* val) { mPointCloud = val; } + + void updateCloud(); + + + + + +private: + + unsigned mParticleBufferNum; + + + NxFluid* mFluid; + + VxVector mParticleColor; + float mParticleSize; + unsigned int mMaxParticles; + + CK_ID entityID; + + + /** + These fields are only relevant for tracking user particle data (MyParticle) + */ + bool mTrackUserData; + pFluid* mMyParticleBuffer; + unsigned int mCreatedParticleIdsNum; + unsigned int* mCreatedParticleIds; + unsigned int mDeletedParticleIdsNum; + unsigned int* mDeletedParticleIds; + + //rendering + float* mRenderBuffer; + float* mRenderBufferUserData; + + protected: + private: +}; + + +/** @} */ + +#endif diff --git a/usr/Include/Core/pFluid/pFluidEmitter.h b/usr/Include/Core/pFluid/pFluidEmitter.h new file mode 100644 index 0000000..8cd1cca --- /dev/null +++ b/usr/Include/Core/pFluid/pFluidEmitter.h @@ -0,0 +1,386 @@ +#ifndef __P_FLUIDS_FLUID_EMITTER_H__ +#define __P_FLUIDS_FLUID_EMITTER_H__ + + +/** \addtogroup fluids + @{ +*/ + + +#include "Nxp.h" +#include "NxPhysicsSDK.h" +#include "pFluidEmitterDesc.h" + +class pFluid; +class pFluidEmitterDesc; +class NxShape; + +/** +\brief The fluid emitter class. It represents an emitter (fluid source) which is associated with one fluid. + +The emitter is an alternative to adding particles to the fluid via the pFluid::addParticles() method. + +Emission always takes place in a plane given by the orientation and position of the emitter. The +shape of the area of emission is either a rectangle or an ellipse. The direction of emission is usually +perpendicular to the emission plane. However, this can be randomly modulated using the setRandomAngle() +method. An emitter can have two types of operation: +
    +
  1. + Constant pressure. + In this case the state of the surrounding fluid is taken into account. The emitter tries + to match the rest spacing of the particles. Nice rays of water can be generated this way. +
  2. + Constant flow rate. + In this case the emitter keeps emitting the same number of particles each frame. The rate can + be adjusted dynamically. +
+The emitter's pose can be animated directly or attached to a shape which belongs to a +dynamic actor. This shape is called the frame shape. When attaching an emitter to a shape, one +has the option of enabling impulse transfer from the emitter to the body of the shape. +The impulse generated is dependent on the rate, density, +and velocity of the emitted particles. + +*/ +class MODULE_API pFluidEmitter +{ + + public: + pFluidEmitter(); + ~pFluidEmitter() {} + + /** + \brief Sets the position of the emitter in world space. + + \param[in] vec New position in world space. + + */ + void setGlobalPosition(const VxVector& vec); + + /** + \brief Sets the orientation of the emitter in world space. + + \param[in] rot New orientation in world space. + */ + void setGlobalOrientation(const VxQuaternion& rot); + + /** + \brief Returns the position of the emitter in world space. + + \return The world space position. + */ + VxVector getGlobalPosition()const; + + /** + \brief Returns the orientation of the emitter in world space. + + \return The world space orientation. + + */ + + VxQuaternion getGlobalOrientation()const; + + /** + \brief Sets the position of the emitter relative to the frameShape. + + The pose is relative to the shape frame. + + If the frameShape is NULL, world space is used. + + \param[in] vec The new local position of the emitter. + + @see pFluidEmitterDesc.relPose + */ + void setLocalPosition(const VxVector& vec) ; + + /** + \brief Sets the orientation of the emitter relative to the frameShape. + + The pose is relative to the shape frame. + + If the frameShape is NULL, world space is used. + + \param[in] mat The new local orientation of the emitter. + + @see pFluidEmitterDesc.relPose + */ + void setLocalOrientation(const VxQuaternion& mat); + + + /** + \brief Returns the position of the emitter relative to the frameShape. + + The pose is relative to the shape frame. + + If the frameShape is NULL, world space is used. + + \return The local position of the emitter. + @see pFluidEmitterDesc.relPose + */ + + VxVector getLocalPosition()const; + + /** + \brief Returns the orientation of the emitter relative to the frameShape. + + The pose is relative to the shape frame. + + If the frameShape is NULL, world space is used. + + \return The local orientation of the emitter. + + @see pFluidEmitterDesc.relPose + */ + VxQuaternion getLocalOrientation()const; + + /** + \brief Sets the frame shape. Can be set to NULL. + + \param[in] shape The frame shape. + + @see pFluidEmitterDesc.frameShape + */ + void setFrameShape(CK3dEntity* shape); + + /** + \brief Returns the frame shape. May be NULL. + + \return The frame shape. + + @see pFluidEmitterDesc.frameShape + */ + CK3dEntity * getFrameShape() const; + + /** + \brief Returns the radius of the emitter along the x axis. + + \return Radius of emitter along the X axis. + + @see pFluidEmitterDesc.dimensionX + */ + float getDimensionX() const; + + /** + \brief Returns the radius of the emitter along the y axis. + + \return Radius of emitter along the Y axis. + + @see pFluidEmitterDesc.dimensionY + */ + float getDimensionY()const; + + /** + \brief Sets the maximal random displacement in every dimension. + + \param[in] disp The maximal random displacement of particles. + @see pFluidEmitterDesc.randomPos + */ + void setRandomPos(VxVector disp); + + /** + \brief Returns the maximal random displacement in every dimension. + + \return The maximal random displacement of particles. + + @see pFluidEmitterDesc.randomPos + */ + VxVector getRandomPos()const; + + /** + \brief Sets the maximal random angle offset (in radians). + + Unit: Radians + + \param[in] angle Maximum random angle for emitted particles. + + @see pFluidEmitterDesc.randomAngle + */ + void setRandomAngle(float angle); + + /** + \brief Returns the maximal random angle offset (in radians). + + Unit: Radians + + \return Maximum random angle for emitted particles. + + @see pFluidEmitterDesc.randomAngle + */ + float getRandomAngle(); + + /** + \brief Sets the velocity magnitude of the emitted particles. + + \param[in] vel New velocity magnitude of emitted particles. + + @see pFluidEmitterDesc.fluidVelocityMagnitude + */ + void setFluidVelocityMagnitude(float vel) ; + + /** + \brief Returns the velocity magnitude of the emitted particles. + + \return Velocity magnitude of emitted particles. + + @see pFluidEmitterDesc.fluidVelocityMagnitude + */ + float getFluidVelocityMagnitude() const; + + /** + \brief Sets the emission rate (particles/second). + + Only used if the pEmitterType is PFET_ConstantFlowRate. + + \param[in] rate New emission rate. + + @see pFluidEmitterDesc.rate + */ + void setRate(float rate); + + /** + \brief Returns the emission rate. + + \return Emission rate. + @see pFluidEmitterDesc.rate + */ + float getRate() const; + + /** + \brief Sets the particle lifetime. + + \param[in] life Lifetime of emitted particles. + + @see pFluidEmitterDesc.particleLifetime + */ + void setParticleLifetime(float life) ; + + /** + \brief Returns the particle lifetime. + + \return Lifetime of emitted particles. + + @see pFluidEmitterDesc.particleLifetime + */ + float getParticleLifetime() const; + + /** + \brief Sets the repulsion coefficient. + + \param[in] coefficient The repulsion coefficient in the range from 0 to inf. + + @see pFluidEmitterDesc.repulsionCoefficient getRepulsionCoefficient() + */ + void setRepulsionCoefficient(float coefficient); + + /** + \brief Retrieves the repulsion coefficient. + + \return The repulsion coefficient. + @see pFluidEmitterDesc.repulsionCoefficient setRepulsionCoefficient() + */ + float getRepulsionCoefficient() const; + + /** + \brief Resets the particle reservoir. + + \param[in] new maxParticles value. + @see pFluidEmitterDesc.maxParticles + */ + void resetEmission(int maxParticles); + + /** + \brief Returns the maximal particle number to be emitted. + + \return max particles. + + @see pFluidEmitterDesc.maxParticles + */ + int getMaxParticles() const; + + /** + \brief Returns the number of particles that have been emitted already. + + \return number of particles already emitted. + + */ + int getNbParticlesEmitted() const; + + /** + \brief Sets the emitter flags. + + \param[in] flag Member of #pFluidEmitterFlag. + \param[in] val New flag value. + + @see pFluidEmitterFlag + */ + void setFlag(pFluidEmitterFlag flag, bool val); + + /** + \brief Returns the emitter flags. + + \param[in] flag Member of #pFluidEmitterFlag. + \return The current flag value. + + @see pFluidEmitterFlag + */ + bool getFlag(pFluidEmitterFlag flag) const; + + /** + \brief Get the emitter shape. + + \param[in] shape Member of #pEmitterShape. + \return True if it is of type shape. + + @see pFluidEmitterDesc.shape + */ + bool getShape(pEmitterShape shape) const; + + /** + \brief Get the emitter type. + + \param[in] type Member of #pEmitterType + \return True if it is of type type. + + @see pEmitterType + */ + bool getType(pEmitterType type) const; + + + NxFluidEmitter* getEmitter() const { return mEmitter; } + void setEmitter(NxFluidEmitter* val) { mEmitter = val; } + + + /** + \brief Returns the owner fluid. + + \return The fluid this emitter is associated with. + + */ + pFluid * getFluid() const { return mFluid; } + + void setFluid(pFluid * val) { mFluid = val; } + + + CK_ID getEntityReference() const { return mEntityReference; } + void setEntityReference(CK_ID val) { mEntityReference = val; } + + pFluidRenderSettings * getRenderSettings() const { return mRenderSettings; } + void setRenderSettings(pFluidRenderSettings * val) { mRenderSettings = val; } + + +private : + + + NxFluidEmitter* mEmitter; + + + pFluid *mFluid; + + CK_ID mEntityReference; + + pFluidRenderSettings *mRenderSettings; + +}; + +/** @} */ + +#endif diff --git a/usr/Include/Core/pFluid/pFluidEmitterDesc.h b/usr/Include/Core/pFluid/pFluidEmitterDesc.h new file mode 100644 index 0000000..848237c --- /dev/null +++ b/usr/Include/Core/pFluid/pFluidEmitterDesc.h @@ -0,0 +1,201 @@ +#ifndef __P_FLUID_EMITTER_DESC_H__ +#define __P_FLUID_EMITTER_DESC_H__ + +/** \addtogroup fluids + @{ +*/ + +/** +\brief Flags which control the behavior of fluid emitters. + +@see pFluidEmitter +*/ +enum pFluidEmitterFlag + { + /** + \brief Flags whether the emitter should be visualized for debugging or not. + */ + PFEF_Visualization = (1<<0), + + /** + \brief This flag specifies whether the emission should cause a force on + the shapes body that the emitter is attached to. + */ + PFEF_ForceOnBody = (1<<2), + + /** + \brief If set, the velocity of the shapes body is added to the emitted particle velocity. + + This is the default behavior . + */ + PFEF_AddBodyVelocity = (1<<3), + + /** + \brief Flag to start and stop the emission. On default the emission is enabled. + */ + PFEF_Enabled = (1<<4), +}; + +/** +\brief Flags to specify the shape of the area of emission. + +Exactly one flag should be set at any time. + +*/ +enum pEmitterShape +{ + PFES_Rectangular = (1<<0), + PFES_Ellipse = (1<<1) +}; + +/** +\brief Flags to specify the emitter's type of operation. +Exactly one flag should be set at any time. + +@see pFluidEmitter +*/ +enum pEmitterType +{ + PFET_ConstantPressure = (1<<0), + PFET_ConstantFlowRate = (1<<1) +}; + + +/** +\brief Descriptor for pFluidEmitter class. Used for saving and loading the emitter state. +*/ +class MODULE_API pFluidEmitterDesc + { + public: + + + + CK_ID entityReference; + /** + \brief A pointer to the shape to which the emitter is attached to. + + If this pointer is set to NULL, the emitter is attached to the world frame. The shape + must be in the same scene as the emitter. + */ + CK3dEntity* frameShape; + + /** + \brief The emitter's mode of operation. + + Either the simulation enforces constant pressure or constant flow rate at the emission site, + given the velocity of emitted particles. + + @see NxEmitterType + */ + pEmitterType type; + + /** + \brief The maximum number of particles which are emitted from this emitter. + + If the total number of particles in the fluid already hit the maxParticles parameter of the fluid, + this maximal values can't be reached. + + If set to 0, the number of emitted particles is unrestricted. + */ + int maxParticles; + + /** + \brief The emitter's shape can either be rectangular or elliptical. + + @see pEmitterShape + */ + pEmitterShape shape; + + /** + \brief The sizes of the emitter in the directions of the first and the second axis of its orientation + frame (relPose). + + The dimensions are actually the radii of the size. + + */ + float dimensionX; + float dimensionY; + + /** + \brief Random vector with values for each axis direction of the emitter orientation. + + The values have to be positive and describe the maximal random particle displacement in each dimension. + + The z value describes the randomization in emission direction. The emission direction + is specified by the third orientation axis of relPose. + + */ + VxVector randomPos; + + /** + \brief Random angle deviation from emission direction. + + The emission direction is specified by the third orientation axis of relPose. + + Unit: Radians + + */ + float randomAngle; + + /** + \brief The velocity magnitude of the emitted fluid particles. + + */ + float fluidVelocityMagnitude; + + /** + \brief The rate specifies how many particles are emitted per second. + + The rate is only considered in the simulation if the type is set to PFET_ConstantFlowRate. + + @see NxEmitterType + */ + float rate; + + /** + \brief This specifies the time in seconds an emitted particle lives. + + If set to 0, each particle will live until it collides with a drain. + */ + float particleLifetime; + + /** + \brief Defines a factor for the impulse transfer from attached emitter to body. + + Only has an effect if PFEF_ForceOnBody is set. + + Default: 1.0
+ Range: [0,inf) + + @see PFEF_ForceOnBody NxFluidEmitter.setRepulsionCoefficient() + */ + float repulsionCoefficient; + + /** + \brief A combination of pFluidEmitterFlags. + + @see pFluidEmitterFlag + */ + pFluidEmitterFlag flags; + + ~pFluidEmitterDesc(); + /** + \brief (Re)sets the structure to the default. + */ + void setToDefault(); + /** + \brief Returns true if the current settings are valid + */ + bool isValid() const; + + /** + \brief Constructor sets to default. + */ + pFluidEmitterDesc(); + }; + + + +/** @} */ + +#endif diff --git a/usr/Include/Core/pFluid/pFluidFlags.h b/usr/Include/Core/pFluid/pFluidFlags.h new file mode 100644 index 0000000..a8cd3c7 --- /dev/null +++ b/usr/Include/Core/pFluid/pFluidFlags.h @@ -0,0 +1,121 @@ +#ifndef __P_FLUID_FLAGS_ +#define __P_FLUID_FLAGS_ + + + +/** \addtogroup Fluid +@{ +*/ + +/** +\brief Fluid flags +*/ +enum pFluidFlag +{ + /** + \brief Enables debug visualization for the NxFluid. + */ + PFF_VISUALIZATION = (1<<0), + + /** + \brief Disables scene gravity for the NxFluid. + */ + PFF_DisableGravity = (1<<1), + + /** + \brief Enable/disable two way collision of fluid with the rigid body scene. + In either case, fluid is influenced by colliding rigid bodies. + If PFF_CollisionTwoway is not set, rigid bodies are not influenced by + colliding pieces of fluid. Use pFluidDesc.collisionResponseCoefficient to + control the strength of the feedback force on rigid bodies. + + @see NxFluidDesc.collisionResponseCoefficient + */ + PFF_CollisionTwoway = (1<<2), + + + /** + \brief Enable/disable execution of fluid simulation. + */ + PFF_Enabled = (1<<3), + + /** + \brief Defines whether this fluid is simulated on the PPU. + */ + PFF_Hardware = (1<<4), + + /** + \brief Enable/disable particle priority mode. + If enabled, the oldest particles are deleted to keep a certain budget for + new particles. Note that particles which have equal lifetime can get deleted + at the same time. In order to avoid this, the particle lifetimes + can be varied randomly. + + @see pFluidDesc.numReserveParticles + */ + PFF_PriorityMode = (1<<5), + + /** + \brief Defines whether the particles of this fluid should be projected to a plane. + This can be used to build 2D fluid applications, for instance. The projection + plane is defined by the parameter pFluidDesc.projectionPlane. + + @see pFluidDesc.projectionPlane + */ + PFF_ProjectToPlane = (1<<6), + + /** + \brief Forces fluid static mesh cooking format to parameters given by the fluid descriptor. + + Currently not implemented! + */ + PFF_ForceStrictCookingFormat = (1<<7), + +}; + +/** +\brief Describes the particle simulation method + +Particles can be treated in two ways: either they are simulated considering +interparticular forces (SPH), or they are simulated independently. +In the latter case (with the simulation method set to PFS_NO_PARTICLE_INTERACTION), +you still get collision between particles and static/dynamic shapes, damping, +acceleration due to gravity, and the user force. +*/ +enum pFluidSimulationMethod +{ + /** + \brief Enable simulation of inter particle forces. + */ + PFS_SPH = (1<<0), + + /** + \brief Do not simulate inter particle forces. + */ + PFS_NoParticleInteraction = (1<<1), + + /** + \brief Alternate between SPH and simple particles + */ + PFS_MixedMode = (1<<2), +}; + +/** +\brief The fluid collision method +*/ +enum pFluidCollisionMethod +{ + /** + \brief collide with static objects + */ + PFCM_Static = (1<<0), + /** + \brief collide with dynamic objects + */ + PFCM_Dynamic = (1<<1), +}; + +/** @} */ + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pFluid/pFluidRenderSettings.h b/usr/Include/Core/pFluid/pFluidRenderSettings.h new file mode 100644 index 0000000..a765b6c --- /dev/null +++ b/usr/Include/Core/pFluid/pFluidRenderSettings.h @@ -0,0 +1,134 @@ +#ifndef __P_FLUID_RENDER_SETTINGS_H__ + #define __P_FLUID_RENDER_SETTINGS_H__ + +#include "pTypes.h" + + +class MODULE_API pFluidRenderSettings +{ +public: + + pFluidRenderSettings(); + + // Constructor + pFluidRenderSettings(CKContext* ctx,CK_ID entity,char* name); + + // the emitter 3d entity + CK_ID m_Entity; + CK_ID m_Texture; + CK_ID m_Group; + int m_MessageType; + VxBbox m_EntityBbox; + + pParticleRenderType mRenderType; + + int m_MaximumParticles; + // total number of particles + int totalParticles; + // particles already emitted + int particleCount; + // emits per frame + int emitsPerFrame; + // emits variation + int emitsVar; + // medium lifeSpan + float m_Life; + // life variation + float m_LifeVariation; + + // trailing particles + int m_TrailCount; + // historic of recent particles. + + // render callback + int (*m_RenderParticlesCallback)(CKRenderContext *dev,CKRenderObject *mov,void *arg); + + void SetState(CKRenderContext* dev,CKBOOL gouraud = FALSE); + // NULL terminated linked list + + // the particles pool + BYTE* m_BackPool; + + + // start size + float m_StartSize; + float m_StartSizeVar; + // end size + float m_EndSize; + float m_EndSizeVar; + + + // Blend Modes + VXBLEND_MODE m_SrcBlend; + VXBLEND_MODE m_DestBlend; + + // Colors + ///////////// + VxColor m_StartColor; + VxColor m_StartColorVar; + VxColor m_EndColor; + VxColor m_EndColorVar; + + // Texture + ///////////// + int m_InitialTextureFrame; + int m_InitialTextureFrameVariance; + int m_SpeedTextureFrame; + int m_SpeedTextureFrameVariance; + int m_TextureFrameCount; + int m_TextureFrameloop; + + // FLAGS + int m_EvolutionsFlags; + int m_VariancesFlags; + int m_InteractorsFlags; + int m_DeflectorsFlags; + int m_RenderMode; + + // Mesh + CK_ID m_Mesh; + + + // Context + CKContext* m_Context; + + pFluidEmitter* mEmitter; + + pFluidEmitter* getEmitter() const { return mEmitter; } + void setEmitter(pFluidEmitter* val) { mEmitter = val; } + + void setToDefault(); + + struct ParticleHistoric + { + inline ParticleHistoric() {} + inline ParticleHistoric(unsigned int size) : + start(0), + count(0) + { + particles.Resize(size); + } + + int start; + int count; + XArray particles; + }; + // Old particles. + XClassArray old_pos; + ParticleHistoric &GetParticleHistoric(pParticle *part); + + + CKBehavior* m_Behavior; + + volatile bool hasBeenRendered; //used for cases where we compute once and render twice + volatile bool hasBeenEnqueud; //used for cases where we compute once and render twice + + + +protected: +private: +}; + + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pJoint/pJoint.h b/usr/Include/Core/pJoint/pJoint.h new file mode 100644 index 0000000..cc455d8 --- /dev/null +++ b/usr/Include/Core/pJoint/pJoint.h @@ -0,0 +1,1119 @@ +#ifndef __PJOINT_H_ +#define __PJOINT_H_ + +#include "vtPhysXBase.h" + +/** \addtogroup Joints +@{ +*/ + +/** +\brief Abstract base class for the different types of joints. + +All joints are used to connect two dynamic bodies, or an body and the environment. + +A NULL body represents the environment. Whenever the below comments mention two bodies, +one of them may always be the environment (NULL). + +*/ +class MODULE_API pJoint { + + + public: + + + pJoint(){} + pJoint(CK3dEntity* _e); + pJoint(pRigidBody* _a,pRigidBody* _b,int _type); + + NxJoint *getJoint() { return mJoint;} + void setJoint(NxJoint*j) { mJoint = j ;} + + ////////////////////////////////////////////////////////////////////////// + protected : + + pRigidBody* m_SolidA; + pRigidBody* m_SolidB; + CK3dEntity* m_vtObjectA; + + + CK3dEntity* m_vtObjectB; + + int m_type; + + pWorld *m_pWorld; + NxJoint *mJoint; + + + + + ////////////////////////////////////////////////////////////////////////// + public : + + /** + \brief Retrieve the type of this joint. + \return The type of joint. + + \see NxJointType + */ + JType getType() const { return (JType)m_type; } + + CK3dEntity* GetVTEntA(){ return m_vtObjectA;} + CK3dEntity* GetVTEntB(){ return m_vtObjectB;} + pRigidBody *GetSolidA(); + pRigidBody *GetSolidB(); + + CK_ID mAID; + CK_ID mBID; + + + + pWorld * getWorld() const { return m_pWorld; } + void setWorld(pWorld * val) { m_pWorld = val; } + + + /** + \brief Sets the maximum force magnitude that the joint is able to withstand without breaking. + + There are two values, one for linear forces, and one for angular forces. Both values are used directly + as a value for the maximum impulse tolerated by the joint constraints. + + Both force values are MaxFloat by default. This setting makes the joint unbreakable. + The values should always be nonnegative. + + The distinction between maxForce and maxTorque is dependent on how the joint is implemented internally, + which may not be obvious. For example what appears to be an angular degree of freedom may be constrained + indirectly by a linear constraint. + + So in most practical applications the user should set both maxTorque and maxForce to low values. + + Sleeping: This call wakes the body(s) if they are sleeping. + + \param[in] maxForce Maximum force the joint can withstand without breaking. Range: (0,inf] + \param[in] maxTorque Maximum torque the joint can withstand without breaking. Range: (0,inf] + + */ + void setBreakForces(float maxForce,float maxTorque); + + /** + \brief Retrieves the max forces of a breakable joint. See #setBreakable(). + + \param[out] maxForce Retrieves the maximum force the joint can withstand without breaking. + \param[out] maxTorque Retrieves the maximum torque the joint can withstand without breaking. + */ + void getBreakForces(float& maxForce,float& maxTorque); + + /** + \brief Adds a limit plane. + + Both of the parameters are given in global coordinates. see setLimitPoint() for the meaning of limit planes. + + The plane is affixed to the body that does not have the limit point. + + The normal of the plane points toward the positive side of the plane, and thus toward the + limit point. If the normal points away from the limit point at the time of this call, the + method returns false and the limit plane is ignored. + + \note This function always returns true and adds the limit plane unlike earlier versions. This behavior + was changed to allow the joint to be serialized easily. + + Sleeping: This call wakes the body(s) if they are sleeping. + + \param[in] normal Normal for the limit plane in global coordinates. Range: direction vector + \param[in] pointInPlane Point in the limit plane in global coordinates. Range: position vector + \param[in] restitution Restitution of the limit plane. + Range: [0.0, 1.0] + Default: 0.0 + \return Always true. + + \see setLimitPoint() purgeLimitPlanes() getNextLimitPlane() + */ + int addLimitPlane(const VxVector normal, VxVector pointInPlane, float restitution=0.0f); + + /** + \brief deletes all limit planes added to the joint. + + Invalidates limit plane iterator. + + Sleeping: Does NOT wake the associated body up automatically. + + \see addLimitPlane() getNextLimitPlane() + */ + void purgeLimitPlanes(); + /** + \brief Restarts the limit plane iteration. + + Call before starting to iterate. This method may be used together with + the below two methods to enumerate the limit planes. + This iterator becomes invalid when planes + are added or removed, or the plane iterator mechanism is + invoked on another joint. + + \see hasMoreLimitPlanes() getNextLimitPlane() + */ + void resetLimitPlaneIterator(); + /** + \brief Returns true until the iterator reaches the end of the set of limit planes. + + Adding or removing elements does not reset the iterator. + + \return True if the iterator has not reached the end of the sequence of limit planes. + + + \see resetLimitPlaneIterator() getNextLimitPlane() + */ + int hasMoreLimitPlanes (); + + /** + \brief Returns the next element pointed to by the limit plane iterator, and increments the iterator. + + Places the global frame plane equation (consisting of normal and d, the 4th + element) coefficients in the argument references. The plane equation is of the form: + + dot(n,p) + d == 0 (n = normal, p = a point on the plane) + + \param[out] planeNormal Used to store the plane normal. + \param[out] planeD Used to store the plane 'D'. + \param[out] restitution Optional, used to store restitution of the limit plane. + \return Returns true if the limit plane is satisfied. + + \see resetLimitPlaneIterator() hasMoreLimitPlanes() + */ + int getNextLimitPlane (VxVector &planeNormal, float &planeD,float *restitution=NULL); + /** + \brief Sets the limit point. + + The point is specified in the global coordinate frame. + + All types of joints may be limited with the same system: + You may elect a point attached to one of the two bodies to act as the limit point. + You may also specify several planes attached to the other body. + + The points and planes move together with the body they are attached to. + + The simulation then makes certain that the pair of bodies only move relative to each other + so that the limit point stays on the positive side of all limit planes. + + the default limit point is (0,0,0) in the local frame of actor2. + Calling this deletes all existing limit planes. + + Sleeping: This call wakes the body(s) if they are sleeping. + + \param[in] point The limit reference point defined in the global frame. Range: position vector + \param[in] pointIsOnActor2 if true the point is attached to the second body. Otherwise it is attached to the first. + + \sa getLimitPoint() addLimitPlane() + */ + void setLimitPoint(VxVector point,bool pointIsOnActor2=true); + + /** + \brief Retrieves the global space limit point. + + Returns true if the point is fixed on actor2. + + \param[out] worldLimitPoint Used to store the global frame limit point. + \return True if the point is fixed to body 2 otherwise the point is fixed to body 1. + + \see setLimitPoint() addLimitPlane() + */ + bool getLimitPoint(VxVector & worldLimitPoint); + + + bool IsValid(); + CKContext *context; + + pJointD6 *castD6Joint(); + pJointFixed*castFixed(); + pJointDistance*castDistanceJoint(); + pJointBall *castBall(); + pJointPulley *castPulley(); + pJointRevolute *castRevolute(); + pJointPrismatic *castPrismatic(); + pJointCylindrical *castCylindrical(); + pJointPointInPlane *castPointInPlane(); + pJointPointOnLine *castPointOnLine(); + + void setLocalAnchor0(VxVector anchor0); + void setLocalAnchor1(VxVector anchor1); + + VxVector getGlobalAxis(); + void setGlobalAxis(VxVector axis); + + VxVector getGlobalAnchor(); + void setGlobalAnchor(VxVector anchor); + + + int getNbLimitPlanes(); + + + virtual void enableCollision(int collision){} + + virtual ~pJoint(){} + +}; +/** +\brief A prismatic joint permits relative translational movement between two bodies along +an axis, but no relative rotational movement. + +\image html prismJoint.png + +

Creation

+ +\include NxPrismaticJoint_Create.cpp + +\sa pFactory::createPrismaticJoint() +*/ +class MODULE_API pJointPrismatic : public pJoint +{ + +public: + pJointPrismatic(pRigidBody* _a,pRigidBody* _b); + + + void setGlobalAxis(VxVector axis); + void setGlobalAnchor(VxVector anchor); + void enableCollision(int collision); + + +}; +/** +\brief Cylindrical Joints permit relative translational movement between two bodies along +an axis, and also relative rotation along the axis. + +\image html cylinderJoint.png + + +\sa pFactory::createCylindricalJoint() +*/ +class MODULE_API pJointCylindrical: public pJoint +{ + +public: + pJointCylindrical(pRigidBody* _a,pRigidBody* _b); + + void setGlobalAxis(VxVector axis); + void setGlobalAnchor(VxVector anchor); + void enableCollision(int collision); + + +}; + +/** +\brief A point in plane joint constrains a point on one actor to only move inside a plane attached to another actor. The point attached to the plane is defined by the anchor point. The joint's axis specifies the plane normal. + + DOFs removed: 1
+ DOFs remaining: 5
+ +\image html pointInPlaneJoint.png + + +\sa pFactory::createPointInPlaneJoint() +*/ +class MODULE_API pJointPointInPlane: public pJoint +{ + +public: + pJointPointInPlane(pRigidBody* _a,pRigidBody* _b); + + /** + \brief Sets the global axis. + \param[in] axis The new axis. + */ + void setGlobalAxis(VxVector axis); + /** + \brief Sets the global anchor. + \param[in] anchor The new anchor. + */ + void setGlobalAnchor(VxVector anchor); + /** + \brief Enables collision between both bodies. + \param[in] collision Collision is enabled. + */ + void enableCollision(int collision); + + +}; +/** +\brief A point on line joint constrains a point on one actor to only move along a line attached to another actor. The point attached to the line is the anchor point for the joint. The line through this point is specified by its direction (axis) vector. + +DOFs removed: 2
+DOFs remaining: 4
+ +\image html pointOnLineJoint.png + + +\sa pFactory::createPointInPlaneJoint() +*/ +class MODULE_API pJointPointOnLine: public pJoint +{ + +public: + pJointPointOnLine(pRigidBody* _a,pRigidBody* _b); + + /** + \brief Sets the global axis. + \param[in] axis The new axis. + */ + void setGlobalAxis(VxVector axis); + /** + \brief Sets the global anchor. + \param[in] anchor The new anchor. + */ + void setGlobalAnchor(VxVector anchor); + /** + \brief Enables collision between both bodies. + \param[in] collision Collision is enabled. + */ + void enableCollision(int collision); + +}; + +/** +\brief A joint which behaves in a similar way to a hinge or axle. + +\image html revoluteJoint.png + +A hinge joint removes all but a single rotational degree of freedom from two objects. +The axis along which the two bodies may rotate is specified with a point and a direction +vector. + +An example for a revolute joint is a door hinge. Another example would be using a revolute +joint to attach rotating fan blades to a ceiling. The revolute joint could be motorized, +causing the fan to rotate. + +

Revolute Joint Limits

+ +A revolute joint allows limits to be placed on how far it rotates around the joint axis. For example, a hinge on a door cannot rotate through 360 degrees; rather, it can rotate between 20 degrees and 180 degrees. +The angle of rotation is measured using the joints normal (axis orthogonal to the joints axis). This is the angle reported by NxRevoluteJoint::getAngle(). The limits are specified as a high and low limit, which must satisfy the condition -Pi < low < high + +Note : The white region represents the allowable rotation for the joint. + +

Limitations of Revolute Joint Limits

+As shown below, it is not possible to specify certain limit configurations without rotating the joint axes, due to the restrictions on the values of low and high: +\image html revoluteLimitLimitation.png + +To achieve this configuration, it is necessary to rotate the joint counter-clockwise so that low is below the 180 degree line. + +NOTE: If the angular region that is prohibited by the twist limit (as in the above figures) is very small, only a few degrees or so, then the joint may "push through" the limit and out on the other side if the relative angular velocity is large enough in relation to the time step. Care must be taken to make sure the limit is "thick" enough for the typical angular velocities it will be subjected to. + +\sa pFactory::createRevoluteJoint() +*/ +class MODULE_API pJointRevolute : public pJoint +{ + +public: + pJointRevolute(pRigidBody* _a,pRigidBody* _b); + + + + /** + \brief Sets the global axis. + \param[in] axis The new axis. + */ + void setGlobalAxis(const VxVector& axis); + /** + \brief Sets the global anchor. + \param[in] anchor The new anchor. + */ + void setGlobalAnchor(const VxVector& anchor); + + /** + \brief Retrieves the optional spring. + \return The spring. + \sa setSpring() + */ + pSpring getSpring(); + /** + \brief Sets an optional spring. + \param[in] spring The spring. + \return TRUE if spring was valid. + \sa getSpring() + */ + bool setSpring(pSpring spring); + + + /** + \brief Retrieves an optional high limit for angular motion of the joint. + \sa setHighLimit() + */ + pJointLimit getHighLimit(); + /** + \brief Sets an optional high limit for angular motion of the joint. + \param[in] limit The new high limit. + \return True if the limit was valid. + \sa getLowLimit() + */ + bool setHighLimit(pJointLimit limit); + /** + \brief Retrieves an optional low limit for angular motion of the joint. + \sa setLowLimit() + */ + pJointLimit getLowLimit(); + /** + \brief Sets an optional high limit for angular motion of the joint. + \param[in] limit The new low limit. + \return True if the limit was valid. + \sa setLowLimit() + */ + bool setLowLimit(pJointLimit limit); + + /** + \brief Sets a motor. + \param[in] motor The new motor settings. + \return True if the motor was valid. + \sa getMotor() + */ + bool setMotor(pMotor motor); + /** + \brief Retrieves a motor. + \return The motor settings + \sa setMotor() + */ + pMotor getMotor(); + /** + \brief Enables collision between both bodies. + \param[in] collision Collision is enabled. + */ + void enableCollision(bool collision); + void setProjectionMode(ProjectionMode mode); + void setProjectionDistance(float distance); + void setProjectionAngle(float angle); + + + + +protected: +private: + +}; + + +/*! + * \brief A pulley joint simulates a rope between two objects passing over 2 pulleys. + * + * \image html pulleyJoint.png + * + * + The pulley joint simulates a rope that can be thrown across a pair of pulleys. In this way, it is similar to the + distance joint (the length of the rope is the distance) but the rope doesn't connect the two bodies along the + shortest path, rather it leads from the connection point on one actor to the pulley point (fixed in world space), + then to the second pulley point, and finally to the other actor. + + The pulley joint can also be used to simulate a rope around a single point by making the pulley points coincide. + + + Note that a setup where either object attachment point coincides with its corresponding pulley suspension point in + world space is invalid. In this case, the simulation would be unable to determine the appropriate direction in which to pull the + object and a random direction would result. The simulation will be unstable. Note that it is also invalid to allow the simulation + to end up in such a state. + +*/ +class MODULE_API pJointPulley : public pJoint +{ + +public: + pJointPulley(pRigidBody* _a,pRigidBody* _b); + + /** + \brief Sets the attachment point of joint in bodie[0]'s space. + + \param[in] VxVector anchor + + \return void + + @see pJointPulley::setLocalAnchorB + */ + void setLocalAnchorA(VxVector anchor); + /** + \brief Sets the attachment point of joint in bodie[1]'s space. + \param[in] VxVector anchor + + \return void + + @see pJointPulley::setLocalAnchorB + */ + void setLocalAnchorB(VxVector anchor); + + /** + \brief Returns the attachment point of joint in bodie[0]'s space. + + \return VxVector + + @see pJointPulley::setLocalAnchorB + */ + VxVector getLocalAnchorA(); + /** + \brief Returns the attachment point of joint in bodie[0]'s space. + + \param[in] VxVector anchor + + \return VxVector + + @see pJointPulley::setLocalAnchorA + */ + VxVector getLocalAnchorB(); + + /** + \brief Sets the suspension point of joint in world space. + + \param[in] VxVector pulley + + \return void + + @see pJointPulley::setPulleyB + */ + void setPulleyA(VxVector pulley); + /** + \brief Sets the suspension point of joint in world space. + + \param[in] VxVector pulley + + \return void + + @see pJointPulley::setPulleyA + */ + void setPulleyB(VxVector pulley); + + /** + \brief Returns the suspension point of joint in world space. + + \return VxVector + + @see pJointPulley::getPulleyB + */ + VxVector getPulleyA(); + /** + \brief Returns the suspension point of joint in world space. + + \return VxVector + + @see pJointPulley::getPulleyA + */ + VxVector getPulleyB(); + + /** + \brief Sets how stiff the constraint is, between 0 and 1 (stiffest). + + \param[in] float stiffness + - Range: [0,1.0f)
+ - Default: 1.0f + + \return void + + @see getStiffness() + */ + void setStiffness(float stiffness); + + /** + \brief Returns how stiff the constraint is, between 0 and 1 (stiffest). + + \return float + + @see setStiffness() + */ + float getStiffness(); + + + /** + \brief Sets transmission ratio. + + \param[in] float ratio + - Range: [0,1.0f)
+ - Default: 1.0f + + \return void + + @see ::getRatio() + */ + void setRatio(float ratio); + + /** + \brief Gets transmission ratio. + + \return float + + @see setRatio + */ + float getRatio(); + + + /** + \brief Set true if the joint also has to maintain a minimum distance, not just a maximum. + + \param[in] bool rigid + - Range: [true,false)
+ - Default:false + \return void + + @see ::isRigid() + */ + void setRigid(bool rigid); + + + /** + \brief Returns true if the joint also has to maintain a minimum distance, not just a maximum. + + \return bool + + @see + */ + bool isRigid(); + + /** + \brief + + Sets the rest length of the rope connecting the two objects. + + The distance is computed as ||(pulley0 - anchor0)|| + ||(pulley1 - anchor1)|| * ratio. + + \param[in] float distance + - Range: [0,inf)
+ - Default: 0.0f + + \return void + + @see getDistance() + */ + void setDistance(float distance); + + /** + \brief Returns the rest length of the rope connecting the two objects. + + \return float + + @see setDistance() + */ + float getDistance(); + + + /** + \brief Sets motor parameters for the joint. + + \param[in] pMotor motor + - Range: [#pMotor)
+ - Default: no motor + + \return void + + @see getMotor() + */ + void setMotor(pMotor motor); + + /** + \brief Returns motor parameter for the joint. + + \return pMotor + + @see setMotor() + */ + pMotor getMotor(); + + + /** + \brief For convenience only. For the case the pulley hooks are moving, the SDK corrects the these points according to reference entities. + + \return void + + @see + */ + void setFollowPulleyReferences(bool follow); + + /** + \brief Sets the first pulley. + + \return void + + @see setPulleyBReference() + */ + void setPulleyAReference(CK3dEntity*ent); + + /** + \brief Sets the second pulley. + + \return void + + @see setPulleyAReference() + */ + void setPulleyBReference(CK3dEntity*ent); + + + /** + \brief Returns the first pulley reference. + + \return void + + @see setPulley1Ref() + */ + CK3dEntity *getPulleyAReference(); + + /** + \brief Sets the second pulley reference + + \return void + + @see setPulley1Ref() + */ + CK3dEntity *getPulleyBReference(); + + /** + \brief Enables collision between both bodies. + + \return void + + @see setPulley1Ref() + */ + void enableCollision(bool collision); + + +private : + CK_ID m_Pulley0Reference0; + CK_ID m_Pulley0Reference1; + bool mFollowPulleyReferences; + + + + + + public : +}; + +/** +\brief A D6 joint is a general constraint between two actors. + + It allows the user to individually define the linear and rotational degrees of freedom. + It also allows the user to configure the joint with limits and driven degrees of freedom as they wish. + +*/ +class MODULE_API pJointD6 : public pJoint +{ + +public: + pJointD6(pRigidBody* _a,pRigidBody* _b); + + + /** + \brief Sets the motion mode for the twist axis. + \param[in] mode The new mode. + \sa getTwistMotionMode() + */ + void setTwistMotionMode(D6MotionMode mode); + D6MotionMode getTwist(); + /** + \brief Sets the motion mode for the swing1 axis. + \param[in] mode The new mode. + \sa getSwing1MotionMode() + */ + void setSwing1MotionMode(D6MotionMode mode); + D6MotionMode getSwing1(); + /** + \brief Sets the motion mode for the swing2 axis. + \param[in] mode The new mode. + \sa getSwing2MotionMode() + */ + void setSwing2MotionMode(D6MotionMode mode); + D6MotionMode getSwing2(); + /** + \brief Sets the motion mode for the linear x axis. + \param[in] mode The new mode + \sa getXMotionMode() + */ + void setXMotionMode(D6MotionMode mode); + D6MotionMode getXMotion(); + /** + \brief Sets the motion mode for the linear y axis. + \param[in] mode The new mode + \sa getZMotionMode() + */ + void setYMotionMode(D6MotionMode mode); + D6MotionMode getYMotion(); + /** + \brief Sets the motion mode for the linear z axis. + \param[in] mode The new mode + \sa getZMotionMode() + */ + void setZMotionMode(D6MotionMode mode); + D6MotionMode getZMotion(); + + + int setLinearLimit(pJD6SoftLimit limit); pJD6SoftLimit getLinearLimit(); + int setSwing1Limit(pJD6SoftLimit limit); pJD6SoftLimit getSwing1Limit( ); + int setSwing2Limit(pJD6SoftLimit limit); pJD6SoftLimit getSwing2Limit(); + int setTwistLowLimit(pJD6SoftLimit value); pJD6SoftLimit getTwistLowLimit(); + int setTwistHighLimit(pJD6SoftLimit value); pJD6SoftLimit getTwistHighLimit(); + + pJD6Drive getXDrive(); int setXDrive(pJD6Drive drive); + pJD6Drive getYDrive(); int setYDrive(pJD6Drive drive); + pJD6Drive getZDrive(); int setZDrive(pJD6Drive drive); + + pJD6Drive getSwingDrive(); int setSwingDrive(pJD6Drive drive); + pJD6Drive getTwistDrive();int setTwistDrive(pJD6Drive drive); + pJD6Drive getSlerpDrive();int setSlerpDrive(pJD6Drive drive); + + /**\brief If the type of xDrive (yDrive,zDrive) is #D6DT_Position, drivePosition defines the goal position. + + Range: position vector
+ Default: Zero + */ + void setDrivePosition(VxVector pos); + + /**\brief If the type of swingDrive or twistDrive is #D6DT_Position, driveOrientation defines the goal orientation. + + Range: position vector
+ Default: Zero + */ + void setDriveRotation(VxQuaternion rot); + + /**\brief If the type of xDrive (yDrive,zDrive) is D6DT_Velocity, driveLinearVelocity defines the goal linear velocity. + + Range: unit quaternion
+ Default: Identity Quaternion + + */ + void setDriveLinearVelocity(VxVector linVel); + + /**\brief If the type of swingDrive or twistDrive is D6DT_Velocity, driveAngularVelocity defines the goal angular velocity. + + - driveAngularVelocity.x - goal angular velocity about the twist axis + - driveAngularVelocity.y - goal angular velocity about the swing1 axis + - driveAngularVelocity.z - goal angular velocity about the swing2 axis + + + Range: angular velocity vector
+ Default: Zero + + */ + void setDriveAngularVelocity(VxVector angVel); + + /** + \brief Enables collision between the two bodies. + \param[in] Collide or not. + */ + void enableCollision(bool value); + /** + \brief Sets the global anchor. + \param[in] anchor The new anchor. + */ + void setGlobalAnchor(VxVector anchor); + /** + \brief Sets the global axis. + \param[in] axis The new axis. + */ + void setGlobalAxis(VxVector axis); + void setRatio(float ratio); + void setProjectionMode(ProjectionMode mode); + void setProjectionDistance(float distance); + void setProjectionAngle(float angle); + + protected: + private: + +}; + + + +/** +\brief A distance joint maintains a certain distance between two points on two bodies. + +\image html distanceJoint.png + +\sa pFactory::createDistanceJoint() +*/ +class MODULE_API pJointDistance : public pJoint +{ + + public: + pJointDistance(pRigidBody* _a,pRigidBody* _b); + + /** + \brief Sets the minimum rest length of the rope or rod between the two anchor points. + \param[in] distance The new rest length. The value must be non-zero! + \sa getMinDistance() + */ + void setMinDistance(float distance); + /** + \brief Sets the maximum rest length of the rope or rod between the two anchor points. + \param[in] distance The new rest length.The value must be non-zero! + \sa getMaxDistance() + */ + void setMaxDistance(float distance); + /** + \brief Sets the attachment point of the joint in bodies[0] space. + \param[in] anchor The new anchor. + \sa getLocalAnchor0() + */ + void setLocalAnchor0(VxVector anchor); + /** + \brief Sets the attachment point of the joint in bodies[1] space. + \param[in] anchor The new anchor. + \sa getLocalAnchor1() + */ + void setLocalAnchor1(VxVector anchor); + /** + \brief Retrieves the attachment point of the joint in bodies[1] space. + \return anchor The local anchor 0 . + \sa setLocalAnchor0() + */ + VxVector getLocalAnchor0(); + /** + \brief Retrieves the attachment point of the joint in bodies[1] space. + \return The local anchor 1. + \sa setLocalAnchor1() + */ + VxVector getLocalAnchor1(); + /** + \brief Retrieves the minimum rest length of the rope or rod between the two anchor points. + \return The minimum distance amongst both bodies. + \sa setMinDist() + */ + float getMinDistance(); + /** + \brief Retrieves the maximum rest length of the rope or rod between the two anchor points. + \return The maximum distance amongst both bodies. + \sa setMaxDist() + */ + float getMaxDistance(); + /** + \brief Retrieves the spring which keeps both bodies springy. + \return The spring. + \sa setSpring() + */ + pSpring getSpring(); + /** + \brief Makes the joint springy. + \param[in] spring The new rest length. The spring.targetValue field is not used. + \sa getSpring() + */ + bool setSpring(pSpring spring); + + /** + \brief Enables collision between the two bodies. + \param[in] Collide or not. + */ + void enableCollision(int collision); + + + protected: + private: + +}; +class MODULE_API pJointFixed : public pJoint +{ +public: + + pJointFixed(pRigidBody* _a,pRigidBody* _b); + protected: + private: +}; + +/** +\brief A sphere joint constrains two points on two bodies to coincide. + +This point, specified in world space (this guarantees that the points coincide +to start with) is the only parameter that has to be specified. + +\image html sphericalJoint.png + + +*/ +class MODULE_API pJointBall : public pJoint +{ + public: + + pJointBall(pRigidBody* _a,pRigidBody* _b); + pJointBall(pRigidBody* _a,pRigidBody* _b,VxVector anchor); + + /** + \brief Retrieves the global space anchor. + \return The joints anchor. + \sa getAnchor() + */ + VxVector getAnchor(); + /** + \brief Sets the global space anchor. + \param[in] worldLimitPoint Used to store the global frame limit point. + \sa getAnchor() + */ + void setAnchor(const VxVector& anchor); + /** + \brief Sets the limit axis defined in the joint space of body a. + \param[in] swingLimitAxis The new limit axis. + \sa getAnchor() + */ + void setSwingLimitAxis(const VxVector& swingLimitAxis); + /** + \brief Sets the swing limit of the twist axis. + \param[in] limit The new swing limit axis. + \return True if the limit was valid. + \sa getSwingLimit() + */ + bool setSwingLimit(pJointLimit limit); + /** + \brief Sets the high rotation limit around the twist axis. + \param[in] limit The new twist high limit. + \return True if the limit was valid. + \sa getTwistLowLimit() + */ + bool setTwistHighLimit(pJointLimit limit); + /** + \brief Sets the high rotation limit around the twist axis. + \param[in] limit The new twist low limit. + \return True if the limit was valid. + \sa getTwistLowLimit() + */ + bool setTwistLowLimit(pJointLimit limit); + + /** + \brief Sets a spring that works against swinging. + \param[in] spring The new spring. + \return True if the spring was valid. + \sa getSwingSpring() + */ + bool setSwingSpring(pSpring spring); + /** + \brief Sets a spring that works against twisting. + \param[in] spring The new spring. + \return True if the spring was valid. + \sa getTwistSpring() + */ + bool setTwistSpring(pSpring spring); + /** + \brief Sets a spring that lets the joint get pulled apart. + \param[in] spring The new spring. + \return True if the spring was valid. + \sa getJointSpring() + */ + bool setJointSpring(pSpring spring); + + pJointLimit getSwingLimit(); + pJointLimit getTwistHighLimit(); + pJointLimit getTwistLowLimit(); + + pSpring getSwingSpring(); + pSpring getTwistSpring(); + pSpring getJointSpring(); + void enableFlag(int flag,bool enable); + + /** + \brief Enables collision between the two bodies. + \param[in] collision Collide or not. + */ + void enableCollision(bool collision); + + void setProjectionMode(ProjectionMode mode); + void setProjectionDistance(float distance); + void setProjectionAngle(float angle); + + + + + protected: + private: +}; + +/** @} */ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pJoint/pJointTypes.h b/usr/Include/Core/pJoint/pJointTypes.h new file mode 100644 index 0000000..9797155 --- /dev/null +++ b/usr/Include/Core/pJoint/pJointTypes.h @@ -0,0 +1,200 @@ +#ifndef __PJOINTTYPES_H__ +#define __PJOINTTYPES_H__ + + +/** \addtogroup Joints +@{ +*/ + + +/** +\brief Describes a joint motor. Some joints can be motorized, this allows them to apply a force to cause attached actors to move. Joints which can be motorized: #pJointPulley #pJointRevolute is used for a similar purpose with pJointD6. + +*/ +class pMotor +{ + +public : + + /** + The relative velocity the motor is trying to achieve.Default = 0.0f. + */ + float targetVelocity; + /** + The maximum force (or torque) the motor can exert.Default = 0.0f. + */ + float maximumForce; + /** + If true, motor will not brake when it spins faster than velTarget.Default = false. + */ + bool freeSpin; + + pMotor() + { + targetVelocity = 0.0f; + maximumForce =0.0f; + freeSpin = false; + } + +}; +/** +\brief Describes a joint limit. pJointLimit is registered as custom structure #pJLimit and can be accessed or modified through parameter operations.
+ +This is used for ball joints. +\sa \ref PJBall. + +*/ +class pJointLimit +{ + +public: + + /** + [not yet implemented!] Limit can be made softer by setting this to less than 1. Default = 0.0f; + */ + float hardness; + /** + The angle / position beyond which the limit is active. Default = 0.0f; + */ + float value; + /** + The limit bounce. Default = 0.0f; + */ + float restitution; + pJointLimit() + { + hardness = 0.0f; + value = 0.0f; + restitution = 0.0f; + } + + pJointLimit(float _h,float _r, float _v) + { + hardness = _h; + restitution = _r; + value = _v; + } + +}; + + + +/** +\brief Describes a joint soft limit for D6 usage. pJD6SoftLimit is registered as custom structure #pJD6SLimit and can be accessed or modified through parameter operations.
+\sa #PJD6. +*/ +class pJD6SoftLimit +{ + + + +public: + /**\brief If spring is greater than zero, this is the damping of the spring. + */ + float damping; + /**\brief If greater than zero, the limit is soft, i.e. a spring pulls the joint back to the limit. + + Range: [0,inf)
+ Default: 0.0 + */ + float spring; + /**\brief The angle or position beyond which the limit is active. + + Which side the limit restricts depends on whether this is a high or low limit. + + Unit: Angular: Radians + Range: Angular: (-PI,PI)
+ Range: Positional: [0.0,inf)
+ Default: 0.0 + */ + float value; + /**\brief Controls the amount of bounce when the joint hits a limit. +
+
+ A restitution value of 1.0 causes the joint to bounce back with the velocity which it hit the limit. A value of zero causes the joint to stop dead. + + In situations where the joint has many locked DOFs (e.g. 5) the restitution may not be applied correctly. This is due to a limitation in the solver which causes the restitution velocity to become zero as the solver enforces constraints on the other DOFs. + + This limitation applies to both angular and linear limits, however it is generally most apparent with limited angular DOFs. + + Disabling joint projection and increasing the solver iteration count may improve this behavior to some extent. + + Also, combining soft joint limits with joint motors driving against those limits may affect stability. + + Range: [0,1]
+ Default: 0.0 + + */ + float restitution; + pJD6SoftLimit() + { + damping = 0.0f; + spring = 0.0f; + value = 0.0f; + restitution = 0.0f; + } + pJD6SoftLimit(float _damping,float _spring,float _value,float _restitution) + { + + damping = _damping; + spring = _spring; + value = _value; + restitution = _restitution; + } + +}; +/** +\brief Class used to describe drive properties for a #pJointD6. +*/ +class pJD6Drive +{ + +public: + + /** + Damper coefficient + Default: 0 + Range: [0,inf) + */ + float damping; + /** + Spring coefficient + + Default: 0 + Range: (-inf,inf) + */ + float spring; + /** + The maximum force (or torque) the drive can exert. + + Default: FloatMax + Range: [0,inf) + */ + float forceLimit; + /** + Type of drive to apply.See #D6DriveType. + Default: FloatMax + Range: [0,inf) + */ + int driveType; + + pJD6Drive() + { + damping = 0.0f; + spring = 0.0f; + forceLimit = 3.402823466e+38F; + driveType = 0; + + } + pJD6Drive(float _damping,float _spring,float _forceLimit,int _driveType) + { + damping = _damping; + spring = _spring; + forceLimit = _forceLimit; + driveType = _driveType; + } + +}; +/** @} */ + +#endif // __PJOINTTYPES_H__ \ No newline at end of file diff --git a/usr/Include/Core/pRigidBody/pRigidBody.h b/usr/Include/Core/pRigidBody/pRigidBody.h new file mode 100644 index 0000000..84595e5 --- /dev/null +++ b/usr/Include/Core/pRigidBody/pRigidBody.h @@ -0,0 +1,1608 @@ +#if !defined(EA_C2D3E6DE_B1A5_4f07_B3FA_73F108249451__INCLUDED_) +#define EA_C2D3E6DE_B1A5_4f07_B3FA_73F108249451__INCLUDED_ + + +#include "vtPhysXBase.h" +#include "pReferencedObject.h" +#include "pCallbackObject.h" + + +/** \addtogroup RigidBody +@{ +*/ + +struct pContactModifyData +{ + + float minImpulse; //!< Minimum impulse value that the solver can apply. Normally this should be 0, negative amount gives sticky contacts. + float maxImpulse; //!< Maximum impulse value that the solver can apply. Normally this is FLT_MAX. If you set this to 0 (and the min impulse value is 0) then you will void contact effects of the constraint. + VxVector error; //!< Error vector. This is the current error that the solver should try to relax. + VxVector target; //!< Target velocity. This is the relative target velocity of the two bodies. + + /** + \brief Constraint attachment point for shape 0. + + If the shape belongs to a dynamic actor, then localpos0 is relative to the body frame of the actor. + Alternatively it is relative to the world frame for a static actor. + */ + VxVector localpos0; + + /** + \brief Constraint attachment point for shape 1. + + If the shape belongs to a dynamic actor, then localpos1 is relative to the body frame of the actor. + Alternatively it is relative to the world frame for a static actor. + */ + VxVector localpos1; + + /** + \brief Constraint orientation quaternion for shape 0 relative to shape 0s body frame for dynamic + actors and relative to the world frame for static actors. + + The constraint axis (normal) is along the x-axis of the quaternion. + The Y axis is the primary friction axis and the Z axis the secondary friction axis. + */ + VxQuaternion localorientation0; + + + /** + \brief Constraint orientation quaternion for shape 1 relative to shape 1s body frame for dynamic + actors and relative to the world frame for static actors. + + The constraint axis (normal) is along the x-axis of the quaternion. + The Y axis is the primary friction axis and the Z axis the secondary friction axis. + */ + VxQuaternion localorientation1; + + /** + \brief Static friction parameter 0. + + \note 0 does not have anything to do with shape 0/1, but is related to anisotropic friction, + 0 is the primary friction axis. + */ + float staticFriction0; + + /** + \brief Static friction parameter 1. + + \note 1 does not have anything to do with shape 0/1, but is related to anisotropic friction, + 0 is the primary friction axis. + */ + float staticFriction1; + + /** + \brief Dynamic friction parameter 0. + + \note 0 does not have anything to do with shape 0/1, but is related to anisotropic friction, + 0 is the primary friction axis. + */ + float dynamicFriction0; + + /** + \brief Dynamic friction parameter 1. + + \note 1 does not have anything to do with shape 0/1, but is related to anisotropic friction, + 0 is the primary friction axis. + */ + float dynamicFriction1; + float restitution; //!< Restitution value. + +}; + +struct pCollisionsEntry +{ + VxVector sumNormalForce; + VxVector sumFrictionForce; + VxVector faceNormal; + VxVector point; + xU32 faceIndex; + float pointNormalForce; + /*float patchNormalForce;*/ + NxActor *actors[2]; + pRigidBody *bodyA; + pRigidBody *bodyB; + int eventType; + float distance; + CK_ID shapeEntityA; + CK_ID shapeEntityB; + + + pCollisionsEntry(){ + + bodyB = bodyA = NULL; + actors[0]=NULL; + actors[1]=NULL; + eventType; + distance = pointNormalForce = 0.0f; + shapeEntityA = shapeEntityB = 0 ; + + + } +}; +typedef XArrayCollisionsArray; + + + + +/** +\brief pRigidBody is the main simulation object in the physics SDK. + +The body is owned by and contained in a pWorld. + + +

Creation

+Instances of this class are created by calling #pFbodyy::createBody() and deleted with #NxScene::deleteBody(). + +See #pObjectDescr for a more detailed description of the parameters which can be set when creating a body. + +//class MODULE_API pRigidBody : public xEngineObjectAssociation + +class MODULE_API pRigidBody : public pStoredObjectAssociation + +*/ +class MODULE_API pRigidBody : + public xEngineObjectAssociation, + public pCallbackObject +{ + +public: + pRigidBody(CK3dEntity* _e); + pRigidBody(CK3dEntity* _e,pWorld *world); + virtual ~pRigidBody(){} + + void test(); + + pObjectDescr *mInitialDescription; + + pObjectDescr * getInitialDescription() const { return mInitialDescription; } + void setInitialDescription(pObjectDescr * val) { mInitialDescription = val; } + void onICRestore(CK3dEntity* parent,pRigidBodyRestoreInfo *restoreInfo); + + bool hasBrokenJoint; + + + int onJointBreak(pBrokenJointEntry *entry); + + /************************************************************************************************/ + /** @name Callback handler + */ + //@{ + + + bool onSubShapeTransformation(bool fromPhysicToVirtools=true,bool position=true,bool rotation=true,CK3dEntity*parent=NULL,bool children=true); + bool onMove(bool position,bool rotation,VxVector pos,VxQuaternion quad); + + void processScriptCallbacks(); + + + //---------------------------------------------------------------- + // + // collision notification + // + void onContactNotify(pCollisionsEntry *collisionData); + void setContactScript(int behaviorID,int eventMask); + + /** + \brief Sets the force threshold for contact reports. + + See #getContactReportThreshold(). + + The actor must be dynamic. + + \param[in] threshold Force threshold for contact reports. + - Range: (0,inf) + + @see getContactReportThreshold getContactReportFlags pContactPairFlag + */ + void setContactReportThreshold(float threshold); + /** + \brief Retrieves the force threshold for contact reports. + + The contact report threshold is a force threshold. If the force between + two actors exceeds this threshold for either of the two actors, a contact report + will be generated according to the union of both body' contact report threshold flags. + See #getContactReportFlags(). + + The body must be dynamic. The threshold used for a collision between a dynamic actor + and the static environment is the threshold of the dynamic actor, and all contacts with + static actors are summed to find the total normal force. + + \return Force threshold for contact reports. + + @see setContactReportThreshold getContactReportFlags pContactPairFlag + */ + float getContactReportThreshold(); + + + void setContactReportFlags(pContactPairFlags flags); + int getContactReportFlags(); + + ////////////////////////////////////////////////////////////////////////// + // + // joint break events + // + void setJointBreakScript(int behaviorID,CK3dEntity *shapeReference = NULL); + + + //---------------------------------------------------------------- + // + // trigger notification + // + void setTriggerScript(int behaviorID,int eventMask,CK3dEntity *shapeReference = NULL); + + int onTrigger(pTriggerEntry *report); + //---------------------------------------------------------------- + // + // contact modification + // + void setContactModificationScript(int behaviorID); + + bool onContactConstraint(int& changeFlags,CK3dEntity *sourceObject,CK3dEntity *otherObject,pContactModifyData *data); + //---------------------------------------------------------------- + // + // raycast hit + // + virtual void setRayCastScript(int val); + virtual bool onRayCastHit(NxRaycastHit *report); + + //@} + + /************************************************************************************************/ + /** @name Collision + */ + //@{ + + void setTriggerFlags(pTriggerFlags flags,CKBeObject *shapeReference=NULL); + pTriggerFlags getTriggerFlags(CKBeObject *shapeReference=NULL); + + int handleContactPair(NxContactPair* pair,int shapeIndex); + int handleContactPairWheel(NxContactPair* pair,int shapeIndex); + + /** + \brief Sets 128-bit mask used for collision filtering. See comments for ::pGroupsMask + + Sleeping: Does NOT wake the associated body up automatically. + + \param[in] shape Reference The sub shape reference object. Leave blank to set the bodies initial shapes groups mask. + \param[in] mask The group mask to set for the shape. + + @see getGroupsMask() + */ + void setGroupsMask(CK3dEntity *shapeReference,const pGroupsMask& mask); + + pGroupsMask getGroupsMask(CK3dEntity *shapeReference); + + + + //@} + + /************************************************************************************************/ + /** @name Velocity + */ + //@{ + + /** + \brief Retrieves the angular velocity of a rigid body. + + \return Vector + + @see setAngularVelocity() getLinearVelocity() + + \warning The body must be dynamic. + + */ + VxVector getAngularVelocity()const; + /** + \brief Retrieves the linear velocity of a rigid body. + \return Vector + \sa setLinearVelocity() getAngularVelocity() + \warning The body must be dynamic. + */ + VxVector getLinearVelocity()const; + /** + \brief Retrieves the maximum angular velocity permitted for this body. + \return float + \sa setMaxAngularVelocity + \warning The body must be dynamic. + */ + float getMaxAngularSpeed()const; + /** + \brief Lets you set the maximum angular velocity permitted for this body. + + Because for various internal computations, very quickly rotating bodies introduce error + into the simulation, which leads to undesired results. + + With PhysicManager::setParameter(EX_MAX_ANGULAR_VELOCITY) you can set the default maximum velocity for bodies created + after the call. Bodies' high angular velocities are clamped to this value. + + However, because some bodies, such as car wheels, should be able to rotate quickly, you can override the default setting + on a per-body basis with the below call. Note that objects such as wheels which are approximated with spherical or + other smooth collision primitives can be simulated with stability at a much higher angular velocity than, say, a box that + has corners. + + Note: The angular velocity is clamped to the set value before the solver, which means that + the limit may still be momentarily exceeded. + + \param[in] val Max allowable angular velocity for body. Range: (0,inf) + + \sa getMaxAngularVelocity() + + \warning The body must be dynamic. + */ + void setMaxAngularSpeed(float val); + /** + \brief Computes the velocity of a point given in body local coordinates as if it were attached to the + body and moving with it. + + \param[in] point Point we wish to determine the velocity of, defined in the body local frame. Range: position vector + + \return The velocity, in the global frame, of the point. + + \sa getLocalPointVelocity() + + \warning The body must be dynamic. + */ + VxVector getPointVelocity(const VxVector& point)const; + /** + \brief Computes the velocity of a point given in body local coordinates as if it were attached to the + body and moving with it. + + \param[in] point Point we wish to determine the velocity of, defined in the body local frame. Range: position vector + + \return The velocity, in the global frame, of the point. + + \sa getPointVelocity() + + \warning The body must be dynamic. + */ + VxVector getLocalPointVelocity(const VxVector& point)const; + /** + \brief Sets the angular velocity of the body. + + \note Note that if you continuously set the angular velocity of an body yourself, + forces such as friction will not be able to rotate the body, because forces directly influence only the velocity/momentum. + + \param[in] angVel New angular velocity of body. Range: angular velocity vector + + \sa getAngularVelocity() setLinearVelocity() + + \warning + The body must be dynamic.
+ Sleeping: This call wakes the body if it is sleeping. + */ + void setAngularVelocity(const VxVector& angVel); + /** + \brief Sets the linear velocity of the body. + + \note Note that if you continuously set the velocity of an body yourself, + forces such as gravity or friction will not be able to manifest themselves, because forces directly + influence only the velocity/momentum of an body. + + \param[in] linVel New linear velocity of body. Range: velocity vector + \sa getLinearVelocity() setAngularVelocity() + + \warning + The body must be dynamic.
+ Sleeping: This call wakes the body if it is sleeping. + */ + void setLinearVelocity(const VxVector& linVel); + + //@} + + + /************************************************************************************************/ + + /** @name Mass Manipulation + */ + //@{ + + + /** + \brief The setCMassOffsetLocal*() methods set the pose of the center of mass relative to the actor. + + See ::setCMassOffsetLocalPose() for more information. + + \note Setting an unrealistic center of mass which is a long way from the body can make it difficult for + the SDK to solve constraints. Perhaps leading to instability and jittering bodies. + + The actor must be dynamic. + + Sleeping: This call wakes the actor if it is sleeping. + + \param[in] vec Mass frame offset relative to the actor frame. Range: position vector + @see setCMassOffsetLocalPose() setCMassOffsetLocalOrientation() setCMassOffsetGlobalPose() + */ + //void setCMassOffsetLocalPosition(VxVector vec); + + + /** + \brief The setCMassOffsetGlobal*() methods set the pose of the center of mass relative to world space. + + See ::setCMassOffsetGlobalPose() for more information. + + \note Setting an unrealistic center of mass which is a long way from the body can make it difficult for + the SDK to solve constraints. Perhaps leading to instability and jittering bodies. + + The rigid body must be dynamic. + + Sleeping: This call wakes the rigid body if it is sleeping. + + \param[in] vec Mass frame offset relative to the global frame. Range: position vector + + @see setCMassOffsetGlobalPose() setCMassOffsetGlobalOrientation() + + */ + void setCMassOffsetGlobalPosition(VxVector vec); + + /** + \brief The setCMassGlobal*() methods move the rigid body by setting the pose of the center of mass. + + See ::setCMassGlobalPose() for more information. + + The rigid body must be dynamic. + + Sleeping: This call wakes the rigid body if it is sleeping. + + \param[in] vec rigid bodys new position, from the transformation of the mass frame to the global frame. Range: position vector + @see setCMassGlobalPose() setCMassGlobalOrientation() getCMassLocalPose() + */ + void setCMassGlobalPosition(VxVector vec); + + /** + \brief The getCMassLocal*() methods retrieve the center of mass pose relative to the rigid body. + + The rigid body must be dynamic. + + \return The center of mass position relative to the rigid body. + + @see getCMassLocalPose() getCMassLocalOrientation() getCMassGlobalPose() + */ + VxVector getCMassLocalPosition(); + + + /** + \brief The getCMassGlobal*() methods retrieve the center of mass pose in world space. + + The rigid body must be dynamic. + + \return The position of the center of mass relative to the global frame. + @see getCMassGlobalPose() getCMassGlobalOrientation() getCMassLocalPose() + + */ + VxVector getCMassGlobalPosition(); + + + /** + \brief Sets the inertia tensor, using a parameter specified in mass space coordinates. + + Note that such matrices are diagonal -- the passed vector is the diagonal. + + If you have a non diagonal world/rigid body space inertia tensor(3x3 matrix). Then you need to + diagonalize it and set an appropriate mass space transform. See #setCMassOffsetLocalPose(). + + The rigid body must be dynamic. + + Sleeping: Does NOT wake the rigid body up automatically. + + \param[in] m New mass space inertia tensor for the rigid body. Range: inertia vector + @see NxBodyDesc.massSpaceInertia getMassSpaceInertia() setMass() setCMassOffsetLocalPose() + */ + void setMassSpaceInertiaTensor(VxVector m); + + /** + \brief Retrieves the diagonal inertia tensor of the rigid body relative to the mass coordinate frame. + + This method retrieves a mass frame inertia vector. If you want a global frame inertia tensor(3x3 matrix), + then see #getGlobalInertiaTensor(). + + The rigid body must be dynamic. + + \return The mass space inertia tensor of this rigid body. + + @see NxBodyDesc.massSpaceInertia setMassSpaceInertiaTensor() setMass() CMassOffsetLocalPose() + */ + VxVector getMassSpaceInertiaTensor(); + + /** + \brief Retrieves the mass of the body. + + Zero represents no damping. The damping coefficient must be nonnegative. + + \param[in] angDamp Angular damping coefficient. Range: [0,inf) + + \sa setMass() + + \warning Static bodies will always return 0. + */ + float getMass(); + /** + \brief Sets the mass of a dynamic body. + + The mass must be positive and the body must be dynamic. + + setMass() does not update the inertial properties of the body, to change the inertia tensor + use setMassSpaceInertiaTensor() or updateMassFromShapes(). + + Sleeping: Does NOT wake the body up automatically. + + \param[in] mass New mass value for the body. Range: (0,inf) + + \sa setMass() + + \warning The mass must be positive and the body must be dynamic. + */ + void setMass(float mass,CKBeObject *shapeReference=NULL); + /** + \brief The setCMassOffsetLocal*() methods set the pose of the center of mass relative to the body. + + Methods that automatically compute the center of mass such as updateMassFromShapes() as well as computing + the mass and inertia using the bodies shapes, will set this pose automatically. + + \note Setting an unrealistic center of mass which is a long way from the body can make it difficult for + the SDK to solve constraints. Perhaps leading to instability and jittering bodies. + + Sleeping: This call wakes the body if it is sleeping. + + \param[in] vec Mass frame offset relative to the body frame. Range: position vector + + \warning The body must be dynamic. + */ + void setCMassOffsetLocalPosition(VxVector offset); + /** + \brief Recomputes a dynamic body's mass properties from its shapes + + Given a constant density or total mass, the bodies mass properties can be recomputed + using the shapes attached to the body. If the body has no shapes, then only the totalMass + parameter can be used. If all shapes in the body are trigger shapes (non-physical), the call + will fail. + + The mass of each shape is either the shape's local density (as specified in the #NxShapeDesc; default 1.0) + multiplied by the shape's volume or a directly specified shape mass. + + The inertia tensor, mass frame and center of mass will always be recomputed. If there are no + shapes in the body, the mass will be totalMass, and the mass frame will be set to the center + of the body. + + If you supply a non-zero total mass, the body's mass and inertia will first be computed as + above and then scaled to fit this total mass. + + If you supply a non-zero density, the body's mass and inertia will first be computed as above + and then scaled by this fbody. + + Either totalMass or density must be non-zero. + + \param[in] density Density scale fbody of the shapes belonging to the body. Range: [0,inf) + \param[in] totalMass Total mass of the body(or zero). Range: [0,inf) + + \sa setMass() + + \warning + The body must be dynamic.
+ Sleeping: Does NOT wake the body up automatically. + + */ + int updateMassFromShapes( float density, float totalMass ); +//@} + + + + /************************************************************************************************/ + + +/** @name Forces + */ + //@{ + + /** + \brief Applies a force (or impulse) defined in the global coordinate frame to the body. + + Methods that automatically compute the center of mass such as updateMassFromShapes() as well as computing + the mass and inertia using the bodies shapes, will set this pose automatically. + + + \param[in] force Force/Impulse to apply defined in the global frame. Range: force vector + \param[in] mode The mode to use when applying the force/impulse(see #ForceMode).Default = #FM_Force. + \param[in] wakeUp Specify if the call should wake up the body.Default = true. + + \sa addForceAtPos() addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() + + + \warning + The body must be dynamic.
+ This will not induce a torque.
+ Sleeping: This call wakes the body if it is sleeping and the wakeup parameter is true (default). + */ + void addForce(const VxVector& force,ForceMode mode=FM_Force,bool wakeUp=true); + /** + \brief Applies a force (or impulse) defined in the global coordinate frame, acting at a particular + point in global coordinates, to the body. + + + Note that if the force does not act along the center of mass of the body, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + + \param[in] force Force/impulse to add, defined in the global frame. Range: force vector + \param[in] point Position in the global frame to add the force at. Range: position vector + \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) + \param[in] wakeUp Specify if the call should wake up the body. + + \sa ForceMode + \sa addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() addLocalForce() + + + \warning + The body must be dynamic.
+ This will not induce a torque.
+ Sleeping: This call wakes the body if it is sleeping and the wakeup parameter is true (default). + */ + void addForceAtPos(const VxVector& force,const VxVector& point,ForceMode mode=FM_Force,bool wakeUp=true); + /** + \brief Applies a force (or impulse) defined in the global coordinate frame, acting at a particular + point in local coordinates, to the body. + + + \note Note that if the force does not act along the center of mass of the body, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a + total external force on an object by calling this once every frame. + + ::ForceMode determines if the force is to be conventional or impulsive. + + \param[in] force Force/impulse to add, defined in the global frame. Range: force vector + \param[in] point Position in the local frame to add the force at. Range: position vector + \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) + \param[in] wakeUp Specify if the call should wake up the body. + + \sa ForceMode + \sa addForceAtPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() addLocalForce() + + + \warning + The body must be dynamic.
+ This will not induce a torque.
+ Sleeping: This call wakes the body if it is sleeping and the wakeup parameter is true (default). + */ + void addForceAtLocalPos(const VxVector& force,const VxVector& point,ForceMode mode=FM_Force,bool wakeUp=true); + /** + \brief Applies a force (or impulse) defined in the body local coordinate frame to the body. + + ::ForceMode determines if the force is to be conventional or impulsive. + + \param[in] force Force/Impulse to apply defined in the local frame. Range: force vector + \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) + \param[in] wakeUp Specify if the call should wake up the body. + + \sa ForceMode + \sa addForceAtPos() addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() + + + \warning + The body must be dynamic.
+ This will not induce a torque.
+ Sleeping: This call wakes the body if it is sleeping and the wakeup parameter is true (default). + */ + void addLocalForce(const VxVector& force,ForceMode mode=FM_Force,bool wakeUp=true); + /** + \brief Applies a force (or impulse) defined in the body local coordinate frame, acting at a + particular point in global coordinates, to the body. + + \note Note that if the force does not act along the center of mass of the body, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a + total external force on an object by calling this once every frame. + + ::ForceMode determines if the force is to be conventional or impulsive. + + \param[in] force Force/impulse to add, defined in the local frame. Range: force vector + \param[in] point Position in the global frame to add the force at. Range: position vector + \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) + \param[in] wakeUp Specify if the call should wake up the body. + + \sa ForceMode + \sa addForceAtPos() addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() + + + \warning + The body must be dynamic.
+ This will not induce a torque.
+ Sleeping: This call wakes the body if it is sleeping and the wakeup parameter is true (default). + */ + void addLocalForceAtPos(const VxVector& force,const VxVector& point,ForceMode mode=FM_Force,bool wakeUp=true); + /** + \brief Applies a force (or impulse) defined in the body local coordinate frame, acting at a + particular point in local coordinates, to the body. + + \note Note that if the force does not act along the center of mass of the body, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, you can maintain a + total external force on an object by calling this once every frame. + + ::ForceMode determines if the force is to be conventional or impulsive. + + \param[in] force Force/impulse to add, defined in the local frame. Range: force vector + \param[in] point Position in the local frame to add the force at. Range: position vector + \param[in] mode The mode to use when applying the force/impulse(see #ForceMode) + \param[in] wakeUp Specify if the call should wake up the body. + + \sa ForceMode + \sa addForceAtPos() addForceAtLocalPos() addLocalForceAtPos() addLocalForceAtLocalPos() addForce() + + + \warning + The body must be dynamic.
+ This will not induce a torque.
+ Sleeping: This call wakes the body if it is sleeping and the wakeup parameter is true (default). + */ + void addLocalForceAtLocalPos(const VxVector& force,const VxVector& point,ForceMode mode=FM_Force,bool wakeUp=true); + /** + \brief Applies an impulsive torque defined in the global coordinate frame to the body. + + ::ForceMode determines if the force is to be conventional or impulsive. + + + \param[in] torque Torque to apply defined in the global frame. + \param[in] mode The mode to use when applying the force/impulse(see #ForceMode). + \param[in] wakeUp Specify if the call should wake up the body. + + \sa addLocalTorque() addForce() + + \warning + The body must be dynamic.
+ This will not induce a torque.
+ Sleeping: This call wakes the body if it is sleeping and the wakeup parameter is true (default). + */ + void addTorque(const VxVector& torque,ForceMode mode=FM_Force,bool wakeUp=true); + /** + \brief Applies an impulsive torque defined in the body local coordinate frame to the body. + + ::ForceMode determines if the force is to be conventional or impulsive. + + \param[in] torque Torque to apply defined in the local frame. + \param[in] mode The mode to use when applying the force/impulse(see #ForceMode). + \param[in] wakeUp Specify if the call should wake up the body. + \sa addLocalTorque() addForce() + + \warning + The body must be dynamic.
+ This will not induce a torque.
+ Sleeping: This call wakes the body if it is sleeping and the wakeup parameter is true (default). + */ + void addLocalTorque(const VxVector& torque,ForceMode mode=FM_Force,bool wakeUp=true); + + //@} + + + /************************************************************************************************/ + + /** @name Momentum + */ + //@{ + + /** + \brief Sets the angular momentum of the body. + + \note Note that if you continuously set the linear momentum of an body yourself, + forces such as gravity or friction will not be able to manifest themselves, because forces directly + influence only the velocity/momentum of a body. + + \param[in] angMoment New angular momentum. Range: angular momentum vector + + \sa getAngularMomentum() + + \warning + The body must be dynamic.
+ */ + void setAngularMomentum(const VxVector& angMoment); + /** + \brief Sets the linear momentum of the body. + + \note Note that if you continuously set the linear momentum of an body yourself, + forces such as gravity or friction will not be able to manifest themselves, because forces directly + influence only the velocity/momentum of a body. + + \param[in] linMoment New linear momentum. Range: momentum vector + + \sa getLinearMomentum() + + \warning + The body must be dynamic.
+ */ + void setLinearMomentum(const VxVector& linMoment); + /** + \brief Retrieves the angular momentum of an body. + + The angular momentum is equal to the angular velocity times the global space inertia tensor. + + \return The angular momentum for the body. + + \sa setLinearMomentum() getAngularMomentum() + + + \warning + The body must be dynamic.
+ */ + VxVector getAngularMomentum()const; + /** + \brief Retrieves the linear momentum of an body. + + The momentum is equal to the velocity times the mass. + + \return The linear momentum for the body. + + \sa setLinearMomentum() getAngularMomentum() + + \warning + The body must be dynamic.
+ */ + VxVector getLinearMomentum()const; + + //@} + + /************************************************************************************************/ + + /** @name Pose + */ + //@{ + + /** + \brief Sets a dynamic body's position in the world. + + \param[in] pos New position for the bodies frame relative to the global frame. Range: position vector + \param[in] subShapeReference Reference object specifing a subshape for the case the body is a compound object. Must be a mesh or an 3D-entity. Default = Null + + \sa getPosition() + + */ + void setPosition(const VxVector& pos,CK3dEntity *subShapeReference=NULL); + /** + \brief Sets a dynamic body's orientation in the world. + + \param[in] rot New orientation for the bodies frame. + \param[in] subShapeReference Reference object specifying a sub shape for the case the body is a compound object. Must be a mesh or an 3D-entity. Default = Null + + \sa getLinearMomentum() setAngularMomentum() + */ + void setRotation(const VxQuaternion& rot,CK3dEntity *subShapeReference=NULL); + //@} + + + /************************************************************************************************/ + /** @name Collision + */ + //@{ + + + /** + \brief Enables/disable collision detection. I.e. the body will not collide with other objects. Please note that you might need to wake + the body up if it is sleeping, this depends on the result you wish to get when using this flag. (If a body is asleep it + will not start to fall through objects unless you activate it). + + \param[in] enable. Flag to determining collisions response for the body. + to collision detect with each other. + \param[in] subShapeReference Reference object specifing a subshape for the case the body is a compound object. Must be a mesh or an 3D-entity. Default = Null + + \Note : Also excludes the body from overlap tests! + + \sa isCollisionEnabled() + + Sleeping: Does NOT wake the associated body up automatically. + */ + void enableCollision(bool enable,CK3dEntity* subShapeReference=NULL); + + bool isCollisionEnabled(CK3dEntity* subShapeReference=NULL) ; + + + void enableCollisionsNotify(bool enable); + bool isCollisionsNotifyEnabled(); + + void enableContactModification(bool enable); + void enableCollisionForceCalculation(bool enable,CK3dEntity* subShapeReference=NULL); + void enableTriggerShape(bool enable,CK3dEntity* subShapeReference=NULL); + bool isTriggerShape(CK3dEntity* subShapeReference=NULL); + /** + \brief Sets the collisions group the body belongs too. + + \param[in] index The new group index. Default group is 0. Maximum possible group is 31.Collision groups are sets of shapes which may or may not be set + to collision detect with each other. + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + + \note If you pass a sub shape reference then its only setting the group on the sub shape and not for all sub shapes. + + \sa getCollisionsGroup() + \warning + The body must be dynamic.
+ Sleeping: Does NOT wake the associated body up automatically. + */ + void setCollisionsGroup(int index,CK3dEntity* subShapeReference=NULL); + + /** + \brief Retrieves the collisions group which this body or a sub shape of it is part of. + + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + + \return The collision group this body or sub shape belongs to. + + \sa setCollisionsGroup() + + \warning + The body must be dynamic.
+ */ + int getCollisionsGroup(CK3dEntity* subShapeReference=NULL); + + //@} + + + + /************************************************************************************************/ + /** @name Shape + */ + //@{ + + /** + \brief Updates the box dimension of the initial shape or a sub shape. + + \param[in] dimension New dimension. Range: dimension vector + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + + \sa getBoxDimensions() + + \warning + The call doesnt updates the bodies mass.Use updateMassFromShapes()
+ + */ + void setBoxDimensions(const VxVector&dimension,CKBeObject* subShapeReference=NULL); + /** + \brief Retrieves the box dimension of the initial shape or sub shape. + + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + + \sa setBoxDimensions() + */ + VxVector getBoxDimensions(CKBeObject* subShapeReference=NULL); + /** + \brief Updates the radius of the initial shape or a sub shape. + + \param[in] radius New radius. + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + + \sa getSphereRadius() + + \warning + The call doest updates the bodies mass.Use updateMassFromShapes()
+ + */ + void setSphereRadius(float radius,CKBeObject* subShapeReference=NULL); + /** + \brief Retrieves the radius of the initial shape or sub shape. + + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + + \sa setSphereRadius() . + */ + float getSphereRadius(CKBeObject* subShapeReference=NULL); + /** + \brief Updates the capsule parameter of the initial shape or a sub shape. + + \param[in] radius New radius. + \param[in] length New length. + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + + \sa getCapsuleDimensions() + + \warning + The call doesnt updates the bodies mass.Use updateMassFromShapes()
+ + */ + void setCapsuleDimensions(float radius,float length,CKBeObject* subShapeReference=NULL); + /** + \brief Retrieves the capsule parameters of the initial shape or sub shape. + + \param[out] radius The radius of the capsule. + \param[out] length The length of the capsule. + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + \sa setCapsuleDimensions() . + */ + void getCapsuleDimensions(float& radius,float& length,CKBeObject* subShapeReference=NULL); + /** + \brief Retrieves the hull type of the initial shape or sub shape. + \return The hull type. + \param[in] subShapeReference Sub shape reference. Default = Null. + */ + HullType getShapeType(CKBeObject* subShapeReference=NULL); + + /** + \brief Retrieves the skin width of the initial shape or a sub shape. + \return The skin with. + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + \sa setSkinWidth() + */ + float getSkinWidth(CKBeObject* subShapeReference=NULL); + + /** + \brief Updates the skin width of the initial shape or a sub shape. + + \param[in] skinWidth The new skin width. Range: (0,inf) + \param[in] subShapeReference Sub shape reference. Must be a mesh or an 3D-entity. Default = Null. + + \sa setSkinWidth() + \warning + Sleeping: Does NOT wake the associated body up automatically. + */ + void setSkinWidth(const float skinWidth,CKBeObject* subShapeReference=NULL); + + //@} + + + + /************************************************************************************************/ + /** @name Optimization + */ + //@{ + + + /** + \brief The solver iteration count determines how accurately joints and contacts are resolved.
+ If you are having trouble with jointed bodies oscillating and behaving erratically, then + setting a higher solver iteration count may improve their stability. + + \param[in] count Number of iterations the solver should perform for this body.
+ - Range: [1,255] + + */ + void setSolverIterationCount(int count); + + /** + + \brief Assigns dynamic bodies a dominance group identifier.
+ + The dominance group is a 5 bit group identifier (legal range from 0 to 31). + + The #pWorld::setDominanceGroupPair() lets you set certain behaviors for pairs of dominance groups. + By default every body is created in group 0. Static bodies must stay in group 0; thus you can only + call this on dynamic bodys. + + Sleeping: Changing the dominance group does NOT wake the body up automatically. + + @see getDominanceGroup() NxScene::setDominanceGroupPair() + */ + void setDominanceGroup(int dominanceGroup); + + /** + \brief Retrieves the value set with setDominanceGroup().
+ + \return The dominance group of this body. + + @see setDominanceGroup() pWorld::setDominanceGroupPair() + */ + int getDominanceGroup() const; + + + /** + \brief Returns the linear velocity below which an body may go to sleep.
+ + Bodies whose linear velocity is above this threshold will not be put to sleep. + + The body must be dynamic. + + @see isSleeping + + \return The threshold linear velocity for sleeping. + + + @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepLinearVelocity() setSleepEnergyThreshold() getSleepEnergyThreshold() + */ + float getSleepLinearVelocity() const ; + + /** + \brief Sets the linear velocity below which an body may go to sleep.
+ + Bodies whose linear velocity is above this threshold will not be put to sleep. + + If the threshold value is negative, the velocity threshold is set using the NxPhysicsSDK's + NX_DEFAULT_SLEEP_LIN_VEL_SQUARED parameter. + + Setting the sleep angular/linear velocity only makes sense when the NX_BF_ENERGY_SLEEP_TEST is not set. In + version 2.5 and later a new method is used by default which uses the kinetic energy of the body to control + sleeping. + + + The body must be dynamic. + + \param[in] threshold Linear velocity below which an body may sleep. Range: (0,inf] + + @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepEnergyThreshold() getSleepEnergyThreshold() + */ + void setSleepLinearVelocity(float threshold); + + + /** + \brief Returns the angular velocity below which an body may go to sleep.
+ + Bodies whose angular velocity is above this threshold will not be put to sleep. + + The body must be dynamic. + + \return The threshold angular velocity for sleeping. + + @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepAngularVelocity() setSleepEnergyThreshold() getSleepEnergyThreshold() + */ + float getSleepAngularVelocity() const; + + + /** + \brief Sets the angular velocity below which an body may go to sleep.
+ + Bodies whose angular velocity is above this threshold will not be put to sleep. + + If the threshold value is negative, the velocity threshold is set using the NxPhysicsSDK's + NX_DEFAULT_SLEEP_LIN_VEL_SQUARED parameter. + + Setting the sleep angular/linear velocity only makes sense when the NX_BF_ENERGY_SLEEP_TEST is not set. In + version 2.5 and later a new method is used by default which uses the kinetic energy of the body to control sleeping. + + The body must be dynamic. + + \param[in] threshold Angular velocity below which an body may go to sleep. + - Range: (0,inf] + + + @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepLinearVelocity() setSleepEnergyThreshold() getSleepEnergyThreshold() + */ + void setSleepAngularVelocity(float threshold); + + + + /** + \brief Sets the energy threshold below which an body may go to sleep.
+ + Bodies whose kinematic energy is above this threshold will not be put to sleep. + + If the threshold value is negative, the velocity threshold is set using the NxPhysicsSDK's + NX_DEFAULT_SLEEP_ENERGY parameter. + + Setting the sleep energy threshold only makes sense when the NX_BF_ENERGY_SLEEP_TEST is set. There + are also other types of sleeping that uses the linear and angular velocities directly instead of the + energy. + + The body must be dynamic. + + \param[in] threshold Energy below which an actor may go to sleep.
+ - Range: (0,inf] + + @see isGroupSleeping() isSleeping() getSleepEnergyThreshold() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepLinearVelocity() setSleepAngularVelocity() + */ + void setSleepEnergyThreshold(float threshold); + + /** + \brief Returns the energy below which an body may go to sleep.
+ + Bodies whose energy is above this threshold will not be put to sleep. + + The body must be dynamic. + + \return The energy threshold for sleeping. + + @see isGroupSleeping() isSleeping() getSleepLinearVelocity() getSleepAngularVelocity() wakeUp() putToSleep() setSleepAngularVelocity() + */ + float getSleepEnergyThreshold() const; + + + /** + \brief Retrieves the linear damping coefficient.
+ + \return The linear damping coefficient associated with this body. + + \sa getAngularDamping() + + \warning The body must be dynamic. + */ + float getLinearDamping()const; + /** + \brief Retrieves the angular damping coefficient.
+ + + \return The angular damping coefficient associated with this body. + + \sa setAngularDamping() + + \warning The body must be dynamic. + */ + float getAngularDamping()const; + /** + \brief Sets the linear damping coefficient.
+ + Zero represents no damping. The damping coefficient must be nonnegative. + + \param[in] linDamp Linear damping coefficient. Range: [0,inf) + + \sa getLinearDamping() + + \warning The body must be dynamic. + */ + void setLinearDamping(float linDamp); + /** + \brief Sets the angular damping coefficient.
+ + Zero represents no damping. The damping coefficient must be nonnegative. + + \param[in] angDamp Angular damping coefficient. Range: [0,inf) + + \sa getLinearDamping() + + \warning The body must be dynamic. + */ + void setAngularDamping(float angDamp); + + + + + + + + + //@} + + + /************************************************************************************************/ + /** @name Conditions + */ + //@{ + + + + /** + \brief Sets the body to kinematic. + \param[in] enabled Enable kinematic mode. Range: (0,inf) + \sa isKinematic() + */ + void setKinematic(bool enabled); + /** + \brief Retrieves the bodies kinematic state. + \return the kinematic state. + */ + bool isKinematic()const; + + /** + \brief Checks whether the body is affected by the worlds gravity. + \return Is affected by gravity. + \sa enableGravity() + */ + bool isAffectedByGravity()const; + /** + \brief Enables gravity on the body. + \param[in] enable The gravity state. + \sa isAffectedByGravity() + */ + void enableGravity(bool enable); + + //@} + + /************************************************************************************************/ + /** @name Sleeping + */ + //@{ + + /** + \brief Checks whether the body is in a sleeping state. + \return True if sleeping. + \sa setSleeping() + */ + bool isSleeping()const; + /** + \brief Forces the body to sleep. + + The body will stay asleep until the next call to simulate, and will not wake up until then even when otherwise + it would (for example a force is applied to it). It can however wake up during + the next simulate call. + + \param[in] sleeping The sleeping state. + \sa setSleeping() + \warning + The body must be dynamic.
+ */ + void setSleeping(bool sleeping); + + /** + \brief Wakes up the body if it is sleeping. + + The wakeCounterValue determines how long until the body is put to sleep, a value of zero means + that the body is sleeping. wakeUp(0) is equivalent to NxActor::putToSleep(). + + \param[in] wakeCounterValue New sleep counter value. Default = (20.0f*0.02f) . Range: [0,inf] + \sa setSleeping() isSleeping() + \warning + The body must be dynamic.
+ */ + void wakeUp(float wakeCounterValue=pSLEEP_INTERVAL); + + //@} + + + /************************************************************************************************/ + /** @name Sub shapes + */ + //@{ + + /* + * \brief Adds an additional shape to the body. + * + * + * + * \return int + * \param CKMesh * mesh + * \param pObjectDescr objectDescr + * \param CK3dEntity * srcRefEntity + * \param VxVector localPosition + * \param VxQuaternion localRotation + * \note + * \sa + * \warning + */ + int addSubShape(CKMesh *mesh,pObjectDescr& objectDescr,CK3dEntity*srcRefEntity=NULL,VxVector localPosition=VxVector(),VxQuaternion localRotation=VxQuaternion()); + + int addCollider(pObjectDescr objectDescr,CK3dEntity*srcRefEntity); + + int removeSubShape(CKBeObject *reference,float newensity=0.0f,float totalMass=0.0f); + NxShape *_getSubShape(CK_ID meshID); + NxShape *_getSubShapeByEntityID(CK_ID id); + bool isSubShape(CKBeObject *object); + int updateSubShapes(bool fromPhysicToVirtools= true,bool position=true,bool rotation=true,CK3dEntity *childObject=NULL); + int updateSubShape(bool fromPhysicToVirtools=true,bool position=true,bool rotation=true,CK3dEntity *childObject=NULL,bool hierarchy=true); + + + NxShape * getMainShape() const { return mMainShape; } + void setMainShape(NxShape * val) { mMainShape = val; } + + NxShape *getShapeByIndex(int index=0); + NxShape* getSubShape(CK3dEntity*shapeReference=NULL); + + + + + //@} + + + int _initMainShape(const pObjectDescr oDescr,NxActorDesc&bodyDesc); + int _initMainShape(const pObjectDescr oDescr,NxActorDesc* bodyDesc); + + + + + bool isWheel(CKBeObject *object); + bool isVehicle(CKBeObject *object); + bool isCharacter(CKBeObject *object); + + + int getNbJoints(); + pJoint* getJointAtIndex(int index); + + + pJoint* getJoint(CK3dEntity*_b,JType type); + void deleteJoint(pJoint*joint); + void deleteJoint(CK3dEntity*_b,JType type); + + + /************************************************************************************************/ + /** @name Serialization + */ + //@{ + + void readFrom(NXU::NxActorDesc *desc,int flags); + void writeTo(const char *filename,int flags); + + //@} + + int getFlags(); + void recalculateFlags(int _flags); + void updateFlags(int _flags,CK3dEntity*shapeReference=NULL); + void setFlags(int _flags); + + + int getHullType(); + void setHullType(int _type); + + ////////////////////////////////////////////////////////////////////////// + //geometry related : + + + + bool isValid()const; + + ////////////////////////////////////////////////////////////////////////// + //maintainence : + + CK3dEntity* GetVT3DObject(); + void SetVT3DObject(CK3dEntity* _obj); + + CK_ID getEntID() const { return mEntID; } + void setEntID(CK_ID val) { mEntID = val; } + void destroy(); + + ////////////////////////////////////////////////////////////////////////// + //optimization settings : + + pSleepingSettings* getSleepingSettings() { return m_SleepingSettings; } + void setSleepingSettings(pSleepingSettings* val) { m_SleepingSettings = val; } + + + void Init(); + void retrieveSettingsFromAttribute(); + + void UpdateGeometry(int flags=0); + + + ////////////////////////////////////////////////////////////////////////// + //pivot manipulation,no affects to mass ! + + void setLocalShapePosition(VxVector relative,CK3dEntity*shapeReference=NULL); + //void SetPivotOrientation(VxQuaternion relative); + + + pWorld * getWorld() const { return m_pWorld; } + void setWorld(pWorld * val) { m_pWorld = val; } + + void clean(int flags=0); + + ////////////////////////////////////////////////////////////////////////// + //joint related + pJoint* isConnected(CK3dEntity*); + pJoint* isConnected(CK3dEntity*,int type); + int JGetNumJoints(); + + + JointListType& GetJoints(){ return m_Joints; } + + + ////////////////////////////////////////////////////////////////////////// + //composite geometries + + VxVector getMassOffset() const { return massOffset; } + void setMassOffset(VxVector val) { massOffset = val; } + void setPivotOffset(VxVector val) { pivotOffset = val; } + VxVector getPivotOffset(CK3dEntity*shapeReference); + + void translateLocalShapePosition(VxVector vec); + float getDensity() const { return mDensity; } + void setDensity(float val) { mDensity = val; } + + + ////////////////////////////////////////////////////////////////////////// + //prototype : + + xBitSet& getDataFlags() { return mDataFlags; } + void setDataFlags(xBitSet val) { mDataFlags = val; } + + void checkDataFlags(); + void checkForOptimization(); + + void updateOptimizationSettings(pOptimization optimization); + + + void checkForCCDSettings(CK3dEntity *shapeReference=NULL); + + void updateCCDSettings(pCCDSettings ccd,CK3dEntity*shapeReference=NULL); + void updateCollisionSettings(const pObjectDescr oDescr,CK3dEntity*shapeReference=NULL); + void updateCollisionSettings(pCollisionSettings collision,CK3dEntity*shapeReference=NULL); + void updatePivotSettings(pPivotSettings pivot,CK3dEntity*shapeReference=NULL); + void updateMaterialSettings(pMaterial& material,CK3dEntity*shapeReference=NULL); + void updateMassSettings(pMassSettings massSettings); + void saveToAttributes(pObjectDescr* oDescr); + + ////////////////////////////////////////////////////////////////////////// + //Surface : + + + void InitSurfaceMaterials(); + ////////////////////////////////////////////////////////////////////////// + + /************************************************************************/ + /* Material */ + /********************************* ***************************************/ + + pMaterial& getShapeMaterial(CK3dEntity *shapeReference=NULL); + void setShapeMaterial(pMaterial&material,CK3dEntity*shapeReference=NULL); + void setShapeMaterialFrom(CKBeObject*src,CK3dEntity*shapeReference=NULL); + + NxMaterial* getMaterial() const { return mMaterial; } + void setMaterial(NxMaterial* val) { mMaterial = val; } + + + NxActor* getActor() const { return mActor; } + void setActor(NxActor* val) { mActor = val; } + + /************************************************************************/ + /* */ + /************************************************************************/ + + + pCloth *mCloth; + pCloth * getCloth() const { return mCloth; } + void setCloth(pCloth * val) { mCloth = val; } + bool isDeformable(); + + ////////////////////////////////////////////////////////////////////////// + void lockTransformation(int flags); + int getTransformationsLockFlags(); + int isBodyFlagOn(int flags); + + /************************************************************************/ + /* Sub shapes : */ + /************************************************************************/ + + CollisionsArray mCollisions; + CollisionsArray&getCollisions(){return mCollisions;} + + pTriggerArray mTriggers; + pTriggerArray& getTriggers() { return mTriggers; } + + + + xBitSet mCollisionFlags; + xBitSet&getCollisionFlags(); + + + + pVehicle * getVehicle() const { return mVehicle; } + void setVehicle(pVehicle * val) { mVehicle = val; } + pWheel* getWheel(CK3dEntity* subShapeReference); + pWheel2* getWheel2(CK3dEntity* subShapeReference); + + + + int getTriggerState() const { return mTriggerState; } + void setTriggerState(int val) { mTriggerState = val; } + + int getNbWheels(); + void updateWheels(float step); + void _transformWheels(); + bool hasWheels(); + + + int getNbSubShapes(); + int getNbSubBodies(); + + + protected : + + DWORD m_DataFlags;//deprecated ! + xBitSet mDataFlags; + + + + CK_ID mEntID; + CKContext* context; + int m_sFlags; + int m_HullType; + float m_friction; + float m_restitution; + float mDensity; + + VxVector massOffset; + VxVector pivotOffset; + + CK3dEntity* mVTObject; + pWorld * m_pWorld; + pSleepingSettings* m_SleepingSettings; + JointListType m_Joints; + + NxActor* mActor; + NxMaterial*mMaterial; + float mSkinWidth; + NxShape *mMainShape; + + + + pVehicle *mVehicle; + + int mTriggerState; + + public: + void _checkForNewSubShapes(); + void _checkForRemovedSubShapes(); + + + +}; + +/** @} */ + + +#endif // !defined(EA_C2D3E6DE_B1A5_4f07_B3FA_73F108249451__INCLUDED_) diff --git a/usr/Include/Core/pRigidBody/pRigidBodyTypes.h b/usr/Include/Core/pRigidBody/pRigidBodyTypes.h new file mode 100644 index 0000000..4734b01 --- /dev/null +++ b/usr/Include/Core/pRigidBody/pRigidBodyTypes.h @@ -0,0 +1,615 @@ +#ifndef __PRIGIDBODYTYPES_H__ +#define __PRIGIDBODYTYPES_H__ + +#include "vtPhysXBase.h" +#include "pVTireFunction.h" +//#include "pWheelTypes.h" + + + +/** \addtogroup RigidBody +@{ +*/ + +struct pRigidBodyRestoreInfo +{ + bool hierarchy; + bool removeJoints; + pRigidBodyRestoreInfo() : hierarchy(false) , removeJoints(false){} + +}; + +/** +\brief Class describing a rigid bodies mass offset. +*/ +class MODULE_API pMassSettings +{ + + public: + /** + \brief Density scale factor of the shapes belonging to the body + - Range: [0,inf) + - Default: [0) + **/ + float newDensity; + + /** + \brief Total mass of the actor(or zero). + - Range: [0,inf) + - Default: 0.0f + **/ + float totalMass; + /** + \brief Local position offset + - Range: [vector) + - Default: (0,0,0) + **/ + VxVector localPosition; + /** + \brief Local orientation offset + - Range: [0,inf) + - Default: (0,0,0) + **/ + VxVector localOrientation; + /** + \brief Reference object to determine the mass local position. The members "Linear" and "Angular" are being used to transform the final matrix. + - Range: [object) + - Default: 0 + **/ + CK_ID massReference; + + pMassSettings() + { + newDensity = totalMass = 0.0f; + massReference = 0 ; + } +}; + +/** + +\brief Class to describe a pivot offset +*/ +class MODULE_API pPivotSettings +{ + + + public: + + bool isValid(); + bool setToDefault(); + bool evaluate(CKBeObject*referenceObject); + + + /** + \brief Local position offset. The local position of can be changed by #pRigidBody::setPosition + - Range: [vector) + - Default: (0,0,0) + **/ + VxVector localPosition; + /** + \brief Local orientation offset. The local orientation of can be changed by #pRigidBody::setRotation + - Range: [0,inf) + - Default: (0,0,0) + **/ + VxVector localOrientation; + /** + \brief Reference object to determine the shape local matrix. The members "Linear" and "Angular" are being used to transform the final matrix. + - Range: [object) + - Default: 0 + **/ + CK_ID pivotReference; + + pPivotSettings() + { + pivotReference=0; + } + +}; + + +//---------------------------------------------------------------- +// +//! \brief Help info to specify a length by an entity reference +// +class MODULE_API pAxisReferencedLength +{ +public: + bool isValid(); + bool setToDefault(); + bool evaluate(CKBeObject *referenceObject); + + float value; + CKBeObject *reference; + int referenceAxis; + + pAxisReferencedLength() : + value(0.0f) , + reference(NULL) , + referenceAxis(0) + { + } +}; + +//---------------------------------------------------------------- +// +//! \brief Additional information for deformable objects +// +struct MODULE_API pDeformableSettings +{ + +public : + + bool isValid(); + bool setToDefault(); + bool evaluate(CKBeObject*referenceObject); + + float ImpulsThresold; + float PenetrationDepth; + float MaxDeform; + + pDeformableSettings() + { + ImpulsThresold = 50.0f; + PenetrationDepth = 0.1f ; + MaxDeform= 0.1f; + } +}; + +//---------------------------------------------------------------- +// +//! \brief Additional settings to override a default capsule +// +struct pCapsuleSettings +{ + +public : + + int localLengthAxis; + int localRadiusAxis; + + float height; + float radius; + pCapsuleSettings() + { + localRadiusAxis=0; + localLengthAxis=0; + height = 0.0f; + radius = 0.0f; + } +}; + +//---------------------------------------------------------------- +// +//! \brief Additional settings to override a default capsule +// +struct MODULE_API pCapsuleSettingsEx +{ +public : + + bool isValid(); + bool setToDefault(); + bool evaluate(CKBeObject*referenceObject); + + /** + \brief Radius specified by value or an objects local box size and an axis + **/ + pAxisReferencedLength radius; + + /** + \brief Height specified by value or an objects local box size and an axis + **/ + pAxisReferencedLength height; + + pCapsuleSettingsEx() + { + + } +}; + + + +//---------------------------------------------------------------- +// +//! \brief Optional override to describe a convex cylinder. +// +class MODULE_API pConvexCylinderSettings +{ + +public: + + + bool isValid(); + bool setToDefault(); + bool evaluate(CKBeObject*referenceObject); + + + /** + \brief Radius specified by value or an objects local box size and an axis + **/ + pAxisReferencedLength radius; + /** + \brief Height specified by value or an objects local box size and an axis + **/ + pAxisReferencedLength height; + + /** + \brief Amount of cap segments + **/ + int approximation; + + /** + \brief Rotation part 1. If a forward axis reference has been specified, the vector gets transformed + **/ + VxVector forwardAxis; + /** + \brief Reference to specify the "Dir" axis + **/ + CK_ID forwardAxisRef; + + /** + \brief Rotation part 2. If a down axis reference has been specified, the vector gets transformed + **/ + VxVector downAxis; + /** + \brief Reference to specify the "Up" axis + **/ + CK_ID downAxisRef; + + /** + \brief Rotation part 3. If a right axis reference has been specified, the vector gets transformed + **/ + VxVector rightAxis; + /** + \brief Reference to specify the "Right" axis + **/ + CK_ID rightAxisRef; + + /** + \brief Create only a half cylinder + */ + bool buildLowerHalfOnly; + + /** + \brief Flags which describe the format and behavior of a convex mesh. See #pConvexFlags + */ + pConvexFlags convexFlags; + + pConvexCylinderSettings() : + approximation(0), + forwardAxisRef(0), + rightAxisRef(0), + downAxisRef(0), + buildLowerHalfOnly(false) + { + setToDefault(); + convexFlags=((pConvexFlags)(CF_ComputeConvex)); + + + + } +}; + +class MODULE_API pWheelDescr +{ + +public : + + //################################################################ + // + // Wheel Capsule Specific + // + int wheelApproximation; + + pAxisReferencedLength radius; + float width; + + //################################################################ + // + // Wheel Common Attributes + // + float wheelSuspension; + float springRestitution; + float springDamping; + float springBias; + + float maxBrakeForce; + + float frictionToSide; + float frictionToFront; + + WheelFlags wheelFlags; + + //################################################################ + // + // Wheel Shape Specific + // + + WheelShapeFlags wheelShapeFlags; + float inverseWheelMass; + pConvexCylinderSettings convexCylinder; + + pConvexCylinderSettings getConvexCylinderSettings() { return convexCylinder; } + void setConvexCylinderSettings(pConvexCylinderSettings val) { convexCylinder = val; } + pTireFunction latFunc;int latFuncXML_Id; + pTireFunction longFunc;int longFuncXML_Id; + + pWheelDescr(){ setToDefault(); } + ~pWheelDescr(){} + + void* userData; + void setToDefault(); + bool isValid() const; + +}; + +//---------------------------------------------------------------- +// +//! \brief Container to store joints +// +typedef XArrayJointListType; + + +class pClothDescr +{ + +}; + +/** +! \brief Describes a rigid body. + +This is used by #pFactory::createBody() and #pRigidBody::addSubShape() only. + +*/ +class MODULE_API pObjectDescr +{ + + +public : + + int mask; + + + typedef enum E_OD_VERSION + { + OD_DECR_V0, + OD_DECR_V1, + }; + + + CK_ID worlReference; + + int version; + /** + \brief The shape type of the body. Default = HT_Sphere. + */ + HullType hullType; + /** + \brief The shape type of the body. Default = 1.0f. + */ + float density; + + /** + \brief Translates the mass center after the body is created in local space. + */ + VxVector massOffset; + /** + \brief Translates the pivot after the body is created in local space. + */ + VxVector shapeOffset; + + /** + \brief Translates the pivot after the body is created in local space. + */ + VxVector pivotOffsetLinear; + /** + \brief Translates the pivot after the body is created in local space. + */ + CK_ID pivotOffsetReference; + + /** + \brief Translates the pivot after the body is created in local space. + */ + VxVector pivotOffsetAngular; + /** + \brief Describes several properties. See #BodyFlags. Default = 0. + */ + BodyFlags flags; + + /** + \brief Will parse the entities hierarchy for additional sub shapes. Child objects needs to have the physic object attribute attached. Default = false. + */ + bool hirarchy; + /** + \brief If there are sub shape attached, #pRigidBodie::addSubShape will call #pRigidBody::updateMassFromShapes(). Default = 0.0f. + */ + float newDensity; + /** + \brief If there are sub shape attached, #pRigidBodie::addSubShape will call #pRigidBody::updateMassFromShapes(). Default = 0.0f. + */ + float totalMass; + + int subEntID; + int transformationFlags; + + int internalXmlID; + int externalXmlID; + int xmlImportFlags; + VxVector pivotAngularOffset; + + + /************************************************************************************************/ + /** @name Collision + */ + //@{ + + /** + \brief Sets 128-bit mask used for collision filtering. See comments for ::pGroupsMask + */ + pGroupsMask groupsMask; + + /** + \brief Adds an additional offset for collision response. + */ + float skinWidth; + + /** + \brief The collision group the body belongs to. Default = 0. + */ + int collisionGroup; + + + //@} + + + /************************************************************************************************/ + /** @name CCD Settings + */ + //@{ + + float ccdMotionThresold; + int ccdFlags; + CK_ID ccdMeshReference; + float ccdScale; + + + //@} + + + + /************************************************************************************************/ + /** @name Damping + */ + //@{ + + /** + \brief the linear damping. + */ + float linearDamping; + + /** + \brief the angular damping. + */ + float angularDamping; + + + //@} + + /************************************************************************************************/ + /** @name Sleeping Settings + */ + //@{ + + float linearSleepVelocity; + float angularSleepVelocity; + float sleepingEnergyThresold; + + + //@} + + + /************************************************************************************************/ + /** @name Optimization + */ + //@{ + + int solverIterations; + int dominanceGroups; + int compartmentID; + + + //@} + + /************************************************************************************************/ + /** @name Mass + */ + //@{ + + VxVector massOffsetLinear; + VxVector massOffsetAngular; + CK_ID massOffsetReference; + + //@} + + + pOptimization optimization; + pOptimization& getOptimization() { return optimization; } + void setOptimization(pOptimization val) { optimization = val; } + + pMaterial material; + pMaterial& getMaterial() { return material; } + void setMaterial(pMaterial val) { material = val; } + + pCCDSettings ccd; + pCCDSettings& getCCD() { return ccd; } + void setCCD(pCCDSettings val) { ccd = val; } + + pCapsuleSettingsEx capsule; + pCapsuleSettingsEx& getCapsule() { return capsule; } + void setCapsule(pCapsuleSettingsEx val) { capsule = val; } + + pConvexCylinderSettings convexCylinder; + pConvexCylinderSettings& getConvexCylinder() { return convexCylinder; } + void setConvexCylinder(pConvexCylinderSettings val) { convexCylinder = val; } + + pMassSettings mass; + pMassSettings& getMass() { return mass; } + void setMass(pMassSettings val) { mass = val; } + + pPivotSettings pivot; + pPivotSettings& getPivot() { return pivot; } + void setPivot(pPivotSettings val) { pivot = val; } + + pCollisionSettings collision; + pCollisionSettings& getCollision() { return collision; } + void setCollision(pCollisionSettings val) { collision = val; } + + pWheelDescr wheel; + pWheelDescr& getWheel() { return wheel; } + void setWheel(pWheelDescr val) { wheel = val; } + + pObjectDescr() + { + setToDefault(); + } + + bool isValid(); + bool setToDefault(); + +}; + +//---------------------------------------------------------------- +// +//! \brief Meta data to track the relation between a NxShape and an CK3dEntity. +//! Also used to track a wheel object in the NxShapes user data. +// +struct pSubMeshInfo +{ + pObjectDescr initDescription; + NxCCDSkeleton *ccdSkeleton; + int meshID; + CKBeObject *mesh; + + int entID; + CKBeObject *refObject; + CK_ID ccdReference; + + pWheel *wheel; + + pSubMeshInfo() + { + wheel = NULL; + meshID = -1; + entID = -1 ; + mesh = NULL; + refObject = NULL; + ccdSkeleton = NULL; + ccdReference = 0; + } +}; + + +/** @} */ + + + +#endif // __PRIGIDBODYTYPES_H__ \ No newline at end of file diff --git a/usr/Include/Core/pRigidBody/pShape.h b/usr/Include/Core/pRigidBody/pShape.h new file mode 100644 index 0000000..f010a88 --- /dev/null +++ b/usr/Include/Core/pRigidBody/pShape.h @@ -0,0 +1,38 @@ +#ifndef __PSHAPE_H_ +#define __PSHAPE_H_ + + +#include "vtOdeEnums.h" +#include "vtOdeTypes.h" +#include "pPrereqs.h" + +namespace vtAgeia +{ + + class pShape + { + public : + + pShape() + { + + } + virtual ~pShape(){} + dGeomID m_OdeGeomID; + + dGeomID OdeGeomID() const { return m_OdeGeomID; } + void OdeGeomID(dGeomID val) { m_OdeGeomID = val; } + + void SetOffsetPosition (VxVector position); + void setOffsetQuaternion(VxQuaternion quad); + + void setOffsetWorldPosition(VxVector position); + void setOffsetWorldQuaternion(VxQuaternion orientation) ; + + }; + + +} + + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pSerializer/pSerializer.h b/usr/Include/Core/pSerializer/pSerializer.h new file mode 100644 index 0000000..8952401 --- /dev/null +++ b/usr/Include/Core/pSerializer/pSerializer.h @@ -0,0 +1,37 @@ +#ifndef __P_SERIALIZER_H__ +#define __P_SERIALIZER_H__ + + +#include "vtPhysXBase.h" + +/** \addtogroup Serialization +@{ +*/ + +/** +\brief Class to import and export NxStream files. Those files can be created by 3D related content editors +such as Maya and 3D-SMax. Also, you can dump the entire Virtools scene and load it in the +supplied PhysX Viewer. +*/ +class MODULE_API pSerializer +{ +public: + pSerializer(); + ~pSerializer(); + + static pSerializer*Instance(); + NXU::NxuPhysicsCollection *getCollection(const char *pFilename,int type); + bool overrideBody(pRigidBody *body,int flags); + int loadCollection(const char*fileName,int flags); + int saveCollection(const char*filename); + void parseFile(const char*filename,int flags); + +protected: + NXU::NxuPhysicsCollection *mCollection; + +private: +}; + +/** @} */ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pVehicle/pDifferential.h b/usr/Include/Core/pVehicle/pDifferential.h new file mode 100644 index 0000000..195735d --- /dev/null +++ b/usr/Include/Core/pVehicle/pDifferential.h @@ -0,0 +1,127 @@ +// racer/differential.h + +#ifndef __RACER_DIFFERENTIAL_H +#define __RACER_DIFFERENTIAL_H + +#include "vtPhysXBase.h" +#include "pDriveline.h" + +class pVehicle; +class pWheel; +class pEngine; + +class MODULE_API pDifferential : public pDriveLineComp +// A differential that has 3 parts; 1 'input', and 2 'outputs'. +// Actually, all parts work together in deciding what happens. +{ + public: + enum Type + { + FREE=0, // Free/open differential + VISCOUS=1, // Viscous locking differential + SALISBURY=2 // Grand Prix Legends type clutch locking + }; + enum Flags + { + //LINEAR_LOCKING=1 // Viscous diff is of linear (expensive) type + }; + + void setToDefault(); + + protected: + + // Definition (static input) + int type; + int flags; // Behavior flags + float lockingCoeff; // Coefficient for viscous diff + // Salisbury diff + float powerAngle,coastAngle; // Ramp angles + int clutches; // Number of clutches in use + float clutchFactor; // Scaling the effect of the clutches + float maxBiasRatioPower; // Resulting max. bias ratio + float maxBiasRatioCoast; // Resulting max. bias ratio + + // Input + + // Torque on the 3 parts + float torqueIn; + float torqueOut[2]; + float torqueBrakingOut[2]; // Potential braking torque + // Inertia of objects + float inertiaIn; + float inertiaOut[2]; + // Limited slip differentials add a locking torque + float torqueLock; + + // State + float velASymmetric; // Difference in wheel rotation speed + float torqueBiasRatio; // Relative difference in reaction T's + float torqueBiasRatioAbs; // Always >=1 + int locked; // Mask of locked ends + + // Output + + // Resulting accelerations + float accIn, + accASymmetric; + float accOut[2]; + float rotVdriveShaft; // Speed of driveshaft (in) + + pVehicle *car; + + public: + // Input + pEngine *engine; + // Output members + pWheel2 *wheel[2]; + + public: + pDifferential(pVehicle *car); + ~pDifferential(); + + void Reset(); + //---------------------------------------------------------------- + // + // experimental + // + + void SetTorqueIn(float torque); + + float GetTorqueOut(int n); + float GetBreakTorqueOut(int n); + + void SetInertiaIn(float inertia); + void SetInertiaOut(int n,float inertia); + + + //---------------------------------------------------------------- + // + // standard + // + + + float GetAccIn() const { return accIn; } + float GetAccASymmetric() const { return accASymmetric; } + float GetAccOut(int n) const { return accOut[n]; } + // Salisbury info + float GetTorqueBiasRatio(){ return torqueBiasRatio; } + float GetMaxBiasRatioPower(){ return maxBiasRatioPower; } + float GetMaxBiasRatioCoast(){ return maxBiasRatioCoast; } + float GetPowerAngle(){ return powerAngle; } + float GetCoastAngle(){ return powerAngle; } + int GetClutches(){ return clutches; } + float GetClutchFactor(){ return clutchFactor; } + // Other info + float GetRotationalVelocityIn() const { return rotVdriveShaft; } + + void Lock(int wheel); + bool IsLocked(int wheel) + { if(locked&(1< +#include + + + +class pLinearInterpolation { + typedef std::map MapType; + typedef MapType::iterator MapIterator; + typedef MapType::const_iterator ConstMapIterator; + MapType _map; + + NxF32 _min, _max; +public: + pLinearInterpolation (): _min(0), _max(0), _map() { } + + void clear() { _map.clear(); } + void insert(float index, float value) { + if (_map.empty()) + _min = _max = index; + else { + _min = NxMath::min(_min, index); + _max = NxMath::max(_max, index); + } + _map[index] = value; + } + + void print() const { + ConstMapIterator it = _map.begin(); + for (; it != _map.end(); ++it) { + printf("%2.3f -> %2.3f\n", it->first, it->second); + } + } + + bool isValid(float number) const { return number>=_min && number<=_max; } + + float getValue(float number) const { + ConstMapIterator lower = _map.begin(); + if (number < _min) + return lower->second; + ConstMapIterator upper = _map.end(); + upper--; + if (number > _max) + return upper->second; + + upper = _map.lower_bound(number); + if (upper == lower) + return (upper->second); + lower = upper; + lower--; + + //printf("- %2.3f %2.3f\n", lower->first, upper->first); + float w1 = number - lower->first; + float w2 = upper->first - number; + return ((w2 * lower->second) + (w1 * upper->second)) / (w1 + w2); + } + + NxF32 getValueAtIndex(NxI32 index) const { + ConstMapIterator it = _map.begin(); + for (int i = 0; i < index; i++) + ++it; + return it->second; + } + + void operator=(const pLinearInterpolation& other) + { + _map.insert(other._map.begin(), other._map.end()); + _max = other._max; + _min = other._min; + } + + int getSize() const { return _map.size(); } +}; + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pVehicle/pPacejka.h b/usr/Include/Core/pVehicle/pPacejka.h new file mode 100644 index 0000000..7897ee4 --- /dev/null +++ b/usr/Include/Core/pVehicle/pPacejka.h @@ -0,0 +1,84 @@ +// racer/pacejka.h + +#ifndef __P_PACEJKA_H__ +#define __P_PACEJKA_H__ + +#include "vtPhysXBase.h" + +#define RR_RAD_DEG_FACTOR 57.29578f // From radians to degrees" +#define RR_RAD2DEG 57.29578f // A bit more descriptive + +#ifndef PI +#define PI 3.14159265358979f +#endif + +// Near-zero definitions +#define RR_EPSILON_VELOCITY 0.001 // Wheel velocity + + +class MODULE_API pPacejka +// A Pacejka calculation engine +// Uses SAE axis system for reference +// (SAE X=Racer Z, SAE Y=Racer X, SAE Z=Racer -Y) +{ + public: + // Fx longitudinal force + float a0,a1,a2,a3,a4,a5,a6,a7,a8, + a9,a10,a111,a112,a12,a13; + // Fy lateral force + float b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10; + // Mz aligning moment + float c0,c1,c2,c3,c4,c5,c6, + c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17; + + protected: + // Input parameters + float camber, // Angle of tire vs. surface (in degrees!) + sideSlip, // Slip angle (in degrees!) + slipPercentage, // Percentage slip ratio (in %) + Fz; // Normal force (in kN!) + // Output + float Fx,Fy,Mz; // Longitudinal/lateral/aligning moment + float longStiffness, // Longitudinal tire stiffness + latStiffness; // Lateral or cornering stiffness + VxVector maxForce; // Max. available tire force (friction ellipse) + + public: + pPacejka(); + ~pPacejka(); + + + void setToDefault(); + + // Attribs + void SetCamber(float _camber){ camber=_camber*RR_RAD2DEG; } + void SetSlipAngle(float sa){ sideSlip=sa*RR_RAD2DEG; } + void SetSlipRatio(float sr){ slipPercentage=sr*100.0f; } + void SetNormalForce(float force){ Fz=force/1000.0f; } + + // Physics + void Calculate(); + protected: + float CalcFx(); + float CalcFy(); + float CalcMz(); + public: + float GetFx(){ return Fx; } + float GetFy(){ return Fy; } + float GetMz(){ return Mz; } + // Adjust (used in combined slip) + void SetFx(float v){ Fx=v; } + void SetFy(float v){ Fy=v; } + void SetMz(float v){ Mz=v; } + + // Extras + float GetMaxLongForce(){ return maxForce.x; } + float GetMaxLatForce(){ return maxForce.y; } + // Adjust (used for surface and quick-adjust modifications) + void SetMaxLongForce(float v){ maxForce.x=v; } + void SetMaxLatForce(float v){ maxForce.x=v; } + float GetLongitudinalStiffness(){ return longStiffness; } + float GetCorneringStiffness(){ return latStiffness; } +}; + +#endif diff --git a/usr/Include/Core/pVehicle/pSteer.h b/usr/Include/Core/pVehicle/pSteer.h new file mode 100644 index 0000000..742541c --- /dev/null +++ b/usr/Include/Core/pVehicle/pSteer.h @@ -0,0 +1,48 @@ +// rsteer.h + +#ifndef __PVEHICLE_STEER_H__ +#define __PVEHICLE_STEER_H__ + +#include "vtPhysXBase.h" +#include "pVehicleTypes.h" + + +class pVehicleSteer +{ + pVehicle *car; + + // Physical + float lock; // Maximum angle (radians) + + VxVector position; + float radius; + float xa; // Rotation towards the driver's face + + // State (output) + float angle; // -lock .. +lock + + + // Input + int axisInput; // Controller position (axis) + + public: + pVehicleSteer(pVehicle *car); + ~pVehicleSteer(); + + + float GetAngle(){ return angle; } + float GetLock(){ return lock; } + void SetAngle(float _angle){ angle=_angle; } // For replays + + void setToDefault(); + + void SetInput(int axisPos); + float getLock() const { return lock; } + void setLock(float val) { lock = val; } + + + void Integrate(); +}; + +#endif + diff --git a/usr/Include/Core/pVehicle/pVTireFunction.h b/usr/Include/Core/pVehicle/pVTireFunction.h new file mode 100644 index 0000000..8986231 --- /dev/null +++ b/usr/Include/Core/pVehicle/pVTireFunction.h @@ -0,0 +1,113 @@ +#ifndef __P_V_TIRE_FUNCTION_H__ +#define __P_V_TIRE_FUNCTION_H__ + +#include "vtPhysXBase.h" + +/** \addtogroup Vehicle +@{ +*/ + + +/** +\brief cubic hermit spline coefficients describing the longitudinal tire force curve. + +Force +^ extrema +| _*_ +| ~ \ asymptote +| / \~__*______________ +| / +|/ +---------------------------> Slip +*/ +class MODULE_API pTireFunction + { + public: + + virtual ~pTireFunction(){}; + + /** + \brief extremal point of curve. Both values must be positive. + + Range: (0,inf)
+ Default: 1.0 + */ + float extremumSlip; + + /** + \brief extremal point of curve. Both values must be positive. + + Range: (0,inf)
+ Default: 0.02 + */ + float extremumValue; + + /** + \brief point on curve at which for all x > minumumX, function equals minimumY. Both values must be positive. + + Range: (0,inf)
+ Default: 2.0 + */ + float asymptoteSlip; + + /** + \brief point on curve at which for all x > minumumX, function equals minimumY. Both values must be positive. + + Range: (0,inf)
+ Default: 0.01 + */ + float asymptoteValue; + + + /** + \brief Scaling factor for tire force. + + This is an additional overall positive scaling that gets applied to the tire forces before passing + them to the solver. Higher values make for better grip. If you raise the *Values above, you may + need to lower this. A setting of zero will disable all friction in this direction. + + Range: (0,inf)
+ Default: 1000000.0 (quite stiff by default) + */ + float stiffnessFactor; + + + /** + \brief Scaling factor for tire force. + + This is an additional overall positive scaling that gets applied to the tire forces before passing + them to the solver. Higher values make for better grip. If you raise the *Values above, you may + need to lower this. A setting of zero will disable all friction in this direction. + + Range: (0,inf)
+ Default: 1000000.0 (quite stiff by default) + */ +// float stiffnessFactor; + + + /** + constructor sets to default. + */ + pTireFunction(); + /** + (re)sets the structure to the default. + */ + virtual void setToDefault(); + /** + returns true if the current settings are valid + */ + virtual bool isValid() const; + + /** + evaluates the Force(Slip) function + */ + float hermiteEval(float t) const; + + + int xmlLink; + +}; + +/** @} */ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pVehicle/pVehicle.h b/usr/Include/Core/pVehicle/pVehicle.h new file mode 100644 index 0000000..31694b8 --- /dev/null +++ b/usr/Include/Core/pVehicle/pVehicle.h @@ -0,0 +1,484 @@ +#ifndef __P_VEHICLE_H__ +#define __P_VEHICLE_H__ + +#include "vtPhysXBase.h" + +#include "pWheel.h" +#include "NxArray.h" +#include "NxUserContactReport.h" +#include "pVehicleGears.h" +#include "pVTireFunction.h" +#include "pReferencedObject.h" +#include "pCallbackObject.h" + + +class pEngine; +class pGearBox; +class pDifferential; +class pDriveLine; +class pVehicleSteer; + + + +/** \addtogroup Vehicle +@{ +*/ +typedef std::vectorWheelArrayType; + +/** +\brief A abstract base class for a vehicle object. +*/ + +typedef enum pVehicleControlStateItem +{ + E_VCS_ACCELERATION, + E_VCS_STEERING, + E_VCS_HANDBRAKE, + E_VCS_BRAKING, + E_VCS_GUP, + E_VCS_GDOWN, + E_VCS_TCLUTCH, + E_VCS_STARTER, + E_VCS_BRAKES, +}; +enum ControlTypes +// Which kind of controls do we have? +{ + T_STEER_LEFT,T_STEER_RIGHT, + T_THROTTLE,T_BRAKES, + T_SHIFTUP,T_SHIFTDOWN, + T_CLUTCH, + T_HANDBRAKE, + T_STARTER, + T_HORN, + MAX_CONTROLLER_TYPE +}; + +typedef enum pVehicleControlStateItemMode +{ + E_VCSM_ANALOG, + E_VCSM_DIGITAL, +}; + +typedef enum pVehicleBreakCase +{ + BC_NoUserInput, + BC_DirectionChange, + BC_UserBreak, + BC_Handbrake, + BC_NumBreakCases, +}; + +typedef enum pVehicleBreakLevel +{ + BL_NoBreak=-1, + BL_Small, + BL_Medium, + BL_High, + BL_NumBreakLevels, +}; + +typedef enum +{ + VBF_UseTable=(1<<0), + VBF_Autobreak=(1<<1), + +}; +enum VehicleStatus +{ + VS_IsMoving=(1<<0), + VS_IsAccelerated=(1<<1), + VS_IsAcceleratedForward=(1<<2), + VS_IsAcceleratedBackward=(1<<3), + VS_AllWheelsOnGround=(1<<4), + VS_IsFalling=(1<<5), + VS_Handbrake=(1<<6), + VS_IsBraking=(1<<7), + VS_IsSteering=(1<<8), + VS_HasGearBox=(1<<9), + VS_HasMotor=(1<<10), + VS_IsRollingForward=(1<<11), + VS_IsRollingBackward=(1<<12), +}; + +class MODULE_API pVehicle : + public xEngineObjectAssociation, + public pCallbackObject +{ + +public: + + + //---------------------------------------------------------------- + // + // new engine code + // + enum Max + { + MAX_WHEEL=8, + MAX_DIFFERENTIAL=3, // Enough for a 4WD Jeep + MAX_WING=10, // Front, rear and perhaps others + MAX_CAMERA=10 // Max #camera's around car + }; + pEngine *engine; + pGearBox *gearbox; + pDifferential *differential[MAX_DIFFERENTIAL]; + int differentials; + pDriveLine *driveLine; + pVehicleSteer *steer; + + + float motorTorque; + float breakTorque; + + + + //---------------------------------------------------------------- + // + // public access + // + pDifferential *getDifferential(int n){ return differential[n]; } + pEngine *getEngine(){ return engine; } + pDriveLine *getDriveLine(){ return driveLine; } + pGearBox *getGearBox(){ return gearbox; } + pVehicleSteer * getSteer() { return steer; } + void setSteer(pVehicleSteer * val) { steer = val; } + + void findDifferentialWheels(int& wheel1Index,int& wheel2Index); + + + + int getNbDifferentials(){ return differentials; } + void addDifferential(pDifferential *diff); + + float getRPM(); + bool isStalled(); + bool isAutoClutch(); + bool isAutoShifting(); + int getGear(); + bool isValidEngine(); + bool hasDifferential(); + bool shiftUp(); + bool shiftDown(); + int setGear(int gear); + float getTorque(int component); + + //---------------------------------------------------------------- + // + // control + // + void setControlState(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake); + void setControlState(int parameter,float value); + void setControlMode(int parameter,int mode); + void getControlState(int parameter,float &value,int &mode); + + + //---------------------------------------------------------------- + // + // internal + // + int initEngine(int flags); + int doEngine(int flags,float dt); + void preCalculate(); + void calcForces(); + void integrate(); + void postStep(); + void cleanup(); + + void PreCalcDriveLine(); + + void calculateForces(); + + + void preAnimate(); + void postAnimate(); + + void setClutch(float clutch); + float getClutch(); + + + + + + //---------------------------------------------------------------- + // + // manager calls + // + void step(float dt); + + + void advanceTime(float lastDeltaMS); + + //---------------------------------------------------------------- + // + // manager calls + // + int onPreProcess(); + int onPostProcess(); + + void processPostScript(); + void processPreScript(); + + + XString debugPrint(int mask); + + //---------------------------------------------------------------- + // + // Break functions + // + + bool useBreakTable; + int breakFlags; + int breakConditionLevels[BC_NumBreakCases]; + float mBreakPressures[BL_NumBreakLevels]; + float mBrakeTable[BL_NumBreakLevels][BREAK_TABLE_ENTRIES]; //!< Brake Table to take advantage of a certain brake lvl at any one time + + pVehicleBrakeTable mSmallBrakeTable; + pVehicleBrakeTable mMediumBrakeTable; + pVehicleBrakeTable mHighBrakeTable; + + bool mBreakLastFrame; + + float mTimeBreaking; + float mBrakeMediumThresold; + float mBrakeHighThresold; + + + + void setBreakPressure(int breakLevel,float pressure); + float getBreakPressure(int breakLevel); + int getBreakFlags() const { return breakFlags; } + void setBreakFlags(int val) { breakFlags = val; } + + bool isUsingBreakTable() const { return useBreakTable; } + void setUsingBreakTable(bool val) { useBreakTable = val; } + pVehicleBreakCase calculateBreakCase(int currentAccelerationStatus); + + + void setBreakCaseLevel(pVehicleBreakCase breakCase,pVehicleBreakLevel level); + pVehicleBreakLevel getBreaklevelForCase(pVehicleBreakCase breakCase) { return (pVehicleBreakLevel)breakConditionLevels[breakCase]; } + + float getBrakeTorque(); + + void setMeasurementWheel(CK3dEntity*wheelReference); + float getBrakeAmount(pVehicleBreakLevel brakeLevel); + float getBrakeAmountFromTable(pVehicleBreakLevel brakeLevel); + + + + float getBrakeSmallPressure() {return mBreakPressures[BL_Small];} + float getBrakeMediumPressure() {return mBreakPressures[BL_Medium];} + float getBrakeHighPressure() {return mBreakPressures[BL_High];} + + float getBrakeMediumApplyTime() {return mBrakeMediumThresold;} + float getBrakeHighApplyTime() {return mBrakeHighThresold;} + + //---------------------------------------------------------------- + // + // misc + // + + int mVSFlags; + float _cSteering; + float _cAcceleration; + int _cShiftStateUp; + int _cShiftStateDown; + bool _cAnalogSteering; + bool _cAnalogAcceleration; + bool _cHandbrake; + + + NxArray _wheels; + + + + + + //WheelArrayType _wheels; + //NxArray getWheels() const { return _wheels; } + + + NxArray& getWheels() { return _wheels; } + + + int& getStateFlags() { return mVSFlags; } + void setVSFlags(int val) { mVSFlags = val; } + + + void printAllToConsole(); + + //---------------------------------------------------------------- + // + // old code + // + pVehicleGears* _vehicleGears; + pVehicleMotor* _vehicleMotor; + + + pVehicleMotor* getMotor() const { return _vehicleMotor; } + void setMotor(pVehicleMotor* val) { _vehicleMotor = val; } + + pVehicleGears* getGears() const { return _vehicleGears; } + void setGears(pVehicleGears* val) { _vehicleGears = val; } + + float _steeringWheelState; + float _accelerationPedal; + float _brakePedal; + bool _brakePedalChanged; + bool _handBrake; + float _acceleration; + + float _digitalSteeringDelta; + float _mass; + + float _lastDT; + VxVector _centerOfMass; + + VxVector _steeringTurnPoint; + + VxVector _steeringSteerPoint; + float getMass(); + void setMass(float val) { _mass = val; } + + + + VxVector getCenterOfMass() const { return _centerOfMass; } + void setCenterOfMass(VxVector val) { _centerOfMass = val; } + + + float getDigitalSteeringDelta() const { return _digitalSteeringDelta; } + void setDigitalSteeringDelta(float val) { _digitalSteeringDelta = val; } + + + + + VxVector getSteeringTurnPoint() const { return _steeringTurnPoint; } + void setSteeringTurnPoint(VxVector val) { _steeringTurnPoint = val; } + + + VxVector getSteeringSteerPoint() const { return _steeringSteerPoint; } + void setSteeringSteerPoint(VxVector val) { _steeringSteerPoint = val; } + + float getMotorForce() const { return _motorForce; } + void setMotorForce(float val) { _motorForce = val; } + + float _transmissionEfficiency; + float _steeringMaxAngleRad; + + float _motorForce; + NxVec3 _localVelocity; + bool _braking; + bool _releaseBraking; + float _maxVelocity; + NxMaterial* _carMaterial; + float _cameraDistance; + + + NxActor* _mostTouchedActor; + bool mAutomaticMode; + + float _differentialRatio; + + + float getTransmissionEfficiency() const { return _transmissionEfficiency; } + void setTransmissionEfficiency(float val) { _transmissionEfficiency = val; } + + + float getDifferentialRatio() const { return _differentialRatio; } + void setDifferentialRatio(float val) { _differentialRatio = val; } + + + + float getMaxVelocity() const { return _maxVelocity; } + void setMaxVelocity(float val) { _maxVelocity = val; } + + + bool getAutomaticMode() const { return mAutomaticMode; } + + + float getMPH(int type=0); + + void setAutomaticMode(bool autoMode); + + void _computeMostTouchedActor(); + void _computeLocalVelocity(); + float _computeAxisTorque(); + float _computeAxisTorqueV2(); + float _computeRpmFromWheels(); + float _computeMotorRpm(float rpm); + + void _updateRpms(); + + float _getGearRatio(); + + void _controlSteering(float steering, bool analogSteering); + void _controlAcceleration(float acceleration, bool analogAcceleration); + + + + float getMaxSteering() const { return _steerMax; } + void setMaxSteering(float val) { _steerMax = val; } + + float _steerMax; + int _nbTouching; + int _nbNotTouching; + int _nbHandbrakeOn; + int _currentStatus; + + int flags; + + int _calculateCurrentStatus(); + int _calculateReaction(); + int _calculateNextSteering(); + int _performSteering(float dt); + void doSteering(); + int _performAcceleration(float dt); + + + float calculateBraking(float dt); + + pRigidBody *mBody; + NxActor *mActor; + + + + public : + pVehicle(); + pVehicle(pVehicleDesc descr,CK3dEntity *referenceObject); + + pRigidBody * getBody() const { return mBody; } + void setBody(pRigidBody * val) { mBody = val; } + void setToDefault(); + + int initWheels(int flags); + + void updateWheels(int flags= 0); + + void handleContactPair(NxContactPair* pair, int carIndex); + void updateVehicle(float lastTimeStepSize); + void control (float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake); + void updateControl(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake); + void gearUp(); + void gearDown(); + void standUp(); + float getDriveVelocity(); + float getMaxVelocity() { return _maxVelocity; } + int getNbWheels() { return _wheels.size(); } + const pWheel* getWheel(int i); + pWheel*getWheel(CK3dEntity* wheelReference); + + + NxActor *getActor(); + void setActor(NxActor * val) { mActor = val; } + int load(const pVehicleDesc& src ); + +}; + + + + + + +/** @} */ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pVehicle/pVehicleGears.h b/usr/Include/Core/pVehicle/pVehicleGears.h new file mode 100644 index 0000000..6cfcafb --- /dev/null +++ b/usr/Include/Core/pVehicle/pVehicleGears.h @@ -0,0 +1,67 @@ +#ifndef __P_VEHICLE_GEARS_H__ + +#define __P_VEHICLE_GEARS_H__ + +#include "pVehicleTypes.h" +#include "NxArray.h" + + +#define NX_VEHICLE_MAX_NB_GEARS 32 + +/** \addtogroup Vehicle +@{ +*/ + +class MODULE_API pVehicleGearDesc { +public: + pVehicleGearDesc() { setToDefault(); } + void setToDefault(); + void setToCorvette(); + bool isValid() const; + int getMaxNumOfGears() const { return NX_VEHICLE_MAX_NB_GEARS; } + + + //NxArray forwardGears; + //NxArray forwardGearRatios; + int nbForwardGears; + pLinearInterpolation forwardGears[NX_VEHICLE_MAX_NB_GEARS]; + float forwardGearRatios[NX_VEHICLE_MAX_NB_GEARS]; + + //NxLinearInterpolationValues backwardGear; + float backwardGearRatio; +}; + +/** +\brief A abstract base class for a vehicle gear box. +*/ +class MODULE_API pVehicleGears { + +public: + //NxArray _forwardGears; + //NxArray _forwardGearRatios; + int _nbForwardGears; + pLinearInterpolation _forwardGears[NX_VEHICLE_MAX_NB_GEARS]; + float _forwardGearRatios[NX_VEHICLE_MAX_NB_GEARS]; + + //NxLinearInterpolationValues _backwardGear; + float _backwardGearRatio; + + int _curGear; + + +public: + pVehicleGears(): _curGear(1) { } + + //static NxVehicleGears* createVehicleGears(const NxVehicleGearDesc& gearDesc); + + float getCurrentRatio() const; + float getRatio(int gear) const; + int getGear() const { return _curGear; } + int getMaxGear() const { return _nbForwardGears; } + void gearUp() { _curGear = NxMath::min(_curGear+1, (int)_nbForwardGears); } + void gearDown() { _curGear = NxMath::max(_curGear-1, -1); } +}; + +/** @} */ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pVehicle/pVehicleMotor.h b/usr/Include/Core/pVehicle/pVehicleMotor.h new file mode 100644 index 0000000..0ee28d6 --- /dev/null +++ b/usr/Include/Core/pVehicle/pVehicleMotor.h @@ -0,0 +1,102 @@ +#ifndef __P_VEHICLE_MOTOR_H__ +#define __P_VEHICLE_MOTOR_H__ + +#include "vtPhysXBase.h" +#include "pVehicleTypes.h" +#include "pDriveline.h" +#include "pEngine.h" + + +/** \addtogroup Vehicle +@{ +*/ + +class MODULE_API pVehicleMotorDesc +{ +public: + pLinearInterpolation torqueCurve; + float maxRpmToGearUp; + float minRpmToGearDown; + float maxRpm; + float minRpm; + + void setToDefault(); + pVehicleMotorDesc() { setToDefault(); } + void setToCorvette(); + bool isValid() const; +}; + +class MODULE_API pVehicleMotor { + +public: + + pLinearInterpolation _torqueCurve; + + float _rpm; + + + + + float getMaxTorquePos() const { return _maxTorquePos; } + void setMaxTorquePos(float val) { _maxTorquePos = val; } + + + + float getMaxRpmToGearUp() const { return _maxRpmToGearUp; } + void setMaxRpmToGearUp(float val) { _maxRpmToGearUp = val; } + + float getMinRpmToGearDown() const { return _minRpmToGearDown; } + void setMinRpmToGearDown(float val) { _minRpmToGearDown = val; } + + + float getMaxTorque() const { return _maxTorque; } + void setMaxTorque(float val) { _maxTorque = val; } + + + + float _maxTorquePos; + float _maxTorque; + + float _maxRpm; + + + + + float _minRpm; + + + + float _minRpmToGearDown; + float _maxRpmToGearUp; + + + + pVehicleMotor() : _rpm(0) { } + + void setMaxRpm(float val) { _maxRpm = val; } + void setMinRpm(float val) { _minRpm = val; } + + + void setRpm(float rpm) { _rpm = rpm; } + float getRpm() const { return _rpm; } + + float getMinRpm() const { return _minRpm; } + float getMaxRpm() const { return _maxRpm; } + + + int changeGears(const pVehicleGears* gears, float threshold) const; + float getTorque() const { return _torqueCurve.getValue(_rpm); } + + int loadNewTorqueCurve(pLinearInterpolation newTCurve); + + + int reload(pVehicleMotorDesc* descr); + + +}; + + + +/** @} */ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pVehicle/pVehicleTypes.h b/usr/Include/Core/pVehicle/pVehicleTypes.h new file mode 100644 index 0000000..6b1e75d --- /dev/null +++ b/usr/Include/Core/pVehicle/pVehicleTypes.h @@ -0,0 +1,110 @@ +#ifndef __PVEHICLETYPES_H__ +#define __PVEHICLETYPES_H__ + +#include "pVTireFunction.h" +#include "pLinearInterpolation.h" + +/** \addtogroup Vehicle +@{ +*/ + +typedef enum FrictionCircleMethod +{ + FC_GENTA, // Genta (page 52?) + FC_VECTOR, // Vector reduction to fit circle + FC_VOID, // Don't touch forces (for testing) + FC_SLIPVECTOR // Gregor's method of combined Pacejka +}; + + +#define BREAK_TABLE_ENTRIES 10 + +class pVehicleBrakeTable +{ +public: + float brakeEntries[BREAK_TABLE_ENTRIES]; +}; + +class MODULE_API pVehicleDesc +{ + +public: + + VxVector position; + + pVehicleGearDesc *gearDescription; + pVehicleGearDesc * getGearDescription() { return gearDescription; } + + pVehicleMotorDesc *motorDescr; + pVehicleMotorDesc * getMotorDescr() { return motorDescr; } + + + + + float mass; + float motorForce; + float transmissionEfficiency; + float differentialRatio; + + VxVector steeringTurnPoint; + VxVector steeringSteerPoint; + float steeringMaxAngle; + + VxVector centerOfMass; + + float digitalSteeringDelta; + + float maxVelocity; + float digitalSteeringDeltaVelocityModifier; + + int xmlLinkID; + XString xmlName; + + pRigidBody *body; + + + void* userData; + + //---------------------------------------------------------------- + // + // Engine Related Parameters + // + float engineInertia; + float engineFriction; + float engineBrakingCoefficient; + float engineMaximumTorque; + + //-RPMs + float engineRpmMaximum; + float engineRpmIdle; + float engineRpmAutoClutch; + float engineRpmStart; + float engineRpmStall; + + int engineFlags; + + //-Engine Torque Curve + pLinearInterpolation torqueCurve; + + int processFlags; + + + + pVehicleDesc(); + void setToDefault(); + bool isValid() const; +}; + + + +typedef std::vectorWheelArrayType; + +/** @} */ + +#include "pLinearInterpolation.h" + + + + + +#endif // __PVEHICLETYPES_H__ \ No newline at end of file diff --git a/usr/Include/Core/pVehicle/pWheel.h b/usr/Include/Core/pVehicle/pWheel.h new file mode 100644 index 0000000..9a871f7 --- /dev/null +++ b/usr/Include/Core/pVehicle/pWheel.h @@ -0,0 +1,461 @@ +#ifndef __P_WHEEL_H__ +#define __P_WHEEL_H__ + +#include "vtPhysXBase.h" +#include "pDriveline.h" +#include "pReferencedObject.h" +#include "pCallbackObject.h" +#include "pPacejka.h" + + + +class pDifferential; +class pWheelContactModifyData; + + +//#include "pWheelTypes.h" + + + +/** \addtogroup Vehicle +@{ +*/ + +/** +\brief Base class to handle a vehicle wheel. +*/ +class MODULE_API pWheel : public pDriveLineComp +{ +public: + + + virtual ~pWheel() {} + + pWheel(pRigidBody *body,pWheelDescr *descr); + pRigidBody * getBody() const { return mBody; } + void setBody(pRigidBody * val) { mBody= val; } + + virtual void tick(bool handbrake, float motorTorque, float brakeTorque, NxReal dt) = 0; + virtual NxActor * getTouchedActor() const; + virtual VxVector getWheelPos() const = 0; + virtual void setAngle(NxReal angle) = 0; + virtual float getRpm() const = 0; + virtual VxVector getGroundContactPos() const = 0; + virtual float getRadius() const = 0; + + virtual bool hasGroundContact() const { return getTouchedActor() != NULL; } + bool getWheelFlag(WheelFlags flag) const { return (mWheelFlags & flag) != 0; } + + NxActor *getActor() const { return mActor; } + void setActor(NxActor* val) { mActor = val; } + + pRigidBody *mBody; + NxActor *mActor; + + + + int mWheelFlags; + int& getWheelFlags(){ return mWheelFlags; } + float _wheelRollAngle; + + float& getWheelRollAngle() { return _wheelRollAngle; } + void setWheelRollAngle(float val) { _wheelRollAngle = val; } + + pWheel1 *castWheel1(); + pWheel2 *castWheel2(); + + virtual void _updateVirtoolsEntity(bool position,bool rotation)=0; + virtual void _updateAgeiaShape(bool position,bool rotation)=0; + + int mEntID; + int getEntID() const { return mEntID; } + void setEntID(int val) { mEntID = val; } + + void setFlags(int flags); + + virtual void _tick(float dt){}; + + virtual int _constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); + + virtual pWheelContactData* getContact()=0; + + + NxMat34 mWheelPose; + virtual NxMat34& getWheelPose(){ return mWheelPose; } + void setWheelPose(NxMat34 val) { mWheelPose = val; } + +}; + +class MODULE_API pWheel1 : public pWheel +{ +public: + + + pWheel1(pRigidBody *body,pWheelDescr *descr); + pWheel1(); + + virtual void tick(bool handbrake, float motorTorque, float brakeTorque, float dt); + virtual NxActor * getTouchedActor(); + virtual VxVector getWheelPos() const; + virtual void setAngle(float angle); + virtual float getRpm() const; + virtual VxVector getGroundContactPos() const { return getWheelPos(); } + virtual float getRadius() const { return _radius; } + + ContactInfo *contactInfo; + + void _updateVirtoolsEntity(bool position,bool rotation); + void _updateAgeiaShape(bool position,bool rotation); + + NxConvexShape* getWheelConvex() const { return wheelConvex; } + void setWheelConvex(NxConvexShape* val) { wheelConvex = val; } + + NxCapsuleShape* getWheelCapsule() const { return wheelCapsule; } + void setWheelCapsule(NxCapsuleShape* val) { wheelCapsule = val; } + + + int _constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation); + + void getSteeringDirection(NxVec3& dir); + void updateContactPosition(); + void updateAngularVelocity(float lastTimeStepSize, bool handbrake); + void setWheelOrientation(const NxMat33& m); + + virtual void _tick(float dt); + + NxCapsuleShape* wheelCapsule; + + NxConvexShape* wheelConvex; + + + NxMaterial* material; + float _frictionToSide; + float _frictionToFront; + + float _turnAngle; + float _turnVelocity; + float _radius; + float _perimeter; + + float _angle; + float _wheelWidth; + float _maxSuspension; + //NxReal _rpm; + VxVector _maxPosition; + pWheelContactData *getContact(); + +}; +class MODULE_API pWheel2 : + public pWheel , + public xEngineObjectAssociation, + public pCallbackObject +{ + public: + + pWheel2(); + pWheel2(pRigidBody *body,pWheelDescr *descr,CK3dEntity *wheelShapeReference); + + //---------------------------------------------------------------- + // + // vehicle + // + + //---------------------------------------------------------------- + // + // new vehicle code : differential + // + pDifferential *differential; + int differentialSide; // Which output from the diff + void setDifferential(pDifferential *diff,int side); + pDifferential *getDifferential(){ return differential; } + int getDifferentialSide(){ return differentialSide; } + + pPacejka pacejka; + + pPacejka *getPacejka() { return &pacejka; } + void setPacejka(pPacejka val) { pacejka = val; } + + + // Translation + VxVector position; // Position in CC wrt the body (!) + VxVector velocity; // Velocity in wheel coords acceleration; + VxVector acceleration; // For the suspension + + VxVector GetVelocity(){ return velocity; } + VxVector GetAcceleration(){ return acceleration; } + VxVector GetSlipVectorCC(){ return slipVectorCC; } + VxVector GetPosContactWC(){ return posContactWC; } + + // Rotation + VxVector rotation; // Current rotation + VxVector rotationV; + VxVector rotationA; // Rotation speed and acceleration + + // Braking + float maxBrakingTorque; // Max. force when braking 100% + float brakingFactor; // For example .58 for fronts, .42 back + float lock; // Max angle of heading (radians) + + int stateFlags; + float lowSpeedFactor; // How slow it is spinning + float slipAngle; // Vel. vs. wheel dir in radians + float slipRatio; // Ratio of wheel speed vs. velocity + + // Pre-calculated + float distCGM; // Distance to center of geometry + float angleCGM; // Angle (around car Y) of wheel + float distCM; // Distance to center of mass + + float GetSlipAngle(){ return slipAngle; } + float GetSlipRatio(){ return slipRatio; } + float GetHeading(){ return rotation.y; } + float GetRotation(){ return rotation.x; } + float GetRotationV(){ return rotationV.x; } + + + + + float GetLock(){ return lock; } + + // End forces + VxVector forceVerticalCC; // Result of suspension+gravity + + float differentialSlipRatio; // SR calculated by differential eq. + float tanSlipAngle; // From this, 'slipAngle' is derived + float relaxationLengthLat; // 'b' in SAE 950311 + float lastU; // To detect switching of long. speed + float signU; // Sign of longitudinal speed + float relaxationLengthLong; // 'B' in SAE 950311 + float dampingFactorLong; // Damping at low speed + float dampingFactorLat; // Damping laterally + // Combined slip + float csSlipLen; // Combined slip vector length + float load; // Load on the wheel (N) + + float mass; // Mass of wheel+tyre + + float radius, + width; + float rollingCoeff; // Rolling resistance coefficient + + float toe; // Pre-rotating the wheel + float ackermanFactor; // Scaling the steering angle + + float optimalSR,optimalSA; // Optimal slip ratio/angle (in rad) + float tanOptimalSA; + + // Spring values + float tireRate; // Spring vertical rate of tire + + // SAE 950311 + float dampingCoefficientLat, // Amount of damping at low speed + dampingCoefficientLong; + float dampingSpeed; // Speed at which to start damping + + + float getTireRate() const { return tireRate; } + void setTireRate(float val) { tireRate = val; } + + + void preCalculate(); + void preAnimate(); + void postAnimate(); + void calcForces(); + + void calcVerticalForces(); + void calcLongForces(); + void calcLatForces(); + void calcBreakForces(); + + void Integrate(); + void postStep(); + void cleanup(); + + + // Physics + void CalcSlipRatio(VxVector *velWheelCC); + void CalcSlipAngle(); + void CalcSlipVelocity(); + void CalcLoad(); + void CalcPacejka(); + void CalcDamping(); + void CalcWheelPosWC(); + + void CalcWheelAngAcc(); + void CalcBodyForce(); + void CalcAccelerations(); + + void updateSteeringPose(float rollangle,float steerAngle,float dt); + void updatePosition(); + + + void setSteering(float angle); + float pWheel2::getSteerAngle(); + + + + void calculatePose(float dt); + + + + + + // Other state vars + //rfloat load; // Load on the wheel (N) + float radiusLoaded; // Rl = radius of loaded wheel to gnd + float aligningTorque; // Mz in the SAE system + + + //---------------------------------------------------------------- + // + // + // + VxVector torqueTC; // 3-dimensions of torque + VxVector torqueBrakingTC; // Total braking torque (incl. rr) + VxVector torqueRollingTC; // Rolling resistance + VxVector torqueFeedbackTC; // Feedback (road reaction) + VxVector forceRoadTC; // Because of slip ratio/angle + VxVector forceDampingTC; // Damping if low-speed (SAE950311) + VxVector forceBrakingTC; // Brakes + VxVector forceBodyCC; // Force on body (for acc.) + VxVector forceGravityCC; // Gravity that pulls wheel down + float velMagnitude; // Length of slip velocity vector (obs) + VxVector velWheelCC, // Real velocity of wheel + velWheelTC; // Velocity in tire coords + // End forces + + VxVector posContactWC; // Position of contact patch in WC + VxVector slipVectorCC, // Diff of tire vs wheel velocity + slipVectorTC; // In tire coords + float slipVectorLength; // Magnitude of slipVector?C + + pLinearInterpolation crvSlipTraction; // Traction curve for slip ratio + pLinearInterpolation crvSlipBraking; // Braking curve + pLinearInterpolation crvLatForce; // Slip angle -> normalized lat. force + pLinearInterpolation crvSlip2FC; // Effect of slip vel on frict. circle + + + // Status + VxVector slipVector; // Diff. of theorial v vs ACTUAL v + float frictionCoeff; // Current friction coefficient + float skidFactor; // How much skidding? 0..1 + float slip2FCVelFactor; // Scaling of 'crvSlip2FC' X axis + + + + + // Forces + VxVector GetForceRoadTC(){ return forceRoadTC; } + VxVector GetForceBodyCC(){ return forceBodyCC; } + VxVector GetTorqueTC(){ return torqueTC; } + // Feedback torque is the road reaction torque + VxVector GetTorqueFeedbackTC(){ return torqueFeedbackTC; } + VxVector GetTorqueBrakingTC(){ return torqueBrakingTC; } + VxVector GetTorqueRollingTC(){ return torqueRollingTC; } + + float getCsSlipLen() const { return csSlipLen; } + void setCsSlipLen(float val) { csSlipLen = val; } + VxVector getVelWheelCC() const { return velWheelCC; } + void setVelWheelCC(VxVector val) { velWheelCC = val; } + VxVector getVelWheelTC() const { return velWheelTC; } + void setVelWheelTC(VxVector val) { velWheelTC = val; } + float getRollingCoeff() { return rollingCoeff; } + void setRollingCoeff(float val) { rollingCoeff = val; } + + float getMass(); + void setMass(float val) { mass = val; } + + + bool hadContact; + + //NxWheelContactData *lastContactData; + pWheelContactData *lastContactData;// = *wheel2->getContact(); + + + + virtual void tick(bool handbrake, float motorTorque, float brakeTorque, float dt); + virtual NxActor * getTouchedActor() const; + virtual VxVector getWheelPos() const; + virtual void setAngle(float angle); + virtual float getRpm() const; + + VxVector getGroundContactPos() const; + bool hasGroundContact() const ; + float getRadius()const; + + NxWheelShape * getWheelShape() const { return mWheelShape; } + void setWheelShape(NxWheelShape * val) { mWheelShape = val; } + + void setAxleSpeed(float speed); + void setMotorTorque(float torque); + void setBreakTorque(float torque); + + float getSuspensionTravel() const; + float getAxleSpeed()const; + + void _updateVirtoolsEntity(bool position,bool rotation); + void _updateAgeiaShape(bool position,bool rotation); + + bool setSuspensionSpring(const pSpring& spring); + pSpring getSuspensionSpring(); + + void setSuspensionTravel(float travel); + int _constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation){ return 1;} + + pWheelContactData *getContact(); + bool getContact(pWheelContactData&dst); + virtual void _tick(float dt); + pVehicle * getVehicle() const { return mVehicle; } + void setVehicle(pVehicle * val) { mVehicle = val; } + + //---------------------------------------------------------------- + // + // manager calls + // + int onPreProcess(); + int onPostProcess(); + + void processPostScript(); + void processPreScript(); + + virtual bool onWheelContact(CK3dEntity* wheelShapeReference, VxVector& contactPoint, VxVector& contactNormal, float& contactPosition, float& normalForce, CK3dEntity* otherShapeReference, int& otherShapeMaterialIndex); + virtual void setWheelContactScript(int val); + virtual bool onWheelContactModify(int& changeFlags,pWheelContactModifyData *contact); + + pWheelContactModify *wheelContactModifyCallback; + + void _createInternalContactModifyCallback(); + + //---------------------------------------------------------------- + // + // physics + // + float getEndBrakingTorqueForWheel(); + float getEndTorqueForWheel(); + float getEndAccForWheel(); + + float getWheelTorque(); + float getWheelBreakTorque(); + + bool isAxleSpeedFromVehicle(); + bool isTorqueFromVehicle(); + + void applyTorqueToPhysics(); + void applyAxleSpeedToPhysics(); + + + + + CK3dEntity * getEntity() const { return entity; } + void setEntity(CK3dEntity * val) { entity = val; } + private: + + NxWheelShape * mWheelShape; + pVehicle *mVehicle; + CK3dEntity *entity; + +}; + +/** @} */ + +#endif \ No newline at end of file diff --git a/usr/Include/Core/pVehicle/pWheelTypes.h b/usr/Include/Core/pVehicle/pWheelTypes.h new file mode 100644 index 0000000..72b7612 --- /dev/null +++ b/usr/Include/Core/pVehicle/pWheelTypes.h @@ -0,0 +1,199 @@ +#ifndef __PWHEELTYPES_H__ +#define __PWHEELTYPES_H__ + +#include "NxVec3.h" +#include "NxMat34.h" +#include "NxUserContactReport.h" + +//#include "pRigidBodyTypes.h" +//#include "pVTireFunction.h" + + + + +/** \addtogroup Vehicle +@{ +*/ + +class pWheelContactModifyData +{ +public : + CK3dEntity *object; + VxVector contactPoint; + VxVector contactNormal; + float contactPosition; + float normalForce; + int otherMaterialIndex; + pWheelContactModify() + { + object = NULL; + contactPosition = 0.0f; + normalForce = 0.0f; + otherMaterialIndex = 0; + } +}; + + + + +struct ContactInfo +{ + ContactInfo() { reset(); } + void reset() { otherActor = NULL; relativeVelocity = 0; } + bool isTouching() const { return otherActor != NULL; } + NxActor* otherActor; + NxVec3 contactPosition; + NxVec3 contactPositionLocal; + NxVec3 contactNormal; + NxReal relativeVelocity; + NxReal relativeVelocitySide; +}; + + +/** +\brief Contact information used by pWheel + + +@see pWheel pWheel.getContact() +*/ +class pWheelContactData +{ +public: + /** + \brief The point of contact between the wheel shape and the ground. + + */ + VxVector contactPoint; + + /** + \brief The normal at the point of contact. + + */ + VxVector contactNormal; + + /** + \brief The direction the wheel is pointing in. + */ + VxVector longitudalDirection; + + /** + \brief The sideways direction for the wheel(at right angles to the longitudinal direction). + */ + VxVector lateralDirection; + + /** + \brief The magnitude of the force being applied for the contact. + */ + float contactForce; + + /** + \brief What these exactly are depend on NX_WF_INPUT_LAT_SLIPVELOCITY and NX_WF_INPUT_LNG_SLIPVELOCITY flags for the wheel. + */ + float longitudalSlip, lateralSlip; + + /** + \brief the clipped impulses applied at the wheel. + */ + float longitudalImpulse, lateralImpulse; + + /** + \brief The material index of the shape in contact with the wheel. + + @see pMaterial + */ + int otherShapeMaterialIndex; + + /** + \brief The distance on the spring travel distance where the wheel would end up if it was resting on the contact point. + */ + float contactPosition; + + /** + \brief The distance on the spring travel distance where the wheel would end up if it was resting on the contact point. + */ + CK3dEntity* contactEntity; + + + /** + \brief The material of the colliding shape + */ + pMaterial otherMaterial; + +}; + +/** +\brief An interface class that the user can implement in order to modify the contact point on which the +WheelShape base its simulation constraints. + +Threading: It is necessary to make this class thread safe as it will be called in the context of the +simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded +parts of the physics engine. + +You enable the use of this callback by specifying a callback function in NxWheelShapeDesc.wheelContactModify +or by setting a callback function through NxWheelShape.setUserWheelContactModify(). + +Please note: ++ There will only be callbacks if the WheelShape finds a contact point. Increasing the suspensionTravel value +gives a longer raycast and increases the chance of finding a contact point (but also gives a potentially slower +simulation). + +@see NxWheelShapeDesc.wheelContactModify NxWheelShape.setUserWheelContactModify() NxWheelShape.getUserWheelContactModify() +*/ +class MODULE_API pWheelContactModify : NxUserWheelContactModify +{ + public: + + pWheelContactModify() : + wheel(NULL) , lastContactModifyData() + { + + } + /** + \brief This callback is called once for each wheel and sub step before the wheel constraints are setup + and fed to the SDK. The values passed in the parameters can be adjusted to affect the vehicle simulation. + The most interesting values are contactPosition, contactPoint, and contactNormal. The contactPosition value + specifies how far on the travel distance the contactPoint was found. If you want to simulate a bumpy road, + then this is the main parameter to change. It is also good to adjust the contactPoint variable, so that the + wheel forces are applied in the correct position. + + \param wheelShape The WheelShape that is being processed. + \param contactPoint The contact point (in world coordinates) that is being used for the wheel. + \param contactNormal The normal of the geometry at the contact point. + \param contactPosition The distance on the spring travel distance where the wheel would end up if it was resting on the contact point. + \param normalForce The normal force on the wheel from the last simulation step. + \param otherShape The shape with which the wheel is in contact. + \param otherShapeMaterialIndex The material on the other shape in the position where the wheel is in contact. Currently has no effect on the simulation. + \param otherShapeFeatureIndex The feature on the other shape in the position where the wheel is in contact. + + \return Return true to keep the contact (with the possibly edited values) or false to drop the contact. + */ + virtual bool onWheelContact(NxWheelShape* wheelShape, NxVec3& contactPoint, NxVec3& contactNormal, NxReal& contactPosition, NxReal& normalForce, NxShape* otherShape, NxMaterialIndex& otherShapeMaterialIndex, NxU32 otherShapeFeatureIndex); + + pWheelContactModifyData* lastContactModifyData; + + + pWheelContactModifyData* getLastContactModifyData() const { return lastContactModifyData; } + void setLastContactModifyData(pWheelContactModifyData* val) { lastContactModifyData = val; } + + + pWheel2* getWheel() const { return wheel; } + void setWheel(pWheel2* val) { wheel = val; } + + pWheelContactModifyData& getLastData(){ return lastData; } + void setLastData(pWheelContactModifyData val) { lastData = val; } + + +private: + + pWheel2* wheel; + pWheelContactModifyData lastData; + + +}; + + + + +/** @} */ + +#endif // __PWHEELTYPES_H__ \ No newline at end of file diff --git a/usr/Include/Core/pWorld/pWorld.h b/usr/Include/Core/pWorld/pWorld.h new file mode 100644 index 0000000..9b73086 --- /dev/null +++ b/usr/Include/Core/pWorld/pWorld.h @@ -0,0 +1,493 @@ +#ifndef __P_WORLD_H__ +#define __P_WORLD_H__ + +#include "pTypes.h" + +/** +\brief Class to maintain physical objects. +*/ + class MODULE_API pWorld + { + + public: + pWorld(); + + bool m_bCompletedLastFrame; // in class definition + float m_fTimeSinceLastCallToSimulate; // in class def + + pWorld(CK3dEntity* _o); + virtual ~pWorld(); + + void _construct(); + + int hadBrokenJoint(); + void cleanBrokenJoints(); + + + CK3dEntity* getReference() const { return m_vtReference; } + void setReference(CK3dEntity* val) { m_vtReference = val; } + + pWorldSettings * getWorldSettings() const { return m_worldSettings; } + void setWorldSettings(pWorldSettings * val) { m_worldSettings = val; } + + pSleepingSettings * getSleepingSettings() const { return m_SleepingSettings; } + void setSleepingSettings(pSleepingSettings * val) { m_SleepingSettings = val; } + + NxScene* getScene() const { return mScene; } + void setScene(NxScene* val) { mScene = val; } + NxMaterial* getDefaultMaterial() const { return mDefaultMaterial; } + void setDefaultMaterial(NxMaterial* val) { mDefaultMaterial = val; } + + + int UpdateProperties(DWORD mode,DWORD flags); + + int& getDataFlags() { return m_DataFlags; } + void setDataFlags(int val) { m_DataFlags = val; } + void destroy(); + + + pRigidBody *getBody(CK3dEntity*ent); + pRigidBody *getBodyFromSubEntity(CK3dEntity *sub); + + //pJoint*getJoint(CK3dEntity*,CK3dEntity*); + pJoint*getJoint(CK3dEntity*_a,CK3dEntity*_b,JType type); + void deleteJoint(pJoint*joint); + + void _checkForDominanceConstraints(); + NxCompartment * compartment; + NxCompartment * getCompartment() const { return compartment; } + void setCompartment(NxCompartment * val) { compartment = val; } + + + /** @name Collision Filtering + */ + //@{ + + /** + \brief Setups filtering operations. See comments for ::pGroupsMask + + Sleeping: Does NOT wake the actors up automatically. + + \param[in] op0 Filter op 0. + \param[in] op1 Filter op 1. + \param[in] op2 Filter op 2. + + @see setFilterBool() setFilterConstant0() setFilterConstant1() + */ + void setFilterOps(pFilterOp op0,pFilterOp op1, pFilterOp op2); + + + /** + \brief Setups filtering's boolean value. See comments for ::pGroupsMask + + Sleeping: Does NOT wake the actors up automatically. + + \param[in] flag Boolean value for filter. + + @see setFilterOps() setFilterConstant0() setFilterConstant1() + */ + void setFilterBool(bool flag); + + /** + \brief Setups filtering's K0 value. See comments for ::pGroupsMask + + Sleeping: Does NOT wake the actors up automatically. + + \param[in] mask The new group mask. See #pGroupsMask. + + @see setFilterOps() setFilterBool() setFilterConstant1() + */ + void setFilterConstant0(const pGroupsMask& mask); + + /** + \brief Setups filtering's K1 value. See comments for ::pGroupsMask + + Sleeping: Does NOT wake the actors up automatically. + + \param[in] mask The new group mask. See #pGroupsMask. + + + @see setFilterOps() setFilterBool() setFilterConstant0() + */ + void setFilterConstant1(const pGroupsMask& mask); + + /** + \brief Retrieves filtering operation. See comments for ::pGroupsMask + + \param[out] op0 First filter operator. + \param[out] op1 Second filter operator. + \param[out] op2 Third filter operator. + + See the user guide page "Contact Filtering" for more details. + + \return the filter operation requested + + @see setFilterOps() setFilterBool() setFilterConstant0() setFilterConstant1() + */ + void getFilterOps(pFilterOp& op0, pFilterOp& op1, pFilterOp& op2)const; + + /** + \brief Retrieves filtering's boolean value. See comments for ::pGroupsMask + + \return flag Boolean value for filter. + + @see setFilterBool() setFilterConstant0() setFilterConstant1() + */ + bool getFilterBool() const; + + /** + \brief Gets filtering constant K0. See comments for ::pGroupsMask + + \return the filtering constant, as a mask. See #pGroupsMask. + + @see setFilterOps() setFilterBool() setFilterConstant0() setFilterConstant1() getFilterConstant1() + */ + pGroupsMask getFilterConstant0() const; + + /** + \brief Gets filtering constant K1. See comments for ::NxGroupsMask + + \return the filtering constant, as a mask. See #pGroupsMask. + + @see setFilterOps() setFilterBool() setFilterConstant0() setFilterConstant1() getFilterConstant0() + */ + pGroupsMask getFilterConstant1() const; + + + + + + + + //@} + + + + /** @name Raycasting + */ + //@{ + + /** + \brief Returns true if any axis aligned bounding box enclosing a shape of type shapeType is intersected by the ray. + + \note Make certain that the direction vector of NxRay is normalized. + + \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is + taken. For example the result of setting the global pose is not immediately visible. + + \param[in] worldRay The ray to cast in the global frame. Range: See #NxRay + \param[in] shapesType Choose if to raycast against static, dynamic or both types of shape. See #pShapesType. + \param[in] groups Mask used to filter shape objects. See #pRigidBody::setGroup + \param[in] maxDist Max distance to check along the ray for intersecting bounds. Range: (0,inf) + \param[in] groupsMask Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask + + \return true if any axis aligned bounding box enclosing a shape of type shapeType is intersected by the ray + + @see pShapesType VxRay pRigidBody.setGroup() raycastAnyShape() + */ + bool raycastAnyBounds (const VxRay& worldRay, pShapesType shapesType, pGroupsMask *groupsMask=NULL,int groups=0xffffffff, float maxDist=pFLOAT_MAX); + + /** + \brief Returns true if any shape of type ShapeType is intersected by the ray. + + \note Make certain that the direction vector of NxRay is normalized. + + \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is + taken. For example the result of setting the global pose is not immediately visible. + + \param[in] worldRay The ray to cast in the global frame. Range: See #VxRay + \param[in] shapesType Choose if to raycast against static, dynamic or both types of shape. See #pShapesType. + \param[in] groups Mask used to filter shape objects. See #pRigidBody::setGroup + \param[in] maxDist Max distance to check along the ray for intersecting objects. Range: (0,inf) + \param[in] groupsMask Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask + \param[in] cache Possible cache for persistent raycasts, filled out by the SDK. + + \return Returns true if any shape of type ShapeType is intersected by the ray. + + @see pShapesType VxRay pRigidBody.setGroup() raycastAnyBounds() + */ + bool raycastAnyShape (const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,CKDataArray* cache, int groups=0xffffffff, float maxDist=pFLOAT_MAX); + + /** + \brief Calls the report's hitCallback() method for all the shapes of type ShapeType intersected by the ray. + + hintFlags is a combination of ::NxRaycastBit flags. + Returns the number of shapes hit. The point of impact is provided as a parameter to hitCallback(). + + \note Make certain that the direction vector of NxRay is normalized. + + \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is + taken. For example the result of setting the global pose is not immediatly visible. + +

Example

+ + \include NxUserRaycastReport_Usage.cpp + + + \param[in] worldRay The ray to cast in the global frame. Range: See #NxRay + \param[in] report User callback, to be called when an intersection is encountered. + \param[in] shapesType Choose if to raycast against static, dynamic or both types of shape. See #NxShapesType. + \param[in] groups Mask used to filter shape objects. See #NxShape::setGroup + \param[in] maxDist Max distance to check along the ray for intersecting objects. Range: (0,inf) + \param[in] hintFlags Allows the user to specify which field of #NxRaycastHit they are interested in. See #NxRaycastBit + \param[in] groupsMask Alternative mask used to filter shapes. See #NxShape::setGroupsMask + + \return the number of shapes hit + + Platform: + \li PC SW: Yes + \li PPU : Yes + \li PS3 : Yes + \li XB360: Yes + + @see raycastAnyShape() raycastAllBounds() NxRay NxUserRaycastReport NxShapesType NxShape.setGroup() NxRaycastHit + */ + int raycastAllShapes (const VxRay& worldRay, pShapesType shapesType, int groups=0xffffffff, float maxDist=pFLOAT_MAX, pRaycastBit hintFlags=(pRaycastBit)0xffffffff, const pGroupsMask* groupsMask=NULL); + + + //@} + + + + + + + + + + /** @name Overlap Testing + */ + //@{ + + /** + \brief Returns the set of shapes overlapped by the world-space sphere. + + You can test against static and/or dynamic objects by adjusting 'shapeType'. + Shapes are written to the static array 'shapes', which should be big enough to hold 'nbShapes'. + + The function returns the total number of collided shapes. + + \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is + taken. For example the result of setting the global pose is not immediatly visible. + + \param[in] worldSphere Sphere description in world space. Range: See #VxSphere + \param[in] shapeType Choose if to intersect with static, dynamic or both types of shape. See #pShapesType. + \param[out] shapes Buffer to store intersecting shapes. + \param[in] activeGroups Mask used to filter shape objects. See #pRigidBody::setGroup + \param[in] groupsMask Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask + \param[in] accurateCollision True to test the sphere against the actual shapes, false to test against the AABBs only. + + \return the total number of collided shapes. + + + @see pShapesType overlapAABBShapes + */ + int overlapSphereShapes (const VxSphere& worldSphere,CK3dEntity*shapeReference,pShapesType shapeType,CKGroup *shapes,int activeGroups=0xffffffff, const pGroupsMask* groupsMask=NULL, bool accurateCollision=false); + + /** + \brief Returns the set of shapes overlapped by the world-space AABB. + + You can test against static and/or dynamic objects by adjusting 'shapeType'. + Shapes are written to the static array 'shapes', which should be big enough to hold 'nbShapes'. + + The function returns the total number of collided shapes. + + \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is + taken. For example the result of setting the global pose is not immediatly visible. + + \param[in] worldBounds Axis Aligned Bounding Box in world space. Range: + \param[in] shapeType Choose if to intersect with static, dynamic or both types of shape. See pShapesType. + \param[out] shapes Buffer to store intersecting shapes. + \param[in] activeGroups Mask used to filter shape objects. See #pRigidBody::setGroup + \param[in] groupsMask Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask + \param[in] accurateCollision True to test the AABB against the actual shapes, false to test against the AABBs only. + + \return the total number of collided shapes. + + @see pxShapesType overlapAABBShapes + */ + int overlapAABBShapes (const VxBbox& worldBounds, CK3dEntity*shapeReference, pShapesType shapeType,CKGroup *shapes,int activeGroups=0xffffffff, const pGroupsMask* groupsMask=NULL, bool accurateCollision=false); + + /** + \brief Returns the set of shapes overlapped by the world-space OBB. + + You can test against static and/or dynamic objects by adjusting 'shapeType'. + + The function returns the total number of collided shapes. + + \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is + taken. For example the result of setting the global pose is not immediatly visible. + + \param[in] worldBox Oriented Bounding Box in world space. Range: See #NxBox + \param[in] shapeType Choose if to intersect with static, dynamic or both types of shape. See #NxShapesType. + \param[out] shapes Buffer to store intersecting shapes. Should be at least sizeof(NxShape *) * nbShapes. + \param[in] activeGroups Mask used to filter shape objects. See #NxShape::setGroup + \param[in] groupsMask Alternative mask used to filter shapes. See #NxShape::setGroupsMask + \param[in] accurateCollision True to test the OBB against the actual shapes, false to test against the AABBs only. + + \return the total number of collided shapes. + + @see pShapesType overlapOBBShapes + */ + int overlapOBBShapes (const VxBbox& worldBox,CK3dEntity*shapeReference, pShapesType shapeType,CKGroup *shapes, int activeGroups=0xffffffff, const pGroupsMask* groupsMask=NULL, bool accurateCollision=false); + + /** + \brief Returns the set of shapes overlapped by the world-space capsule. + + You can test against static and/or dynamic objects by adjusting 'shapeType'. + Shapes are written to the static array 'shapes', which should be big enough to hold 'nbShapes'. + An alternative is to use the ::NxUserEntityReport callback mechanism. + + The function returns the total number of collided shapes. + + \note Because the SDK double buffers shape state, a shape will not be updated until a simulation step is + taken. For example the result of setting the global pose is not immediatly visible. + + \param[in] worldCapsule capsule in world space. Range: See #NxCapsule + \param[in] shapeType Choose if to intersect with static, dynamic or both types of shape. See #NxShapesType. + \param[out] shapes Buffer to store intersecting shapes. Should be at least sizeof(NxShape *) * nbShapes. + \param[in] activeGroups Mask used to filter shape objects. See #NxShape::setGroup + \param[in] groupsMask Alternative mask used to filter shapes. See #NxShape::setGroupsMask + \param[in] accurateCollision True to test the capsule against the actual shapes, false to test against the AABBs only. + + \return the total number of collided shapes. + + Platform: + \li PC SW: Yes + \li PPU : Yes + \li PS3 : Yes + \li XB360: Yes + + @see pShapesType overlapCapsuleShapes + */ + //virtual NxU32 overlapCapsuleShapes (const NxCapsule& worldCapsule, NxShapesType shapeType, NxU32 nbShapes, NxShape** shapes, NxUserEntityReport* callback, NxU32 activeGroups=0xffffffff, const NxGroupsMask* groupsMask=NULL, bool accurateCollision=false) = 0; + + //@} + + + + + + void step(float stepsize); + bool isValid(); + + JointFeedbackListType m_JointFeedbackList; + + JointFeedbackListType& getJointFeedbackList() { return m_JointFeedbackList; } + void setJointFeedbackList(JointFeedbackListType val) { m_JointFeedbackList = val; } + void inspectJoints(); + + void deleteBody(pRigidBody*body); + int getNbBodies(); + int getNbJoints(); + void checkList(); + + + /************************************************************************/ + /* */ + /************************************************************************/ + void cSetGroupCollisionFlag(int g1 , int g2,int enabled); + void cIgnorePair(CK3dEntity* _a,CK3dEntity *_b,int ignore); + + + void initUserReports(); + pContactReport *contactReport; + pContactReport*getContactReportPtr(){ return contactReport;} + + pContactModify *contactModify; + pContactModify*getContactModifyPtr(){ return contactModify;} + + pTriggerReport *triggerReport; + pTriggerReport *getTriggerReportPtr(){ return triggerReport;} + + pRayCastReport *raycastReport; + pRayCastReport * getRaycastReport(){ return raycastReport; } + void setRaycastReport(pRayCastReport * val) { raycastReport = val; } + + UserAllocator* mAllocator; + + UserAllocator* setAllocator() const { return mAllocator; } + void setAllocator(UserAllocator* val) { mAllocator= val; } + + int getNbOfVehicles(); + int getNbOfWhees(); + + + public : + + CK3dEntity* m_vtReference; + + pSleepingSettings *m_SleepingSettings; + pWorldSettings *m_worldSettings; + + NxScene* mScene; + NxMaterial* mDefaultMaterial; + NxControllerManager *mCManager; + + + + void updateVehicles(float dt); + void updateVehicle(pVehicle *vehicle,float dt); + pVehicle *getVehicle(CK3dEntity* body); + void deleteVehicle(CK3dEntity*body,int flags = 0); + bool isVehicle(NxActor* actor); + pWheel1 *getWheel1(CK3dEntity *reference); + pWheel2 *getWheel2(CK3dEntity *reference); + + /************************************************************************/ + /* */ + /************************************************************************/ + void updateClothes(); + void updateFluids(); + + + + pCloth *getCloth(CK3dEntity*reference); + pCloth *getCloth(CK_ID id); + void destroyCloth(CK_ID id); + + + pFluid *getFluid(CK_ID id); + pFluid *getFluid(CK3dEntity* entity); + + + NxShape *getShapeByEntityID(CK_ID id); + NxShape *getShapeByMeshID(CK_ID id); + + NxControllerManager * getCManager() const { return mCManager; } + void setCManager(NxControllerManager * val) { mCManager = val; } + + + void advanceTime(float lastDeltaMS); + int onPreProcess(); + int onPostProcess(); + + int callMask; + int& getCallMask() { return callMask; } + void setCallMask(int val) { callMask = val; } + + int overrideMask; + int& getOverrideMask() { return overrideMask; } + void setOverrideMask(int val) { overrideMask = val; } + + + + //---------------------------------------------------------------- + // + // material + // + bool getMaterialByIndex(int index,pMaterial&dst); + bool updateMaterialByIndex(int index,pMaterial src); + + + //---common settings + + void setGravity(VxVector gravity); + VxVector getGravity(); + + int m_DataFlags; + }; + +/** @} */ + +#endif // !defined(EA_0976AF4F_8E4B_4e7b_B4CD_B7588D3D4FF8__INCLUDED_) diff --git a/usr/Include/Core/pWorld/pWorldCallbacks.h b/usr/Include/Core/pWorld/pWorldCallbacks.h new file mode 100644 index 0000000..a6f1f04 --- /dev/null +++ b/usr/Include/Core/pWorld/pWorldCallbacks.h @@ -0,0 +1,65 @@ +#ifndef __PWORLDCALLBACKS_H__ +#define __PWORLDCALLBACKS_H__ + +#include "vtPhysXAll.h" + + + +class pRayCastReport : public NxUserRaycastReport +{ + +public: + + bool onHit(const NxRaycastHit& hit); + pWorld *mWorld; + pWorld * getWorld() const { return mWorld; } + void setWorld(pWorld * val) { mWorld = val; } + int mCurrentBehavior; + int getCurrentBehavior() const { return mCurrentBehavior; } + void setCurrentBehavior(int val) { mCurrentBehavior = val; } + pRayCastReport() + { + mWorld = NULL; + mCurrentBehavior=-1; + } +} ; + +class pContactReport : public NxUserContactReport +{ +public: + virtual void onContactNotify(NxContactPair& pair, NxU32 events); + pWorld *mWorld; + pWorld * getWorld() const { return mWorld; } + void setWorld(pWorld * val) { mWorld = val; } + +} ; + +class pContactModify : public NxUserContactModify +{ +public: + virtual bool onContactConstraint( + NxU32& changeFlags, + const NxShape* shape0, + const NxShape* shape1, + const NxU32 featureIndex0, + const NxU32 featureIndex1, + NxContactCallbackData& data); + + pWorld *mWorld; + pWorld * getWorld() const { return mWorld; } + void setWorld(pWorld * val) { mWorld = val; } + +} ; + + +class pTriggerReport : public NxUserTriggerReport +{ +public: + void onTrigger(NxShape& triggerShape, NxShape& otherShape, NxTriggerFlag status); + pWorld *mWorld; + pWorld * getWorld() const { return mWorld; } + void setWorld(pWorld * val) { mWorld = val; } +}; + + +#endif // __PWORLDCALLBACKS_H__ \ No newline at end of file diff --git a/usr/Include/Core/pWorld/pWorldSettings.h b/usr/Include/Core/pWorld/pWorldSettings.h new file mode 100644 index 0000000..d2796cb --- /dev/null +++ b/usr/Include/Core/pWorld/pWorldSettings.h @@ -0,0 +1,61 @@ +#if !defined(EA_45F10106_0809_49c3_8B43_1556D139853F__INCLUDED_) +#define EA_45F10106_0809_49c3_8B43_1556D139853F__INCLUDED_ + +namespace vtAgeia +{ + + class pWorldSettings + { + + + public: + + + pWorldSettings(); + + VxVector getGravity() const{ + + return m_Gravity; + } + void setGravity(VxVector val){ + m_Gravity = val; + } + float getSkinWith() const{ + return m_SkinWith; + } + void setSkinWith(float val) + { + m_SkinWith = val; + } + + bool isFixedTime() const { return fixedTime; } + void setFixedTime(bool val) { fixedTime = val; } + + int getNumIterations() const { return numIterations; } + void setNumIterations(int val) { numIterations = val; } + + float getFixedTimeStep() const { return fixedTimeStep; } + void setFixedTimeStep(float val) { fixedTimeStep = val; } + int getSceneFlags() const { return sceneFlags; } + void setSceneFlags(int val) { sceneFlags = val; } + + int getPhysicFlags() const { return physicFlags; } + void setPhysicFlags(int val) { physicFlags = val; } + + + protected: + + float m_SkinWith; + VxVector m_Gravity; + + float fixedTimeStep; + int numIterations; + bool fixedTime; + int sceneFlags; + int physicFlags; + + }; + + +} +#endif // !defined(EA_45F10106_0809_49c3_8B43_1556D139853F__INCLUDED_) diff --git a/usr/Include/Core/pWorld/pWorldTypes.h b/usr/Include/Core/pWorld/pWorldTypes.h new file mode 100644 index 0000000..58b6194 --- /dev/null +++ b/usr/Include/Core/pWorld/pWorldTypes.h @@ -0,0 +1,77 @@ +#ifndef __PWORLDTYPES_H__ +#define __PWORLDTYPES_H__ + + +//################################################################ +// +// Help structures and types +// + +//---------------------------------------------------------------- +// +//! \brief Meta info to track a broken joint from a NX-SDK callback to the next frame. +// +struct pBrokenJointEntry +{ + pJoint*joint; + float impulse; + CK_ID mAEnt; + CK_ID mBEnt; + bool isTriggered; + int jType; + + pBrokenJointEntry() + { + impulse = 0 ; + mAEnt = NULL; + mBEnt = NULL; + jType -1; + isTriggered = false; + } +}; + +typedef XArrayJointFeedbackListType; + + +/** \addtogroup World +@{ +*/ + +//---------------------------------------------------------------- +// +//! \brief Dominance setup for the scene +// +struct pDominanceSetupItem +{ + struct pDominanceConstraint + { + float dominanceA; + float dominanceB; + + pDominanceConstraint() : + dominanceA(1.0f), + dominanceB(0.0f) + { + + } + }; + + pDominanceConstraint constraint; + + int dominanceGroup0; + int dominanceGroup1; + + pDominanceSetupItem() : + dominanceGroup0(0), + dominanceGroup1(0) + { + } +}; + +/** @} */ + +//################################################################ +// +// User callbacks +// +#endif diff --git a/usr/Include/Core/sharedStructs.h b/usr/Include/Core/sharedStructs.h new file mode 100644 index 0000000..7ff8cf6 --- /dev/null +++ b/usr/Include/Core/sharedStructs.h @@ -0,0 +1,30 @@ +#include "CKAll.h" +#include "VSLManagerSDK.h" + + +enum vtEventState +{ + EEVT_STARTED, + EEVT_FINISHED +}; + +struct vtExternalEvent +{ + unsigned long timeOfCreation; + + char command[MAX_PATH]; + char commandArg[MAX_PATH]; + vtEventState state; +}; + +struct TSharedMemory { + + vtExternalEvent event; +}; + +struct haptekMsg +{ + XString command; + int k; + +}; \ No newline at end of file diff --git a/usr/Include/Core/vcWarnings.h b/usr/Include/Core/vcWarnings.h new file mode 100644 index 0000000..dbdc059 --- /dev/null +++ b/usr/Include/Core/vcWarnings.h @@ -0,0 +1,16 @@ +#ifndef __VC_WARNINGS_H__ +#define __VC_WARNINGS_H__ + +#pragma warning( disable : 4311 ) +#pragma warning( disable : 4244 ) +#pragma warning( disable : 4267 ) +#pragma warning( disable : 4275 ) +#pragma warning( disable : 4311) +#pragma warning( disable : 4099) +#pragma warning( disable : 4996) + + + + + +#endif diff --git a/usr/Include/Core/vtCBBErrorHelper.h b/usr/Include/Core/vtCBBErrorHelper.h new file mode 100644 index 0000000..51d98e9 --- /dev/null +++ b/usr/Include/Core/vtCBBErrorHelper.h @@ -0,0 +1,26 @@ +#ifndef __VT_C_BB_ERROR_HELPER_H__ + #define __VT_C_BB_ERROR_HELPER_H__ + +#ifndef __X_LOGGER_H__ + #include +#endif + +#ifndef __P_CONSTANTS_H__ + #include "pConstants.h" +#endif + + +#define CERROR_STRING(F) sBBErrorStrings[F] + + +#define bbSErrorME(A) { xLogger::xLog(XL_START,ELOGERROR,E_BB,CERROR_STRING(A));\ + XLOG_BB_INFO;\ + beh->ActivateOutput(0);\ + return CKBR_PARAMETERERROR ; } + +#define bbErrorME(A) { xLogger::xLog(XL_START,ELOGERROR,E_BB,A);\ + XLOG_BB_INFO;\ + beh->ActivateOutput(0);\ + return CKBR_PARAMETERERROR ; } + +#endif \ No newline at end of file diff --git a/usr/Include/Core/vtCModuleDefines.h b/usr/Include/Core/vtCModuleDefines.h new file mode 100644 index 0000000..832ab61 --- /dev/null +++ b/usr/Include/Core/vtCModuleDefines.h @@ -0,0 +1,24 @@ +/******************************************************************** + created: 2009/01/05 + created: 5:1:2009 18:18 + filename: x:\ProjectRoot\svn\local\vtTools\SDK\Include\Core\vtCModuleDefines.h + file path: x:\ProjectRoot\svn\local\vtTools\SDK\Include\Core + file base: vtCModuleDefines + file ext: h + author: + + purpose: +*********************************************************************/ +#ifndef __VTCMODULES_DEFINES_H_ + #define __VTCMODULES_DEFINES_H_ + +#include + +#define VTCMODULE_NAME VTCX_API_PREFIX("TOOLS") +#define VTCMODULE_ATTRIBUTE_CATAEGORY VTCMODULE_NAME + +#define VTM_TOOL_MANAGER_GUID CKGUID(0x7a9a6475,0x6fb90c74) + +#define VTBB_PLG_GUID CKGUID(0x3262afb,0x230b4434) + +#endif diff --git a/usr/Include/Core/vtModuleConstants.h b/usr/Include/Core/vtModuleConstants.h new file mode 100644 index 0000000..46a7c7c --- /dev/null +++ b/usr/Include/Core/vtModuleConstants.h @@ -0,0 +1,77 @@ +#ifndef __vtModuleConstants_h__ +#define __vtModuleConstants_h__ + + +//---------------------------------------------------------------- +// +// Include of system headers +// + +#include // float max + +//################################################################ +// +// Component specific names, prefixes,etc.... +// + +//---------------------------------------------------------------- +// +//! \brief Global API prefix +// +#define VTCX_API_PREFIX "vt" + +//---------------------------------------------------------------- +// +//! \brief Module name, merged with module suffix "vt" with see #VTCX_API_PREFIX +// +#define VTCMODULE_NAME VTCX_API_PREFIX("Physic") + + +//---------------------------------------------------------------- +// +//! \brief Modules attribute category prefix , using module name above +// +#define VTCMODULE_ATTRIBUTE_CATAEGORY VTCMODULE_NAME + +//---------------------------------------------------------------- +// +//! \brief Error enumerations +// +#include "vtModuleErrorCodes.h" + +//---------------------------------------------------------------- +// +//! \brief Error strings +// +#include "vtModuleErrorStrings.h" + +//---------------------------------------------------------------- +// +//! \brief Guids of the plug-in it self +// +#include "vtModuleGuids.h" + + + +//---------------------------------------------------------------- +// +//! \brief Math oriented values +// + +#define pSLEEP_INTERVAL (20.0f*0.02f) +#define pFLOAT_MAX FLT_MAX + + +//---------------------------------------------------------------- +// +//! \brief Constants for building blocks +// +#ifndef VTCX_AUTHOR + #define VTCX_AUTHOR "Guenter Baumgart" +#endif + +#ifndef VTCX_AUTHOR_GUID + #define VTCX_AUTHOR_GUID CKGUID(0x79ba75dd,0x41d77c63) +#endif + +#endif // vtModuleConstants_h__ \ No newline at end of file diff --git a/usr/Include/Core/vtPhysXAll.h b/usr/Include/Core/vtPhysXAll.h new file mode 100644 index 0000000..84ae235 --- /dev/null +++ b/usr/Include/Core/vtPhysXAll.h @@ -0,0 +1,127 @@ +/******************************************************************** + created: 2009/02/17 + created: 17:2:2009 10:21 + filename: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core\vtPhysXAll.h + file path: x:\ProjectRoot\svn\local\vtPhysX\SDK\Include\Core + file base: vtPhysXAll + file ext: h + author: Günter Baumgart + + purpose: Common header for all definitions. Includes ALL ! +*********************************************************************/ +#ifndef __VTPHYSXALL_H__ +#define __VTPHYSXALL_H__ + +#include "pTypes.h" + + +//################################################################ +// +// Help types +// + +//---------------------------------------------------------------- +// +//! \brief Include of necessary meta and extra structures. +// + +#include "pTypes.h" + +#include "pWorldTypes.h" +#include "pManagerTypes.h" +#include "pJointTypes.h" +#include "pRigidBodyTypes.h" + + +#include "pVehicleTypes.h" +#include "pWheelTypes.h" + +#include "pVehicleMotor.h" +#include "pVehicleGears.h" + +#include "pClothTypes.h" + + +//---------------------------------------------------------------- +// +//! \brief Logger +// +#include + + +//################################################################ +// +// Implementation Objects +// +#include "PhysicManager.h" +#include "pRigidBody.h" +#include "pFactory.h" +#include "pWorld.h" +#include "pJoint.h" +#include "pSerializer.h" + +#include "pWheel.h" +#include "pCloth.h" + + +//---------------------------------------------------------------- +// +//! \brief Vehicle Based Types +// +#include "pVehicle.h" + + +//################################################################ +// +// Implementation Helper +// +#include "pMisc.h" + + +//################################################################ +// +// Parameter Guids +// +#include "vtParameterGuids.h" + + +//################################################################ +// +// NVDIA PhysX Objects +// +#include "NxPhysics.h" +#include "NxUserOutputStream.h" +#include "NxSceneDesc.h" +#include "NxClothDesc.h" +#include "NxFluidDesc.h" +#include "NxFluidEmitterDesc.h" +#include "NxConvexShapeDesc.h" +#include "NxScene.h" +#ifdef VTPX_HAS_CHARACTER_CONTROLLER + #include "NxControllerManager.h" + #include "NxCharacter.h" + #include "NxBoxController.h" + #include "NxCapsuleController.h" + #include "pBoxController.h" +#endif + + + +//################################################################ +// +// Generic Virtools Helpers +// +#include + + + +//################################################################ +// +// Math conversions +// +#include "pMathTools.h" +using namespace pMath; + + + +#endif // __VTPHYSXALL_H__ \ No newline at end of file diff --git a/usr/Include/Core/xSystem3D.h b/usr/Include/Core/xSystem3D.h new file mode 100644 index 0000000..3b0a3c1 --- /dev/null +++ b/usr/Include/Core/xSystem3D.h @@ -0,0 +1,36 @@ +/******************************************************************** + created: 2007/10/29 + created: 29:10:2007 15:16 + filename: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src\xSystem3D.h + file path: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src + file base: xSystem3D + file ext: h + author: mc007 + + purpose: +*********************************************************************/ + +#include "pch.h" +#include "base_macros.h" + +class CKContext; +class CKBehaviorContext; + +namespace xSystem3DHelper +{ + + +#ifdef __cplusplus + extern "C" { +#endif + + API_EXPORT int xSGetAvailableTextureMem(); + API_EXPORT float xSGetPhysicalMemoryInMB(); + API_EXPORT int xSGetPhysicalGPUMemoryInMB(int device); + API_EXPORT void xSSaveAllDxPropsToFile(char*file); + +#ifdef __cplusplus + } +#endif + +} \ No newline at end of file diff --git a/usr/Include/Interface/PBXMLSetup.h b/usr/Include/Interface/PBXMLSetup.h new file mode 100644 index 0000000..f39185d --- /dev/null +++ b/usr/Include/Interface/PBXMLSetup.h @@ -0,0 +1,130 @@ +#pragma once +#include "StdAfx2.h" +#include "VIControls.h" +#include "ParameterDialog.h" +#include "CKShader.h" +//#include "CUIKNotificationReceiver.h" + +//--- Include "GenericObjectParameterDialog.h" from CK2UI define IDDs to mak it compile +#define IDD_GENOBJECTDIALOG 2011 +#define IDD_BASEPARAMDIALOG 2000 +#include "Parameters\GenericObjectParameterDialog.h" + +#include "resource.h" +#include "PCommonDialog.h" + + +//--- Some constants +#define MFC_NAME_OF_DIALOG "#32770" +#define CHECK_MATERIAL_TIMER 57 +class CPBXMLSetup : public CParameterDialog ,public CPSharedBase +{ + +public: + + // virtual void PreSubclassWindow(); + + int m_paramType; + + CPBXMLSetup(CKParameter* Parameter,CWnd* parent = NULL); + CPBXMLSetup(CKParameter* Parameter,CWnd *parent,CK_CLASSID Cid=CKCID_OBJECT); + CPBXMLSetup(CKParameter* Parameter,CK_CLASSID Cid=CKCID_OBJECT); + virtual ~CPBXMLSetup(); + void _destroy(); + + //BOOL Create(CKParameter* Parameter,UINT nIDTemplate, CWnd* pParentWnd); + //BOOL Init(CKParameter* Parameter,UINT nIDTemplate,CParameterDialog *parent); + + //BOOL OnInitDialog(); + + + CPBXMLSetup* refresh(CKParameter*src); + /************************************************************************/ + /* Overrides + */ + /************************************************************************/ + void OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); + LRESULT OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam); + + + /************************************************************************/ + /* Accessors */ + /************************************************************************/ + CKParameter * getEditedParameter() const { return mParameter; } + void setEditedParameter(CKParameter * val) { mParameter= val; } + + /************************************************************************/ + /* Virtools mParameter transfer callbacks : */ + /************************************************************************/ + virtual BOOL On_UpdateFromParameter(CKParameter* p){ + + // if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); + // if(!p) return FALSE; + + return TRUE; + } + + virtual BOOL On_UpdateToParameter(CKParameter* p) + { + + /* + if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); + if(!p) return FALSE; + CString cstr;*/ + return TRUE; + + } + + + +public: + + + /************************************************************************/ + /* Low Level passes */ + /************************************************************************/ + LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); + + + + /************************************************************************/ + /* Logical Actions */ + /************************************************************************/ + virtual int OnSelect(int before=-1); + + void fillXMLLinks(); + + HWND getDlgWindowHandle(UINT templateID); + + /************************************************************************/ + /* Members */ + /************************************************************************/ + + // Hull Type + + VIComboBox XMLInternLink; + VIStaticText XMLInternLinkLbl; + VIComboBox XMLExternLink; + VIStaticText XMLExternLinkLbl; + CKParameter *mParameter; + VIEdit editValue; + VIStaticText textValue; + VIComboBox type; + + + enum { IDD = IDD_PB_XML_PARENT }; + + //{{AFX_VIRTUAL(CPBXMLSetup) +protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + + //{{AFX_MSG(CPBXMLSetup) + BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() + + +public: + afx_msg void OnStnClickedXmlMainView(); +}; diff --git a/usr/Include/Interface/PBodySetup.h b/usr/Include/Interface/PBodySetup.h new file mode 100644 index 0000000..d504f31 --- /dev/null +++ b/usr/Include/Interface/PBodySetup.h @@ -0,0 +1,177 @@ +#pragma once + +#include "StdAfx2.h" +#include "VIControls.h" +#include "ParameterDialog.h" +//#include "CUIKNotificationReceiver.h" + +//--- Include "GenericObjectParameterDialog.h" from CK2UI define IDDs to mak it compile + + +#include "resource.h" +#include "PCommonDialog.h" +#include "afxwin.h" + + +//--- Some constants +#define MFC_NAME_OF_DIALOG "#32770" +#define CHECK_MATERIAL_TIMER 57 + +class CPBodyCfg : public CParameterDialog +{ + +public: + + // virtual void PreSubclassWindow(); + + int m_paramType; + + CPBodyCfg(CKParameter* Parameter,CK_CLASSID Cid=CKCID_OBJECT); + virtual ~CPBodyCfg(); + void _destroy(); + + //virtual BOOL Create(UINT nIDTemplate, CWnd* pParentWnd); + virtual void Init(CParameterDialog *parent); + + CParameterDialog* refresh(CKParameter*src); + void initSplitter(); + + /************************************************************************/ + /* Overrides + */ + /************************************************************************/ + void OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); + LRESULT OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam); + + + /************************************************************************/ + /* Accessors */ + /************************************************************************/ + CKParameter * getEditedParameter() const { return mParameter; } + void setEditedParameter(CKParameter * val) { mParameter= val; } + + + + /************************************************************************/ + /* Virtools mParameter transfer callbacks : */ + /************************************************************************/ + virtual BOOL On_UpdateFromParameter(CKParameter* p){ + + // if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); + // if(!p) return FALSE; + + return TRUE; + } + + virtual BOOL On_UpdateToParameter(CKParameter* p) + { + + /* + if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); + if(!p) return FALSE; + CString cstr;*/ + return TRUE; + + } + + + + // associated resource id : + enum { IDD = IDD_PBCOMMON }; + + + virtual int OnSelect(int before=-1); + + + + //{{AFX_VIRTUAL(CPBodyCfg) +protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + + + //{{AFX_MSG(CPBodyCfg) + + //}}AFX_MSG + +public: + + CParameterDialog *dlgDeformableSettings; + //VITrackCtrl mTestViControl; + //VITreeCtrl mTestViControl; + VITabCtrl mTestViControl; + CParameterDialog *mParent; + + + /************************************************************************/ + /* Low Level passes */ + /************************************************************************/ + LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); + + + + /************************************************************************/ + /* Members */ + /************************************************************************/ + + + // Hull Type + + VIComboBox HType; VIStaticText LBL_HType; + + void fillHullType(); + + + + // Body main Flags + + VIStaticText LBL_Flags; + + VICheckButton BF_Move; + VICheckButton BF_Grav; + VICheckButton BF_Collision; + VICheckButton BF_CollisionNotify; + + VICheckButton BF_Kinematic; + VICheckButton BF_TriggerShape; + VICheckButton BF_SubShape; + VICheckButton BF_Sleep; + VICheckButton BF_Hierarchy; + + VICheckButton BF_Deformable; + + VIStaticRectangle BF_BG_Rect; + VIStaticRectangle BF_FLEX_Rect; + + void fillFlags(); + + // Transformation Lock Flags + + VIStaticText LBL_TransformationLockFlags; + VICheckButton TF_POS; + VICheckButton TF_ROT; + VICheckButton TF_PX; VICheckButton TF_RX; + VICheckButton TF_PY; VICheckButton TF_RY; + VICheckButton TF_PZ; VICheckButton TF_RZ; + + + void fillTransformationFlags(); + + +public: + + + CKParameter *mParameter; + VIEdit editValue; + VIStaticText textValue; + VIComboBox type; + + DECLARE_MESSAGE_MAP() + + afx_msg void OnTcnSelchangeMaintab(NMHDR *pNMHDR, LRESULT *pResult); + CComboBox UserLevel; + afx_msg void OnCbnSelchangeHulltype2(); + afx_msg void OnStnClickedLblFlags(); + afx_msg void OnStnClickedDynaFlagsRect(); +}; + diff --git a/usr/Include/Interface/PCommonDialog.h b/usr/Include/Interface/PCommonDialog.h new file mode 100644 index 0000000..a6e8894 --- /dev/null +++ b/usr/Include/Interface/PCommonDialog.h @@ -0,0 +1,152 @@ +#pragma once + +#include "StdAfx2.h" +#include "VIControls.h" +#include "ParameterDialog.h" +#include "CKShader.h" +#include "ParameterDialog.h" +//#include "CUIKNotificationReceiver.h" + +//--- Include "GenericObjectParameterDialog.h" from CK2UI define IDDs to mak it compile +#define IDD_GENOBJECTDIALOG 2011 +#define IDD_BASEPARAMDIALOG 2000 +#include "Parameters\GenericObjectParameterDialog.h" + +#include "resource.h" + + +//--- Some constants +#define MFC_NAME_OF_DIALOG "#32770" +#define CHECK_MATERIAL_TIMER 57 + +class CPBCommonDialog : public CParameterDialog +{ + +public: + + + bool InitChildWin( CDialog* pDlg, UINT iWinID,int otherID ); + LRESULT OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam); + + + + //virtual BOOL Create(UINT nIDTemplate, CWnd* pParentWnd /* = NULL */); + + VIComboBox HType; + VIStaticText LBL_HType; + VIStaticText LBL_Flags; + VIStaticText LBL_DFlags; + + + VICheckButton BF_Move; + VICheckButton BF_Grav; + VICheckButton BF_Collision; + VICheckButton BF_CollisionNotify; + + VICheckButton BF_Kinematic; + VICheckButton BF_TriggerShape; + VICheckButton BF_SubShape; + VICheckButton BF_Sleep; + VICheckButton BF_Hierarchy; + + VICheckButton BF_Deformable; + + VIStaticRectangle BF_BG_Rect; + VIStaticRectangle BF_FLEX_Rect; + + CButton FlexButton; + CStatic mPlaceHolder; + + + VIStaticRectangle mDynaFlagsRect; + + + VICheckButton TF_POS; + VICheckButton TF_ROT; + + + + VICheckButton TF_PX; VICheckButton TF_RX; + VICheckButton TF_PY; VICheckButton TF_RY; + VICheckButton TF_PZ; VICheckButton TF_RZ; + + + CToolTipCtrl *m_tt; + + + int m_paramType; + + CPBCommonDialog(CKParameter* Parameter,CK_CLASSID Cid=CKCID_OBJECT) : CParameterDialog(Parameter,Cid) + { + setEditedParameter(Parameter); + m_tt =NULL; + + + + + } + virtual ~CPBCommonDialog() { } + + CKParameter *m_EditedParameter; + + CKParameter * getEditedParameter() const { return m_EditedParameter; } + void setEditedParameter(CKParameter * val) { m_EditedParameter = val; } + virtual CKBOOL On_Init(); + + // associated resource id : + enum { IDD = IDD_PBCOMMON }; + + // Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(CPBCommonDialog) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + + void fillHullType(); + void fillFlags(); + void fillTransformationFlags(); + +public: + + + + virtual BOOL On_UpdateFromParameter(CKParameter* p){ + +// if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); +// if(!p) return FALSE; + + return TRUE; + } + + virtual BOOL On_UpdateToParameter(CKParameter* p){ + + +/* if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); + if(!p) return FALSE; + + CString cstr; +/* + + +*/ + return TRUE; + } + + + + + virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); + + +public: + + + CKParameter *parameter; + VIEdit editValue; + VIStaticText textValue; + DECLARE_MESSAGE_MAP() + virtual BOOL OnInitDialog(); + virtual BOOL PreTranslateMessage(MSG* pMsg); + afx_msg void OnStnClickedDynaFlagsRect(); +}; \ No newline at end of file diff --git a/usr/Include/Interface/StdAfx2.h b/usr/Include/Interface/StdAfx2.h new file mode 100644 index 0000000..1bd7509 --- /dev/null +++ b/usr/Include/Interface/StdAfx2.h @@ -0,0 +1,56 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// +#pragma once + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#define WINVER 0x0501 + +#include // MFC core and standard components +#include // MFC extensions + +#ifndef _AFX_NO_OLE_SUPPORT +#include // MFC OLE classes +#include // MFC OLE dialog classes +#include // MFC Automation classes +#endif // _AFX_NO_OLE_SUPPORT + + +#ifndef _AFX_NO_DB_SUPPORT +#include // MFC ODBC database classes +#endif // _AFX_NO_DB_SUPPORT + +#ifndef _AFX_NO_DAO_SUPPORT +#include // MFC DAO database classes +#endif // _AFX_NO_DAO_SUPPORT + +#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + +//PLUGIN PRECOMPILED HEADER INCLUDED +#include "CKAll.h" +#include "VIControls.h" +#include "CKControlsAll.h" +#include "VEP_ScriptActionMenu.h" +#include "VEP_KeyboardShortcutManager.h" +#include "VEP_All.h" + + +#include "vtBodyStructs.h" +#include "vtJointsStructs.h" +#include "vtCModuleDefines.h" + +#include + +namespace vtAgeia{} +#include "xEnumerations.h" + +#include "pConfig.h" +#include + + + +using namespace CKControl; diff --git a/usr/Include/Interface/StdAfx2.h2 b/usr/Include/Interface/StdAfx2.h2 new file mode 100644 index 0000000..a9349a2 --- /dev/null +++ b/usr/Include/Interface/StdAfx2.h2 @@ -0,0 +1,103 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// +#pragma once +#ifndef _SECURE_ATL +#define _SECURE_ATL 1 +#endif + +#ifndef VC_EXTRALEAN +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#endif + + +//#include "targetver.h" + +//#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit + +// turns off MFC's hiding of some common and often safely ignored warning messages +//#define _AFX_ALL_WARNINGS + + + + +#include // MFC core and standard components +#include // MFC extensions +#include // MFC Automation classes +#include // MFC support for Internet Explorer 4 Common Controls +#include // MFC extensions +#include + + +#ifndef _AFX_NO_OLE_SUPPORT +#include // MFC OLE classes +#include // MFC OLE dialog classes +#include // MFC Automation classes +#endif // _AFX_NO_OLE_SUPPORT + + +#ifndef _AFX_NO_AFXCMN_SUPPORT + #include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + + +//#include // MFC support for ribbon and control bars + +#ifndef _AFX_NO_DB_SUPPORT +#include // MFC ODBC database classes +#endif // _AFX_NO_DB_SUPPORT + +#ifndef _AFX_NO_DAO_SUPPORT +#include // MFC DAO database classes +#endif // _AFX_NO_DAO_SUPPORT + +#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif // _AFX_NO_AFXCMN_SUPPORT + +//#include // MFC support for ribbons and control bars + +//#include // MFC support for ribbon and control bars + +/* +#if defined _M_IX86 +#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") +#elif defined _M_IA64 +#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"") +#elif defined _M_X64 +#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") +#else +#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") +#endif +*/ + +//PLUGIN PRECOMPILED HEADER INCLUDED +#include "CKAll.h" +#include "VIControls.h" +#include "CKControlsAll.h" +#include "VEP_ScriptActionMenu.h" +#include "VEP_KeyboardShortcutManager.h" +#include "VEP_All.h" + +#include "pch.h" + +#include "resource.h" +#include "VITabCtrl.h" +#include "VIControl.h" + +#include "vtBodyStructs.h" +#include "vtJointsStructs.h" +#include "vtCModuleDefines.h" + +#include + +namespace vtAgeia{} +#include "xEnumerations.h" + +#include "pConfig.h" + + + +using namespace CKControl; diff --git a/usr/Include/Interface/vtAgeiaInterfaceCallback.h b/usr/Include/Interface/vtAgeiaInterfaceCallback.h new file mode 100644 index 0000000..9a05c6b --- /dev/null +++ b/usr/Include/Interface/vtAgeiaInterfaceCallback.h @@ -0,0 +1,5 @@ +#pragma once + +void InitParameters(PluginInfo::CALLBACK_REASON reason,PluginInterface* plugininterface); + +void PluginCallback(PluginInfo::CALLBACK_REASON reason,PluginInterface* plugininterface); diff --git a/usr/Include/Interface/vtAgeiaInterfaceEditor.h b/usr/Include/Interface/vtAgeiaInterfaceEditor.h new file mode 100644 index 0000000..2cf9837 --- /dev/null +++ b/usr/Include/Interface/vtAgeiaInterfaceEditor.h @@ -0,0 +1,67 @@ +// vtAgeiaInterfaceEditor.h : main header file for the EDITOR DLL +// + +#pragma once + +#ifndef __AFXWIN_H__ + #error include 'stdafx.h' before including this file for PCH +#endif + +#include "resource.h" // main symbols + +class vtAgeiaInterfaceEditorDlg; +class vtAgeiaInterfaceToolbarDlg; + +extern vtAgeiaInterfaceEditorDlg* g_Editor; +extern vtAgeiaInterfaceToolbarDlg* g_Toolbar; + +//plugin interface for communication with Virtools Dev +extern PluginInterface* s_Plugininterface; + +///////////////////////////////////////////////////////////////////////////// +// CEditorApp +// See Editor.cpp for the implementation of this class +// + + +#include "PhysicManager.h" + + +class vtAgeiaInterfaceEditorApp : public CWinApp +{ +protected: + void InitImageList(); + void DeleteImageList(); + CImageList m_ImageList; + +public: + vtAgeiaInterfaceEditorApp(); + + CKContext *mContext; + PhysicManager *pMan; + PhysicManager *getPMan(){return pMan;} + CKContext *getContext(){return mContext;} + + + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(vtAgeiaInterfaceCEditorApp) + public: + virtual BOOL InitInstance(); + virtual int ExitInstance(); + //}}AFX_VIRTUAL + + //{{AFX_MSG(vtAgeiaInterfaceCEditorApp) + // NOTE - the ClassWizard will add and remove member functions here. + // DO NOT EDIT what you see in these blocks of generated code ! + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + + +///////////////////////////////////////////////////////////////////////////// + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. diff --git a/usr/Include/Interface/vtAgeiaInterfaceEditorDlg.h b/usr/Include/Interface/vtAgeiaInterfaceEditorDlg.h new file mode 100644 index 0000000..065d5b6 --- /dev/null +++ b/usr/Include/Interface/vtAgeiaInterfaceEditorDlg.h @@ -0,0 +1,83 @@ +#pragma once + +#include "PhysicManager.h" + + +// vtAgeiaInterfaceEditorDlg.h : header file +// + +//editor dialog creation function, to be called by Virtools Dev +DllEditorDlg* fCreateEditorDlg(HWND parent); + +///////////////////////////////////////////////////////////////////////////// +// EditorDlg dialog + +class vtAgeiaInterfaceEditorDlg : public DllEditorDlg +{ +public: + //called on creation of the dialog by Virtools Dev interface + //the PluginInterface will be avalaible only when the OnInterfaceInit() has been called + virtual void OnInterfaceInit(); + //called on destruction of the dialog by Virtools Dev interface + virtual void OnInterfaceEnd(); + //callback for receiving notification + virtual HRESULT ReceiveNotification(UINT MsgID,DWORD Param1=0,DWORD Param2=0,CKScene* Context=NULL); + + int OnGlobalKeyboardShortcut(int commandID); + int OnLocalKeyboardShortcut(int commandID); + virtual void OnCustomMenu(CMenu* menu,int startingCommandID,int endingCommandID); //fill custom menu, use commandID= baseID+startingCommandID + virtual void OnCustomMenu(int commandID); //callback when custom menu used, commandID==baseID (without the startingCommandID) + //Create a CTooltipCtrl for tooltip management + void CreateTooltip(); + + CKContext *mContext; + PhysicManager *pMan; + PhysicManager *getPMan(){return pMan;} + CKContext *getContext(){return mContext;} + + void init(CKContext *ctx,PhysicManager *pm); + void objectPosChanged(CK_ID objID); + void objectSelChanged(DWORD par1,DWORD par2); + + virtual BOOL LoadData(CKInterfaceObjectManager* iom); + virtual BOOL SaveData(CKInterfaceObjectManager* iom); + + +protected: + //tooltip + CToolTipCtrl m_wndToolTip; + +// Construction +public: + vtAgeiaInterfaceEditorDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(vtAgeiaInterfaceEditorDlg) + enum { IDD = IDD_EDITOR }; + // NOTE: the ClassWizard will add data members here + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(vtAgeiaInterfaceEditorDlg) + public: + virtual BOOL PreTranslateMessage(MSG* pMsg); + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(vtAgeiaInterfaceEditorDlg) + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + diff --git a/usr/Include/Interface/vtAgeiaInterfaceKeyboardShortcuts.h b/usr/Include/Interface/vtAgeiaInterfaceKeyboardShortcuts.h new file mode 100644 index 0000000..b1e5e35 --- /dev/null +++ b/usr/Include/Interface/vtAgeiaInterfaceKeyboardShortcuts.h @@ -0,0 +1,77 @@ +#pragma once + +//----------------------------------------------------------------------------- +//CATEGORY FLAGS--------------------------------------------------------------- +#define FIXED KeyboardShortcutManager::KSCategory::FIXED +#define GLOBAL KeyboardShortcutManager::KSCategory::GLOBAL +#define ACTIVE KeyboardShortcutManager::KSCategory::ACTIVE +#define HIDDEN KeyboardShortcutManager::KSCategory::HIDDEN + +//Notes : +// +//for Global shortcuts, you can check for them in WindowProc +// on WM_KEYDOWN +// VirtoolsExternalPlugin::KeyboardShortcutManager* ksm = GetInterface()->GetKeyboardShortcutManager(); +// int commandID = ksm->TestKS(STR_CATEGORY,pMsg->wParam); +// +//for Local shortcuts you can check for them in PreTranslateMessage +// on WM_SYSKEYDOWN (for alt+key or F10) or WM_KEYDOWN +// VirtoolsExternalPlugin::KeyboardShortcutManager* ksm = GetInterface()->GetKeyboardShortcutManager(); +// int commandID = ksm->TestKS(STR_CATEGORY,pMsg->wParam); + +//category name under which you want to have your keyboard shortcuts +#define STR_CATEGORY "vtAgeiaInterface Keyboard Shortcuts Category" + +//command ids sample - command ID min must be 1 +#define CID_A 1 +#define CID_B 2 + +//names of these commands, sample +#define STR_A "Command A" +#define STR_B "Command B" +//command ids sample end + + +//IMPORTANT! +//by default these functions are called in vtAgeiaInterfacecallback.cpp +//if you do not use callback (do not have vtAgeiaInterfacecallback.cpp), you should call these functions manually + +//register keyboard shortcut category (shortcuts of this category will be saved when Virtools Dev is closed) +int RegisterKeyboardShortcutCategory(); +//unregister keyboard shortcut category (shortcuts of this category will be saved no more when Virtools Dev is closed) +int UnregisterKeyboardShortcutCategory(); +//register keyboard shortcuts for your editor. Fill this function +int RegisterKeyboardShortcuts(); + +//function that returns command name from its command id +//used in RegisterActionEditorKSCategory, as a callback for the keyboard shortcut category +//to know the command name +//Note : in ksm->RegisterCategory, +// you can set the callback to NULL (change "GetCommandName" into "NULL" +// but you should then put directly names into keyboard shortcuts you register in that category +// see in RegisterActionEditorKS(); +// ks.key = 'A'; +// ks.flags = ks.KS_CONTROL|ks.KS_SHIFT|ks.KS_ALT; +// ks.commandID = CID_A; +// ks.name = "Command A"; //LINE TO ADD TO SET NAME DIRECTLY +// ksm->RegisterKS(index,ks); +// but in that case, it will be less easy to integrate into popup menus +const char* GetCommandName(int commandID); + +//function that returns command name +//usefull for popup menus +const char* GetCommandMenuName(int commandID,XString &name); + +/* +//here the sample code to fill a menu +#define MENUSTR(commandID) GetActionEditorMenuName(commandID,name) + + POINT p; + GetCursorPos(&p); + XString name; + CKVIPopupMenu menu; + menu.AddItem(MENUSTR(CID_A),CID_A); + menu.AddItem(MENUSTR(CID_B),CID_B); + m_ActionMenu.AddSeparator(); + menu.Show(p.x,p.y); +*/ \ No newline at end of file diff --git a/usr/Include/Interface/vtAgeiaInterfaceMenu.h b/usr/Include/Interface/vtAgeiaInterfaceMenu.h new file mode 100644 index 0000000..6a43034 --- /dev/null +++ b/usr/Include/Interface/vtAgeiaInterfaceMenu.h @@ -0,0 +1,13 @@ +#pragma once + +//by default these functions are called in vtAgeiaInterfacecallback.cpp +//if you do not use callback (do not have vtAgeiaInterfacecallback.cpp), you should call these functions manually + +//to add a menu in Virtools Dev main menu. +void InitMenu(); +//to remove the menu from Virtools Dev main menu +void RemoveMenu(); +//to fill menu with your own commands +void UpdateMenu(); + +#define STR_MAINMENUNAME "vtAgeiaInterface Menu" diff --git a/usr/Include/Interface/vtAgeiaInterfaceToolbarDlg.h b/usr/Include/Interface/vtAgeiaInterfaceToolbarDlg.h new file mode 100644 index 0000000..b3238ef --- /dev/null +++ b/usr/Include/Interface/vtAgeiaInterfaceToolbarDlg.h @@ -0,0 +1,61 @@ +#pragma once + +// vtAgeiaInterfaceToolbarDlg.h : header file +// + +//toolbar dialog creation function, to be called by Virtools Dev +DllToolbarDlg* fCreateToolbarDlg(HWND parent); + +///////////////////////////////////////////////////////////////////////////// +// ToolbarDlg dialog + +class vtAgeiaInterfaceToolbarDlg : public DllToolbarDlg +{ +public: + //called on creation of the dialog by Virtools Dev interface + //the PluginInterface will be avalaible only when the OnInterfaceInit() has been called + virtual void OnInterfaceInit(); + //called on destruction of the dialog by Virtools Dev interface + virtual void OnInterfaceEnd(); + //callback for receiving notification + virtual HRESULT ReceiveNotification(UINT MsgID,DWORD Param1=0,DWORD Param2=0,CKScene* Context=NULL); + + //Create a CTooltipCtrl for tooltip management + void CreateTooltip(); + +protected: + //tooltip + CToolTipCtrl m_wndToolTip; + +// Construction +public: + vtAgeiaInterfaceToolbarDlg(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(vtAgeiaInterfaceToolbarDlg) + enum { IDD = IDD_TOOLBAR }; + // NOTE: the ClassWizard will add data members here + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(vtAgeiaInterfaceToolbarDlg) + public: + virtual BOOL PreTranslateMessage(MSG* pMsg); + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(vtAgeiaInterfaceToolbarDlg) + virtual BOOL OnInitDialog(); + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. diff --git a/usr/Include/xmlstream/XLoader.h b/usr/Include/xmlstream/XLoader.h new file mode 100644 index 0000000..6efecb3 --- /dev/null +++ b/usr/Include/xmlstream/XLoader.h @@ -0,0 +1,90 @@ +/*************************************************************************/ +/* File : XLoader.h */ +/* */ +/* DirectX .X files loader */ +/* */ +/* Virtools SDK */ +/* Copyright (c) Virtools 2000, All Rights Reserved. */ +/*************************************************************************/ + +#ifndef _XLOADER_H +#define _XLOADER_H + +//#include "Windows.h" +#include "stdio.h" +#include "DxFile.h" +#include "rmxfguid.h" +#include "rmxftmpl.h" +#include "Ge2Virtools.h" +#include "ptypes.h" + + +XString GetFileObjectName(LPDIRECTXFILEOBJECT obj); + + +#define SAFERELEASE(x) { if (x) x->Release(); x = NULL; } + +/************************************************** ++ Overload of a model reade ++ +***************************************************/ +class CKXReader: public CKModelReader { +public: + void Release() {delete this; }; + +// Reader Info + virtual CKPluginInfo* GetReaderInfo(); + +// No specific Options + virtual int GetOptionsCount() { return 0; } + virtual CKSTRING GetOptionDescription(int i) { return NULL; } + +// This reader can only load .X files + virtual CK_DATAREADER_FLAGS GetFlags() {return (CK_DATAREADER_FLAGS)CK_DATAREADER_FILELOAD;} + +// Load Method + virtual CKERROR Load(CKContext* context,CKSTRING FileName,CKObjectArray *liste,CKDWORD LoadFlags,CKCharacter *carac=NULL); + BOOL LoadFromFileC(CKContext *ctx, XString filename, CKBOOL hidden, CKDWORD loadflags, CKObjectArray* targetArray, XString password); + + + CKXReader() { + + m_Context = NULL; + m_VirtoolsExport = NULL; + + m_Unnamed = 0; + } + ~CKXReader() { + CleanUp(); + } + +protected: + void CleanUp() { + + delete m_VirtoolsExport; + m_VirtoolsExport = NULL; + } +//-- High level + + + //-- For unnamed objects return a generic string "Unnamed_XX" + XString GetUnnamed() { XString Temp = "Unnamed_"; Temp << m_Unnamed++; return Temp; } + +public: + CKContext* m_Context; + CK_OBJECTCREATION_OPTIONS m_CreationOptions; + CKCharacter* m_Character; + DWORD m_LoadFlags; + CK_CLASSID m_3dObjectsClass; + XString m_FileName; + + Export2Virtools* m_VirtoolsExport; + + int m_Unnamed; + float m_AnimationLength; + + +}; + + +#endif \ No newline at end of file diff --git a/usr/Src/Behaviors/AddNodalLink.cpp b/usr/Src/Behaviors/AddNodalLink.cpp new file mode 100644 index 0000000..1a660b9 --- /dev/null +++ b/usr/Src/Behaviors/AddNodalLink.cpp @@ -0,0 +1,81 @@ +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +// +// AddNodalLink +// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +#include "CKAll.h" +#include "N3dGraph.h" + +CKObjectDeclaration *FillBehaviorAddNodalLinkDecl(); +CKERROR CreateAddNodalLinkProto(CKBehaviorPrototype **); +int AddNodalLink(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorAddNodalLinkDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Create Nodal Edge"); + od->SetDescription(""); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x47ea2c5c,0x5b6b2b81)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateAddNodalLinkProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + od->SetCategory("3D Transformations/Nodal Path"); + return od; +} + + +CKERROR CreateAddNodalLinkProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = NULL; + proto = CreateCKBehaviorPrototype("Create Nodal Edge"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Nodal Path",CKPGUID_GROUP); + proto->DeclareInParameter("Start Node",CKPGUID_3DENTITY); + proto->DeclareInParameter("End Node",CKPGUID_3DENTITY); + proto->DeclareInParameter("Difficult",CKPGUID_FLOAT); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction( AddNodalLink ); + + *pproto = proto; + return CK_OK; + +} + + +int AddNodalLink(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + CKAttributeManager* attman = ctx->GetAttributeManager(); + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + + CKGroup* group = (CKGroup*)beh->GetInputParameterObject(0); + CKParameterOut* param = group->GetAttributeParameter(attman->GetAttributeTypeByName(Network3dName)); + if(!param) throw "Given Group isn't a Network"; + N3DGraph* graph; + param->GetValue(&graph); + + CK3dEntity* s = (CK3dEntity*)beh->GetInputParameterObject(1); + CK3dEntity* e = (CK3dEntity*)beh->GetInputParameterObject(2); + float b; + beh->GetInputParameterValue(3,&b); + graph->InsertEdge(s,e,b); + beh->ActivateOutput(0); + + + + + + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/DeleteNodalLink.cpp b/usr/Src/Behaviors/DeleteNodalLink.cpp new file mode 100644 index 0000000..5d8090d --- /dev/null +++ b/usr/Src/Behaviors/DeleteNodalLink.cpp @@ -0,0 +1,76 @@ +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +// +// DeleteNodalLink +// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +#include "CKAll.h" +#include "N3dGraph.h" + +CKObjectDeclaration *FillBehaviorDeleteNodalLinkDecl(); +CKERROR CreateDeleteNodalLinkProto(CKBehaviorPrototype **); +int DeleteNodalLink(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorDeleteNodalLinkDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("DeleteNodalLink"); + od->SetDescription(""); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x6ff16e0d,0x34561d5a)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateDeleteNodalLinkProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + od->SetCategory("3D Transformations/Nodal Path"); + return od; +} + + +CKERROR CreateDeleteNodalLinkProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = NULL; + proto = CreateCKBehaviorPrototype("DeleteNodalLink"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Nodal Path",CKPGUID_GROUP); + proto->DeclareInParameter("Start Node",CKPGUID_3DENTITY); + proto->DeclareInParameter("End Node",CKPGUID_3DENTITY); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction( DeleteNodalLink ); + + *pproto = proto; + return CK_OK; + +} + + +int DeleteNodalLink(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + CKAttributeManager* attman = ctx->GetAttributeManager(); + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + + CKGroup* group = (CKGroup*)beh->GetInputParameterObject(0); + CKParameterOut* param = group->GetAttributeParameter(attman->GetAttributeTypeByName(Network3dName)); + if(!param) throw "Given Group isn't a Network"; + N3DGraph* graph; + param->GetValue(&graph); + + CK3dEntity* s = (CK3dEntity*)beh->GetInputParameterObject(1); + CK3dEntity* e = (CK3dEntity*)beh->GetInputParameterObject(2); + + + graph->DeleteEdge(s,e); + + graph->DeleteEdge(e,s); + + beh->ActivateOutput(0); + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/Files/DirToArray.cpp b/usr/Src/Behaviors/Files/DirToArray.cpp new file mode 100644 index 0000000..97d61fd --- /dev/null +++ b/usr/Src/Behaviors/Files/DirToArray.cpp @@ -0,0 +1,111 @@ +#include "CKAll.h" + +CKObjectDeclaration *FillBehaviorDirToArrayDecl(); +CKERROR CreateDirToArrayProto(CKBehaviorPrototype **pproto); +int DirToArray(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorDirToArrayDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Dir to Array"); + od->SetDescription(""); + od->SetCategory("Narratives/Files"); + + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x4be0703f,0x208b5a7f)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateDirToArrayProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} + + +CKERROR CreateDirToArrayProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Dir to Array"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("Fill"); + proto->DeclareInput("Loop In"); + + proto->DeclareOutput("Reseted"); + proto->DeclareOutput("Loop Out"); + + proto->DeclareInParameter("Directory", CKPGUID_STRING,"0"); + proto->DeclareInParameter("Mask", CKPGUID_STRING,"0"); + proto->DeclareInParameter("Recursive", CKPGUID_BOOL,"0"); + + + + proto->DeclareOutParameter("entry", CKPGUID_STRING); + proto->DeclareOutParameter("counter", CKPGUID_INT); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(DirToArray); + *pproto = proto; + return CK_OK; +} + + + + +#include +std::vectorflist; + + +int counter = 0 ; + +int DirToArray(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + XString filename((CKSTRING) beh->GetInputParameterReadDataPtr(0)); + XString Mask((CKSTRING) beh->GetInputParameterReadDataPtr(1)); + + int rec; + + beh->GetInputParameterValue(2,&rec); + + + + if( beh->IsInputActive(0) ){ + beh->ActivateInput(0,FALSE); + + flist.erase(flist.begin(),flist.end()); + + CKDirectoryParser MyParser(filename.Str(),Mask.Str(),rec); + char* str = NULL; + while(str = MyParser.GetNextFile()) + flist.push_back(XString(str)); + + counter = 0; + beh->ActivateInput(1,TRUE); + + + } + + + if( beh->IsInputActive(1) ){ + beh->ActivateInput(1,FALSE); + + if ( counter < flist.size() ){ + XString entry = flist.at(counter); + CKParameterOut * pout = beh->GetOutputParameter(0); + pout->SetStringValue(entry.Str() ); + + counter++; + beh->SetOutputParameterValue(1,&counter); + beh->ActivateOutput(1); + + }else{ + + beh->SetOutputParameterValue(1,&counter); + counter = 0 ; + beh->ActivateOutput(0); + } + } + return 0; +} diff --git a/usr/Src/Behaviors/Files/GetCurrentPath.cpp b/usr/Src/Behaviors/Files/GetCurrentPath.cpp new file mode 100644 index 0000000..9291fe6 --- /dev/null +++ b/usr/Src/Behaviors/Files/GetCurrentPath.cpp @@ -0,0 +1,66 @@ +#include "CKAll.h" +CKObjectDeclaration *FillBehaviorGetCurrentPathDecl(); +CKERROR CreateGetCurrentPathProto(CKBehaviorPrototype **pproto); +int GetCurrentPath(const CKBehaviorContext& behcontext); + + +/************************************************************************/ +/* */ +/************************************************************************/ + +CKObjectDeclaration *FillBehaviorGetCurrentPathDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Get Current Path"); + od->SetDescription("Add Objects"); + od->SetCategory("Narratives/Files"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x41676403,0x5d3d10c4)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateGetCurrentPathProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateGetCurrentPathProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Get Current Path"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Create Zip File"); + proto->DeclareOutput("Zip File created"); + proto->DeclareOutParameter("Path",CKPGUID_STRING); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(GetCurrentPath); + *pproto = proto; + return CK_OK; +} + +#include + +int GetCurrentPath(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + +// GetModuleFileName(NULL,szPath,_MAX_PATH); + + //_splitpath(szPath, drive, dir, NULL, NULL ); + + //sprintf(Current.Str(),"%s%s",drive,dir); + + VxGetCurrentDirectory(szPath); + CKParameterOut *pout = beh->GetOutputParameter(0); + pout->SetStringValue(szPath); + beh->ActivateOutput(0); + + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/Files/GetLastFile.cpp b/usr/Src/Behaviors/Files/GetLastFile.cpp new file mode 100644 index 0000000..6c36bec --- /dev/null +++ b/usr/Src/Behaviors/Files/GetLastFile.cpp @@ -0,0 +1,75 @@ +#include "CKAll.h" +#include +#include +#include "Shlwapi.h" +#pragma comment (lib,"SHLWAPI.LIB") + + +CKObjectDeclaration *FillBehaviorGetLastFileNameDecl(); +CKERROR CreateGetLastFileNameProto(CKBehaviorPrototype **pproto); +int GetLastFileName(const CKBehaviorContext& behcontext); + + +/************************************************************************/ +/* */ +/************************************************************************/ + +CKObjectDeclaration *FillBehaviorGetLastFileNameDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("GetLastFileName"); + od->SetDescription("Add Objects"); + od->SetCategory("Narratives/Objects"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0xa2e4a61,0x170735ce)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateGetLastFileNameProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateGetLastFileNameProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("GetLastFileName"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Create Zip File"); + proto->DeclareOutput("Zip File created"); + + + proto->DeclareOutParameter("FilePath",CKPGUID_STRING); + proto->DeclareOutParameter("Path",CKPGUID_STRING); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(GetLastFileName); + *pproto = proto; + return CK_OK; +} + + +int GetLastFileName(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + XString Inpath (ctx->GetLastCmoLoaded()); + + + + CKParameterOut *pout = beh->GetOutputParameter(0); + pout->SetStringValue(Inpath.Str()); + + PathRemoveFileSpec(Inpath.Str()); + + + CKParameterOut *pout2 = beh->GetOutputParameter(1); + pout2->SetStringValue(Inpath.Str()); + + + + beh->ActivateOutput(0); + + +return 0; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/Files/ResolveFileName.cpp b/usr/Src/Behaviors/Files/ResolveFileName.cpp new file mode 100644 index 0000000..210da4c --- /dev/null +++ b/usr/Src/Behaviors/Files/ResolveFileName.cpp @@ -0,0 +1,66 @@ +#include "CKAll.h" +CKObjectDeclaration *FillBehaviorResolveFileNameDecl(); +CKERROR CreateResolveFileNameProto(CKBehaviorPrototype **pproto); +int ResolveFileName(const CKBehaviorContext& behcontext); + + +/************************************************************************/ +/* */ +/************************************************************************/ + +CKObjectDeclaration *FillBehaviorResolveFileNameDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("ResolveFileName"); + od->SetDescription("Add Objects"); + od->SetCategory("Narratives/Files"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x55d13c2b,0xe030cbf)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateResolveFileNameProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateResolveFileNameProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("ResolveFileName"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Create Zip File"); + proto->DeclareOutput("Zip File created"); + + proto->DeclareInParameter("FileName",CKPGUID_STRING); + proto->DeclareOutParameter("Path",CKPGUID_STRING); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(ResolveFileName); + *pproto = proto; + return CK_OK; +} + + +int ResolveFileName(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + XString Inpath((CKSTRING) beh->GetInputParameterReadDataPtr(0)); + + behcontext.Context->GetPathManager()->ResolveFileName(Inpath,BITMAP_PATH_IDX,-1); + +// Inpath =behcontext.Context->GetPathManager()->GetVirtoolsTemporaryFolder(); + + + CKParameterOut *pout = beh->GetOutputParameter(0); + pout->SetStringValue(Inpath.Str()); + + + + beh->ActivateOutput(0); + + return CKBR_OK; + +} + + diff --git a/usr/Src/Behaviors/Ftp/FTPLOGIN.cpp b/usr/Src/Behaviors/Ftp/FTPLOGIN.cpp new file mode 100644 index 0000000..c666f6c --- /dev/null +++ b/usr/Src/Behaviors/Ftp/FTPLOGIN.cpp @@ -0,0 +1,103 @@ +#include "pch.h" +#include "CKAll.h" + +#include "FTP4W.H" + + +CKObjectDeclaration *FillBehaviorFTPLoginDecl(); +CKERROR CreateFTPLoginProto(CKBehaviorPrototype **pproto); +int FTPLogin(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorFTPLoginDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("FTP Login"); + od->SetDescription(""); + od->SetCategory("Narratives/Files"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x3d100c46,0x206c6bc2)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateFTPLoginProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} + + +CKERROR CreateFTPLoginProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("FTP Login"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("Login"); + proto->DeclareInput("Logout"); + + proto->DeclareOutput("Login Exit"); + proto->DeclareOutput("Logout Exit"); + proto->DeclareOutput("Error"); + + proto->DeclareInParameter("Host", CKPGUID_STRING,"127.0.0.1"); + proto->DeclareInParameter("User", CKPGUID_STRING,"ich"); + proto->DeclareInParameter("Password", CKPGUID_STRING,"ich"); + proto->DeclareInParameter("Port", CKPGUID_INT,"21"); + + + proto->DeclareOutParameter("Error Code 0=ok", CKPGUID_INT,"0"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(FTPLogin); + *pproto = proto; + return CK_OK; +} +#define LOG_FILE "c:\\ftp4w.log" + +int FTPLogin(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + if( beh->IsInputActive(0)){ + beh->ActivateInput(0,FALSE); + + HWND win = (HWND)ctx->GetMainWindow(); + FtpInit(win); + //HFILE hLogFile = _lcreat (LOG_FILE, 0); + //FtpLogTo (hLogFile); + + + + FtpSetDefaultTimeOut (30); + FtpSetPassiveMode(TRUE); + FtpSetAsynchronousMode(); + + int Port; + beh->GetInputParameterValue(3,&Port); + + + + XString Host((CKSTRING) beh->GetInputParameterReadDataPtr(0)); + XString User((CKSTRING) beh->GetInputParameterReadDataPtr(1)); + XString Pw((CKSTRING) beh->GetInputParameterReadDataPtr(2)); + + int Login = FtpLogin(Host.Str(),User.Str(),Pw.Str(),win,0); + beh->SetOutputParameterValue(0,&Login); + + + if (Login == 0)beh->ActivateOutput(0); + else{ + beh->ActivateOutput(2); + return CKBR_OK; + } + return CKBR_ACTIVATENEXTFRAME; + } + + if( beh->IsInputActive(1)){ + beh->ActivateInput(1,FALSE); + + FtpCloseConnection(); + FtpRelease (); + beh->ActivateOutput(1); + return CKBR_OK; + } + return CKBR_ACTIVATENEXTFRAME; +} diff --git a/usr/Src/Behaviors/Ftp/GetF.cpp b/usr/Src/Behaviors/Ftp/GetF.cpp new file mode 100644 index 0000000..7eab20a --- /dev/null +++ b/usr/Src/Behaviors/Ftp/GetF.cpp @@ -0,0 +1,108 @@ +#include "CKAll.h" + + +#include "FTP4W.H" + + + +//#pragma comment(lib, "ftp4w32.lib") + + + +CKObjectDeclaration *FillBehaviorGetFileDecl(); +CKERROR CreateGetFileProto(CKBehaviorPrototype **pproto); +int GetFile(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorGetFileDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Get File"); + od->SetDescription(""); + od->SetCategory("Narratives/Files"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x2e1c1420,0x1ecd1db0)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateGetFileProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} + + +CKERROR CreateGetFileProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Get File"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("Start Download"); + + proto->DeclareOutput("Download Started"); + + proto->DeclareOutput("Finish"); + + proto->DeclareOutput("Error"); + + proto->DeclareInParameter("RemoteFile", CKPGUID_STRING); + proto->DeclareInParameter("LocalFile", CKPGUID_STRING); + + proto->DeclareOutParameter("Length in Bytes", CKPGUID_INT); + proto->DeclareOutParameter("Current Download in Bytes", CKPGUID_INT); + proto->DeclareOutParameter("Current Download in %", CKPGUID_PERCENTAGE); + proto->DeclareOutParameter("Error Code", CKPGUID_INT); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(GetFile); + *pproto = proto; + return CK_OK; +} + +int GetFile(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + int Length=0; + + // Start by In0 + if( beh->IsInputActive(0)){ + beh->ActivateInput(0,FALSE); + + + XString RemoteFile((CKSTRING) beh->GetInputParameterReadDataPtr(0)); + XString LocalFile((CKSTRING) beh->GetInputParameterReadDataPtr(1)); + + char *Type = "Type_B"; + int Get = FtpRecvFile ( RemoteFile.Str(),LocalFile.Str(),*Type, FALSE,NULL,NULL); + Length = FtpBytesToBeTransferred(); + + if ( Get !=0 ){ + beh->SetOutputParameterValue(3,&Get); + beh->ActivateOutput(2); + return CKBR_OK; + } + + beh->SetOutputParameterValue(0,&Length); + beh->ActivateOutput(0); + return CKBR_ACTIVATENEXTFRAME; + } + + + beh->GetOutputParameterValue(0,&Length); + + int down=FtpBytesTransferred(); + beh->SetOutputParameterValue(1,&down); + float progress=(float)(down*100.0f/Length); // percentage of file downloaded + progress /=100.0f; + beh->SetOutputParameterValue(2,&progress); + + + + if ( down == Length){ + + beh->ActivateOutput(1); + return CKBR_OK; + } + + return CKBR_ACTIVATENEXTFRAME; + +} diff --git a/usr/Src/Behaviors/Ftp/SendF.cpp b/usr/Src/Behaviors/Ftp/SendF.cpp new file mode 100644 index 0000000..ef850de --- /dev/null +++ b/usr/Src/Behaviors/Ftp/SendF.cpp @@ -0,0 +1,92 @@ +#include "pch.h" +#include "CKAll.h" + + +#include "FTP4W.H" + +CKObjectDeclaration *FillBehaviorSendFileDecl(); +CKERROR CreateSendFileProto(CKBehaviorPrototype **pproto); +int SendFile(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorSendFileDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Send File"); + od->SetDescription(""); + od->SetCategory("Narratives/Files"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x637664ae,0x57df7e83)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateSendFileProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} + + +CKERROR CreateSendFileProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Send File"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("Start Upload"); + + proto->DeclareOutput("Upload Started"); + + proto->DeclareOutput("Finish"); + + proto->DeclareInParameter("LocalFile", CKPGUID_STRING); + proto->DeclareInParameter("RemoteFile", CKPGUID_STRING); + + + proto->DeclareOutParameter("Legth", CKPGUID_INT); + proto->DeclareOutParameter("Current Download in Bytes", CKPGUID_INT); + proto->DeclareOutParameter("Current Download in %", CKPGUID_PERCENTAGE); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(SendFile); + *pproto = proto; + return CK_OK; +} + +int SendFile(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + int Length=0; + + // Start by In0 + if( beh->IsInputActive(0)){ + beh->ActivateInput(0,FALSE); + + XString LocalFile((CKSTRING) beh->GetInputParameterReadDataPtr(0)); + XString RemoteFile((CKSTRING) beh->GetInputParameterReadDataPtr(1)); + + + char *Type = "Type_B"; + int Send = FtpSendFile(LocalFile.Str(),RemoteFile.Str(),*Type, FALSE,NULL,NULL); + + Length = FtpBytesToBeTransferred(); + + beh->SetOutputParameterValue(0,&Length); + beh->ActivateOutput(0); + return CKBR_ACTIVATENEXTFRAME; + } + + beh->GetOutputParameterValue(0,&Length); + + int down=FtpBytesTransferred(); + beh->SetOutputParameterValue(1,&down); + float progress=(float)(down*100.0f/Length); // percentage of file downloaded + progress /=100.0f; + beh->SetOutputParameterValue(2,&progress); + + if ( down == Length){ + + beh->ActivateOutput(1); + return CKBR_OK; + } + + return CKBR_ACTIVATENEXTFRAME; + +} diff --git a/usr/Src/Behaviors/Init.cpp b/usr/Src/Behaviors/Init.cpp new file mode 100644 index 0000000..7557465 --- /dev/null +++ b/usr/Src/Behaviors/Init.cpp @@ -0,0 +1,146 @@ +#include "CKAll.h" +#include "Manager/InitMan.h" + + + +#ifdef CK_LIB +#define RegisterBehaviorDeclarations Register_TOOLS_BehaviorDeclarations +#define InitInstance _TOOLS_InitInstance +#define ExitInstance _TOOLS_ExitInstance +#define CKGetPluginInfoCount CKGet_TOOLS_PluginInfoCount +#define CKGetPluginInfo CKGet_TOOLS_PluginInfo +#define g_PluginInfo g_TOOLS_PluginInfo +#else +#define RegisterBehaviorDeclarations RegisterBehaviorDeclarations +#define InitInstance InitInstance +#define ExitInstance ExitInstance +#define CKGetPluginInfoCount CKGetPluginInfoCount +#define CKGetPluginInfo CKGetPluginInfo +#define g_PluginInfo g_PluginInfo +#endif + +CKPluginInfo g_PluginInfo; + +PLUGIN_EXPORT int CKGetPluginInfoCount(){return 2;} + +#ifdef Dev25 +#include "vslmanagersdk.h" +#endif + +#ifdef Dev3 +#include "VSLManager.h" +#endif + + + +CKERROR InitInstance(CKContext* context) +{ + + CKParameterManager* pm = context->GetParameterManager(); + InitMan* initman =new InitMan(context); + initman->RegisterVSL(); + + + return CK_OK; + +} + +CKERROR ExitInstance(CKContext* context) +{ + InitMan* initman =(InitMan*)context->GetManagerByGuid(INIT_MAN_GUID); + + delete initman; + return CK_OK; +} +#define INIT_BEH_GUID CKGUID(0x64cb5f9a,0x1aac3b37) + +PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) +{ + switch (Index) + { + case 0: + g_PluginInfo.m_Author = "mw"; + g_PluginInfo.m_Description = "tool building blocks"; + g_PluginInfo.m_Extension = ""; + g_PluginInfo.m_Type = CKPLUGIN_BEHAVIOR_DLL; + g_PluginInfo.m_Version = 0x000001; + g_PluginInfo.m_InitInstanceFct = NULL; + g_PluginInfo.m_ExitInstanceFct = NULL; + g_PluginInfo.m_GUID = INIT_BEH_GUID; + g_PluginInfo.m_Summary = "tool BB's"; + break; + + case 1: + g_PluginInfo.m_Author = "mw"; + g_PluginInfo.m_Description = "tool Manager "; + g_PluginInfo.m_Extension = ""; + g_PluginInfo.m_Type = CKPLUGIN_MANAGER_DLL; + g_PluginInfo.m_Version = 0x000001; + g_PluginInfo.m_InitInstanceFct = InitInstance; + g_PluginInfo.m_ExitInstanceFct = ExitInstance; + g_PluginInfo.m_GUID = INIT_MAN_GUID; + g_PluginInfo.m_Summary = "tool Manager"; + break; + + + } + return &g_PluginInfo; +} + + +PLUGIN_EXPORT void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg); + +void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) +{ + + + + + + RegisterBehavior(reg,FillBehaviorAddNodalLinkDecl); + + RegisterBehavior(reg,FillBehaviorDirToArrayDecl); + RegisterBehavior(reg,FillBehaviorSetNodalDifficultDecl); + RegisterBehavior(reg,FillBehaviorCopyFileBBDecl); + RegisterBehavior(reg,FillBehaviorExecBBDecl); + + + // [11/6/2004] // FTP + + /* + RegisterBehavior(reg,FillBehaviorFTPLoginDecl); + RegisterBehavior(reg,FillBehaviorGetFileDecl); + RegisterBehavior(reg,FillBehaviorSendFileDecl);* + + + // [11/6/2004] //Zip + RegisterBehavior(reg,FillBehaviorLoadUnZipLibraryDecl); + RegisterBehavior(reg,FillBehaviorLoadZipLibraryDecl); + RegisterBehavior(reg,FillBehaviorUnzipFilesDecl); + RegisterBehavior(reg,FillBehaviorZipFilesDecl); **/ + RegisterBehavior(reg,FillBehaviorSaveObjectsDecl); + + + + RegisterBehavior(reg,FillBehaviorTextureSinusDecl); + RegisterBehavior(reg,FillBehaviorNoiseDecl); + + + RegisterBehavior(reg, FillBehaviorHasFFEffectsDecl); + RegisterBehavior(reg, FillBehaviorJSetXYForceDecl); + + + RegisterBehavior(reg,FillBehaviorGetCurrentPathDecl); + + + + RegisterBehavior(reg,FillBehaviorResolveFileNameDecl); + RegisterBehavior(reg,FillBehaviorMimicDecl); + /* + + RegisterBehavior(reg,*/ +// RegisterBehavior(reg,FillBehaviorCharacterControllerDecl); +} + + + diff --git a/usr/Src/Behaviors/JoyStick/JSetXYForce.cpp b/usr/Src/Behaviors/JoyStick/JSetXYForce.cpp new file mode 100644 index 0000000..49b7562 --- /dev/null +++ b/usr/Src/Behaviors/JoyStick/JSetXYForce.cpp @@ -0,0 +1,192 @@ +/******************************************************************** + created: 2009/06/01 + created: 1:6:2009 14:15 + filename: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick\JSetXYForce.cpp + file path: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick + file base: JSetXYForce + file ext: cpp + author: Günter Baumgart + + purpose: +*********************************************************************/ + + + +#include +#include "CKAll.h" +#include "dInputShared.h" + + +static CKContext *ctx = NULL; +static bool gInitiated = false; +extern LPDIRECTINPUTEFFECT g_pEffect; +extern LPDIRECTINPUTDEVICE8 g_pFFDevice; + + +#define HAS_CONFIG + +#ifdef HAS_CONFIG + #include "gConfig.h" +#endif // BB_TOOLS + +#ifdef BB_TOOLS + + #include + #include "vtLogTools.h" + #include "vtCBBErrorHelper.h" + #include + #include + + using namespace vtTools::BehaviorTools; + +#endif + + +CKObjectDeclaration *FillBehaviorJSetXYForceDecl(); +CKERROR CreateJSetXYForceProto(CKBehaviorPrototype **); +int JSetXYForce(const CKBehaviorContext& behcontext); +CKERROR PlayFFECallBackObject(const CKBehaviorContext& behcontext); +CKObjectDeclaration *FillBehaviorJSetXYForceDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("JSetXYForce"); + od->SetDescription(""); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x6890534f,0x31c12074)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateJSetXYForceProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + od->SetCategory("Controllers/Joystick"); + return od; +} + +enum bbIO_Inputs +{ + BB_I_DO, + BB_I_RELEASE, +}; + +enum bbIO_Outputs +{ + BB_O_DONE, + BB_O_RELEASED, + BB_O_ERROR, +}; + +CKERROR CreateJSetXYForceProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = NULL; + proto = CreateCKBehaviorPrototype("JSetXYForce"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareInput("release device"); + + proto->DeclareOutput("Done"); + proto->DeclareOutput("Released"); + proto->DeclareOutput("Error"); + + + proto->DeclareInParameter("Force Vector",CKPGUID_2DVECTOR); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction( JSetXYForce ); + + proto->SetBehaviorCallbackFct(PlayFFECallBackObject); + + *pproto = proto; + return CK_OK; +} + + + + + +int JSetXYForce(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx2 = behcontext.Context; + if (!ctx) + { + ctx = ctx2; + } + + HWND mWin = (HWND )ctx->GetMainWindow(); + HRESULT hr = S_OK; + + + //init and load effect + if( beh->IsInputActive(BB_I_DO) ) + { + beh->ActivateInput(BB_I_DO,FALSE); + if (!gInitiated) + { + if (!InitDirectInput2(mWin) == S_OK) + { + beh->ActivateOutput(BB_O_ERROR); + return CKBR_OK; + }else{ + + hr = g_pFFDevice->Acquire(); + hr =g_pEffect->Start( 1, 0 ); // Start the effect + gInitiated = true; + } + } + + Vx2DVector vectorForce; + beh->GetInputParameterValue(0,&vectorForce); + + + + SetDeviceForcesXY(vectorForce.x,vectorForce.y); + beh->ActivateOutput(BB_O_DONE); + } + + + //play + + if( beh->IsInputActive(BB_I_RELEASE)) + { + beh->ActivateInput(BB_I_RELEASE,FALSE); + { + beh->ActivateOutput(BB_I_RELEASE); + FreeDirectInput2(); + return CKBR_OK; + } + } + + + /* + //stop the effect + if( beh->IsInputActive(2) ){ + beh->ActivateInput(2,FALSE); + + //g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ); + beh->ActivateOutput(2); + return CKBR_OK; + }*/ + + + return CKBR_OK; +} + + +CKERROR PlayFFECallBackObject(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) + { + case CKM_BEHAVIORDETACH: + case CKM_BEHAVIORRESET: + { + gInitiated = false; + if ( g_pFFDevice) + g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ); + FreeDirectInput2(); + } + break; + } + + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/JoyStick/dInputShared.cpp b/usr/Src/Behaviors/JoyStick/dInputShared.cpp new file mode 100644 index 0000000..d94be17 --- /dev/null +++ b/usr/Src/Behaviors/JoyStick/dInputShared.cpp @@ -0,0 +1,353 @@ +/******************************************************************** + created: 2009/06/01 + created: 1:6:2009 14:19 + filename: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick\dInputShared.cpp + file path: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick + file base: dInputShared + file ext: cpp + author: Günter Baumgart + + purpose: shared joystick functions +*********************************************************************/ + +#include "dInputShared.h" +#include "CKAll.h" + +extern CKContext *ctx=NULL; + +//----------------------------------------------------------------------------- +// Defines, constants, and global variables +//----------------------------------------------------------------------------- +struct EFFECTS_NODE +{ + LPDIRECTINPUTEFFECT pDIEffect; + DWORD dwPlayRepeatCount; + EFFECTS_NODE* pNext; +}; + +LPDIRECTINPUT8 g_pDI = NULL; +LPDIRECTINPUTDEVICE8 g_pFFDevice = NULL; +EFFECTS_NODE g_EffectsList; + + +LPDIRECTINPUTEFFECT g_pEffect = NULL; +BOOL g_bActive = TRUE; + +DWORD g_dwNumForceFeedbackAxis = 0; +INT g_nXForce; +INT g_nYForce; +DWORD g_dwLastEffectSet; // Time of the previous force feedback effect set + +//----------------------------------------------------------------------------- +// Name: EnumAxesCallback() +// Desc: Callback function for enumerating the axes on a joystick and counting +// each force feedback enabled axis +//----------------------------------------------------------------------------- +BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi, + VOID* pContext ) +{ + DWORD* pdwNumForceFeedbackAxis = ( DWORD* )pContext; + + if( ( pdidoi->dwFlags & DIDOI_FFACTUATOR ) != 0 ) + ( *pdwNumForceFeedbackAxis )++; + + return DIENUM_CONTINUE; +} + +HRESULT InitDirectInput2( HWND hDlg ) +{ + HRESULT hr; + + DIPROPDWORD dipdw; + + // Setup the g_EffectsList circular linked list + ZeroMemory( &g_EffectsList, sizeof( EFFECTS_NODE ) ); + g_EffectsList.pNext = &g_EffectsList; + + // Create a DInput object + if( FAILED( hr = DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&g_pDI, NULL ) ) ) + { + ctx->OutputToConsole("PlayFFE :: DirectInput8Create"); + return hr; + } + + // Get the first enumerated force feedback device + if( FAILED( hr = g_pDI->EnumDevices( DI8DEVCLASS_GAMECTRL, EnumFFDevicesCallback2, 0, + DIEDFL_ATTACHEDONLY | + DIEDFL_FORCEFEEDBACK ) ) ) + { + ctx->OutputToConsole("PlayFFE :: EnumDevices failed"); + return hr; + } + + + if( g_pFFDevice == NULL ) + { + + ctx->OutputToConsole("PlayFFE :: No force feedback device found."); + return -1; + } + + + // Set the data format + if( FAILED( hr = g_pFFDevice->SetDataFormat( &c_dfDIJoystick ) ) ) + return hr; + + + // Set the coop level + //hr = g_pFFDevice->SetCooperativeLevel( hDlg , DISCL_EXCLUSIVE | DISCL_FOREGROUND) ; + hr = g_pFFDevice->SetCooperativeLevel( hDlg , DISCL_EXCLUSIVE | DISCL_BACKGROUND) ; + + + + //DISCL_NONEXCLUSIVE + + // Since we will be playing force feedback effects, we should disable the + // auto-centering spring. + dipdw.diph.dwSize = sizeof( DIPROPDWORD ); + dipdw.diph.dwHeaderSize = sizeof( DIPROPHEADER ); + dipdw.diph.dwObj = 0; + dipdw.diph.dwHow = DIPH_DEVICE; + dipdw.dwData = FALSE; + + if( FAILED( hr = g_pFFDevice->SetProperty( DIPROP_AUTOCENTER, &dipdw.diph ) ) ) + return hr; + + // Enumerate and count the axes of the joystick + if( FAILED( hr = g_pFFDevice->EnumObjects( EnumAxesCallback, + ( VOID* )&g_dwNumForceFeedbackAxis, DIDFT_AXIS ) ) ) + return hr; + + + // This simple sample only supports one or two axis joysticks + if( g_dwNumForceFeedbackAxis > 2 ) + g_dwNumForceFeedbackAxis = 2; + + // This application needs only one effect: Applying raw forces. + DWORD rgdwAxes[2] = { DIJOFS_X, DIJOFS_Y }; + LONG rglDirection[2] = { 0,0 }; + DICONSTANTFORCE cf = { 0 }; + cf.lMagnitude = 0; + + + DIEFFECT eff; + ZeroMemory( &eff, sizeof( eff ) ); + eff.dwSize = sizeof( DIEFFECT ); + eff.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; + eff.dwDuration = INFINITE; + eff.dwSamplePeriod = 0; + eff.dwGain = DI_FFNOMINALMAX; + eff.dwTriggerButton = DIEB_NOTRIGGER; + eff.dwTriggerRepeatInterval = 0; + eff.cAxes = g_dwNumForceFeedbackAxis; + eff.rgdwAxes = rgdwAxes; + eff.rglDirection = rglDirection; + eff.lpEnvelope = 0; + eff.cbTypeSpecificParams = sizeof( DICONSTANTFORCE ); + eff.lpvTypeSpecificParams = &cf; + eff.dwStartDelay = 0; + + // Create the prepared effect + if( FAILED( hr = g_pFFDevice->CreateEffect( GUID_ConstantForce, + &eff, &g_pEffect, NULL ) ) ) + { + return hr; + } + + if( NULL == g_pEffect ) + return E_FAIL; + + return S_OK; +} + + + + +//----------------------------------------------------------------------------- +// Name: EnumFFDevicesCallback2() +// Desc: Get the first enumerated force feedback device +//----------------------------------------------------------------------------- +BOOL CALLBACK EnumFFDevicesCallback2( LPCDIDEVICEINSTANCE pDDI, VOID* pvRef ) +{ + if( FAILED( g_pDI->CreateDevice( pDDI->guidInstance, &g_pFFDevice, NULL ) ) ) + return DIENUM_CONTINUE; // If failed, try again + + // Stop when a device was successfully found + return DIENUM_STOP; +} + +//----------------------------------------------------------------------------- +// Name: FreeDirectInput2() +// Desc: Initialize the DirectInput variables. +//----------------------------------------------------------------------------- +HRESULT FreeDirectInput2() +{ + // Release any DirectInputEffect objects. + if( g_pFFDevice ) + { + EmptyEffectList2(); + g_pFFDevice->Unacquire(); + SAFE_RELEASE( g_pFFDevice ); + } + + // Release any DirectInput objects. + SAFE_RELEASE( g_pDI ); + + return S_OK; +} +//----------------------------------------------------------------------------- +// Name: EmptyEffectList2() +// Desc: Goes through the circular linked list and releases the effects, +// and deletes the nodes +//----------------------------------------------------------------------------- +VOID EmptyEffectList2() +{ + EFFECTS_NODE* pEffectNode = g_EffectsList.pNext; + EFFECTS_NODE* pEffectDelete; + + while ( pEffectNode != &g_EffectsList ) + { + pEffectDelete = pEffectNode; + pEffectNode = pEffectNode->pNext; + + SAFE_RELEASE( pEffectDelete->pDIEffect ); + SAFE_DELETE( pEffectDelete ); + } + + g_EffectsList.pNext = &g_EffectsList; +} +//----------------------------------------------------------------------------- +// Name: OnReadFile2() +// Desc: Reads a file contain a collection of DirectInput force feedback +// effects. It creates each of effect read in and stores it +// in the linked list, g_EffectsList. +//----------------------------------------------------------------------------- +HRESULT OnReadFile2( HWND hDlg,const char*file) +{ + HRESULT hr; + + EmptyEffectList2(); + + // Enumerate the effects in the file selected, and create them in the callback + if( FAILED( hr = g_pFFDevice->EnumEffectsInFile( file,EnumAndCreateEffectsCallback2, + NULL, DIFEF_MODIFYIFNEEDED ) ) ) + return hr; + + // If list of effects is empty, then we haven't been able to create any effects + if( g_EffectsList.pNext == &g_EffectsList ) + { + ctx->OutputToConsole("Unable to create any effects."); + + } + else + { + // We have effects so enable the 'play effects' button + + } + + return S_OK; +} + +BOOL CALLBACK EnumAndCreateEffectsCallback2(LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ) +{ + HRESULT hr; + LPDIRECTINPUTEFFECT pDIEffect = NULL; + + // Create the file effect + if( FAILED( hr = g_pFFDevice->CreateEffect( pDIFileEffect->GuidEffect, + pDIFileEffect->lpDiEffect, + &pDIEffect, NULL ) ) ) + { + ctx->OutputToConsole("Could not create force feedback effect on this device"); + return DIENUM_CONTINUE; + } + + // Create a new effect node + EFFECTS_NODE* pEffectNode = new EFFECTS_NODE; + if( NULL == pEffectNode ) + return DIENUM_STOP; + + // Fill the pEffectNode up + ZeroMemory( pEffectNode, sizeof( EFFECTS_NODE ) ); + pEffectNode->pDIEffect = pDIEffect; + pEffectNode->dwPlayRepeatCount = 1; + + // Add pEffectNode to the circular linked list, g_EffectsList + pEffectNode->pNext = g_EffectsList.pNext; + g_EffectsList.pNext = pEffectNode; + + return DIENUM_CONTINUE; +} +HRESULT OnPlayEffects2( HWND hDlg ) +{ + EFFECTS_NODE* pEffectNode = g_EffectsList.pNext; + LPDIRECTINPUTEFFECT pDIEffect = NULL; + HRESULT hr; + + // Stop all previous forces + if( FAILED( hr = g_pFFDevice->SendForceFeedbackCommand( DISFFC_STOPALL ) ) ) + return hr; + + + while ( pEffectNode != &g_EffectsList ) + { + // Play all of the effects enumerated in the file + pDIEffect = pEffectNode->pDIEffect; + + if( NULL != pDIEffect ) + { + if( FAILED( hr = pDIEffect->Start( pEffectNode->dwPlayRepeatCount, 0 ) ) ) + return hr; + } + + pEffectNode = pEffectNode->pNext; + } + + return S_OK; +} + +HRESULT SetDeviceForcesXY(float x,float y) +{ + // Modifying an effect is basically the same as creating a new one, except + // you need only specify the parameters you are modifying + LONG rglDirection[2] = { 0, 0 }; + + DICONSTANTFORCE cf; + + if( g_dwNumForceFeedbackAxis == 1 ) + { + // If only one force feedback axis, then apply only one direction and + // keep the direction at zero + cf.lMagnitude = x; + rglDirection[0] = 0; + } + else + { + // If two force feedback axis, then apply magnitude from both directions + rglDirection[0] = x; + rglDirection[1] = y; + cf.lMagnitude = ( DWORD )sqrt( x * x + y * y ); + + } + + DIEFFECT eff; + ZeroMemory( &eff, sizeof( eff ) ); + eff.dwSize = sizeof( DIEFFECT ); + eff.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; + eff.cAxes = g_dwNumForceFeedbackAxis; + eff.rglDirection = rglDirection; + eff.lpEnvelope = 0; + eff.cbTypeSpecificParams = sizeof( DICONSTANTFORCE ); + eff.lpvTypeSpecificParams = &cf; + eff.dwStartDelay = 0; + + // Now set the new parameters and start the effect immediately. + HRESULT hr = S_OK; + + hr = g_pEffect->SetParameters( &eff, DIEP_DIRECTION |DIEP_TYPESPECIFICPARAMS |DIEP_START ); + HRESULT a1 = DIERR_INVALIDPARAM; + + + + return hr; +} diff --git a/usr/Src/Behaviors/JoyStick/dInputShared.h b/usr/Src/Behaviors/JoyStick/dInputShared.h new file mode 100644 index 0000000..ffdadd6 --- /dev/null +++ b/usr/Src/Behaviors/JoyStick/dInputShared.h @@ -0,0 +1,37 @@ +/******************************************************************** + created: 2009/06/01 + created: 1:6:2009 14:19 + filename: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick\dInputShared.h + file path: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick + file base: dInputShared + file ext: h + author: Günter Baumgart + + purpose: shared functions for joystick +*********************************************************************/ +#ifndef __DINPUT_SHARED_H__ +#define __DINPUT_SHARED_H__ + +#define STRICT +#define DIRECTINPUT_VERSION 0x0800 + +#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } +#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } +#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } + +#include + +//----------------------------------------------------------------------------- +// Function-prototypes +//----------------------------------------------------------------------------- +INT_PTR CALLBACK MainDialogProc( HWND, UINT, WPARAM, LPARAM ); +BOOL CALLBACK EnumFFDevicesCallback2( LPCDIDEVICEINSTANCE pDDI, VOID* pvRef ); +BOOL CALLBACK EnumAndCreateEffectsCallback2( LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ); + +HRESULT InitDirectInput2( HWND hDlg ); +HRESULT FreeDirectInput2(); +VOID EmptyEffectList2(); +HRESULT OnReadFile2( HWND hDlg,const char*file); +HRESULT OnPlayEffects2( HWND hDlg ); +HRESULT SetDeviceForcesXY(float x,float y); +#endif \ No newline at end of file diff --git a/usr/Src/Behaviors/JoyStick/hasFFe.cpp b/usr/Src/Behaviors/JoyStick/hasFFe.cpp new file mode 100644 index 0000000..17c39c2 --- /dev/null +++ b/usr/Src/Behaviors/JoyStick/hasFFe.cpp @@ -0,0 +1,136 @@ +/******************************************************************** + created: 2009/06/01 + created: 1:6:2009 14:12 + filename: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick\hasFFe.cpp + file path: x:\ProjectRoot\vtmodsvn\tools\vtTools\Sdk\Src\Behaviors\JoyStick + file base: hasFFe + file ext: cpp + author: Günter Baumgart + + purpose: +*********************************************************************/ + +#define STRICT +#define DIRECTINPUT_VERSION 0x0800 + +#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } +#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } +#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } + +//#include +#include +#include +#include +#include +#include "dinput.h" +#include "CKAll.h" + +//---------------------------------------------------------------- +// +// globals +// +LPDIRECTINPUT8 g_pDI2 = NULL; +LPDIRECTINPUTDEVICE8 g_pFFDevice2 = NULL; + + +#define HAS_CONFIG + +#ifdef HAS_CONFIG + #include "gConfig.h" +#endif // BB_TOOLS + +#ifdef BB_TOOLS + + + #include + #include "vtLogTools.h" + #include "vtCBBErrorHelper.h" + #include + #include + using namespace vtTools::BehaviorTools; +#endif + + + +CKObjectDeclaration *FillBehaviorHasFFEffectsDecl(); +CKERROR CreateHasFFEffectsProto(CKBehaviorPrototype **); +int HasFFEffects(const CKBehaviorContext& behcontext); +CKERROR PlayFFECallBackObject2(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorHasFFEffectsDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("JHasForceFeedback"); + od->SetDescription(""); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x12641a78,0x7ca70c45)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateHasFFEffectsProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + od->SetCategory("Controllers/Joystick"); + return od; +} + + +CKERROR CreateHasFFEffectsProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = NULL; + proto = CreateCKBehaviorPrototype("JHasForceFeedback"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("yes"); + proto->DeclareOutput("no"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction( HasFFEffects ); + *pproto = proto; + return CK_OK; +} + +BOOL CALLBACK EnumFFDevicesCallback0( LPCDIDEVICEINSTANCE pDDI, VOID* pvRef ) +{ + if( FAILED( g_pDI2->CreateDevice( pDDI->guidInstance, &g_pFFDevice2, NULL ) ) ) + return DIENUM_CONTINUE; // If failed, try again + return DIENUM_STOP; +} + +HRESULT FreeDirectInput0() +{ + // Release any DirectInputEffect objects. + if( g_pFFDevice2 ) + { + + g_pFFDevice2->Unacquire(); + SAFE_RELEASE( g_pFFDevice2 ); + } + + // Release any DirectInput objects. + SAFE_RELEASE( g_pDI2 ); + + return S_OK; +} + +int HasFFEffects(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + HWND mWin = (HWND )ctx->GetMainWindow(); + + DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&g_pDI2, NULL ) ; + + // Get the first enumerated force feedback device + g_pDI2->EnumDevices( 0, EnumFFDevicesCallback0, 0, DIEDFL_ATTACHEDONLY | DIEDFL_FORCEFEEDBACK ); + + if( g_pFFDevice2 == NULL ) + beh->ActivateOutput(1); + else + beh->ActivateOutput(0); + + FreeDirectInput0(); + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/MeshAddition.cpp b/usr/Src/Behaviors/MeshAddition.cpp new file mode 100644 index 0000000..41f83ba --- /dev/null +++ b/usr/Src/Behaviors/MeshAddition.cpp @@ -0,0 +1,109 @@ +#include "ckall.h" + +CKERROR CreateMeshAddProto(CKBehaviorPrototype **pproto); +int MeshAdd(const CKBehaviorContext& context); + +extern void CleanUp(CKBehavior *beh); +extern void Load(CKBehavior *beh,CKScene *scn); + +CKObjectDeclaration *FillMeshAddDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Mesh Addition"); + od->SetDescription("Duplicates objects"); + od->SetCategory("Mesh Modifications/Multi Mesh"); + od->SetType(CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0xc73102f,0x4f8c574b)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateMeshAddProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} + + +CKERROR CreateMeshAddProto(CKBehaviorPrototype **pproto) +{ + + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Mesh Addition"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Original", CKPGUID_3DENTITY); + proto->DeclareInParameter("Additional", CKPGUID_3DENTITY); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(MeshAdd); + + + *pproto = proto; + return CK_OK; + +} +int MeshAdd(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + CK3dEntity *oe = (CK3dEntity *)beh->GetInputParameterObject(0); + CKMesh *om=oe->GetCurrentMesh(); + + CK3dEntity *ae = (CK3dEntity *)beh->GetInputParameterObject(1); + CKMesh *am=ae->GetCurrentMesh(); + + VxVector oePos; + oe->GetPosition(&oePos,NULL); + + int oVCount = om->GetVertexCount(); + int aVCount = am->GetVertexCount(); + + int oFCount = om->GetFaceCount(); + int aFCount = am->GetFaceCount(); + + + om->SetVertexCount(oVCount+aVCount); + om->SetFaceCount(oFCount+aFCount); + + + VxVector oVPos,oVNormals; + float u,v; + + + VxVector aePos,Delta; + ae->GetPosition(&aePos,NULL); + + Delta = aePos-oePos; + + for (int j = 0; j< aVCount; j++){ + + am->GetVertexPosition(j,&oVPos); + oVPos += Delta; + om->SetVertexPosition(j+oVCount,&oVPos); + + am->GetVertexNormal(j,&oVNormals); + om->SetVertexNormal(j+oVCount,&oVNormals); + + am->GetVertexTextureCoordinates(j,&u,&v,-1); + om->SetVertexTextureCoordinates(j+oVCount,u,v,-1); + } + + for ( int l=0;l< aFCount;l++){ + + int a,b,c; + VxVector FN; + am->GetFaceVertexIndex(l,a,b,c); + om->SetFaceVertexIndex(l+oFCount,a+oVCount,b+oVCount,c+oVCount); + CKMaterial *OMAT = am->GetFaceMaterial(l); + om->SetFaceMaterial(l+oFCount,OMAT); + } + + + om->BuildFaceNormals(); + beh->ActivateOutput(0); + return CKBR_OK; +} + + diff --git a/usr/Src/Behaviors/Mimic.cpp b/usr/Src/Behaviors/Mimic.cpp new file mode 100644 index 0000000..d21248f --- /dev/null +++ b/usr/Src/Behaviors/Mimic.cpp @@ -0,0 +1,189 @@ +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +// +// Mimic +// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// + +#include "CKAll.h" + + +CKObjectDeclaration *FillBehaviorMimicDecl(); +CKERROR CreateMimicProto(CKBehaviorPrototype **pproto); +int Mimic(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorMimicDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Mimic"); + od->SetDescription("Makes a 3D Entity copy the motion of another one."); + /* rem: + In: triggers the process
+ Out: is activated when the process is completed.
+
+ Object: object to copy.
+ Copy Position: TRUE means the object's position will be copied.
+ Position Speed: how fast the 3D Entity is to copy the object's position. + The higher the percentage, the faster the 3D Entity will do this.
+ Copy Orientation: TRUE means that 3D Entity will copy the object's orientation.
+ Orientation Speed: how fast the 3D Entity is to copy the object's orientation. + The higher the percentage, the faster the 3D Entity will do this.
+ Copy Scale: TRUE means that the 3D Entity will copy the object's scale.
+ Scale Speed: how fast the 3D Entity is to copy the object's orientation. + The higher the percentage, the faster the 3D Entity will do this.
+ Hierarchy: if TRUE, then this behavior will also apply to the 3D Entity's children.
+
+ Time Based: If checked, this building block will be Time and not Frame Rate + dependant. Making this building block Time dependant has the advantage that compositions will run + at the same rate on all computer configurations.
+
+ This behavior needs to be looped, if you want the object to constantly mimic the target.
+ */ + /* warning: + - If you want no attenuation during motion, you shouldn't use the 'Time Based' setting.
+ - As a time dependant looping process this building block has to be looped with a 1 frame link delay. + The reason of this is because the internally laps of time used is always equal to the duration of one global process of the building blocks.
+ This means, if you use 2 or 3 frame link delay, the process will become frame dependant.
+ Note: if you don't use any '... Speed' value (ie 100), the above remark is useless (because movement is instantaneous).
+ */ + od->SetCategory("3D Transformations/Constraint"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x1df50d81,0x53cc788f)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateMimicProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + return od; +} + + +CKERROR CreateMimicProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Mimic2"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Object", CKPGUID_3DENTITY ); + proto->DeclareInParameter("Copy Position", CKPGUID_BOOL , "TRUE"); + proto->DeclareInParameter("Position Speed", CKPGUID_PERCENTAGE, "100"); + proto->DeclareInParameter("add vec", CKPGUID_VECTOR); + + proto->DeclareInParameter("Copy Orientation", CKPGUID_BOOL , "TRUE"); + proto->DeclareInParameter("Orientation Speed", CKPGUID_PERCENTAGE, "100"); + proto->DeclareInParameter("add quat", CKPGUID_QUATERNION); + + proto->DeclareInParameter("Copy Scale", CKPGUID_BOOL , "TRUE"); + proto->DeclareInParameter("Scale Speed", CKPGUID_PERCENTAGE, "100"); + proto->DeclareInParameter("Hierarchy", CKPGUID_BOOL , "TRUE"); + + proto->DeclareSetting("Time Based", CKPGUID_BOOL, "TRUE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(Mimic); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + *pproto = proto; + return CK_OK; +} + +int Mimic(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + // Set IO states + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + + // Get the Owner Object + CK3dEntity *Ent1 = (CK3dEntity *) beh->GetTarget(); + if( !Ent1 ) return CKBR_OWNERERROR; + + // Get the Object + CK3dEntity *Ent2 = (CK3dEntity *) beh->GetInputParameterObject(0); + if(!Ent2) return CKBR_OK; + + // hierarchy + CKBOOL k = TRUE; + beh->GetInputParameterValue(7, &k); + k=!k; + + CKBOOL b; + float f = 0.0; + + ///////////////////////////////////////////////////////////////////////////////////// + // Time Based Setting Version ? + CKBOOL time_based=FALSE; + beh->GetLocalParameterValue(0, &time_based); + + // Mimic Position + beh->GetInputParameterValue(1,&b); + if(b) { + beh->GetInputParameterValue(2,&f); + if( time_based ) { + f *= behcontext.DeltaTime * 0.07f; + if (f > 1.0f) f = 1.0f; + } + + VxVector p1,p2; + Ent1->GetPosition(&p1); + Ent2->GetPosition(&p2); + VxVector addV; + beh->GetInputParameterValue(3,&addV); + + p1 +=addV; + p1 += (p2-p1) * f; + + Ent1->SetPosition(&p1,NULL,k); + + } + + // Mimic orientation + beh->GetInputParameterValue(4,&b); + if(b) { + beh->GetInputParameterValue(5,&f); + if( time_based ) { + f *= behcontext.DeltaTime * 0.07f; + if (f > 1.0f) f = 1.0f; + } + + + VxQuaternion quatA, quatB, quatC,quatD; + beh->GetInputParameterValue(6,&quatD); + + + VxVector scale1, scale2, scaleUnit(1,1,1); + Ent1->GetScale(&scale1); + + Ent1->GetQuaternion(&quatA); + Ent2->GetQuaternion(&quatB); + + quatC=Slerp(f, quatA, quatB); + + Ent1->SetQuaternion(&quatC,NULL,k); + Ent1->SetScale(&scale1); + } + + // Mimic Scale + beh->GetInputParameterValue(7,&b); + if(b) { + beh->GetInputParameterValue(8,&f); + if( time_based ) { + f *= behcontext.DeltaTime * 0.07f; + if (f > 1.0f) f = 1.0f; + } + + VxVector p1,p2; + Ent1->GetScale(&p1); + Ent2->GetScale(&p2); + + p1 += (p2-p1) * f; + + Ent1->SetScale(&p1,k); + } + + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/Mouse/NeoSetMousePos.cpp b/usr/Src/Behaviors/Mouse/NeoSetMousePos.cpp new file mode 100644 index 0000000..3044da4 --- /dev/null +++ b/usr/Src/Behaviors/Mouse/NeoSetMousePos.cpp @@ -0,0 +1,82 @@ +////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NeoSetMousePos +////////////////////////////////////////////////////////////////////////////////////////////////////////// +//#include +#include "CKAll.h" +#include "windows.h" + +CKObjectDeclaration *FillBehaviorNeoSetMousePosDecl(); +CKERROR CreateNeoSetMousePosProto(CKBehaviorPrototype **); +int NeoSetMousePos(const CKBehaviorContext& BehContext); +int NeoSetMousePosCallBack(const CKBehaviorContext& BehContext); + +CKObjectDeclaration *FillBehaviorNeoSetMousePosDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Set Mouse Pos"); + + od->SetType(CKDLL_BEHAVIORPROTOTYPE); + od->SetVersion(0x0000001); + od->SetCreationFunction(CreateNeoSetMousePosProto); + od->SetDescription("Set Mouse Position"); + od->SetCategory("Controllers/Mouse"); + od->SetGuid(CKGUID(0xa72d87d4, 0x882b89a6)); + od->SetAuthorGuid(CKGUID(0x56495254,0x4f4f4c53)); + od->SetAuthorName("Neo"); + od->SetCompatibleClassId(CKCID_BEOBJECT); + + return od; +} + +CKERROR CreateNeoSetMousePosProto(CKBehaviorPrototype** pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Set Mouse Pos"); + if (!proto) { + return CKERR_OUTOFMEMORY; + } + +//--- Inputs declaration + proto->DeclareInput("Set"); + +//--- Outputs declaration + proto->DeclareOutput("Done"); + +//--- Input Parameters declaration + proto->DeclareInParameter("X", CKPGUID_INT,"100"); + proto->DeclareInParameter("Y", CKPGUID_INT,"100"); + proto->DeclareInParameter("Keep Active", CKPGUID_BOOL, "TRUE"); +// proto->DeclareSetting("Keep Active",CKPGUID_BOOL,"TRUE"); +// proto->DeclareLocalParameter("KeepActive", CKPGUID_BOOL); + + +//---- Local Parameters Declaration + +//---- Settings Declaration + + proto->SetBehaviorCallbackFct(NeoSetMousePosCallBack, NULL); + proto->SetFunction(NeoSetMousePos); + + *pproto = proto; + return CK_OK; +} + +int NeoSetMousePos(const CKBehaviorContext& BehContext) +{ + CKBehavior* beh = BehContext.Behavior; + int x, y; + + beh->GetInputParameterValue(0,&x); + beh->GetInputParameterValue(1,&y); + SetCursorPos(x,y); + beh->ActivateOutput(0); + CKBOOL keepActive; + beh->GetInputParameterValue(2,&keepActive); + if(keepActive)return CKBR_ACTIVATENEXTFRAME; + return CKBR_OK; +} + +int NeoSetMousePosCallBack(const CKBehaviorContext& BehContext) +{ + return CKBR_OK; +} + + diff --git a/usr/Src/Behaviors/N3DGRAPH.CPP b/usr/Src/Behaviors/N3DGRAPH.CPP new file mode 100644 index 0000000..3be51e4 --- /dev/null +++ b/usr/Src/Behaviors/N3DGRAPH.CPP @@ -0,0 +1,885 @@ + +#include "CKAll.h" + +#include "N3dGraph.h" + +char* Network3dName = "Nodal Path"; + +N3DGraph::N3DGraph(CKContext *context):m_Size(0),m_AllocatedSize(10) { + m_States = new N3DState[m_AllocatedSize]; + m_Display = NULL; + m_EdgeNumber = 0; + m_Context=context; +} + +N3DGraph::~N3DGraph() { + for(int i=0;im_Next; + delete temp; + } + } + delete [] m_States; + m_States = NULL; +} + +void +N3DGraph::TestAndReallocate(int n) { + if(m_Size+n > m_AllocatedSize) { + m_AllocatedSize *= 2; + N3DState* old = m_States; + m_States = new N3DState[m_AllocatedSize]; + memcpy(m_States,old,m_Size*sizeof(N3DState)); + delete [] old; + } +} + +int +N3DGraph::GetStatesNumber() const +{ + return m_Size; +} + +int +N3DGraph::GetEdgesNumber() const +{ + return m_EdgeNumber; +} + + +N3DState* +N3DGraph::InsertState(CK3dEntity* e) +{ + if(!StateSeek(CKOBJID(e))) { + TestAndReallocate(); + m_States[m_Size].m_Edges = NULL; + m_States[m_Size].m_Data = CKOBJID(e); + m_Size++; + return m_States+(m_Size-1); + } + return NULL; +} + + +void +N3DGraph::SetDifficult(CK3dEntity *ent,float diff){ + + + int sp = SeekPosition(CKOBJID(ent)); + if(sp<0) return; + + N3DState* state = GetState(sp); + if(state) { + // first we (de)activate all the leaving edges + N3DEdge* edge; + edge = state->m_Edges; + while(edge) { + edge->m_Difficulty = diff ; + edge = edge->m_Next; + } + } + + +} + +N3DEdge* +N3DGraph::InsertEdge(CK3dEntity* s,CK3dEntity* e,float d) +{ + if(s == e) return NULL; + + int spos = SeekPosition(CKOBJID(s)); + if(spos == -1) { // the first state isn't yet in graph + InsertState(s); + spos = m_Size-1; + } + // we check if the destination state is in the graph + int epos = SeekPosition(CKOBJID(e)); + if(epos == -1) { + InsertState(e); + epos = m_Size-1; + } + + N3DEdge* edge = m_States[spos].m_Edges; + if(edge) { + while(edge->m_Next) { + // if successor is already there, we didn't do anything + if(edge->m_Successor == epos) return NULL; + edge=edge->m_Next; + } + if(edge->m_Successor == epos) return NULL; + edge->m_Next = CreateEdge(epos,d,GetDistance(GetState(spos),GetState(epos))); + return edge->m_Next; + } else { + m_States[spos].m_Edges = CreateEdge(epos,d,GetDistance(GetState(spos),GetState(epos))); + return m_States[spos].m_Edges; + } +} + +void +N3DGraph::ActivateEdge(CK3dEntity* s,CK3dEntity* e,BOOL a,BOOL dyn) +{ + N3DEdge* edge = EdgeSeek(CKOBJID(s),CKOBJID(e)); + if(edge) { + if(dyn) { + if(a) edge->m_Active |= STATEDYNAMICACTIVITY; + else edge->m_Active &= ~STATEDYNAMICACTIVITY; + } else { + if(a) { + edge->m_Active |= STATEBASICACTIVITY; + edge->m_Active |= STATEDYNAMICACTIVITY; + } else { + edge->m_Active &= ~STATEBASICACTIVITY; + edge->m_Active &= ~STATEDYNAMICACTIVITY; + } + } + } +} + +void +N3DGraph::ActivateState(CK3dEntity* s,BOOL a) +{ + int sp = SeekPosition(CKOBJID(s)); + if(sp<0) return; + + N3DState* state = GetState(sp); + if(state) { + // first we (de)activate all the leaving edges + N3DEdge* edge; + edge = state->m_Edges; + while(edge) { + if(a) edge->m_Active |= STATEDYNAMICACTIVITY; + else edge->m_Active &= ~STATEDYNAMICACTIVITY; + edge = edge->m_Next; + } + + // next we iterate all the edges to (de)activate the entering ones + for(int i=0;im_Successor == sp) { + if(a) edge->m_Active |= STATEDYNAMICACTIVITY; + else edge->m_Active &= ~STATEDYNAMICACTIVITY; + } + edge = edge->m_Next; + } + } + + } +} + +BOOL +N3DGraph::SetOccupier(CK3dEntity* s,CK3dEntity* o) +{ + N3DState* state = StateSeek(CKOBJID(s)); + if(state) { + CK_ID id = CKOBJID(o); + if(id) { // we are trying to set an occupier + if(state->m_Occupier && state->m_Occupier!=id ) // there is already an occupier : we can't set it + return FALSE; + state->m_Occupier = id; + } else { // we are trying to remove an occupation + state->m_Occupier = 0; + } + return TRUE; + } + return FALSE; +} + +CK3dEntity* +N3DGraph::GetOccupier(CK3dEntity* s) +{ + N3DState* state = StateSeek(CKOBJID(s)); + if(state) { + return (CK3dEntity*)m_Context->GetObject(state->m_Occupier); + } + + return NULL; +} + +BOOL +N3DGraph::IsEdgeActive(CK3dEntity* s,CK3dEntity* e) +{ + N3DEdge* edge = EdgeSeek(CKOBJID(s),CKOBJID(e)); + if(edge) { + return (edge->m_Active&STATEDYNAMICACTIVITY); + } else return false; +} + +void +N3DGraph::ResetActivity() +{ + N3DEdge* edge; + for(int i=0;im_Active&STATEBASICACTIVITY) edge->m_Active |= STATEDYNAMICACTIVITY; + else edge->m_Active &= ~STATEDYNAMICACTIVITY; + edge = edge->m_Next; + } + } + +} + +void +N3DGraph::DeleteState(CK_ID e) +{ + int ni = SeekPosition(e); + if(ni<0) return; + // we now destroy all the edges leaving the destroyed node + N3DEdge* edge; + N3DEdge* backedge; + edge = m_States[ni].m_Edges; + while(edge) { + backedge = edge; + edge = edge->m_Next; + delete backedge; + m_EdgeNumber--; + } + + memmove(m_States+ni,m_States+ni+1,sizeof(N3DState)*(m_Size-ni-1)); + int* trans = new int[m_Size]; + int i; + for (i=0;im_Successor = trans[edge->m_Successor]; + if(edge->m_Successor == -1) { + if(backedge) { + N3DEdge* temp = backedge->m_Next; + backedge->m_Next = edge->m_Next; + edge=edge->m_Next; + delete temp; + m_EdgeNumber--; + } else { + N3DEdge* temp = edge; + m_States[i].m_Edges = edge->m_Next; + edge = edge->m_Next; + delete temp; + m_EdgeNumber--; + } + } else { + backedge = edge; + edge=edge->m_Next; + } + } + } + delete [] trans; +} + +void +N3DGraph::DeleteEdge(CK3dEntity* s,CK3dEntity* e) +{ + int si = SeekPosition(CKOBJID(s)); + int ei = SeekPosition(CKOBJID(e)); + + N3DEdge* edge; + N3DEdge* backedge; + edge=m_States[si].m_Edges; + backedge = NULL; + while(edge) { + if(edge->m_Successor == ei) { + if(backedge) { + N3DEdge* temp = backedge->m_Next; + backedge->m_Next = edge->m_Next; + edge=edge->m_Next; + delete temp; + m_EdgeNumber--; + } else { + N3DEdge* temp = edge; + m_States[si].m_Edges = edge->m_Next; + edge = edge->m_Next; + delete temp; + m_EdgeNumber--; + } + } else { + backedge = edge; + edge=edge->m_Next; + } + } +} + +N3DEdge* +N3DGraph::EdgeSeek(CK_ID s,CK_ID e) +{ + int si = SeekPosition(s); + int ei = SeekPosition(e); + + if(si < 0 || ei < 0) + return NULL; + + N3DEdge* edge; + edge=m_States[si].m_Edges; + while(edge) { + if(edge->m_Successor == ei) { + return edge; + } else { + edge=edge->m_Next; + } + } + return NULL; +} + +N3DState* +N3DGraph::StateSeek(CK_ID s) +{ + for(int i=0;im_Active = STATEBASICACTIVITY|STATEDYNAMICACTIVITY; + edge->m_Next = NULL; + edge->m_Successor = e; + edge->m_Difficulty = d; + return edge; +} + +N3DEdge* +N3DGraph::GetSuccessorsList(int i) +{ + return m_States[i].m_Edges; +} + +int +N3DGraph::SeekPosition(CK_ID e) const +{ + for(int i=0;i nodelist; +typedef XListIt nodelistit; + +CK3dEntity* +N3DGraph::FindPath(CK3dEntity* start,CK3dEntity* goal,CKGroup* path,BOOL basic,BOOL occupation) +{ + DWORD activity; + if(basic) activity = STATEBASICACTIVITY; + else activity = STATEDYNAMICACTIVITY; + + nodelist open; + VxVector a,b,c; + + N3DState* startnode = StateSeek(CKOBJID(start)); + if(!startnode) return NULL; + N3DState* goalnode = StateSeek(CKOBJID(goal)); + if(!goalnode) return NULL; + + startnode->m_AStar.g = 0; + startnode->m_AStar.h = GetDistance(startnode,goalnode); + startnode->m_AStar.f = startnode->m_AStar.g + startnode->m_AStar.h; + startnode->m_AStar.parent = NULL; + + PushOnOpen(open,startnode); + while (open.Size()) { + nodelistit first = open.Begin(); + N3DState* n = *first; + open.Remove(first); + n->m_Flag &= ~LISTOPEN; + + if(n == goalnode) { + CK3dEntity* nodetogo = NULL; + if(path) { // we construct an entire path + // parcourir n en remontant les parent et ajouter les m_Data au path + while(n->m_AStar.parent && (n!=n->m_AStar.parent)) { + path->AddObjectFront((CKBeObject*)m_Context->GetObject(n->m_Data)); + n = n->m_AStar.parent; + } + nodetogo = (CK3dEntity*)path->GetObject(0); + path->AddObjectFront((CKBeObject*)m_Context->GetObject(n->m_Data)); + } else { + // parcourir n en remontant les parent et ajouter les m_Data au path + CK_ID idtogo=0; + while(n->m_AStar.parent && (n!=n->m_AStar.parent)) { + idtogo = n->m_Data; + n = n->m_AStar.parent; + } + nodetogo = (CK3dEntity*)m_Context->GetObject(idtogo); + } + + // now we must clear the flags + for(int i=0;im_Edges; + N3DState* n_; + float newg; + while(edge) { + if(edge->m_Active&activity) { + n_ = m_States+edge->m_Successor; + if(!occupation || !n_->m_Occupier) { + // newg = n->m_AStar.g + GetDistance(n,n_); + newg = n->m_AStar.g + edge->m_Difficulty*edge->m_Distance; + if(n_->m_Flag) { + if(n_->m_AStar.g <= newg) { + edge = edge->m_Next; + continue; + } + } + n_->m_AStar.parent = n; + n_->m_AStar.g = newg; + n_->m_AStar.h = GetDistance(n_,goalnode); + n_->m_AStar.f = n_->m_AStar.g + n_->m_AStar.h; + // remove n' if present in closed + n_->m_Flag &= ~LISTCLOSE; + // add n_ in open if it is not yet in it + if(!(n_->m_Flag&LISTOPEN)) { + PushOnOpen(open,n_); + } + } + } + // get the next successor + edge = edge->m_Next; + } + // closed->InsertRear(n); + n->m_Flag |= LISTCLOSE; + } + + // now we must clear the flags + for(int i=0;im_Flag |= LISTOPEN; + nodelistit first = open.Begin(); + nodelistit last = open.End(); + + while(first != last) { + if(n->m_AStar.f < (*first)->m_AStar.f) { + open.Insert(first,n); + return; + } + first++; + } + + open.Insert(first,n); +} + +float +N3DGraph::GetDistance(N3DState* n1,N3DState* n2) +{ + return Magnitude(n1->m_Position-n2->m_Position); +} + +CK3dEntity* +N3DGraph::GetSafeEntity(N3DState* s) +{ + CK3dEntity *ent = (CK3dEntity*)m_Context->GetObject(s->m_Data); + if(!ent) { + DeleteState(s->m_Data); + } + return ent; +} + + +void +N3DGraph::CreateFromChunk(CKStateChunk* chunk) +{ + chunk->StartRead(); + if(!chunk->SeekIdentifier(N3DGRAPHSTART_IDENTIFIER)) return; + + int version = chunk->ReadInt(); + if((version != N3DGRAPH_VERSION1)&&(version != N3DGRAPH_VERSION2)) return; + + m_Size = chunk->ReadInt(); + delete[] m_States; + if(m_Size) { + m_States = new N3DState[m_Size]; + m_AllocatedSize = m_Size; + } else { // size = 0 + m_States = new N3DState[1]; + m_AllocatedSize = 1; + } + + for(int i=0;iReadObjectID(); + + if(version == N3DGRAPH_VERSION2) { + m_States[i].m_Occupier = chunk->ReadObjectID(); + } else m_States[i].m_Occupier = 0; + + // edges number + int size = chunk->ReadInt(); + + N3DEdge* edge; + N3DEdge* oldedge = NULL; + N3DEdge* firstedge = NULL; + for(int j=0;jm_Next = edge; + oldedge = edge; + } + edge->m_Active = chunk->ReadInt(); + edge->m_Difficulty= chunk->ReadFloat(); + edge->m_Successor = chunk->ReadInt(); + } + m_States[i].m_Edges = firstedge; + } + + // We clean everything + Clean(); + // we calculate the distance + UpdateDistance(); +} + +void N3DGraph::Clean() +{ + // we check if the nodes have themselves as successors = not permitted + int i; + for(i=0;im_Successor == i) { // Self edge : achtung + if(backedge) { + N3DEdge* temp = backedge->m_Next; + backedge->m_Next = edge->m_Next; + edge=edge->m_Next; + delete temp; + m_EdgeNumber--; + } else { + N3DEdge* temp = edge; + m_States[i].m_Edges = edge->m_Next; + edge = edge->m_Next; + delete temp; + m_EdgeNumber--; + } + } else { + backedge = edge; + edge=edge->m_Next; + } + } + } +} + +void +N3DGraph::SaveToChunk(CKStateChunk* chunk) +{ + Clean(); + + chunk->StartWrite(); + // start identifier + chunk->WriteIdentifier(N3DGRAPHSTART_IDENTIFIER); + // version + chunk->WriteInt(N3DGRAPH_VERSION2); + // size + chunk->WriteInt(m_Size); + // state size + int i; + for(i=0;iWriteObject(m_Context->GetObject(m_States[i].m_Data)); + chunk->WriteObject(m_Context->GetObject(m_States[i].m_Occupier)); + int count=0; + N3DEdge* edge = m_States[i].m_Edges; + while(edge) { + edge=edge->m_Next; + count++; + } + + chunk->WriteInt(count); + edge = m_States[i].m_Edges; + while(edge) { + chunk->WriteInt(edge->m_Active); + chunk->WriteFloat(edge->m_Difficulty); + chunk->WriteInt(edge->m_Successor); + edge = edge->m_Next; + } + } + // end identifier + chunk->CloseChunk(); +} + +void +N3DGraph::UpdateDistance() +{ + int i; + for(i=0;iGetPosition(&a); + m_States[i].m_Position = a; + } + for(i=0;im_Distance = GetDistance(GetState(i),GetState(edge->m_Successor)); + edge=edge->m_Next; + } + } + +} + + +void GraphRender(CKRenderContext* rc, void *arg) +{ + CKContext* m_Context=rc->GetCKContext(); + VxDrawPrimitiveData* data = rc->GetDrawPrimitiveStructure(CKRST_DP_TR_CL_VC,3); + CKWORD* indices = rc->GetDrawPrimitiveIndices(3); + VxVector4* positions = (VxVector4*)data->Positions.Ptr; + DWORD* colors = (DWORD*)data->Colors.Ptr; + + VxVector pos; + VxVector nodepos,nodepos2; + VxVector4 hompos; + + indices[0] = 0; + indices[1] = 1; + indices[2] = 2; + + VxVector v0(0,3,0); + VxVector v1(3,-3,0); + VxVector v2(-3,-3,0); + + int width = rc->GetWidth(); + int height= rc->GetHeight(); + + colors[0] = RGBAFTOCOLOR(1.0f,1.0f,1.0f,1.0f); + + VxRect ScreenSize; + rc->GetViewRect(ScreenSize); + float WidthOn2=ScreenSize.GetWidth()*0.5f; + float HeightOn2=ScreenSize.GetHeight()*0.5f; + float DevX=ScreenSize.left+WidthOn2; + float DevY=ScreenSize.top+HeightOn2; + + v0.x *=0.5f / WidthOn2; + v1.x *=0.5f / WidthOn2; + v2.x *=0.5f / WidthOn2; + + v0.y *=0.5f / HeightOn2; + v1.y *=0.5f / HeightOn2; + v2.y *=0.5f / HeightOn2; + + + VxMatrix View = rc->GetViewTransformationMatrix(); + VxMatrix Projection = rc->GetProjectionTransformationMatrix(); +// A custom projection matrix to render homogenous coordinates + rc->SetWorldTransformationMatrix(VxMatrix::Identity()); + rc->SetViewTransformationMatrix(VxMatrix::Identity()); + + + + + N3DGraph* graph = (N3DGraph*)arg; + if(!graph) return; + N3DDisplayStructure* display = graph->GetDisplay(); + + XVoidArray* extents = graph->GetExtentsList(); + if(extents) + { + for (void** ptr=extents->Begin();ptr!=extents->End();++ptr) + delete (N3DExtent*)*ptr; + extents->Clear(); + } + + N3DEdge* edge; + N3DEdge* edgeend; + N3DState* start; + N3DState* end; + CK3dEntity* startent; + CK3dEntity* endent; + int i; + rc->SetTexture(NULL); + rc->SetState(VXRENDERSTATE_ALPHATESTENABLE,FALSE); + rc->SetState(VXRENDERSTATE_ZENABLE,TRUE); + rc->SetState(VXRENDERSTATE_CULLMODE,VXCULL_NONE); + rc->SetState(VXRENDERSTATE_ZWRITEENABLE,FALSE); + rc->SetState(VXRENDERSTATE_ALPHABLENDENABLE,TRUE); + rc->SetState(VXRENDERSTATE_SRCBLEND,VXBLEND_SRCALPHA); + rc->SetState(VXRENDERSTATE_DESTBLEND,VXBLEND_INVSRCALPHA); + + + for(i=0;iGetStatesNumber();i++) { + start = graph->GetState(i); + edge = start->m_Edges; + startent = graph->GetSafeEntity(start); + if(!startent) { + continue; + } + + startent->GetPosition(&pos); + + // Transform Pos to Node_Pos & Hom_pos (ClipFlags is 0 if the vertex is inside the view frustrum) + Vx3DMultiplyMatrixVector(&nodepos,View,&pos); + Vx3DMultiplyMatrixVector4(&hompos,Projection,&nodepos); + BOOL Clipped = FALSE; + if ((hompos.x<-hompos.w) || (hompos.x>hompos.w) || + (hompos.y<-hompos.w) || (hompos.y>hompos.w) || + (hompos.z<0) || (hompos.z>hompos.w)) { + Clipped = TRUE; + } + + // First we draw the node + data->VertexCount=3; + if( !Clipped) { // is the node in viewport + // we can then add it to the Node Extents list + if(extents) { + N3DExtent* ext = new N3DExtent; + VxVector4 screenpos = hompos; + screenpos.w = 1.0f/screenpos.w; + screenpos.x = (screenpos.x*screenpos.w*WidthOn2)+DevX; + screenpos.y = -(screenpos.y*screenpos.w*HeightOn2)+DevY; + + ext->m_Node = start->m_Data; + ext->m_Rect.left = (long)screenpos.x - 6; + ext->m_Rect.right= (long)screenpos.x + 6; + ext->m_Rect.top = (long)screenpos.y - 6; + ext->m_Rect.bottom = (long)screenpos.y + 6; + extents->PushBack((void *)ext); + } + + if(display && ((start->m_Data == display->m_Node)||(start->m_Data == display->m_EndNode))) { // this node is the selected one or the ending one + positions[0] = nodepos + 2 * v0 * nodepos.z; + positions[1] = nodepos + 2 * v1 * nodepos.z; + positions[2] = nodepos + 2 * v2 * nodepos.z; + colors[0] = colors[1] = colors[2] = RGBAFTOCOLOR(1.0f ,0,1.0f,0.6f); + } else { + positions[0] = nodepos + v0 * nodepos.z; + positions[1] = nodepos + v1 * nodepos.z; + positions[2] = nodepos + v2 * nodepos.z; + if(start->m_Occupier) { + colors[0] = colors[1] = colors[2] = RGBAFTOCOLOR(1.0f,0.0f,0.0f,0.6f); + } else { + colors[0] = colors[1] = colors[2] = RGBAFTOCOLOR(0.3f,0.3f,1.0f,0.6f); + } + } + // we actually draw it + rc->DrawPrimitive(VX_TRIANGLELIST,indices,3,data); + } + + + // Next we draw the edges + data->VertexCount=2; + while(edge) { + BOOL MustDraw = TRUE; + end = graph->GetState(edge->m_Successor); + edgeend = end->m_Edges; + + if(edge->m_Active&STATEDYNAMICACTIVITY) { + colors[0]=RGBAFTOCOLOR(0,1.0f,0,0.6f); + } else { + colors[0]=RGBAFTOCOLOR(1.0f,0,0,0.6f); + } + colors[1]=RGBAFTOCOLOR(0,0,1.0f,0.6f); + while(edgeend) { + if(edgeend->m_Successor == i) { + if(i > edge->m_Successor) MustDraw = FALSE; + else { + if(edge->m_Active&STATEDYNAMICACTIVITY) { + colors[0]=RGBAFTOCOLOR(0,1.0f,0.0f,0.6f); + } else { + colors[0]=RGBAFTOCOLOR(1.0f,0,0,0.6f); + } + if(edgeend->m_Active&STATEDYNAMICACTIVITY) { + colors[1]=RGBAFTOCOLOR(0,1.0f,0,0.6f); + } else { + colors[1]=RGBAFTOCOLOR(1.0f,0,0,0.6f); + } + } + break; + } + edgeend = edgeend->m_Next; + } + if(MustDraw) { + endent = graph->GetSafeEntity(end); + if(!endent) return; + endent->GetPosition(&pos); + Vx3DMultiplyMatrixVector(&nodepos2,View,&pos); + positions[0] = nodepos; + positions[1] = nodepos2; + rc->DrawPrimitive(VX_LINELIST,indices,2,data); + } + + edge = edge->m_Next; + } + } + + // We now draw the path selected + data->VertexCount=3; + CKGroup* group = graph->GetPath(); + if(group) { + int count = group->GetObjectCount(); + for(i=1;iGetObject(i-1); + endent = (CK3dEntity*)group->GetObject(i); + + startent->GetPosition(&pos); + Vx3DMultiplyMatrixVector(&nodepos,View,&pos); + endent->GetPosition(&pos); + Vx3DMultiplyMatrixVector(&nodepos2,View,&pos); + positions[2] = nodepos2; + + VxVector d = Normalize(nodepos2 - nodepos); + d.x *= nodepos.z * 0.5f / WidthOn2; + d.y *= nodepos.z * 0.5f / HeightOn2; + VxVector n(-d.y*3.0f ,d.x*3.0f,0); + positions[0] = nodepos + n; + positions[1] = nodepos - n; + + colors[0] = colors[1] = colors[2] = RGBAFTOCOLOR(1.0f,0.0f,1.0f,0.6f); + // we actually draw it + rc->DrawPrimitive(VX_TRIANGLELIST,indices,3,data); + } + } + + rc->SetViewTransformationMatrix(View); + +} diff --git a/usr/Src/Behaviors/N3DGRAPH.H b/usr/Src/Behaviors/N3DGRAPH.H new file mode 100644 index 0000000..b0ad001 --- /dev/null +++ b/usr/Src/Behaviors/N3DGRAPH.H @@ -0,0 +1,196 @@ + +#ifndef N3DGRAPH_H +#define N3DGRAPH_H + +#include "CKALL.h" + +#include +#include + +#pragma warning (disable : 4786) + +#include + +#define N3DGRAPHSTART_IDENTIFIER 2000666 +#define N3DGRAPH_VERSION1 1 +#define N3DGRAPH_VERSION2 2 + +#define STATEBASICACTIVITY 1 +#define STATEDYNAMICACTIVITY 2 + +#define LISTNONE 0 +#define LISTOPEN 1 +#define LISTCLOSE 2 + +struct N3DEdge; +struct N3DState; + +struct N3DAStar { + N3DAStar():g(0.0f),h(0.0f),f(0.0f),parent(NULL) {;} + // cheapest cost of arriving to node n + float g; + // heuristic estimate of the cost to the goal + float h; + // cost of node n + float f; + // index of the parent state + N3DState* parent; +}; + +struct N3DState { + N3DState():m_Edges(NULL),m_Data(0),m_Occupier(0),m_Flag(0){}; + // list of transitions + N3DEdge* m_Edges; + // Pointer on Associated Entity + CK_ID m_Data; + // Pointer on Associated Entity + CK_ID m_Occupier; + // AStar structure + N3DAStar m_AStar; + // List flag : LISTOPEN, LISTCLOSE or LISTNONE + DWORD m_Flag; + // Node Position + VxVector m_Position; +}; + +struct N3DExtent { + // Node ID + CK_ID m_Node; + // Node Extent + CKRECT m_Rect; +}; + +struct N3DEdge { + N3DEdge():m_Successor(-1),m_Active(TRUE),m_Difficulty(0),m_Next(NULL) {}; + // state successor + int m_Successor; + // activity + int m_Active; + // terrain difficulty + float m_Distance; + // terrain difficulty + float m_Difficulty; + // Next Edge + N3DEdge* m_Next; +}; + +struct N3DDisplayStructure { + N3DDisplayStructure(CKContext* context):m_Node(0),m_EndNode(0) { + + m_Group = (CKGroup *)context->CreateObject(CKCID_GROUP,"Graph Path"); + } + ~N3DDisplayStructure() { + for (void** ptr=m_NodeExtents.Begin();ptr!=m_NodeExtents.End();ptr++) + delete (N3DExtent*)*ptr; + + CKDestroyObject(m_Group); + } + // Nodes extents + XVoidArray m_NodeExtents; + // group of nodes to go + CKGroup* m_Group; + // node selected + CK_ID m_Node; + // end node for the link selected + CK_ID m_EndNode; +}; + +class N3DGraph +{ +public: + // Constructor + N3DGraph(CKContext* context); + ~N3DGraph(); + + // Cleanification method + void Clean(); + + void SetDifficult(CK3dEntity *ent, float diff); + + // Test Method + int GraphEmpty() const; + + // Data Access Methods + int GetStatesNumber() const; + N3DState* GetState(int i); + int GetEdgesNumber() const; + CK3dEntity* GetSafeEntity(N3DState* s); +// int GetWeight(const CK3dEntity& v1, const CK3dEntity& v2); + + // Find the State Index by the associated data + int SeekPosition(CK_ID e) const; + int SeekPosition(N3DState* e) const; + // Get the successors of State i + N3DEdge* GetSuccessorsList(int i); + + // Graph Modification + // insertion + N3DState* InsertState(CK3dEntity* e); + N3DEdge* InsertEdge(CK3dEntity* s,CK3dEntity* e,float d); + + // Activity + void ActivateEdge(CK3dEntity* s,CK3dEntity* e,BOOL a,BOOL dyn=TRUE); + void ActivateState(CK3dEntity* s,BOOL a); + void ResetActivity(); + BOOL IsEdgeActive(CK3dEntity* s,CK3dEntity* e); + + // Occupation + BOOL SetOccupier(CK3dEntity* s,CK3dEntity* o); + CK3dEntity* GetOccupier(CK3dEntity* s); + + // deletion + void DeleteState(CK_ID e); + void DeleteEdge(CK3dEntity* s,CK3dEntity* e); + + void CreateFromChunk(CKStateChunk*); + void SaveToChunk(CKStateChunk*); + + // Path finding + CK3dEntity* FindPath(CK3dEntity* start,CK3dEntity* goal,CKGroup* path,BOOL basic=FALSE,BOOL occupation=FALSE); + + // Distance update + void UpdateDistance(); + + // Author highlight display + void StartDisplay() {if(m_Display) delete m_Display;m_Display = new N3DDisplayStructure(m_Context);} + void StopDisplay() {delete m_Display;m_Display=NULL;} + N3DDisplayStructure* GetDisplay() {return m_Display;} + CKGroup* GetPath() {if(m_Display) return m_Display->m_Group;else return NULL;} + XVoidArray* GetExtentsList() {if(m_Display) return &m_Display->m_NodeExtents;else return NULL;} + +private: + // methods + void TestAndReallocate(int i=1); + // insertion in a queue + void PushOnOpen(XList& open,N3DState* n); + // return en edge pointer, NULL if not found + N3DEdge* EdgeSeek(CK_ID s,CK_ID e); + // same thing with the indice of the start node + // N3DEdge* EdgeSeek(int s,CK_ID e); + // Create a State + N3DEdge* CreateEdge(int e,float d,float dist); + // Find the node Containing the Entity e + N3DState* StateSeek(CK_ID e); + // retreive the distance between 2 nodes + float GetDistance(N3DState* n1,N3DState* n2); + + // members + + // list of vertices + N3DState* m_States; + // graph size + int m_Size; + // edge number; + int m_EdgeNumber; + // Graph allocated size + int m_AllocatedSize; + // Display structure (for selected items highlighting) + N3DDisplayStructure* m_Display; + CKContext* m_Context; +}; + +extern char* Network3dName; + +void GraphRender(CKRenderContext* ctx,void *arg); + +#endif \ No newline at end of file diff --git a/usr/Src/Behaviors/SaveObject.cpp b/usr/Src/Behaviors/SaveObject.cpp new file mode 100644 index 0000000..e1f4fd4 --- /dev/null +++ b/usr/Src/Behaviors/SaveObject.cpp @@ -0,0 +1,65 @@ +#include "CKAll.h" + +CKObjectDeclaration *FillBehaviorSaveObjectsDecl(); +CKERROR CreateSaveObjectsProto(CKBehaviorPrototype **pproto); +int SaveObjects(const CKBehaviorContext& behcontext); + + +CKERROR ZipCallBack(const CKBehaviorContext& behcontext); +CKObjectDeclaration *FillBehaviorSaveObjectsDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Save Objects"); + od->SetDescription(""); + od->SetCategory("Narratives/Files"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x6f12495d,0x1aff17f4)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateSaveObjectsProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} + + + +CKERROR CreateSaveObjectsProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Save Objects"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("Save"); + + proto->DeclareOutput("Saved"); + proto->DeclareInParameter("Filename", CKPGUID_STRING); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + + proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_VARIABLEPARAMETERINPUTS)); + proto->SetFunction(SaveObjects); + *pproto = proto; + return CK_OK; +} +int SaveObjects(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + + XString filename((CKSTRING) beh->GetInputParameterReadDataPtr(0)); + + CKBeObject *beo; + CKObjectArray* oa = CreateCKObjectArray(); + for (int i = 1 ;iGetInputParameterCount();i++) + { + beo = (CKBeObject *)beh->GetInputParameterObject(i); + oa->InsertAt(beo->GetID()); + } + + ctx->Save(filename.Str(),oa,0xFFFFFFFF,NULL); + + beh->ActivateOutput(0); + return CKBR_OK; + + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/SetNodalDiff.cpp b/usr/Src/Behaviors/SetNodalDiff.cpp new file mode 100644 index 0000000..c50263e --- /dev/null +++ b/usr/Src/Behaviors/SetNodalDiff.cpp @@ -0,0 +1,78 @@ +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +// +// SetNodalDifficult +// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +#include "CKAll.h" +#include "N3dGraph.h" + +CKObjectDeclaration *FillBehaviorSetNodalDifficultDecl(); +CKERROR CreateSetNodalDifficultProto(CKBehaviorPrototype **); +int SetNodalDifficult(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorSetNodalDifficultDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("SetNodalDifficult"); + od->SetDescription(""); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x77a61036,0x47496bde)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateSetNodalDifficultProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + od->SetCategory("3D Transformations/Nodal Path"); + return od; +} + + +CKERROR CreateSetNodalDifficultProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = NULL; + proto = CreateCKBehaviorPrototype("SetNodalDifficult"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Nodal Path",CKPGUID_GROUP); + proto->DeclareInParameter("Node",CKPGUID_3DENTITY); + proto->DeclareInParameter("Difficult",CKPGUID_FLOAT); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction( SetNodalDifficult ); + + *pproto = proto; + return CK_OK; + +} + + +int SetNodalDifficult(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + CKAttributeManager* attman = ctx->GetAttributeManager(); + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + + CKGroup* group = (CKGroup*)beh->GetInputParameterObject(0); + CKParameterOut* param = group->GetAttributeParameter(attman->GetAttributeTypeByName(Network3dName)); + if(!param) throw "Given Group isn't a Network"; + N3DGraph* graph; + param->GetValue(&graph); + + CK3dEntity* s = (CK3dEntity*)beh->GetInputParameterObject(1); + + float b; + beh->GetInputParameterValue(2,&b); + + graph->SetDifficult(s,b); + beh->ActivateOutput(0); + + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/WebPackRegister.cpp b/usr/Src/Behaviors/WebPackRegister.cpp new file mode 100644 index 0000000..1d277c0 --- /dev/null +++ b/usr/Src/Behaviors/WebPackRegister.cpp @@ -0,0 +1,74 @@ +#include "StdAfx.h" +#include "CKAll.h" + + + + + + +#ifdef WebPack + + + + + + +#define CAMERA_BEHAVIOR CKGUID(0x12d94eba,0x47057415) +#define CKPGUID_PROJECTIONTYPE CKDEFINEGUID(0x1ee22148, 0x602c1ca1) +#define CKPGUID_MOUSEBUTTON CKGUID(0x1ff24d5a,0x122f2c1f) + +CKERROR InitInstanceCamera(CKContext* context) +{ + + CKParameterManager* pm = context->GetParameterManager(); + pm->RegisterNewEnum( CKPGUID_PROJECTIONTYPE,"Projection Mode","Perspective=1,Orthographic=2" ); + // Mouse Camera Orbit + pm->RegisterNewEnum(CKPGUID_MOUSEBUTTON,"Mouse Button","Left=0,Middle=2,Right=1" ); + + return CK_OK; + +} + +CKERROR ExitInstanceCamera(CKContext* context) +{ + CKParameterManager* pm = context->GetParameterManager(); + pm->UnRegisterParameterType(CKPGUID_PROJECTIONTYPE); + pm->UnRegisterParameterType(CKPGUID_MOUSEBUTTON); + return CK_OK; + +} + + + +int RegisterCameraBeh(XObjectDeclarationArray *reg) +{ + + // Cameras/Basic + RegisterBehavior(reg, FillBehaviorDollyDecl); + RegisterBehavior(reg, FillBehaviorSetOrthographicZoomDecl); + RegisterBehavior(reg, FillBehaviorSetCameraTargetDecl); + RegisterBehavior(reg, FillBehaviorSetClippingDecl); + RegisterBehavior(reg, FillBehaviorSetFOVDecl); + RegisterBehavior(reg, FillBehaviorSetProjectionDecl); + RegisterBehavior(reg, FillBehaviorSetZoomDecl); + + // Cameras/FX + RegisterBehavior(reg, FillBehaviorCameraColorFilterDecl); + RegisterBehavior(reg, FillBehaviorVertigoDecl); + + // Cameras/Montage + RegisterBehavior(reg, FillBehaviorGetCurrentCameraDecl); + RegisterBehavior(reg, FillBehaviorSetAsActiveCameraDecl); + + // Cameras/Movement + RegisterBehavior(reg, FillBehaviorOrbitDecl); + RegisterBehavior(reg, FillBehaviorKeyboardCameraOrbitDecl); + RegisterBehavior(reg, FillBehaviorMouseCameraOrbitDecl); + RegisterBehavior(reg, FillBehaviorJoystickCameraOrbitDecl); + RegisterBehavior(reg, FillBehaviorGenericCameraOrbitDecl); + + + return 0; +} + +#endif \ No newline at end of file diff --git a/usr/Src/Behaviors/exec.cpp b/usr/Src/Behaviors/exec.cpp new file mode 100644 index 0000000..aec1c06 --- /dev/null +++ b/usr/Src/Behaviors/exec.cpp @@ -0,0 +1,111 @@ +#include "CKAll.h" + +CKObjectDeclaration *FillBehaviorExecBBDecl(); +CKERROR CreateExecBBProto(CKBehaviorPrototype **pproto); +int ExecBB(const CKBehaviorContext& behcontext); + + +CKERROR ZipCallBack(const CKBehaviorContext& behcontext); +CKObjectDeclaration *FillBehaviorExecBBDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("ExecBB"); + od->SetDescription(""); + od->SetCategory("Narratives/Files"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x6b62506d,0x3dd1067)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateExecBBProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} + + + +CKERROR CreateExecBBProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("ExecBB"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("Execute"); + + proto->DeclareOutput("Ok"); + proto->DeclareOutput("Failed"); + + proto->DeclareInParameter("Filename", CKPGUID_STRING); + proto->DeclareInParameter("Directory", CKPGUID_STRING); + + proto->DeclareOutParameter("last error", CKPGUID_INT); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + + proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_VARIABLEPARAMETERINPUTS)); + proto->SetFunction(ExecBB); + *pproto = proto; + return CK_OK; +} + +#include + +BOOL RunAndForgetProcess(char *pCmdLine, + char *pRunningDir, + int *nRetValue) +{ + int nError; + STARTUPINFO stInfo; + PROCESS_INFORMATION prInfo; + BOOL bResult; + ZeroMemory( &stInfo, sizeof(stInfo) ); + stInfo.cb = sizeof(stInfo); + stInfo.dwFlags=STARTF_USESHOWWINDOW; + stInfo.wShowWindow=SW_SHOW; + bResult = CreateProcess(NULL, + (LPSTR)pCmdLine, + NULL, + NULL, + TRUE, + CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP +// DETACHED_PROCESS + | NORMAL_PRIORITY_CLASS , + NULL, + (LPSTR)pRunningDir , + &stInfo, + &prInfo); + *nRetValue = nError = GetLastError(); + // Don't write these two lines if you need + CloseHandle(prInfo.hThread); + // to use these handles + CloseHandle(prInfo.hProcess); + if (!bResult) return FALSE; + return TRUE; +} +int ExecBB(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + + char* filename = ((CKSTRING) beh->GetInputParameterReadDataPtr(0)); + char* dirname = ((CKSTRING) beh->GetInputParameterReadDataPtr(1)) ; + + + if (!strlen(dirname)) + dirname = NULL;//argh....... ? + + int ret = 0; + + bool res = RunAndForgetProcess(filename,dirname,&ret); + + + beh->SetOutputParameterValue(0,&ret); + + if (res) + beh->ActivateOutput(0); + else + beh->ActivateOutput(1); + + + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/filecopy.cpp b/usr/Src/Behaviors/filecopy.cpp new file mode 100644 index 0000000..c483078 --- /dev/null +++ b/usr/Src/Behaviors/filecopy.cpp @@ -0,0 +1,81 @@ +#include "CKAll.h" +#include + + +CKObjectDeclaration *FillBehaviorCopyFileBBDecl(); +CKERROR CreateCopyFileBBProto(CKBehaviorPrototype **pproto); +int CopyFileBB(const CKBehaviorContext& behcontext); + + +CKERROR ZipCallBack(const CKBehaviorContext& behcontext); +CKObjectDeclaration *FillBehaviorCopyFileBBDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("File Copy"); + od->SetDescription(""); + od->SetCategory("Narratives/Files"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x149e1e15,0x23536f5a)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateCopyFileBBProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} + + + +CKERROR CreateCopyFileBBProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("File Copy"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("start"); + + proto->DeclareOutput("end"); + proto->DeclareOutput("error"); + + proto->DeclareInParameter("source", CKPGUID_STRING); + proto->DeclareInParameter("target", CKPGUID_STRING); + + + proto->DeclareInParameter("overwrite", CKPGUID_BOOL); + + proto->DeclareOutParameter("overwrite", CKPGUID_STRING); + + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + + proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_VARIABLEPARAMETERINPUTS)); + proto->SetFunction(CopyFileBB); + *pproto = proto; + return CK_OK; +} + +int CopyFileBB(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + XString sfilename((CKSTRING) beh->GetInputParameterReadDataPtr(0)); + XString tfilename((CKSTRING) beh->GetInputParameterReadDataPtr(1)); + +// XPath mdirs( sfilename ); + + + bool ow; + beh->GetInputParameterValue(2,&ow); + + + + ow=!ow; + + CopyFile(sfilename.Str() , tfilename.Str() ,ow ); + beh->ActivateOutput(0); + + + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/keyboard/KeyWaiter.cpp b/usr/Src/Behaviors/keyboard/KeyWaiter.cpp new file mode 100644 index 0000000..ba3b1bb --- /dev/null +++ b/usr/Src/Behaviors/keyboard/KeyWaiter.cpp @@ -0,0 +1,176 @@ +#include + +CKERROR CreateKeyWaiter2BehaviorProto(CKBehaviorPrototype **pproto); + +int KeyWaiter2(const CKBehaviorContext& behcontext); +int ReadKey2(const CKBehaviorContext& behcontext); +CKERROR KeyWaiter2CallBack(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorKeyWaiter2Decl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("Key Waiter2"); + od->SetDescription("Waits for a key to be pressed."); + /* rem: + In: triggers the process.
+ Out: is activated when the process is completed.
+
+ Key: key to wait for. This is chosen in the parameter dialog box by first + clicking "Select Key" and then pressing the key to wait for. The desired key will then appear to + the right of "Select Key".
+
+ Wait For Any Key: if TRUE, the building block will wait any key to be pressed. + The input parameter is deleted, and a output parameter is created; and in this case the output parameter retrieves the pressed key.
+ Useful for "Press any key to continue..." capabilities.
+
+ Waits for a key to be pressed. If the setting parameter 'Wait Any Key' is set to FALSE, this building block will + wait for a specific given key (default), if set to TRUE, then it will wait for anykey to be pressed, retrieving this key as an output parameter.
+
+ See Also: Switch On Key, Key Event.
+ */ + od->SetCategory("Controllers/Keyboard"); + od->SetType(CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x60280837,0x38976869)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("mw"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateKeyWaiter2BehaviorProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + od->NeedManager(INPUT_MANAGER_GUID); + return od; +} + + +CKERROR CreateKeyWaiter2BehaviorProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Key Waiter2"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareInput("StopIt"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Key", CKPGUID_KEY); + + proto->DeclareSetting("Wait For Any Key", CKPGUID_BOOL, "FALSE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(KeyWaiter2); + proto->SetBehaviorCallbackFct(KeyWaiter2CallBack); + proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS|CKBEHAVIOR_INTERNALLYCREATEDOUTPUTPARAMS)); + + *pproto = proto; + return CK_OK; +} + + +/*******************************************************/ +/* CALLBACK */ +/*******************************************************/ +CKERROR KeyWaiter2CallBack(const CKBehaviorContext& behcontext){ + + CKBehavior* beh = behcontext.Behavior; + + switch( behcontext.CallbackMessage ){ + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + CKBOOL anyKey=FALSE; + beh->GetLocalParameterValue(0, &anyKey); + + CKParameterIn *pin = beh->GetInputParameter(0); + if( anyKey ){ // wait any Key + beh->SetFunction(ReadKey2); + if( pin ){ + CKDestroyObject( beh->RemoveInputParameter(0) ); + beh->CreateOutputParameter("Key", CKPGUID_KEY); + } + } else { // wait specific Key + beh->SetFunction(KeyWaiter2); + if( !pin ){ + CKDestroyObject( beh->RemoveOutputParameter(0) ); + beh->CreateInputParameter("Key", CKPGUID_KEY); + } + } + } break; + } + + return CKBR_OK; +} + + +/*******************************************************/ +/* Main Function 1 */ +/*******************************************************/ +int KeyWaiter2(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + CKInputManager* input = (CKInputManager*)behcontext.Context->GetManagerByGuid(INPUT_MANAGER_GUID); + if (!input){ + behcontext.Context->OutputToConsoleEx("Can't get the Input Manager"); + return CKBR_GENERICERROR; + } + + if ( beh->IsInputActive( 1 ) ) + { + beh->ActivateInput( 0 , FALSE); + beh->ActivateInput( 1 , FALSE); + + + beh->ActivateOutput(0,FALSE); + return CKBR_OK; + } + + int key = 0; + beh->GetInputParameterValue(0,&key); + if( input->IsKeyDown(key) ){ + // Set IO states + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0,TRUE); + return CKBR_OK; + } + + return CKBR_ACTIVATENEXTFRAME; +} + + +/*******************************************************/ +/* Main Function 2 */ +/*******************************************************/ +int ReadKey2(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + CKInputManager* input = (CKInputManager*)behcontext.Context->GetManagerByGuid(INPUT_MANAGER_GUID); + if (!input){ + behcontext.Context->OutputToConsoleEx("Can't get the Input Manager"); + return CKBR_GENERICERROR; + } + + if ( beh->IsInputActive( 1 ) ) + { + beh->ActivateInput( 0 , FALSE); + beh->ActivateInput( 1 , FALSE); + + + beh->ActivateOutput(0,FALSE); + return CKBR_OK; + } + + CKDWORD key = 0; + if(input->GetKeyFromBuffer(0,key) == KEY_PRESSED) { + // Set IO states + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0,TRUE); + + // write the key + beh->SetOutputParameterValue(0,&key); + + return CKBR_OK; + } + + return CKBR_ACTIVATENEXTFRAME; +} + + diff --git a/usr/Src/Behaviors/logics/AddAttributeByName.cpp b/usr/Src/Behaviors/logics/AddAttributeByName.cpp new file mode 100644 index 0000000..06cfaed --- /dev/null +++ b/usr/Src/Behaviors/logics/AddAttributeByName.cpp @@ -0,0 +1,114 @@ +#include "CKAll.h" + +CKObjectDeclaration *FillBehaviorAddAttributesDecl(); +CKERROR CreateAddAttributesProto(CKBehaviorPrototype **); +int AddAttributes(const CKBehaviorContext& behcontext); + +CKERROR SetAttributeCallBack(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorAddAttributesDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Add Attribute by Substring"); + + od->SetCategory("Logics/Attribute"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x290f0795,0x16743e10)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateAddAttributesProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + + return od; +} + + +CKERROR CreateAddAttributesProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Add Attribute by Substring"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Attribute",CKPGUID_ATTRIBUTE); + proto->DeclareInParameter("Key Substring", CKPGUID_STRING, "PM_"); + proto->DeclareInParameter("Class", CKPGUID_CLASSID); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(AddAttributes); + + proto->SetBehaviorCallbackFct( SetAttributeCallBack ); + proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS)); + + *pproto = proto; + return CK_OK; +} + + +int AddAttributes(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + char string[512]; + beh->GetInputParameterValue(1,&string); + + int Attribute=-1; + beh->GetInputParameterValue(0,&Attribute); + + CKLevel* level = ctx->GetCurrentLevel(); + CK_CLASSID C_ID; + beh->GetInputParameterValue(2,&C_ID); + + XObjectPointerArray myarray=level->ComputeObjectList(C_ID); + for (CKObject** it = myarray.Begin(); it != myarray.End(); ++it) { + CKObject *obj = *it; + if (obj) { + if (obj->GetName()) { + if (strstr(obj->GetName(),string)) { + CK3dEntity *ent = (CK3dEntity *)*it; + ent->SetAttribute(Attribute); + CKParameterOut* pout = ent->GetAttributeParameter(Attribute); + if(pout) { + CKParameter* real; + CKParameterIn* tpin = (CKParameterIn*)beh->GetInputParameter(3); + if(tpin && (real=tpin->GetRealSource())) pout->CopyValue(real); + } + } + } + } + } + return CKBR_OK; +} + +CKERROR SetAttributeCallBack(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + switch( behcontext.CallbackMessage ){ + case CKM_BEHAVIOREDITED: + { + CKAttributeManager* Manager = behcontext.AttributeManager; + + int Attribute=-1; + beh->GetInputParameterValue(0,&Attribute); + int ParamType = Manager->GetAttributeParameterType(Attribute); + + if(ParamType != -1) { // we test if there is a parameter attached + beh->EnableInputParameter(2,TRUE); + CKParameterIn* pin = beh->GetInputParameter(3); + if (pin) { + if (pin->GetType()!=ParamType){ + pin->SetType( ParamType ); + } + } else beh->CreateInputParameter("Attribute Value",ParamType); + } else beh->EnableInputParameter(3,FALSE); + } + + } + beh->ActivateOutput(0); + + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/mesh/Bend.cpp b/usr/Src/Behaviors/mesh/Bend.cpp new file mode 100644 index 0000000..52f11a2 --- /dev/null +++ b/usr/Src/Behaviors/mesh/Bend.cpp @@ -0,0 +1,219 @@ +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +// +// Bend +// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +#include "CKAll.h" + +CKObjectDeclaration *FillBehaviorBendDecl(); +CKERROR CreateBendProto(CKBehaviorPrototype **); +int Bend(const CKBehaviorContext& behcontext); +//CKERROR MeshModificationsCallBack(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorBendDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Bend2"); + od->SetDescription("Bends a mesh uniformly along an axis with an angle and a direction of bending."); + /* rem: + In : triggers the process.
+ Exit : is activated when the process is completed.
+
+ Angle : angle to bend from the vertical plane.
+ Direction : direction of the bend relative to the horizontal plane.
+ Axis : vector that specifies the axis that the object will bend along.
+ Reset Mesh: if TRUE, the mesh is resetted to its initial conditions at activation.
+
+ The model need to be somewhat facetted for a good result.
+ */ + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7c9a7008,0x6b0f1d1f)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00020000); + od->SetCreationFunction(CreateBendProto); + od->SetCompatibleClassId(CKCID_3DOBJECT); + od->SetCategory("Mesh Modifications/Deformation"); + return od; +} + + +CKERROR CreateBendProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = NULL; + proto = CreateCKBehaviorPrototype("Bend"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Exit"); + + proto->DeclareInParameter("Angle", CKPGUID_ANGLE, "0:90" ); + proto->DeclareInParameter("Direction", CKPGUID_FLOAT ,"0.0"); + // To change by Radio buttons + proto->DeclareInParameter("Axis", CKPGUID_VECTOR, "0,0,1" ); + proto->DeclareInParameter("Reset Mesh", CKPGUID_BOOL, "TRUE" ); + proto->DeclareInParameter("Normal Recalculation", CKPGUID_BOOL, "TRUE" ); + + proto->DeclareLocalParameter(NULL, CKPGUID_VOIDBUF ); // Data + proto->DeclareLocalParameter(NULL, CKPGUID_BOX ); // Initial Box + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(Bend); + +// proto->SetBehaviorCallbackFct(MeshModificationsCallBack); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + *pproto = proto; + return CK_OK; + +} + + +int Bend(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + // we get the entity + CK3dEntity *ent = (CK3dEntity *) beh->GetTarget(); + + // we get the angle + float angle; + beh->GetInputParameterValue(0,&angle); + angle *= 0.5f; + + // we get the direction + float direction; + beh->GetInputParameterValue(1,&direction); + + // we get the axis + VxVector axis; + beh->GetInputParameterValue(2,&axis); + int naxis=0; + while (axis[naxis]==0.0f) naxis++; + + // we get the mesh + CKMesh *mesh = ent->GetCurrentMesh(); + CKDWORD vStride=0; + BYTE* varray = (BYTE*)mesh->GetModifierVertices(&vStride); + int pointsNumber = mesh->GetModifierVertexCount(); +/* + CKBOOL resetmesh = TRUE; + beh->GetInputParameterValue(3,&resetmesh); + if (resetmesh) { // The Mesh must be resetted + if(beh->GetVersion() < 0x00020000) { // Old Version with vertices stuffed inside + // we get the saved position + VxVector* savePos = (VxVector*)beh->GetLocalParameterWriteDataPtr(0); + + BYTE* temparray = varray; + for(int i=0;iGetObjectInitialValue(mesh); + if(chunk) mesh->LoadVertices(chunk); + varray = (BYTE*)mesh->GetModifierVertices(&vStride); + pointsNumber = mesh->GetModifierVertexCount(); + const VxBbox& bbox = mesh->GetLocalBox(); + beh->SetLocalParameterValue(1,&bbox); + } + } + + VxBbox bbox; + beh->GetLocalParameterValue(1,&bbox); + + VxMatrix mat; + switch (naxis) { + case 0: { VxVector vz(0.0f,1.0f,0.0f); Vx3DMatrixFromRotation(mat,vz,-HALFPI); } break; //x + case 1: { VxVector vx(0.0f,0.0f,1.0f); Vx3DMatrixFromRotation(mat,vx,-HALFPI); } break; //y + case 2: { mat = VxMatrix::Identity(); } break; //z + } + + // attention inversion y / z + if (direction) { + VxMatrix rot; + VxVector vz(0.0f,0.0f,1.0f); + Vx3DMatrixFromRotation(rot,vz,direction); + Vx3DMultiplyMatrix(mat,rot,mat); + } + + float r,len; + switch (naxis) { + case 0: len = bbox.Max.x - bbox.Min.x; break; + case 1: len = bbox.Max.y - bbox.Min.y; break; + case 2: len = bbox.Max.z - bbox.Min.z; break; + } + + // Skip the singularity + if (fabs(angle) <0.0001) { + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + return CKBR_OK; + } else { + r = len/angle; + } + + + VxMatrix invmat; + Vx3DInverseMatrix(invmat,mat); + + // we move all the points + float x,y,c,s,yr; + VxVector v,n; + + float invr = 1.0f/r; + + CKBOOL normalc = TRUE; + beh->GetInputParameterValue(4,&normalc); + + CKDWORD nStride=0; + BYTE* narray = (BYTE*)mesh->GetNormalsPtr(&nStride); + if (CKIsChildClassOf(mesh,CKCID_PATCHMESH) || !normalc) narray = NULL; + + for(int i=0;iModifierVertexMove(FALSE,TRUE); + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0,TRUE); + */ + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/mesh/Noise.cpp b/usr/Src/Behaviors/mesh/Noise.cpp new file mode 100644 index 0000000..88c73d7 --- /dev/null +++ b/usr/Src/Behaviors/mesh/Noise.cpp @@ -0,0 +1,286 @@ +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +// +// Noise +// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +#include "CKAll.h" + + +CKObjectDeclaration *FillBehaviorNoiseDecl(); +CKERROR CreateNoiseProto(CKBehaviorPrototype **); +int Noise(const CKBehaviorContext& behcontext); +//CKERROR MeshModificationsCallBack(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorNoiseDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Noise2"); + od->SetDescription("Displaces the vertices of the mesh with a random vector."); + /* rem: + In: triggers the process.
+ Out: is activated when the process is completed.
+
+ Seed: generates a random starting point from the number you set.
+ Scale: size of noise effect (not strength).
+ Axis: strength of the noise effect along each of three axes.
+ Reset Mesh: if TRUE, the mesh is reseted to its initial conditions at activation.
+ */ + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x6d300730,0x26c83f42)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00020000); + od->SetCreationFunction(CreateNoiseProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + od->SetCategory("Mesh Modifications/Deformation"); + return od; +} + + +CKERROR CreateNoiseProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = NULL; + proto = CreateCKBehaviorPrototype("Noise2"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Seed", CKPGUID_FLOAT,"0.1" ); + proto->DeclareInParameter("Scale", CKPGUID_FLOAT ,"50.0"); + // To change by Radio buttons + proto->DeclareInParameter("Axis", CKPGUID_VECTOR, "0.1,0,0" ); + proto->DeclareInParameter("Reset Mesh", CKPGUID_BOOL, "TRUE" ); + + + proto->DeclareInParameter("target", CKPGUID_3DENTITY); + + + proto->DeclareLocalParameter("data", CKPGUID_VOIDBUF ); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(Noise); + + //proto->SetBehaviorCallbackFct(MeshModificationsCallBack); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + *pproto = proto; + return CK_OK; + +} + +#define B 0x100 +#define BM 0xff + +#define N 0x1000 +#define NP 12 /* 2^N */ +#define NM 0xfff + +static int p[B + B + 2]; +static float g3[B + B + 2][3]; +static float g2[B + B + 2][2]; +static float g1[B + B + 2]; +static int start = 1; + +static void init(void); + +#define s_curve(t) ( t * t * (3.0f - 2.0f * t) ) + +#define lerp(t, a, b) ( a + t * (b - a) ) + +#define setup(i,b0,b1,r0,r1)\ + t = vec[i] + N;\ + b0 = ((int)t) & BM;\ + b1 = (b0+1) & BM;\ + r0 = t - (int)t;\ + r1 = r0 - 1.0f; + +float noise3(const VxVector &vect) +{ + const float *vec = vect.v; + int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11; + float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v; + register int i, j; + + if (start) { + start = 0; + init(); + } + + setup(0, bx0,bx1, rx0,rx1); + setup(1, by0,by1, ry0,ry1); + setup(2, bz0,bz1, rz0,rz1); + + i = p[ bx0 ]; + j = p[ bx1 ]; + + b00 = p[ i + by0 ]; + b10 = p[ j + by0 ]; + b01 = p[ i + by1 ]; + b11 = p[ j + by1 ]; + + t = s_curve(rx0); + sy = s_curve(ry0); + sz = s_curve(rz0); + +#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] ) + + q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0); + q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0); + a = lerp(t, u, v); + + q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0); + q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0); + b = lerp(t, u, v); + + c = lerp(sy, a, b); + + q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1); + q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1); + a = lerp(t, u, v); + + q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1); + q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1); + b = lerp(t, u, v); + + d = lerp(sy, a, b); + + return lerp(sz, c, d); +} + +static void normalize2(float v[2]) +{ + float s; + + s = 1.0f / sqrtf(v[0] * v[0] + v[1] * v[1]); + v[0] = v[0] * s; + v[1] = v[1] * s; +} + +static void normalize3(float v[3]) +{ + float s; + + s = 1.0f / sqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + v[0] = v[0] * s; + v[1] = v[1] * s; + v[2] = v[2] * s; +} + +static void init(void) +{ + int i, j, k; + + for (i = 0 ; i < B ; i++) { + p[i] = i; + + g1[i] = (float)((rand() % (B + B)) - B) / B; + + for (j = 0 ; j < 2 ; j++) + g2[i][j] = (float)((rand() % (B + B)) - B) / B; + normalize2(g2[i]); + + for (j = 0 ; j < 3 ; j++) + g3[i][j] = (float)((rand() % (B + B)) - B) / B; + normalize3(g3[i]); + } + + while (--i) { + k = p[i]; + p[i] = p[j = rand() % B]; + p[j] = k; + } + + for (i = 0 ; i < B + 2 ; i++) { + p[B + i] = p[i]; + g1[B + i] = g1[i]; + for (j = 0 ; j < 2 ; j++) + g2[B + i][j] = g2[i][j]; + for (j = 0 ; j < 3 ; j++) + g3[B + i][j] = g3[i][j]; + } +} + +int Noise(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + // we get the 3d entity + CK3dEntity *ent = (CK3dEntity *) beh->GetInputParameterObject(4); + if(!ent) return 0; + + // we get the seed value + float seed=0.1f; + CKParameterIn *pin = beh->GetInputParameter(0); + if( pin->GetGUID() == CKPGUID_INT ){ // back compatibility + int seed_int = 0; + pin->GetValue( &seed_int ); + seed = (float)seed_int; + } else { + beh->GetInputParameterValue(0,&seed); + } + seed *= 0.01f; + + // we get the scale value + float scale; + beh->GetInputParameterValue(1,&scale); + + // we get the amount value + VxVector axis; + beh->GetInputParameterValue(2,&axis); + + // we get the mesh + CKMesh *mesh = ent->GetCurrentMesh(); + CKDWORD vStride=0; + BYTE* varray = (BYTE*)mesh->GetModifierVertices(&vStride); + int pointsNumber = mesh->GetModifierVertexCount(); + + CKBOOL resetmesh = TRUE; + beh->GetInputParameterValue(3,&resetmesh); + if (resetmesh) { // The Mesh must be reseted + if(beh->GetVersion() < 0x00020000) { // Old Version with vertices stuffed inside + // we get the saved position + VxVector* savePos = (VxVector*)beh->GetLocalParameterWriteDataPtr(0); + + BYTE* temparray = varray; + for(int i=0;iGetObjectInitialValue(mesh); + if(chunk) mesh->LoadVertices(chunk); + varray = (BYTE*)mesh->GetModifierVertices(&vStride); + pointsNumber = mesh->GetModifierVertexCount(); + } + } + + // we move all the points + VxVector v,sp,d(0,0,0); + VxVector offset(0.5f,0.5f,0.5f); + VxVector noise_vect(0,0,seed); + for(int i=0;iModifierVertexMove(TRUE,TRUE); + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/pCloth/PCAttachToCore.cpp b/usr/Src/Behaviors/pCloth/PCAttachToCore.cpp new file mode 100644 index 0000000..c4f9841 --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PCAttachToCore.cpp @@ -0,0 +1,276 @@ +/*! + * + * + * Copyright (c) 2005 by + */ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPClothAttachToCoreDecl(); +CKERROR CreatePClothAttachToCoreProto(CKBehaviorPrototype **pproto); +int PClothAttachToCore(const CKBehaviorContext& behcontext); +CKERROR PClothAttachToCoreCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + bbI_BodyReference, + bbI_ImpulseThreshold, + bbI_PenetrationDepth, + bbI_MaxDeform, +}; + + + + + +//************************************ +// Method: FillBehaviorPClothAttachToCoreDecl +// FullName: FillBehaviorPClothAttachToCoreDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +/*! + * \brief + * Write brief comment for FillBehaviorPClothAttachToCoreDecl here. + * + * \returns + * Write description of return value here. + * + * \throws + * Description of criteria for throwing this exception. + * + * Write detailed description for FillBehaviorPClothAttachToCoreDecl here. + * + * \remarks + * Write remarks for FillBehaviorPClothAttachToCoreDecl here. + * + * \see + * Separate items with the '|' character. + */ +CKObjectDeclaration *FillBehaviorPClothAttachToCoreDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAttachToCore"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Surrounds a rigid body with a cloth."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x37d75f67,0x7041320f)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothAttachToCoreProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothAttachToCoreProto +// FullName: CreatePClothAttachToCoreProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothAttachToCoreProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAttachToCore"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothAttachToCore + + + PClothAttachToCore is categorized in \ref Clothes + +

Description

+ Apply to a
3DEntity
+ Attaches a cloth to a body.
+ + Call this function only once right after the cloth is created. + Turning cloth into metal and vice versa during the simulation is not recommended. + + This feature is well suited for volumetric objects like barrels. + It cannot handle two dimensional flat pieces well. + + After this call, the cloth is infinitely stiff between collisions and simply + moves with the body. At impacts with an impact impulse greater than impulseThreshold, + the cloth is plastically deformed. Thus, a cloth with a core behaves like a piece of metal. + + The core body's geometry is adjusted automatically. Its size also depends on the + cloth thickness. Thus, it is recommended to choose small values for the thickness. + At impacts, colliding objects are moved closer to the cloth by the value provided in + penetrationDepth which causes a more dramatic collision result. + + The core body must have at least one shape, and currently supported shapes are + spheres, capsules, boxes and compounds of spheres. + It is recommended to specify the density rather than the mass of the core body. + This way the mass and inertia tensor are updated when the core deforms. + + The maximal deviation of cloth particles from their initial positions + (modulo the global rigid body transforms translation and rotation) can be + specified via the parameter maxDeformationDistance. Setting this parameter to + zero means that the deformation is not limited. + +

Technical Information

+ + \image html PClothAttachToCore.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + Target: Target cloth reference. +
+
+ + Body Reference: The core body to attach the cloth to. + + @see pCloth::attachToCore() +
+ Impulse Threshold: Threshold for when deformation is allowed. +
+ + Penetration Depth: Amount by which colliding objects are brought closer to the cloth. +
+ + + Max Deformation Distance: Maximum deviation of cloth particles from initial position. +
+ + + +
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include pCloth.cpp + + */ + + + + proto->SetBehaviorCallbackFct( PClothAttachToCoreCB ); + + proto->DeclareInParameter("Body Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Impulse Threshold",CKPGUID_FLOAT); + proto->DeclareInParameter("Penetration Depth",CKPGUID_FLOAT); + proto->DeclareInParameter("Max Deformation Distance",CKPGUID_FLOAT); + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothAttachToCore); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothAttachToCore +// FullName: PClothAttachToCore +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothAttachToCore(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + + CK3dEntity*bodyReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_BodyReference); + if (!bodyReference) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pRigidBody *body = GetPMan()->getBody(bodyReference); + if (!body) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pWorld *world = body->getWorld(); + if (!world) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pCloth *cloth = world->getCloth(target); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + + + float impulseThreshold = GetInputParameterValue(beh,bbI_ImpulseThreshold); + float penetrationDepth = GetInputParameterValue(beh,bbI_PenetrationDepth); + float maxDeform = GetInputParameterValue(beh,bbI_MaxDeform); + + cloth->attachToCore(bodyReference,impulseThreshold,penetrationDepth,maxDeform); + + beh->ActivateOutput(0); + + } + return 0; +} + +//************************************ +// Method: PClothAttachToCoreCB +// FullName: PClothAttachToCoreCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothAttachToCoreCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCloth/PCAttachToShape.cpp b/usr/Src/Behaviors/pCloth/PCAttachToShape.cpp new file mode 100644 index 0000000..d183696 --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PCAttachToShape.cpp @@ -0,0 +1,242 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorPClothAttachToShapeDecl(); +CKERROR CreatePClothAttachToShapeProto(CKBehaviorPrototype **pproto); +int PClothAttachToShape(const CKBehaviorContext& behcontext); +CKERROR PClothAttachToShapeCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + bbI_ShapeReference, + bbI_AttachmentFlags, + bbI_AttachToColliding, +}; + + +enum bSettings +{ + bbS_USE_DEFAULT_WORLD, + bbS_ADD_ATTRIBUTES +}; + +//************************************ +// Method: FillBehaviorPClothAttachToShapeDecl +// FullName: FillBehaviorPClothAttachToShapeDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothAttachToShapeDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAttachToShape"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Attaches a cloth to a shape."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x2ca5453a,0x7dc1598f)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothAttachToShapeProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothAttachToShapeProto +// FullName: CreatePClothAttachToShapeProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothAttachToShapeProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAttachToShape"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothAttachToShape + + PClothAttachToShape is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Attaches a cloth to a shape .
+ +

Technical Information

+ + \image html PClothAttachToShape.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+
+ + Shape Reference: Shape to which the cloth should be attached to. + + @see pCloth::attachToShape() +
+
+ + Attachment Flags: One or two way interaction, tearable or non-tearable + + Default: PCAF_ClothAttachmentTwoway + + @see pClothAttachmentFlag +
+
+ +
+
+ Attach to colliding shapes: Attaches the cloth to all shapes, currently colliding. + + This method only works with primitive and convex shapes. Since the inside of a general + triangle mesh is not clearly defined. + + @see pCloth::attachToCollidingShapes() + +
+
+ + + +
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include pCloth.cpp + + */ + + + + proto->SetBehaviorCallbackFct( PClothAttachToShapeCB ); + + proto->DeclareInParameter("Shape Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Attachment Flags",VTE_CLOTH_ATTACH_FLAGS); + proto->DeclareInParameter("Attach to colliding shapes",CKPGUID_BOOL); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothAttachToShape); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothAttachToShape +// FullName: PClothAttachToShape +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothAttachToShape(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + + CK3dEntity*shapeReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_ShapeReference); + if (!shapeReference) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pWorld *world = GetPMan()->getDefaultWorld(); + if (!world) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pCloth *cloth = world->getCloth(target); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + + + int flags = GetInputParameterValue(beh,bbI_AttachmentFlags); + int attachToColliders = GetInputParameterValue(beh,bbI_AttachToColliding); + + NxShape *shape = world->getShapeByEntityID(shapeReference->GetID()); + if(shape) + { + cloth->attachToShape((CKBeObject*)shapeReference,flags); + } + + + if (attachToColliders) + { + cloth->attachToCollidingShapes(flags); + } + + + beh->ActivateOutput(0); + + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothAttachToShapeCB +// FullName: PClothAttachToShapeCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothAttachToShapeCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pCloth/PCAttachVertexToGlobalPos.cpp b/usr/Src/Behaviors/pCloth/PCAttachVertexToGlobalPos.cpp new file mode 100644 index 0000000..293e942 --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PCAttachVertexToGlobalPos.cpp @@ -0,0 +1,187 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPClothAttachVertexToPositionDecl(); +CKERROR CreatePClothAttachVertexToPositionProto(CKBehaviorPrototype **pproto); +int PClothAttachVertexToPosition(const CKBehaviorContext& behcontext); +CKERROR PClothAttachVertexToPositionCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + bbI_VertexIndex, + bbI_GlobalPosition +}; + +//************************************ +// Method: FillBehaviorPClothAttachVertexToPositionDecl +// FullName: FillBehaviorPClothAttachVertexToPositionDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothAttachVertexToPositionDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAttachVertexToPosition"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Attaches a cloth vertex to a position in world space"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x6f502320,0x48065a45)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothAttachVertexToPositionProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothAttachVertexToPositionProto +// FullName: CreatePClothAttachVertexToPositionProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothAttachVertexToPositionProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAttachVertexToPosition"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothAttachVertexToPosition + + PClothAttachVertexToPosition is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Attaches a cloth vertex to a position in world space.
+ + @see pCloth::attachVertexToGlobalPosition() + + +

Technical Information

+ + \image html PClothAttachVertexToPosition.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+
+ +
+
+ Vertex Index: Index of the vertex to attach. +
+
+ + Global Position: TThe position in world space. +
+
+ + */ + + proto->SetBehaviorCallbackFct( PClothAttachVertexToPositionCB ); + + proto->DeclareInParameter("Vertex Index",CKPGUID_INT); + proto->DeclareInParameter("Global Position",CKPGUID_VECTOR); + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothAttachVertexToPosition); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothAttachVertexToPosition +// FullName: PClothAttachVertexToPosition +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothAttachVertexToPosition(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + + pWorld *world = GetPMan()->getDefaultWorld(); + if (!world) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pCloth *cloth = world->getCloth(target); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + int vertexIndex = GetInputParameterValue(beh,bbI_VertexIndex); + VxVector localPosition = GetInputParameterValue(beh,bbI_GlobalPosition); + + cloth->attachVertexToGlobalPosition(vertexIndex,localPosition); + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothAttachVertexToPositionCB +// FullName: PClothAttachVertexToPositionCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothAttachVertexToPositionCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pCloth/PCAttachVertexToShape.cpp b/usr/Src/Behaviors/pCloth/PCAttachVertexToShape.cpp new file mode 100644 index 0000000..0b5f811 --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PCAttachVertexToShape.cpp @@ -0,0 +1,243 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorPClothAttachVertexToShapeDecl(); +CKERROR CreatePClothAttachVertexToShapeProto(CKBehaviorPrototype **pproto); +int PClothAttachVertexToShape(const CKBehaviorContext& behcontext); +CKERROR PClothAttachVertexToShapeCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + bbI_ShapeReference, + bbI_AttachmentFlags, + bbI_VertexIndex, + bbI_LocalPosition +}; + + +enum bSettings +{ + bbS_USE_DEFAULT_WORLD, + bbS_ADD_ATTRIBUTES +}; + +//************************************ +// Method: FillBehaviorPClothAttachVertexToShapeDecl +// FullName: FillBehaviorPClothAttachVertexToShapeDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothAttachVertexToShapeDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAttachVertexToShape"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Attaches a cloth vertex to another shape."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x27970ee2,0x1247425d)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothAttachVertexToShapeProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothAttachVertexToShapeProto +// FullName: CreatePClothAttachVertexToShapeProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothAttachVertexToShapeProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAttachVertexToShape"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothAttachVertexToShape + + PClothAttachVertexToShape is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Attaches a cloth vertex to a shape .
+ + @see pCloth::attachVertexToShape() + + +

Technical Information

+ + \image html PClothAttachVertexToShape.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+
+ + Shape Reference: Shape to which the cloth should be attached to. + + @see pCloth::attachToShape() +
+
+ + Attachment Flags: One or two way interaction, tearable or non-tearable + + Default: PCAF_ClothAttachmentTwoway + + @see pClothAttachmentFlag +
+
+ +
+
+ Vertex Index: Index of the vertex to attach. +
+
+ + Local Position: The position relative to the pose of the shape. +
+
+ + + + +
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include pCloth.cpp + + */ + + + + proto->SetBehaviorCallbackFct( PClothAttachVertexToShapeCB ); + + proto->DeclareInParameter("Shape Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Attachment Flags",VTE_CLOTH_ATTACH_FLAGS); + proto->DeclareInParameter("Vertex Index",CKPGUID_INT); + proto->DeclareInParameter("Local Position",CKPGUID_VECTOR); + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothAttachVertexToShape); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothAttachVertexToShape +// FullName: PClothAttachVertexToShape +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothAttachVertexToShape(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + + CK3dEntity*shapeReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_ShapeReference); + if (!shapeReference) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pWorld *world = GetPMan()->getDefaultWorld(); + if (!world) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pCloth *cloth = world->getCloth(target); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + + + int flags = GetInputParameterValue(beh,bbI_AttachmentFlags); + int vertexIndex = GetInputParameterValue(beh,bbI_VertexIndex); + VxVector localPosition = GetInputParameterValue(beh,bbI_LocalPosition); + + + NxShape *shape = world->getShapeByEntityID(shapeReference->GetID()); + if(shape) + { + cloth->attachVertexToShape(vertexIndex,(CKBeObject*)shapeReference,localPosition,flags); + } + + beh->ActivateOutput(0); + + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothAttachVertexToShapeCB +// FullName: PClothAttachVertexToShapeCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothAttachVertexToShapeCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCloth/PCDestroy.cpp b/usr/Src/Behaviors/pCloth/PCDestroy.cpp new file mode 100644 index 0000000..6119b56 --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PCDestroy.cpp @@ -0,0 +1,162 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPClothDestroyDecl(); +CKERROR CreatePClothDestroyProto(CKBehaviorPrototype **pproto); +int PClothDestroy(const CKBehaviorContext& behcontext); +CKERROR PClothDestroyCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + bbI_ShapeReference, + +}; + + + +//************************************ +// Method: FillBehaviorPClothDestroyDecl +// FullName: FillBehaviorPClothDestroyDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothDestroyDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothDestroy"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Destroys a physical cloth."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x8d604ec,0x2e926408)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothDestroyProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothDestroyProto +// FullName: CreatePClothDestroyProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothDestroyProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothDestroy"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothDestroy + + PClothDestroy is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Destroys a physical cloth.
+ + @see pWorld::destroyCloth() + +

Technical Information

+ + \image html PClothDestroy.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+
+ + */ + + proto->SetBehaviorCallbackFct( PClothDestroyCB ); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothDestroy); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothDestroy +// FullName: PClothDestroy +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothDestroy(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + ////////////////////////////////////////////////////////////////////////// + pCloth *cloth = GetPMan()->getCloth(target->GetID()); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pWorld *world = cloth->getWorld(); + world->destroyCloth(target->GetID()); + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothDestroyCB +// FullName: PClothDestroyCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothDestroyCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pCloth/PCDetachFromShape.cpp b/usr/Src/Behaviors/pCloth/PCDetachFromShape.cpp new file mode 100644 index 0000000..ce78ddd --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PCDetachFromShape.cpp @@ -0,0 +1,189 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPClothDetachFromShapeDecl(); +CKERROR CreatePClothDetachFromShapeProto(CKBehaviorPrototype **pproto); +int PClothDetachFromShape(const CKBehaviorContext& behcontext); +CKERROR PClothDetachFromShapeCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + bbI_ShapeReference, + +}; + + + +//************************************ +// Method: FillBehaviorPClothDetachFromShapeDecl +// FullName: FillBehaviorPClothDetachFromShapeDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothDetachFromShapeDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothDetachFromShape"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Detaches the cloth from a shape it has been attached to before. "); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0xf4b0609,0x75b453a3)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothDetachFromShapeProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothDetachFromShapeProto +// FullName: CreatePClothDetachFromShapeProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothDetachFromShapeProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothDetachFromShape"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothDetachFromShape + + PClothDetachFromShape is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Detaches the cloth from a shape it has been attached to before
+ + @see pCloth::detachFromShape() + +

Technical Information

+ + \image html PClothDetachFromShape.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+
+ + Shape Reference: Shape to which the cloth should be attached to. + + +
+
+ + Attachment Flags: One or two way interaction, tearable or non-tearable + */ + + proto->SetBehaviorCallbackFct( PClothDetachFromShapeCB ); + proto->DeclareInParameter("Shape Reference",CKPGUID_3DENTITY); + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothDetachFromShape); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothDetachFromShape +// FullName: PClothDetachFromShape +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothDetachFromShape(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + + CK3dEntity*shapeReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_ShapeReference); + if (!shapeReference) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pCloth *cloth = GetPMan()->getCloth(target->GetID()); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + + NxShape *shape = cloth->getWorld()->getShapeByEntityID(shapeReference->GetID()); + if(shape) + { + cloth->detachFromShape((CKBeObject*)shapeReference); + } + + + beh->ActivateOutput(0); + + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothDetachFromShapeCB +// FullName: PClothDetachFromShapeCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothDetachFromShapeCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} diff --git a/usr/Src/Behaviors/pCloth/PCDominateVertex.cpp b/usr/Src/Behaviors/pCloth/PCDominateVertex.cpp new file mode 100644 index 0000000..9139070 --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PCDominateVertex.cpp @@ -0,0 +1,212 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPClothDominateVertexDecl(); +CKERROR CreatePClothDominateVertexProto(CKBehaviorPrototype **pproto); +int PClothDominateVertex(const CKBehaviorContext& behcontext); +CKERROR PClothDominateVertexCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_VertexIndex, + bbI_expireTime, + bbI_domWeight, + +}; + +//************************************ +// Method: FillBehaviorPClothDominateVertexDecl +// FullName: FillBehaviorPClothDominateVertexDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothDominateVertexDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothDominateVertex"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Changes the weight of a vertex in the cloth solver for a period of time."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x92979b9,0x4ced0f82)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothDominateVertexProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothDominateVertexProto +// FullName: CreatePClothDominateVertexProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothDominateVertexProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothDominateVertex"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothDominateVertex + + PClothDominateVertex is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Changes the weight of a vertex in the cloth solver for a period of time.
+ + If this method is called for some vertex, the cloth solver will, during a time + period of length expirationTime, assign a different weight to the vertex + while internal cloth constraints (i.e. bending & stretching) are being resolved. + + With a high dominanceWeight, the modified vertex will force neighboring vertices + to strongly accommodate their positions while its own is kept fairly constant. + The reverse holds for smaller dominanceWeights. + + Using a dominanceWeight of +infinity has a similar effect as temporarily attaching + the vertex to a global position. However, unlike using attachments, the velocity + of the vertex is kept intact when using this method. + + \note The current implementation will not support the full range of dominanceWeights. + All dominanceWeights > 0.0 are treated equally as being +infinity. + + \note An expiration time of 0.0 is legal and will result in dominance being + applied throughout one substep before being discarded immediately. + + \note Having a large number of vertices dominant at once may result in a performance penalty. + + + + @see pCloth::dominateVertex() + + +

Technical Information

+ + \image html PClothDominateVertex.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+
+ + Vertex Index: Index of the vertex. +
+ + Expiration Time: Time period where dominance will be active for this vertex. +
+
+ + Dominance Weight: Dominance weight for this vertex. +
+
+ + */ + + proto->SetBehaviorCallbackFct( PClothDominateVertexCB ); + + proto->DeclareInParameter("Vertex Index",CKPGUID_INT); + proto->DeclareInParameter("Expiration Time",CKPGUID_FLOAT); + proto->DeclareInParameter("Dominance Weight",CKPGUID_FLOAT); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothDominateVertex); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothDominateVertex +// FullName: PClothDominateVertex +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothDominateVertex(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + + pWorld *world = GetPMan()->getDefaultWorld(); + if (!world) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pCloth *cloth = world->getCloth(target); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + int vertexIndex = GetInputParameterValue(beh,bbI_VertexIndex); + float expTime = GetInputParameterValue(beh,bbI_expireTime); + float domWeight = GetInputParameterValue(beh,bbI_domWeight); + cloth->dominateVertex(vertexIndex,expTime,domWeight); + + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothDominateVertexCB +// FullName: PClothDominateVertexCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothDominateVertexCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pCloth/PCFreeVertex.cpp b/usr/Src/Behaviors/pCloth/PCFreeVertex.cpp new file mode 100644 index 0000000..8570e03 --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PCFreeVertex.cpp @@ -0,0 +1,177 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPClothFreeVertexDecl(); +CKERROR CreatePClothFreeVertexProto(CKBehaviorPrototype **pproto); +int PClothFreeVertex(const CKBehaviorContext& behcontext); +CKERROR PClothFreeVertexCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_VertexIndex, + +}; + +//************************************ +// Method: FillBehaviorPClothFreeVertexDecl +// FullName: FillBehaviorPClothFreeVertexDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothFreeVertexDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothFreeVertex"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Frees a previously attached cloth point."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x718e795d,0x5006d9d)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothFreeVertexProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothFreeVertexProto +// FullName: CreatePClothFreeVertexProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothFreeVertexProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothFreeVertex"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothFreeVertex + + PClothFreeVertex is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Frees a previously attached cloth point.
+ + @see pCloth::freeVertex() + + +

Technical Information

+ + \image html PClothFreeVertex.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+
+ +
+
+ Vertex Index: Index of the vertex to free. +
+
+ + */ + + proto->SetBehaviorCallbackFct( PClothFreeVertexCB ); + + proto->DeclareInParameter("Vertex Index",CKPGUID_INT); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothFreeVertex); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothFreeVertex +// FullName: PClothFreeVertex +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothFreeVertex(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + + pWorld *world = GetPMan()->getDefaultWorld(); + if (!world) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pCloth *cloth = world->getCloth(target); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + int vertexIndex = GetInputParameterValue(beh,bbI_VertexIndex); + cloth->freeVertex(vertexIndex); + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothFreeVertexCB +// FullName: PClothFreeVertexCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothFreeVertexCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pCloth/PClothAddDirectedForceAtPos.cpp b/usr/Src/Behaviors/pCloth/PClothAddDirectedForceAtPos.cpp new file mode 100644 index 0000000..103fe89 --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PClothAddDirectedForceAtPos.cpp @@ -0,0 +1,191 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPClothAddDirectedForceAtPosDecl(); +CKERROR CreatePClothAddDirectedForceAtPosProto(CKBehaviorPrototype **pproto); +int PClothAddDirectedForceAtPos(const CKBehaviorContext& behcontext); +CKERROR PClothAddDirectedForceAtPosCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_Pos, + bbI_Force, + bbI_Radius, + bbI_ForceMode, +}; + + + +//************************************ +// Method: FillBehaviorPClothAddDirectedForceAtPosDecl +// FullName: FillBehaviorPClothAddDirectedForceAtPosDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothAddDirectedForceAtPosDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAddDirectedForceAtPos"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Applies a directed force (or impulse) at a particular position. All vertices within radius will be affected with a quadratic drop-off. "); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x439b04ff,0x252950fc)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothAddDirectedForceAtPosProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothAddDirectedForceAtPosProto +// FullName: CreatePClothAddDirectedForceAtPosProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothAddDirectedForceAtPosProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAddDirectedForceAtPos"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothAddDirectedForceAtPos + + PClothAddDirectedForceAtPos is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Applies a directed force (or impulse) at a particular position. All vertices + within radius will be affected with a quadratic drop-off.
+ + Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + + + @see pCloth::addDirectedForceAtPos() + + +

Technical Information

+ + \image html PClothAddDirectedForceAtPos.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+ Position: Position to apply force at. +
+ Force: Force to apply. +
+ Magnitude: Magnitude of the force/impulse to apply. +
+ Radius: The sphere radius in which particles will be affected. +
+ Force Mode: The mode to use when applying the force/impulse. + (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange). +
+ + */ + + + + proto->SetBehaviorCallbackFct( PClothAddDirectedForceAtPosCB ); + proto->DeclareInParameter("Position",CKPGUID_VECTOR); + proto->DeclareInParameter("Magnitude",CKPGUID_FLOAT); + proto->DeclareInParameter("Radius",CKPGUID_FLOAT); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothAddDirectedForceAtPos); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothAddDirectedForceAtPos +// FullName: PClothAddDirectedForceAtPos +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothAddDirectedForceAtPos(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + pCloth *cloth = GetPMan()->getCloth(target->GetID()); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + VxVector position= GetInputParameterValue(beh,bbI_Pos); + VxVector force = GetInputParameterValue(beh,bbI_Force); + float radius= GetInputParameterValue(beh,bbI_Radius); + int forceMode = GetInputParameterValue(beh,bbI_ForceMode); + + cloth->addDirectedForceAtPos(position,force,radius,(ForceMode)forceMode); + + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothAddDirectedForceAtPosCB +// FullName: PClothAddDirectedForceAtPosCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothAddDirectedForceAtPosCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pCloth/PClothAddForceAtPos.cpp b/usr/Src/Behaviors/pCloth/PClothAddForceAtPos.cpp new file mode 100644 index 0000000..947d367 --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PClothAddForceAtPos.cpp @@ -0,0 +1,188 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPClothAddForceAtPosDecl(); +CKERROR CreatePClothAddForceAtPosProto(CKBehaviorPrototype **pproto); +int PClothAddForceAtPos(const CKBehaviorContext& behcontext); +CKERROR PClothAddForceAtPosCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_Pos, + bbI_Magnitute, + bbI_Radius, + bbI_ForceMode, +}; + + + +//************************************ +// Method: FillBehaviorPClothAddForceAtPosDecl +// FullName: FillBehaviorPClothAddForceAtPosDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothAddForceAtPosDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAddForceAtPos"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Applies a radial force (or impulse) at a particular position. All vertices within radius will be affected with a quadratic drop-off. "); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x3f47037b,0x737a60f0)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothAddForceAtPosProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothAddForceAtPosProto +// FullName: CreatePClothAddForceAtPosProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothAddForceAtPosProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAddForceAtPos"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothAddForceAtPos + + PClothAddForceAtPos is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Applies a radial force (or impulse) at a particular position. All vertices + within radius will be affected with a quadratic drop-off.
+ + Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + + + @see pCloth::addForceAtPos() + + +

Technical Information

+ + \image html PClothAddForceAtPos.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+ Position: Position to apply force at. +
+ Magnitude: Magnitude of the force/impulse to apply. +
+ Radius: The sphere radius in which particles will be affected. +
+ Force Mode: The mode to use when applying the force/impulse. + (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange). +
+ + */ + + + + proto->SetBehaviorCallbackFct( PClothAddForceAtPosCB ); + proto->DeclareInParameter("Position",CKPGUID_VECTOR); + proto->DeclareInParameter("Magnitude",CKPGUID_FLOAT); + proto->DeclareInParameter("Radius",CKPGUID_FLOAT); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothAddForceAtPos); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothAddForceAtPos +// FullName: PClothAddForceAtPos +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothAddForceAtPos(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + pCloth *cloth = GetPMan()->getCloth(target->GetID()); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + VxVector position= GetInputParameterValue(beh,bbI_Pos); + float magnitude= GetInputParameterValue(beh,bbI_Magnitute); + float radius= GetInputParameterValue(beh,bbI_Radius); + int forceMode = GetInputParameterValue(beh,bbI_ForceMode); + + cloth->addForceAtPos(position,magnitude,radius,(ForceMode)forceMode); + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothAddForceAtPosCB +// FullName: PClothAddForceAtPosCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothAddForceAtPosCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} diff --git a/usr/Src/Behaviors/pCloth/PClothAddForceAtVertex.cpp b/usr/Src/Behaviors/pCloth/PClothAddForceAtVertex.cpp new file mode 100644 index 0000000..e4817dc --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PClothAddForceAtVertex.cpp @@ -0,0 +1,188 @@ +#include +#include "pCommon.h" + + + + +CKObjectDeclaration *FillBehaviorPClothAddForceAtVertexDecl(); +CKERROR CreatePClothAddForceAtVertexProto(CKBehaviorPrototype **pproto); +int PClothAddForceAtVertex(const CKBehaviorContext& behcontext); +CKERROR PClothAddForceAtVertexCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_VertexIndex, + bbI_Force, + bbI_ForceMode +}; + + + +//************************************ +// Method: FillBehaviorPClothAddForceAtVertexDecl +// FullName: FillBehaviorPClothAddForceAtVertexDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothAddForceAtVertexDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PClothAddForceAtVertex"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Applies a force (or impulse) defined in the global coordinate frame, to a particular vertex of the cloth"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x506e7b29,0xd3a2720)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothAddForceAtVertexProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothAddForceAtVertexProto +// FullName: CreatePClothAddForceAtVertexProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothAddForceAtVertexProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PClothAddForceAtVertex"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PClothAddForceAtVertex + + PClothAddForceAtVertex is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Applies a force (or impulse) defined in the global coordinate frame, to a particular + vertex of the cloth.
+ + + Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + + + @see pCloth::addForceAtVertex() + + +

Technical Information

+ + \image html PClothAddForceAtVertex.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target cloth reference. +
+ Vertex Index: Number of the vertex to add the force at. +
+ Force: Force/impulse to add, defined in the global frame. +
+ Force Mode: The mode to use when applying the force/impulse. + (see #ForceMode, supported modes are FM_Force, FM_Impulse, FM_Acceleration, FM_VelocityChange) +
+ + */ + + + + proto->SetBehaviorCallbackFct( PClothAddForceAtVertexCB ); + proto->DeclareInParameter("Vertex Index",CKPGUID_INT); + proto->DeclareInParameter("Force",CKPGUID_VECTOR); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PClothAddForceAtVertex); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PClothAddForceAtVertex +// FullName: PClothAddForceAtVertex +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PClothAddForceAtVertex(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + pCloth *cloth = GetPMan()->getCloth(target->GetID()); + if (!cloth) + { + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + int vertexIndex = GetInputParameterValue(beh,bbI_VertexIndex); + VxVector force = GetInputParameterValue(beh,bbI_Force); + int forceMode = GetInputParameterValue(beh,bbI_ForceMode); + + cloth->addForceAtVertex(force,vertexIndex,(ForceMode)forceMode); + + + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothAddForceAtVertexCB +// FullName: PClothAddForceAtVertexCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothAddForceAtVertexCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + } + break; + } + return CKBR_OK; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pCloth/PClothBB.cpp b/usr/Src/Behaviors/pCloth/PClothBB.cpp new file mode 100644 index 0000000..7f89a6e --- /dev/null +++ b/usr/Src/Behaviors/pCloth/PClothBB.cpp @@ -0,0 +1,776 @@ +#include +#include "pCommon.h" + + + +CKObjectDeclaration *FillBehaviorPClothDecl(); +CKERROR CreatePClothProto(CKBehaviorPrototype **pproto); +int PCloth(const CKBehaviorContext& behcontext); +CKERROR PClothCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + + bbI_AttachmentFlags=E_CS_FLAGS+2, + bbI_TargetWorld = E_CS_FLAGS+3, + + +}; + + +enum bSettings +{ + bbS_USE_DEFAULT_WORLD, + bbS_ADD_ATTRIBUTES +}; + +//************************************ +// Method: FillBehaviorPClothDecl +// FullName: FillBehaviorPClothDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPClothDecl() +{ + + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PCloth"); + od->SetCategory("Physic/Cloth"); + od->SetDescription("Creates or modifies a cloth."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7901564e,0x7fdb5d76)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePClothProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePClothProto +// FullName: CreatePClothProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePClothProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCloth"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PCloth + + PCloth is categorized in \ref Clothes + +

Description

+ Apply to a 3DEntity
+ Creates or modifies a cloth.
+ +

Technical Information

+ + \image html PCloth.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target: Target reference. The entity can not be a rigid body or a shub shape! +
+
+ + Thickness: Thickness of the cloth. + + The thickness is usually a fraction of the overall extent of the cloth and + should not be set to a value greater than that. A good value is the maximal + distance between two adjacent cloth particles in their rest pose. Visual + artifacts or collision problems may appear if the thickness is too small. + + Default: 0.01
+ Range: [0,inf) + + @see pCloth.setThickness()
+ + Density : Density of the cloth (mass per area). + + Default: 1.0
+ Range: (0,inf)
+ +
+ + + + Bending Stiffness: Bending stiffness of the cloth in the range 0 to 1. + + Only has an effect if the flag PCF_Bending is set. + + Default: 1.0
+ Range: [0,1] + + @see PCF_Bending pCloth.setBendingStiffness() + + + + + +
+ Stretching Stiffness: Stretching stiffness of the cloth in the range 0 to 1. + + \note: stretching stiffness must be larger than 0. + + Default: 1.0
+ Range: (0,1] + + @see pCloth.setStretchingStiffness() + +
+
+ + +
+ Damping: Spring damping of the cloth in the range 0 to 1. + + Only has an effect if the flag PCF_Damping is set. + + Default: 0.5
+ Range: [0,1] + + @see PCF_Damping pCloth.setDampingCoefficient() + +
+
+ + +
+ FrictionFriction coefficient in the range 0 to 1. + + Defines the damping of the velocities of cloth particles that are in contact. + + Default: 0.5
+ Range: [0,1] + + @see pCloth.setFriction() + +
+
+ +
+ Pressure : + + If the flag PCF_Pressure is set, this variable defines the volume + of air inside the mesh as volume = pressure * restVolume. + + For pressure < 1 the mesh contracts w.r.t. the rest shape + For pressure > 1 the mesh expands w.r.t. the rest shape + + Default: 1.0
+ Range: [0,inf) + + @see PCF_pressure pCloth.setPressure() + +
+
+ + + +
+
+ +
+ Tear Factor: + + If the flag PCF_Tearable is set, this variable defines the + elongation factor that causes the cloth to tear. + + Must be larger than 1. + Make sure meshData.maxVertices and the corresponding buffers + in meshData are substantially larger (e.g. 2x) than the number + of original vertices since tearing will generate new vertices. + + When the buffer cannot hold the new vertices anymore, tearing stops. + + Default: 1.5
+ Range: (1,inf) + + @see pCloth.setTearFactor() + +
+
+ +
+ Collision Response Coefficient: + + Defines a factor for the impulse transfer from cloth to colliding rigid bodies. + + Only has an effect if PCF_CollisionTwoWay is set. + + Default: 0.2
+ Range: [0,inf) + + @see PCF_CollisionTwoWay pCloth.setCollisionResponseCoefficient() + +
+
+ +
+ +
+
+ + + +
+ Attachment Response Coefficient: Defines a factor for the impulse transfer from cloth to attached rigid bodies. + + Only has an effect if the mode of the attachment is set to nx_cloth_attachment_twoway. + + Default: 0.2
+ Range: [0,1] + + @see pCloth.attachToShape pCloth.attachToCollidingShapes pCloth.attachVertexToShape pCloth.setAttachmentResponseCoefficient() + +
+
+ +
+ Attachment Tear Factor: + + If the flag PCF_Tearable is set in the attachment method of pCloth, + this variable defines the elongation factor that causes the attachment to tear. + + Must be larger than 1. + + Default: 1.5
+ Range: (1,inf) + + @see pCloth.setAttachmentTearFactor() pCloth.attachToShape pCloth.attachToCollidingShapes pCloth.attachVertexToShape + +
+
+ +
+ To Fluid Response Coefficient: + + Defines a factor for the impulse transfer from this cloth to colliding fluids. + + Only has an effect if the PCF_FluidCollision flag is set. + + Default: 1.0
+ Range: [0,inf) + + Note: Large values can cause instabilities + + @see pClothDesc.flags pClothDesc.fromFluidResponseCoefficient +
+
+ +
+ From Fluid Response Coefficient: + + Defines a factor for the impulse transfer from colliding fluids to this cloth. + + Only has an effect if the PCF_FluidCollision flag is set. + + Default: 1.0
+ Range: [0,inf) + + Note: Large values can cause instabilities + + @see pClothDesc.flags pClothDesc.ToFluidResponseCoefficient + +
+
+ +
+ Min Adhere Velocity: + + If the PCF_Adhere flag is set the cloth moves partially in the frame + of the attached actor. + + This feature is useful when the cloth is attached to a fast moving character. + In that case the cloth adheres to the shape it is attached to while only + velocities below the parameter minAdhereVelocity are used for secondary effects. + + Default: 1.0 + Range: [0,inf) + + @see PCF_AdHere + + + +
+
+ +
+ Solver Iterations: + + Number of solver iterations. + + Note: Small numbers make the simulation faster while the cloth gets less stiff. + + Default: 5 + Range: [1,inf) + + @see pCloth.setSolverIterations() +
+
+ +
+ External acceleration : + + External acceleration which affects all non attached particles of the cloth. + + Default: (0,0,0) + + @see pCloth.setExternalAcceleration() + +
+
+ +
+ Wind Acceleration: + + Acceleration which acts normal to the cloth surface at each vertex. + + Default: (0,0,0) + + @see pCloth.setWindAcceleration() + + +
+
+ +
+ Wake Up Counter: + + The cloth wake up counter. + + Range: [0,inf)
+ Default: 20.0f*0.02f + + @see pCloth.wakeUp() pCloth.putToSleep() + +
+
+ +
+ Sleep Linear Velocity: + + Maximum linear velocity at which cloth can go to sleep. + + If negative, the global default will be used. + + Range: [0,inf)
+ Default: -1.0 + + @see pCloth.setSleepLinearVelocity() pCloth.getSleepLinearVelocity() + +
+
+ + +
+ Collision Group: + + Sets which collision group this cloth is part of. + + Range: [0, 31] + Default: 0 + + pCloth.setCollisionGroup() + +
+
+ +
+ Valid Bounds: + + If the flag PCF_ValidBounds is set, this variable defines the volume + outside of which cloth particle are automatically removed from the simulation. + + @see PCF_ValidBounds pCloth.setValidBounds() + + +
+
+ +
+ Relative Grid Spacing: + + This parameter defines the size of grid cells for collision detection. + + The cloth is represented by a set of world aligned cubical cells in broad phase. + The size of these cells is determined by multiplying the length of the diagonal + of the AABB of the initial cloth size with this constant. + + Range: [0.01,inf)
+ Default: 0.25 + +
+
+ + +
+ Flags: + + Cloth flags. + + Default: Gravity + + @see pClothFlag + +
+
+ + +
+ Attachment Flags: + + Attachment flags. + + Default: PCAF_ClothAttachmentTwoway + + @see pClothAttachmentFlag + +
+
+ +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager #pCloth
+ +

VSL


+ + \include PClothCreate.vsl + + */ + + + + proto->SetBehaviorCallbackFct( PClothCB ); + + proto->DeclareInParameter("Thickness",CKPGUID_FLOAT,"0.01f"); + proto->DeclareInParameter("Density",CKPGUID_FLOAT,"1.0f"); + proto->DeclareInParameter("Bending Stiffness",CKPGUID_FLOAT,"1.0f"); + proto->DeclareInParameter("Stretching Stiffness",CKPGUID_FLOAT,"1.0f"); + + proto->DeclareInParameter("Damping Coefficient",CKPGUID_FLOAT,"0.50f"); + + proto->DeclareInParameter("Friction",CKPGUID_FLOAT,"0.5f"); + proto->DeclareInParameter("Pressure",CKPGUID_FLOAT,"1.0f"); + proto->DeclareInParameter("Tear Factor",CKPGUID_FLOAT,"1.5f"); + proto->DeclareInParameter("Collision Response Coefficient",CKPGUID_FLOAT,"0.2f"); + + proto->DeclareInParameter("Attachment Response Coefficient",CKPGUID_FLOAT,"0.2f"); + proto->DeclareInParameter("AttachmentTearFactor",CKPGUID_FLOAT,"1.5f"); + proto->DeclareInParameter("ToFluidResponseCoefficient",CKPGUID_FLOAT,"1.0f"); + proto->DeclareInParameter("FromFluidResponseCoefficient",CKPGUID_FLOAT,"1.0f"); + + proto->DeclareInParameter("MinAdhereVelocity",CKPGUID_FLOAT,"1.0f"); + proto->DeclareInParameter("SolverIterations",CKPGUID_INT,"5"); + proto->DeclareInParameter("ExternalAcceleration",CKPGUID_VECTOR); + proto->DeclareInParameter("WindAcceleration",CKPGUID_VECTOR); + + proto->DeclareInParameter("WakeUpCounter",CKPGUID_FLOAT,"0.4f"); + proto->DeclareInParameter("SleepLinearVelocity",CKPGUID_FLOAT,"-1.0f"); + proto->DeclareInParameter("CollisionGroup",CKPGUID_INT); + proto->DeclareInParameter("ValidBounds",CKPGUID_BOX); + + proto->DeclareInParameter("RelativeGridSpacing",CKPGUID_FLOAT,"0.25f"); + proto->DeclareInParameter("Flags",VTE_CLOTH_FLAGS,"Gravity"); + proto->DeclareInParameter("Tear Vertex Color",CKPGUID_COLOR,"1.0f"); + proto->DeclareInParameter("Target World Reference",CKPGUID_3DENTITY,"pDefaultWorld"); + proto->DeclareInParameter("Attachment Flags",VTE_CLOTH_ATTACH_FLAGS); + + + proto->DeclareInParameter("Core Body Reference",CKPGUID_3DENTITY,""); + + proto->DeclareInParameter("Metal Impulse Threshold",CKPGUID_FLOAT,"50"); + proto->DeclareInParameter("Metal Penetration Depth",CKPGUID_FLOAT,"0.5"); + proto->DeclareInParameter("Metal Max Deformation Distance",CKPGUID_FLOAT,"0.5"); + + //proto->DeclareSetting("Use Default World",CKPGUID_BOOL,"TRUE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PCloth); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PCloth +// FullName: PCloth +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PCloth(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + +#ifdef DONLGE + if(!PhysicManager::DongleHasAdvancedVersion) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : no license !"); + beh->ActivateOutput(0); + return 0; + } + +#endif + + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + + CK3dEntity*worldRef = (CK3dEntity *) beh->GetInputParameterObject(E_CS_WORLD_REFERENCE); + if (!worldRef) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : invalid world reference !"); + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + + CK3dEntity*metalCoreRef = (CK3dEntity *) beh->GetInputParameterObject(E_CS_ATTACHMENT_FLAGS +1); + if (!metalCoreRef) + { + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : invalid world reference !"); + //beh->ActivateOutput(0); + //return CKBR_PARAMETERERROR; + } + + + pWorld *world = GetPMan()->getWorld(worldRef->GetID()); + if (!world) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : couldn't find world !"); + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + pRigidBody*body = world->getBody(target); + if(body) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Cannot create cloth : target can not be a rigid body !"); + beh->ActivateOutput(0); + return CKBR_OWNERERROR; + } + + NxShape *shape = world->getShapeByEntityID(target->GetID()); + if(shape) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Cannot create cloth : target can not be a shape !"); + beh->ActivateOutput(0); + return CKBR_OWNERERROR; + } + + + pClothDesc *descr = new pClothDesc(); + + using namespace vtTools::ParameterTools; + using namespace vtTools::BehaviorTools; + descr->thickness = GetInputParameterValue(beh,E_CS_THICKNESS); + descr->density = GetInputParameterValue(beh,E_CS_DENSITY); + descr->bendingStiffness = GetInputParameterValue(beh,E_CS_BENDING_STIFFNESS); + descr->stretchingStiffness = GetInputParameterValue(beh,E_CS_STRETCHING_STIFFNESS); + descr->dampingCoefficient = GetInputParameterValue(beh,E_CS_DAMPING_COEFFICIENT); + descr->friction = GetInputParameterValue(beh,E_CS_FRICTION); + descr->pressure = GetInputParameterValue(beh,E_CS_PRESSURE); + descr->tearFactor = GetInputParameterValue(beh,E_CS_TEAR_FACTOR); + descr->collisionResponseCoefficient = GetInputParameterValue(beh,E_CS_COLLISIONRESPONSE_COEFFICIENT); + descr->attachmentResponseCoefficient = GetInputParameterValue(beh,E_CS_ATTACHMENTRESPONSE_COEFFICIENT); + descr->attachmentTearFactor = GetInputParameterValue(beh,E_CS_ATTACHMENT_TEAR_FACTOR); + descr->toFluidResponseCoefficient = GetInputParameterValue(beh,E_CS_TO_FLUID_RESPONSE_COEFFICIENT); + + descr->fromFluidResponseCoefficient = GetInputParameterValue(beh,E_CS_FROM_FLUIDRESPONSE_COEFFICIENT); + descr->minAdhereVelocity = GetInputParameterValue(beh,E_CS_MIN_ADHERE_VELOCITY); + descr->solverIterations = GetInputParameterValue(beh,E_CS_SOLVER_ITERATIONS); + + + descr->externalAcceleration = GetInputParameterValue(beh,E_CS_EXTERN_ALACCELERATION); + descr->windAcceleration = GetInputParameterValue(beh,E_CS_WIND_ACCELERATION); + descr->wakeUpCounter = GetInputParameterValue(beh,E_CS_WAKE_UP_COUNTER); + + descr->sleepLinearVelocity = GetInputParameterValue(beh,E_CS_SLEEP_LINEAR_VELOCITY); + descr->collisionGroup = GetInputParameterValue(beh,E_CS_COLLISIONG_ROUP); + + descr->validBounds = GetInputParameterValue(beh,E_CS_VALID_BOUNDS); + descr->relativeGridSpacing = GetInputParameterValue(beh,E_CS_RELATIVE_GRID_SPACING); + + descr->flags = GetInputParameterValue(beh,E_CS_FLAGS); + descr->tearVertexColor = GetInputParameterValue(beh,E_CS_TEAR_VERTEX_COLOR); + descr->attachmentFlags = (pClothAttachmentFlag)GetInputParameterValue(beh,E_CS_ATTACHMENT_FLAGS); + + + float metalImpulsThresold = GetInputParameterValue(beh,E_CS_ATTACHMENT_FLAGS + 2); + float metalPenetrationDepth = GetInputParameterValue(beh,E_CS_ATTACHMENT_FLAGS + 3); + float metalMaxDeform= GetInputParameterValue(beh,E_CS_ATTACHMENT_FLAGS + 4); + + + descr->worldReference = worldRef->GetID(); + + //descr->setToDefault(); +// descr->flags = descr->flags | PCF_Bending; + + pCloth *cloth = world->getCloth(target); + if (!cloth) + { + cloth = pFactory::Instance()->createCloth(target,*descr); + if (!cloth) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : factory object failed !"); + } + } + +// descr->flags = descr->flags | PCF_AttachToCore; + + + if (cloth) + { + cloth->setThickness(descr->thickness); + cloth->setBendingStiffness(descr->bendingStiffness); + cloth->setStretchingStiffness(descr->stretchingStiffness); + cloth->setDampingCoefficient(descr->dampingCoefficient); + cloth->setFriction(descr->friction); + cloth->setPressure(descr->pressure); + cloth->setTearFactor(descr->tearFactor); + cloth->setCollisionResponseCoefficient(descr->collisionResponseCoefficient); + cloth->setAttachmentResponseCoefficient(descr->attachmentResponseCoefficient); + cloth->setAttachmentTearFactor(descr->attachmentTearFactor); + cloth->setToFluidResponseCoefficient(descr->toFluidResponseCoefficient); + cloth->setFromFluidResponseCoefficient(descr->fromFluidResponseCoefficient); + cloth->setMinAdhereVelocity(descr->minAdhereVelocity); + cloth->setSolverIterations(descr->solverIterations); + cloth->setExternalAcceleration(descr->externalAcceleration); + cloth->setWindAcceleration(descr->windAcceleration); + cloth->setSleepLinearVelocity(descr->sleepLinearVelocity); + cloth->setGroup(descr->collisionGroup); + cloth->setValidBounds(descr->validBounds); + cloth->setFlags(descr->flags); + + } + + int flags = GetInputParameterValue(beh,bbI_AttachmentFlags); + + if (descr->flags & PCF_AttachToParentMainShape ) + { + if (target->GetParent()) + { + CK3dEntity *bodyReference = pf->getMostTopParent(target); + if (bodyReference) + { + pRigidBody *body = GetPMan()->getBody(bodyReference); + if (body) + { + cloth->attachToShape((CKBeObject*)bodyReference,flags); + } + } + } + } + + + + if (descr->flags & PCF_AttachToCollidingShapes) + { + cloth->attachToCollidingShapes(flags); + } + + + + if (descr->flags & PCF_AttachToCore) + { + if (metalCoreRef) + { + pRigidBody*metalBody = world->getBody(metalCoreRef); + if (!metalBody) + { + + + pObjectDescr objDesc; + objDesc.flags =(BodyFlags)(BF_Collision|BF_Gravity|BF_Moving); + objDesc.hullType = HT_Capsule; + objDesc.density = 0.1f; + metalBody = pFactory::Instance()->createCapsule(metalCoreRef,worldRef,&objDesc,0); + if (metalBody) + { + cloth->attachToCore(metalCoreRef,metalImpulsThresold,metalPenetrationDepth,metalMaxDeform); + } + + } + } + } + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PClothCB +// FullName: PClothCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PClothCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { +/* + DWORD useDWorld; + beh->GetLocalParameterValue(bbS_USE_DEFAULT_WORLD,&useDWorld); + beh->EnableInputParameter(bbI_TargetWorld,!useDWorld); +*/ + + + /*DWORD ADamp; + beh->GetLocalParameterValue(bbI_ADamp,&ADamp); + beh->EnableInputParameter(bbI_ADamp,ADamp);*/ + + + } + break; + } + return CKBR_OK; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pCollision/PCGoupTriggerEvent.cpp b/usr/Src/Behaviors/pCollision/PCGoupTriggerEvent.cpp new file mode 100644 index 0000000..8b0568d --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PCGoupTriggerEvent.cpp @@ -0,0 +1,303 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPCGroupTriggerEventDecl(); +CKERROR CreatePCGroupTriggerEventProto(CKBehaviorPrototype **pproto); +int PCGroupTriggerEvent(const CKBehaviorContext& behcontext); +CKERROR PCGroupTriggerEventCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPCGroupTriggerEventDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PCGroupTriggerEvent"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Triggers output if elements of a group stays within, enters or leaves a body ."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0xd8c142a,0x4ce04f7b)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePCGroupTriggerEventProto); + od->SetCompatibleClassId(CKCID_GROUP); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePCGroupTriggerEventProto +// FullName: CreatePCGroupTriggerEventProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePCGroupTriggerEventProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCGroupTriggerEvent"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PCGroupTriggerEvent + + PCGroupTriggerEvent is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Triggers outputs if the body enters,stays or leaves another body .
+ See pBTriggerEvent.cmo for example. + +

Technical Information

+ + \image html PCGroupTriggerEvent.png + + In: triggers the process +
+ + No Event: Nothing touched. +
+ Entering: Body entered. +
+ Leaving: Body leaved. +
+ Stay: Inside body . +
+ + Target Group: The group which the bb outputs triggers for. +
+ Touched Object: The touched body. +
+ +

Warning

+ The body must be dynamic. +
+
+

Note


+ + +
+
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForce().
+ + */ + + //proto->DeclareInParameter("Extra Filter",VTF_TRIGGER,"0"); + //proto->DeclareInParameter("Remove Event",CKPGUID_BOOL,"0"); + + proto->DeclareInput("In"); + proto->DeclareInput("Next"); + + proto->DeclareOutput("No Event"); + proto->DeclareOutput("Entering"); + proto->DeclareOutput("Stay"); + proto->DeclareOutput("Leaving"); + proto->DeclareOutput("Has More"); + + + proto->DeclareOutParameter("Trigger Object",CKPGUID_3DENTITY,0); + proto->DeclareOutParameter("Touched Object",CKPGUID_3DENTITY,0); + proto->DeclareOutParameter("Trigger Event",VTF_TRIGGER,0); + + proto->DeclareLocalParameter("currentIndex", CKPGUID_INT); + + + //proto->DeclareSetting("Trigger on Enter",CKPGUID_BOOL,"FALSE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PCGroupTriggerEvent); + *pproto = proto; + return CK_OK; +} +enum bOutputs +{ + bbO_None, + bbO_Enter, + bbO_Stay, + bbO_Leave, + bbO_HasMore, +}; + +enum bInputs +{ + bbI_Init, + bbI_Next, +}; + +bool isInGroup(CKGroup *src, CK3dEntity* testObject) +{ + + if (src && testObject) + { + for (int i = 0 ; i < src->GetObjectCount() ; i++ ) + { + CK3dEntity *ent = (CK3dEntity*)src->GetObject(i); + if(ent) + { + if (ent==testObject) + { + return true; + } + } + } + } + + return false; +} + +int getEventCount() +{ + + int result= 0; + int nbEntries = GetPMan()->getTriggers().Size() ; + + for (int i = 0 ; i < GetPMan()->getTriggers().Size(); i++ ) + { + pTriggerEntry &entry = *GetPMan()->getTriggers().At(i); + if(!entry.triggered) + result++; + } + + return result; + +} + + +//************************************ +// Method: PCGroupTriggerEvent +// FullName: PCGroupTriggerEvent +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PCGroupTriggerEvent(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CKGroup *target = (CKGroup *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + //int extraFilter = GetInputParameterValue(beh,0); + //int remove = GetInputParameterValue(beh,1); + + int nbOfEvents = getEventCount(); + if (!nbOfEvents) + { + beh->ActivateOutput(bbO_None); + return 0; + } + + /************************************************************************/ + /* handle init */ + /************************************************************************/ + if( beh->IsInputActive(bbI_Init) ) + { + beh->ActivateInput(bbI_Init,FALSE); + + int index = 0;beh->SetLocalParameterValue(0,&index); + + //we have some, forward to in 1:next + if (nbOfEvents) + { + beh->ActivateInput(bbI_Next,TRUE); + beh->ActivateOutput(bbO_HasMore); + } + } + + /************************************************************************/ + /* handle trigger 'next' */ + /************************************************************************/ + if( beh->IsInputActive(bbI_Next) ) + { + beh->ActivateInput(bbI_Next,FALSE); + + int index = 0;beh->GetLocalParameterValue(0,&index); + for (int i = index ; i < GetPMan()->getTriggers().Size(); i++ ) + { + pTriggerEntry &entry = *GetPMan()->getTriggers().At(i); + if (!entry.triggered) + { + if (isInGroup(target,entry.triggerShapeEnt)) + { + beh->SetOutputParameterObject(0,entry.triggerShapeEnt); + beh->SetOutputParameterObject(1,entry.otherObject); + + SetOutputParameterValue(beh,2,entry.triggerEvent); + entry.triggered = true; + + //trigger out + if(entry.triggerEvent == NX_TRIGGER_ON_ENTER) + { + beh->ActivateOutput(bbO_Enter); + } + if(entry.triggerEvent == NX_TRIGGER_ON_STAY) + { + beh->ActivateOutput(bbO_Stay); + } + if(entry.triggerEvent == NX_TRIGGER_ON_LEAVE) + { + beh->ActivateOutput(bbO_Leave); + } + + //store index + beh->SetLocalParameterValue(1,&index); + int nbOfLeftEvents = getEventCount(); + if (nbOfLeftEvents) + { + beh->ActivateOutput(bbO_HasMore); + return 0; + }else + { + beh->ActivateOutput(bbO_None); + return 0; + } + } + } + } + } + + /************************************************************************/ + /* */ + /************************************************************************/ + return 0; +} + +//************************************ +// Method: PCGroupTriggerEventCB +// FullName: PCGroupTriggerEventCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PCGroupTriggerEventCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCollision/PCHasContact.cpp b/usr/Src/Behaviors/pCollision/PCHasContact.cpp new file mode 100644 index 0000000..26fb837 --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PCHasContact.cpp @@ -0,0 +1,195 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorCollisionsCheckADecl(); +CKERROR CreateCollisionsCheckAProto(CKBehaviorPrototype **pproto); +int CollisionsCheckA(const CKBehaviorContext& behcontext); +CKERROR CollisionsCheckACB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorCollisionsCheckADecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PCHasContact"); + od->SetDescription("Checks for a collision on a given body"); + od->SetCategory("Physic/Collision"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x5189255c,0x18134074)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateCollisionsCheckAProto); + //od->SetCompatibleClassId(CKCID_BEOBJECT); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + return od; +} + +CKERROR CreateCollisionsCheckAProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCHasContact"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->SetBehaviorCallbackFct( CollisionsCheckACB ); + proto->DeclareInput("Check"); + + proto->DeclareOutput("Collision"); + proto->DeclareOutput("No Collision"); + + proto->DeclareOutParameter("Collider", CKPGUID_3DENTITY); + proto->DeclareOutParameter("Position", CKPGUID_VECTOR); + proto->DeclareOutParameter("Normal", CKPGUID_VECTOR); + proto->DeclareOutParameter("Face Index", CKPGUID_INT); + proto->DeclareOutParameter("Normal Force", CKPGUID_VECTOR); + proto->DeclareOutParameter("Friction Force", CKPGUID_VECTOR); + + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(CollisionsCheckA); + + *pproto = proto; + return CK_OK; +} + + +int CollisionsCheckA(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0, FALSE); + + ////////////////////////////////////////////////////////////////////////// + //we haven't't seen yet, create a local array : + + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_PARAMETERERROR; + + pRigidBody *body = GetPMan()->getBody(target); + if (body) + { + VxVector pos; + VxVector normal; + float depth; + int size = body->getCollisions().Size(); + + CK3dEntity *colliderEntity = NULL; + + if (!size) + { + beh->ActivateOutput(1); + beh->SetOutputParameterObject(0,NULL); + return 0; + + } + if (size) + { + + + + for (int i = 0; i < body->getCollisions().Size() ; i ++) + { + pCollisionsEntry *entry = body->getCollisions().At(i); + if (entry) + { + CK3dEntity *shapeA = (CK3dEntity*)GetPMan()->GetContext()->GetObject(entry->shapeEntityA); + CK3dEntity *shapeB = (CK3dEntity*)GetPMan()->GetContext()->GetObject(entry->shapeEntityB); + pRigidBody *collider = NULL; + body->getCollisions().RemoveAt(i); + if( target == body->GetVT3DObject()) + { + if (entry->bodyA && entry->bodyA == body) + { + collider = entry->bodyB; + colliderEntity = shapeB; + } + if (entry->bodyB && entry->bodyB == body) + { + collider = entry->bodyA; + colliderEntity = shapeA; + } + }else // its a sub shape collision + { + if (shapeA && shapeA == target ) + { + colliderEntity = shapeB; + } + if (shapeB && shapeB == target) + { + colliderEntity = shapeA; + + } + } + if (colliderEntity) + { + beh->SetOutputParameterObject(0,colliderEntity); + beh->ActivateOutput(0); + SetOutputParameterValue(beh,1,entry->point); + SetOutputParameterValue(beh,2,entry->faceNormal); + SetOutputParameterValue(beh,3,entry->faceIndex); + SetOutputParameterValue(beh,4,entry->sumNormalForce); + SetOutputParameterValue(beh,5,entry->sumFrictionForce); + body->getCollisions().Clear(); + return 0; + } + } + } + } +/* int size = world->getCollisions().Size(); + for (int i = 0; i < world->getCollisions().Size() ; i ++) + { + pCollisionsEntry *entry = world->getCollisions().At(i); + if (entry) + { + printf("asdasd"); + int o = 2; + o++; + } + + } +*/ + //CK3dEntity *collider = world->CIsInCollision(target,pos,normal,depth); + /* + if (collider) + { + beh->SetOutputParameterObject(0,collider); + beh->SetOutputParameterValue(1,&pos); + beh->SetOutputParameterValue(2,&normal); + beh->SetOutputParameterValue(3,&depth); + beh->ActivateOutput(0); + return 0; + }else + { + + beh->ActivateOutput(1); + }*/ + } + } + beh->ActivateOutput(1); + return 0; +} + +CKERROR CollisionsCheckACB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + } + break; + } + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/pCollision/PCIgnorePair.cpp b/usr/Src/Behaviors/pCollision/PCIgnorePair.cpp new file mode 100644 index 0000000..1553669 --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PCIgnorePair.cpp @@ -0,0 +1,131 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPCIgnorePairDecl(); +CKERROR CreatePCIgnorePairProto(CKBehaviorPrototype **pproto); +int PCIgnorePair(const CKBehaviorContext& behcontext); +CKERROR PCIgnorePairCB(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorPCIgnorePairDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PCIgnorePair"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Enables/Disables collision between two bodies."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x63f648f7,0x13c7097f)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePCIgnorePairProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePCIgnorePairProto +// FullName: CreatePCIgnorePairProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePCIgnorePairProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCIgnorePair"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + + proto->SetBehaviorCallbackFct( PCIgnorePairCB ); + + proto->DeclareInParameter("Object A",CKPGUID_3DENTITY); + proto->DeclareInParameter("Object B",CKPGUID_3DENTITY); + proto->DeclareInParameter("Ignore",CKPGUID_BOOL,"0"); + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PCIgnorePair); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PCIgnorePair +// FullName: PCIgnorePair +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PCIgnorePair(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + CK3dEntity *targetA = (CK3dEntity *) beh->GetInputParameterObject(0); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(1); + int ignore = GetInputParameterValue(beh,2); + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(target); + + if(world){ + world->cIgnorePair(targetA,targetB,ignore); + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PCIgnorePairCB +// FullName: PCIgnorePairCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PCIgnorePairCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCollision/PCTriggerEvent.cpp b/usr/Src/Behaviors/pCollision/PCTriggerEvent.cpp new file mode 100644 index 0000000..752ae6b --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PCTriggerEvent.cpp @@ -0,0 +1,246 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPCTriggerEventDecl(); +CKERROR CreatePCTriggerEventProto(CKBehaviorPrototype **pproto); +int PCTriggerEvent(const CKBehaviorContext& behcontext); +CKERROR PCTriggerEventCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPCTriggerEventDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PCTriggerEvent"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Triggers output if body stays,enter or leaves a body ."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7e866b0f,0x5935367c)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePCTriggerEventProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePCTriggerEventProto +// FullName: CreatePCTriggerEventProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePCTriggerEventProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCTriggerEvent"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PCTriggerEvent + + PCTriggerEvent is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Triggers outputs if the body enters,stays or leaves another body .
+ See pBTriggerEvent.cmo for example. + +

Technical Information

+ + \image html PCTriggerEvent.png + + In: triggers the process +
+ + No Event: Nothing touched. +
+ Entering: Body entered. +
+ Leaving: Body leaved. +
+ Stay: Inside body . +
+ + Target: The 3D Entity associated to the rigid body. +
+ Touched Object: The touched body. +
+ +

Warning

+ The body must be dynamic. +
+
+

Note


+ + +
+
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForce().
+ + */ + proto->DeclareInput("In"); + proto->DeclareInput("Next"); + proto->DeclareOutput("No Event"); + proto->DeclareOutput("Entering"); + proto->DeclareOutput("Stay"); + proto->DeclareOutput("Leaving"); + + proto->DeclareOutParameter("Touched Object",CKPGUID_3DENTITY,0); + + //proto->DeclareSetting("Trigger on Enter",CKPGUID_BOOL,"FALSE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PCTriggerEvent); + *pproto = proto; + return CK_OK; +} +enum bOutputs +{ + bbO_None, + bbO_Enter, + bbO_Stay, + bbO_Leave, +}; + +//************************************ +// Method: PCTriggerEvent +// FullName: PCTriggerEvent +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PCTriggerEvent(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + using namespace vtTools::BehaviorTools; + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + //world->getScene()->setFilterOps() + // body exists already ? clean and delete it : + pRigidBody*result = GetPMan()->getBody(target); + if (!result) + { + beh->ActivateOutput(bbO_None); + return 0; + } + + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + if (GetPMan()->getTriggers().Size()==0) + { + beh->ActivateOutput(bbO_None); + return 0; + } + + if (GetPMan()->getTriggers().Size()) + { + + + int nbEntries = GetPMan()->getTriggers().Size() ; + for (int i = 0 ; i < GetPMan()->getTriggers().Size(); i++ ) + { + pTriggerEntry &entry = *GetPMan()->getTriggers().At(i); + + if (!entry.triggered) + { + + if(entry.triggerEvent == NX_TRIGGER_ON_ENTER) + { + beh->ActivateOutput(bbO_Enter); + } + if(entry.triggerEvent == NX_TRIGGER_ON_STAY) + { + beh->ActivateOutput(bbO_Stay); + } + if(entry.triggerEvent == NX_TRIGGER_ON_LEAVE) + { + beh->ActivateOutput(bbO_Leave); + } + + nbEntries--; + entry.triggered = true; + + + NxActor *triggerActor = &entry.shapeA->getActor(); + NxActor *otherActor = &entry.shapeB->getActor(); + + pRigidBody *triggerBody = NULL; + pRigidBody *otherBody = NULL; + + if (triggerActor) + { + triggerBody = static_cast(triggerActor->userData); + } + + if (otherActor) + { + otherBody = static_cast(otherActor->userData); + } + + if (triggerBody && result == triggerBody) + { + CK_ID id = otherBody->getEntID(); + CKObject *entOut= (CK3dEntity*)ctx->GetObject(id); + beh->SetOutputParameterObject(0,entOut); + } + + if (otherBody && result == otherBody ) + { + CK_ID id = triggerBody->getEntID(); + CKObject *entOut= (CK3dEntity*)ctx->GetObject(id); + beh->SetOutputParameterObject(0,entOut); + } + + } + } + }else{ + beh->SetOutputParameterObject(0,NULL); + } + } + return 0; +} + +//************************************ +// Method: PCTriggerEventCB +// FullName: PCTriggerEventCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PCTriggerEventCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCollision/PWOBBOverlap.cpp b/usr/Src/Behaviors/pCollision/PWOBBOverlap.cpp new file mode 100644 index 0000000..d3b6404 --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PWOBBOverlap.cpp @@ -0,0 +1,377 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPWOBBOverlapDecl(); +CKERROR CreatePWOBBOverlapProto(CKBehaviorPrototype **pproto); +int PWOBBOverlap(const CKBehaviorContext& behcontext); +CKERROR PWOBBOverlapCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPWOBBOverlapDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PWOBBOverlap"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Performs an overlap test against masked shape groups.Outputs an object only!"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x16a46d79,0xa951a4a)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePWOBBOverlapProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePWOBBOverlapProto +// FullName: CreatePWOBBOverlapProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +enum bInput +{ + + //bbI_WorldRef, + bbI_SIZE, + bbI_Center, + bbI_Ref, + bbI_ShapesType, + bbI_Accurate, + bbI_Groups, + bbI_Mask, + + +}; + +enum bbS +{ + bbS_Result=0, + bbS_Index, + bbS_Size, + bbS_Groups=3, + bbS_Mask=4 +}; + +enum bbOT +{ + bbOT_Yes, + bbOT_No, + bbOT_Finish, + bbOT_Next, +}; +CKERROR CreatePWOBBOverlapProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWOBBOverlap"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PWOBBOverlap + + + PWOBBOverlap is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Performs an overlap test against masked shape groups.
+ See PWOverlaps.cmo for example. + +

Technical Information

+ + \image html PWOBBOverlap.png + + In: triggers the process +
+ Next: Iterate through next hit. +
+
+ + Yes: Hit occured. +
+ No: No hits. +
+ Finish: Last hit. +
+ Next: Loop out. +
+
+ + + Target: World Reference. pDefaultWorld! +
+ Size: The box dimension. +
+ Center: The box center in world space.If shape reference is given, then its transforming this value in its local space. +
+ Shapes Types: Adds static and/or dynamic shapes to the test. +
+ Accurate: True to test the sphere against the actual shapes, false to test against the AABBs only. +
+ Groups: Includes specific groups to the test. +
+ Groups Mask: Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask +
+ + +
+

Note


+ + +
+
+ + Is utilizing #pWorld::overlapOBBShapes()
+ + */ + + proto->DeclareInput("In"); + proto->DeclareInput("Next"); + + + + + proto->DeclareOutput("Yes"); + proto->DeclareOutput("No"); + proto->DeclareOutput("Finish"); + proto->DeclareOutput("Next"); + + proto->DeclareInParameter("Size",CKPGUID_VECTOR); + proto->DeclareInParameter("Center",CKPGUID_VECTOR); + proto->DeclareInParameter("Shape Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Shapes Type",VTF_SHAPES_TYPE); + proto->DeclareInParameter("Accurate",CKPGUID_BOOL); + proto->DeclareInParameter("Groups",CKPGUID_INT); + proto->DeclareInParameter("Filter Mask",VTS_FILTER_GROUPS); + + + proto->DeclareLocalParameter("result", CKPGUID_GROUP); + proto->DeclareLocalParameter("index", CKPGUID_INT); + proto->DeclareLocalParameter("size", CKPGUID_INT); + + proto->DeclareSetting("Groups",CKPGUID_BOOL,"false"); + proto->DeclareSetting("Groups Mask",CKPGUID_BOOL,"false"); + + + proto->DeclareOutParameter("Touched Body",CKPGUID_3DENTITY); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetBehaviorCallbackFct( PWOBBOverlapCB ); + proto->SetFunction(PWOBBOverlap); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PWOBBOverlap +// FullName: PWOBBOverlap +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PWOBBOverlap(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + using namespace vtTools::ParameterTools; + + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(target->GetID()); + if (!world) + { + beh->ActivateOutput(bbOT_No); + return 0; + } + + NxScene *scene = world->getScene(); + if (!scene) + { + beh->ActivateOutput(bbOT_No); + return 0; + } + + if( beh->IsInputActive(0) ) + { + + beh->ActivateInput(0,FALSE); + + + CKGroup *carray = (CKGroup*)beh->GetLocalParameterObject(bbS_Result); + if (carray) + { + //carray->clear(); + carray->Clear(); + }else + { + + CK_OBJECTCREATION_OPTIONS creaoptions = (CK_OBJECTCREATION_OPTIONS)(CK_OBJECTCREATION_NONAMECHECK|CK_OBJECTCREATION_DYNAMIC); + carray = (CKGroup*)ctx()->CreateObject(CKCID_GROUP,"asdasd",creaoptions); + + } + + beh->SetLocalParameterObject(0,carray); + + int hitIndex = 0; + beh->SetLocalParameterValue(bbS_Index,&hitIndex); + int hitSize = 0; + beh->SetLocalParameterValue(bbS_Size,&hitSize); + + + + + ////////////////////////////////////////////////////////////////////////// + + int types = GetInputParameterValue(beh,bbI_ShapesType); + int accurate = GetInputParameterValue(beh,bbI_Accurate); + + + + DWORD groupsEnabled; + DWORD groups = 0xffffffff; + beh->GetLocalParameterValue(bbS_Groups,&groupsEnabled); + if (groupsEnabled) + { + groups = GetInputParameterValue(beh,bbI_Groups); + } + + pGroupsMask *gmask = NULL; + DWORD mask; + beh->GetLocalParameterValue(bbS_Mask,&mask); + if (mask) + { + CKParameter *maskP = beh->GetInputParameter(bbI_Mask)->GetRealSource(); + gmask->bits0 = GetValueFromParameterStruct(maskP,0); + gmask->bits1 = GetValueFromParameterStruct(maskP,1); + gmask->bits2 = GetValueFromParameterStruct(maskP,2); + gmask->bits3 = GetValueFromParameterStruct(maskP,3); + + } + + VxVector size = GetInputParameterValue(beh,bbI_SIZE); + VxVector center = GetInputParameterValue(beh,bbI_Center); + + VxBbox box; + box.SetCenter(center,size/2); + box.SetDimension(center,size); + + + + CK3dEntity *shape = (CK3dEntity*)beh->GetInputParameterObject(bbI_Ref); + + int nbShapes = world->overlapOBBShapes(box,shape,(pShapesType)types,carray,groups,gmask,accurate); + if (nbShapes) + { + beh->ActivateOutput(bbOT_Yes); + beh->ActivateInput(1,TRUE); + + }else{ + beh->ActivateOutput(bbOT_No); + } + } + + if( beh->IsInputActive(1) ) + { + + beh->ActivateInput(1,FALSE); + CKGroup *carray = (CKGroup*)beh->GetLocalParameterObject(bbS_Result); + + ////////////////////////////////////////////////////////////////////////// + if (carray) + { + if (carray->GetObjectCount()) + { + CKBeObject *hit = carray->GetObject(carray->GetObjectCount()-1); + if (hit) + { + + + beh->SetOutputParameterObject(0,hit); + carray->RemoveObject(hit); + + + + + if (carray->GetObjectCount()) + { + beh->ActivateOutput(bbOT_Next); + }else + { + beh->ActivateOutput(bbOT_Finish); + CKDestroyObject(carray); + } + + } + }else{ + beh->ActivateOutput(bbOT_Finish); + CKDestroyObject(carray); + } + }else + { + beh->ActivateOutput(bbOT_Finish); + CKDestroyObject(carray); + } + + } + + return 0; +} + +//************************************ +// Method: PWOBBOverlapCB +// FullName: PWOBBOverlapCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PWOBBOverlapCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + + DWORD groups; + beh->GetLocalParameterValue(bbS_Groups,&groups); + beh->EnableInputParameter(bbI_Groups,groups); + + DWORD mask; + beh->GetLocalParameterValue(bbS_Mask,&mask); + beh->EnableInputParameter(bbI_Mask,mask); + + + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCollision/PWRayCastAllShapes.cpp b/usr/Src/Behaviors/pCollision/PWRayCastAllShapes.cpp new file mode 100644 index 0000000..ba8fc6c --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PWRayCastAllShapes.cpp @@ -0,0 +1,502 @@ +#include +#include "pCommon.h" + +#include "pWorldCallbacks.h" + + + +CKObjectDeclaration *FillBehaviorPWRayCastAllShapeDecl(); +CKERROR CreatePWRayCastAllShapeProto(CKBehaviorPrototype **pproto); +int PWRayCastAllShape(const CKBehaviorContext& behcontext); +CKERROR PWRayCastAllShapeCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPWRayCastAllShapeDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PWRayCastAllShapes"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Performs a ray cast test"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7a2308ad,0x7a777c6e)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePWRayCastAllShapeProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePWRayCastAllShapeProto +// FullName: CreatePWRayCastAllShapeProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +enum bInput +{ + + //bbI_WorldRef, + bbI_RayOri, + bbI_RayOriRef, + bbI_RayDir, + bbI_RayDirRef, + bbI_Length, + bbI_ShapesType, + bbI_Groups, + bbI_Mask, + + +}; + +enum bbS +{ + bbS_Hints=2, + bbS_Groups=3, + bbS_Mask=4 +}; + +enum bbO +{ + + bbO_Shape, + bbO_Impact, + bbO_Normal, + bbO_FaceIndex, + bbO_Distance, + bbO_UV, + bbO_Material + +}; +enum bbOT +{ + bbOT_Yes, + bbOT_No, + bbOT_Finish, + bbOT_Next, + +}; +CKERROR CreatePWRayCastAllShapeProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWRayCastAllShapes"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PWRayCastAllShapes + + + PWRayCastAllShapes is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Performs a ray cast test. Outputs hit informations.
+ See PWRayCasts.cmo for example. + +

Technical Information

+ + \image html PWRayCastAllShapes.png + + In: Triggers the process. +
+ Next: Next Hit. +
+ + + Yes: Hit occured. +
+ No: No hits. +
+ Finish: Last hit. +
+ Next: Loop out. +
+ + + + + + Target: World Reference. pDefaultWorld! +
+ Ray Origin: Start of the ray. +
+ Ray Origin Reference: Reference object to determine the start of the ray. Ray Origin becomes transformed if an object is given. +
+ Ray Direction: Direction of the ray. +
+ Ray Direction Reference: Reference object to determine the direction of the ray. Ray Direction becomes transformed if an object is given. Up axis will be used then. +
+ Length: Lenght of the ray. +
+ Shapes Types: Adds static and/or dynamic shapes to the test. +
+ + Groups: Includes specific groups to the test. +
+ Groups Mask: Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask +
+ + Touched Body: The touched body. +
+ Impact Position: Hit point in world space. +
+ Face Normal: Normal of the hit. +
+ Face Index: +
+ Distance: Distance between ray start and hit. +
+ UV: not used yet ! +
+ Material Index: Index of the internal physic material. +
+ + + +
+
+ + Is utilizing #pWorld::raycastAllShapes()
+ + */ + + proto->DeclareInput("In"); + proto->DeclareInput("Next"); + + + + + proto->DeclareOutput("Yes"); + proto->DeclareOutput("No"); + proto->DeclareOutput("Finish"); + proto->DeclareOutput("Next"); + + + proto->DeclareInParameter("Ray Origin",CKPGUID_VECTOR); + proto->DeclareInParameter("Ray Origin Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Ray Direction",CKPGUID_VECTOR); + proto->DeclareInParameter("Ray Direction Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Length",CKPGUID_FLOAT); + proto->DeclareInParameter("Shapes Type",VTF_SHAPES_TYPE); + + proto->DeclareInParameter("Groups",CKPGUID_INT); + proto->DeclareInParameter("Filter Mask",VTS_FILTER_GROUPS); + + + proto->DeclareLocalParameter("result", CKPGUID_POINTER); + proto->DeclareLocalParameter("index", CKPGUID_INT); + + proto->DeclareSetting("RayCast Hints",VTF_RAY_HINTS,"0"); + proto->DeclareSetting("Groups",CKPGUID_BOOL,"false"); + proto->DeclareSetting("Groups Mask",CKPGUID_BOOL,"false"); + + + proto->DeclareOutParameter("Touched Body",CKPGUID_3DENTITY); + proto->DeclareOutParameter("Impact Position",CKPGUID_VECTOR); + proto->DeclareOutParameter("Face Normal",CKPGUID_VECTOR); + proto->DeclareOutParameter("Face Index",CKPGUID_INT); + proto->DeclareOutParameter("Distance",CKPGUID_FLOAT); + proto->DeclareOutParameter("UV",CKPGUID_2DVECTOR); + proto->DeclareOutParameter("Material Index",CKPGUID_INT); + + //proto->DeclareSetting("Trigger on Enter",CKPGUID_BOOL,"FALSE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetBehaviorCallbackFct( PWRayCastAllShapeCB ); + proto->SetFunction(PWRayCastAllShape); + *pproto = proto; + return CK_OK; +} +enum bOutputs +{ + bbO_None, + bbO_Enter, + bbO_Stay, + bbO_Leave, +}; + +//************************************ +// Method: PWRayCastAllShape +// FullName: PWRayCastAllShape +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PWRayCastAllShape(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + using namespace vtTools::ParameterTools; + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(target->GetID()); + if (!world) + { + beh->ActivateOutput(bbOT_No); + return 0; + } + + NxScene *scene = world->getScene(); + if (!scene) + { + beh->ActivateOutput(bbOT_No); + return 0; + } + + if( beh->IsInputActive(0) ) + { + + beh->ActivateInput(0,FALSE); + + + pRayCastHits *carray = NULL; + beh->GetLocalParameterValue(0,&carray); + if (carray) + { + carray->clear(); + }else + { + carray = new pRayCastHits(); + } + + beh->SetLocalParameterValue(0,&carray); + + int hitIndex = 0; + beh->SetLocalParameterValue(1,&hitIndex); + + + + ////////////////////////////////////////////////////////////////////////// + CK3dEntity *rayOriRef= (CK3dEntity *) beh->GetInputParameterObject(bbI_RayOriRef); + CK3dEntity *rayDirRef= (CK3dEntity *) beh->GetInputParameterObject(bbI_RayDirRef); + + //ori : + VxVector ori = GetInputParameterValue(beh,bbI_RayOri); + VxVector oriOut = ori; + if (rayOriRef) + { + rayOriRef->Transform(&oriOut,&ori); + } + //dir : + VxVector dir = GetInputParameterValue(beh,bbI_RayDir); + VxVector dirOut = dir; + if (rayDirRef) + { + VxVector dir,up,right; + rayDirRef->GetOrientation(&dir,&up,&right); + rayDirRef->TransformVector(&dirOut,&up); + } + + float lenght = GetInputParameterValue(beh,bbI_Length); + int types = GetInputParameterValue(beh,bbI_ShapesType); + + VxRay ray; + ray.m_Direction = dirOut; + ray.m_Origin = oriOut; + + pRayCastReport &report = *world->getRaycastReport(); + report.setCurrentBehavior(beh->GetID()); + + + + pRaycastBit hints; + beh->GetLocalParameterValue(bbS_Hints,&hints); + + + DWORD groupsEnabled; + DWORD groups = 0xffffffff; + beh->GetLocalParameterValue(bbS_Groups,&groupsEnabled); + if (groupsEnabled) + { + groups = GetInputParameterValue(beh,bbI_Groups); + } + + pGroupsMask *gmask = NULL; + DWORD mask; + beh->GetLocalParameterValue(bbS_Mask,&mask); + if (mask) + { + CKParameter *maskP = beh->GetInputParameter(bbI_Mask)->GetRealSource(); + gmask->bits0 = GetValueFromParameterStruct(maskP,0); + gmask->bits1 = GetValueFromParameterStruct(maskP,1); + gmask->bits2 = GetValueFromParameterStruct(maskP,2); + gmask->bits3 = GetValueFromParameterStruct(maskP,3); + + } + + int nbShapes = world->raycastAllShapes(ray,(pShapesType)types,groups,lenght,hints,gmask); + + if (nbShapes) + { + beh->ActivateOutput(bbOT_Yes); + beh->ActivateInput(1,TRUE); + + }else{ + beh->ActivateOutput(bbOT_No); + } + } + + if( beh->IsInputActive(1) ) + { + + beh->ActivateInput(1,FALSE); + pRayCastHits *carray = NULL; + beh->GetLocalParameterValue(0,&carray); + + ////////////////////////////////////////////////////////////////////////// + if (carray) + { + if (carray->size()) + { + NxRaycastHit *hit = carray->at(carray->size()-1); + if (hit) + { + + pRaycastBit hints; + beh->GetLocalParameterValue(bbS_Hints,&hints); + + ////////////////////////////////////////////////////////////////////////// + // + // + if (hints & RCH_Shape) + { + NxShape *shape = hit->shape; + if (shape) + { + + pSubMeshInfo *sInfo = static_cast(shape->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + beh->SetOutputParameterObject(bbO_Shape,obj); + } + + } + + } + } + + ////////////////////////////////////////////////////////////////////////// + // + // + if (hints & RCH_Distance) + { + beh->SetOutputParameterValue(bbO_Distance,&hit->distance); + } + if (hints & RCH_FaceIndex) + { + beh->SetOutputParameterValue(bbO_FaceIndex,&hit->internalFaceID); + } + + if (hints & RCH_Impact) + { + VxVector vec = getFrom(hit->worldImpact); + beh->SetOutputParameterValue(bbO_Impact,&vec); + } + + if (hints & RCH_FaceNormal) + { + VxVector vec = getFrom(hit->worldNormal); + beh->SetOutputParameterValue(bbO_Normal,&vec); + } + + if (hints & RCH_Material) + { + int vec = hit->materialIndex; + beh->SetOutputParameterValue(bbO_Material,&vec); + + } + if (hints & RCH_FaceIndex) + { + int vec = hit->faceID; + beh->SetOutputParameterValue(bbO_FaceIndex,&vec); + } + + + carray->pop_back(); + + if (carray->size()) + { + beh->ActivateOutput(bbOT_Next); + }else + { + beh->ActivateOutput(bbOT_Finish); + } + + + } + } + } + + } + + return 0; +} + +//************************************ +// Method: PWRayCastAllShapeCB +// FullName: PWRayCastAllShapeCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PWRayCastAllShapeCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + DWORD flags; + beh->GetLocalParameterValue(bbS_Hints,&flags); + + beh->EnableOutputParameter(bbO_Shape,flags & RCH_Shape); + beh->EnableOutputParameter(bbO_Impact,flags & RCH_Impact); + beh->EnableOutputParameter(bbO_Normal,flags & RCH_Normal); + beh->EnableOutputParameter(bbO_FaceIndex,flags & RCH_FaceIndex); + beh->EnableOutputParameter(bbO_Distance,flags & RCH_Distance); + beh->EnableOutputParameter(bbO_UV,flags & RCH_UV); + beh->EnableOutputParameter(bbO_Material,flags & RCH_Material); + + + DWORD groups; + beh->GetLocalParameterValue(bbS_Groups,&groups); + beh->EnableInputParameter(bbI_Groups,groups); + + DWORD mask; + beh->GetLocalParameterValue(bbS_Mask,&mask); + beh->EnableInputParameter(bbI_Mask,mask); + + + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCollision/PWRayCastAnyBounds.cpp b/usr/Src/Behaviors/pCollision/PWRayCastAnyBounds.cpp new file mode 100644 index 0000000..151edf6 --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PWRayCastAnyBounds.cpp @@ -0,0 +1,324 @@ +#include +#include "pCommon.h" + +#include "pWorldCallbacks.h" + + +CKObjectDeclaration *FillBehaviorPWRayCastAnyBoundsDecl(); +CKERROR CreatePWRayCastAnyBoundsProto(CKBehaviorPrototype **pproto); +int PWRayCastAnyBounds(const CKBehaviorContext& behcontext); +CKERROR PWRayCastAnyBoundsCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPWRayCastAnyBoundsDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PWRayCastAnyBounds"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Performs a ray cast test"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x6e155f2f,0x6d634931)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePWRayCastAnyBoundsProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePWRayCastAnyBoundsProto +// FullName: CreatePWRayCastAnyBoundsProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +enum bInput +{ + bbI_RayOri, + bbI_RayOriRef, + bbI_RayDir, + bbI_RayDirRef, + bbI_Length, + bbI_ShapesType, + bbI_Groups, + bbI_Mask, +}; + +enum bbS +{ + bbS_Groups=0, + bbS_Mask=1 +}; + + +enum bbOT +{ + bbOT_Yes, + bbOT_No, + +}; +CKERROR CreatePWRayCastAnyBoundsProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWRayCastAnyBounds"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PWRayCastAnyBounds + + PWRayCastAnyBounds is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Performs a ray cast test.
+ See PWRayCasts.cmo for example. + + +

Technical Information

+ + \image html PWRayCastAnyBounds.png + + In: Triggers the process. +
+ + + + Yes: Hit occured. +
+ No: No hits. +
+ + + + + + + Target: World Reference. pDefaultWorld! +
+ Ray Origin: Start of the ray. +
+ Ray Origin Reference: Reference object to determine the start of the ray. Ray Origin becomes transformed if an object is given. +
+ Ray Direction: Direction of the ray. +
+ Ray Direction Reference: Reference object to determine the direction of the ray. Ray Direction becomes transformed if an object is given. Up axis will be used then. +
+ Length: Lenght of the ray. +
+ Shapes Types: Adds static and/or dynamic shapes to the test. +
+ + Groups: Includes specific groups to the test. +
+ Groups Mask: Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask +
+ +

Note

+ This is as parameter opertion avaiable. See \ref CollisionsOps ! +
+
+ + Is utilizing #pWorld::raycastAnyBounds().
+ + */ + + proto->DeclareInput("In"); + + proto->DeclareOutput("Yes"); + proto->DeclareOutput("No"); + + + + proto->DeclareInParameter("Ray Origin",CKPGUID_VECTOR); + proto->DeclareInParameter("Ray Origin Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Ray Direction",CKPGUID_VECTOR); + proto->DeclareInParameter("Ray Direction Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Length",CKPGUID_FLOAT); + proto->DeclareInParameter("Shapes Type",VTF_SHAPES_TYPE); + + proto->DeclareInParameter("Groups",CKPGUID_INT); + proto->DeclareInParameter("Filter Mask",VTS_FILTER_GROUPS); + + + proto->DeclareSetting("Groups",CKPGUID_BOOL,"false"); + proto->DeclareSetting("Groups Mask",CKPGUID_BOOL,"false"); + + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetBehaviorCallbackFct( PWRayCastAnyBoundsCB ); + proto->SetFunction(PWRayCastAnyBounds); + *pproto = proto; + return CK_OK; +} +enum bOutputs +{ + bbO_None, + bbO_Enter, + bbO_Stay, + bbO_Leave, +}; + +//************************************ +// Method: PWRayCastAnyBounds +// FullName: PWRayCastAnyBounds +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PWRayCastAnyBounds(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + using namespace vtTools::ParameterTools; + + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(target->GetID()); + if (!world) + { + beh->ActivateOutput(bbOT_No); + return 0; + } + + NxScene *scene = world->getScene(); + if (!scene) + { + beh->ActivateOutput(bbOT_No); + return 0; + } + + if( beh->IsInputActive(0) ) + { + + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + CK3dEntity *rayOriRef= (CK3dEntity *) beh->GetInputParameterObject(bbI_RayOriRef); + CK3dEntity *rayDirRef= (CK3dEntity *) beh->GetInputParameterObject(bbI_RayDirRef); + + //ori : + VxVector ori = GetInputParameterValue(beh,bbI_RayOri); + VxVector oriOut = ori; + if (rayOriRef) + { + rayOriRef->Transform(&oriOut,&ori); + } + + //dir : + VxVector dir = GetInputParameterValue(beh,bbI_RayDir); + VxVector dirOut = dir; + if (rayDirRef) + { + VxVector dir,up,right; + rayDirRef->GetOrientation(&dir,&up,&right); + rayDirRef->TransformVector(&dirOut,&up); + } + + float lenght = GetInputParameterValue(beh,bbI_Length); + int types = GetInputParameterValue(beh,bbI_ShapesType); + + + + VxRay ray; + ray.m_Direction = dirOut; + ray.m_Origin = oriOut; + + pRayCastReport &report = *world->getRaycastReport(); + report.setCurrentBehavior(beh->GetID()); + + int groupsEnabled; + DWORD groups = 0xffffffff; + beh->GetLocalParameterValue(bbS_Groups,&groupsEnabled); + if (groupsEnabled) + { + groups = GetInputParameterValue(beh,bbI_Groups); + } + + pGroupsMask *gmask = NULL; + DWORD mask; + beh->GetLocalParameterValue(bbS_Mask,&mask); + if (mask) + { + CKParameter *maskP = beh->GetInputParameter(bbI_Mask)->GetRealSource(); + gmask->bits0 = GetValueFromParameterStruct(maskP,0); + gmask->bits1 = GetValueFromParameterStruct(maskP,1); + gmask->bits2 = GetValueFromParameterStruct(maskP,2); + gmask->bits3 = GetValueFromParameterStruct(maskP,3); + + } + + int nbShapes = world->raycastAnyBounds(ray,(pShapesType)types,gmask,groups,lenght); + + + + if (nbShapes) + { + beh->ActivateOutput(bbOT_Yes); + + }else{ + beh->ActivateOutput(bbOT_No); + } + } + + return 0; +} + +//************************************ +// Method: PWRayCastAnyBoundsCB +// FullName: PWRayCastAnyBoundsCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PWRayCastAnyBoundsCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + + DWORD groups; + beh->GetLocalParameterValue(bbS_Groups,&groups); + beh->EnableInputParameter(bbI_Groups,groups); + + DWORD mask; + beh->GetLocalParameterValue(bbS_Mask,&mask); + beh->EnableInputParameter(bbI_Mask,mask); + + + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCollision/PWSetCollisionGroupFlag.cpp b/usr/Src/Behaviors/pCollision/PWSetCollisionGroupFlag.cpp new file mode 100644 index 0000000..2140ed7 --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PWSetCollisionGroupFlag.cpp @@ -0,0 +1,128 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPWSetCollisionGroupFlagDecl(); +CKERROR CreatePWSetCollisionGroupFlagProto(CKBehaviorPrototype **pproto); +int PWSetCollisionGroupFlag(const CKBehaviorContext& behcontext); +CKERROR PWSetCollisionGroupFlagCB(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorPWSetCollisionGroupFlagDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PWSetCollisionGroupFlag"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Enables collision between two collisions groups."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x44961cc7,0x2d104ced)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePWSetCollisionGroupFlagProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePWSetCollisionGroupFlagProto +// FullName: CreatePWSetCollisionGroupFlagProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePWSetCollisionGroupFlagProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWSetCollisionGroupFlag"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + proto->SetBehaviorCallbackFct( PWSetCollisionGroupFlagCB ); + + proto->DeclareInParameter("Collisions Group A",CKPGUID_INT,"0"); + proto->DeclareInParameter("Collisions Group A",CKPGUID_INT,"0"); + proto->DeclareInParameter("Enabled",CKPGUID_BOOL,"0"); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PWSetCollisionGroupFlag); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PWSetCollisionGroupFlag +// FullName: PWSetCollisionGroupFlag +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PWSetCollisionGroupFlag(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(target); + int collGA = GetInputParameterValue(beh,0); + int collGB = GetInputParameterValue(beh,1); + int value = GetInputParameterValue(beh,2); + if(world) + world->cSetGroupCollisionFlag(collGA,collGB,value); + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PWSetCollisionGroupFlagCB +// FullName: PWSetCollisionGroupFlagCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PWSetCollisionGroupFlagCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCollision/PWSetFiltering.cpp b/usr/Src/Behaviors/pCollision/PWSetFiltering.cpp new file mode 100644 index 0000000..a99c54a --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PWSetFiltering.cpp @@ -0,0 +1,229 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPWSetFilteringDecl(); +CKERROR CreatePWSetFilteringProto(CKBehaviorPrototype **pproto); +int PWSetFiltering(const CKBehaviorContext& behcontext); +CKERROR PWSetFilteringCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPWSetFilteringDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PWSetFiltering"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Sets the worlds filter settings for contact generation."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7ae099f,0x1f8e6949)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePWSetFilteringProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePWSetFilteringProto +// FullName: CreatePWSetFilteringProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +enum bInput +{ + + bbI_FBool, + bbI_FOp0, + bbI_FOp1, + bbI_FOp2, + bbI_FConst0, + bbI_FConst1, + + +}; +CKERROR CreatePWSetFilteringProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWSetFiltering"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PWSetFiltering + + PWSetFiltering is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Sets the worlds filter settings for contact generation.
+ See pWFiltering.cmo for example. + +

Technical Information

+ + \image html PWSetFiltering.png + + In: triggers the process +
+ + Out: is activated when the process is completed. +
+ + Target: The world reference. Choose pDefaultWord if there are no multiple worlds in use. +
+ + Filter Bool: Setups filtering's boolean value. +
+ + Filter Op 0: Setups filtering operation. +
+ Filter Op 1: Setups filtering operation. +
+ Filter Op 2: Setups filtering operation. +
+ Filter Constant 0: Setups filtering's K0 value. +
+ Filter Constant 1: Setups filtering's K1 value. +
+ +

Note


+ + See \ref CollisionFiltering for more details. + +
+
+ + Is utilizing #pWorld .
+ + */ + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Filter Bool",CKPGUID_BOOL,"true"); + proto->DeclareInParameter("Filter Op 0",VTE_FILTER_OPS,"Or"); + proto->DeclareInParameter("Filter Op 1",VTE_FILTER_OPS,"Or"); + proto->DeclareInParameter("Filter Op 2",VTE_FILTER_OPS,"And"); + proto->DeclareInParameter("Filter Constant 0",VTS_FILTER_GROUPS,"0"); + proto->DeclareInParameter("Filter Constant 1",VTS_FILTER_GROUPS,"0"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PWSetFiltering); + *pproto = proto; + return CK_OK; +} +enum bOutputs +{ + bbO_None, + bbO_Enter, + bbO_Stay, + bbO_Leave, +}; + +//************************************ +// Method: PWSetFiltering +// FullName: PWSetFiltering +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PWSetFiltering(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + using namespace vtTools::ParameterTools; + + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(target->GetID()); + if (!world) + { + beh->ActivateOutput(0); + return 0; + } + + NxScene *scene = world->getScene(); + if (!scene) + { + return 0; + } + + int filterBool = GetInputParameterValue(beh,bbI_FBool); + int fOP0 = GetInputParameterValue(beh,bbI_FOp0); + int fOP1 = GetInputParameterValue(beh,bbI_FOp1); + int fOP2 = GetInputParameterValue(beh,bbI_FOp2); + + CKParameter *fConst0 = beh->GetInputParameter(bbI_FConst0)->GetRealSource(); + + NxGroupsMask mask0; + mask0.bits0 = GetValueFromParameterStruct(fConst0,0); + mask0.bits1 = GetValueFromParameterStruct(fConst0,1); + mask0.bits2 = GetValueFromParameterStruct(fConst0,2); + mask0.bits3 = GetValueFromParameterStruct(fConst0,3); + + CKParameter *fConst1 = beh->GetInputParameter(bbI_FConst1)->GetRealSource(); + + NxGroupsMask mask1; + mask1.bits0 = GetValueFromParameterStruct(fConst1,0); + mask1.bits1 = GetValueFromParameterStruct(fConst1,1); + mask1.bits2 = GetValueFromParameterStruct(fConst1,2); + mask1.bits3 = GetValueFromParameterStruct(fConst1,3); + + + scene->setFilterBool(filterBool); + scene->setFilterOps((NxFilterOp)fOP0,(NxFilterOp)fOP1,(NxFilterOp)fOP2); + + scene->setFilterConstant0(mask0); + scene->setFilterConstant1(mask1); + + //scene->raycastAnyShape() + + beh->ActivateOutput(0); + + + + return 0; +} + +//************************************ +// Method: PWSetFilteringCB +// FullName: PWSetFilteringCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PWSetFilteringCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pCollision/PWSphereOverlap.cpp b/usr/Src/Behaviors/pCollision/PWSphereOverlap.cpp new file mode 100644 index 0000000..9874d9a --- /dev/null +++ b/usr/Src/Behaviors/pCollision/PWSphereOverlap.cpp @@ -0,0 +1,377 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPWOverlapSphereDecl(); +CKERROR CreatePWOverlapSphereProto(CKBehaviorPrototype **pproto); +int PWOverlapSphere(const CKBehaviorContext& behcontext); +CKERROR PWOverlapSphereCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPWOverlapSphereDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PWOverlapSphere"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Performs an overlap test against masked shape groups.Outputs an object only!"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x12254994,0x4e200bf8)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePWOverlapSphereProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePWOverlapSphereProto +// FullName: CreatePWOverlapSphereProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +enum bInput +{ + + //bbI_WorldRef, + bbI_Radius, + bbI_Center, + bbI_Ref, + bbI_ShapesType, + bbI_Accurate, + bbI_Groups, + bbI_Mask, + + +}; + +enum bbS +{ + bbS_Result=0, + bbS_Index, + bbS_Size, + bbS_Groups=3, + bbS_Mask=4 +}; + +enum bbOT +{ + bbOT_Yes, + bbOT_No, + bbOT_Finish, + bbOT_Next, +}; +CKERROR CreatePWOverlapSphereProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PWOverlapSphere"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PWOverlapSphere + + + PWOverlapSphere is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Performs an overlap test against masked shape groups.Outputs an object only.
+ See PWOverlaps.cmo for example. + +

Technical Information

+ + \image html PWOverlapSphere.png + + In: triggers the process +
+ Next: Next Hit. +
+ + Next: Iterate through next hit. +
+ Yes: Hit occured. +
+ No: No hits. +
+ Finish: Last hit. +
+ Next: Loop out. +
+ + Target: World Reference. pDefaultWorld! +
+ Radius: The sphere radius. +
+ Center: The spheres center in world space.If shape reference is given, then its transforming this value in its local space. +
+ Shapes Types: Adds static and/or dynamic shapes to the test. +
+ Accurate: True to test the sphere against the actual shapes, false to test against the AABBs only. +
+ Groups: Includes specific groups to the test. +
+ Groups Mask: Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask +
+ + +
+

Note


+ + +
+
+ + Is utilizing #pWorld::overlapSphereShapes()
+ + */ + + proto->DeclareInput("In"); + proto->DeclareInput("Next"); + + + + + proto->DeclareOutput("Yes"); + proto->DeclareOutput("No"); + proto->DeclareOutput("Finish"); + proto->DeclareOutput("Next"); + + proto->DeclareInParameter("Radius",CKPGUID_FLOAT); + proto->DeclareInParameter("Center",CKPGUID_VECTOR); + proto->DeclareInParameter("Shape Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Shapes Type",VTF_SHAPES_TYPE); + proto->DeclareInParameter("Accurate",CKPGUID_BOOL); + proto->DeclareInParameter("Groups",CKPGUID_INT); + proto->DeclareInParameter("Filter Mask",VTS_FILTER_GROUPS); + + + + + proto->DeclareLocalParameter("result", CKPGUID_GROUP); + proto->DeclareLocalParameter("index", CKPGUID_INT); + proto->DeclareLocalParameter("size", CKPGUID_INT); + + proto->DeclareSetting("Groups",CKPGUID_BOOL,"false"); + proto->DeclareSetting("Groups Mask",CKPGUID_BOOL,"false"); + + + proto->DeclareOutParameter("Touched Body",CKPGUID_3DENTITY); + + + //proto->DeclareSetting("Trigger on Enter",CKPGUID_BOOL,"FALSE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetBehaviorCallbackFct( PWOverlapSphereCB ); + proto->SetFunction(PWOverlapSphere); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PWOverlapSphere +// FullName: PWOverlapSphere +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PWOverlapSphere(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + using namespace vtTools::ParameterTools; + + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(target->GetID()); + if (!world) + { + beh->ActivateOutput(bbOT_No); + return 0; + } + + NxScene *scene = world->getScene(); + if (!scene) + { + beh->ActivateOutput(bbOT_No); + return 0; + } + + if( beh->IsInputActive(0) ) + { + + beh->ActivateInput(0,FALSE); + + + CKGroup *carray = (CKGroup*)beh->GetLocalParameterObject(bbS_Result); + if (carray) + { + //carray->clear(); + carray->Clear(); + }else + { + + CK_OBJECTCREATION_OPTIONS creaoptions = (CK_OBJECTCREATION_OPTIONS)(CK_OBJECTCREATION_NONAMECHECK|CK_OBJECTCREATION_DYNAMIC); + carray = (CKGroup*)ctx()->CreateObject(CKCID_GROUP,"asdasd",creaoptions); + + } + + beh->SetLocalParameterObject(0,carray); + + int hitIndex = 0; + beh->SetLocalParameterValue(bbS_Index,&hitIndex); + int hitSize = 0; + beh->SetLocalParameterValue(bbS_Size,&hitSize); + + + + + ////////////////////////////////////////////////////////////////////////// + + int types = GetInputParameterValue(beh,bbI_ShapesType); + int accurate = GetInputParameterValue(beh,bbI_Accurate); + + + + DWORD groupsEnabled; + DWORD groups = 0xffffffff; + beh->GetLocalParameterValue(bbS_Groups,&groupsEnabled); + if (groupsEnabled) + { + groups = GetInputParameterValue(beh,bbI_Groups); + } + + pGroupsMask *gmask = NULL; + DWORD mask; + beh->GetLocalParameterValue(bbS_Mask,&mask); + if (mask) + { + CKParameter *maskP = beh->GetInputParameter(bbI_Mask)->GetRealSource(); + gmask->bits0 = GetValueFromParameterStruct(maskP,0); + gmask->bits1 = GetValueFromParameterStruct(maskP,1); + gmask->bits2 = GetValueFromParameterStruct(maskP,2); + gmask->bits3 = GetValueFromParameterStruct(maskP,3); + + } + + float radius = GetInputParameterValue(beh,bbI_Radius); + VxVector center = GetInputParameterValue(beh,bbI_Center); + + VxSphere sphere(center,radius); + + CK3dEntity *shape = (CK3dEntity*)beh->GetInputParameterObject(bbI_Ref); + + int nbShapes = world->overlapSphereShapes(sphere,shape,(pShapesType)types,carray,groups,gmask,accurate); + if (nbShapes) + { + beh->ActivateOutput(bbOT_Yes); + beh->ActivateInput(1,TRUE); + + }else{ + beh->ActivateOutput(bbOT_No); + } + } + + if( beh->IsInputActive(1) ) + { + + beh->ActivateInput(1,FALSE); + CKGroup *carray = (CKGroup*)beh->GetLocalParameterObject(bbS_Result); + + ////////////////////////////////////////////////////////////////////////// + if (carray) + { + if (carray->GetObjectCount()) + { + CKBeObject *hit = carray->GetObject(carray->GetObjectCount()-1); + if (hit) + { + + + beh->SetOutputParameterObject(0,hit); + carray->RemoveObject(hit); + + + + + if (carray->GetObjectCount()) + { + beh->ActivateOutput(bbOT_Next); + }else + { + beh->ActivateOutput(bbOT_Finish); + CKDestroyObject(carray); + } + + } + }else{ + beh->ActivateOutput(bbOT_Finish); + CKDestroyObject(carray); + } + }else + { + beh->ActivateOutput(bbOT_Finish); + CKDestroyObject(carray); + } + + } + + return 0; +} + +//************************************ +// Method: PWOverlapSphereCB +// FullName: PWOverlapSphereCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PWOverlapSphereCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + + DWORD groups; + beh->GetLocalParameterValue(bbS_Groups,&groups); + beh->EnableInputParameter(bbI_Groups,groups); + + DWORD mask; + beh->GetLocalParameterValue(bbS_Mask,&mask); + beh->EnableInputParameter(bbI_Mask,mask); + + + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pJoint/D6/JD6.cpp b/usr/Src/Behaviors/pJoint/D6/JD6.cpp new file mode 100644 index 0000000..fd53b55 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/D6/JD6.cpp @@ -0,0 +1,351 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorJSetD6Decl(); +CKERROR CreateJSetD6Proto(CKBehaviorPrototype **pproto); +int JSetD6(const CKBehaviorContext& behcontext); +CKERROR JSetD6CB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_BodyA=0, + bbI_BodyB, + bbI_Anchor, + bbI_AnchorRef, + bbI_Axis, + bbI_AxisRef, + bbI_Coll, + bbI_PMode, + bbI_PDistance, + bbI_PAngle +}; + +//************************************ +// Method: FillBehaviorJSetD6Decl +// FullName: FillBehaviorJSetD6Decl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorJSetD6Decl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6"); + od->SetCategory("Physic/D6"); + od->SetDescription("Sets or modifies a D6 joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7456331,0xc6c58d6)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateJSetD6Proto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateJSetD6Proto +// FullName: CreateJSetD6Proto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateJSetD6Proto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + /*! \page PJD6 + +
+ PJD6 is categorized in \ref Joints +
+
See PJD6.cmo. + +

Description

+ Apply to a 3DEntity
+ Creates or modifies a D6 joint. +
+
+ DOFs removed: 0-6
+ DOFs remaining: 0-6
+
+
+ + This joint type can be configured to model nearly any joint imaginable. Each degree of freedom - both linear and angular - can be selectively locked or freed, and separate limits can be applied to each. The 6 DOF joint provides motor drive on all axes independently, and also allows soft limits. + + The joint axis (localAxis[]) defines the joint's local x-axis. The joint normal (localNormal[]) defines the joint's local y-axis. The local z-axis is computed as a cross product of the first two. + + When constraining the angular motion of the joint, rotation around the x-axis is referred to as twist, rotation around the y-axis as swing1, and rotation around the z-axis as swing2. + + + \image html 6dofaxis.png + + +

Technical Information

+ + \image html PJD6.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body. Leave blank to create a joint constraint with the world. +
+
+ +
+ + Anchor:A point in world space coordinates. See pJointD6::setGlobalAnchor(). +
+ Anchor Reference: A helper entity to transform a local anchor into the world space. +
+ +
+ + Axis: An in world space. See pJointD6::setGlobalAxis(). +
+ Axis Up Reference: A helper entity to transform a local axis into the world space. +
+
+
+ + Collision: Enable Collision. See pJointD6::enableCollision(). +
+ +
+ Projection Mode: Joint projection mode. See pJointD6::setProjectionMode() and #ProjectionMode. +
+ + Projection Distance: If any joint projection is used, it is also necessary to set + projectionDistance to a small value greater than zero. When the joint error is larger than projectionDistance the SDK will change it so that the joint error is equal to projectionDistance. Setting projectionDistance too + small will introduce unwanted oscillations into the simulation.See pJointD6::setProjectionDistance(). +
+ + Projection Angle: Angle must be greater than 0.02f .If its smaller then current algo gets too close to a singularity. See pJointD6::setProjectionAngle(). +
+ + + + +
+

Warning

+ The body must be dynamic. +
+
+ +

VSL : Creation


+ + \include D6Creation.vsl + +
+
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createD6Joint().
+ + */ + + proto->SetBehaviorCallbackFct( JSetD6CB ); + + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Anchor",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY,"0.0f"); + + proto->DeclareInParameter("Axis",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Collision",CKPGUID_BOOL,"TRUE"); + + proto->DeclareInParameter("Projection Mode",VTE_JOINT_PROJECTION_MODE,"0"); + proto->DeclareInParameter("Projection Distance",CKPGUID_FLOAT,"0"); + proto->DeclareInParameter("Projection Angle",CKPGUID_FLOAT,"0"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(JSetD6); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: JSetD6 +// FullName: JSetD6 +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int JSetD6(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) + { + + return CK_OK; + } + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + + } + + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + if(bodyA || bodyB) + { + + pJointD6 *joint =static_cast(worldA->getJoint(target,targetB,JT_D6)); + //anchor : + VxVector anchor = GetInputParameterValue(beh,1); + VxVector anchorOut = anchor; + CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(2); + + if (anchorReference) + { + anchorReference->Transform(&anchorOut,&anchor); + } + + //axis + VxVector axis = GetInputParameterValue(beh,3); + VxVector axisOut = axis; + CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(4); + + if (axisReference) + { + VxVector dir,up,right; + axisReference->GetOrientation(&dir,&up,&right); + axisReference->TransformVector(&axisOut,&up); + } + + int coll = GetInputParameterValue(beh,bbI_Coll); + + ProjectionMode mode =GetInputParameterValue(beh,bbI_PMode); + float distance = GetInputParameterValue(beh,bbI_PDistance); + float angle= GetInputParameterValue(beh,bbI_PAngle); + + + if (!joint) + { + joint = static_cast(pFactory::Instance()->createD6Joint(target,targetB,anchorOut,axisOut,coll)); + } + + ////////////////////////////////////////////////////////////////////////// + //joints parameters : + //set it up : + if (joint) + { + joint->setGlobalAnchor(anchorOut); + joint->setGlobalAxis(axisOut); + joint->enableCollision(coll); + if (mode != 0) + { + joint->setProjectionMode(mode); + joint->setProjectionDistance(distance); + joint->setProjectionAngle(angle); + } + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: JSetD6CB +// FullName: JSetD6CB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR JSetD6CB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + DWORD fmax; + beh->GetLocalParameterValue(0,&fmax); + if (fmax ) + { + beh->EnableInputParameter(6,fmax); + beh->EnableInputParameter(7,fmax); + + }else + { + beh->EnableInputParameter(6,fmax); + beh->EnableInputParameter(7,fmax); + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (target && targetB) + { + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + return CKBR_OK; + + // the physic object A and B : + pRigidBody*bodyA= world->getBody(target); + pRigidBody*bodyB= world->getBody(targetB); + + if(bodyA && bodyB) + { +// pJointHinge2 *joint = static_cast(bodyA->isConnected(targetB)); + /* + if (joint && joint->GetFeedBack()) + { + joint->SetFeedBack(NULL,0,0); + }*/ + } + } + } + } + break; + } + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/pJoint/D6/JD6SetDrive.cpp b/usr/Src/Behaviors/pJoint/D6/JD6SetDrive.cpp new file mode 100644 index 0000000..5ebe4a0 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/D6/JD6SetDrive.cpp @@ -0,0 +1,238 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorJD6SetDriveDecl(); +CKERROR CreateJD6SetDriveProto(CKBehaviorPrototype **pproto); +int JD6SetDrive(const CKBehaviorContext& behcontext); +CKERROR JD6SetDriveCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_BodyA=0, + bbI_BodyB, + bbI_Anchor, + bbI_AnchorRef, + bbI_Axis, + bbI_AxisRef +}; + +//************************************ +// Method: FillBehaviorJD6SetDriveDecl +// FullName: FillBehaviorJD6SetDriveDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorJD6SetDriveDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6SetDrive"); + od->SetCategory("Physic/D6"); + od->SetDescription("Modifies the D6 drive."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x2db16c45,0x695938e4)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateJD6SetDriveProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateJD6SetDriveProto +// FullName: CreateJD6SetDriveProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateJD6SetDriveProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6SetDrive"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PJD6SetDrive + +
+ PJD6SetDrive is categorized in \ref D6BB +
+
See PJD6.cmo. + +

Description

+ Apply to a 3DEntity
+ Modifies a linear or an angular drive. +
+
+

Technical Information

+ + \image html PJD6SetDrive.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body to identfy the joint. +
+
+ + Target Drive: The target drive. See #D6DriveAxis. +
+ Drive: Holds drive settings. See #pJD6Drive. +
+ + See \ref D6AngularDrivesGuide "Angular Drives"
+ + See \ref D6LinearDrivesGuide "Linear Drives"
+ + + +*/ + + proto->SetBehaviorCallbackFct( JD6SetDriveCB ); + + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Target Drive",VTE_JOINT_DRIVE_AXIS,0); + proto->DeclareInParameter("Drive",VTS_JOINT_DRIVE); + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(JD6SetDrive); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: JD6SetDrive +// FullName: JD6SetDrive +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int JD6SetDrive(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) + { + + return CK_OK; + + } + + + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + if(bodyA || bodyB) + { + + pJointD6 *joint =static_cast(worldA->getJoint(target,targetB,JT_D6)); + D6DriveAxis targetDrive = GetInputParameterValue(beh,1); + pJD6Drive drive; + + + CKParameter* pout = beh->GetInputParameter(2)->GetRealSource(); + CK_ID* ids = (CK_ID*)pout->GetReadDataPtr(); + float damping,spring,forceLimit; + int driveMode; + pout = (CKParameterOut*)ctx->GetObject(ids[0]); + pout->GetValue(&damping); + pout = (CKParameterOut*)ctx->GetObject(ids[1]); + pout->GetValue(&spring); + pout = (CKParameterOut*)ctx->GetObject(ids[2]); + pout->GetValue(&forceLimit); + pout = (CKParameterOut*)ctx->GetObject(ids[3]); + pout->GetValue(&driveMode); + + + drive.damping = damping; + drive.spring = spring; + drive.driveType = driveMode; + drive.forceLimit = forceLimit; + + if (joint) + { + switch(targetDrive) + { + + case D6DA_Twist: + joint->setTwistDrive(drive); + break; + case D6DA_Swing: + joint->setSwingDrive(drive); + break; + case D6DA_Slerp: + joint->setSlerpDrive(drive); + break; + case D6DA_X: + joint->setXDrive(drive); + break; + case D6DA_Y: + joint->setYDrive(drive); + break; + case D6DA_Z: + joint->setZDrive(drive); + break; + } + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: JD6SetDriveCB +// FullName: JD6SetDriveCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR JD6SetDriveCB(const CKBehaviorContext& behcontext) +{ + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/pJoint/D6/JD6SetMotionMode.cpp b/usr/Src/Behaviors/pJoint/D6/JD6SetMotionMode.cpp new file mode 100644 index 0000000..6e6ff40 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/D6/JD6SetMotionMode.cpp @@ -0,0 +1,234 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorJD6SetMotionModeDecl(); +CKERROR CreateJD6SetMotionModeProto(CKBehaviorPrototype **pproto); +int JD6SetMotionMode(const CKBehaviorContext& behcontext); +CKERROR JD6SetMotionModeCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_BodyA=0, + bbI_BodyB, + bbI_Anchor, + bbI_AnchorRef, + bbI_Axis, + bbI_AxisRef +}; + +//************************************ +// Method: FillBehaviorJD6SetMotionModeDecl +// FullName: FillBehaviorJD6SetMotionModeDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorJD6SetMotionModeDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6SetMotionMode"); + od->SetCategory("Physic/D6"); + od->SetDescription("Sets the motion freedom mode in a D6 joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x62dc4a7e,0x20736a5e)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateJD6SetMotionModeProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateJD6SetMotionModeProto +// FullName: CreateJD6SetMotionModeProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateJD6SetMotionModeProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6SetMotionMode"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + + + proto->SetBehaviorCallbackFct( JD6SetMotionModeCB ); + + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Motion Axis",VTE_JOINT_MOTION_MODE_AXIS,0); + proto->DeclareInParameter("Motion Mode",VTE_JOINT_MOTION_MODE,0); + + + + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(JD6SetMotionMode); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: JD6SetMotionMode +// FullName: JD6SetMotionMode +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int JD6SetMotionMode(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) + { + + return CK_OK; + } + + + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + if(bodyA || bodyB) + { + + pJointD6 *joint =static_cast(worldA->getJoint(target,targetB,JT_D6)); + int motionAxis = GetInputParameterValue(beh,1); + D6MotionMode motionMode = GetInputParameterValue(beh,2); + + if (joint) + { + switch(motionAxis) + { + + case D6MA_Twist: + joint->setTwistMotionMode(motionMode); + break; + case D6MA_Swing1: + joint->setSwing1MotionMode(motionMode); + break; + case D6MA_Swing2: + joint->setSwing2MotionMode(motionMode); + break; + case D6MA_X: + joint->setXMotionMode(motionMode); + break; + case D6MA_Y: + joint->setYMotionMode(motionMode); + break; + case D6MA_Z: + joint->setZMotionMode(motionMode); + break; + } + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: JD6SetMotionModeCB +// FullName: JD6SetMotionModeCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR JD6SetMotionModeCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + DWORD fmax; + beh->GetLocalParameterValue(0,&fmax); + if (fmax ) + { + beh->EnableInputParameter(6,fmax); + beh->EnableInputParameter(7,fmax); + + }else + { + beh->EnableInputParameter(6,fmax); + beh->EnableInputParameter(7,fmax); + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (target && targetB) + { + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + return CKBR_OK; + + // the physic object A and B : + pRigidBody*bodyA= world->getBody(target); + pRigidBody*bodyB= world->getBody(targetB); + + if(bodyA && bodyB) + { +// pJointHinge2 *joint = static_cast(bodyA->isConnected(targetB)); + /* + if (joint && joint->GetFeedBack()) + { + joint->SetFeedBack(NULL,0,0); + }*/ + } + } + } + } + break; + } + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/pJoint/D6/JD6SetParameters.cpp b/usr/Src/Behaviors/pJoint/D6/JD6SetParameters.cpp new file mode 100644 index 0000000..73a91a4 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/D6/JD6SetParameters.cpp @@ -0,0 +1,171 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorJD6SetParametersDecl(); +CKERROR CreateJD6SetParametersProto(CKBehaviorPrototype **pproto); +int JD6SetParameters(const CKBehaviorContext& behcontext); +CKERROR JD6SetParametersCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_BodyA=0, + bbI_BodyB, + bbI_Anchor, + bbI_AnchorRef, + bbI_Axis, + bbI_AxisRef +}; + +//************************************ +// Method: FillBehaviorJD6SetParametersDecl +// FullName: FillBehaviorJD6SetParametersDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorJD6SetParametersDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6SetParameters"); + od->SetCategory("Physic/D6"); + od->SetDescription("Sets parameters in a D6 joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x4b8207b2,0x57964805)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateJD6SetParametersProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateJD6SetParametersProto +// FullName: CreateJD6SetParametersProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateJD6SetParametersProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6SetParameters"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + + + proto->SetBehaviorCallbackFct( JD6SetParametersCB ); + + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Drive Linear Velocity",CKPGUID_VECTOR); + proto->DeclareInParameter("Drive Angular Velocity",CKPGUID_VECTOR); + proto->DeclareInParameter("Drive Position",CKPGUID_VECTOR); + proto->DeclareInParameter("Drive Orientation",CKPGUID_QUATERNION); + + proto->DeclareInParameter("Ratio",CKPGUID_FLOAT,"0"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(JD6SetParameters); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: JD6SetParameters +// FullName: JD6SetParameters +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int JD6SetParameters(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) + { + + return CK_OK; + } + + + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + if(bodyA || bodyB) + { + + pJointD6 *joint =static_cast(worldA->getJoint(target,targetB,JT_D6)); + VxVector linVel = GetInputParameterValue(beh,1); + VxVector aVel = GetInputParameterValue(beh,2); + VxVector pos = GetInputParameterValue(beh,3); + VxQuaternion rot = GetInputParameterValue(beh,4); + + float ratio = GetInputParameterValue(beh,5); + + + joint->setDriveLinearVelocity(linVel); + joint->setDriveAngularVelocity(aVel); + joint->setRatio(ratio); + + joint->setDrivePosition(pos); + joint->setDriveRotation(rot); + + + + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: JD6SetParametersCB +// FullName: JD6SetParametersCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR JD6SetParametersCB(const CKBehaviorContext& behcontext) +{ + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pJoint/D6/JD6SetSoftLimit.cpp b/usr/Src/Behaviors/pJoint/D6/JD6SetSoftLimit.cpp new file mode 100644 index 0000000..8bf7bb9 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/D6/JD6SetSoftLimit.cpp @@ -0,0 +1,239 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorJD6SetSoftLimitDecl(); +CKERROR CreateJD6SetSoftLimitProto(CKBehaviorPrototype **pproto); +int JD6SetSoftLimit(const CKBehaviorContext& behcontext); +CKERROR JD6SetSoftLimitCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_BodyA=0, + bbI_BodyB, + bbI_Anchor, + bbI_AnchorRef, + bbI_Axis, + bbI_AxisRef +}; + +//************************************ +// Method: FillBehaviorJD6SetSoftLimitDecl +// FullName: FillBehaviorJD6SetSoftLimitDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorJD6SetSoftLimitDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJD6SetSoftLimit"); + od->SetCategory("Physic/D6"); + od->SetDescription("Sets the soft limits in a D6 joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x536d5df9,0x4e5b275c)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateJD6SetSoftLimitProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateJD6SetSoftLimitProto +// FullName: CreateJD6SetSoftLimitProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateJD6SetSoftLimitProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJD6SetSoftLimit"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PJD6SetSoftLimit + + +
+ PJD6SetSoftLimit is categorized in \ref D6 +
+
See PJD6.cmo. + +

Description

+ Apply to a 3DEntity
+ Modifies D6 joint limits. +
+
+

Technical Information

+ + \image html PJD6SetSoftLimit.png + + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body to identfy the joint. +
+
+ + Limit Axis: The target limit axis. See #D6LimitAxis. +
+ Soft Limit: The new limit. See #pJD6SoftLimit. +
+
+ +
+ + See \ref D6AngularLimitGuide "Angular Limits"
+ + See \ref D6LinearLimitGuide "Linear Limits"
+ + */ + + + + proto->SetBehaviorCallbackFct( JD6SetSoftLimitCB ); + + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Limit Axis",VTE_JOINT_LIMIT_AXIS,0); + + proto->DeclareInParameter("Soft Limit",VTS_JOINT_SLIMIT); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(JD6SetSoftLimit); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: JD6SetSoftLimit +// FullName: JD6SetSoftLimit +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int JD6SetSoftLimit(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) + { + + return CK_OK; + } + + + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + if(bodyA || bodyB) + { + + pJointD6 *joint =static_cast(worldA->getJoint(target,targetB,JT_D6)); + D6LimitAxis limitAxis = GetInputParameterValue(beh,1); + pJD6SoftLimit softLimit; + + CKParameter* pout = beh->GetInputParameter(2)->GetRealSource(); + CK_ID* ids = (CK_ID*)pout->GetReadDataPtr(); + float damping,spring,value,restitution; + pout = (CKParameterOut*)ctx->GetObject(ids[0]); + pout->GetValue(&damping); + + pout = (CKParameterOut*)ctx->GetObject(ids[1]); + pout->GetValue(&spring); + pout = (CKParameterOut*)ctx->GetObject(ids[2]); + pout->GetValue(&value); + pout = (CKParameterOut*)ctx->GetObject(ids[3]); + pout->GetValue(&restitution); + + softLimit.damping = damping; + softLimit.spring = spring; + softLimit.value = value; + softLimit.restitution = restitution; + + + + if (joint) + { + switch(limitAxis) + { + case D6LA_Linear: + joint->setLinearLimit(softLimit); + break; + case D6LA_Swing1: + joint->setSwing1Limit(softLimit); + break; + case D6LA_Swing2: + joint->setSwing2Limit(softLimit); + break; + case D6LA_TwistHigh: + joint->setTwistHighLimit(softLimit); + break; + case D6LA_TwistLow: + joint->setTwistLowLimit(softLimit); + break; + + } + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: JD6SetSoftLimitCB +// FullName: JD6SetSoftLimitCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR JD6SetSoftLimitCB(const CKBehaviorContext& behcontext) +{ + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/pJoint/PJAddLimitPlane.cpp b/usr/Src/Behaviors/pJoint/PJAddLimitPlane.cpp new file mode 100644 index 0000000..b8677a4 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJAddLimitPlane.cpp @@ -0,0 +1,311 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorPJAddLimitPlaneDecl(); +CKERROR CreatePJAddLimitPlaneProto(CKBehaviorPrototype **pproto); +int PJAddLimitPlane(const CKBehaviorContext& behcontext); +CKERROR PJAddLimitPlaneCB(const CKBehaviorContext& behcontext); + +enum bbInputs +{ + + bI_ObjectB, + bI_Type, + bI_Res, + bI_LPoint, + bI_LPointRef, + bI_IsOnBodyB, + bI_Anchor, + bI_AnchorRef, + bI_Axis, + bI_AxisRef, + bI_Coll +}; + +//************************************ +// Method: FillBehaviorPJAddLimitPlaneDecl +// FullName: FillBehaviorPJAddLimitPlaneDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJAddLimitPlaneDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJAddLimitPlane"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Adds a limit plane to a joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x150a1e5a,0xebc0c00)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJAddLimitPlaneProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJAddLimitPlaneProto +// FullName: CreatePJAddLimitPlaneProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJAddLimitPlaneProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJAddLimitPlane"); + if(!proto) return CKERR_OUTOFMEMORY; + + + + /*! \page PJAddLimitPlane + +
+ PJAddLimitPlane is categorized in \ref Joints +
+ +

Description

+ Apply to a 3DEntity
+ Adds a limit plane. +
+
See PJPointInPlane.cmo. + + +

Technical Information

+ + \image html PJAddLimitPlane.png + + This building blocks invokes #pJoint::setLimitPoint() and afterwards #pJoint::addLimitPlane() internally. + + + In: triggers the process. +
+
+ + Out: is activated when the process is completed. +
+ + + Body B: The second body. Leave blank to create a joint constraint with the world. +
+ + Joint Type: The joint type. This helps the building block to identify a joint constraint. As usual there can be only one joint of the type x between two bodies.
+ + + Restitution: Restitution of the limit plane.
+ - Range: [0,1.0f) + - Default: 0.0 + + + Limit Point:The point specified in global coordinate frame.
+ - Range: [Position Vector) + + Limit Point Reference:Reference to transform limit point (local) into world space.
+ + Point is Body B:Set to true if the point is attached to the second actor.Otherwise it is attached to the first.
+ + Point in Plane:Point in the limit plane in global coordinates.
+ - Range: [Position Vector) + + Point in Plane Reference:Reference to transform plane "Point in Plane"(local then) into global coordinates.
+ + Normal:Normal for the limit plane in global coordinates.
+ - Range: [Position Vector) + + Normal Reference:Reference to transform plane "Normal"(local up then) into global coordinates.
+ + + + +

VSL : Creation


+ + \include pJAddLimitPlane.vsl + + + + + Is utilizing #pRigidBody #pWorld #PhysicManager #joint::setLimitPoint() #joint::addLimitPlane() + + */ + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->SetBehaviorCallbackFct( PJAddLimitPlaneCB ); + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Type",VTE_JOINT_TYPE,""); + proto->DeclareInParameter("Restitution",CKPGUID_FLOAT,"0.0f"); + + proto->DeclareInParameter("Limit Point",CKPGUID_VECTOR); + proto->DeclareInParameter("Limit Point Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Point Is On Body B",CKPGUID_BOOL,"TRUE"); + + + proto->DeclareInParameter("Point In Plane",CKPGUID_VECTOR); + proto->DeclareInParameter("Point In Plane Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Normal",CKPGUID_VECTOR); + proto->DeclareInParameter("Normal Reference",CKPGUID_3DENTITY); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJAddLimitPlane); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJAddLimitPlane +// FullName: PJAddLimitPlane +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJAddLimitPlane(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + + + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Revolute)) + { + + return CK_OK; + } + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA && ! worldB ) + { + return 0; + } + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + + //anchor : + VxVector anchor0 = GetInputParameterValue(beh,bI_LPoint); + VxVector anchorOut0 = anchor0; + CK3dEntity*anchorReference0 = (CK3dEntity *) beh->GetInputParameterObject(bI_LPointRef); + if (anchorReference0) + { + anchorReference0->Transform(&anchorOut0,&anchor0); + } + + + //anchor : + VxVector anchor = GetInputParameterValue(beh,bI_Anchor); + VxVector anchorOut = anchor; + CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); + if (anchorReference) + { + anchorReference->Transform(&anchorOut,&anchor); + } + //swing axis + VxVector Axis = GetInputParameterValue(beh,bI_Axis); + VxVector axisOut = Axis; + CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); + + if (axisReference) + { + VxVector dir,up,right; + axisReference->GetOrientation(&dir,&up,&right); + axisReference->TransformVector(&axisOut,&up); + } + + ////////////////////////////////////////////////////////////////////////// + int type = GetInputParameterValue(beh,bI_Type); + int isOnBodyB = GetInputParameterValue(beh,bI_IsOnBodyB); + float res = GetInputParameterValue(beh,bI_Res); + pJoint*joint = (worldA->getJoint(target,targetB,(JType)type)); + if(bodyA || bodyB) + { + if (joint) + { + if (XAbs(anchorOut0.SquareMagnitude()) >=0.01f) + joint->setLimitPoint(anchorOut0,isOnBodyB); + + VxVector b = anchorOut; + joint->addLimitPlane(axisOut,anchorOut,res); + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: PJAddLimitPlaneCB +// FullName: PJAddLimitPlaneCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJAddLimitPlaneCB(const CKBehaviorContext& behcontext) +{ + + + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + +/* + DWORD twistLimit; + beh->GetLocalParameterValue(1,&twistLimit); + beh->EnableInputParameter(bbI_HighLimit,twistLimit); + beh->EnableInputParameter(bbI_LowLimit,twistLimit); + + DWORD springSwing; + beh->GetLocalParameterValue(0,&springSwing); + beh->EnableInputParameter(bbI_Spring,springSwing); + + DWORD motor; + beh->GetLocalParameterValue(2,&motor); + beh->EnableInputParameter(bbI_Motor,motor); +*/ + break; + } + } + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/pJoint/PJCreateDistanceJoint.cpp b/usr/Src/Behaviors/pJoint/PJCreateDistanceJoint.cpp new file mode 100644 index 0000000..7c20251 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJCreateDistanceJoint.cpp @@ -0,0 +1,351 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJCreateDistanceJointDecl(); +CKERROR CreatePJCreateDistanceJointProto(CKBehaviorPrototype **pproto); +int PJCreateDistanceJoint(const CKBehaviorContext& behcontext); +CKERROR PJCreateDistanceJointCB(const CKBehaviorContext& behcontext); + +enum bbInputs +{ + + bI_ObjectB, + bI_Anchor0, + bI_Anchor1, + bI_Collision, + bbI_Min, + bbI_Max, + bbI_Spring, +}; + +//************************************ +// Method: FillBehaviorPJCreateDistanceJointDecl +// FullName: FillBehaviorPJCreateDistanceJointDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJCreateDistanceJointDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJDistance"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Sets a distance joint between two bodies."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x52ff6b14,0x474e4938)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJCreateDistanceJointProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJCreateDistanceJointProto +// FullName: CreatePJCreateDistanceJointProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJCreateDistanceJointProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJDistance"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PJDistance + +
+ PJDistance is categorized in \ref Joints +
+
See PJDistance.cmo. + +

Description

+ Apply to a 3DEntity
+ Creates or modifies a distance joint. +
+
+ DOFs removed: 1
+ DOFs remaining: 5
+
+ \image html distanceJoint.png + + + The distance joint tries to maintain a certain minimum and/or maximum distance between two points attached to a pair of actors. It can be set to springy in order to behave like a rubber band. + + An example for a distance joint is a pendulum swinging on a string, or in the case of a springy distance joint, a rubber band between two objects. + + +

Technical Information

+ + \image html PJDistance.png + + In :triggers the process +
+ Out :is activated when the process is completed. +
+
+ Body B :The second body. Leave blank to create a joint constraint with the world. +
+
+ Local Anchor 0 :A point in bodies a local space. See pJointDistance::setLocalAnchor0(). +
+
+ Local Anchor 1 :A point in bodies a local space. See pJointDistance::setLocalAnchor1(). +
+
+ Collision :Enable Collision. See pJointDistance::enableCollision(). +
+
+ + Minimum Distance :The minimum rest length of the rope or rod between the two anchor points.The value must be non-zero! See pJointDistance::setMinDistance(). +
+
+ + Maximum Distance :The maximum rest length of the rope or rod between the two anchor points. The value must be non-zero! See pJointDistance::setMaxDistance(). +
+
+ + Joint Spring: The spring to make it springy. The spring.targetValue field is not used. See pJointDistance::setSpring(). +
+
+ + + + Minimum Distance : Enables parameter input for minimum distance. +
+ Maximum Distance : Enables parameter input for maximum distance. +
+ Spring : Enables parameter input for the spring. +
+ +
+

Warning

+ The body must be dynamic. +
+
+ +

VSL : Creation


+ + \include PJDistance.vsl + +
+ +

VSL : Modifiy


+ + \include PJDistanceModify.vsl + +
+
+
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createDistanceJoint().
+ + */ + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + proto->SetBehaviorCallbackFct( PJCreateDistanceJointCB ); + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + + proto->DeclareInParameter("Local Anchor 0",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Local Anchor 1",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Collision",CKPGUID_BOOL,"TRUE"); + + proto->DeclareInParameter("Minimum Distance",CKPGUID_FLOAT,"0.0f"); + proto->DeclareInParameter("Maximum Distance",CKPGUID_FLOAT,"0.0f"); + proto->DeclareInParameter("Joint Spring",VTS_JOINT_SPRING,"2.1,3.0,4.0"); + + proto->DeclareSetting("Minimum Distance",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Maximum Distance",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Spring",CKPGUID_BOOL,"TRUE"); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJCreateDistanceJoint); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJCreateDistanceJoint +// FullName: PJCreateDistanceJoint +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJCreateDistanceJoint(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Distance)) + { + + return CK_OK; + } + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + + + if(bodyA && bodyB) + { + + + + + //anchor : + VxVector anchor0 = GetInputParameterValue(beh,bI_Anchor0); + VxVector anchor1 = GetInputParameterValue(beh,bI_Anchor1); + + int coll = GetInputParameterValue(beh,bI_Collision); + + + float min= 0.0f; + float max = 0.0f; + + + DWORD minDistance; + beh->GetLocalParameterValue(0,&minDistance); + if (minDistance) + { + min = GetInputParameterValue(beh,bbI_Min); + } + + DWORD maxDistance; + beh->GetLocalParameterValue(1,&maxDistance); + if (maxDistance) + { + max = GetInputParameterValue(beh,bbI_Max); + } + + + pSpring spring; + DWORD hasspring; + beh->GetLocalParameterValue(2,&hasspring); + if (hasspring) + { + CKParameterIn *par = beh->GetInputParameter(bbI_Spring); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + spring = pFactory::Instance()->createSpringFromParameter(rPar); + } + } + }else + { + spring.spring = 0.0f; + spring.damper = 0.0f; + spring.targetValue= 0.0f; + } + ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + + pJointDistance *joint = static_cast(worldA->getJoint(target,targetB,JT_Distance)); + + if (!joint) + { + joint = static_cast(pFactory::Instance()->createDistanceJoint(target,targetB,anchor0,anchor1,min,max,spring)); + } + if (joint) + { + + joint->setMinDistance(min); + joint->setMaxDistance(max); + joint->setLocalAnchor0(anchor0); + joint->setLocalAnchor1(anchor1); + joint->setSpring(spring); + joint->enableCollision(coll); + + } + } + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: PJCreateDistanceJointCB +// FullName: PJCreateDistanceJointCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJCreateDistanceJointCB(const CKBehaviorContext& behcontext) +{ + + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + DWORD minDistance; + beh->GetLocalParameterValue(0,&minDistance); + beh->EnableInputParameter(bbI_Min,minDistance); + + DWORD maxDistance; + beh->GetLocalParameterValue(1,&maxDistance); + beh->EnableInputParameter(bbI_Max,maxDistance); + + DWORD spring; + beh->GetLocalParameterValue(2,&spring); + beh->EnableInputParameter(bbI_Spring,spring); + + + + + + + + + break; + } + } + return CKBR_OK; +} + + + diff --git a/usr/Src/Behaviors/pJoint/PJCylindrical.cpp b/usr/Src/Behaviors/pJoint/PJCylindrical.cpp new file mode 100644 index 0000000..0b66804 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJCylindrical.cpp @@ -0,0 +1,291 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJCylindricalDecl(); +CKERROR CreatePJCylindricalProto(CKBehaviorPrototype **pproto); +int PJCylindrical(const CKBehaviorContext& behcontext); +CKERROR PJCylindricalCB(const CKBehaviorContext& behcontext); + +enum bbInputs +{ + + bI_ObjectB, + bI_Anchor, + bI_AnchorRef, + bI_Axis, + bI_AxisRef, + bI_Coll +}; + +//************************************ +// Method: FillBehaviorPJCylindricalDecl +// FullName: FillBehaviorPJCylindricalDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJCylindricalDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJCylindrical"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Sets/modifies a cylindrical joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x54821791,0x38290804)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJCylindricalProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJCylindricalProto +// FullName: CreatePJCylindricalProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJCylindricalProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJCylindrical"); + if(!proto) return CKERR_OUTOFMEMORY; + + + /*! \page PJCylindrical + +
+ PJCylindrical is categorized in \ref Joints +
+ +

Description

+ Apply to a 3DEntity
+ Creates or modifies a cylindrical joint between a two bodies or the world. +
+
See PJCylindrical.cmo. + + + \image html cylinderJoint.png + + +

Technical Information

+ + \image html PJCylindrical.png + + A cylindrical joint permits both relative translational and rotational movement between two bodies along a single axis (i.e., the bodies are allowed to both slide and twist along the axis of the joint). It is usually necessary to add joint limits to prevent the bodies from getting too far from each other along the joint axis. If the distance becomes too great, then the SDK can have difficulty maintaining the joint constraints (see Joint Limits). + + An example for a cylindrical joint is a telescopic radio antenna. Another example is a piston on a machine such as a steam engine. + + DOFs removed: 4 + DOFs remaining: 2 + + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body. Leave blank to create a joint constraint with the world. +
+ Anchor:A point in world space coordinates. See pJointCylindrical::setGlobalAnchor(). +
+ Anchor Reference: A helper entity to transform a local anchor into the world space. +
+ Axis: An in world space. See pJointCylindrical::setGlobalAxis(). +
+ Axis Up Reference: A helper entity to transform a local axis into the world space. +
+ Collision: Enables Collision. See pJointCylindrical::enableCollision(). +
+ + + +

VSL : Creation


+ + \include pJCylindrical.vsl + +
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createJointCylindrical().
+ + */ + + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + proto->SetBehaviorCallbackFct( PJCylindricalCB ); + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + + proto->DeclareInParameter("Anchor",CKPGUID_VECTOR); + proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Axis",CKPGUID_VECTOR); + proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Collision",CKPGUID_BOOL); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJCylindrical); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJCylindrical +// FullName: PJCylindrical +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJCylindrical(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + + + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Revolute)) + { + + return CK_OK; + } + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA && ! worldB ) + bbErrorME("Couldnt find any world object"); + + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + + + //anchor : + VxVector anchor = GetInputParameterValue(beh,bI_Anchor); + VxVector anchorOut = anchor; + CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); + if (anchorReference) + { + anchorReference->Transform(&anchorOut,&anchor); + } + + + + + + //swing axis + VxVector Axis = GetInputParameterValue(beh,bI_Axis); + VxVector axisOut = Axis; + CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); + + if (axisReference) + { + VxVector dir,up,right; + axisReference->GetOrientation(&dir,&up,&right); + axisReference->TransformVector(&axisOut,&up); + } + + ////////////////////////////////////////////////////////////////////////// + int col = GetInputParameterValue(beh,bI_Coll); + ////////////////////////////////////////////////////////////////////////// + // + pJointCylindrical *joint = static_cast(worldA->getJoint(target,targetB,JT_Cylindrical)); + if(bodyA || bodyB) + { + ////////////////////////////////////////////////////////////////////////// + //joint create ? + if (!joint) + { + joint = static_cast(pFactory::Instance()->createCylindricalJoint(target,targetB,anchorOut,axisOut)); + } + ////////////////////////////////////////////////////////////////////////// Modification : + if (joint) + { + + joint->setGlobalAxis(axisOut); + joint->setGlobalAnchor(anchorOut); + joint->enableCollision(col); + + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: PJCylindricalCB +// FullName: PJCylindricalCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJCylindricalCB(const CKBehaviorContext& behcontext) +{ + + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + +/* + DWORD twistLimit; + beh->GetLocalParameterValue(1,&twistLimit); + beh->EnableInputParameter(bbI_HighLimit,twistLimit); + beh->EnableInputParameter(bbI_LowLimit,twistLimit); + + DWORD springSwing; + beh->GetLocalParameterValue(0,&springSwing); + beh->EnableInputParameter(bbI_Spring,springSwing); + + DWORD motor; + beh->GetLocalParameterValue(2,&motor); + beh->EnableInputParameter(bbI_Motor,motor); +*/ + break; + } + } + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pJoint/PJDestroy.cpp b/usr/Src/Behaviors/pJoint/PJDestroy.cpp new file mode 100644 index 0000000..220148c --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJDestroy.cpp @@ -0,0 +1,188 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorJDestroyDecl(); +CKERROR CreateJDestroyProto(CKBehaviorPrototype **pproto); +int JDestroy(const CKBehaviorContext& behcontext); +CKERROR JDestroyCB(const CKBehaviorContext& behcontext); + + + +//************************************ +// Method: FillBehaviorJDestroyDecl +// FullName: FillBehaviorJDestroyDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorJDestroyDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJDestroy"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Destroys a joint given by two bodies and the joint type."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x42cd6243,0x5f7b18af)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateJDestroyProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateJDestroyProto +// FullName: CreateJDestroyProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateJDestroyProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJDestroy"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PJDestroy + +
+ PJDestroy is categorized in \ref Joints +
+
See PJDestroy.cmo. + +

Description

+ Apply to a 3DEntity
+ Deletes a joint, given by references and type. + +
+ +

Technical Information

+ + \image html PJDestroy.png + + + In: triggers the process +
+ Out: is activated when the process is completed. +
+ + Body B: The second body. Leave blank to create a joint constraint with the world. +
+ + Joint Type: The joint type. This helps the building block to identify a joint constraint. As usual there can be only one joint of the type x between two bodies. +
+ + Sleeping: This call wakes the actor(s) if they are sleeping. + + Is utilizing #pRigidBody #pWorld #PhysicManager #pWorld::deleteJoint().
+ */ + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->SetBehaviorCallbackFct( JDestroyCB ); + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Type",VTE_JOINT_TYPE,""); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(JDestroy); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: JDestroy +// FullName: JDestroy +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int JDestroy(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + + int jointType = GetInputParameterValue(beh,1); + + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,jointType)) + { + return CK_OK; + } + + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + if(bodyA || bodyB) + { + + pJoint *joint = worldA->getJoint(target,targetB,(JType)jointType); + if (joint) + { + worldA->deleteJoint(joint); + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: JDestroyCB +// FullName: JDestroyCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR JDestroyCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + } + break; + } + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/pJoint/PJGroupBreakIterator.cpp b/usr/Src/Behaviors/pJoint/PJGroupBreakIterator.cpp new file mode 100644 index 0000000..577e422 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJGroupBreakIterator.cpp @@ -0,0 +1,236 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJGroupBreakIteratorDecl(); +CKERROR CreatePJGroupBreakIteratorProto(CKBehaviorPrototype **pproto); +int PJGroupBreakIterator(const CKBehaviorContext& behcontext); +CKERROR PJGroupBreakIteratorCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPJGroupBreakIteratorDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJGroupBreakIterator"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Enables trigger output for multiple objects when a joint got broken"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7a64881,0x3aca7f0c)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJGroupBreakIteratorProto); + od->SetCompatibleClassId(CKCID_GROUP); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJGroupBreakIteratorProto +// FullName: CreatePJGroupBreakIteratorProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJGroupBreakIteratorProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJGroupBreakIterator"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PJGroupBreakIterator + + PJGroupBreakIterator is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Triggers outputs if the body enters,stays or leaves another body .
+ See pBTriggerEvent.cmo for example. + +

Technical Information

+ + \image html PJGroupBreakIterator.png + + In: triggers the process +
+ + No Event: Nothing touched. +
+ Entering: Body entered. +
+ Leaving: Body leaved. +
+ Stay: Inside body . +
+ + Target Group: The group which the bb outputs triggers for. +
+ Touched Object: The touched body. +
+ +

Warning

+ The body must be dynamic. +
+
+

Note


+ + +
+
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForce().
+ + */ + + //proto->DeclareInParameter("Extra Filter",VTF_TRIGGER,"0"); + //proto->DeclareInParameter("Remove Event",CKPGUID_BOOL,"0"); + + proto->DeclareInput("In"); + proto->DeclareInput("Next"); + + proto->DeclareOutput("None"); + proto->DeclareOutput("Break"); + + proto->DeclareOutParameter("Body A",CKPGUID_3DENTITY,0); + proto->DeclareOutParameter("Body B",CKPGUID_3DENTITY,0); + proto->DeclareOutParameter("Impulse",CKPGUID_FLOAT,0); + + proto->DeclareLocalParameter("currentIndex", CKPGUID_INT); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJGroupBreakIterator); + *pproto = proto; + return CK_OK; +} +enum bOutputs +{ + bbO_None, + bbO_Break, +}; + +enum bInputs +{ + bbI_Init, + bbI_Next, +}; + +bool isInGroup2(CKGroup *src, CK3dEntity* testObject) +{ + + if (src && testObject) + { + for (int i = 0 ; i < src->GetObjectCount() ; i++ ) + { + CK3dEntity *ent = (CK3dEntity*)src->GetObject(i); + if(ent) + { + if (ent==testObject) + { + return true; + } + } + } + } + + return false; +} + +//************************************ +// Method: PJGroupBreakIterator +// FullName: PJGroupBreakIterator +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJGroupBreakIterator(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CKGroup *target = (CKGroup *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + int nbOfEvents = GetPMan()->getJointFeedbackList().Size(); + /************************************************************************/ + /* handle init */ + /************************************************************************/ + if( beh->IsInputActive(bbI_Init) ) + { + beh->ActivateInput(bbI_Init,FALSE); + if (nbOfEvents) + { + beh->ActivateInput(bbI_Next,TRUE); + } + } + + /************************************************************************/ + /* handle trigger 'next' */ + /************************************************************************/ + if( beh->IsInputActive(bbI_Next) && nbOfEvents ) + { + beh->ActivateInput(bbI_Next,FALSE); + beh->ActivateOutput(bbO_Break,FALSE); + CK3dEntity *bodyAEnt =NULL; //static_cast(GetPMan()->GetContext()->GetObject(entry->mAEnt)); + CK3dEntity *bodyBEnt = NULL;//static_cast(GetPMan()->GetContext()->GetObject(entry->mBEnt)); + + pBrokenJointEntry *entry = *GetPMan()->getJointFeedbackList().At(0); + + bodyAEnt = static_cast(GetPMan()->GetContext()->GetObject(entry->mAEnt)); + bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(entry->mBEnt)); + + if (isInGroup2(target,bodyAEnt) || isInGroup2(target,bodyBEnt)) + { + + beh->SetOutputParameterObject(0,bodyAEnt); + beh->SetOutputParameterObject(1,bodyBEnt); + SetOutputParameterValue(beh,2,entry->impulse); + GetPMan()->getJointFeedbackList().EraseAt(0); + beh->ActivateOutput(bbO_Break); + return 0; + } + } + + /************************************************************************/ + /* terminate */ + /************************************************************************/ + beh->ActivateOutput(bbO_None); + return 0; +} + +//************************************ +// Method: PJGroupBreakIteratorCB +// FullName: PJGroupBreakIteratorCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJGroupBreakIteratorCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pJoint/PJIsBroken.cpp b/usr/Src/Behaviors/pJoint/PJIsBroken.cpp new file mode 100644 index 0000000..e356fdc --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJIsBroken.cpp @@ -0,0 +1,232 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJIsBrokenDecl(); +CKERROR CreatePJIsBrokenProto(CKBehaviorPrototype **pproto); +int PJIsBroken(const CKBehaviorContext& behcontext); +CKERROR PJIsBrokenCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_BodyB, + bbI_Type, +}; + +//************************************ +// Method: FillBehaviorPJIsBrokenDecl +// FullName: FillBehaviorPJIsBrokenDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJIsBrokenDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJIsBroken"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Triggers when joint has been broken."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x17082b70,0x6eae5b38)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJIsBrokenProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJIsBrokenProto +// FullName: CreatePJIsBrokenProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJIsBrokenProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJIsBroken"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PJIsBroken + +
+ PJIsBroken is categorized in \ref Joints +
+ + +

Description

+ Apply to a 3DEntity
+ Activates output trigger when a joint has been broken. + +
+ +

Technical Information

+ + \image html PJIsBroken.png + + + In: triggers the process. +
+
+ + Exit On: is activated when the building block has been started. +
+ + Exit Off: is activated when the process is completed. +
+ + Broken: is activated when the joint has been broken. +
+
+ + Body B: The second body. Leave blank to create a joint constraint with the world. +
+ + Joint Type: The joint type. This helps the building block to identify a joint constraint. As usual there can be only one joint of the type x between two bodies. +
+
+ + Breaking Impulse: The impulse which broke the joint. This is clamped to the values of maxForce (or maxTorque, depending on what made the joint break) that was specified for the joint. +
+ + Is utilizing #pRigidBody #pWorld #PhysicManager.
+ */ + + proto->DeclareInput("On"); + proto->DeclareInput("Off"); + proto->DeclareOutput("Exit On"); + proto->DeclareOutput("Exit Off"); + proto->DeclareOutput("Broken"); + proto->DeclareOutParameter("Break Impulse",CKPGUID_FLOAT); + + + proto->SetBehaviorCallbackFct( PJIsBrokenCB ); + + + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Joint Type",VTE_JOINT_TYPE,"0"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJIsBroken); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJIsBroken +// FullName: PJIsBroken +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJIsBroken(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(1) ) + { + beh->ActivateInput(1,FALSE); + return CK_OK; + } + + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + } + + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bbI_BodyB); + + int jointType = GetInputParameterValue(beh,bbI_Type); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,jointType)) + { + + return CKBR_ACTIVATENEXTFRAME; + } + + + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + int size = GetPMan()->getJointFeedbackList().Size(); + + if(bodyA || bodyB) + { + for (int i = 0 ; i < GetPMan()->getJointFeedbackList().Size(); i++ ) + { + pBrokenJointEntry *entry = *GetPMan()->getJointFeedbackList().At(i); + if (entry) + { + + if ( entry->jType ==jointType ) + { + CK3dEntity *bodyAEnt = static_cast(GetPMan()->GetContext()->GetObject(entry->mAEnt)); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(entry->mBEnt)); + + if ( bodyAEnt == target && bodyBEnt ==targetB) + { + beh->ActivateOutput(2); + SetOutputParameterValue(beh,0,entry->impulse); + GetPMan()->getJointFeedbackList().EraseAt(i); + return CKBR_ACTIVATENEXTFRAME; + } + + if (bodyBEnt == targetB && bodyAEnt==target) + { + beh->ActivateOutput(2); + SetOutputParameterValue(beh,0,entry->impulse); + GetPMan()->getJointFeedbackList().EraseAt(i); + return CKBR_ACTIVATENEXTFRAME; + } + } + } + } + } + return CKBR_ACTIVATENEXTFRAME; +} +//************************************ +// Method: PJIsBrokenCB +// FullName: PJIsBrokenCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJIsBrokenCB(const CKBehaviorContext& behcontext) +{ + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/pJoint/PJIterator.cpp b/usr/Src/Behaviors/pJoint/PJIterator.cpp new file mode 100644 index 0000000..a2ad9ea --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJIterator.cpp @@ -0,0 +1,339 @@ +#include +#include "pCommon.h" + +#include "pWorldCallbacks.h" + + + +CKObjectDeclaration *FillBehaviorPJIteratorDecl(); +CKERROR CreatePJIteratorProto(CKBehaviorPrototype **pproto); +int PJIterator(const CKBehaviorContext& behcontext); +CKERROR PJIteratorCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPJIteratorDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJIterator"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Iterates through bodies joints"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x115941e7,0x15861d73)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJIteratorProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJIteratorProto +// FullName: CreatePJIteratorProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +enum bInput +{ +}; +enum bbO +{ + + bbO_BodyB, + bbO_Type, + +}; +enum bbOT +{ + bbOT_Finish, + bbOT_Next, +}; +CKERROR CreatePJIteratorProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJIterators"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PJIterator + + + PJIterators is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Performs a ray cast test. Outputs hit informations.
+ See PWRayCasts.cmo for example. + +

Technical Information

+ + \image html PJIterators.png + + In: Triggers the process. +
+ Next: Next Hit. +
+ + + Yes: Hit occured. +
+ No: No hits. +
+ Finish: Last hit. +
+ Next: Loop out. +
+ + + + + + Target: World Reference. pDefaultWorld! +
+ Ray Origin: Start of the ray. +
+ Ray Origin Reference: Reference object to determine the start of the ray. Ray Origin becomes transformed if an object is given. +
+ Ray Direction: Direction of the ray. +
+ Ray Direction Reference: Reference object to determine the direction of the ray. Ray Direction becomes transformed if an object is given. Up axis will be used then. +
+ Length: Lenght of the ray. +
+ Shapes Types: Adds static and/or dynamic shapes to the test. +
+ + Groups: Includes specific groups to the test. +
+ Groups Mask: Alternative mask used to filter shapes. See #pRigidBody::setGroupsMask +
+ + Touched Body: The touched body. +
+ Impact Position: Hit point in world space. +
+ Face Normal: Normal of the hit. +
+ Face Index: +
+ Distance: Distance between ray start and hit. +
+ UV: not used yet ! +
+ Material Index: Index of the internal physic material. +
+ + + +
+
+ + Is utilizing #pWorld::raycastAllShapes()
+ + */ + + proto->DeclareInput("In"); + proto->DeclareInput("Next"); + proto->DeclareOutput("Finish"); + proto->DeclareOutput("LoopOut"); + + proto->DeclareLocalParameter("result", CKPGUID_POINTER); + proto->DeclareLocalParameter("index", CKPGUID_INT); + + proto->DeclareOutParameter("Body B",CKPGUID_3DENTITY); + proto->DeclareOutParameter("Joint Type",VTE_JOINT_TYPE); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetBehaviorCallbackFct( PJIteratorCB ); + proto->SetFunction(PJIterator); + *pproto = proto; + return CK_OK; +} + +struct _pJoint +{ + pJoint *_j; + CK3dEntity *_b; + +}; +typedef std::vector<_pJoint*>_pJointList; + + +//************************************ +// Method: PJIterator +// FullName: PJIterator +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJIterator(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + using namespace vtTools::ParameterTools; + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + ////////////////////////////////////////////////////////////////////////// + // the world : + + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + bbErrorME("No valid world object found"); + + + pRigidBody *body = NULL; + + body = GetPMan()->getBody(target); + if (!body) bbErrorME("Object not physicalized"); + + /************************************************************************/ + /* we come in by reset */ + /************************************************************************/ + + if( beh->IsInputActive(0) ) + { + + beh->ActivateInput(0,FALSE); + + + _pJointList *jarray = NULL; + beh->GetLocalParameterValue(0,&jarray); + if (jarray) + { + jarray->clear(); + }else + { + jarray = new _pJointList(); + } + + beh->SetLocalParameterValue(0,&jarray); + + int hitIndex = 0; + beh->SetLocalParameterValue(1,&hitIndex); + + ////////////////////////////////////////////////////////////////////////// + // get joint list + int nbJoints = body->getNbJoints(); + if (nbJoints) + { + NxU32 jointCount = world->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + world->getScene()->resetJointIterator(); + + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = world->getScene()->getNextJoint(); + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == target || mJoint->GetVTEntB() == target ) + { + + _pJoint *j = new _pJoint(); + j->_j = mJoint; + + + if (mJoint->GetVTEntA() == target ) + { + j->_b = mJoint->GetVTEntB(); + } + + if (mJoint->GetVTEntB() == target ) + { + j->_b = mJoint->GetVTEntA(); + } + + jarray->push_back(j); + } + } + } + } + } + if (nbJoints) + { + beh->ActivateOutput(bbOT_Next); + beh->ActivateInput(1,TRUE); + + }else{ + beh->ActivateOutput(bbOT_Finish); + } + } + + if( beh->IsInputActive(1) ) + { + + beh->ActivateInput(1,FALSE); + _pJointList *carray = NULL; + beh->GetLocalParameterValue(0,&carray); + + ////////////////////////////////////////////////////////////////////////// + if (carray) + { + if (carray->size()) + { + _pJoint *hit = carray->at(carray->size()-1); + if (hit) + { + beh->SetOutputParameterObject(bbO_BodyB,hit->_b); + SetOutputParameterValue(beh,bbO_Type,hit->_j->getType()); + carray->pop_back(); + if (carray->size()) + { + beh->ActivateOutput(bbOT_Next); + }else + { + beh->ActivateOutput(bbOT_Finish); + } + } + } + } + + } + + return 0; +} + +//************************************ +// Method: PJIteratorCB +// FullName: PJIteratorCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJIteratorCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pJoint/PJPointInPlane.cpp b/usr/Src/Behaviors/pJoint/PJPointInPlane.cpp new file mode 100644 index 0000000..507423d --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJPointInPlane.cpp @@ -0,0 +1,272 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJPointPlaneDecl(); +CKERROR CreatePJPointPlaneProto(CKBehaviorPrototype **pproto); +int PJPointPlane(const CKBehaviorContext& behcontext); +CKERROR PJPointPlaneCB(const CKBehaviorContext& behcontext); + +enum bbInputs +{ + + bI_ObjectB, + bI_Anchor, + bI_AnchorRef, + bI_Axis, + bI_AxisRef, + bI_Coll +}; + +//************************************ +// Method: FillBehaviorPJPointPlaneDecl +// FullName: FillBehaviorPJPointPlaneDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJPointPlaneDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJPointInPlane"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Sets/modifies a point in plane joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x6b7f6a11,0x4cb565b8)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJPointPlaneProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJPointPlaneProto +// FullName: CreatePJPointPlaneProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJPointPlaneProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJPointInPlane"); + if(!proto) return CKERR_OUTOFMEMORY; + + + /*! \page PJPointInPlane + +
+ PJPointPlane is categorized in \ref Joints +
+ +

Description

+ Apply to a 3DEntity
+ Creates or modifies a cylindrical joint between a two bodies or the world. +
+
See PJPointInPlane.cmo. + + + \image html pointInPlaneJoint.png + + + +

Technical Information

+ + \image html PJPointPlane.png + + A point in plane joint constrains a point on one actor to only move inside a plane attached to another actor. The point attached to the plane is defined by the anchor point. The joint's axis specifies the plane normal. + + An example for a point in plane joint is a magnet on a refrigerator. + + DOFs removed: 1 + DOFs remaining: 5 + + + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body. Leave blank to create a joint constraint with the world. +
+ Anchor:A point in world space coordinates. See pJointPointInPlane::setGlobalAnchor(). +
+ Anchor Reference: A helper entity to transform a local anchor into the world space. +
+ Axis: An in world space. See pJointPointInPlane::setGlobalAxis(). +
+ Axis Up Reference: A helper entity to transform a local axis into the world space. +
+ Collision: Enables Collision. See pJointPointInPlane::enableCollision(). +
+ + + +

VSL : Creation


+ + \include PJPointInPlane.vsl + +
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createPointInPlaneJoint().
+ + */ + + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + proto->SetBehaviorCallbackFct( PJPointPlaneCB ); + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + + proto->DeclareInParameter("Anchor",CKPGUID_VECTOR); + proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Axis",CKPGUID_VECTOR); + proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Collision",CKPGUID_BOOL); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJPointPlane); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJPointPlane +// FullName: PJPointPlane +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJPointPlane(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_PointInPlane)) + { + + return CK_OK; + } + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA && ! worldB ) + bbErrorME("Couldnt find any world object"); + + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + + + //anchor : + VxVector anchor = GetInputParameterValue(beh,bI_Anchor); + VxVector anchorOut = anchor; + CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); + if (anchorReference) + { + anchorReference->Transform(&anchorOut,&anchor); + } + + //swing axis + VxVector Axis = GetInputParameterValue(beh,bI_Axis); + VxVector axisOut = Axis; + CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); + + if (axisReference) + { + VxVector dir,up,right; + axisReference->GetOrientation(&dir,&up,&right); + axisReference->TransformVector(&axisOut,&up); + } + + ////////////////////////////////////////////////////////////////////////// + int col = GetInputParameterValue(beh,bI_Coll); + ////////////////////////////////////////////////////////////////////////// + // + pJointPointInPlane *joint = static_cast(GetPMan()->getJoint(target,targetB,JT_PointInPlane)); + if(bodyA || bodyB) + { + ////////////////////////////////////////////////////////////////////////// + //joint create ? + if (!joint) + { + joint = static_cast(pFactory::Instance()->createPointInPlaneJoint(target,targetB,anchorOut,axisOut)); + } + ////////////////////////////////////////////////////////////////////////// Modification : + if (joint) + { + + joint->setGlobalAxis(axisOut); + joint->setGlobalAnchor(anchorOut); + joint->enableCollision(col); + + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: PJPointPlaneCB +// FullName: PJPointPlaneCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJPointPlaneCB(const CKBehaviorContext& behcontext) +{ + + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + break; + } + } + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pJoint/PJPointOnLine.cpp b/usr/Src/Behaviors/pJoint/PJPointOnLine.cpp new file mode 100644 index 0000000..59beeba --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJPointOnLine.cpp @@ -0,0 +1,269 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJPointOnLineDecl(); +CKERROR CreatePJPointOnLineProto(CKBehaviorPrototype **pproto); +int PJPointOnLine(const CKBehaviorContext& behcontext); +CKERROR PJPointOnLineCB(const CKBehaviorContext& behcontext); + +enum bbInputs +{ + + bI_ObjectB, + bI_Anchor, + bI_AnchorRef, + bI_Axis, + bI_AxisRef, + bI_Coll +}; + +//************************************ +// Method: FillBehaviorPJPointOnLineDecl +// FullName: FillBehaviorPJPointOnLineDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJPointOnLineDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJPointOnLine"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Sets/modifies a point on line joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x5c342d2a,0x35885b1a)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJPointOnLineProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJPointOnLineProto +// FullName: CreatePJPointOnLineProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJPointOnLineProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJPointOnLine"); + if(!proto) return CKERR_OUTOFMEMORY; + + + /*! \page PJPointOnLine + +
+ PJPointOnLine is categorized in \ref Joints +
+ +

Description

+ Apply to a 3DEntity
+ Creates or modifies a point on line joint between a two bodies or the world. +
+
See PJPointOnLine.cmo. + + + \image html pointOnLineJoint.png + +

Technical Information

+ + \image html PJPointOnLine.png + + A point on line joint constrains a point on one actor to only move along a line attached to another actor. The point attached to the line is the anchor point for the joint. The line through this point is specified by its direction (axis) vector. + + An example for a point on line joint is a curtain hanger widget. + + DOFs removed: 2 + DOFs remaining: 4 + + + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body. Leave blank to create a joint constraint with the world. +
+ Anchor:A point in world space coordinates. See pJointPointInPlane::setGlobalAnchor(). +
+ Anchor Reference: A helper entity to transform a local anchor into the world space. +
+ Axis: An in world space. See pJointPointInPlane::setGlobalAxis(). +
+ Axis Up Reference: A helper entity to transform a local axis into the world space. +
+ Collision: Enables Collision. See pJointPointInPlane::enableCollision(). +
+ + + +

VSL : Creation


+ + \include PJPointOnLine.vsl + +
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createPointOnLineJoint().
+ + */ + + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + proto->SetBehaviorCallbackFct( PJPointOnLineCB ); + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + + proto->DeclareInParameter("Anchor",CKPGUID_VECTOR); + proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Axis",CKPGUID_VECTOR); + proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Collision",CKPGUID_BOOL); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJPointOnLine); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJPointOnLine +// FullName: PJPointOnLine +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJPointOnLine(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_PointOnLine)) + { + + return CK_OK; + } + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA && ! worldB ) + bbErrorME("Couldnt find any world object"); + + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + + + //anchor : + VxVector anchor = GetInputParameterValue(beh,bI_Anchor); + VxVector anchorOut = anchor; + CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); + if (anchorReference) + { + anchorReference->Transform(&anchorOut,&anchor); + } + + VxVector Axis = GetInputParameterValue(beh,bI_Axis); + VxVector axisOut = Axis; + CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); + + if (axisReference) + { + VxVector dir,up,right; + axisReference->GetOrientation(&dir,&up,&right); + axisReference->TransformVector(&axisOut,&up); + } + + ////////////////////////////////////////////////////////////////////////// + int col = GetInputParameterValue(beh,bI_Coll); + ////////////////////////////////////////////////////////////////////////// + // + pJointPointOnLine*joint = static_cast(GetPMan()->getJoint(target,targetB,JT_PointOnLine)); + if(bodyA || bodyB) + { + ////////////////////////////////////////////////////////////////////////// + //joint create ? + if (!joint) + { + joint = static_cast(pFactory::Instance()->createPointOnLineJoint(target,targetB,anchorOut,axisOut)); + } + ////////////////////////////////////////////////////////////////////////// Modification : + if (joint) + { + + joint->setGlobalAxis(axisOut); + joint->setGlobalAnchor(anchorOut); + joint->enableCollision(col); + + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: PJPointOnLineCB +// FullName: PJPointOnLineCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJPointOnLineCB(const CKBehaviorContext& behcontext) +{ + + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + break; + } + } + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pJoint/PJPrismatic.cpp b/usr/Src/Behaviors/pJoint/PJPrismatic.cpp new file mode 100644 index 0000000..d81a9c3 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJPrismatic.cpp @@ -0,0 +1,243 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJPrismaticDecl(); +CKERROR CreatePJPrismaticProto(CKBehaviorPrototype **pproto); +int PJPrismatic(const CKBehaviorContext& behcontext); +CKERROR PJPrismaticCB(const CKBehaviorContext& behcontext); + +enum bbInputs +{ + + bI_ObjectB, + bI_Anchor, + bI_AnchorRef, + bI_Axis, + bI_AxisRef, + bI_Coll +}; + +//************************************ +// Method: FillBehaviorPJPrismaticDecl +// FullName: FillBehaviorPJPrismaticDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJPrismaticDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJPrismatic"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Sets/modifies a prismatic joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x2c270788,0x2d886425)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJPrismaticProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJPrismaticProto +// FullName: CreatePJPrismaticProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJPrismaticProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJPrismatic"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + proto->SetBehaviorCallbackFct( PJPrismaticCB ); + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + + proto->DeclareInParameter("Anchor",CKPGUID_VECTOR); + proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Axis",CKPGUID_VECTOR); + proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Collision",CKPGUID_BOOL); + /* + + proto->DeclareInParameter("Spring",VTS_JOINT_SPRING); + + proto->DeclareInParameter("High Limit",VTS_JLIMIT); + proto->DeclareInParameter("Low Limit",VTS_JLIMIT); + + + + + proto->DeclareInParameter("Motor",VTS_JOINT_MOTOR); +*/ +/* + proto->DeclareSetting("Spring",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Limit",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Motor",CKPGUID_BOOL,"FALSE"); +*/ + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJPrismatic); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJPrismatic +// FullName: PJPrismatic +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJPrismatic(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + + + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Prismatic)) + { + return CK_OK; + } + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA && ! worldB ) + { + return 0; + } + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + + + //anchor : + VxVector anchor = GetInputParameterValue(beh,bI_Anchor); + VxVector anchorOut = anchor; + CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); + if (anchorReference) + { + anchorReference->Transform(&anchorOut,&anchor); + } + + + + + + //swing axis + VxVector Axis = GetInputParameterValue(beh,bI_Axis); + VxVector axisOut = Axis; + CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); + + if (axisReference) + { + VxVector dir,up,right; + axisReference->GetOrientation(&dir,&up,&right); + axisReference->TransformVector(&axisOut,&up); + } + + ////////////////////////////////////////////////////////////////////////// + int col = GetInputParameterValue(beh,bI_Coll); + ////////////////////////////////////////////////////////////////////////// + // + pJointPrismatic *joint = static_cast(worldA->getJoint(target,targetB,JT_Prismatic)); + if(bodyA || bodyB) + { + ////////////////////////////////////////////////////////////////////////// + //joint create ? + if (!joint) + { + joint = static_cast(pFactory::Instance()->createPrismaticJoint(target,targetB,anchorOut,axisOut)); + } + ////////////////////////////////////////////////////////////////////////// Modification : + if (joint) + { + + joint->setGlobalAxis(axisOut); + joint->setGlobalAnchor(anchorOut); + joint->enableCollision(col); + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: PJPrismaticCB +// FullName: PJPrismaticCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJPrismaticCB(const CKBehaviorContext& behcontext) +{ + + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + +/* + DWORD twistLimit; + beh->GetLocalParameterValue(1,&twistLimit); + beh->EnableInputParameter(bbI_HighLimit,twistLimit); + beh->EnableInputParameter(bbI_LowLimit,twistLimit); + + DWORD springSwing; + beh->GetLocalParameterValue(0,&springSwing); + beh->EnableInputParameter(bbI_Spring,springSwing); + + DWORD motor; + beh->GetLocalParameterValue(2,&motor); + beh->EnableInputParameter(bbI_Motor,motor); +*/ + break; + } + } + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pJoint/PJPulley.cpp b/usr/Src/Behaviors/pJoint/PJPulley.cpp new file mode 100644 index 0000000..9aeea19 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJPulley.cpp @@ -0,0 +1,367 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJPulleyDecl(); +CKERROR CreatePJPulleyProto(CKBehaviorPrototype **pproto); +int PJPulley(const CKBehaviorContext& behcontext); +CKERROR PJPulleyCB(const CKBehaviorContext& behcontext); + +enum bbInputs +{ + bI_ObjectB, + bI_Anchor0, + bI_Anchor1, + bI_Pulley0, + bI_Pulley0Ref, + bI_Pulley1, + bI_Pulley1Ref, + bI_Stifness, + bI_Distance, + bI_Ratio, + bI_Rigid, + bi_Collision, + bI_Motor, + +}; +//************************************ +// Method: FillBehaviorPJPulleyDecl +// FullName: FillBehaviorPJPulleyDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJPulleyDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJPulley"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Sets a pulley joint between two bodies."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x43d5361f,0x683f2741)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJPulleyProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + return od; +} +//************************************ +// Method: CreatePJPulleyProto +// FullName: CreatePJPulleyProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJPulleyProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJPulley"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PJPulley + +
+ PJPulley is categorized in \ref Joints +
+
See pJPulley.cmo. + + + + + +

Description

+ Apply to a 3DEntity
+ Creates or modifies a pulley (rope) joint. +
+ + \image html pulleyJoint.png + + + The pulley joint simulates a rope that can be thrown across a pair of pulleys. In this way, it is similar to the distance joint (the length of the rope is the distance) but the rope doesn't connect the two bodies along the shortest path, rather it leads from the connection point on one actor to the pulley point (fixed in world space), then to the second pulley point, and finally to the other actor. + + The pulley joint can also be used to simulate a rope around a single point by making the pulley points coincide. + + Note that a setup where either object attachment point coincides with its corresponding pulley suspension point in world space is invalid. In this case, the simulation would be unable to determine the appropriate direction in which to pull the object and a random direction would result. The simulation will be unstable. Note that it is also invalid to allow the simulation to end up in such a state. + + +

Technical Information

+ + \image html PJPulley.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body. Leave blank to create a joint constraint with the world. +
+
+ + + Local Anchor A:Sets the attachment point of joint in bodie[0]'s space.See pJointPulley::setLocalAnchorA(). +
+ + Local Anchor B:Sets the attachment point of joint in bodie[1]'s space.See pJointPulley::setLocalAnchorB(). +
+ + + + Pulley A: Sets the suspension point of joint in world space. See pJointPulley::setPulleyA(). +
+ + Pulley A Reference: Sets the suspension point of joint in local space by using an reference entity. The above vector gets transformed. +
+ + Pulley B: Sets the suspension point of joint in world space.See pJointPulley::setPulleyA(). +
+ + Pulley B Reference: Sets the suspension point of joint in local space by using an reference entity. The above vector gets transformed. +
+ + Stiffness: Sets how stiff the constraint is, between 0 and 1 (stiffest). See pJointPulley::setStiffness(). +
+ + Distance: Sets the rest length of the rope connecting the two objects.See pJointPulley::setDistance(). +
+ + \Note The distance is computed as ||(pulley0 - anchor0)|| + ||(pulley1 - anchor1)|| * ratio. + + Ratio: .Sets transmission ratio. See pJointPulley::setRatio(). +
+ + Is Rigid: .Set true if the joint also has to maintain a minimum distance, not just a maximum. See pJointPulley::setRigid(). +
+ + + Collision: Enables Collision. See pJointPulley::enableCollision(). +
+ + Motor: Motor parameters. See pJointPulley::setMotor(). +
+
+
+ + +
+

Warning

+ At least one body must be dynamic. +
+ + +

VSL : Creation


+ + \include pJPulley.vsl + +
+ +

VSL : Motor Modification


+ + \include PJRevoluteSetMotor.vsl + +
+
+ + + Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createJointPulley(). #pJointPulley
+ + */ + + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + proto->SetBehaviorCallbackFct( PJPulleyCB ); + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + + proto->DeclareInParameter("Local Anchor A",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Local Anchor B",CKPGUID_VECTOR,"0.0f"); + + proto->DeclareInParameter("Pulley A",CKPGUID_VECTOR); + proto->DeclareInParameter("Pulley A Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Pulley B",CKPGUID_VECTOR); + proto->DeclareInParameter("Pulley B Reference",CKPGUID_3DENTITY); + + proto->DeclareInParameter("Stiffness",CKPGUID_FLOAT); + proto->DeclareInParameter("Distance",CKPGUID_FLOAT); + proto->DeclareInParameter("Ratio",CKPGUID_FLOAT); + + proto->DeclareInParameter("Is Rigid",CKPGUID_BOOL); + + proto->DeclareInParameter("Collision",CKPGUID_BOOL); + + proto->DeclareInParameter("Motor",VTS_JOINT_MOTOR); + + + proto->DeclareSetting("Motor",CKPGUID_BOOL,"FALSE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJPulley); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJPulley +// FullName: PJPulley +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJPulley(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Pulley)) + { + return CK_OK; + } + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + + if (!worldA && !worldB) + bbErrorME("Couldnt find any world object"); + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + if (!bodyA && !bodyB) + bbErrorME("Couldnt find any physic object"); + + + + if(bodyA && bodyB) + { + + VxVector anchor0 = GetInputParameterValue(beh,bI_Anchor0); + VxVector anchor1 = GetInputParameterValue(beh,bI_Anchor1); + + VxVector pulley0 = GetInputParameterValue(beh,bI_Pulley0); + CK3dEntity*pulley0Ref= (CK3dEntity *) beh->GetInputParameterObject(bI_Pulley0Ref); + VxVector pulley1 = GetInputParameterValue(beh,bI_Pulley1); + CK3dEntity*pulley1Ref= (CK3dEntity *) beh->GetInputParameterObject(bI_Pulley1Ref); + + + int coll = GetInputParameterValue(beh,bi_Collision); + + + + VxVector pulley0Out = pulley0; + if (pulley0Ref) + pulley0Ref->Transform(&pulley0Out,&pulley0); + + VxVector pulley1Out = pulley1; + if (pulley1Ref) + pulley1Ref->Transform(&pulley1Out,&pulley1); + + + float ratio = GetInputParameterValue(beh,bI_Ratio); + float stiff = GetInputParameterValue(beh,bI_Stifness); + float distance = GetInputParameterValue(beh,bI_Distance); + int rigid = GetInputParameterValue(beh,bI_Rigid); + + pMotor motor; + + DWORD hasMotor;beh->GetLocalParameterValue(0,&hasMotor); + if (hasMotor) + { + CKParameterIn *par = beh->GetInputParameter(bI_Motor); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + motor = pFactory::Instance()->createMotorFromParameter(rPar); + } + } + } + + + ////////////////////////////////////////////////////////////////////////// + // + pJointPulley*joint = static_cast(worldA->getJoint(target,targetB,JT_Pulley)); + + if (!joint) + { + joint = static_cast(pFactory::Instance()->createPulleyJoint(target,targetB,pulley0Out,pulley1Out,anchor0,anchor1)); + if (!joint) + { + bbErrorMesg("Couldn't create Pulley joint!"); + } + } + + ////////////////////////////////////////////////////////////////////////// + //joint exists : update : + if (joint) + { + joint->setStiffness(stiff); + joint->setRatio(ratio); + joint->setRigid(rigid); + joint->setDistance(distance); + joint->setPulleyA(pulley0Out); + joint->setPulleyB(pulley1Out); + joint->setLocalAnchorA(anchor0); + joint->setLocalAnchorB(anchor1); + joint->enableCollision(coll); + + if (hasMotor) + { + joint->setMotor(motor); + } + } + } + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: PJPulleyCB +// FullName: PJPulleyCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJPulleyCB(const CKBehaviorContext& behcontext) +{ + + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + DWORD hasMotor; + beh->GetLocalParameterValue(0,&hasMotor); + beh->EnableInputParameter(bI_Motor,hasMotor); + + + break; + } + } + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pJoint/PJRevolute.cpp b/usr/Src/Behaviors/pJoint/PJRevolute.cpp new file mode 100644 index 0000000..07a7044 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJRevolute.cpp @@ -0,0 +1,485 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJRevoluteDecl(); +CKERROR CreatePJRevoluteProto(CKBehaviorPrototype **pproto); +int PJRevolute(const CKBehaviorContext& behcontext); +CKERROR PJRevoluteCB(const CKBehaviorContext& behcontext); + +enum bbInputs +{ + + bI_ObjectB, + bI_Anchor, + bI_AnchorRef, + bI_Axis, + bI_AxisRef, + bbI_Collision, + bbI_PMode, + bbI_PDistance, + bbI_PAngle, + bbI_Spring, + bbI_HighLimit, + bbI_LowLimit, + bbI_Motor +}; + +//************************************ +// Method: FillBehaviorPJRevoluteDecl +// FullName: FillBehaviorPJRevoluteDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJRevoluteDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJRevolute"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Sets/modifies a revolute joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x77cb361c,0x670112a9)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJRevoluteProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJRevoluteProto +// FullName: CreatePJRevoluteProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJRevoluteProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJRevolute"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PJRevolute + +
+ PJRevolute is categorized in \ref Joints +
+
See PJRevolute.cmo. + +

Description

+ Apply to a 3DEntity
+ Creates or modifies a revolute joint. +
+
+ DOFs removed: 5
+ DOFs remaining: 1
+
+ \image html revoluteJoint.png + + A revolute joint removes all but a single rotational degree of freedom from two objects. + The axis along which the two bodies may rotate is specified with a point and a direction + vector. In theory, the point along the direction vector does not matter, but in practice, + it should be near the area where the bodies are closest to improve simulation stability. + + An example for a revolute joint is a door hinge. + Another example would be using a revolute joint to attach rotating fan blades to a + ceiling. The revolute joint could be motorized, causing the fan to rotate. + +

Technical Information

+ + \image html PJRevolute.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body. Leave blank to create a joint constraint with the world. +
+
+ + Anchor:A point in world space coordinates. See pJointRevolute::setGlobalAnchor(). +
+ Anchor Reference: A helper entity to transform a local anchor into the world space. +
+ + Axis: An in world space. See pJointRevolute::setGlobalAxis(). +
+ Axis Up Reference: A helper entity to transform a local axis into the world space. +
+
+
+ + Collision: Enable Collision. See pJointRevolute::enableCollision(). +
+ +
+ Projection Mode: Joint projection mode. See pJointRevolute::setProjectionMode() and #ProjectionMode. +
+ + Projection Distance: If any joint projection is used, it is also necessary to set + projectionDistance to a small value greater than zero. When the joint error is larger than projectionDistance the SDK will change it so that the joint error is equal to projectionDistance. Setting projectionDistance too + small will introduce unwanted oscillations into the simulation.See pJointRevolute::setProjectionDistance(). +
+ + Projection Angle: Angle must be greater than 0.02f .If its smaller then current algo gets too close to a singularity. See pJointRevolute::setProjectionAngle(). +
+ + +
+ Spring: Make it springy.See pJointRevolute::setSpring(). +
+ +
+ High Limit: Higher rotation limit around the rotation axis. See pJointRevolute::setHighLimit(). +
+ + Low Limit: Lower rotation limit around rotation axis. See pJointRevolute::setLowLimit(). +
+ +
+ Motor: Motor parameters. See pJointRevolute::setMotor(). +
+
+ +
+ + Spring: Enables parameter input for spring settings. +
+ + High Limit: Enables parameter inputs for angular limits. +
+ + + Motor: Enables parameter input for motor settings. +
+ + + +

Revolute Joint Limits

+ + A revolute joint allows limits to be placed on how far it rotates around the joint axis. For example, a hinge on a door cannot rotate through 360 degrees; rather, it can rotate between 20 degrees and 180 degrees. + The angle of rotation is measured using the joints normal (axis orthogonal to the joints axis). This is the angle reported by NxRevoluteJoint::getAngle(). The limits are specified as a high and low limit, which must satisfy the condition -Pi < low < high + + Note : The white region represents the allowable rotation for the joint. + +

Limitations of Revolute Joint Limits

+ As shown below, it is not possible to specify certain limit configurations without rotating the joint axes, due to the restrictions on the values of low and high: + \image html revoluteLimitLimitation.png + + To achieve this configuration, it is necessary to rotate the joint counter-clockwise so that low is below the 180 degree line. + + NOTE: If the angular region that is prohibited by the twist limit (as in the above figures) is very small, only a few degrees or so, then the joint may "push through" the limit and out on the other side if the relative angular velocity is large enough in relation to the time step. Care must be taken to make sure the limit is "thick" enough for the typical angular velocities it will be subjected to. + + +
+

Warning

+ The body must be dynamic. +
+
+ +

VSL : Creation


+ + \include PJRevolute.vsl + +
+ +

VSL : Limit Modification


+ + \include PJRevoluteSetLimits.vsl + +
+ +

VSL : Motor Modification


+ + \include PJRevoluteSetMotor.vsl + +
+
+
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createJointRevolute().
+ + */ + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + proto->SetBehaviorCallbackFct( PJRevoluteCB ); + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + + proto->DeclareInParameter("Anchor",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY,"0.0f"); + + proto->DeclareInParameter("Axis",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Axis Up Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Collision",CKPGUID_BOOL); + proto->DeclareInParameter("Projection Mode",VTE_JOINT_PROJECTION_MODE,"0"); + proto->DeclareInParameter("Projection Distance",CKPGUID_FLOAT,"0"); + proto->DeclareInParameter("Projection Angle",CKPGUID_FLOAT,"0.025"); + + proto->DeclareInParameter("Spring",VTS_JOINT_SPRING); + proto->DeclareInParameter("High Limit",VTS_JLIMIT); + proto->DeclareInParameter("Low Limit",VTS_JLIMIT); + proto->DeclareInParameter("Motor",VTS_JOINT_MOTOR); + + + proto->DeclareSetting("Spring",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Limit",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Motor",CKPGUID_BOOL,"FALSE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJRevolute); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJRevolute +// FullName: PJRevolute +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJRevolute(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + + + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Revolute)) + { + + return CK_OK; + } + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA && ! worldB ) + { + return 0; + } + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + + + //anchor : + VxVector anchor = GetInputParameterValue(beh,bI_Anchor); + VxVector anchorOut = anchor; + CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); + if (anchorReference) + { + anchorReference->Transform(&anchorOut,&anchor); + } + + //swing axis + VxVector Axis = GetInputParameterValue(beh,bI_Axis); + VxVector axisOut = Axis; + CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); + + if (axisReference) + { + VxVector dir,up,right; + axisReference->GetOrientation(&dir,&up,&right); + axisReference->TransformVector(&axisOut,&up); + } + + ////////////////////////////////////////////////////////////////////////// + //limit high : + pJointLimit limitH; + pJointLimit limitL; + DWORD limit; + beh->GetLocalParameterValue(1,&limit); + if (limit) + { + CKParameterIn *par = beh->GetInputParameter(bbI_HighLimit); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + limitH = pFactory::Instance()->createLimitFromParameter(rPar); + } + } + } + + if (limit) + { + CKParameterIn *par = beh->GetInputParameter(bbI_LowLimit); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + limitL = pFactory::Instance()->createLimitFromParameter(rPar); + } + } + } + + ////////////////////////////////////////////////////////////////////////// + DWORD spring; + pSpring sSpring; + beh->GetLocalParameterValue(0,&spring); + if (spring) + { + CKParameterIn *par = beh->GetInputParameter(bbI_Spring); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + sSpring = pFactory::Instance()->createSpringFromParameter(rPar); + } + } + } + + pMotor motor; + + DWORD hasMotor;beh->GetLocalParameterValue(2,&hasMotor); + if (hasMotor) + { + CKParameterIn *par = beh->GetInputParameter(bbI_Motor); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + motor = pFactory::Instance()->createMotorFromParameter(rPar); + } + } + } + + + int col = GetInputParameterValue(beh,bbI_Collision); + ProjectionMode mode =GetInputParameterValue(beh,bbI_PMode); + float distance = GetInputParameterValue(beh,bbI_PDistance); + float angle= GetInputParameterValue(beh,bbI_PAngle); + + ////////////////////////////////////////////////////////////////////////// + // + pJointRevolute *joint = static_cast(worldA->getJoint(target,targetB,JT_Revolute)); + if(bodyA || bodyB) + { + ////////////////////////////////////////////////////////////////////////// + //joint create ? + if (!joint) + { + joint = static_cast(pFactory::Instance()->createRevoluteJoint(target,targetB,anchorOut,axisOut)); + } + ////////////////////////////////////////////////////////////////////////// Modification : + if (joint) + { + + joint->setGlobalAxis(axisOut); + joint->setGlobalAnchor(anchorOut); + + if (mode!=0) + { + joint->setProjectionMode(mode); + joint->setProjectionDistance(distance); + joint->setProjectionAngle(angle); + } + + ////////////////////////////////////////////////////////////////////////// + if(limit) + { + joint->setHighLimit(limitH); + joint->setLowLimit(limitL); + } + + ////////////////////////////////////////////////////////////////////////// + if (spring) + { + joint->setSpring(sSpring); + } + + if (hasMotor) + { + joint->setMotor(motor); + } + + joint->enableCollision(col); + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: PJRevoluteCB +// FullName: PJRevoluteCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJRevoluteCB(const CKBehaviorContext& behcontext) +{ + + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + DWORD twistLimit; + beh->GetLocalParameterValue(1,&twistLimit); + beh->EnableInputParameter(bbI_HighLimit,twistLimit); + beh->EnableInputParameter(bbI_LowLimit,twistLimit); + + DWORD springSwing; + beh->GetLocalParameterValue(0,&springSwing); + beh->EnableInputParameter(bbI_Spring,springSwing); + + DWORD motor; + beh->GetLocalParameterValue(2,&motor); + beh->EnableInputParameter(bbI_Motor,motor); + + break; + } + } + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pJoint/PJSetBall.cpp b/usr/Src/Behaviors/pJoint/PJSetBall.cpp new file mode 100644 index 0000000..f7eb979 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJSetBall.cpp @@ -0,0 +1,518 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorJSetBallDecl(); +CKERROR CreateJSetBallProto(CKBehaviorPrototype **pproto); +int JSetBall(const CKBehaviorContext& behcontext); +CKERROR JSetBallCB(const CKBehaviorContext& behcontext); + +enum bbInputs +{ + + bI_ObjectB, + bI_Anchor, + bI_AnchorRef, + bbI_SwingAxis, + bbI_PMode, + bbI_PDistance, + bbI_Collision, + bbI_SwingLimit, + bbI_TwistHighLimit, + bbI_TwistLowLimit, + bbI_SwingSpring, + bbI_TwistSpring, + bbI_JointSpring +}; + +//************************************ +// Method: FillBehaviorJSetBallDecl +// FullName: FillBehaviorJSetBallDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorJSetBallDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJBall"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Sets/modifies a ball joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x2df921e4,0x20295f52)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateJSetBallProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateJSetBallProto +// FullName: CreateJSetBallProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateJSetBallProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJBall"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PJBall + +
+ PJBall is categorized in \ref Joints +
+
See pJBall.cmo. + +

Description

+ Apply to a 3DEntity
+ Creates or modifies a sphere joint. +
+
+ DOFs removed: 3
+ DOFs remaining: 3
+
+ \image html sphericalJoint.png + + A spherical joint is the simplest kind of joint. It constrains two points on two different bodies from coinciding. + This point, located in world space, is the only parameter that has to be specified (the other parameters are optional). + Specifying the anchor point (point that is forced to coincide) in world space guarantees that the point in the local space of each + body will coincide when the point is transformed back from local into world space. + + By attaching a series of spherical joints and bodies, chains/ropes can be created. + Another example for a common spherical joint is a person's shoulder, which is quite limited in its range of motion. + + +

Technical Information

+ + \image html PJBall.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body. Leave blank to create a joint constraint with the world. +
+
+ Anchor:A point in world space coordinates. See pJointBall::setAnchor(). +
+ Anchor Reference: A helper entity to transform a local anchor into the world space. +
+ Swing Limt Axis: Limit axis defined in the joint space of body a. See pJointBall::setSwingLimitAxis(). +
+ Projection Mode: Joint projection mode. See pJointBall::setProjectionMode() and #ProjectionMode. +
+
+ Projection Distance: If any joint projection is used, it is also necessary to set + projectionDistance to a small value greater than zero. When the joint error is larger than projectionDistance the SDK will change it so that the joint error is equal to projectionDistance. Setting projectionDistance too + small will introduce unwanted oscillations into the simulation. +
+ Collision :Enable Collision. See pJointRevolute::enableCollision(). +
+
+ Swing Limit: Swing limit of the twist axis. +
+
+ Twist High Limit: Higher rotation limit around twist axis. See pJointBall::setTwistHighLimit(). +
+
+ Twist Low Limit: Lower rotation limit around twist axis. See pJointBall::setTwistLowLimit(). +
+
+ + Swing Spring: .The spring that works against swinging. See pJointBall::setSwingSpring(). +
+ + Twist Spring: .The spring that works against twisting. See pJointBall::setTwistSpring(). +
+ + Joint Spring: .The spring that lets the joint get pulled apart. See pJointBall::setJointSpring(). +
+
+
+ + + Swing Limit: Enables parameter input for swing limit. +
+ Twist High Limit: Enables parameter input for high twist limit. +
+ Twist Low Limit: Enables parameter input for low twist limit. +
+ Swing Spring: .Enables parameter input for swing spring. +
+ Twist Spring: .Enables parameter input for twist spring. +
+ Joint Spring: .Enables parameter input for joint spring. +
+ +

Spherical Joint Limits

+ + Spherical joints allow limits that can approximate the physical limits of motion on a human arm. + It is possible to specify a cone which limits how far the arm can swing from a given axis. + In addition, a twist limit can be specified which controls how much the arm is allowed to twist around its own axis. + + \image html sphericalLimits.png + + NOTE: There are similar restrictions on the twist limits for spherical joints as there are for revolute joints. + +
+

Warning

+ The body must be dynamic. +
+
+ +

VSL : Creation


+ + \include PJSetBall.vsl + +
+ +

VSL : Limit Modification


+ + \include PJSetBallLimits.vsl + +
+
+
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createJointBall().
+ + */ + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + proto->SetBehaviorCallbackFct( JSetBallCB ); + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + + proto->DeclareInParameter("Anchor",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Anchor Reference",CKPGUID_3DENTITY,"0.0f"); + proto->DeclareInParameter("Limit Swing Axis",CKPGUID_VECTOR,"0.0f"); + + proto->DeclareInParameter("Projection Mode",VTE_JOINT_PROJECTION_MODE,"0"); + proto->DeclareInParameter("Projection Distance",CKPGUID_FLOAT,"0"); + proto->DeclareInParameter("Collision",CKPGUID_BOOL,"TRUE"); + + + + proto->DeclareInParameter("Swing Limit",VTS_JLIMIT,""); + proto->DeclareInParameter("Twist High Limit",VTS_JLIMIT); + proto->DeclareInParameter("Twist Low Limit",VTS_JLIMIT); + + proto->DeclareInParameter("Swing Spring",VTS_JOINT_SPRING); + proto->DeclareInParameter("Twist Spring",VTS_JOINT_SPRING); + proto->DeclareInParameter("Joint Spring",VTS_JOINT_SPRING); + + + + proto->DeclareSetting("Swing Limit",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Twist Limit",CKPGUID_BOOL,"FALSE"); + + + proto->DeclareSetting("Swing Spring",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Twist Spring",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Joint Spring",CKPGUID_BOOL,"FALSE"); + + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(JSetBall); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: JSetBall +// FullName: JSetBall +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int JSetBall(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + + + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Spherical)) + { + + return CK_OK; + } + + + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA && ! worldB ) + { + return 0; + } + if (!worldA) + { + worldA = worldB; + } + + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + + + //anchor : + VxVector anchor = GetInputParameterValue(beh,bI_Anchor); + VxVector anchorOut = anchor; + CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); + + if (anchorReference) + { + anchorReference->Transform(&anchorOut,&anchor); + } + + //swing axis + VxVector swingAxis = GetInputParameterValue(beh,bbI_SwingAxis); + + ProjectionMode mode =GetInputParameterValue(beh,bbI_PMode); + float distance = GetInputParameterValue(beh,bbI_PDistance); + int coll = GetInputParameterValue(beh,bbI_Collision); + + + + ////////////////////////////////////////////////////////////////////////// + //swing limit : + pJointLimit sLimit; + DWORD swingLimit; + beh->GetLocalParameterValue(0,&swingLimit); + if (swingLimit) + { + CKParameterIn *par = beh->GetInputParameter(bbI_SwingLimit); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + sLimit = pFactory::Instance()->createLimitFromParameter(rPar); + } + } + } + ////////////////////////////////////////////////////////////////////////// + //twist limit high : + pJointLimit tLimitH; + DWORD twistLimit; + beh->GetLocalParameterValue(1,&twistLimit); + if (twistLimit) + { + CKParameterIn *par = beh->GetInputParameter(bbI_TwistHighLimit); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + tLimitH = pFactory::Instance()->createLimitFromParameter(rPar); + + } + } + } + ////////////////////////////////////////////////////////////////////////// + //twist limit low : + pJointLimit tLimitL; + if (twistLimit) + { + CKParameterIn *par = beh->GetInputParameter(bbI_TwistLowLimit); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + tLimitL = pFactory::Instance()->createLimitFromParameter(rPar); + } + } + } + + ////////////////////////////////////////////////////////////////////////// + DWORD swingSpring; + pSpring sSpring; + beh->GetLocalParameterValue(2,&swingSpring); + if (swingSpring) + { + CKParameterIn *par = beh->GetInputParameter(bbI_SwingSpring); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + sSpring = pFactory::Instance()->createSpringFromParameter(rPar); + } + } + } + ////////////////////////////////////////////////////////////////////////// + DWORD twistSpring; + pSpring tSpring; + beh->GetLocalParameterValue(3,&twistSpring); + if (twistSpring) + { + CKParameterIn *par = beh->GetInputParameter(bbI_TwistSpring); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + tSpring= pFactory::Instance()->createSpringFromParameter(rPar); + } + } + } + ////////////////////////////////////////////////////////////////////////// + // + DWORD jointSpring; + pSpring jSpring; + beh->GetLocalParameterValue(4,&jointSpring); + if (jointSpring) + { + CKParameterIn *par = beh->GetInputParameter(bbI_JointSpring); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + jSpring = pFactory::Instance()->createSpringFromParameter(rPar); + } + } + } + pJointBall *joint = static_cast(worldA->getJoint(target,targetB,JT_Spherical)); + if(bodyA || bodyB) + { + ////////////////////////////////////////////////////////////////////////// + //joint create ? + if (!joint) + { + joint = static_cast(pFactory::Instance()->createBallJoint(target,targetB,anchorOut,swingAxis)); + } + ////////////////////////////////////////////////////////////////////////// Modification : + if (joint) + { + + joint->setAnchor(anchorOut); + joint->setSwingLimitAxis(swingAxis); + joint->setProjectionMode(mode); + joint->setProjectionDistance(distance); + joint->enableCollision(coll); + + + ////////////////////////////////////////////////////////////////////////// + if(swingLimit) + { + joint->setSwingLimit(sLimit); + } + joint->enableFlag(NX_SJF_SWING_LIMIT_ENABLED,swingLimit); + + ////////////////////////////////////////////////////////////////////////// + if (twistLimit) + { + joint->setTwistHighLimit(tLimitH); + joint->setTwistLowLimit(tLimitL); + } + joint->enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,twistLimit); + + ////////////////////////////////////////////////////////////////////////// + if (swingSpring) + { + joint->setSwingSpring(sSpring); + } + joint->enableFlag(NX_SJF_SWING_SPRING_ENABLED,swingSpring); + ////////////////////////////////////////////////////////////////////////// + if (twistSpring) + { + joint->setTwistSpring(tSpring); + } + joint->enableFlag(NX_SJF_TWIST_SPRING_ENABLED,twistSpring); + ////////////////////////////////////////////////////////////////////////// + if (jointSpring) + { + joint->setJointSpring(jSpring); + } + joint->enableFlag(NX_SJF_JOINT_SPRING_ENABLED,jointSpring); + + } + } + + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: JSetBallCB +// FullName: JSetBallCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR JSetBallCB(const CKBehaviorContext& behcontext) +{ + + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + DWORD swingLimit; + beh->GetLocalParameterValue(0,&swingLimit); + beh->EnableInputParameter(bbI_SwingLimit,swingLimit); + + DWORD twistLimit; + beh->GetLocalParameterValue(1,&twistLimit); + beh->EnableInputParameter(bbI_TwistHighLimit,twistLimit); + beh->EnableInputParameter(bbI_TwistLowLimit,twistLimit); + + DWORD springSwing; + beh->GetLocalParameterValue(2,&springSwing); + beh->EnableInputParameter(bbI_SwingSpring,springSwing); + + DWORD twistSwing; + beh->GetLocalParameterValue(3,&twistSwing); + beh->EnableInputParameter(bbI_TwistSpring,twistSwing); + + DWORD jointSwing; + beh->GetLocalParameterValue(4,&jointSwing); + beh->EnableInputParameter(bbI_JointSpring,jointSwing); + + break; + } + } + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pJoint/PJSetBreakForces.cpp b/usr/Src/Behaviors/pJoint/PJSetBreakForces.cpp new file mode 100644 index 0000000..0ece9b6 --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJSetBreakForces.cpp @@ -0,0 +1,220 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPJSetBreakForcesDecl(); +CKERROR CreatePJSetBreakForcesProto(CKBehaviorPrototype **pproto); +int PJSetBreakForces(const CKBehaviorContext& behcontext); +CKERROR PJSetBreakForcesCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_BodyB, + bbI_Type, + bbI_MaxForce, + bbI_MaxTorque +}; + +//************************************ +// Method: FillBehaviorPJSetBreakForcesDecl +// FullName: FillBehaviorPJSetBreakForcesDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPJSetBreakForcesDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJSetBreakForces"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Sets the maximum forces on a joint."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x3ace1062,0x265d33c5)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePJSetBreakForcesProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePJSetBreakForcesProto +// FullName: CreatePJSetBreakForcesProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePJSetBreakForcesProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJSetBreakForces"); + if(!proto) return CKERR_OUTOFMEMORY; + + + /*! \page PJSetBreakForces + +
+ PJSetBreakForces is categorized in \ref Joints +
+ + +

Description

+ Apply to a 3DEntity
+ Sets a joint as breakable or unbreakable. + +
+ +

Technical Information

+ + + Joints can be set to be breakable. This means that if a joint is tugged on with a large enough force, it will snap apart. To set a breakable joint, set the maxForce and maxTorque members of NxJointDesc to the desired values - the smaller the value, the more easily the joint will break. The maxForce defines the limit for linear forces that can be applied to a joint before it breaks, while the maxTorque defines the limit for angular forces. The exact behavior depends on the type of joint. It is possible to change these parameters for an existing joint using #pJoint::setBreakForces(). + + When a joint breaks, the \ref PJIsBroken will be called. + + Maximum Force and maximum Torque + + The distinction between maxForce and maxTorque is dependent on how the joint is implemented internally, which may not be obvious. For example, what appears to be an angular degree of freedom may be constrained indirectly by a linear constraint. + + Therefore, in most practical applications the user should set both maxTorque and maxForce to similar values. + + In the current implementation, the following joints use angular constraints: + + - \ref PJD6 - Only in the case where angular DOFs are locked. + - \ref PJFixed + - \ref PJPrismatic + - \ref PJRevolute + + + \image html PJSetBreakForces.png + + + In: triggers the process +
+ Out: is activated when the process is completed. +
+ + Body B: The second body. Leave blank to create a joint constraint with the world. +
+ + Joint Type: The joint type. This helps the building block to identify a joint constraint. As usual there can be only one joint of the type x between two bodies. +
+ + Maximum Force: Maximum force the joint can withstand without breaking. + - Range: (0,inf] +
+ + Maximum Torque: Maximum torque the joint can withstand without breaking. + - Range: (0,inf] +
+ + + \Note If Maximum Force = 0.0 AND Maximum Torque = 0.0 the joint becomes unbreakable. + +

VSL : Set break forces


+ + \include pJSetBreakForces.vsl + +
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pJoint::setBreakForces().
+ */ + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + + proto->SetBehaviorCallbackFct( PJSetBreakForcesCB ); + + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + proto->DeclareInParameter("Joint Type",VTE_JOINT_TYPE,"0"); + proto->DeclareInParameter("Maximum Force",CKPGUID_FLOAT,"0"); + proto->DeclareInParameter("Maximum Torque",CKPGUID_FLOAT,"0"); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PJSetBreakForces); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PJSetBreakForces +// FullName: PJSetBreakForces +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PJSetBreakForces(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A + B: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bbI_BodyB); + + int jointType = GetInputParameterValue(beh,bbI_Type); + float maxForce = GetInputParameterValue(beh,bbI_MaxForce); + float maxTorque = GetInputParameterValue(beh,bbI_MaxTorque); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,jointType)) + return CK_OK; + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + + + // the physic object A && B: + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + //at least one needs to be there + if(bodyA || bodyB) + { + pJoint *joint = (worldA->getJoint(target,targetB,(JType)jointType)); + if (joint) + joint->setBreakForces(maxForce,maxTorque); + } + beh->ActivateOutput(0); + } + return 0; +} +//************************************ +// Method: PJSetBreakForcesCB +// FullName: PJSetBreakForcesCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PJSetBreakForcesCB(const CKBehaviorContext& behcontext) +{ + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pJoint/PJSetFixed.cpp b/usr/Src/Behaviors/pJoint/PJSetFixed.cpp new file mode 100644 index 0000000..15f634d --- /dev/null +++ b/usr/Src/Behaviors/pJoint/PJSetFixed.cpp @@ -0,0 +1,187 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorJSetFixedDecl(); +CKERROR CreateJSetFixedProto(CKBehaviorPrototype **pproto); +int JSetFixed(const CKBehaviorContext& behcontext); +CKERROR JSetFixedCB(const CKBehaviorContext& behcontext); + + + +//************************************ +// Method: FillBehaviorJSetFixedDecl +// FullName: FillBehaviorJSetFixedDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorJSetFixedDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PJFixed"); + od->SetCategory("Physic/Joints"); + od->SetDescription("Creates a Fixed Joint between world('None') or an entity."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x2d80b0a,0x3d5a0caf)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateJSetFixedProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateJSetFixedProto +// FullName: CreateJSetFixedProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateJSetFixedProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PJFixed"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PJFixed + +
+ PJFixed is categorized in \ref Joints +
+ +

Description

+ Apply to a 3DEntity
+ Creates a fixed joint between a two bodies or the world. +
+
+ + + \image html fixedJoint.png + + + +

Technical Information

+ + \image html PJFixed.png + + The fixed joint effectively glues two bodies together with no remaining degrees of freedom for relative motion. It is useful to set it to be breakable (see Breakable Joint) to simulate simple fracture effects. + + An example for a fixed joint is a factory chimney divided into sections, each section held together with fixed joints. When the chimney is hit, it will break apart and topple over by sections rather than unrealistically falling over in one piece. + + DOFs removed: 6 + DOFs remaining: 0 + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Body B: The second body. Leave blank to create a joint constraint with the world. +
+
+ + +

VSL : Creation


+ + \include pJFixed.vsl + +
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createJointFixed().
+ + */ + + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("Body B",CKPGUID_3DENTITY,"ball2"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(JSetFixed); + proto->SetBehaviorCallbackFct( JSetFixedCB); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: JSetFixed +// FullName: JSetFixed +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int JSetFixed(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object A: + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); + + if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Fixed)) + { + return CK_OK; + } + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(target); + pWorld *worldB=GetPMan()->getWorldByBody(targetB); + if (!worldA) + { + worldA = worldB; + } + if (!worldA) + { + beh->ActivateOutput(0); + return 0; + } + // the physic object A : + pRigidBody*bodyA= worldA->getBody(target); + pRigidBody*bodyB= worldA->getBody(targetB); + + if(bodyA || bodyB) + { + + pJointFixed*joint =static_cast(worldA->getJoint(target,targetB,JT_Fixed)); + + if (!joint) + { + joint = static_cast(pFactory::Instance()->createFixedJoint(target,targetB)); + } + beh->ActivateOutput(0); + } + } + return 0; +} +//************************************ +// Method: JSetFixedCB +// FullName: JSetFixedCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR JSetFixedCB(const CKBehaviorContext& behcontext) +{ + + return CKBR_OK; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pManager/PManager.cpp b/usr/Src/Behaviors/pManager/PManager.cpp new file mode 100644 index 0000000..b44f3e8 --- /dev/null +++ b/usr/Src/Behaviors/pManager/PManager.cpp @@ -0,0 +1,180 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPManagerDecl(); +CKERROR CreatePManagerProto(CKBehaviorPrototype **pproto); +int PManager(const CKBehaviorContext& behcontext); +CKERROR PManagerCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_ReloadXML, +}; + + +#define BB_SSTART 0 + +BBParameter pInMapM[] = +{ + + + BB_SPIN(bbI_ReloadXML,CKPGUID_STRING,"XML File","None"), + +}; + +#define gPIMAP pInMapM + +//************************************ +// Method: FillBehaviorPManagerDecl +// FullName: FillBehaviorPManagerDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPManagerDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PManager"); + od->SetCategory("Physic/Manager"); + od->SetDescription("Calls various functions in the manager."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x57295d90,0x11da3970)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePManagerProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePManagerProto +// FullName: CreatePManagerProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePManagerProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PManager"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + proto->SetBehaviorCallbackFct( PManagerCB ); + + BB_EVALUATE_SETTINGS(gPIMAP) + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PManager); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PManager +// FullName: PManager +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PManager(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + BB_DECLARE_PIMAP; + + + + /************************************************************************/ + /* retrieve settings state */ + /************************************************************************/ + BBSParameter(bbI_ReloadXML); + + + /************************************************************************/ + /* retrieve values */ + /************************************************************************/ + + + ////////////////////////////////////////////////////////////////////////// + // load some settings from XML + if(sbbI_ReloadXML) + { + CKSTRING xmlFile = GetInputParameterValue(beh,BB_IP_INDEX(bbI_ReloadXML)); + pFactory::Instance()->reloadConfig(xmlFile); + + } + + + + + + } + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PManagerCB +// FullName: PManagerCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PManagerCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pManager/xRegisterAttributeType.cpp b/usr/Src/Behaviors/pManager/xRegisterAttributeType.cpp new file mode 100644 index 0000000..c21f39a --- /dev/null +++ b/usr/Src/Behaviors/pManager/xRegisterAttributeType.cpp @@ -0,0 +1,198 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorRegisterAttributeTypeDecl(); +CKERROR CreateRegisterAttributeTypeProto(CKBehaviorPrototype **pproto); +int RegisterAttributeType(const CKBehaviorContext& behcontext); +CKERROR RegisterAttributeTypeCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_Name, + bbI_Category, + bbI_DefValue, + bbI_PType, + bbI_Class, + bbI_User, + bbI_Save, + + + +}; + + + + +//************************************ +// Method: FillBehaviorRegisterAttributeTypeDecl +// FullName: FillBehaviorRegisterAttributeTypeDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorRegisterAttributeTypeDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("RegisterAttribute"); + od->SetCategory("Physic/Manager"); + od->SetDescription("Registers a new attribute type."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x63e567c4,0x65583276)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateRegisterAttributeTypeProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateRegisterAttributeTypeProto +// FullName: CreateRegisterAttributeTypeProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateRegisterAttributeTypeProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("RegisterAttribute"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + proto->DeclareOutput("Error"); + + proto->DeclareInParameter("Name",CKPGUID_STRING); + proto->DeclareInParameter("Category",CKPGUID_STRING); + proto->DeclareInParameter("Default Value",CKPGUID_STRING); + proto->DeclareInParameter("Parameter Type",CKPGUID_PARAMETERTYPE); + proto->DeclareInParameter("Compatible Class",CKPGUID_CLASSID); + + proto->DeclareInParameter("User",CKPGUID_BOOL,"TRUE"); + proto->DeclareInParameter("Save",CKPGUID_BOOL,"TRUE"); + + + proto->SetBehaviorCallbackFct( RegisterAttributeTypeCB ); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + + proto->SetFunction(RegisterAttributeType); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: RegisterAttributeType +// FullName: RegisterAttributeType +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int RegisterAttributeType(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + CKAttributeManager* attman = ctx->GetAttributeManager(); + CKParameterManager *pMan = ctx->GetParameterManager(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + CKSTRING name = GetInputParameterValue(beh,bbI_Name); + CKSTRING category = GetInputParameterValue(beh,bbI_Category); + CKSTRING defValue = GetInputParameterValue(beh,bbI_DefValue); + int pType = GetInputParameterValue(beh,bbI_PType); + CK_CLASSID classId = GetInputParameterValue(beh,bbI_Class); + + int attFlags = 0 ; + int user = GetInputParameterValue(beh,bbI_User); + int save = GetInputParameterValue(beh,bbI_Save); + + if(user) + attFlags|=CK_ATTRIBUT_USER; + + if(save) + attFlags|=CK_ATTRIBUT_TOSAVE; + + attFlags|=CK_ATTRIBUT_CAN_DELETE; + + CKAttributeType aIType = attman->GetAttributeTypeByName(name); + if (aIType!=-1) + { + beh->ActivateOutput(1); + } + + int att = attman->RegisterNewAttributeType(name,pMan->ParameterTypeToGuid(pType),classId,(CK_ATTRIBUT_FLAGS)attFlags); + + if (strlen(category)) + { + attman->AddCategory(category); + attman->SetAttributeCategory(att,category); + } + if (strlen(defValue)) + { + attman->SetAttributeDefaultValue(att,defValue); + } + + } + pm->populateAttributeFunctions(); + pm->_RegisterAttributeCallbacks(); + + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: RegisterAttributeTypeCB +// FullName: RegisterAttributeTypeCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR RegisterAttributeTypeCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + /* + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + */ + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pMisc/LogOut.cpp b/usr/Src/Behaviors/pMisc/LogOut.cpp new file mode 100644 index 0000000..9a9e488 --- /dev/null +++ b/usr/Src/Behaviors/pMisc/LogOut.cpp @@ -0,0 +1,209 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorLogEntryDecl(); +CKERROR CreateLogEntryProto(CKBehaviorPrototype **); +int LogEntry(const CKBehaviorContext& behcontext); +CKERROR LogEntryCB(const CKBehaviorContext& behcontext); + + + +#define BEH_IN_INDEX_MIN_COUNT 2 +#define BEH_OUT_MIN_COUNT 0 +#define BEH_OUT_MAX_COUNT 1 + + + +CKObjectDeclaration *FillBehaviorLogEntryDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("pLogEvent"); + od->SetDescription("Displays Internal Log Entries"); + + od->SetCategory("Physics/Manager"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x512542dc,0x1b836fd9)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateLogEntryProto); + od->SetCompatibleClassId(CKCID_OBJECT); + return od; +} + + +CKERROR CreateLogEntryProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("pLogEvent"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareInput("Off"); + proto->DeclareOutput("Message"); + + proto->DeclareOutput("Error"); + proto->DeclareOutput("Warning"); + proto->DeclareOutput("Info"); + proto->DeclareOutput("Trace"); + proto->DeclareOutput("Debug"); + + + + proto->DeclareOutParameter("Entry",CKPGUID_STRING); + + proto->DeclareOutParameter("Type",CKPGUID_INT); + proto->DeclareOutParameter("Component",CKPGUID_STRING); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)( CKBEHAVIOR_VARIABLEPARAMETERINPUTS )); + proto->SetFunction(LogEntry); + proto->SetBehaviorCallbackFct(LogEntryCB); + + + *pproto = proto; + + + return CK_OK; + +} + + +int LogEntry(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKMessageManager* mm = behcontext.MessageManager; + CKContext* ctx = behcontext.Context; + CKParameterManager *pam = static_cast(ctx->GetParameterManager()); + + + XString File((CKSTRING) beh->GetInputParameterReadDataPtr(0)); + + + if (GetPMan()->GetLastLogEntry().Length()) + { + CKParameterOut *pout = beh->GetOutputParameter(0); + pout->SetStringValue(GetPMan()->GetLastLogEntry().Str()); + GetPMan()->SetLastLogEntry(""); + + + vtTools::BehaviorTools::SetOutputParameterValue(beh,1,xLogger::GetInstance()->lastTyp); + int descriptionS = xLogger::GetInstance()->getItemDescriptions().size(); + + int compo = xLogger::GetInstance()->lastComponent; + + XString compoStr; + /*if(compo<= xLogger::GetInstance()->getItemDescriptions().size() ) + compoStr.Format("%s",xLogger::GetInstance()->getItemDescriptions().at(compo));*/ + + + + beh->ActivateOutput(0,TRUE); + switch (xLogger::GetInstance()->lastTyp) + { + + case ELOGERROR: + beh->ActivateOutput(1,TRUE); + + case ELOGWARNING: + beh->ActivateOutput(2,TRUE); + + case ELOGINFO: + beh->ActivateOutput(3,TRUE); + + case ELOGTRACE: + beh->ActivateOutput(4,TRUE); + + case ELOGDEBUG: + beh->ActivateOutput(5,TRUE); + default: + beh->ActivateOutput(0,TRUE); + + } + + + + } + + + // Steering + if( beh->IsInputActive(1) ) + { + beh->ActivateOutput(0,FALSE); + + return 1; + } + return CKBR_ACTIVATENEXTFRAME; +} + +CKERROR LogEntryCB(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKBeObject *beo = (CKBeObject *)beh->GetTarget(); + + if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) + { + /* CKParameterIn* pin = beh->GetInputParameter(0); + if (!pin) { + CKBehavior* pbeh = beh; + XString name; + while ((pbeh=pbeh->GetParent())) { + name << pbeh->GetName() << "->"; + } + name << beh->GetName(); + + XString str; + str << '[' << name << "] : failed to retrieve first input parameter"; + behcontext.Context->OutputToConsole(str.Str(),TRUE); + return CKBR_PARAMETERERROR; + } + + if (pin->GetGUID()!=CKPGUID_MESSAGE) { + pin->SetGUID(CKPGUID_MESSAGE,FALSE); + + CKBehavior* pbeh = beh; + XString name; + while ((pbeh=pbeh->GetParent())) { + name << pbeh->GetName() << "->"; + } + name << beh->GetName(); + + XString str; + str << '[' << name << "] : first input parameter type must be \"Message\"!"; + behcontext.Context->OutputToConsole(str.Str(),TRUE); + } + + pin = beh->GetInputParameter(1); + if (!pin) { + CKBehavior* pbeh = beh; + XString name; + while ((pbeh=pbeh->GetParent())) { + name << pbeh->GetName() << "->"; + } + name << beh->GetName(); + + XString str; + str << '[' << name << "] : failed to retrieve second input parameter"; + behcontext.Context->OutputToConsole(str.Str(),TRUE); + return CKBR_PARAMETERERROR; + } + + if (!behcontext.ParameterManager->IsDerivedFrom(pin->GetGUID(),CKPGUID_OBJECT)) { + pin->SetGUID(CKPGUID_BEOBJECT,FALSE); + + CKBehavior* pbeh = beh; + XString name; + while ((pbeh=pbeh->GetParent())) { + name << pbeh->GetName() << "->"; + } + name << beh->GetName(); + + XString str; + str << '[' << name << "] : second input parameter type must derived from \"BeObject\"!"; + behcontext.Context->OutputToConsole(str.Str(),TRUE); + }*/ + } + + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pMisc/pMisc.cpp b/usr/Src/Behaviors/pMisc/pMisc.cpp new file mode 100644 index 0000000..d5317fc --- /dev/null +++ b/usr/Src/Behaviors/pMisc/pMisc.cpp @@ -0,0 +1,117 @@ +#include +#include "pMisc.h" +#include "pCommon.h" + +namespace vtAgeia +{ + +int getHullTypeFromShape(NxShape *shape) +{ + + int result = - 1; + if (!shape) + { + return result; + } + + int nxType = shape->getType(); + switch (nxType) + { + case NX_SHAPE_PLANE: + return HT_Plane; + + case NX_SHAPE_BOX: + return HT_Box; + + case NX_SHAPE_SPHERE: + return HT_Sphere; + + case NX_SHAPE_CONVEX: + return HT_ConvexMesh; + + case NX_SHAPE_CAPSULE: + return HT_Capsule; + + case NX_SHAPE_MESH: + return HT_Mesh; + } + + return -1; + +} + + +XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide,int parameterSubIndex) +{ + + XString result="None"; + int pType = pm->ParameterGuidToType(parGuide); + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + if(i == parameterSubIndex) + { + result = enumStruct->GetEnumDescription(i); + } + } + } + return result; +} + +//************************************ +// Method: BoxGetZero +// FullName: vtAgeia::BoxGetZero +// Access: public +// Returns: VxVector +// Qualifier: +// Parameter: vt3DObject ent +//************************************ +VxVector BoxGetZero(CK3dEntity* ent) +{ + + VxVector box_s= VxVector(1,1,1); + if (ent) + { + + VxMatrix mat = ent->GetWorldMatrix(); + VxVector g; + Vx3DMatrixToEulerAngles(mat,&g.x,&g.y,&g.z); + SetEulerDirection(ent,VxVector(0,0,0)); + CKMesh *mesh = ent->GetCurrentMesh(); + + + if (mesh!=NULL) + { + box_s = mesh->GetLocalBox().GetSize(); + } + SetEulerDirection(ent,g); + } + return box_s; +} + +//************************************ +// Method: SetEulerDirection +// FullName: vtAgeia::SetEulerDirection +// Access: public +// Returns: void +// Qualifier: +// Parameter: CK3dEntity* ent +// Parameter: VxVector direction +//************************************ +void SetEulerDirection(CK3dEntity* ent,VxVector direction) +{ + + VxVector dir,up,right; + VxMatrix mat; + Vx3DMatrixFromEulerAngles(mat,direction.x,direction.y,direction.z); + dir=(VxVector)mat[2]; + up=(VxVector)mat[1]; + right=(VxVector)mat[0]; + ent->SetOrientation(&dir,&up,&right,NULL,FALSE); + +} + + +} diff --git a/usr/Src/Behaviors/pRigidBody/PBAddForce.cpp b/usr/Src/Behaviors/pRigidBody/PBAddForce.cpp new file mode 100644 index 0000000..769ed2d --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddForce.cpp @@ -0,0 +1,174 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBAddForceDecl(); +CKERROR CreatePBAddForceProto(CKBehaviorPrototype **pproto); +int PBAddForce(const CKBehaviorContext& behcontext); +CKERROR PBAddForceCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPBAddForceDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddForce"); + od->SetCategory("Physic/Body"); + od->SetDescription("Applies a force (or impulse) defined in the global coordinate frame to the body."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x201d24e6,0x38990b5f)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBAddForceProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBAddForceProto +// FullName: CreatePBAddForceProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBAddForceProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddForce"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PBAddForce + + PBAddForce is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Applies a force (or impulse) defined in the global coordinate frame to the body.
+ +

Technical Information

+ + \image html PBAddForce.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Global Force:The force to add. +
+ Force Mode: The way how the force is applied.See #ForceMode +
+
+

Warning

+ The body must be dynamic. +
+
+

Note


+ + Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. +
+
+ + Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForce().
+ + */ + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + proto->DeclareInParameter("Global Force",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBAddForce); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBAddForce +// FullName: PBAddForce +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBAddForce(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + //the vector : + VxVector vec = GetInputParameterValue(beh,0); + int fMode = GetInputParameterValue(beh,1); + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + result->addForce(vec,(ForceMode)fMode); + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBAddForceCB +// FullName: PBAddForceCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBAddForceCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBAddForceAtLocalPos.cpp b/usr/Src/Behaviors/pRigidBody/PBAddForceAtLocalPos.cpp new file mode 100644 index 0000000..27c36df --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddForceAtLocalPos.cpp @@ -0,0 +1,191 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBAddForceAtLocalPosDecl(); +CKERROR CreatePBAddForceAtLocalPosProto(CKBehaviorPrototype **pproto); +int PBAddForceAtLocalPos(const CKBehaviorContext& behcontext); +CKERROR PBAddForceAtLocalPosCB(const CKBehaviorContext& behcontext); + + + +enum bbInputs +{ + + bbI_Force, + bbI_Pos, + bbI_Mode +}; + +//************************************ +// Method: FillBehaviorPBAddForceAtLocalPosDecl +// FullName: FillBehaviorPBAddForceAtLocalPosDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBAddForceAtLocalPosDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddForceAtLocalPos"); + od->SetCategory("Physic/Body"); + od->SetDescription("Applies a force (or impulse) defined in the global coordinate frame, acting at a particular point in local coordinates, to the body."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x48b7200b,0x4c2d0fc0)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBAddForceAtLocalPosProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBAddForceAtLocalPosProto +// FullName: CreatePBAddForceAtLocalPosProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBAddForceAtLocalPosProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddForceAtLocalPos"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PBAddForceAtLocalPos + + PBAddForceAtLocalPos is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Applies a force (or impulse) defined in the global coordinate frame, acting at a particular + point in local coordinates, to the actor.
+ +

Technical Information

+ + \image html PBAddForceAtLocalPos.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Global Force:Force/impulse to add, defined in the global frame. +
+ Local Position:Position in the local frame to add the force at. +
+ Force Mode: The way how the force is applied.See #ForceMode +
+
+

Warning

+ The body must be dynamic. +

Note


+ Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. +
+
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForceAtLocalPos().
+ */ + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + proto->DeclareInParameter("Global Force",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Local Position",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBAddForceAtLocalPos); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBAddForceAtLocalPos +// FullName: PBAddForceAtLocalPos +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBAddForceAtLocalPos(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + //the vector : + VxVector force = GetInputParameterValue(beh,bbI_Force); + VxVector pos = GetInputParameterValue(beh,bbI_Pos); + int fMode = GetInputParameterValue(beh,bbI_Mode); + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + result->addForceAtLocalPos(force,pos,(ForceMode)fMode); + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBAddForceAtLocalPosCB +// FullName: PBAddForceAtLocalPosCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBAddForceAtLocalPosCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBAddForceAtPos.cpp b/usr/Src/Behaviors/pRigidBody/PBAddForceAtPos.cpp new file mode 100644 index 0000000..22becfe --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddForceAtPos.cpp @@ -0,0 +1,204 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorAddForceAtPosDecl(); +CKERROR CreateAddForceAtPosProto(CKBehaviorPrototype **pproto); +int AddForceAtPos(const CKBehaviorContext& behcontext); +CKERROR AddForceAtPosCB(const CKBehaviorContext& behcontext); + + +//************************************ +// Method: FillBehaviorAddForceAtPosDecl +// FullName: FillBehaviorAddForceAtPosDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorAddForceAtPosDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddForceAtPos"); + od->SetCategory("Physic/Body"); + od->SetDescription("Applies a force (or impulse) defined in the global coordinate frame, acting at a particular point in global coordinates, to the body."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x5f182eea,0x747f062d)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateAddForceAtPosProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreateAddForceAtPosProto +// FullName: CreateAddForceAtPosProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreateAddForceAtPosProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddForceAtPos"); + if(!proto) return CKERR_OUTOFMEMORY; + + + /*! \page PBAddForceAtPos + + PBAddForceAtPos is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Applies a force (or impulse) defined in the global coordinate frame, acting at a particular + point in global coordinates, to the actor.
+ +

Technical Information

+ + \image html PBAddForceAtPos.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Global Force:Force/impulse to add, defined in the global frame. +
+ Point:Position in the global/local frame to add the force at. +
+ Point Reference:Reference object to transform a local point into world coords. +
+ Force Mode: The way how the force is applied.See #ForceMode +
+
+

Warning

+ The body must be dynamic. +

Note


+ Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + +
+
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addForceAtPos().
+ */ + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + + + proto->DeclareInParameter("Global Force",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Point",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Point Reference",CKPGUID_3DENTITY); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + //proto->SetBehaviorCallbackFct( AddForceAtPosCB ); + proto->SetFunction(AddForceAtPos); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: AddForceAtPos +// FullName: AddForceAtPos +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int AddForceAtPos(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + //the vector : + VxVector vec = GetInputParameterValue(beh,0); + VxVector vec0 = GetInputParameterValue(beh,1); + + VxVector outPos = vec0; + + + //the reference object : + CK3dEntity *referenceObject = (CK3dEntity *) beh->GetInputParameterObject(2); + + if (referenceObject) + { + + referenceObject->Transform(&outPos,&vec0); + } + + + int fMode = GetInputParameterValue(beh,3); + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + result->addForceAtPos(vec,outPos,(ForceMode)fMode); + + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: AddForceAtPosCB +// FullName: AddForceAtPosCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR AddForceAtPosCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBAddLocalForce.cpp b/usr/Src/Behaviors/pRigidBody/PBAddLocalForce.cpp new file mode 100644 index 0000000..8c3c3b3 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddLocalForce.cpp @@ -0,0 +1,187 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBAddLocalForceDecl(); +CKERROR CreatePBAddLocalForceProto(CKBehaviorPrototype **pproto); +int PBAddLocalForce(const CKBehaviorContext& behcontext); +CKERROR PBAddLocalForceCB(const CKBehaviorContext& behcontext); + + + +enum bbInputs +{ + + bbI_Force, + bbI_Mode +}; + +//************************************ +// Method: FillBehaviorPBAddLocalForceDecl +// FullName: FillBehaviorPBAddLocalForceDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBAddLocalForceDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddLocalForce"); + od->SetCategory("Physic/Body"); + od->SetDescription("Applies a force (or impulse) defined in the actor local coordinate frame to the body."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x23cb2655,0x50da723c)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBAddLocalForceProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBAddLocalForceProto +// FullName: CreatePBAddLocalForceProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBAddLocalForceProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddLocalForce"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PBAddLocalForce + + PBAddLocalForce is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Applies a force (or impulse) defined in the actor local coordinate frame, acting at a + particular point in global coordinates, to the actor.
+ +

Technical Information

+ + \image html PBAddLocalForce.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Local Force:Force/Impulse to apply defined in the local frame. +
+ Force Mode: The way how the force is applied.See #ForceMode +
+
+

Warning

+ The body must be dynamic. +

Note


+ + Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. +
+
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addLocalForce().
+ */ + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + proto->DeclareInParameter("Local Force",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBAddLocalForce); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBAddLocalForce +// FullName: PBAddLocalForce +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBAddLocalForce(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + //the vector : + VxVector force = GetInputParameterValue(beh,bbI_Force); + int fMode = GetInputParameterValue(beh,bbI_Mode); + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + result->addLocalForce(force,(ForceMode)fMode); + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBAddLocalForceCB +// FullName: PBAddLocalForceCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBAddLocalForceCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBAddLocalForceAtLocalPos.cpp b/usr/Src/Behaviors/pRigidBody/PBAddLocalForceAtLocalPos.cpp new file mode 100644 index 0000000..dfafaae --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddLocalForceAtLocalPos.cpp @@ -0,0 +1,195 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBAddLocalForceAtLocalPosDecl(); +CKERROR CreatePBAddLocalForceAtLocalPosProto(CKBehaviorPrototype **pproto); +int PBAddLocalForceAtLocalPos(const CKBehaviorContext& behcontext); +CKERROR PBAddLocalForceAtLocalPosCB(const CKBehaviorContext& behcontext); + + + +enum bbInputs +{ + + bbI_Force, + bbI_Pos, + bbI_Mode +}; + +//************************************ +// Method: FillBehaviorPBAddLocalForceAtLocalPosDecl +// FullName: FillBehaviorPBAddLocalForceAtLocalPosDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBAddLocalForceAtLocalPosDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddLocalForceAtLocalPos"); + od->SetCategory("Physic/Body"); + od->SetDescription("Applies a force (or impulse) defined in the bodies local coordinate frame, acting at a particular point in local coordinates, to the actor."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x27b72bda,0x4db179ce)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBAddLocalForceAtLocalPosProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBAddLocalForceAtLocalPosProto +// FullName: CreatePBAddLocalForceAtLocalPosProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBAddLocalForceAtLocalPosProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddLocalForceAtLocalPos"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PBAddLocalForceAtLocalPos + + PBAddLocalForceAtLocalPos is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Applies a force (or impulse) defined in the actor local coordinate frame, acting at a + particular point in local coordinates, to the actor.
+ +

Technical Information

+ + \image html PBAddLocalForceAtLocalPos.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Local Force:Force/impulse to add, defined in the local frame. +
+ Local Position:Position in the local frame to add the force at. +
+ Force Mode: The way how the force is applied.See #ForceMode +
+
+

Warning

+ The body must be dynamic. + +

Note


+ Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. +
+
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addLocalForceAtLocalPos().
+ */ + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + + proto->DeclareInParameter("Local Force",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Local Position",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBAddLocalForceAtLocalPos); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBAddLocalForceAtLocalPos +// FullName: PBAddLocalForceAtLocalPos +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBAddLocalForceAtLocalPos(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + //the vector : + VxVector force = GetInputParameterValue(beh,bbI_Force); + VxVector pos = GetInputParameterValue(beh,bbI_Pos); + int fMode = GetInputParameterValue(beh,bbI_Mode); + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + result->addLocalForceAtLocalPos(force,pos,(ForceMode)fMode); + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBAddLocalForceAtLocalPosCB +// FullName: PBAddLocalForceAtLocalPosCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBAddLocalForceAtLocalPosCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBAddLocalForceAtPos.cpp b/usr/Src/Behaviors/pRigidBody/PBAddLocalForceAtPos.cpp new file mode 100644 index 0000000..522a6f6 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddLocalForceAtPos.cpp @@ -0,0 +1,194 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBAddLocalForceAtPosDecl(); +CKERROR CreatePBAddLocalForceAtPosProto(CKBehaviorPrototype **pproto); +int PBAddLocalForceAtPos(const CKBehaviorContext& behcontext); +CKERROR PBAddLocalForceAtPosCB(const CKBehaviorContext& behcontext); + + + +enum bbInputs +{ + + bbI_Force, + bbI_Pos, + bbI_Mode +}; + +//************************************ +// Method: FillBehaviorPBAddLocalForceAtPosDecl +// FullName: FillBehaviorPBAddLocalForceAtPosDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBAddLocalForceAtPosDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddLocalForceAtPos"); + od->SetCategory("Physic/Body"); + od->SetDescription("Applies a force (or impulse) defined in the bodies local coordinate frame, acting at a particular point in global coordinates, to the body."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x4b1628cb,0x2e560e25)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBAddLocalForceAtPosProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBAddLocalForceAtPosProto +// FullName: CreatePBAddLocalForceAtPosProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBAddLocalForceAtPosProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddLocalForceAtPos"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PBAddLocalForceAtPos + + PBAddLocalForceAtPos is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Applies a force (or impulse) defined in the actor local coordinate frame, acting at a + particular point in global coordinates, to the actor.
+ +

Technical Information

+ + \image html PBAddLocalForceAtPos.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Local Force:Force/impulse to add, defined in the local frame. +
+ Point:Position in the global frame to add the force at. +
+ Force Mode: The way how the force is applied.See #ForceMode +
+
+

Warning

+ The body must be dynamic. +

Note


+ Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. + +
+
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addLocalForceAtPos().
+ */ + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + + proto->DeclareInParameter("Local Force",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Global Position",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBAddLocalForceAtPos); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBAddLocalForceAtPos +// FullName: PBAddLocalForceAtPos +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBAddLocalForceAtPos(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + //the vector : + VxVector force = GetInputParameterValue(beh,bbI_Force); + VxVector pos = GetInputParameterValue(beh,bbI_Pos); + int fMode = GetInputParameterValue(beh,bbI_Mode); + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + result->addLocalForceAtPos(force,pos,(ForceMode)fMode); + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBAddLocalForceAtPosCB +// FullName: PBAddLocalForceAtPosCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBAddLocalForceAtPosCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBAddLocalTorque.cpp b/usr/Src/Behaviors/pRigidBody/PBAddLocalTorque.cpp new file mode 100644 index 0000000..6381e7f --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddLocalTorque.cpp @@ -0,0 +1,177 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBAddLocalTorqueDecl(); +CKERROR CreatePBAddLocalTorqueProto(CKBehaviorPrototype **pproto); +int PBAddLocalTorque(const CKBehaviorContext& behcontext); +CKERROR PBAddLocalTorqueCB(const CKBehaviorContext& behcontext); + + +//************************************ +// Method: FillBehaviorPBAddLocalTorqueDecl +// FullName: FillBehaviorPBAddLocalTorqueDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBAddLocalTorqueDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddLocalTorque"); + od->SetCategory("Physic/Body"); + od->SetDescription("Applies an impulsive torque defined in the bodies local coordinate frame to the body."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x72de2e71,0x57264f89)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBAddLocalTorqueProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBAddLocalTorqueProto +// FullName: CreatePBAddLocalTorqueProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBAddLocalTorqueProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddLocalTorque"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PBAddLocalTorque + + PBAddLocalTorque is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Applies an impulsive torque defined in the actor local coordinate frame to the actor.
+

Technical Information

+ + \image html PBAddLocalTorque.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+ Local Torque: Torque to apply defined in the local frame. +
+ Force Mode: The way how the force is applied.See #ForceMode +
+
+

Warning

+ The body must be dynamic. +

Note


+ + Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. +
+
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addLocalTorque().
+ */ + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + proto->DeclareInParameter("Local Torque",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBAddLocalTorque); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBAddLocalTorque +// FullName: PBAddLocalTorque +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBAddLocalTorque(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + //the vector : + VxVector vec = GetInputParameterValue(beh,0); + int fMode = GetInputParameterValue(beh,1); + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + result->addLocalTorque(vec,(ForceMode)fMode); + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBAddLocalTorqueCB +// FullName: PBAddLocalTorqueCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBAddLocalTorqueCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBAddShape.cpp b/usr/Src/Behaviors/pRigidBody/PBAddShape.cpp new file mode 100644 index 0000000..882ec5a --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddShape.cpp @@ -0,0 +1,233 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBAddShapeDecl(); +CKERROR CreatePBAddShapeProto(CKBehaviorPrototype **pproto); +int PBAddShape(const CKBehaviorContext& behcontext); +CKERROR PBAddShapeCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPBAddShapeDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddShape"); + od->SetCategory("Physic/Body"); + od->SetDescription("Adds a sub shape given by a mesh or a reference object."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x55c61f90,0x2e512638)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBAddShapeProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBAddShapeProto +// FullName: CreatePBAddShapeProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ + +enum bInputs +{ + bbI_Mesh=0, + bbI_PObject, + bbI_Pos, + bbI_Rot, + bbI_Ref, + bbI_Density, + bbI_TotalMass, +}; + +CKERROR CreatePBAddShapeProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddShape"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + /* + PBAddShape + PBAddShape is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Adds a sub shape. See also pRigidBody::addSubShape() + .
+ See PBAddShape.cmo for example. +

Technical Information

+ + \image html PBAddShape.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target:The 3D Entity associated to the rigid body.
+ + Mesh:The mesh reference. If null then it’s using the current mesh of the reference 3D-entity object.
+ + Physic Properties: The hull type, new density and/or total mass are used only. You can overwrite these values if the source mesh or the reference object has a physic attribute.
+ + Local Position: Local position in the bodies’ space. This parameter is used when + + mesh !=null AND reference 3D-entity = null
+ + + Local Orientation: Local rotation in the bodies’ space. This parameter is used when : + + Mesh !=null AND reference 3D-entity = null
+ + Reference: If mesh != null and reference !=null ,then its adding the shape and using the reference only as transformation helper. + + If mesh = null and reference !=null, then its adding reference’s current mesh. In that, the function will try to get the hull type from objects attribute. If there is no attribute, then it’s using the building blocks physic properties parameter. + + +
+

Note

+ + Physic Material Lookup: (it’s looking for the physic material attribute on the objects listed below) + + - Materials lookup order for the case reference is null AND mesh is not null : + - mesh + - mesh’s material (index = 0) + + - Materials lookup order for the case mesh is null AND reference is not null : + - reference object + - reference’s current mesh’s material (index = 0 ) + + - Materials lookup order for the case mesh is not null AND reference is not null: + - mesh + - mesh’s material (index = 0) + - reference’s current mesh’s material (index = 0 ) + + + When it couldn’t find any material attribute until now, it’s using the target’s body material. This material is chosen or even created during the registration (\ref PBPhysicalize). + Here the lookup order during the registration of an entity in the physic engine: + - entity + - entity current mesh + - entity current mesh’s material ( index = 0 ) + + If no material specified, it fails back the the holding world’s material ( retrieved from PhysicDefaults.xml/Default ) + + +

Note


+
+ + You can execute this function multiple times. + + Is utilizing #pRigidBody #pWorld #PhysicManager
+ + + + */ + + proto->DeclareInParameter("Mesh",CKPGUID_MESH); + proto->DeclareInParameter("Physic Properties",VTS_PHYSIC_PARAMETER); + proto->DeclareInParameter("Local Position",CKPGUID_VECTOR); + proto->DeclareInParameter("Local Rotation",CKPGUID_QUATERNION); + proto->DeclareInParameter("Reference",CKPGUID_3DENTITY); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBAddShape); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBAddShape +// FullName: PBAddShape +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBAddShape(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + pRigidBody*result = world->getBody(target); + if(!result) + { + return 0; + } + + CKMesh *mesh = (CKMesh*)GetInputParameterValue(beh,bbI_Mesh); + VxVector pos = GetInputParameterValue(beh,bbI_Pos); + VxQuaternion rot = GetInputParameterValue(beh,bbI_Rot); + pObjectDescr *descr = pFactory::Instance()->createPObjectDescrFromParameter(beh->GetInputParameter(bbI_PObject)->GetRealSource()); + CK3dEntity *ref = (CK3dEntity*)GetInputParameterValue(beh,bbI_Ref); + //float density = GetInputParameterValue(beh,bbI_Density); + //float totalMass = GetInputParameterValue(beh,bbI_TotalMass); + + result->addSubShape(mesh,*descr,ref,pos,rot); + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBAddShapeCB +// FullName: PBAddShapeCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBAddShapeCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBAddShapeEx.cpp b/usr/Src/Behaviors/pRigidBody/PBAddShapeEx.cpp new file mode 100644 index 0000000..66c668b --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddShapeEx.cpp @@ -0,0 +1,622 @@ +#include +#include "pCommon.h" +#include "IParameter.h" + + +CKObjectDeclaration *FillBehaviorPBAddShapeExDecl(); +CKERROR CreatePBAddShapeExProto(CKBehaviorPrototype **pproto); +int PBAddShapeEx(const CKBehaviorContext& behcontext); +CKERROR PBAddShapeExCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_BodyRef, + bbI_HullType, + bbI_Flags, + bbI_Pivot, + bbI_Mass, + bbI_Collision, + bbI_CCD, + bbI_Material, + bbI_Capsule, + bbI_CCylinder, + bbI_Wheel, +}; + + +#define BB_SSTART 3 +#define gPIMAP pInMap2322 +BBParameter pInMap2322[] = +{ + BB_PIN(bbI_BodyRef,CKPGUID_3DENTITY,"Body Reference",""), + BB_PIN(bbI_HullType,VTE_COLLIDER_TYPE,"Hull Type","Sphere"), + BB_PIN(bbI_Flags,VTF_BODY_FLAGS,"Flags","Collision,Sub Shape"), + BB_SPIN(bbI_Pivot,VTS_PHYSIC_PIVOT_OFFSET,"Pivot",""), + BB_SPIN(bbI_Mass,VTS_PHYSIC_MASS_SETUP,"Mass",""), + BB_SPIN(bbI_Collision,VTS_PHYSIC_COLLISIONS_SETTINGS,"Collision","All,0,0.025f"), + BB_SPIN(bbI_CCD,VTS_PHYSIC_CCD_SETTINGS,"CCD",""), + BB_SPIN(bbI_Material,VTS_MATERIAL,"Material",""), + BB_SPIN(bbI_Capsule,VTS_CAPSULE_SETTINGS_EX,"Capsule Settings",""), + BB_SPIN(bbI_CCylinder,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,"Convex Cylinder Settings",""), + BB_SPIN(bbI_Wheel,VTS_PHYSIC_WHEEL_DESCR,"Wheel Settings",""), +}; + +CKObjectDeclaration *FillBehaviorPBAddShapeExDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddShapeEx"); + od->SetCategory("Physic/Body"); + od->SetDescription("Adds an entity to the physic engine."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0xd8e2970,0x1efe7f65)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBAddShapeExProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBAddShapeExProto +// FullName: CreatePBAddShapeExProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBAddShapeExProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddShapeEx"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PBAddShapeEx + + PBAddShapeEx is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Adds a sub shape to a registered rigid body.
+ See PBPhysicalizeExSamples.cmo for example. + +

Technical Information

+ + \image html PBAddShapeEx.png + + In: triggers the process
+ + Out: is activated when the process is completed
+ +
+ + Target:The 3D Entity associated to the rigid body
+ + Flags: Flags to determine common properties for the desired body.It is possible to alter certain flags after creation. See #BodyFlags for more information
+ + - Range: [BodyFlags] + - Default:Moving,Collision,World Gravity
+ + - Ways to alter flags : + - Using \ref PBSetPar + - Using VSL : #pRigidBody::updateFlags() + + Hull Type: The desired shape type. The intial shape can NOT be changed after creation. See #HullType for more information
+ + - Range: [HullType]
+ - Default:Sphere
+ + +
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createRigidBody().
+ + + + +

Optional Parameters

+ + All more specific parameters such as material or pivot offset must be enabled by the building block settings
+ + Pivot: Specifies the rigid bodies local shape offset (#pPivotSettings)

+ \image html pBPivotParameter.jpg + + - Offset Linear: \copydoc pPivotSettings::localPosition + - Offset Angular: \copydoc pPivotSettings::localOrientation + - Offset Reference: \copydoc pPivotSettings::pivotReference + +

Notes


+ + - Alter or set the shape offset : + - Using the built-in building blocks with "Physics" settings enabled : + - "Set Position" + - "Translate" + - "Set Orientation" + - #pRigidBody::setPosition() or #pRigidBody::setRotation() + - Attach attribute "Physics\pBPivotSettings" to : + - 3D-Entity + - its mesh + - or to the meshes material
+ +
+ + Mass: Overrides mass setup (#pMassSettings)

+ \image html pBMassParameter.jpg + + - New Density: \copydoc pMassSettings::newDensity + + - Total Mass: \copydoc pMassSettings::totalDensity + + - Offset Linear: \copydoc pMassSettings::localPosition + + - Offset Angular: \copydoc pMassSettings::localOrientation + + - Offset Reference: \copydoc pMassSettings::massReference + +

Notes


+ - Alter or set mass settings : + - Attach attribute "Physics\pBOptimization" to the : + - 3D-Entity + - its mesh + - or to the meshes material
+ - #pRigidBody::updateMassFromShapes() + +
+ + Collision: Overrides collsion settings (#pCollisionSettings)

+ \image html pBCollisionParameter.jpg + + - Collision Group: \copydoc pCollisionSettings::collisionGroup + + - Group Mask: \copydoc pCollisionSettings::groupsMask + + - Skin Width:\copydoc pCollisionSettings::skinWidth + +

Notes


+ - Alter or set collisions settings : + - \ref PBSetPar. Collisions group can be set per sub shape. + - pRigidBody::setCollisionsGroup() + - pRigidBody::setGroupsMask() + - Attach attribute "Physics\pBCollisionSettings" to : + - 3D-Entity + - its mesh + - or to the meshes material
+ - Please create custom groups in the Virtools "Flags and Enum manager" : "pBCollisionsGroup". This enumeration is stored in the cmo
+ +
+ + CCD: Specifies a CCD mesh. This parameter is NOT being used in this release.

+ \image html pBCCSettingsParameter.jpg + +
+ + + Material: Specifies a physic material(#pMaterial)

+ \image html pBMaterial.jpg + + - XML Link : \copydoc pMaterial::xmlLinkID + - Dynamic Friction : \copydoc pMaterial::dynamicFriction + - Static Friction: \copydoc pMaterial::staticFriction + - Restitution: \copydoc pMaterial::restitution + - Dynamic Friction V: \copydoc pMaterial::dynamicFrictionV + - Static Friction V : \copydoc pMaterial::staticFrictionV + - Direction Of Anisotropy: \copydoc pMaterial::dirOfAnisotropy + - Friction Combine Mode: \copydoc pMaterial::frictionCombineMode + - Restitution Combine Mode: \copydoc pMaterial::restitutionCombineMode + - Flags: \copydoc pMaterial::flags + +

Notes


+ + - Alter or set a physic material is also possible by : + - \ref PBSetMaterial + - #pRigidBody::updateMaterialSettings() + - Attach attribute "Physics\pBMaterial" to : + - 3D-Entity + - its mesh + - or to the meshes material + - Using VSL : + + + \include pBMaterialSetup.vsl + + + - The enumeration "XML Link" is being populated by the file "PhysicDefaults.xml" and gets updated on every reset. + - If using settings from XML, the parameter gets updated too
+ +
+ + + + Capsule Settings: Overrides capsule default dimensions(#pCapsuleSettingsEx)

+ \image html pBCapsuleSettings.jpg + + - Radius : \copydoc pCapsuleSettingsEx::radius + - Height : \copydoc pCapsuleSettingsEx::height + + +

Notes


+ + - Setting a rigid bodies capsule dimension is also possible by : + - Attach the attribute "Physics\pCapsule" to : + - 3D-Entity + - its mesh + - or to the meshes material + + - VSL : + + + \include pBCapsuleEx.vsl + + +
+ + + Convex Cylinder Settings: Overrides default convex cylinder settings(#pConvexCylinderSettings)

+ \image html pBConvexCylinder.jpg + + - Approximation : \copydoc pConvexCylinderSettings::approximation + + - Radius : \copydoc pConvexCylinderSettings::radius + - Height : \copydoc pConvexCylinderSettings::height + + - Forward Axis : \copydoc pConvexCylinderSettings::forwardAxis + - Forward Axis Reference: \copydoc pConvexCylinderSettings::forwardAxisRef + + - Down Axis : \copydoc pConvexCylinderSettings::downAxis + - Down Axis Reference: \copydoc pConvexCylinderSettings::downAxisRef + + - Right : \copydoc pConvexCylinderSettings::rightAxis + - Right Axis Reference: \copydoc pConvexCylinderSettings::rightAxisRef + + - Build Lower Half Only : \copydoc pConvexCylinderSettings::buildLowerHalfOnly + + - Convex Flags : \copydoc pConvexCylinderSettings::convexFlags + + +

Notes


+ + - Set a rigid bodies convex cylinder parameters by : + - Attach the attribute "Physics\pConvexCylinder" to : + - 3D-Entity + - its mesh + - or to the meshes material + - VSL : + + \include pBConvexCylinder.vsl + + +
+ + + Wheel: Overrides wheel settings(#pWheelDescr)

+ \image html pBWheelSettings.jpg + + - @todo Documentation ! + + */ + + + BB_EVALUATE_PINS(gPIMAP) + BB_EVALUATE_SETTINGS(gPIMAP) + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + proto->SetBehaviorCallbackFct( PBAddShapeExCB ); + proto->SetFunction(PBAddShapeEx); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBAddShapeEx +// FullName: PBAddShapeEx +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBAddShapeEx(const CKBehaviorContext& behcontext) +{ + + using namespace vtTools::BehaviorTools; + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // objects + // + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + + + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + //the world reference, optional used + CK3dEntity*worldRef = NULL; + + //the world object, only used when reference has been specified + pWorld *world = NULL; + + //final object description + pObjectDescr oDesc; + + pRigidBody *body = NULL; + NxShape *shape = NULL; + XString errMesg; + + //---------------------------------------------------------------- + // + // sanity checks + // + + + CK3dEntity *bodyReference = (CK3dEntity *) beh->GetInputParameterObject(bbI_BodyRef); + if( !bodyReference) + bbErrorME("No body reference specified"); + body = GetPMan()->getBody(bodyReference); + if( !body){ + errMesg.Format("Object %s is not physicalized",bodyReference->GetName()); + bbErrorME(errMesg.Str()); + } + + if( !target->GetCurrentMesh() ){ + errMesg.Format("Object %s has no mesh",target->GetName()); + bbErrorME(errMesg.Str()); + } + + shape= GetPMan()->getSubShape(target); + if (shape && !body->isSubShape(bodyReference) ) + { + errMesg.Format("Object %s is not a sub shape of %s",target,bodyReference->GetName()); + bbErrorME(errMesg.Str()); + } + + //get the parameter array + BB_DECLARE_PIMAP; + + + //---------------------------------------------------------------- + // + // general settings + // + oDesc.hullType = (HullType)GetInputParameterValue(beh,bbI_HullType); + oDesc.flags = (BodyFlags)GetInputParameterValue(beh,bbI_Flags); + + oDesc.version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + VxQuaternion refQuad;target->GetQuaternion(&refQuad,body->GetVT3DObject()); + VxVector relPos;target->GetPosition(&relPos,body->GetVT3DObject()); + + + // optional + // Pivot + // + BBSParameterM(bbI_Pivot,BB_SSTART); + if (sbbI_Pivot) + { + CKParameter*pivotParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Pivot))->GetRealSource(); + if (pivotParameter) + { + IParameter::Instance()->copyTo(oDesc.pivot,pivotParameter); + oDesc.mask |= OD_Pivot; + } + } + //---------------------------------------------------------------- + // optional + // mass + // + BBSParameterM(bbI_Mass,BB_SSTART); + if (sbbI_Mass) + { + + CKParameter*massParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Mass))->GetRealSource(); + if (massParameter) + { + IParameter::Instance()->copyTo(oDesc.mass,massParameter); + oDesc.mask |= OD_Mass; + } + + } + + //---------------------------------------------------------------- + // optional + // collision + // + BBSParameterM(bbI_Collision , BB_SSTART); + if (sbbI_Collision) + { + + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Collision))->GetRealSource(); + if (par) + { + IParameter::Instance()->copyTo(oDesc.collision,par); + oDesc.mask |= OD_Collision; + } + } + + //---------------------------------------------------------------- + // optional + // collision : CCD + // + BBSParameterM(bbI_CCD, BB_SSTART); + if (sbbI_CCD) + { + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCD))->GetRealSource(); + if (par) + { + IParameter::Instance()->copyTo(oDesc.ccd,par); + oDesc.mask |= OD_CCD; + } + } + + //---------------------------------------------------------------- + // optional + // Material + // + BBSParameterM(bbI_Material, BB_SSTART); + if (sbbI_Material) + { + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); + if (par) + { + pFactory::Instance()->copyTo(oDesc.material,par); + oDesc.mask |= OD_Material; + } + } + + //---------------------------------------------------------------- + // optional + // capsule + // + BBSParameterM(bbI_Capsule, BB_SSTART); + if (sbbI_Capsule) + { + if (oDesc.hullType == HT_Capsule) + { + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Capsule))->GetRealSource(); + if (par) + { + IParameter::Instance()->copyTo(oDesc.capsule,par); + oDesc.mask |= OD_Capsule; + } + }else{ + errMesg.Format("You attached a capsule parameter but the hull type is not capsule"); + bbWarning(errMesg.Str()); + } + } + + //---------------------------------------------------------------- + // optional + // convex cylinder + // + BBSParameterM(bbI_CCylinder, BB_SSTART); + if (sbbI_CCylinder) + { + if (oDesc.hullType == HT_ConvexCylinder) + { + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCylinder))->GetRealSource(); + if (par) + { + pFactory::Instance()->copyTo(oDesc.convexCylinder,par,true); + oDesc.mask |= OD_ConvexCylinder; + } + }else{ + errMesg.Format("You attached a convex cylinder parameter but the hull type is not a convex cylinder"); + bbWarning(errMesg.Str()); + } + } + + //---------------------------------------------------------------- + // optional + // convex cylinder + // + BBSParameterM(bbI_Wheel, BB_SSTART); + if (sbbI_Wheel) + { + if (oDesc.hullType == HT_Wheel) + { + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Wheel))->GetRealSource(); + if (par) + { + IParameter::Instance()->copyTo(oDesc.wheel,(CKParameterOut*)par); + oDesc.mask |= OD_Wheel; + } + }else{ + errMesg.Format("You attached a wheel parameter but the hull type is not a wheel"); + bbWarning(errMesg.Str()); + } + } + + //---------------------------------------------------------------- + // + // create sub shape : + // + shape = pFactory::Instance()->createShape(bodyReference,oDesc,target,target->GetCurrentMesh(),relPos,refQuad); + + //---------------------------------------------------------------- + // + // update input parameters + // + if (sbbI_Material) + { + CKParameterOut *par = (CKParameterOut*)beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); + if (par) + { + pFactory::Instance()->copyTo(par,oDesc.material); + } + } + //---------------------------------------------------------------- + // + // error out + // + errorFound: + { + beh->ActivateOutput(0); + return CKBR_GENERICERROR; + } + //---------------------------------------------------------------- + // + // All ok + // + allOk: + { + beh->ActivateOutput(0); + return CKBR_OK; + } + + return 0; +} + +//************************************ +// Method: PBAddShapeExCB +// FullName: PBAddShapeExCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBAddShapeExCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBAddTorque.cpp b/usr/Src/Behaviors/pRigidBody/PBAddTorque.cpp new file mode 100644 index 0000000..6a1e9c0 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBAddTorque.cpp @@ -0,0 +1,177 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBAddTorqueDecl(); +CKERROR CreatePBAddTorqueProto(CKBehaviorPrototype **pproto); +int PBAddTorque(const CKBehaviorContext& behcontext); +CKERROR PBAddTorqueCB(const CKBehaviorContext& behcontext); + + +//************************************ +// Method: FillBehaviorPBAddTorqueDecl +// FullName: FillBehaviorPBAddTorqueDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBAddTorqueDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBAddTorque"); + od->SetCategory("Physic/Body"); + od->SetDescription("Applies an impulsive torque defined in the global coordinate frame to the body."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x54cf4fe3,0x1b912870)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBAddTorqueProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBAddTorqueProto +// FullName: CreatePBAddTorqueProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBAddTorqueProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBAddTorque"); + if(!proto) return CKERR_OUTOFMEMORY; + + /*! \page PBAddTorque + + PBAddTorque is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Applies an impulsive torque defined in the global coordinate frame to the actor.
+

Technical Information

+ + \image html PBAddTorque.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+ Global Torque: Torque to apply defined in the global frame. +
+ Force Mode: The way how the force is applied.See #ForceMode +
+
+

Warning

+ The body must be dynamic. +

Note


+ + Note that if the force does not act along the center of mass of the actor, this + will also add the corresponding torque. Because forces are reset at the end of every timestep, + you can maintain a total external force on an object by calling this once every frame. +
+
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pRigidBody::addTorque().
+ */ + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + proto->DeclareInParameter("Global Torque",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Force Mode",VTE_BODY_FORCE_MODE,0); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBAddTorque); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBAddTorque +// FullName: PBAddTorque +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBAddTorque(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + //the vector : + VxVector vec = GetInputParameterValue(beh,0); + int fMode = GetInputParameterValue(beh,1); + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + result->addTorque(vec,(ForceMode)fMode); + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBAddTorqueCB +// FullName: PBAddTorqueCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBAddTorqueCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBGet.cpp b/usr/Src/Behaviors/pRigidBody/PBGet.cpp new file mode 100644 index 0000000..6ef116b --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBGet.cpp @@ -0,0 +1,255 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorPBGetDecl(); +CKERROR CreatePBGetProto(CKBehaviorPrototype **pproto); +int PBGet(const CKBehaviorContext& behcontext); +CKERROR PBGetCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_Vel=0, + bbI_AVel, + bbI_Torque, + bbI_Force, +}; + +//************************************ +// Method: FillBehaviorPBGetDecl +// FullName: FillBehaviorPBGetDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBGetDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBGet-Obsolete"); + od->SetCategory("Physic/Body"); + od->SetDescription("Retrieves information of a rigid body."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x44f65362,0x36d558af)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBGetProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBGetProto +// FullName: CreatePBGetProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBGetProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBGet-Obsolete"); + if(!proto) return CKERR_OUTOFMEMORY; + + + /* + PBGet + + PBGet is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Retrieves various physical informations.
+ +

Technical Information

+ + \image html PBGet.png + + In:triggers the process +
+ Out:is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Linear Velocity: The linear velocity.See pRigidBody::getLinearVelocity(). +
+ Angular Velocity: The angular velocity.See pRigidBody::getAngularVelocity(). +
+ Agular Momentum: The angular momentum.See pRigidBody::getAngularMomentum(). +
+ Linear Momentum: The linear momentum.See pRigidBody::getLinearMomentum(). +
+
+ Linear Velocity: Enables output for linear velocity. +
+ Angular Velocity: Enables output for angular velocity. +
+ Agular Momentum: Enables output for angular momentum. +
+ Linear Momentum: Enables output for linear momentum. +
+
+ +
+

Warning

+ The body must be dynamic. +
+
+ +

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager . + + */ + + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + proto->DeclareSetting("Velocity",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Angular Velocity",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Torque",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Force",CKPGUID_BOOL,"FALSE"); + proto->SetBehaviorCallbackFct( PBGetCB ); + proto->DeclareOutParameter("Linear Velocity",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareOutParameter("Angular Velocity",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareOutParameter("Torque",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareOutParameter("Force",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBGet); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBGet +// FullName: PBGet +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBGet(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + } + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + ////////////////////////////////////////////////////////////////////////// + //velocity : + DWORD vel; + beh->GetLocalParameterValue(bbI_Vel,&vel); + if (vel) + { + VxVector vel_ = result->getLinearVelocity(); + beh->SetOutputParameterValue(bbI_Vel,&vel_); + } + + ////////////////////////////////////////////////////////////////////////// + //angular velocity + DWORD avel; + beh->GetLocalParameterValue(bbI_AVel,&avel); + if (avel) + { + VxVector avel_ = result->getAngularVelocity(); + beh->SetOutputParameterValue(bbI_Vel,&avel_); + } + + ////////////////////////////////////////////////////////////////////////// + //torque + DWORD torque; + beh->GetLocalParameterValue(bbI_Torque,&avel); + if (avel) + { + VxVector torque_ = result->getAngularMomentum(); + beh->SetOutputParameterValue(bbI_Torque,&torque_); + } + + ////////////////////////////////////////////////////////////////////////// + //force + DWORD force; + beh->GetLocalParameterValue(bbI_Force,&force); + if (avel) + { + VxVector force_ = result->getLinearMomentum(); + beh->SetOutputParameterValue(bbI_Force,&force_); + } + + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBGetCB +// FullName: PBGetCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBGetCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + DWORD vel; + beh->GetLocalParameterValue(bbI_Vel,&vel); + beh->EnableOutputParameter(bbI_Vel,vel); + + DWORD avel; + beh->GetLocalParameterValue(bbI_AVel,&avel); + beh->EnableOutputParameter(bbI_AVel,avel); + + DWORD torque; + beh->GetLocalParameterValue(bbI_Torque,&torque); + beh->EnableOutputParameter(bbI_Torque,torque); + + DWORD force; + beh->GetLocalParameterValue(bbI_Force,&force); + beh->EnableOutputParameter(bbI_Force,force); + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBGetEx.cpp b/usr/Src/Behaviors/pRigidBody/PBGetEx.cpp new file mode 100644 index 0000000..b4d2b2f --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBGetEx.cpp @@ -0,0 +1,295 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBGet2Decl(); +CKERROR CreatePBGet2Proto(CKBehaviorPrototype **pproto); +int PBGet2(const CKBehaviorContext& behcontext); +CKERROR PBGet2CB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + bbI_CollisionGroup, + bbI_Kinematic, + bbI_Gravity, + bbI_Collision, + bbI_MassOffset, + bbI_ShapeOffset, + + +}; + +//************************************ +// Method: FillBehaviorPBGet2Decl +// FullName: FillBehaviorPBGet2Decl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBGet2Decl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBGetEx-Obsolete"); + od->SetCategory("Physic/Body"); + od->SetDescription("Retrieves physic related parameters."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x234334d3,0x70d06f74)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBGet2Proto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBGet2Proto +// FullName: CreatePBGet2Proto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBGet2Proto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBGetEx-Obsolete"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + /* + PBGetEx + + PBGet2 is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Retrieves various physical informations.
+ +

Technical Information

+ + \image html PBGet2.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Collisions Group: Which collision group this body is part of.See pRigidBody::getCollisionsGroup(). +
+ Kinematic Object: The kinematic state. See pRigidBody::isKinematic(). +
+ Gravity: The gravity state.See pRigidBody::isAffectedByGravity(). +
+ Collision: Determines whether the body reacts to collisions.See pRigidBody::isCollisionEnabled(). +
+
+ Collisions Group: Enables output for collisions group. +
+ Kinematic Object: Enables output for kinematic object. +
+ Gravity: Enables output for gravity. +
+ Collision: Enables output for collision. +
+
+
+ +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBGetEx.cpp + + */ + + + + proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Kinematic",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Gravity",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Mass Offset",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Pivot Offset",CKPGUID_BOOL,"FALSE"); + + proto->SetBehaviorCallbackFct( PBGet2CB ); + + proto->DeclareOutParameter("Collisions Group",CKPGUID_INT,"0"); + proto->DeclareOutParameter("Kinematic Object",CKPGUID_BOOL,"FALSE"); + proto->DeclareOutParameter("Gravity",CKPGUID_BOOL,"FALSE"); + proto->DeclareOutParameter("Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareOutParameter("Mass Offset",CKPGUID_VECTOR,"0.0f"); + proto->DeclareOutParameter("Pivot Offset",CKPGUID_VECTOR,"0.0f"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBGet2); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBGet2 +// FullName: PBGet2 +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBGet2(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + } + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + + ////////////////////////////////////////////////////////////////////////// + //linear damp : + DWORD cGroup; + beh->GetLocalParameterValue(bbI_CollisionGroup,&cGroup); + if (cGroup) + { + int val = result->getCollisionsGroup(); + SetOutputParameterValue(beh,bbI_CollisionGroup,val); + } + + DWORD kine; + beh->GetLocalParameterValue(bbI_Kinematic,&kine); + if (kine) + { + int val = result->isKinematic(); + SetOutputParameterValue(beh,bbI_Kinematic,val); + } + + + DWORD gravity; + beh->GetLocalParameterValue(bbI_Gravity,&gravity); + if (gravity) + { + int val = result->getActor()->readBodyFlag(NX_BF_DISABLE_GRAVITY); + SetOutputParameterValue(beh,bbI_Gravity,!val); + } + + + DWORD col; + beh->GetLocalParameterValue(bbI_Collision,&col); + if (col) + { + int val = result->isCollisionEnabled(); + SetOutputParameterValue(beh,bbI_Collision,val); + } + + + DWORD mass; + beh->GetLocalParameterValue(bbI_MassOffset,&mass); + if (mass) + { + VxVector val = result->getMassOffset(); + SetOutputParameterValue(beh,bbI_MassOffset,val); + } + + + DWORD pivot; + beh->GetLocalParameterValue(bbI_ShapeOffset,&pivot); + if (mass) + { +// VxVector val = result->getPivotOffset(); +// SetOutputParameterValue(beh,bbI_ShapeOffset,val); + } + } + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBGet2CB +// FullName: PBGet2CB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBGet2CB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + DWORD collGroup; + beh->GetLocalParameterValue(bbI_CollisionGroup,&collGroup); + beh->EnableOutputParameter(bbI_CollisionGroup,collGroup); + + DWORD kinematic; + beh->GetLocalParameterValue(bbI_Kinematic,&kinematic); + beh->EnableOutputParameter(bbI_Kinematic,kinematic); + + DWORD grav; + beh->GetLocalParameterValue(bbI_Gravity,&grav); + beh->EnableOutputParameter(bbI_Gravity,grav); + + DWORD coll; + beh->GetLocalParameterValue(bbI_Collision,&coll); + beh->EnableOutputParameter(bbI_Collision,coll); + + + DWORD mOff; + beh->GetLocalParameterValue(bbI_MassOffset,&mOff); + beh->EnableOutputParameter(bbI_MassOffset,mOff); + + DWORD pOff; + beh->GetLocalParameterValue(bbI_ShapeOffset,&pOff); + beh->EnableOutputParameter(bbI_ShapeOffset,pOff); + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBGetPar.cpp b/usr/Src/Behaviors/pRigidBody/PBGetPar.cpp new file mode 100644 index 0000000..2d4095a --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBGetPar.cpp @@ -0,0 +1,256 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorPBGetParameterDecl(); +CKERROR CreatePBGetParameterProto(CKBehaviorPrototype **pproto); +int PBGetParameter(const CKBehaviorContext& behcontext); +CKERROR PBGetParameterCB(const CKBehaviorContext& behcontext); + +using namespace vtTools; +using namespace BehaviorTools; + + + +enum bbI_Inputs +{ + bbI_BodyReference, + +}; + +#define BB_SSTART 0 + + +enum bInputs +{ + + bbO_CollisionGroup, + bbO_GroupsMask, + bbO_Flags, + bbO_TFlags, + bbO_LinDamp, + bbO_AngDamp, + bbO_MassOffset, + bbO_ShapeOffset, + +}; +BBParameter pOutMap12[] = +{ + BB_SPOUT(bbO_CollisionGroup,CKPGUID_INT,"Collision Group","0.0"), + BB_SPOUT(bbO_GroupsMask,VTS_FILTER_GROUPS,"Groups Mask",""), + BB_SPOUT(bbO_Flags,VTF_BODY_FLAGS,"Body Flags",""), + BB_SPOUT(bbO_TFlags,VTF_BODY_TRANS_FLAGS,"Transformation Lock Flags",""), + BB_SPOUT(bbO_LinDamp,CKPGUID_FLOAT,"Linear Damping","0.0"), + BB_SPOUT(bbO_AngDamp,CKPGUID_FLOAT,"Angular Damping","0.0"), + BB_SPOUT(bbO_MassOffset,CKPGUID_VECTOR,"Mass Offset","0.0"), + BB_SPOUT(bbO_ShapeOffset,CKPGUID_VECTOR,"Pivot Offset","0.0"), + +}; + +#define gOPMap pOutMap12 + + +CKERROR PBGetParameterCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + int cb = behcontext.CallbackMessage; + BB_DECLARE_PMAP; + switch(behcontext.CallbackMessage) { + + + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_POMAP(gOPMap,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PMAP(gOPMap,BB_SSTART); + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PMAP(gOPMap,BB_SSTART); + break; + } + } + return CKBR_OK; +} + +CKObjectDeclaration *FillBehaviorPBGetParameterDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBGetPar"); + od->SetCategory("Physic/Body"); + od->SetDescription("Retrieves rigid bodies parameters"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x59a670a,0x59a557ec)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBGetParameterProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBGetParameterProto +// FullName: CreatePBGetParameterProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBGetParameterProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBGetPar"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + /* + PBGetPar + PBGetPar is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Retrieves various physical informations.
+ +

Technical Information

+ + \image html PBGetPar.png + + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Collisions Group: Which collision group this body or the sub shape is part of.See pRigidBody::getCollisionsGroup(). +
+ Groupsmask: Sets 128-bit mask used for collision filtering. It can be sub shape specific.See comments for ::pGroupsMask and pRigidBody::setGroupsMask() +
+ Flags: The current flags. See pRigidBody::getFlags() +
+ Transformation Locks: Current transformations locks. +
+ Linear Damping: The linear damping scale. +
+ Angular Damping: The linear damping scale. +
+ Mass Offset: The mass center in the bodies local space. +
+ Pivot Offset: The shapes position in the bodies local space. See pRigidBody::getLocalShapePosition(). +
+ +

Warning

+ + */ + + proto->SetBehaviorCallbackFct( PBGetParameterCB ); + + + BB_EVALUATE_SETTINGS(gOPMap); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBGetParameter); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBGetParameter +// FullName: PBGetParameter +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBGetParameter(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + pRigidBody *body = NULL; + + + body = GetPMan()->getBody(target); + if (!body) bbErrorME("No Reference Object specified"); + + BB_DECLARE_PMAP; + + BBSParameter(bbO_CollisionGroup); + BBSParameter(bbO_GroupsMask); + + BBSParameter(bbO_Flags); + BBSParameter(bbO_TFlags); + + BBSParameter(bbO_LinDamp); + BBSParameter(bbO_AngDamp); + + BBSParameter(bbO_MassOffset); + BBSParameter(bbO_ShapeOffset); + + body->recalculateFlags(0); + + BB_O_SET_VALUE_IF(int,bbO_CollisionGroup,body->getCollisionsGroup(target)); + BB_O_SET_VALUE_IF(int,bbO_Flags,body->getFlags()); + BB_O_SET_VALUE_IF(int,bbO_TFlags,body->getTransformationsLockFlags()); + BB_O_SET_VALUE_IF(float,bbO_LinDamp,body->getLinearDamping()); + BB_O_SET_VALUE_IF(float,bbO_AngDamp,body->getAngularDamping()); + BB_O_SET_VALUE_IF(VxVector,bbO_MassOffset,body->getMassOffset()); + BB_O_SET_VALUE_IF(VxVector,bbO_ShapeOffset,body->getPivotOffset(target)); + + if (sbbO_GroupsMask) + { + pGroupsMask gMask = body->getGroupsMask(target); + CKParameterOut *poutMask = beh->GetOutputParameter(BB_OP_INDEX(bbO_GroupsMask)); + + if (poutMask) + { + pFactory::Instance()->copyTo(poutMask,gMask); + } + } + } + + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PBGetParameterCB +// FullName: PBGetParameterCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ + + diff --git a/usr/Src/Behaviors/pRigidBody/PBGetPar2.cpp b/usr/Src/Behaviors/pRigidBody/PBGetPar2.cpp new file mode 100644 index 0000000..1eb31be --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBGetPar2.cpp @@ -0,0 +1,230 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBGetVelocitiesAndForcesDecl(); +CKERROR CreatePBGetVelocitiesAndForcesProto(CKBehaviorPrototype **pproto); +int PBGetVelocitiesAndForces(const CKBehaviorContext& behcontext); +CKERROR PBGetVelocitiesAndForcesCB(const CKBehaviorContext& behcontext); + +using namespace vtTools; +using namespace BehaviorTools; + + + +enum bbI_Inputs +{ + bbI_BodyReference, + +}; + +#define BB_SSTART 0 + + +enum bInputs +{ + + bbO_Vel, + bbO_AVel, + bbO_Momentum, + bbO_Torque, +}; +BBParameter pOutMapPBGetPar2[] = +{ + BB_SPOUT(bbO_Vel,CKPGUID_VECTOR,"Linear Velocity",""), + BB_SPOUT(bbO_AVel,CKPGUID_VECTOR,"Angular Velocity",""), + BB_SPOUT(bbO_Torque,CKPGUID_VECTOR,"Linear Momentum",""), + BB_SPOUT(bbO_Momentum,CKPGUID_VECTOR,"Angular Momentum",""), + +}; + +#define gOPMap pOutMapPBGetPar2 + + +CKERROR PBGetVelocitiesAndForcesCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + int cb = behcontext.CallbackMessage; + BB_DECLARE_PMAP; + switch(behcontext.CallbackMessage) { + + + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_POMAP(gOPMap,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PMAP(gOPMap,BB_SSTART); + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PMAP(gOPMap,BB_SSTART); + break; + } + } + return CKBR_OK; +} + +CKObjectDeclaration *FillBehaviorPBGetVelocitiesAndForcesDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBGetParEx"); + od->SetCategory("Physic/Body"); + od->SetDescription("Retrieves forces and velocities"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x1076b62,0x1dea09ed)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBGetVelocitiesAndForcesProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBGetVelocitiesAndForcesProto +// FullName: CreatePBGetVelocitiesAndForcesProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBGetVelocitiesAndForcesProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBGetParEx"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + /*! \page PBGetParEx + + PBGetParEx is categorized in \ref Vehicle + +

Description

+ Apply to a 3DEntity
+ Retrieves velocities and forces.
+ +

Technical Information

+ + \image html PBGetParEx.png + In:triggers the process +
+ Out:is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Linear Velocity: The linear velocity.See pRigidBody::getLinearVelocity(). +
+ Angular Velocity: The angular velocity.See pRigidBody::getAngularVelocity(). +
+ Agular Momentum: The angular momentum.See pRigidBody::getAngularMomentum(). +
+ Linear Momentum: The linear momentum.See pRigidBody::getLinearMomentum(). +
+
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBGetEx.cpp + + */ + proto->SetBehaviorCallbackFct( PBGetVelocitiesAndForcesCB ); + + + BB_EVALUATE_SETTINGS(gOPMap); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBGetVelocitiesAndForces); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBGetVelocitiesAndForces +// FullName: PBGetVelocitiesAndForces +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBGetVelocitiesAndForces(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + pRigidBody *body = NULL; + + + body = GetPMan()->getBody(target); + if (!body) bbErrorME("No Reference Object specified"); + + BB_DECLARE_PMAP; + + BBSParameter(bbO_Vel); + BBSParameter(bbO_AVel); + + BBSParameter(bbO_Torque); + BBSParameter(bbO_Momentum); + + + + BB_O_SET_VALUE_IF(VxVector,bbO_Vel,body->getLinearVelocity()); + BB_O_SET_VALUE_IF(VxVector,bbO_AVel,body->getAngularVelocity()); + BB_O_SET_VALUE_IF(VxVector,bbO_Momentum,body->getLinearMomentum()); + BB_O_SET_VALUE_IF(VxVector,bbO_Vel,body->getLinearVelocity()); + + } + + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PBGetVelocitiesAndForcesCB +// FullName: PBGetVelocitiesAndForcesCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ + + diff --git a/usr/Src/Behaviors/pRigidBody/PBPhysicalize.cpp b/usr/Src/Behaviors/pRigidBody/PBPhysicalize.cpp new file mode 100644 index 0000000..29f6cce --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBPhysicalize.cpp @@ -0,0 +1,375 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorPBPhysicalizeDecl(); +CKERROR CreatePBPhysicalizeProto(CKBehaviorPrototype **pproto); +int PBPhysicalize(const CKBehaviorContext& behcontext); +CKERROR PBPhysicalizeCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ +/* bbI_TargetObject=0,*/ + bbI_Flags=0, + bbI_HullType, + bbI_Density, + bbI_SkinWidth, + bbI_MassShift, + bbI_ShapeShift, + bbI_TargetWorld, + bbI_Hierachy, + bbI_NewDensity, + bbI_TotalMass, + bbI_Material + +}; + +enum bSettings +{ + bbS_USE_DEFAULT_WORLD, + //bbS_USE_WORLD_SLEEP_SETTINGS, + //bbS_USE_WORLD_DAMPING_SETTINGS, + bbS_USE_WORLD_MATERIAL, + bbS_ADD_ATTRIBUTES +}; + +//************************************ +// Method: FillBehaviorPBPhysicalizeDecl +// FullName: FillBehaviorPBPhysicalizeDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBPhysicalizeDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBPhysicalize"); + od->SetCategory("Physic/Body"); + od->SetDescription("Adds an entity to the physic engine."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x186f7d29,0xe8901dc)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBPhysicalizeProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBPhysicalizeProto +// FullName: CreatePBPhysicalizeProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBPhysicalizeProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBPhysicalize"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /* \page TestBlock + PBPhysicalize + + PBPhysicalize is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Applies an impulsive torque defined in the actor local coordinate frame to the actor.
+ See pBPhysicalize.cmo for example. +

Technical Information

+ + \image html PBPhysicalize.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + Target: The 3D Entity associated to the rigid body. +
+ + Flags: Flags to determine common properties for the desired body. See #BodyFlags. +
+ Hulltype: The desired shape type. See #HullType. +
+ You can add or remove sub shapes on the fly by pRigidBody::addSubShape() or #PBAddShape.
+ The intial shape can NOT changed after the bodies registration.
+
+ Density: Density of the initial shape. This will be only used if
+ "Hierarchy" =false and
+ "New Density" !=0.0f or "Total Mass" != 0.0f. #pRigidBody::updateMassFromShapes() can update the mass dynamically. +
+
+ Skin Width: Specifies by how much shapes can interpenetrate. See #pRigidBody::setSkinWidth(). +
+
+ Mass Offset: Moves the mass center in the local bodies space. +
+
+ Pivot Offset: Position of the initial shape in the bodies space. +
+
+ Target World: Multiple worlds are provided. If not specified, it belongs to an automatically created default world(pDefaultWorld).This parameter must be enabled through the settings of this building block. +
+
+ Hierarchy: If enabled, this function will parse the entities hierarchy and attaches children as additional collisions shapes. Those children must have the physic attribute attached whereby the sub shape flag must be + enabled(#BodyFlags). Sub shapes can be attached by #addSubShape() or #PBAddShape afterwards. +
+
+ New Density: Density scale factor of the shapes belonging to the body.If you supply a non-zero total mass, + the bodies mass and inertia will first be computed as above and then scaled to fit this total mass. See #pRigidBody::updateMassFromShapes(). +
+
+ Total Mass: Total mass if it has sub shapes.If you supply a non-zero density, + the bodies mass and inertia will first be computed as above and then scaled by this factor.See #pRigidBody::updateMassFromShapes(). +
+
+ Material: The material of this body. This parameter must be enabled through the settings of this building block.By default it is using the worlds material. The material of a body can be specified explicity by attaching + a physic material attribute on the entity or its mesh or the meshs material. This is the lookup order :
+ - building block input parameter
+ - entity mesh
+ - entities mesh material +
+
+
+ Use Default World: Enables input for the world reference. +
+ Use Worlds Material: Enables input for a physic material. +
+ Add Attributes: Attaches the physic attribute to the entity. +
+ + +
+

Warning

+ +

Note


+
+
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createBody().
+ +

VSL


+ + \include PBPhysicalize.cpp + + + */ + + + proto->DeclareInParameter("Flags",VTF_BODY_FLAGS,"Moving Object,Updates in Virtools,Auto Disable,World Gravity,Enabled,Collision"); + proto->DeclareInParameter("Hull type",VTE_COLLIDER_TYPE,"Sphere"); + proto->DeclareInParameter("Density",CKPGUID_FLOAT,"1.0f"); + proto->DeclareInParameter("Skin Width",CKPGUID_FLOAT,"-1.0f"); + + proto->DeclareInParameter("Mass Offset",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Pivot Offset",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Target World Reference",CKPGUID_3DENTITY,"pDefaultWorld"); + proto->DeclareInParameter("Hierarchy",CKPGUID_BOOL,"FALSE"); + proto->DeclareInParameter("New Density",CKPGUID_FLOAT,"0.0f"); + proto->DeclareInParameter("Total Mass",CKPGUID_FLOAT,"0.0f"); + proto->DeclareInParameter("Material",VTS_MATERIAL); + + proto->DeclareSetting("Use Default World",CKPGUID_BOOL,"TRUE"); + proto->DeclareSetting("Use Worlds Material",CKPGUID_BOOL,"TRUE"); + proto->DeclareSetting("Add Attributes",CKPGUID_BOOL,"TRUE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + proto->SetBehaviorCallbackFct( PBPhysicalizeCB ); + proto->SetFunction(PBPhysicalize); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBPhysicalize +// FullName: PBPhysicalize +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBPhysicalize(const CKBehaviorContext& behcontext) +{ + + using namespace vtTools::BehaviorTools; + using namespace vtTools; + using namespace vtTools::AttributeTools; + + ////////////////////////////////////////////////////////////////////////// + //basic parameters + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + pFactory *pf = pFactory::Instance(); + + + + ////////////////////////////////////////////////////////////////////////// + //settings + int useDWorld; beh->GetLocalParameterValue(bbS_USE_DEFAULT_WORLD,&useDWorld); +// int useWorldSS; beh->GetLocalParameterValue(bbS_USE_WORLD_SLEEP_SETTINGS,&useWorldSS); +// int useWorldDS; beh->GetLocalParameterValue(bbS_USE_WORLD_DAMPING_SETTINGS,&useWorldDS); + int useWorldM; beh->GetLocalParameterValue(bbS_USE_WORLD_MATERIAL,&useWorldM); + int addAttributes; beh->GetLocalParameterValue(bbS_ADD_ATTRIBUTES,&addAttributes); + + + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *referenceObject = (CK3dEntity *) beh->GetTarget(); + if( !referenceObject ) return CKBR_OWNERERROR; + + + + ////////////////////////////////////////////////////////////////////////// + //the world : + CK3dEntity*worldRef = NULL; + if (!useDWorld) + { + worldRef = (CK3dEntity *) beh->GetInputParameterObject(bbI_TargetWorld); + } + + // the world : + pWorld *world=GetPMan()->getWorld(worldRef,referenceObject); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + pRigidBody*result = world->getBody(referenceObject); + if (result) + { + beh->ActivateOutput(0); + return 0; + } + + + ////////////////////////////////////////////////////////////////////////// + //pick up some parameters : + int flags = GetInputParameterValue(beh,bbI_Flags); + int hType = GetInputParameterValue(beh,bbI_HullType); + float density = GetInputParameterValue(beh,bbI_Density); + float skinWidth = GetInputParameterValue(beh,bbI_SkinWidth); + int hierarchy = GetInputParameterValue(beh,bbI_Hierachy); + float newDensity = GetInputParameterValue(beh,bbI_NewDensity); + float totalMass = GetInputParameterValue(beh,bbI_TotalMass); + + + + + VxVector massOffset = GetInputParameterValue(beh,bbI_MassShift); + VxVector shapeOffset = GetInputParameterValue(beh,bbI_ShapeShift); + + + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(GetPMan()->GetPAttribute())) + { + referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); + } + referenceObject->SetAttribute(GetPMan()->GetPAttribute()); + + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HIRARCHY,&hierarchy); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HULLTYPE,&hType); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_BODY_FLAGS,&flags); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_DENSITY,&density); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_NEW_DENSITY,&newDensity); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_TOTAL_MASS,&totalMass); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_MASS_OFFSET,&massOffset); + //SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_MASS_OFFSET,&massOffset); + + CK_ID wID = world->getReference()->GetID(); + AttributeTools::SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_WORLD,&wID); + + + + ////////////////////////////////////////////////////////////////////////// + //Material : + if (!useWorldM) + { + if (referenceObject->HasAttribute(GetPMan()->att_surface_props)) + { + referenceObject->RemoveAttribute(GetPMan()->att_surface_props); + } + + referenceObject->SetAttribute(GetPMan()->att_surface_props); + + CKParameterIn *pMatIn = beh->GetInputParameter(bbI_Material); + CKParameter *pMat = pMatIn->GetRealSource(); + CKParameterOut* pout = referenceObject->GetAttributeParameter(GetPMan()->att_surface_props); + int error = pout->CopyValue(pMat); + pout->Update(); + } + + pRigidBody *body = pFactory::Instance()->createRigidBodyFull(referenceObject,worldRef); + if (body) + { + body->translateLocalShapePosition(shapeOffset); + } + //GetPMan()->checkWorlds(); + + if (!addAttributes) + { + referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); + referenceObject->RemoveAttribute(GetPMan()->att_surface_props); + } + + beh->ActivateOutput(0); + + return 0; +} + +//************************************ +// Method: PBPhysicalizeCB +// FullName: PBPhysicalizeCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBPhysicalizeCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + DWORD useDWorld; + beh->GetLocalParameterValue(bbS_USE_DEFAULT_WORLD,&useDWorld); + beh->EnableInputParameter(bbI_TargetWorld,!useDWorld); + +/* + DWORD useDWorldSS; + beh->GetLocalParameterValue(bbS_USE_WORLD_SLEEP_SETTINGS,&useDWorldSS); + beh->EnableInputParameter(bbI_SleepSettings,!useDWorldSS); + + DWORD useDWorldDS; + beh->GetLocalParameterValue(bbS_USE_WORLD_DAMPING_SETTINGS,&useDWorldDS); + beh->EnableInputParameter(bbI_DampingSettings,!useDWorldDS); +*/ + DWORD useDWorldM; + beh->GetLocalParameterValue(bbS_USE_WORLD_MATERIAL,&useDWorldM); + beh->EnableInputParameter(bbI_Material,!useDWorldM); + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBPhysicalizeEx.cpp b/usr/Src/Behaviors/pRigidBody/PBPhysicalizeEx.cpp new file mode 100644 index 0000000..ce61be4 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBPhysicalizeEx.cpp @@ -0,0 +1,758 @@ +#include +#include "pCommon.h" +#include "IParameter.h" + + +CKObjectDeclaration *FillBehaviorPBPhysicalizeExDecl(); +CKERROR CreatePBPhysicalizeExProto(CKBehaviorPrototype **pproto); +int PBPhysicalizeEx(const CKBehaviorContext& behcontext); +CKERROR PBPhysicalizeExCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_HullType, + bbI_Flags, + bbI_Density, + bbI_XML,// from here optional parameters + bbI_World, + bbI_Pivot, + bbI_Mass, + bbI_Collision, + bbI_CCD, + bbI_Material, + bbI_Optimization, + bbI_Capsule, + bbI_CCylinder, +}; + + +#define BB_SSTART 3 +#define gPIMAP pInMap232 +BBParameter pInMap232[] = +{ + + BB_PIN(bbI_HullType,VTE_COLLIDER_TYPE,"Hull Type","Sphere"), + BB_PIN(bbI_Flags,VTF_BODY_FLAGS,"Flags","Moving Object,World Gravity,Collision"), + BB_PIN(bbI_Density,CKPGUID_FLOAT,"Density","1.0"), + BB_SPIN(bbI_XML,VTS_PHYSIC_ACTOR_XML_SETUP,"XML Setup",""),// from here optional parameters + BB_SPIN(bbI_World,CKPGUID_3DENTITY,"World Reference","pDefaultWorld"), + BB_SPIN(bbI_Pivot,VTS_PHYSIC_PIVOT_OFFSET,"Pivot",""), + BB_SPIN(bbI_Mass,VTS_PHYSIC_MASS_SETUP,"Mass",""), + BB_SPIN(bbI_Collision,VTS_PHYSIC_COLLISIONS_SETTINGS,"Collision","All,0,0.025f"), + BB_SPIN(bbI_CCD,VTS_PHYSIC_CCD_SETTINGS,"CCD",""), + BB_SPIN(bbI_Material,VTS_MATERIAL,"Material",""), + BB_SPIN(bbI_Optimization,VTS_PHYSIC_ACTOR_OPTIMIZATION,"Optimization",""), + BB_SPIN(bbI_Capsule,VTS_CAPSULE_SETTINGS_EX,"Capsule Settings",""), + BB_SPIN(bbI_CCylinder,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,"Convex Cylinder Settings",""), +}; +CKObjectDeclaration *FillBehaviorPBPhysicalizeExDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBPhysicalizeEx"); + od->SetCategory("Physic/Body"); + od->SetDescription("Adds an entity to the physic engine."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x16b33c81,0x8a96d3e)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBPhysicalizeExProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBPhysicalizeExProto +// FullName: CreatePBPhysicalizeExProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBPhysicalizeExProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBPhysicalizeEx"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PBPhysicalizeEx + + PBPhysicalizeEx is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Registers an object in the physic engine.
+ See PBPhysicalizeEx.cmo for example. + +

Technical Information

+ + \image html PBPhysicalizeEx.png + + In: triggers the process
+ + Out: is activated when the process is completed
+ +
+ + Target:The 3D Entity associated to the rigid body
+ + Flags: Flags to determine common properties for the desired body.It is possible to alter certain flags after creation. See #BodyFlags for more information
+ + - Range: [BodyFlags] + - Default:Moving,Collision,World Gravity
+ + - Ways to alter flags : + - Using \ref PBSetPar + - Using VSL : #pRigidBody::updateFlags() + + Hull Type: The desired shape type. The intial shape can NOT be changed after creation. See #HullType for more information
+ + - Range: [HullType]
+ - Default:Sphere
+ + Density: Density of the initial shape
+ + - Range: [0,inf]
+ - Default:1.0f
+ + - Ways to change the mass : + - Enable "Mass" in building block settings and set "New Density" or "Total Mass" non-zero. + - Using VSL #pRigidBody::updateMassFromShapes() + +
+ Is utilizing #pRigidBody #pWorld #PhysicManager #pFactory::createRigidBody().
+ + + + +

Optional Parameters

+ + All more specific parameters such as material or pivot offset must be enabled by the building block settings
+ + PBPhysicalizeEx all settings enabled :
+ + \image html PBPhysicalizeExCollapsed.jpg + + + XML Setup: This parameter is not being used in this release
+ +
+ World Reference: World associated with this rigid body. Leave blank to use default world (3D - Frame "pDefaultWorld" with world attribute)
+ + - Range: [object range]
+ - Default:NULL
+ +
+ + + Pivot: Specifies the rigid bodies local shape offset (#pPivotSettings)

+ \image html pBPivotParameter.jpg + + - Offset Linear: \copydoc pPivotSettings::localPosition + - Offset Angular: \copydoc pPivotSettings::localOrientation + - Offset Reference: \copydoc pPivotSettings::pivotReference + +

Notes


+ + - Alter or set the shape offset : + - Using the built-in building blocks with "Physics" settings enabled : + - "Set Position" + - "Translate" + - "Set Orientation" + - #pRigidBody::setPosition() or #pRigidBody::setRotation() + - Attach attribute "Physics\pBPivotSettings" to : + - 3D-Entity + - its mesh + - or to the meshes material
+ +
+ + Mass: Overrides mass setup (#pMassSettings)

+ \image html pBMassParameter.jpg + + - New Density: \copydoc pMassSettings::newDensity + + - Total Mass: \copydoc pMassSettings::totalDensity + + - Offset Linear: \copydoc pMassSettings::localPosition + + - Offset Angular: \copydoc pMassSettings::localOrientation + + - Offset Reference: \copydoc pMassSettings::massReference + +

Notes


+ - Alter or set mass settings : + - Attach attribute "Physics\pBOptimization" to the : + - 3D-Entity + - its mesh + - or to the meshes material
+ - #pRigidBody::updateMassFromShapes() + +
+ + + + Collision: Overrides collsion settings (#pCollisionSettings)

+ \image html pBCollisionParameter.jpg + + - Collision Group: \copydoc pCollisionSettings::collisionGroup + + - Group Mask: \copydoc pCollisionSettings::groupsMask + + - Skin Width:\copydoc pCollisionSettings::skinWidth + +

Notes


+ - Alter or set collisions settings : + - \ref PBSetPar. Collisions group can be set per sub shape. + - pRigidBody::setCollisionsGroup() + - pRigidBody::setGroupsMask() + - Attach attribute "Physics\pBCollisionSettings" to : + - 3D-Entity + - its mesh + - or to the meshes material
+ + - Please create custom groups in the Virtools "Flags and Enum manager" : "pBCollisionsGroup". This enumeration is stored in the cmo
+ +
+ + CCD: Specifies a CCD mesh. This parameter is NOT being used in this release.

+ \image html pBCCSettingsParameter.jpg + +
+ + + + + Material: Specifies a physic material(#pMaterial)

+ \image html pBMaterial.jpg + + - XML Link : \copydoc pMaterial::xmlLinkID + - Dynamic Friction : \copydoc pMaterial::dynamicFriction + - Static Friction: \copydoc pMaterial::staticFriction + - Restitution: \copydoc pMaterial::restitution + - Dynamic Friction V: \copydoc pMaterial::dynamicFrictionV + - Static Friction V : \copydoc pMaterial::staticFrictionV + - Direction Of Anisotropy: \copydoc pMaterial::dirOfAnisotropy + - Friction Combine Mode: \copydoc pMaterial::frictionCombineMode + - Restitution Combine Mode: \copydoc pMaterial::restitutionCombineMode + - Flags: \copydoc pMaterial::flags + +

Notes


+ + - Alter or set a physic material is also possible by : + - \ref PBSetMaterial + - #pRigidBody::updateMaterialSettings() + - Attach attribute "Physics\pBMaterial" to : + - 3D-Entity + - its mesh + - or to the meshes material + - Using VSL : + + + \include pBMaterialSetup.vsl + + + - The enumeration "XML Link" is being populated by the file "PhysicDefaults.xml" and gets updated on every reset. + - If using settings from XML, the parameter gets updated too
+ +
+ + + Optimization: Specifies various optimizations(#pOptimization)

+ \image html pBOptimization.jpg + + - Transformation Locks : Flags to lock a rigid body in certain degree of freedom. See also #pRigidBody::lockTransformation + - Damping: + + - Linear Damping : \copydoc pRigidBody::setLinearDamping + + - Angular Damping : \copydoc pRigidBody::setAngularDamping + + - Sleeping: + + - Linear Sleep Velocity : \copybrief pRigidBody::setSleepLinearVelocity + + - Angular Sleep Velocity : \copydoc pRigidBody::setSleepAngularVelocity + + - Sleep Energy Threshold : \copydoc pRigidBody::setSleepEnergyThreshold + + - Solver Iteration : \copydoc pRigidBody::setSolverIterationCount + + - Dominance Group : \copydoc pRigidBody::setDominanceGroup + + - Compartment Id : Not Implemented + +

Notes


+ + - Alter or set a rigid bodies optimization is also possible by : + - \ref PBSetPar + - #pRigidBody::updateOptimizationSettings() + - Attach the attribute "Physics\pBOptimization" to : + - 3D-Entity + - its mesh + - or to the meshes material
+ - Using VSL before creation : + + + \include pBOptimizationCreation.vsl + + + - Using VSL after creation : + + + \include pBOptimizationAfterCreation.vsl + + + + +
+ + Capsule Settings: Overrides capsule default dimensions(#pCapsuleSettingsEx)

+ \image html pBCapsuleSettings.jpg + + - Radius : \copydoc pCapsuleSettingsEx::radius + - Height : \copydoc pCapsuleSettingsEx::height + + +

Notes


+ + - Setting a rigid bodies capsule dimension is also possible by : + - Attach the attribute "Physics\pCapsule" to : + - 3D-Entity + - its mesh + - or to the meshes material + + - VSL : + + + \include pBCapsuleEx.vsl + + +
+ + + + + Convex Cylinder Settings: Overrides default convex cylinder settings(#pConvexCylinderSettings)

+ \image html pBConvexCylinder.jpg + + - Approximation : \copydoc pConvexCylinderSettings::approximation + + - Radius : \copydoc pConvexCylinderSettings::radius + - Height : \copydoc pConvexCylinderSettings::height + + - Forward Axis : \copydoc pConvexCylinderSettings::forwardAxis + - Forward Axis Reference: \copydoc pConvexCylinderSettings::forwardAxisRef + + - Down Axis : \copydoc pConvexCylinderSettings::downAxis + - Down Axis Reference: \copydoc pConvexCylinderSettings::downAxisRef + + - Right : \copydoc pConvexCylinderSettings::rightAxis + - Right Axis Reference: \copydoc pConvexCylinderSettings::rightAxisRef + + - Build Lower Half Only : \copydoc pConvexCylinderSettings::buildLowerHalfOnly + + - Convex Flags : \copydoc pConvexCylinderSettings::convexFlags + + +

Notes


+ + - Set a rigid bodies convex cylinder parameters by : + - Attach the attribute "Physics\pConvexCylinder" to : + - 3D-Entity + - its mesh + - or to the meshes material + - VSL : + + + \include pBConvexCylinder.vsl + + +
+ +*/ + + + BB_EVALUATE_PINS(gPIMAP) + BB_EVALUATE_SETTINGS(gPIMAP) + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + proto->SetBehaviorCallbackFct( PBPhysicalizeExCB ); + proto->SetFunction(PBPhysicalizeEx); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBPhysicalizeEx +// FullName: PBPhysicalizeEx +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBPhysicalizeEx(const CKBehaviorContext& behcontext) +{ + + using namespace vtTools::BehaviorTools; + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // objects + // + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + pFactory *pf = pFactory::Instance(); + + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + //the world reference, optional used + CK3dEntity*worldRef = NULL; + + //the world object, only used when reference has been specified + pWorld *world = NULL; + + //final object description + pObjectDescr *oDesc = new pObjectDescr(); + + pRigidBody *body = NULL; + XString errMesg; + + //---------------------------------------------------------------- + // + // sanity checks + // + + + // rigid body + GetPMan()->getBody(target); + if( body){ + errMesg.Format("Object %s already registered.",target->GetName()); + bbErrorME(errMesg.Str()); + + } + + //---------------------------------------------------------------- + // + // + // + if (!GetPMan()->isValid()) + GetPMan()->performInitialization(); + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // Collecting data. Stores all settings in a pObjectDescr. + // + + //get the parameter array + BB_DECLARE_PIMAP; + + //---------------------------------------------------------------- + // + // generic settings + // + oDesc->hullType = (HullType)GetInputParameterValue(beh,bbI_HullType); + oDesc->flags = (BodyFlags)GetInputParameterValue(beh,bbI_Flags); + oDesc->density = GetInputParameterValue(beh,bbI_Density); + + //---------------------------------------------------------------- + // optional + // world + // + BBSParameterM(bbI_World,BB_SSTART); + if (sbbI_World) + { + worldRef = (CK3dEntity *) beh->GetInputParameterObject(BB_IP_INDEX(bbI_World)); + if (worldRef) + { + world = GetPMan()->getWorld(worldRef,target); + if (!world) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"World reference has been specified but no valid world object found. Switching to default world"); + goto errorFound; + } + } + } + + //---------------------------------------------------------------- + // optional + // Pivot + // + BBSParameterM(bbI_Pivot,BB_SSTART); + if (sbbI_Pivot) + { + CKParameter*pivotParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Pivot))->GetRealSource(); + if (pivotParameter) + { + + IParameter::Instance()->copyTo(oDesc->pivot,pivotParameter); + oDesc->mask |= OD_Pivot; + + } + } + //---------------------------------------------------------------- + // optional + // mass + // + BBSParameterM(bbI_Mass,BB_SSTART); + if (sbbI_Mass) + { + + CKParameter*massParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Mass))->GetRealSource(); + if (massParameter) + { + + IParameter::Instance()->copyTo(oDesc->mass,massParameter); + oDesc->mask |= OD_Mass; + } + + } + + //---------------------------------------------------------------- + // optional + // collision + // + BBSParameterM(bbI_Collision , BB_SSTART); + if (sbbI_Collision) + { + + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Collision))->GetRealSource(); + if (par) + { + oDesc->collisionGroup = GetValueFromParameterStruct(par,PS_BC_GROUP,false); + + CKParameterOut* maskPar = GetParameterFromStruct(par,PS_BC_GROUPSMASK); + if (maskPar) + { + oDesc->groupsMask.bits0 = GetValueFromParameterStruct(maskPar,0); + oDesc->groupsMask.bits1 = GetValueFromParameterStruct(maskPar,1); + oDesc->groupsMask.bits2 = GetValueFromParameterStruct(maskPar,2); + oDesc->groupsMask.bits3 = GetValueFromParameterStruct(maskPar,3); + } + + oDesc->skinWidth = GetValueFromParameterStruct(par,PS_BC_SKINWITDH,false); + + IParameter::Instance()->copyTo(oDesc->collision,par); + oDesc->mask |= OD_Collision; + } + } + + //---------------------------------------------------------------- + // optional + // collision : CCD + // + BBSParameterM(bbI_CCD, BB_SSTART); + if (sbbI_CCD) + { + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCD))->GetRealSource(); + if (par) + { + IParameter::Instance()->copyTo(oDesc->ccd,par); + oDesc->mask |= OD_CCD; + } + } + //---------------------------------------------------------------- + // optional + // optimization + // + BBSParameterM(bbI_Optimization, BB_SSTART); + if (sbbI_Optimization) + { + + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Optimization))->GetRealSource(); + if (par) + { + IParameter::Instance()->copyTo(oDesc->optimization,par); + oDesc->mask |= OD_Optimization; + + } + } + + //---------------------------------------------------------------- + // optional + // Material + // + BBSParameterM(bbI_Material, BB_SSTART); + if (sbbI_Material) + { + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); + if (par) + { + pFactory::Instance()->copyTo(oDesc->material,par); + oDesc->mask |= OD_Material; + } + } + + //---------------------------------------------------------------- + // optional + // capsule + // + BBSParameterM(bbI_Capsule, BB_SSTART); + if (sbbI_Capsule) + { + if (oDesc->hullType == HT_Capsule) + { + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Capsule))->GetRealSource(); + if (par) + { + IParameter::Instance()->copyTo(oDesc->capsule,par); + oDesc->mask |= OD_Capsule; + } + }else{ + errMesg.Format("You attached a capsule parameter but the hull type is not capsule"); + bbWarning(errMesg.Str()); + } + } + + //---------------------------------------------------------------- + // optional + // convex cylinder + // + BBSParameterM(bbI_CCylinder, BB_SSTART); + if (sbbI_CCylinder) + { + if (oDesc->hullType == HT_ConvexCylinder) + { + CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCylinder))->GetRealSource(); + if (par) + { + pFactory::Instance()->copyTo(oDesc->convexCylinder,par,true); + oDesc->mask |= OD_ConvexCylinder; + } + }else{ + errMesg.Format("You attached a convex cylinder parameter but the hull type is not a convex cylinder"); + bbWarning(errMesg.Str()); + } + } + + + oDesc->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // body creation + // + if (!body) + { + + if(! (oDesc->flags & BF_SubShape) ) + { + body = pFactory::Instance()->createRigidBody(target,*oDesc); + } + } + + if (!body) + { + SAFE_DELETE(oDesc); + bbErrorME("No Reference Object specified"); + } + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // attribute creation, attach settings + // + if (oDesc->flags & BF_AddAttributes ) + { + //body->saveToAttributes(oDesc); + GetPMan()->copyToAttributes(*oDesc,target); + } + + //---------------------------------------------------------------- + // + // update input parameters + // + if (sbbI_Material) + { + CKParameterOut *par = (CKParameterOut*)beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); + if (par) + { + pFactory::Instance()->copyTo(par,oDesc->material); + } + } + //---------------------------------------------------------------- + // + // cleanup + // + //SAFE_DELETE(oDesc); + + //---------------------------------------------------------------- + // + // error out + // + errorFound: + { + beh->ActivateOutput(0); + return CKBR_GENERICERROR; + } + + //---------------------------------------------------------------- + // + // All ok + // + allOk: + { + beh->ActivateOutput(0); + return CKBR_OK; + } + + return 0; +} + +//************************************ +// Method: PBPhysicalizeExCB +// FullName: PBPhysicalizeExCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBPhysicalizeExCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBRemoveShape.cpp b/usr/Src/Behaviors/pRigidBody/PBRemoveShape.cpp new file mode 100644 index 0000000..5d79749 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBRemoveShape.cpp @@ -0,0 +1,184 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorPBRemoveShapeDecl(); +CKERROR CreatePBRemoveShapeProto(CKBehaviorPrototype **pproto); +int PBRemoveShape(const CKBehaviorContext& behcontext); +CKERROR PBRemoveShapeCB(const CKBehaviorContext& behcontext); + +CKObjectDeclaration *FillBehaviorPBRemoveShapeDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBRemoveShape"); + od->SetCategory("Physic/Body"); + od->SetDescription("Removes a sub shape given by a mesh."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x25637ead,0x3a881190)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBRemoveShapeProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBRemoveShapeProto +// FullName: CreatePBRemoveShapeProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ + +enum bInputs +{ + bbI_Mesh=0, + bbI_Density, + bbI_TotalMass, +}; + +CKERROR CreatePBRemoveShapeProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBRemoveShape"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PBRemoveShape + + PBRemoveShape is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Removes a sub shape. See also pRigidBody::addSubShape() .
+ +

Technical Information

+ + \image html PBRemoveShape.png + + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + + Target:The 3D Entity associated to the rigid body.
+ + Mesh Reference:The mesh reference. Must be a Entity3D or a Mesh.
+ +
+ New Density: Density scale factor of the shapes belonging to the body.If you supply a non-zero total mass, + the bodies mass and inertia will first be computed as above and then scaled to fit this total mass. See #pRigidBody::updateMassFromShapes(). +
+
+ Total Mass: Total mass if it has sub shapes.If you supply a non-zero density, + the bodies mass and inertia will first be computed as above and then scaled by this factor.See #pRigidBody::updateMassFromShapes(). +
+ +
+

Note

+ + The mesh reference can NOT be the initial shape of the target body. + + */ + + proto->DeclareInParameter("Reference",CKPGUID_BEOBJECT); + proto->DeclareInParameter("Density",CKPGUID_FLOAT); + proto->DeclareInParameter("Total Mass",CKPGUID_FLOAT); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBRemoveShape); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBRemoveShape +// FullName: PBRemoveShape +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBRemoveShape(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + beh->ActivateInput(0,FALSE); + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + pRigidBody*result = world->getBody(target); + if(!result) + { + beh->ActivateOutput(0); + return 0; + } + + CKMesh *mesh = (CKMesh*)GetInputParameterValue(beh,bbI_Mesh); + float density = GetInputParameterValue(beh,bbI_Density); + float totalMass = GetInputParameterValue(beh,bbI_TotalMass); + + result->removeSubShape(mesh,density,totalMass); + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBRemoveShapeCB +// FullName: PBRemoveShapeCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBRemoveShapeCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBSet.cpp b/usr/Src/Behaviors/pRigidBody/PBSet.cpp new file mode 100644 index 0000000..538b7a9 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBSet.cpp @@ -0,0 +1,306 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorPBSetDecl(); +CKERROR CreateBodySetProto(CKBehaviorPrototype **pproto); +int BodySet(const CKBehaviorContext& behcontext); +CKERROR BodySetCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_Vel=0, + bbI_AVel, + bbI_Torque, + bbI_Force, + bbI_Pos, + bbI_Rot + +}; + +enum bSettings +{ + bbS_Vel=0, + bbS_AVel, + bbS_Torque, + bbS_Force, + bbS_Pos, + bbS_Rot +}; + +//************************************ +// Method: FillBehaviorPBSetDecl +// FullName: FillBehaviorPBSetDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBSetDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSet"); + od->SetCategory("Physic/Body"); + od->SetDescription("Sets physical quantities."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x6915390d,0x1d775a96)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateBodySetProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} +CKERROR CreateBodySetProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSet-Obsolete"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->SetBehaviorCallbackFct( BodySetCB ); + + + + /* + PBSet + + PBSet is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PBSet.png + + In:triggers the process +
+ Out:is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Linear Velocity: The linear velocity.See pRigidBody::setLinearVelocity(). +
+ Angular Velocity: The angular velocity.See pRigidBody::setAngularVelocity(). +
+ Agular Momentum: The angular momentum.See pRigidBody::getAngularMomentum(). +
+ Linear Momentum: The linear momentum.See pRigidBody::getLinearMomentum(). +
+ Position: The position.See pRigidBody::setPosition(). +
+
+ + Linear Velocity: Enables output for linear velocity. +
+ Angular Velocity: Enables output for angular velocity. +
+ Agular Momentum: Enables output for angular momentum. +
+ Linear Momentum: Enables output for linear momentum. +
+ Position: Enables output for position. +
+ Orientation: Enables output for orientation. +
+
+
+

Warning

+ The body must be dynamic. +
+
+ +

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager . +
+
+ + The known building block "Set Position" has new settings avaiable. + Enable there "Update Physics" in order to transfer the new position on the body automatically! + + +

VSL


+ + \include PBSet.cpp + + + */ + + + proto->DeclareInParameter("Linear Velocity",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Angular Velocity",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Angular Momentum",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Linear Momentum",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Position",CKPGUID_VECTOR,"0.0f,0.0f,0.0f"); + proto->DeclareInParameter("Orientation",CKPGUID_QUATERNION); + + + proto->DeclareSetting("Velocity",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Angular Velocity",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Torque",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Force",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Position",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Rotation",CKPGUID_BOOL,"FALSE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(BodySet); + *pproto = proto; + return CK_OK; +} + +int BodySet(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + // body exists already ? clean and delete it : + pRigidBody*result = world->getBody(target); + if(result) + { + + ////////////////////////////////////////////////////////////////////////// + //velocity : + DWORD vel=0; + beh->GetLocalParameterValue(bbS_Vel,&vel); + if (vel) + { + VxVector vec = GetInputParameterValue(beh,bbI_Vel); + result->setLinearVelocity(vec); + } + + ////////////////////////////////////////////////////////////////////////// + //angular velocity + DWORD avel=0; + beh->GetLocalParameterValue(bbS_AVel,&avel); + if (avel) + { + VxVector vec = GetInputParameterValue(beh,bbI_AVel); + result->setAngularVelocity(vec); + } + + ////////////////////////////////////////////////////////////////////////// + //torque + DWORD torque=0; + beh->GetLocalParameterValue(bbS_Torque,&avel); + if (torque) + { + VxVector vec = GetInputParameterValue(beh,bbI_Torque); + result->setAngularMomentum(vec); + } + + ////////////////////////////////////////////////////////////////////////// + //force + DWORD force=0; + beh->GetLocalParameterValue(bbS_Force,&force); + if (force) + { + VxVector vec = GetInputParameterValue(beh,bbI_Force); + result->setLinearMomentum(vec); + } + + ////////////////////////////////////////////////////////////////////////// + //force + DWORD pos=0; + beh->GetLocalParameterValue(bbS_Pos,&pos); + if (pos) + { + + VxVector vec = GetInputParameterValue(beh,bbI_Pos); + result->setPosition(vec); + } + ////////////////////////////////////////////////////////////////////////// + DWORD rot=0; + beh->GetLocalParameterValue(bbS_Rot,&rot); + if (rot) + { + + VxQuaternion vec = GetInputParameterValue(beh,bbI_Rot); + result->setRotation(vec); + } + + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: BodySetCB +// FullName: BodySetCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR BodySetCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + DWORD vel; + beh->GetLocalParameterValue(bbS_Vel,&vel); + beh->EnableInputParameter(bbI_Vel,vel); + + DWORD avel; + beh->GetLocalParameterValue(bbS_AVel,&avel); + beh->EnableInputParameter(bbI_AVel,avel); + + DWORD torque; + beh->GetLocalParameterValue(bbS_Torque,&torque); + beh->EnableInputParameter(bbI_Torque,torque); + + DWORD force; + beh->GetLocalParameterValue(bbS_Force,&force); + beh->EnableInputParameter(bbI_Force,force); + + DWORD pos; + beh->GetLocalParameterValue(bbS_Pos,&pos); + beh->EnableInputParameter(bbI_Pos,pos); + DWORD rot; + beh->GetLocalParameterValue(bbS_Rot,&rot); + beh->EnableInputParameter(bbI_Rot,rot); + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBSetCallback.cpp b/usr/Src/Behaviors/pRigidBody/PBSetCallback.cpp new file mode 100644 index 0000000..91e2424 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBSetCallback.cpp @@ -0,0 +1,433 @@ +#include +#include "pCommon.h" +#include "IParameter.h" + +#include "pCallbackSignature.h" +#include "vtBBHelper.h" +#include "xDebugTools.h" +#include "pCallbackSignature.h" + + +CKObjectDeclaration *FillBehaviorPBSetCallbackDecl(); +CKERROR CreatePBSetCallbackProto(CKBehaviorPrototype **pproto); +int PBSetCallback(const CKBehaviorContext& behcontext); +CKERROR PBSetCallbackCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_FetchSignature, + bbI_ContactTypeMask, + bbI_TriggerTypeMask, + bbI_Threshold, + bbI_Reserved, + bbI_Reserved2, + bbI_Contact, + bbI_ContactModification, + bbI_Trigger, + bbI_WheelContact, + bbI_RayCastHit, + bbI_PreProcess, + bbI_PostProcess, + bbI_Copy, + bbI_Delete +// bbI_JointBreak, +}; + + +void creatInputParameters(BBParameter pArray[],int size,CKBehavior *beh) +{ + //---------------------------------------------------------------- + // + // remove all + // + while(beh->GetInputParameterCount()) + { + CKParameterIn* pi = beh->RemoveInputParameter(0); + CKDestroyObject(pi); + } + for(int i = 0 ; i < size ; i ++ ) + { + BBParameter *par = &pArray[i]; + beh->CreateInputParameter( par->name.Str(), par->guid); + } +} + +void creatOutputParameters(BBParameter pArray[],int size,CKBehavior *beh) +{ + //---------------------------------------------------------------- + // + // remove all + // + while(beh->GetOutputParameterCount()) + { + CKParameterOut* pi = beh->RemoveOutputParameter(0); + CKDestroyObject(pi); + } + for(int i = 0 ; i < size ; i ++ ) + { + BBParameter *par = &pArray[i]; + beh->CreateOutputParameter( par->name.Str(), par->guid); + } +} + +#define BB_SSTART 6 + +BBParameter pInMap221[] = +{ + BB_PIN(bbI_FetchSignature,CKPGUID_BOOL,"Create Parameters Only",""), + BB_PIN(bbI_ContactTypeMask,VTF_COLLISIONS_EVENT_MASK,"Contact Event Mask",""), + BB_PIN(bbI_TriggerTypeMask,VTF_TRIGGER,"Trigger Event Mask",""), + BB_PIN(bbI_Threshold,CKPGUID_FLOAT,"Contact Threshold",""), + BB_PIN(bbI_Reserved,CKPGUID_FLOAT,"Stub",""), + BB_PIN(bbI_Reserved2,CKPGUID_FLOAT,"Stub",""), + BB_SPIN(bbI_Contact,CKPGUID_BEHAVIOR,"Contact Notification",""), + BB_SPIN(bbI_ContactModification,CKPGUID_BEHAVIOR,"Contact Modification",""), + BB_SPIN(bbI_Trigger,CKPGUID_BEHAVIOR,"Trigger Event",""), + BB_SPIN(bbI_WheelContact,CKPGUID_BEHAVIOR,"Wheel Contact Modify",""), + BB_SPIN(bbI_RayCastHit,CKPGUID_BEHAVIOR,"Raycast Hit",""), + BB_SPIN(bbI_PreProcess,CKPGUID_BEHAVIOR,"Pre Process",""), + BB_SPIN(bbI_PostProcess,CKPGUID_BEHAVIOR,"Post Process",""), + BB_SPIN(bbI_Copy,CKPGUID_BEHAVIOR,"Copy",""), + BB_SPIN(bbI_Delete,CKPGUID_BEHAVIOR,"Delete","") + //BB_SPIN(bbI_JointBreak,CKPGUID_BEHAVIOR,"Joint Break",""), + +}; + +#define gPIMAP pInMap221 + + +CKObjectDeclaration *FillBehaviorPBSetCallbackDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetCallback"); + od->SetCategory("Physic/Body"); + od->SetDescription("Sets a callback script for the manager post process."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x1db50304,0x371a786b)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBSetCallbackProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +CKERROR CreatePBSetCallbackProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetCallback"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PBSetCallback + + PBSetCallback is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PBSetCallback.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body or its sub shape. +
+ + + \include PBSetEx.cpp + + */ + + proto->SetBehaviorCallbackFct( PBSetCallbackCB ); + + BB_EVALUATE_PINS(gPIMAP) + BB_EVALUATE_SETTINGS(pInMap221) + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBSetCallback); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBSetCallback +// FullName: PBSetCallback +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBSetCallback(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + pFactory *pf = pFactory::Instance(); + using namespace vtTools::BehaviorTools; + + BB_DECLARE_PIMAP; + int fetchSignature = GetInputParameterValue(beh,BB_IP_INDEX(bbI_FetchSignature)); + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target && !fetchSignature ) + bbErrorME("No Reference Object specified"); + pRigidBody *body = NULL; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world && !fetchSignature) + bbErrorME("No valid world object found"); + + body = GetPMan()->getBody(target); + if (!body && !fetchSignature) + bbErrorME("Object not physicalized"); + + + + int contactMask = GetInputParameterValue(beh,BB_IP_INDEX(bbI_ContactTypeMask)); + int triggerMask = GetInputParameterValue(beh,BB_IP_INDEX(bbI_TriggerTypeMask)); + + + BBSParameterM(bbI_Contact,BB_SSTART); + BBSParameterM(bbI_Trigger,BB_SSTART); + BBSParameterM(bbI_ContactModification,BB_SSTART); + BBSParameterM(bbI_RayCastHit,BB_SSTART); + + BBSParameterM(bbI_Copy,BB_SSTART); + BBSParameterM(bbI_Delete,BB_SSTART); + BBSParameterM(bbI_WheelContact,BB_SSTART); + BBSParameterM(bbI_PreProcess,BB_SSTART); + BBSParameterM(bbI_PostProcess,BB_SSTART); + //BBSParameterM(bbI_JointBreak,BB_SSTART); + + + //---------------------------------------------------------------- + // + // update contact threshold + // + float threshold = GetInputParameterValue(beh,BB_IP_INDEX(bbI_Threshold)); + if (body && !fetchSignature && sbbI_Contact && (body->getFlags() & BF_Moving )) + body->setContactReportThreshold(threshold); + if (sbbI_Delete || sbbI_Copy || sbbI_PostProcess || sbbI_PostProcess || sbbI_RayCastHit) + { + bbErrorME("Not Implemented yet"); + } + XString errMessg; + + //---------------------------------------------------------------- + // + // collision notify + // + if (sbbI_Contact) + { + + + CK_ID contactScript = GetInputParameterValue(beh,BB_IP_INDEX(bbI_Contact)); + CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(contactScript); + if (!cScript) + { + errMessg.Format("Callback for contact notification enabled but input script invalid"); + bbWarning(errMessg.Str()); + }else + { + if (fetchSignature){ + creatInputParameters(pInMapContactCallback,BB_PMAP_SIZE(pInMapContactCallback),cScript); + } + else + body->setContactScript(contactScript,contactMask); + } + } + + //---------------------------------------------------------------- + // + // wheel contact modify + // + if (sbbI_WheelContact) + { + CK_ID wheelContactModifyScript = GetInputParameterValue(beh,BB_IP_INDEX(bbI_WheelContact)); + CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(wheelContactModifyScript); + if (!cScript) + { + errMessg.Format("Callback for wheel contact modification enabled but input script invalid"); + bbWarning(errMessg.Str()); + }else + { + if (fetchSignature){ + creatInputParameters(pInMapWheelContactModifyCallback,BB_PMAP_SIZE(pInMapWheelContactModifyCallback),cScript); + creatOutputParameters(pOutMapWheelContactModifyCallback,BB_PMAP_SIZE(pOutMapWheelContactModifyCallback),cScript); + } + else{ + + pWheel2 *w = body->getWheel2(target); + w->setWheelContactScript(wheelContactModifyScript); + + + } + } + } + + //---------------------------------------------------------------- + // + // collision notify + // + if (sbbI_Trigger) + { + + + CK_ID triggerScript = GetInputParameterValue(beh,BB_IP_INDEX(bbI_Trigger)); + CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(triggerScript); + if (!cScript) + { + errMessg.Format("Callback for trigger notification enabled but input script invalid"); + bbWarning(errMessg.Str()); + }else + { + if (fetchSignature){ + creatInputParameters(pInMapTriggerCallback,BB_PMAP_SIZE(pInMapTriggerCallback),cScript); + } + else + body->setTriggerScript(triggerScript,triggerMask,target); + } + } + + + //---------------------------------------------------------------- + // + // collision notify + // + if (sbbI_ContactModification) + { + CK_ID contactModifyScript = GetInputParameterValue(beh,BB_IP_INDEX(bbI_ContactModification)); + CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(contactModifyScript); + if (!cScript) + { + errMessg.Format("Callback for contact modification enabled but input script invalid"); + bbWarning(errMessg.Str()); + }else + { + if (fetchSignature) + { + creatInputParameters(pInMapContactModifyCallback,BB_PMAP_SIZE(pInMapContactModifyCallback),cScript); + creatOutputParameters(pOutMapContactModifyCallback,BB_PMAP_SIZE(pOutMapContactModifyCallback),cScript); + } + else + body->setContactModificationScript(contactModifyScript); + } + } + //---------------------------------------------------------------- + // + // raycast + // + if (sbbI_RayCastHit) + { + bbErrorME("Not Implemented yet"); + + CK_ID raycastScript = GetInputParameterValue(beh,BB_IP_INDEX(bbI_RayCastHit)); + CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(raycastScript); + if (!cScript) + { + errMessg.Format("Callback for raycast hit reports enabled but input script invalid"); + bbWarning(errMessg.Str()); + }else + { + if (fetchSignature) + { + creatInputParameters(pInMapRaycastHitCallback,BB_PMAP_SIZE(pInMapRaycastHitCallback),cScript); + } + else + body->setRayCastScript(raycastScript); + } + } + + + + //---------------------------------------------------------------- + // + // raycast + // + /*if (sbbI_JointBreak) + { + CK_ID jointBreakScript = GetInputParameterValue(beh,BB_IP_INDEX(bbI_JointBreak)); + CKBehavior * cScript = (CKBehavior*)GetPMan()->GetContext()->GetObject(jointBreakScript); + if (!cScript) + { + errMessg.Format("Callback for joint breaks enabled but input script invalid"); + bbWarning(errMessg.Str()); + }else + { + if (fetchSignature) + { + creatInputParameters(pInMapJointBreakCallback,BB_PMAP_SIZE(pInMapJointBreakCallback),cScript); + } + else + body->setJointBreakScript(jointBreakScript); + } + } + */ + } + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PBSetCallbackCB +// FullName: PBSetCallbackCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBSetCallbackCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBSetEx.cpp b/usr/Src/Behaviors/pRigidBody/PBSetEx.cpp new file mode 100644 index 0000000..d8a9051 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBSetEx.cpp @@ -0,0 +1,438 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBSet2Decl(); +CKERROR CreatePBSet2Proto(CKBehaviorPrototype **pproto); +int PBSet2(const CKBehaviorContext& behcontext); +CKERROR PBSet2CB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + bbI_CollisionGroup, + bbI_Kinematic, + bbI_Gravity, + bbI_Collision, + bbI_MassOffset, + bbI_ShapeOffset, + bbI_CollNotify, + bbI_TFlags, + bbI_LDamp, + bbI_ADamp, + bbI_GroupsMask, +}; + +//************************************ +// Method: FillBehaviorPBSet2Decl +// FullName: FillBehaviorPBSet2Decl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBSet2Decl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetEx"); + od->SetCategory("Physic/Body"); + od->SetDescription("Sets physical quantities."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x3da14376,0x3b4748a2)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBSet2Proto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBSet2Proto +// FullName: CreatePBSet2Proto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBSet2Proto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetEx-Obsolete"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /* PBSetEx + + PBSet2 is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PBSet2.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Collisions Group: Which collision group this body is part of.See pRigidBody::setCollisionsGroup(). +
+ Kinematic Object: The kinematic state. See pRigidBody::setKinematic(). +
+ Gravity: The gravity state.See pRigidBody::enableGravity(). +
+ Collision: Determines whether the body reacts to collisions.See pRigidBody::enableCollision(). +
+ Mass Offset: The new mass center in the bodies local space. +
+ Pivot Offset: The initial shape position in the bodies local space. +
+ Notify Collision: Enables collision notification.This is necessary to use collisions related building blocks. +
+ Transformation Locks: Specifies in which dimension a a transformation lock should occour. +
+ Linear Damping: The new linear damping scale. +
+ Angular Damping: The new linear damping scale. +
+ + Filter Groups: Sets the filter mask of the initial or sub shape. +
+ + + Collisions Group: Enables input for collisions group. +
+ Kinematic Object: Enables input for kinematic object. +
+ Gravity: Enables input for gravity. +
+ Collision: Enables input for collision. +
+ Mas Offset: Enables input for mass offset. +
+ Pivot Offset: Enables input for pivot offset. +
+ Notify Collision: Enables input for collision. +
+ Linear Damping: Enables input for linear damping. +
+ Angular Damping: Enables input for angular damping. +
+ Filter Groups: Enables input for filter groups. +
+ +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBSetEx.cpp + + */ + + proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Kinematic",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Gravity",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Mass Offset",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Pivot Offset",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Notify Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Transformation Locks",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Linear Damping",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Angular Damping",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Filter Groups",CKPGUID_BOOL,"FALSE"); + + proto->SetBehaviorCallbackFct( PBSet2CB ); + + proto->DeclareInParameter("Collisions Group",CKPGUID_INT,"0"); + proto->DeclareInParameter("Kinematic Object",CKPGUID_BOOL,"FALSE"); + proto->DeclareInParameter("Gravity",CKPGUID_BOOL,"FALSE"); + proto->DeclareInParameter("Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareInParameter("Mass Offset",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Pivot Offset",CKPGUID_VECTOR,"0.0f"); + proto->DeclareInParameter("Notify Collisions",CKPGUID_BOOL,"FALSE"); + proto->DeclareInParameter("Transformation Locks",VTF_BODY_TRANS_FLAGS,"FALSE"); + proto->DeclareInParameter("Linear Damping",CKPGUID_FLOAT,"0"); + proto->DeclareInParameter("Angular Damping",CKPGUID_FLOAT,"0"); + proto->DeclareInParameter("Filter Groups",VTS_FILTER_GROUPS,"0"); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBSet2); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBSet2 +// FullName: PBSet2 +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBSet2(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + + } + + // body exists already ? clean and delete it : + pRigidBody*result = world->getBodyFromSubEntity(target); + if(result) + { + + ////////////////////////////////////////////////////////////////////////// + //linear damp : + DWORD cGroup; + beh->GetLocalParameterValue(bbI_CollisionGroup,&cGroup); + if (cGroup) + { + int val = GetInputParameterValue(beh,bbI_CollisionGroup); + result->setCollisionsGroup(val); + } + + DWORD kine; + beh->GetLocalParameterValue(bbI_Kinematic,&kine); + if (kine && (result->getFlags() & BF_Moving) ) + { + int val = GetInputParameterValue(beh,bbI_Kinematic); + result->setKinematic(val); + + } + + + DWORD gravity; + beh->GetLocalParameterValue(bbI_Gravity,&gravity); + if (gravity) + { + int val = GetInputParameterValue(beh,bbI_Gravity); + if (result->getActor() && (result->getFlags() & BF_Moving)) + { + if (!val) + { + result->getActor()->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); + }else{ + result->getActor()->clearBodyFlag(NX_BF_DISABLE_GRAVITY); + } + } + } + + DWORD col=0; + beh->GetLocalParameterValue(bbI_Collision,&col); + if (col) + { + int val = GetInputParameterValue(beh,bbI_Collision); + result->enableCollision(!val); + } + + + DWORD mass=0; + beh->GetLocalParameterValue(bbI_MassOffset,&mass); + if (mass) + { + VxVector val = GetInputParameterValue(beh,bbI_MassOffset); + result->setMassOffset(val); + } + + + DWORD pivot=0; + beh->GetLocalParameterValue(bbI_ShapeOffset,&pivot); + if (mass) + { + VxVector val = GetInputParameterValue(beh,bbI_ShapeOffset); + result->setPivotOffset(val); + + } + + DWORD collNotify=0; + beh->GetLocalParameterValue(bbI_CollNotify,&collNotify); + if (collNotify) + { + int val = GetInputParameterValue(beh,bbI_CollNotify); + if (val) + { + result->getActor()->setContactReportFlags(NX_NOTIFY_ON_TOUCH); + }else + result->getActor()->setContactReportFlags(NX_IGNORE_PAIR); + } + + DWORD tFlags=0; + beh->GetLocalParameterValue(bbI_TFlags,&tFlags); + if (tFlags && (result->getFlags() & BF_Moving)) + { + int val = GetInputParameterValue(beh,bbI_TFlags); + result->lockTransformation(val); + } + + DWORD LDamp; + beh->GetLocalParameterValue(bbI_LDamp,&LDamp); + if (LDamp) + { + float val = GetInputParameterValue(beh,bbI_LDamp); + result->setLinearDamping(val); + } + + DWORD ADamp; + beh->GetLocalParameterValue(bbI_ADamp,&ADamp); + if (ADamp) + { + float val = GetInputParameterValue(beh,bbI_ADamp); + result->setAngularDamping(val); + } + + DWORD fMask; + beh->GetLocalParameterValue(bbI_GroupsMask,&fMask); + if (fMask) + { + + NxShape *dstShape = NULL; + + NxShape *mainshape = result->getMainShape(); + if (mainshape==NULL) + { + int op = 2; + op++; + + } + NxShape *inputShape = result->_getSubShapeByEntityID(target->GetID()); + if (mainshape==inputShape) + { + dstShape = mainshape; + }else{ + dstShape = inputShape; + } + + CKParameter *fConst1 = beh->GetInputParameter(bbI_GroupsMask)->GetRealSource(); + + using namespace vtTools::BehaviorTools; + using namespace vtTools::ParameterTools; + + NxGroupsMask mask1; + mask1.bits0 = GetValueFromParameterStruct(fConst1,0); + mask1.bits1 = GetValueFromParameterStruct(fConst1,1); + mask1.bits2 = GetValueFromParameterStruct(fConst1,2); + mask1.bits3 = GetValueFromParameterStruct(fConst1,3); + + if (dstShape) + { + dstShape->setGroupsMask(mask1); + } + } + } + + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBSet2CB +// FullName: PBSet2CB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBSet2CB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + DWORD collGroup; + beh->GetLocalParameterValue(bbI_CollisionGroup,&collGroup); + beh->EnableInputParameter(bbI_CollisionGroup,collGroup); + + DWORD kinematic; + beh->GetLocalParameterValue(bbI_Kinematic,&kinematic); + beh->EnableInputParameter(bbI_Kinematic,kinematic); + + DWORD grav; + beh->GetLocalParameterValue(bbI_Gravity,&grav); + beh->EnableInputParameter(bbI_Gravity,grav); + + DWORD coll; + beh->GetLocalParameterValue(bbI_Collision,&coll); + beh->EnableInputParameter(bbI_Collision,coll); + + + DWORD mOff; + beh->GetLocalParameterValue(bbI_MassOffset,&mOff); + beh->EnableInputParameter(bbI_MassOffset,mOff); + + DWORD pOff; + beh->GetLocalParameterValue(bbI_ShapeOffset,&pOff); + beh->EnableInputParameter(bbI_ShapeOffset,pOff); + + DWORD collNotify; + beh->GetLocalParameterValue(bbI_CollNotify,&collNotify); + beh->EnableInputParameter(bbI_CollNotify,collNotify); + + DWORD tFlags; + beh->GetLocalParameterValue(bbI_TFlags,&tFlags); + beh->EnableInputParameter(bbI_TFlags,tFlags); + + DWORD lDamp; + beh->GetLocalParameterValue(bbI_LDamp,&lDamp); + beh->EnableInputParameter(bbI_LDamp,lDamp); + + DWORD ADamp; + beh->GetLocalParameterValue(bbI_ADamp,&ADamp); + beh->EnableInputParameter(bbI_ADamp,ADamp); + + DWORD fMask; + beh->GetLocalParameterValue(bbI_GroupsMask,&fMask); + beh->EnableInputParameter(bbI_GroupsMask,fMask); + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBSetHard.cpp b/usr/Src/Behaviors/pRigidBody/PBSetHard.cpp new file mode 100644 index 0000000..2f1fa40 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBSetHard.cpp @@ -0,0 +1,291 @@ +#include +#include "pCommon.h" + + + +CKObjectDeclaration *FillBehaviorPBSetHardDecl(); +CKERROR CreatePBSetHardProto(CKBehaviorPrototype **pproto); +int PBSetHard(const CKBehaviorContext& behcontext); +CKERROR PBSetHardCB(const CKBehaviorContext& behcontext); + + +enum bInputs +{ + + bbI_Vel, + bbI_AVel, + bbI_Momentum, + bbI_Torque, + bbI_Pos, + bbI_Rotation, + +}; + +#define BB_SSTART 0 + +BBParameter pInMap23[] = +{ + + + BB_SPIN(bbI_Vel,CKPGUID_VECTOR,"Linear Velocity",""), + BB_SPIN(bbI_AVel,CKPGUID_VECTOR,"Angular Velocity",""), + BB_SPIN(bbI_Momentum,CKPGUID_VECTOR,"Linear Momentum",""), + BB_SPIN(bbI_Torque,CKPGUID_VECTOR,"Angualar Momentum",""), + BB_SPIN(bbI_Pos,CKPGUID_VECTOR,"Position",""), + BB_SPIN(bbI_Rotation,CKPGUID_QUATERNION,"Rotation",""), + +}; + +#define gPIMAP pInMap23 + +//************************************ +// Method: FillBehaviorPBSetHardDecl +// FullName: FillBehaviorPBSetHardDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBSetHardDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetHard"); + od->SetCategory("Physic/Body"); + od->SetDescription("Sets momentum,velocities and transformations."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x528d58e0,0x2fca203a)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBSetHardProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBSetHardProto +// FullName: CreatePBSetHardProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBSetHardProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetHard"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + /*! \page PBSetHard + + PBSet is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PBSetHard.png + + In:triggers the process +
+ Out:is activated when the process is completed. +
+
+ Target: The 3D Entity associated with the rigid body or its sub shape. +
+
+ Linear Velocity: The linear velocity.See pRigidBody::setLinearVelocity(). +
+ Angular Velocity: The angular velocity.See pRigidBody::setAngularVelocity(). +
+ Agular Momentum: The angular momentum.See pRigidBody::getAngularMomentum(). +
+ Linear Momentum: The linear momentum.See pRigidBody::getLinearMomentum(). +
+ Position: The position.See pRigidBody::setPosition(). +
+ Orientation: The new rotation.See pRigidBody::setRotation(). +
+ + +

Warning

+ The body must be dynamic. +
+
+ +

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager . +
+
+ + The known building block "Set Position" has new settings avaiable. + Enable there "Update Physics" in order to transfer the new position on the body automatically! + + +

VSL


+ + \include PBSet.cpp + + + */ + + proto->SetBehaviorCallbackFct( PBSetHardCB ); + + BB_EVALUATE_SETTINGS(gPIMAP) + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBSetHard); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBSetHard +// FullName: PBSetHard +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBSetHard(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + pRigidBody *body = NULL; + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + { + if (!body) bbErrorME("No valid world object found"); + } + + + body = GetPMan()->getBody(target); + if (!body) bbErrorME("No Reference Object specified"); + + BB_DECLARE_PIMAP; + + /************************************************************************/ + /* retrieve settings state */ + /************************************************************************/ + BBSParameter(bbI_Vel); + BBSParameter(bbI_AVel); + BBSParameter(bbI_Torque); + BBSParameter(bbI_Momentum); + BBSParameter(bbI_Pos); + BBSParameter(bbI_Rotation); + + + + if (sbbI_Vel) + { + VxVector velocity= GetInputParameterValue(beh,BB_IP_INDEX(bbI_Vel)); + body->setLinearVelocity(velocity); + } + + if (sbbI_AVel) + { + VxVector aVelocity= GetInputParameterValue(beh,BB_IP_INDEX(bbI_AVel)); + body->setAngularVelocity(aVelocity); + } + + if (sbbI_Torque) + { + VxVector torque= GetInputParameterValue(beh,BB_IP_INDEX(bbI_Torque)); + body->setAngularMomentum(torque); + } + if (sbbI_Momentum) + { + VxVector momentum= GetInputParameterValue(beh,BB_IP_INDEX(bbI_Momentum)); + body->setLinearMomentum(momentum); + } + + + if (sbbI_Pos) + { + VxVector pos= GetInputParameterValue(beh,BB_IP_INDEX(bbI_Pos)); + body->setPosition(pos,target); + } + if (sbbI_Rotation) + { + VxQuaternion rot= GetInputParameterValue(beh,BB_IP_INDEX(bbI_Rotation)); + body->setRotation(rot,target); + } + + } + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PBSetHardCB +// FullName: PBSetHardCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBSetHardCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBSetMaterial.cpp b/usr/Src/Behaviors/pRigidBody/PBSetMaterial.cpp new file mode 100644 index 0000000..eef02c3 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBSetMaterial.cpp @@ -0,0 +1,358 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBSetMaterialDecl(); +CKERROR CreatePBSetMaterialProto(CKBehaviorPrototype **pproto); +int PBSetMaterial(const CKBehaviorContext& behcontext); +CKERROR PBSetMaterialCB(const CKBehaviorContext& behcontext); + +using namespace vtTools::BehaviorTools; +using namespace vtTools::ParameterTools; + + +enum bInputs +{ + I_XML, + I_DFRICTION, + I_SFRICTION, + I_RES, + I_DFRICTIONV, + I_SFRICTIONV, + I_ANIS, + I_FCMODE, + I_RCMODE, + I_FLAGS, +}; + +CKERROR PBSetMaterialCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + CKContext *ctx = beh->GetCKContext(); + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORATTACH: + { + + DWORD outputResult = 0; + beh->GetLocalParameterValue(1,&outputResult); + beh->EnableOutputParameter(0,outputResult); + + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + + + DWORD outputResult = 0; + beh->GetLocalParameterValue(1,&outputResult); + beh->EnableOutputParameter(0,outputResult); + + int fromParameter=0; + beh->GetLocalParameterValue(0,&fromParameter); + + if (fromParameter) + { + if (beh->GetInputParameterCount() > 1 ) + { + while ( beh->GetInputParameterCount()) + { + CKDestroyObject(beh->RemoveInputParameter(0)); + } + beh->CreateInputParameter("Material Settings",VTS_MATERIAL); + } + } + + if (!fromParameter) + { + if (beh->GetInputParameterCount() < 2 ) + { + CKDestroyObject(beh->RemoveInputParameter(0)); + beh->CreateInputParameter("XML Link",VTE_XML_MATERIAL_TYPE); + beh->CreateInputParameter("Dynamic Friction",CKPGUID_FLOAT); + beh->CreateInputParameter("Static Friction",CKPGUID_FLOAT); + beh->CreateInputParameter("Restitution",CKPGUID_FLOAT); + beh->CreateInputParameter("Dynamic Friction V",CKPGUID_FLOAT); + beh->CreateInputParameter("Static Friction V",CKPGUID_FLOAT); + beh->CreateInputParameter("Direction of Anisotropy ",CKPGUID_VECTOR); + beh->CreateInputParameter("Friction Combine Mode",VTE_MATERIAL_COMBINE_MODE); + beh->CreateInputParameter("Restitution Combine Mode",VTE_MATERIAL_COMBINE_MODE); + beh->CreateInputParameter("Flags",VTF_MATERIAL_FLAGS); + } + } + break; + + } + + } + return CKBR_OK; + +} + +//************************************ +// Method: FillBehaviorPBSetMaterialDecl +// FullName: FillBehaviorPBSetMaterialDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration*FillBehaviorPBSetMaterialDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetMaterial"); + od->SetCategory("Physic/Body"); + od->SetDescription("Attaches and/or modifies the physic material of a rigid body or its sub shape"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x52523d82,0x5cb74a78)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBSetMaterialProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBSetMaterialProto +// FullName: CreatePBSetMaterialProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBSetMaterialProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetMaterial"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + proto->DeclareInParameter("Material Settings",VTS_MATERIAL,"NONE"); + proto->DeclareSetting("From Material Parameter",CKPGUID_BOOL,"TRUE"); + proto->DeclareSetting("Output Result",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Add Attribute",CKPGUID_BOOL,"FALSE"); + + proto->DeclareOutParameter("Result",VTS_MATERIAL); + + + /*! \page PBSetMaterial + + PBSetMaterial is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies a rigid bodies physic material .
+ +

Technical Information

+ + \image html PBSetMaterial.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ + Target: The 3D Entity associated to the rigid body or its sub shape. +
+ + + XML Link: The name of the material stored in the chosen xml file. If set to "None" the values from the parameter struct will be used. The list of avaiable materials will be updated from PhysicDefaults.xml on Dev reset. +
+ + Dynamic Friction: Coefficient of dynamic friction -- should be in [0, +inf]. If set to greater than staticFriction, the effective value of staticFriction will be increased to match. + If in the flags "Anisotropic" is set, then this value is used for the primary direction of anisotropy (U axis).
+ + Range: [0,inf]
+ Default: 0.0 + + + Static Friction: Coefficient of static friction -- should be in [0, +inf] + If in the flags "Anisotropic" is set, then this value is used for the primary direction of anisotropy (U axis) + + Range: [0,inf]
+ Default: 0.0 + + Restitution: Coefficient of restitution -- 0 makes the object bounce as little as possible, higher values up to 1.0 result in more bounce. + Note that values close to or above 1 may cause stability problems and/or increasing energy. + + Range: [0,1]
+ Default: 0.0 + + Dynamic Friction V: Anisotropic dynamic friction coefficient for along the secondary (V) axis of anisotropy. + This is only used if the flag Anisotropic is set. + + Range: [0,inf]
+ Default: 0.0 + + Static Friction V : Anisotropic static friction coefficient for along the secondary (V) axis of anisotropy. + This is only used if the flag Anisotropic is set. + + Range: [0,inf]
+ Default: 0.0 + + + Dir Of Anisotropy: Shape space direction (unit vector) of anisotropy. + This is only used if flags Anisotropic is set. + + Range: direction vector
+ Default: 1.0f,0.0f,0.0f + + Flags: Flags, a combination of the bits defined by the enum ::MaterialFlags. + + From Material Parameter: Switches the input method between the custom parameter struct "pMaterial" and its enacpsulated input. The parameter "pMaterial" can be modified through parameter operations! +
+ + Output Result: Outputs a pMaterial parameter. This can be useful if a xml setup has be been chosen. +
+ + Add Attribute: Adds the resulting material as a parameter to the selected object. +
+ + +

Warning

+ - By default, each body or sub shape retrieves the worlds default material(PhysicDefaults.xml - Default). This building block creates or modifies a new material. + - If the settings are invalid, the building block aborts and outputs a message in the console. + - You can assign a material to a deformable or a cloth object. + + +
+
+ */ + + proto->SetBehaviorCallbackFct( PBSetMaterialCB ); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBSetMaterial); + *pproto = proto; + return CK_OK; +} + + +//************************************ +// Method: PBSetMaterial +// FullName: PBSetMaterial +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ + + + + +int PBSetMaterial(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + + + + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbSErrorME(E_PE_REF); + + pRigidBody *body = GetPMan()->getBody(target); + if (!body) + body = GetPMan()->getBody(target); + + if( !body ) bbSErrorME(E_PE_REF); + + int fromStruct=0; + beh->GetLocalParameterValue(0,&fromStruct); + + int output=0; + beh->GetLocalParameterValue(1,&output); + + int AddAsAttribute=0; + beh->GetLocalParameterValue(2,&AddAsAttribute); + + + + pMaterial mat; + mat.setToDefault(); + + + if (fromStruct) + { + CKParameter *mParameter = beh->GetInputParameter(0)->GetRealSource(); + if (mParameter) + { + pFactory::Instance()->copyTo(mat,mParameter); + } + }else + { + mat.xmlLinkID = GetInputParameterValue(beh,I_XML); + mat.dynamicFriction = GetInputParameterValue(beh,I_DFRICTION); + mat.dynamicFrictionV = GetInputParameterValue(beh,I_DFRICTIONV); + mat.staticFriction = GetInputParameterValue(beh,I_SFRICTION); + mat.staticFrictionV = GetInputParameterValue(beh,I_SFRICTIONV); + mat.restitution = GetInputParameterValue(beh,I_RES); + mat.dirOfAnisotropy = GetInputParameterValue(beh,I_ANIS); + mat.restitutionCombineMode = (CombineMode)GetInputParameterValue(beh,I_RCMODE); + mat.frictionCombineMode = (CombineMode)GetInputParameterValue(beh,I_FCMODE); + mat.flags = GetInputParameterValue(beh,I_FLAGS); + } + + XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,mat.xmlLinkID); + if ( mat.xmlLinkID !=0 ) + { + + bool err = pFactory::Instance()->loadFrom(mat,nodeName.Str(),pFactory::Instance()->getDefaultDocument()); + if (!err) + { + XString error; + error << "Couldn't load " << nodeName << " from XML!"; + bbErrorME(error.Str()); + } + if (output) + { + pFactory::Instance()->copyTo(beh->GetOutputParameter(0),mat); + } + } + + if (!mat.isValid()) + { + XString error; + error << "Material Settings " << nodeName << " are invalid!"; + bbErrorME(error.Str()); + } + + if (mat.isValid()) + { + body->setShapeMaterial(mat,target); + + if (AddAsAttribute) + { + if (!target->HasAttribute(GetPMan()->att_surface_props)) + target->SetAttribute(GetPMan()->att_surface_props); + pFactory::Instance()->copyTo(target->GetAttributeParameter(GetPMan()->att_surface_props),mat); + } + } + } + beh->ActivateOutput(0); + return 0; +} diff --git a/usr/Src/Behaviors/pRigidBody/PBSetPar.cpp b/usr/Src/Behaviors/pRigidBody/PBSetPar.cpp new file mode 100644 index 0000000..591d7c9 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBSetPar.cpp @@ -0,0 +1,340 @@ +#include +#include "pCommon.h" + + + +CKObjectDeclaration *FillBehaviorPBSetParDecl(); +CKERROR CreatePBSetParProto(CKBehaviorPrototype **pproto); +int PBSetPar(const CKBehaviorContext& behcontext); +CKERROR PBSetParCB(const CKBehaviorContext& behcontext); + + +enum bInputs +{ + + bbI_CollisionGroup, + bbI_GroupsMask, + bbI_Flags, + bbI_TFlags, + bbI_LinDamp, + bbI_AngDamp, + bbI_MassOffset, + bbI_ShapeOffset, + +}; + +#define BB_SSTART 0 + +BBParameter pInMap22[] = +{ + + BB_SPIN(bbI_CollisionGroup,CKPGUID_INT,"Collision Group",""), + BB_SPIN(bbI_GroupsMask,VTS_FILTER_GROUPS,"Group Mask","0.0"), + BB_SPIN(bbI_Flags,VTF_BODY_FLAGS,"Body Flags",""), + BB_SPIN(bbI_TFlags,VTF_BODY_TRANS_FLAGS,"Transformation Lock Flags",""), + BB_SPIN(bbI_LinDamp,CKPGUID_FLOAT,"Linear Damping","0.0"), + BB_SPIN(bbI_AngDamp,CKPGUID_FLOAT,"Angular Damping",""), + BB_SPIN(bbI_MassOffset,CKPGUID_VECTOR,"Mass Offset",""), + BB_SPIN(bbI_ShapeOffset,CKPGUID_VECTOR,"Pivot Offset",""), + +}; + +#define gPIMAP pInMap22 + +//************************************ +// Method: FillBehaviorPBSetParDecl +// FullName: FillBehaviorPBSetParDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBSetParDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetPar"); + od->SetCategory("Physic/Body"); + od->SetDescription("Sets physic parameters."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x137e7ec4,0x4ca85a4b)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBSetParProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBSetParProto +// FullName: CreatePBSetParProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBSetParProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetPar"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PBSetPar + + PBSetPar is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PBSetPar.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body or its sub shape. +
+ Collisions Group: Which collision group this body or the sub shape is part of.See pRigidBody::setCollisionsGroup(). +
+ Groupsmask: Sets 128-bit mask used for collision filtering. It can be sub shape specific.See comments for ::pGroupsMask and pRigidBody::setGroupsMask() +
+ + Flags: Changes essential physic behavior. See pRigidBody::setFlags()
+ - This flags can be changed after the bodies registration : + - Gravity - See pRigidBody::ennableGravity() + - Kinematic - See pRigidBody::setKinematic() + - Trigger Shape - See pRigidBody::enableTriggerShape() + - Collisions Notify - See pRigidBody::enableCollisionsNotify() + - Sleep - pRigidBody::setSleeping() or pRigidBody::isSleeping() + + Transformation Locks: Locks a translation or orientation in a specific dimension. +
+ + Linear Damping: The new linear damping scale. +
+ Angular Damping: The new linear damping scale. +
+ + Mass Offset: The new mass center in the bodies local space. +
+ Pivot Offset: Specifies the shapes position in the bodies local space. See pRigidBody::setLocalShapePosition(). +
+ + +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBSetEx.cpp + + */ + + proto->SetBehaviorCallbackFct( PBSetParCB ); + + BB_EVALUATE_SETTINGS(pInMap22) + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBSetPar); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBSetPar +// FullName: PBSetPar +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBSetPar(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + pRigidBody *body = NULL; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + bbErrorME("No valid world object found"); + + + body = GetPMan()->getBody(target); + if (!body) bbErrorME("Object not physicalized"); + + + BB_DECLARE_PIMAP; + + /************************************************************************/ + /* retrieve settings state */ + /************************************************************************/ + BBSParameter(bbI_CollisionGroup); + BBSParameter(bbI_Flags); + BBSParameter(bbI_TFlags); + BBSParameter(bbI_GroupsMask); + BBSParameter(bbI_LinDamp); + BBSParameter(bbI_AngDamp); + BBSParameter(bbI_MassOffset); + BBSParameter(bbI_ShapeOffset); + + + if (sbbI_GroupsMask) + { + NxGroupsMask mask1; + CKParameter *fConst1 = beh->GetInputParameter(BB_IP_INDEX(bbI_GroupsMask))->GetRealSource(); + + using namespace vtTools::BehaviorTools; + using namespace vtTools::ParameterTools; + + NxShape *dstShape = NULL; + + NxShape *mainshape = body->getMainShape(); + if (mainshape==NULL) + { + int op = 2; + op++; + + } + NxShape *inputShape = body->_getSubShapeByEntityID(target->GetID()); + if (mainshape==inputShape) + { + dstShape = mainshape; + }else{ + dstShape = inputShape; + } + + + mask1.bits0 = GetValueFromParameterStruct(fConst1,0); + mask1.bits1 = GetValueFromParameterStruct(fConst1,1); + mask1.bits2 = GetValueFromParameterStruct(fConst1,2); + mask1.bits3 = GetValueFromParameterStruct(fConst1,3); + + if (dstShape) + { + dstShape->setGroupsMask(mask1); + } + } + + if (sbbI_CollisionGroup) + { + int collGroup = GetInputParameterValue(beh,BB_IP_INDEX(bbI_CollisionGroup)); + body->setCollisionsGroup(collGroup,target); + } + + if (sbbI_Flags) + { + int flags = GetInputParameterValue(beh,BB_IP_INDEX(bbI_Flags)); + body->updateFlags(flags,target); + } + + if (sbbI_TFlags) + { + int tflags = GetInputParameterValue(beh,BB_IP_INDEX(bbI_TFlags)); + body->lockTransformation(tflags); + } + + if (sbbI_LinDamp) + { + float lDamp = GetInputParameterValue(beh,BB_IP_INDEX(bbI_LinDamp)); + body->setLinearDamping(lDamp); + } + if (sbbI_AngDamp) + { + float aDamp= GetInputParameterValue(beh,BB_IP_INDEX(bbI_AngDamp)); + body->setAngularDamping(aDamp); + } + + if (sbbI_MassOffset) + { + VxVector mOffset= GetInputParameterValue(beh,BB_IP_INDEX(bbI_MassOffset)); + body->setMassOffset(mOffset); + } + + if (sbbI_ShapeOffset) + { + VxVector sOffset= GetInputParameterValue(beh,BB_IP_INDEX(bbI_ShapeOffset)); + body->setLocalShapePosition(sOffset,target); + } + + } + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PBSetParCB +// FullName: PBSetParCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBSetParCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBSetPar.test b/usr/Src/Behaviors/pRigidBody/PBSetPar.test new file mode 100644 index 0000000..157c85a --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBSetPar.test @@ -0,0 +1,354 @@ +#include +#include "pCommon.h" + +CKObjectDeclaration *FillBehaviorPBSetParDecl(); +CKERROR CreatePBSetParProto(CKBehaviorPrototype **pproto); +int PBSetPar(const CKBehaviorContext& behcontext); +CKERROR PBSetParCB(const CKBehaviorContext& behcontext); + + +enum bInputs +{ + + bbI_CollisionGroupX, + bbI_CollisionGroup, + bbI_GroupsMask, + /*bbI_Flags, + bbI_TFlags, + bbI_LinDamp, + bbI_AngDamp, + bbI_MassOffset, + bbI_ShapeOffset,*/ + +}; + +#define BB_SSTART 1 + +BBParameter pInMap22[] = +{ + + BB_PIN(bbI_CollisionGroupX,CKPGUID_INT,"Collision Group",""), + BB_SPIN(bbI_CollisionGroup,CKPGUID_INT,"settings driven",""), + BB_SPIN(bbI_GroupsMask,VTS_FILTER_GROUPS,"Group Mask","0.0"), + /*BB_SPIN(bbI_Flags,VTF_BODY_FLAGS,"Body Flags",""), + BB_SPIN(bbI_TFlags,VTF_BODY_TRANS_FLAGS,"Transformation Lock Flags",""), + BB_SPIN(bbI_LinDamp,CKPGUID_FLOAT,"Linear Damping","0.0"), + BB_SPIN(bbI_AngDamp,CKPGUID_FLOAT,"Angular Damping",""), + BB_SPIN(bbI_MassOffset,CKPGUID_VECTOR,"Mass Offset",""), + BB_SPIN(bbI_ShapeOffset,CKPGUID_VECTOR,"Pivot Offset",""),*/ + +}; + +#define gPIMAP pInMap22 +//************************************ +// Method: FillBehaviorPBSetParDecl +// FullName: FillBehaviorPBSetParDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBSetParDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBSetPar"); + od->SetCategory("Physic/Body"); + od->SetDescription("Sets physic parameters."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x137e7ec4,0x4ca85a4b)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBSetParProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBSetParProto +// FullName: CreatePBSetParProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBSetParProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBSetPar"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PBSetPar + + PBSetPar is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PBSetPar.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body or its sub shape. +
+ Collisions Group: Which collision group this body or the sub shape is part of.See pRigidBody::setCollisionsGroup(). +
+ Groupsmask: Sets 128-bit mask used for collision filtering. It can be sub shape specific.See comments for ::pGroupsMask and pRigidBody::setGroupsMask() +
+ + Flags: Changes essential physic behavior. See pRigidBody::setFlags()
+ - This flags can be changed after the bodies registration : + - Gravity - See pRigidBody::ennableGravity() + - Kinematic - See pRigidBody::setKinematic() + - Trigger Shape - See pRigidBody::enableTriggerShape() + - Collisions Notify - See pRigidBody::enableCollisionsNotify() + - Sleep - pRigidBody::setSleeping() or pRigidBody::isSleeping() + + Transformation Locks: Locks a translation or orientation in a specific dimension. +
+ + Linear Damping: The new linear damping scale. +
+ Angular Damping: The new linear damping scale. +
+ + Mass Offset: The new mass center in the bodies local space. +
+ Pivot Offset: Specifies the shapes position in the bodies local space. See pRigidBody::setLocalShapePosition(). +
+ + +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBSetEx.cpp + + */ + + proto->SetBehaviorCallbackFct( PBSetParCB ); + +// proto->DeclareInParameter() + + BB_EVALUATE_PINS(pInMap22) + BB_EVALUATE_SETTINGS(pInMap22) + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBSetPar); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBSetPar +// FullName: PBSetPar +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBSetPar(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + /* + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + pRigidBody *body = NULL; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorldByBody(target); + if (!world) + bbErrorME("No valid world object found"); + + + body = GetPMan()->getBody(pFactory::Instance()->getMostTopParent(target)); + if (!body) bbErrorME("Object not physicalized"); + + + */ + BB_DECLARE_PIMAP; + + + BBSParameter(bbI_CollisionGroup); + BBSParameter(bbI_CollisionGroupX); + + + int fIndex = BB_IP_INDEX(bbI_CollisionGroupX); + int fIndex2 = BB_IP_INDEX(bbI_CollisionGroup); + int fIndex3 = BB_IP_INDEX(bbI_GroupsMask); + int fIndex4 = BB_IP_INDEX(bbI_GroupsMask); + + + + /*BBSParameter(bbI_TFlags); + BBSParameter(bbI_GroupsMask); + BBSParameter(bbI_LinDamp); + BBSParameter(bbI_AngDamp); + BBSParameter(bbI_MassOffset); + BBSParameter(bbI_ShapeOffset); + + + if (sbbI_GroupsMask) + { + NxGroupsMask mask1; + CKParameter *fConst1 = beh->GetInputParameter(BB_IP_INDEX(bbI_GroupsMask))->GetRealSource(); + + using namespace vtTools::BehaviorTools; + using namespace vtTools::ParameterTools; + + NxShape *dstShape = NULL; + + NxShape *mainshape = body->getMainShape(); + if (mainshape==NULL) + { + int op = 2; + op++; + + } + NxShape *inputShape = body->_getSubShapeByEntityID(target->GetID()); + if (mainshape==inputShape) + { + dstShape = mainshape; + }else{ + dstShape = inputShape; + } + + + mask1.bits0 = GetValueFromParameterStruct(fConst1,0); + mask1.bits1 = GetValueFromParameterStruct(fConst1,1); + mask1.bits2 = GetValueFromParameterStruct(fConst1,2); + mask1.bits3 = GetValueFromParameterStruct(fConst1,3); + + if (dstShape) + { + dstShape->setGroupsMask(mask1); + } + } + + if (sbbI_CollisionGroup) + { + int collGroup = GetInputParameterValue(beh,BB_IP_INDEX(bbI_CollisionGroup)); + body->setCollisionsGroup(collGroup,target); + } + + if (sbbI_Flags) + { + int flags = GetInputParameterValue(beh,BB_IP_INDEX(bbI_Flags)); + body->updateFlags(flags,target); + } + + if (sbbI_TFlags) + { + int tflags = GetInputParameterValue(beh,BB_IP_INDEX(bbI_TFlags)); + body->lockTransformation(tflags); + } + + if (sbbI_LinDamp) + { + float lDamp = GetInputParameterValue(beh,BB_IP_INDEX(bbI_LinDamp)); + body->setLinearDamping(lDamp); + } + if (sbbI_AngDamp) + { + float aDamp= GetInputParameterValue(beh,BB_IP_INDEX(bbI_AngDamp)); + body->setAngularDamping(aDamp); + } + + if (sbbI_MassOffset) + { + VxVector mOffset= GetInputParameterValue(beh,BB_IP_INDEX(bbI_MassOffset)); + body->setMassOffset(mOffset); + } + + if (sbbI_ShapeOffset) + { + VxVector sOffset= GetInputParameterValue(beh,BB_IP_INDEX(bbI_ShapeOffset)); + body->setLocalShapePosition(sOffset,target); + } + + */ + } + + + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PBSetParCB +// FullName: PBSetParCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBSetParCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBSetTriggerMask.cpp b/usr/Src/Behaviors/pRigidBody/PBSetTriggerMask.cpp new file mode 100644 index 0000000..8a37dc5 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBSetTriggerMask.cpp @@ -0,0 +1,200 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPBSetTriggerMaskDecl(); +CKERROR CreatePBSetTriggerMaskProto(CKBehaviorPrototype **pproto); +int PBSetTriggerMask(const CKBehaviorContext& behcontext); +CKERROR PBSetTriggerMaskCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + + bbI_OnEnter, + bbI_OnStay, + bbI_OnLeave, +}; + +//************************************ +// Method: FillBehaviorPBSetTriggerMaskDecl +// FullName: FillBehaviorPBSetTriggerMaskDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBSetTriggerMaskDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PCSetTriggerMask"); + od->SetCategory("Physic/Collision"); + od->SetDescription("Modifies trigger mask"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x27ae51d4,0x45bf2c6c)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBSetTriggerMaskProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBSetTriggerMaskProto +// FullName: CreatePBSetTriggerMaskProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBSetTriggerMaskProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PCSetTriggerMask"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! \page PCSetTriggerMask + + PCSetTriggerMask is categorized in \ref Collision + +

Description

+ Apply to a 3DEntity
+ Modifies the trigger mask of a bodies or a sub shape of it.
+ See pBTriggerEvent.cmo for example. + + +

Technical Information

+ + \image html PBSetTriggerMask.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The shape reference. Can be a sub shape or the initial mesh. +
+
+ On Enter: Enables triggering if the body starts entering another shape. +
+ On Stay: Enables triggering if the body stays in another shape. +
+ On Leave: Enables triggering if the body leaves another shape. +
+ +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PCSetTriggerMask.cpp + + */ + + proto->SetBehaviorCallbackFct( PBSetTriggerMaskCB ); + proto->DeclareInParameter("On Enter",CKPGUID_BOOL,"true"); + proto->DeclareInParameter("On Stay",CKPGUID_BOOL,"true"); + proto->DeclareInParameter("On Leave",CKPGUID_BOOL,"true"); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PBSetTriggerMask); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBSetTriggerMask +// FullName: PBSetTriggerMask +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBSetTriggerMask(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) return CKBR_OWNERERROR; + + + ////////////////////////////////////////////////////////////////////////// + // the world : + + pWorld *world = GetPMan()->getWorldByShapeReference(target); + if (!world) + { + beh->ActivateOutput(0); + return 0; + } + + if (world) + { + NxShape *shape = world->getShapeByEntityID(target->GetID()); + if (shape) + { + + int onEnter = GetInputParameterValue(beh,bbI_OnEnter); + int onStay = GetInputParameterValue(beh,bbI_OnStay); + int onLeave = GetInputParameterValue(beh,bbI_OnLeave); + + shape->setFlag(NX_TRIGGER_ON_ENTER,onEnter); + shape->setFlag(NX_TRIGGER_ON_STAY,onStay); + shape->setFlag(NX_TRIGGER_ON_LEAVE,onLeave); + + } + } + + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBSetTriggerMaskCB +// FullName: PBSetTriggerMaskCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBSetTriggerMaskCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PBUnPhysicalize.cpp b/usr/Src/Behaviors/pRigidBody/PBUnPhysicalize.cpp new file mode 100644 index 0000000..0e4efe9 --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PBUnPhysicalize.cpp @@ -0,0 +1,129 @@ +#include +#include "pCommon.h" + + + +CKObjectDeclaration *FillBehaviorPBDestroyDecl(); +CKERROR CreatePBDestroyProto(CKBehaviorPrototype **pproto); +int PBDestroy(const CKBehaviorContext& behcontext); +CKERROR PBDestroyCB(const CKBehaviorContext& behcontext); + + +//************************************ +// Method: FillBehaviorPBDestroyDecl +// FullName: FillBehaviorPBDestroyDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPBDestroyDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PBDestroy"); + od->SetCategory("Physic/Body"); + od->SetDescription("Removes an entity from the physic engine."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x72519cc,0x1f2d16da)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePBDestroyProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePBDestroyProto +// FullName: CreatePBDestroyProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePBDestroyProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PBDestroy"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In0"); + proto->DeclareOutput("Out0"); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + proto->SetBehaviorCallbackFct( PBDestroyCB ); + proto->SetFunction(PBDestroy); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PBDestroy +// FullName: PBDestroy +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PBDestroy(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *referenceObject = (CK3dEntity *) beh->GetTarget(); + if( !referenceObject ) return CKBR_OWNERERROR; + + pWorld *world=GetPMan()->getWorldByBody(referenceObject); + if (world) + { + + pRigidBody*bodyA= world->getBody(referenceObject); + if (bodyA) + { + world->deleteBody(bodyA); + } + } + beh->ActivateInput(0,FALSE); + beh->ActivateOutput(0); + } + return 0; +} + +//************************************ +// Method: PBDestroyCB +// FullName: PBDestroyCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PBDestroyCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORATTACH: + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORSETTINGSEDITED: + { + + + } + break; + } + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/pRigidBody/PMaterialIterator.cpp b/usr/Src/Behaviors/pRigidBody/PMaterialIterator.cpp new file mode 100644 index 0000000..c825dbf --- /dev/null +++ b/usr/Src/Behaviors/pRigidBody/PMaterialIterator.cpp @@ -0,0 +1,275 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPMaterialIteratorDecl(); +CKERROR CreatePMaterialIteratorProto(CKBehaviorPrototype **pproto); +int PMaterialIterator(const CKBehaviorContext& behcontext); +CKERROR PMaterialIteratorCB(const CKBehaviorContext& behcontext); + +using namespace vtTools::BehaviorTools; +using namespace vtTools::ParameterTools; + + +enum bInputs +{ + I_XML, + I_DFRICTION, + I_SFRICTION, + I_RES, + I_DFRICTIONV, + I_SFRICTIONV, + I_ANIS, + I_FCMODE, + I_RCMODE, + I_FLAGS, +}; + +enum bOutputs +{ + O_INDEX, + O_XML, + O_NAME, + O_DFRICTION, + O_SFRICTION, + O_RES, + O_DFRICTIONV, + O_SFRICTIONV, + O_ANIS, + O_FCMODE, + O_RCMODE, + O_FLAGS, + O_MATERIAL, +}; + +CKERROR PMaterialIteratorCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + CKContext *ctx = beh->GetCKContext(); + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORLOAD: + case CKM_BEHAVIORATTACH: + { + + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + + + + + } + + } + return CKBR_OK; + +} + +//************************************ +// Method: FillBehaviorPMaterialIteratorDecl +// FullName: FillBehaviorPMaterialIteratorDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration*FillBehaviorPMaterialIteratorDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PMaterialIterator"); + od->SetCategory("Physic/Body"); + od->SetDescription("Attaches and/or modifies the physic material of a rigid body or its sub shape"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x121d1c0f,0x65a62e73)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePMaterialIteratorProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePMaterialIteratorProto +// FullName: CreatePMaterialIteratorProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePMaterialIteratorProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PMaterialIterator"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + + proto->DeclareInput("Next"); + proto->DeclareOutput("Finish"); + proto->DeclareOutput("Loop"); + + proto->DeclareLocalParameter("current result", CKPGUID_POINTER, "0"); + + proto->DeclareOutParameter("Index",CKPGUID_INT); + proto->DeclareOutParameter("XML Link",VTE_XML_MATERIAL_TYPE); + proto->DeclareOutParameter("Name",CKPGUID_STRING); + proto->DeclareOutParameter("Dynamic Friction",CKPGUID_FLOAT); + proto->DeclareOutParameter("Static Friction",CKPGUID_FLOAT); + proto->DeclareOutParameter("Restitution",CKPGUID_FLOAT); + proto->DeclareOutParameter("Dynamic Friction V",CKPGUID_FLOAT); + proto->DeclareOutParameter("Static Friction V",CKPGUID_FLOAT); + proto->DeclareOutParameter("Direction of Anisotropy ",CKPGUID_VECTOR); + proto->DeclareOutParameter("Friction Combine Mode",VTE_MATERIAL_COMBINE_MODE); + proto->DeclareOutParameter("Restitution Combine Mode",VTE_MATERIAL_COMBINE_MODE); + proto->DeclareOutParameter("Flags",VTF_MATERIAL_FLAGS); + proto->DeclareOutParameter("Result",VTS_MATERIAL); + + proto->SetBehaviorCallbackFct( PMaterialIteratorCB ); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PMaterialIterator); + *pproto = proto; + return CK_OK; +} + + +//************************************ +// Method: PMaterialIterator +// FullName: PMaterialIterator +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ + +typedef std::vectorLMaterials; + + +int PMaterialIterator(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + if (beh->IsInputActive(0)) + { + beh->ActivateInput(0,FALSE); + + ////////////////////////////////////////////////////////////////////////// + //we reset our session counter + int sessionIndex=-1; + beh->SetOutputParameterValue(0,&sessionIndex); + + + LMaterials*sResults = NULL; + beh->GetLocalParameterValue(0,&sResults); + if (!sResults) + { + sResults = new LMaterials(); + }else + sResults->clear(); + + + NxScene * scene = GetPMan()->getDefaultWorld()->getScene(); + for(int i = 0 ; i < GetPMan()->getDefaultWorld()->getScene()->getNbMaterials() ; i ++) + { + + NxMaterial *currentMaterial = scene->getMaterialFromIndex(i); + + sResults->push_back(currentMaterial); + } + + beh->SetLocalParameterValue(0,&sResults); + + + + if (sResults->size()) + { + beh->ActivateInput(1); + }else + { + beh->ActivateOutput(0); + return 0; + } + } + + + + + if( beh->IsInputActive(1) ) + { + beh->ActivateInput(1,FALSE); + + int currentIndex=0; CKParameterOut *pout = beh->GetOutputParameter(0); pout->GetValue(¤tIndex); + currentIndex++; + + + + LMaterials *sResults = NULL; beh->GetLocalParameterValue(0,&sResults); + if (!sResults) { beh->ActivateOutput(0); return 0; } + + if (currentIndex>=sResults->size()) + { + sResults->clear(); + beh->ActivateOutput(0); + return 0; + } + + NxMaterial * material = sResults->at(currentIndex); + if (material!=NULL) + { + + int sIndex = currentIndex+1; + beh->SetOutputParameterValue(0,&sIndex); + + + + + //SetOutputParameterValue(beh,O_XML,material->xmlLinkID); + SetOutputParameterValue(beh,O_DFRICTION,material->getDynamicFriction()); + SetOutputParameterValue(beh,O_SFRICTION,material->getStaticFriction()); + + SetOutputParameterValue(beh,O_RES,material->getRestitution()); + + SetOutputParameterValue(beh,O_DFRICTIONV,material->getDynamicFrictionV()); + SetOutputParameterValue(beh,O_SFRICTIONV,material->getStaticFrictionV()); + + SetOutputParameterValue(beh,O_ANIS,getFrom(material->getDirOfAnisotropy())); + SetOutputParameterValue(beh,O_FCMODE,material->getFrictionCombineMode()); + SetOutputParameterValue(beh,O_RCMODE,material->getFrictionCombineMode()); + SetOutputParameterValue(beh,O_FLAGS,material->getFlags()); + } + + if(material->userData ) + { + pMaterial *bMaterial = static_cast(material->userData); + + if (bMaterial && bMaterial->xmlLinkID ) + { + + int xid = bMaterial->xmlLinkID; + XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,xid); + CKParameterOut *nameStr = beh->GetOutputParameter(O_NAME); + nameStr->SetStringValue(nodeName.Str()); + } + } + //pFactory::Instance()->copyTo(beh->GetOutputParameter(O_MATERIAL),material); + + + beh->ActivateOutput(0); + } + return 0; +} diff --git a/usr/Src/Behaviors/pVehicle/PVControl.cpp b/usr/Src/Behaviors/pVehicle/PVControl.cpp new file mode 100644 index 0000000..316989b --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVControl.cpp @@ -0,0 +1,333 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPVControlDecl(); +CKERROR CreatePVControlProto(CKBehaviorPrototype **pproto); +int PVControl(const CKBehaviorContext& behcontext); +CKERROR PVControlCB(const CKBehaviorContext& behcontext); + +using namespace vtTools::BehaviorTools; + + + +enum bInTrigger +{ + TI_DO, +}; + +enum bOutputs +{ + + O_Flags, + O_Gear, + O_RPM, + O_RPM_WHEELS, + O_RATIO, + + +}; + + +enum bInputs +{ + I_Acc, + I_Steer, + I_AnalogAcc, + I_AnalogSteering, + I_Handbrake, + +}; + + + +#define BB_SSTART 0 + +BBParameter pInMap3[] = +{ + + BB_SPIN(I_Acc,CKPGUID_FLOAT,"Acceleration","0"), + BB_SPIN(I_Steer,CKPGUID_FLOAT,"Steering","0"), + BB_SPIN(I_AnalogAcc,CKPGUID_BOOL,"Analog Acceleration","0"), + BB_SPIN(I_AnalogSteering,CKPGUID_BOOL,"Analog Steering","0"), + BB_SPIN(I_Handbrake,CKPGUID_BOOL,"Handbrake","0"), + + +}; + +#define BBIMAP pInMap3 + +CKERROR PVControlCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(BBIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(BBIMAP,BB_SSTART); + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(BBIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; + +} + +//************************************ +// Method: FillBehaviorPVControlDecl +// FullName: FillBehaviorPVControlDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPVControlDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVControl"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Controls a vehicle by real values instead of input trigger"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x550d3ca3,0x27f10ac3)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVControlProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePVControlProto +// FullName: CreatePVControlProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePVControlProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVControl"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /* PVControl + + PVControl is categorized in \ref Vehicles + +

Description

+ Apply to a 3DEntity
+ Controls a vehicle by real values instead of input trigger.
+ +

Technical Information

+ + \image html PVControl.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the vehicle. The entity needs to be physicalized before. It needs to have at least one wheel in its hierarchy. +
+
+ Acceleration: The acceleration for this frame.
+ Range: [0,1] +
+ + Steering: The steering for this frame.
+ Range: [-1,1] +
+ + Analog Acceleration: Switches between analog and digital acceleration.
+ Range: TRUE,FALSE] +
+ + Analog Steering: Switches between analog and digital steering.
+ Range: TRUE,FALSE] +
+ + Handbrake: Sets the handbrake status to enabled for this frame.
+ Range: TRUE,FALSE] +
+ + Acceleration: Enables input for acceleration. +
+ + Steering: Enables input for steering. +
+ + Analog Acceleration: Enables input for analog acceleration. +
+ + Analog Steering: Enables input for analog steering. +
+ + Handbrake: Enables input for handbrake. +
+ +
+

Warning

+ The body must be dynamic.
+ The body must have a vehicle object. See #ref PVSet +
+ +

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ + + + */ + + + + proto->SetBehaviorCallbackFct( PVControlCB ); + + proto->DeclareOutParameter("Flags",VTF_VSTATE_FLAGS,"-1"); + proto->DeclareOutParameter("Gear",CKPGUID_INT,"-1"); + proto->DeclareOutParameter("RPM",CKPGUID_FLOAT,"-1"); + proto->DeclareOutParameter("RPM Wheels",CKPGUID_FLOAT,"-1"); + proto->DeclareOutParameter("Motor Ratio",CKPGUID_FLOAT,"-1"); + + + BB_EVALUATE_SETTINGS(BBIMAP); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PVControl); + *pproto = proto; + return CK_OK; +} + + +//************************************ +// Method: PVControl +// FullName: PVControl +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ + + +#define BBSParameter(A) DWORD s##A;\ + beh->GetLocalParameterValue(A,&s##A) + +int PVControl(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + + beh->ActivateInput(0,FALSE); + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbSErrorME(E_PE_REF); + + + pRigidBody *body = NULL; + + + BB_DECLARE_PIMAP; + + body = GetPMan()->getBody(target); + if (!body) + bbSErrorME(E_PE_NoBody); + + + + float acc = GetInputParameterValue(beh,BB_IP_INDEX(I_Acc)); + int accAnalog = GetInputParameterValue(beh,BB_IP_INDEX(I_AnalogAcc)); + float steer = GetInputParameterValue(beh,BB_IP_INDEX(I_Steer)); + int steerAnalog = GetInputParameterValue(beh,BB_IP_INDEX(I_AnalogSteering)); + int handBrake = GetInputParameterValue(beh,BB_IP_INDEX(I_Handbrake)); + + + BBSParameter(I_Acc); + BBSParameter(I_AnalogAcc); + BBSParameter(I_Steer); + BBSParameter(I_AnalogSteering); + BBSParameter(I_Handbrake); + + pVehicle *v = body->getVehicle(); + if (!v) + { + bbSErrorME(E_PE_NoVeh); + } + + if (sI_Acc && acc!=v->_cAcceleration) + v->setControlState(E_VCS_ACCELERATION,acc); + + if (sI_AnalogAcc && accAnalog!=v->_cAnalogAcceleration) + v->setControlMode(E_VCS_ACCELERATION,accAnalog ? E_VCSM_ANALOG : E_VCSM_DIGITAL); + + if (sI_Steer && steer!=v->_cSteering) + v->setControlState(E_VCS_STEERING,steer); + + if (sI_AnalogSteering && steerAnalog!=v->_cAnalogSteering ) + v->setControlMode(E_VCS_STEERING,steerAnalog ? E_VCSM_ANALOG : E_VCSM_DIGITAL); + + + if (sI_Handbrake && handBrake ) + v->setControlState(E_VCS_HANDBRAKE,handBrake == 1 ? true : false); + + + + DWORD flags = v->getStateFlags(); + beh->SetOutputParameterValue(O_Flags,&flags); + + + float ratio = v->_getGearRatio(); + beh->SetOutputParameterValue(O_RATIO,&ratio); + + if (v->getGears()) + { + int g = v->getGears()->getGear(); + beh->SetOutputParameterValue(O_Gear,&g); + } + + if (v->getMotor()) + { + float rpm = v->getMotor()->getRpm(); + beh->SetOutputParameterValue(O_RPM,&rpm); + } + + beh->ActivateOutput(0); + } + return 0; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pVehicle/PVControlCar.cpp b/usr/Src/Behaviors/pVehicle/PVControlCar.cpp new file mode 100644 index 0000000..cf556f4 --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVControlCar.cpp @@ -0,0 +1,528 @@ + +#include +#include "pCommon.h" + + + + + +CKObjectDeclaration *FillBehaviorPVControl2Decl(); +CKERROR CreatePVControl2Proto(CKBehaviorPrototype **pproto); +int PVControl2(const CKBehaviorContext& behcontext); +CKERROR PVControl2CB(const CKBehaviorContext& behcontext); + +using namespace vtTools::BehaviorTools; + + + +enum bInTrigger +{ + TI_DO, +}; + +enum bOutputs +{ + + O_Gear, + O_MPH, + O_GearRatio, + O_MotorRPM, + /*O_RPM, + O_RPM_WHEELS, + O_RATIO,*/ +}; + + +enum bTInputs +{ + + IT_On, + IT_Off, + IT_Forward, + IT_Backwards, + IT_Left, + IT_Right, + IT_HandBrake, + IT_GUP, + IT_GDOWN + +}; + +enum bTOutputs +{ + OT_On, + OT_Off, + OT_GearUp, + OT_GearDown, +}; + + +enum bSettings +{ + bs_Manual, +}; + + + +#define BB_SSTART 0 + + + + +//************************************ +// Method: FillBehaviorPVControl2Decl +// FullName: FillBehaviorPVControl2Decl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPVControl2Decl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVCarControl"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Physics Car"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x26371b1c,0x4e3924)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVControl2Proto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePVControl2Proto +// FullName: CreatePVControl2Proto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePVControl2Proto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVCarControl"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("On"); + proto->DeclareInput("Off"); + proto->DeclareInput("Forward"); + proto->DeclareInput("Backward"); + proto->DeclareInput("Turn Left"); + proto->DeclareInput("Turn Right"); + proto->DeclareInput("Handbrake"); + + proto->DeclareOutput("Exit On"); + proto->DeclareOutput("Exit Off"); + proto->DeclareOutput("GearUp"); + proto->DeclareOutput("GearDown"); + + + + proto->DeclareOutParameter("Current Gear",CKPGUID_INT,"-1"); + proto->DeclareOutParameter("MPH",CKPGUID_FLOAT,"-1"); + proto->DeclareOutParameter("Gear Ratio",CKPGUID_FLOAT,"-1"); + proto->DeclareOutParameter("Motor RPM",CKPGUID_FLOAT,"-1"); + + + proto->DeclareSetting("Automatic",CKPGUID_BOOL,"TRUE"); + proto->DeclareSetting("Semi Analog",CKPGUID_BOOL,"TRUE"); + + + /* PVControl2 + + PVControl2 is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PVControl2.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Collisions Group: Which collision group this body is part of.See pRigidBody::setCollisionsGroup(). +
+ Kinematic Object: The kinematic state. See pRigidBody::setKinematic(). +
+ Gravity: The gravity state.See pRigidBody::enableGravity(). +
+ Collision: Determines whether the body reacts to collisions.See pRigidBody::enableCollision(). +
+ Mass Offset: The new mass center in the bodies local space. +
+ Pivot Offset: The initial shape position in the bodies local space. +
+ Notify Collision: Enables collision notification.This is necessary to use collisions related building blocks. +
+ Transformation Locks: Specifies in which dimension a a transformation lock should occour. +
+ Linear Damping: The new linear damping scale. +
+ Angular Damping: The new linear damping scale. +
+ + Filter Groups: Sets the filter mask of the initial or sub shape. +
+ + + Collisions Group: Enables input for collisions group. +
+ Kinematic Object: Enables input for kinematic object. +
+ Gravity: Enables input for gravity. +
+ Collision: Enables input for collision. +
+ Mas Offset: Enables input for mass offset. +
+ Pivot Offset: Enables input for pivot offset. +
+ Notify Collision: Enables input for collision. +
+ Linear Damping: Enables input for linear damping. +
+ Angular Damping: Enables input for angular damping. +
+ Filter Groups: Enables input for filter groups. +
+ +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ + +*/ + proto->SetBehaviorCallbackFct( PVControl2CB ); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PVControl2); + *pproto = proto; + return CK_OK; +} + + +//************************************ +// Method: PVControl2 +// FullName: PVControl2 +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ + + +#define BBSParameter(A) DWORD s##A;\ + beh->GetLocalParameterValue(A,&s##A) + +int PVControl2(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbSErrorME(E_PE_REF); + + + pRigidBody *body = NULL; + + body = GetPMan()->getBody(target); + if (!body) + bbSErrorME(E_PE_NoBody); + + + pVehicle *v = body->getVehicle(); + if (!v) + { + bbSErrorME(E_PE_NoVeh); + } + + + + if( beh->IsInputActive(IT_On) ) + { + beh->ActivateInput(IT_On,FALSE); + beh->ActivateOutput(OT_On); + + + } + + if( beh->IsInputActive(IT_Off) ) + { + beh->ActivateInput(IT_Off,FALSE); + beh->ActivateOutput(OT_Off); + return 0; + + } + + ////////////////////////////////////////////////////////////////////////// + // + // + // Acceleration + // + + + float acceleration = 0.0f; + float steering = 0.0; + + int gearUP= 0; + int gearDown= 0; + int handbrake = 0; + + + /* + v->setControlState(E_VCS_ACCELERATION,acceleration); + v->setControlState(E_VCS_HANDBRAKE,handbrake); + v->setControlState(E_VCS_STEERING,steering); + v->setControlMode(E_VCS_ACCELERATION,E_VCSM_DIGITAL); + v->setControlMode(E_VCS_STEERING,E_VCSM_DIGITAL); + */ + + ////////////////////////////////////////////////////////////////////////// + // + // Acceleration + Handbrake + // + + if( beh->IsInputActive(IT_Forward) ) + { + beh->ActivateInput(IT_Forward,FALSE); + acceleration = 1.0f; + v->setControlState(E_VCS_ACCELERATION,acceleration); + } + + if( beh->IsInputActive(IT_Backwards) ) + { + beh->ActivateInput(IT_Backwards,FALSE); + acceleration = -1.0f; + v->setControlState(E_VCS_ACCELERATION,acceleration); + } + + + if( beh->IsInputActive(IT_HandBrake) ) + { + beh->ActivateInput(IT_HandBrake,FALSE); + handbrake = 1; + v->setControlState(E_VCS_HANDBRAKE,handbrake); + } + + ////////////////////////////////////////////////////////////////////////// + // + // Steering + if( beh->IsInputActive(IT_Left) ) + { + beh->ActivateInput(IT_Left,FALSE); + steering = 1.0f; + v->setControlState(E_VCS_STEERING,steering); + } + + if( beh->IsInputActive(IT_Right) ) + { + beh->ActivateInput(IT_Right,FALSE); + steering = -1.0f; + v->setControlState(E_VCS_STEERING,steering); + } + + //if(acceleration !=0.0f || steering !=0.0f || handbrake) + //v->control(steering,false,acceleration,false,handbrake); + + + int semiAnalog = 0; + beh->GetLocalParameterValue(1,&semiAnalog); + + + + ////////////////////////////////////////////////////////////////////////// + // + // Gears + // + int automatic=0; + beh->GetLocalParameterValue(bs_Manual,&automatic); + v->setAutomaticMode(automatic); + + + int lastGear=0; + beh->GetOutputParameterValue(O_Gear,&lastGear); + + int currentGear = 0; + + if (v->getGears()) + { + currentGear = v->getGears()->getGear(); + } + + if (!automatic) + { + + if( beh->IsInputActive(IT_GUP) ) + { + beh->ActivateInput(IT_GUP,FALSE); + gearUP =1; + } + if( beh->IsInputActive(IT_GDOWN) ) + { + beh->ActivateInput(IT_GDOWN,FALSE); + gearDown=1; + } + + } + + if ( gearUP && !gearDown) + { + v->setControlState(E_VCS_GUP,1); + v->setControlState(E_VCS_GDOWN,0); + }else{ + v->setControlState(E_VCS_GUP,0); + } + + if ( !gearUP && gearDown) + { + v->setControlState(E_VCS_GUP,0); + v->setControlState(E_VCS_GDOWN,1); + } + if ( !gearUP) + { + v->setControlState(E_VCS_GUP,0); + } + if ( !gearDown) + { + v->setControlState(E_VCS_GDOWN,0); + } + +/* + + if (!automatic) + { + + if( beh->IsInputActive(IT_GUP) ) + { + beh->ActivateInput(IT_GUP,FALSE); + gearUP =1; + } + + if( beh->IsInputActive(IT_GDOWN) ) + { + beh->ActivateInput(IT_GDOWN,FALSE); + gearDown=1; + } + + if (gearUP && !gearDown) + { + v->gearUp(); + } + if (!gearUP && gearDown) + { + v->gearDown(); + } + }else + { + if (v->getGears()) + { + if (currentGear!=lastGear) + { + if (currentGear > lastGear) + { + beh->ActivateOutput(OT_GearUp); + }else + beh->ActivateOutput(OT_GearDown); + } + } + } + +*/ + + + + /////////////////////////////////////////////////////////////////////////// + // + // Vehicle Data : + // + + + float mph = v->getMPH(); + beh->SetOutputParameterValue(O_MPH,&mph); + + float gRatio = v->_getGearRatio(); + beh->SetOutputParameterValue(O_GearRatio,&gRatio); + beh->SetOutputParameterValue(O_Gear,¤tGear); + if (v->getMotor()) + { + float rpm = v->getMotor()->getRpm(); + beh->SetOutputParameterValue(O_MotorRPM,&rpm); + } + return CKBR_ACTIVATENEXTFRAME; +} + +CKERROR PVControl2CB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORLOAD: + { + break; + } + case CKM_BEHAVIORDETACH: + { + break; + } + + case CKM_BEHAVIORATTACH: + { + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + int automatic=0; + beh->GetLocalParameterValue(bs_Manual,&automatic); + + int nbI = beh->GetInputCount(); + + if (automatic) + { + if (nbI > IT_GUP ) + { + beh->DeleteInput( IT_GUP); + beh->DeleteInput( IT_GUP); + } + } + + if (!automatic) + { + if (nbI < IT_GDOWN ) + { + beh->AddInput("Gear Up"); + beh->AddInput("Gear Down"); + } + } + + break; + } + } + return CKBR_OK; + +} diff --git a/usr/Src/Behaviors/pVehicle/PVSet.cpp b/usr/Src/Behaviors/pVehicle/PVSet.cpp new file mode 100644 index 0000000..7f2a1d1 --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVSet.cpp @@ -0,0 +1,428 @@ +#include +#include "pCommon.h" + + + + +CKObjectDeclaration *FillBehaviorPVSetDecl(); +CKERROR CreatePVSetProto(CKBehaviorPrototype **pproto); +int PVSet(const CKBehaviorContext& behcontext); +CKERROR PVSetCB(const CKBehaviorContext& behcontext); + +using namespace vtTools::BehaviorTools; + + + +enum bInputs +{ + I_XML, + I_Mass, + I_CMass, + + I_MotorForce, + I_DiffRatio, + I_TEff, + I_MaxVelocity, + + I_SteerMax, + I_SteeringSteerPoint, + I_SteerTurnPoint, + I_DSDelta, + +}; + + + +#define BB_SSTART 0 + +BBParameter pInMap[] = +{ + + BB_SPIN(I_XML,VTE_XML_VEHICLE_SETTINGS,"Vehicle Settings","None"), + BB_SPIN(I_Mass,CKPGUID_FLOAT,"Mass","1000"), + BB_SPIN(I_CMass,CKPGUID_VECTOR,"Center of Mass","0,0,0"), + + BB_SPIN(I_MotorForce,CKPGUID_FLOAT,"Motor Force","2000.0"), + BB_SPIN(I_DiffRatio,CKPGUID_FLOAT,"Differential Ratio","1.0"), + BB_SPIN(I_TEff,CKPGUID_FLOAT,"Transmission Efficiency","0.5"), + BB_SPIN(I_MaxVelocity,CKPGUID_FLOAT,"Max Velocity","1000"), + + BB_SPIN(I_SteerMax,CKPGUID_ANGLE,"Maximum Steer","15"), + BB_SPIN(I_CMass,CKPGUID_VECTOR,"Steering Steer Point","0,0,0"), + BB_SPIN(I_CMass,CKPGUID_VECTOR,"Steering Turn Point","0,0,0"), + BB_SPIN(I_DSDelta,CKPGUID_FLOAT,"Digital Steering Delta","0.5"), + + + +}; + +#define gVSMap pInMap +//#define BB_LOAD_PIMAP(SOURCE_MAP,SETTING_START_INDEX) BBHelper::loadPIMap(beh,pIMap,SOURCE_MAP,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX) + + +CKERROR PVSetCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + BB_DECLARE_PMAP; + switch(behcontext.CallbackMessage) + { + + + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gVSMap,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gVSMap,BB_SSTART); + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gVSMap,BB_SSTART); + break; + } + } + return CKBR_OK; + +} + +//************************************ +// Method: FillBehaviorPVSetDecl +// FullName: FillBehaviorPVSetDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPVSetDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVSet"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Modifies vehicle parameter."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0xb7e2395,0x7cfe4597)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVSetProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePVSetProto +// FullName: CreatePVSetProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePVSetProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVSet"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /*! PVSet + + PVSet is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PVSet.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Collisions Group: Which collision group this body is part of.See pRigidBody::setCollisionsGroup(). +
+ Kinematic Object: The kinematic state. See pRigidBody::setKinematic(). +
+ Gravity: The gravity state.See pRigidBody::enableGravity(). +
+ Collision: Determines whether the body reacts to collisions.See pRigidBody::enableCollision(). +
+ Mass Offset: The new mass center in the bodies local space. +
+ Pivot Offset: The initial shape position in the bodies local space. +
+ Notify Collision: Enables collision notification.This is necessary to use collisions related building blocks. +
+ Transformation Locks: Specifies in which dimension a a transformation lock should occour. +
+ Linear Damping: The new linear damping scale. +
+ Angular Damping: The new linear damping scale. +
+ + Filter Groups: Sets the filter mask of the initial or sub shape. +
+ + + Collisions Group: Enables input for collisions group. +
+ Kinematic Object: Enables input for kinematic object. +
+ Gravity: Enables input for gravity. +
+ Collision: Enables input for collision. +
+ Mas Offset: Enables input for mass offset. +
+ Pivot Offset: Enables input for pivot offset. +
+ Notify Collision: Enables input for collision. +
+ Linear Damping: Enables input for linear damping. +
+ Angular Damping: Enables input for angular damping. +
+ Filter Groups: Enables input for filter groups. +
+ +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBSetEx.cpp + + */ + + //proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); + /*proto->DeclareSetting("Kinematic",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Gravity",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Mass Offset",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Pivot Offset",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Notify Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Transformation Locks",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Linear Damping",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Angular Damping",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Filter Groups",CKPGUID_BOOL,"FALSE"); +*/ + proto->SetBehaviorCallbackFct( PVSetCB ); + + + BB_EVALUATE_SETTINGS(pInMap); + + //---------------------------------------------------------------- + // + // We just want create the building block pictures + // + #ifdef _DOC_ONLY_ + BB_EVALUATE_INPUTS(pInMap); + #endif // _DOC_ONLY_ + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PVSet); + *pproto = proto; + return CK_OK; +} + + +//************************************ +// Method: PVSet +// FullName: PVSet +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ + + +#define BBSParameter(A) DWORD s##A;\ + beh->GetLocalParameterValue(A,&s##A) + +int PVSet(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbSErrorME(E_PE_REF); + + + pRigidBody *body = NULL; + + + BB_DECLARE_PIMAP; + + body = GetPMan()->getBody(target); + if (!body) + bbSErrorME(E_PE_NoBody); + + + int xmlValue = GetInputParameterValue(beh,BB_IP_INDEX(I_XML)); + float mass = GetInputParameterValue(beh,BB_IP_INDEX(I_Mass)); + float mForce = GetInputParameterValue(beh,BB_IP_INDEX(I_MotorForce)); + float dRatio = GetInputParameterValue(beh,BB_IP_INDEX(I_DiffRatio)); + float steerMax = GetInputParameterValue(beh,BB_IP_INDEX(I_SteerMax)); + float dsDelta = GetInputParameterValue(beh,BB_IP_INDEX(I_DSDelta)); + float tEff = GetInputParameterValue(beh,BB_IP_INDEX(I_TEff)); + float maxVel = GetInputParameterValue(beh,BB_IP_INDEX(I_MaxVelocity)); + VxVector cMass = GetInputParameterValue(beh,BB_IP_INDEX(I_CMass)); + + VxVector steeringSteerPoint = GetInputParameterValue(beh,BB_IP_INDEX(I_SteeringSteerPoint)); + VxVector steeringTurnPoint = GetInputParameterValue(beh,BB_IP_INDEX(I_SteerTurnPoint)); + + + BBSParameter(I_XML); + BBSParameter(I_Mass); + BBSParameter(I_MotorForce); + BBSParameter(I_DiffRatio); + BBSParameter(I_SteerMax); + BBSParameter(I_DSDelta); + BBSParameter(I_MaxVelocity); + BBSParameter(I_CMass); + BBSParameter(I_TEff); + + BBSParameter(I_SteeringSteerPoint); + BBSParameter(I_SteerTurnPoint); + + + pVehicle *v = body->getVehicle(); + if (!v) + { + pVehicleDesc vdesc; + vdesc.setToDefault(); + + //pVehicleGearDesc *gearDesc = vdesc.getGearDescription(); + //gearDesc->setToCorvette(); + + //pVehicleMotorDesc *motorDesc = vdesc.getMotorDescr(); + //motorDesc->setToCorvette(); + v = pFactory::Instance()->createVehicle(target,vdesc); + + } + + if (!v) + bbErrorME("Couldn't create vehicle"); + + if (sI_Mass) v->setMass(mass); + if (sI_MotorForce) v->setMotorForce(mForce); + if (sI_DiffRatio)v->setDifferentialRatio(dRatio); + if (sI_SteerMax)v->setMaxSteering(steerMax) ; + if (sI_DSDelta)v->setDigitalSteeringDelta(dsDelta); + if (sI_MaxVelocity)v->setMaxVelocity(maxVel); + if (sI_CMass)v->setCenterOfMass(cMass); + if (sI_TEff)v->setTransmissionEfficiency(tEff); + if(sI_SteeringSteerPoint)v->setSteeringSteerPoint(steeringSteerPoint); + if(sI_SteerTurnPoint)v->setSteeringTurnPoint(steeringTurnPoint ); + + + } + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PVSetCB +// FullName: PVSetCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +/* + +dx -0.99999821 float +angle -0.21089047 float +zPos 0.99999857 float +dz 4.6712832 float +xPos -0.99999821 float +atan3 -0.21089047 float + + +dx 1.0000019 float +angle 0.21089132 float +zPos 1.0000004 float +dz 4.6712813 float +xPos 1.0000019 float +atan3 0.21089132 float + + + + +*/ + +/* +// int indexA = BBHelper::getIndex(beh,pMap,bbI_AxleSpeed); +// int indexB = BBHelper::getIndex(beh,pMap,bbI_Steer); + +/* +EnablePInputBySettings(beh,bbI_AxleSpeed); +EnablePInputBySettings(beh,bbI_Steer); +EnablePInputBySettings(beh,bbI_MotorTorque); +EnablePInputBySettings(beh,bbI_BrakeTorque); +EnablePInputBySettings(beh,bbI_SuspensionSpring); +EnablePInputBySettings(beh,bbI_SuspensionTravel); +EnablePInputBySettings(beh,bbI_Radius); +*/ + + + + +/* + case CKM_BEHAVIORDETACH: + { + + /* BB_DECLARE_PIMAP; + while ( pIMap->getArray().size() ) + { + + BBParameter *p=pIMap->getArray().at(0); + pIMap->getArray().erase(pIMap->getArray().begin()); + delete p; + p = NULL; + } + break; + */ + // BB_DECLARE_PIMAP; + // BBHelper::destroyPIMap(beh,pIMap,BB_PMAP_SIZE); + + + diff --git a/usr/Src/Behaviors/pVehicle/PVSetBreakSettings.cpp b/usr/Src/Behaviors/pVehicle/PVSetBreakSettings.cpp new file mode 100644 index 0000000..fc7d0ac --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVSetBreakSettings.cpp @@ -0,0 +1,289 @@ +#include +#include "pCommon.h" +#include "IParameter.h" +#include + + +CKObjectDeclaration *FillBehaviorPVSetBreakSettingsDecl(); +CKERROR CreatePVSetBreakSettingsProto(CKBehaviorPrototype **pproto); +int PVSetBreakSettings(const CKBehaviorContext& behcontext); +CKERROR PVSetBreakSettingsCB(const CKBehaviorContext& behcontext); + +enum bInputs +{ + bbI_XML_Link, + bbI_BreakFlags, + bbI_BSmallPressure, + bbI_BMediumPressure, + bbI_BHighPressure, + bbI_BMediumTime, + bbI_BHighTime, + bbI_BTableSmall, + bbI_BTableMedium, + bbI_BTableHigh, + +}; + +#define BB_SSTART bbI_BTableSmall + +BBParameter pInMap233[] = +{ + + BB_PIN(bbI_XML_Link,VTE_BRAKE_XML_LINK,"XML Link","Stub"), + BB_PIN(bbI_BreakFlags,VTF_BRAKE_FLAGS,"Use Break Table","Use Table"), + BB_PIN(bbI_BSmallPressure,CKPGUID_FLOAT,"Break Pressure : Small ","0.1f"), + BB_PIN(bbI_BMediumPressure,CKPGUID_FLOAT,"Break Pressure : Medium ","0.3f"), + BB_PIN(bbI_BHighPressure,CKPGUID_FLOAT,"Break Pressure : High","1.0f"), + BB_PIN(bbI_BMediumTime,CKPGUID_TIME,"Medium Apply Time","1.5"), + BB_PIN(bbI_BHighTime,CKPGUID_TIME,"High Apply Time","3.5"), + BB_SPIN(bbI_BTableSmall,VTS_BRAKE_TABLE,"Break Table : Small",""), + BB_SPIN(bbI_BTableMedium,VTS_BRAKE_TABLE,"Break Table : Medium",""), + BB_SPIN(bbI_BTableHigh,VTS_BRAKE_TABLE,"Break Table : High",""), +}; +#define gPIMAP pInMap233 + +CKObjectDeclaration *FillBehaviorPVSetBreakSettingsDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVSetBreakSettings"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Sets custom break behavior."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x719d41c2,0x46b76965)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVSetBreakSettingsProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePVSetBreakSettingsProto +// FullName: CreatePVSetBreakSettingsProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePVSetBreakSettingsProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVSetBreakSettings"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + /* PVSetBreakSettings + + PVSetBreakSettings is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Registers an object in the physic engine.
+ See PVSetBreakSettings.cmo for example. + +

Technical Information

+ + \image html PVSetBreakSettings.png + + In: triggers the process
+ + Out: is activated when the process is completed
+ +
+ + Target:The 3D Entity associated to the rigid body
+ +*/ + + + BB_EVALUATE_PINS(gPIMAP) + BB_EVALUATE_SETTINGS(gPIMAP) + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + proto->SetBehaviorCallbackFct( PVSetBreakSettingsCB ); + proto->SetFunction(PVSetBreakSettings); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PVSetBreakSettings +// FullName: PVSetBreakSettings +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PVSetBreakSettings(const CKBehaviorContext& behcontext) +{ + + using namespace vtTools::BehaviorTools; + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // objects + // + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + pFactory *pf = pFactory::Instance(); + + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbSErrorME(E_PE_REF); + + //the world reference, optional used + CK3dEntity*worldRef = NULL; + + //the world object, only used when reference has been specified + pWorld *world = NULL; + + //final object description + pObjectDescr *oDesc = new pObjectDescr(); + + pRigidBody *body = NULL; + pVehicle *v = NULL; + + XString errMesg; + + //---------------------------------------------------------------- + // + // sanity checks + // + body = GetPMan()->getBody(target); + if (!body) + bbSErrorME(E_PE_NoBody); + + v = body->getVehicle(); + if (!v) + bbSErrorME(E_PE_NoVeh); + + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // Collecting data. Stores all settings in a pObjectDescr. + // + + //get the parameter array + BB_DECLARE_PIMAP; + + v->setBreakFlags(GetInputParameterValue(beh,BB_IP_INDEX(bbI_BreakFlags))); + + //---------------------------------------------------------------- + // + // brake pressures + // + float pressureSmall = GetInputParameterValue(beh,BB_IP_INDEX(bbI_BSmallPressure)); + iAssertW( pressureSmall >=0.0f && pressureSmall <=1.0f , _FLT_ASSIGMENT(pressureSmall,0.1f) ,""); + + float pressureMedium = GetInputParameterValue(beh,BB_IP_INDEX(bbI_BMediumPressure)); + iAssertW( pressureMedium>=0.0f && pressureMedium<=1.0f , _FLT_ASSIGMENT(pressureMedium,0.3f) ,""); + + float pressureHigh = GetInputParameterValue(beh,BB_IP_INDEX(bbI_BHighPressure)); + iAssertW( pressureHigh >=0.0f && pressureHigh<=1.0f , _FLT_ASSIGMENT(pressureHigh,1.0f) ,""); + + v->setBreakPressure(BL_Small,pressureSmall); + v->setBreakPressure(BL_Medium,pressureMedium); + v->setBreakPressure(BL_High,pressureHigh); + + //---------------------------------------------------------------- + // + // brake table + // + BBSParameterM(bbI_BTableSmall,BB_SSTART); + if(sbbI_BTableSmall) + IParameter::Instance()->copyTo(v->mSmallBrakeTable,beh->GetInputParameter(BB_IP_INDEX(bbI_BTableSmall))->GetRealSource()); + + BBSParameterM(bbI_BTableMedium,BB_SSTART); + if(sbbI_BTableMedium) + IParameter::Instance()->copyTo(v->mMediumBrakeTable,beh->GetInputParameter(BB_IP_INDEX(bbI_BTableMedium))->GetRealSource()); + + BBSParameterM(bbI_BTableHigh,BB_SSTART); + if(sbbI_BTableHigh) + IParameter::Instance()->copyTo(v->mHighBrakeTable,beh->GetInputParameter(BB_IP_INDEX(bbI_BTableHigh))->GetRealSource()); + + //---------------------------------------------------------------- + // + // brake wait time + // + v->mBrakeMediumThresold = GetInputParameterValue(beh,BB_IP_INDEX(bbI_BMediumTime)); + v->mBrakeHighThresold = GetInputParameterValue(beh,BB_IP_INDEX(bbI_BHighTime)); + + //---------------------------------------------------------------- + // + // error out + // + errorFound: + { + beh->ActivateOutput(0); + return CKBR_GENERICERROR; + } + + //---------------------------------------------------------------- + // + // All ok + // + allOk: + { + beh->ActivateOutput(0); + return CKBR_OK; + } + + return 0; +} + +//************************************ +// Method: PVSetBreakSettingsCB +// FullName: PVSetBreakSettingsCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PVSetBreakSettingsCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; +} \ No newline at end of file diff --git a/usr/Src/Behaviors/pVehicle/PVSetEx.cpp b/usr/Src/Behaviors/pVehicle/PVSetEx.cpp new file mode 100644 index 0000000..745205f --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVSetEx.cpp @@ -0,0 +1,287 @@ +#include +#include "pCommon.h" +#include "pVehicleAll.h" + +CKObjectDeclaration *FillBehaviorPVSetExDecl(); +CKERROR CreatePVSetExProto(CKBehaviorPrototype **pproto); +int PVSetEx(const CKBehaviorContext& behcontext); +CKERROR PVSetExCB(const CKBehaviorContext& behcontext); + +using namespace vtTools::BehaviorTools; + + + +enum bInputs +{ + I_XML, + I_Flags, + I_PFlags, + I_SteerMax, +}; + + + +#define BB_SSTART 0 + +BBParameter pInMapx[] = +{ + + BB_SPIN(I_XML,VTE_XML_VEHICLE_SETTINGS,"Vehicle Settings","None"), + BB_SPIN(I_Flags,VTF_VFLAGS,"Vehicle Flags",""), + BB_SPIN(I_PFlags,VTF_VEHICLE_PROCESS_OPTIONS,"Vehicle Process Flags",""), + BB_SPIN(I_SteerMax,CKPGUID_ANGLE,"Maximum Steer","15"), + +}; + +#define gVSMap pInMapx +//#define BB_LOAD_PIMAP(SOURCE_MAP,SETTING_START_INDEX) BBHelper::loadPIMap(beh,pIMap,SOURCE_MAP,BB_PMAP_SIZE(SOURCE_MAP),SETTING_START_INDEX) + + +CKERROR PVSetExCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + BB_DECLARE_PMAP; + switch(behcontext.CallbackMessage) + { + + + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gVSMap,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gVSMap,BB_SSTART); + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gVSMap,BB_SSTART); + break; + } + } + return CKBR_OK; + +} +CKObjectDeclaration *FillBehaviorPVSetExDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVSetEx"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Modifies vehicle parameter."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x5b527a19,0x1e1600a9)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVSetExProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} +CKERROR CreatePVSetExProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVSetEx"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + proto->SetBehaviorCallbackFct( PVSetExCB ); + + + BB_EVALUATE_SETTINGS(gVSMap); + + //---------------------------------------------------------------- + // + // We just want create the building block pictures + // + #ifdef _DOC_ONLY_ + BB_EVALUATE_INPUTS(pInMap); + #endif // _DOC_ONLY_ + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PVSetEx); + *pproto = proto; + return CK_OK; +} + +int PVSetEx(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbSErrorME(E_PE_REF); + + + pRigidBody *body = NULL; + + + BB_DECLARE_PIMAP; + + body = GetPMan()->getBody(target); + if (!body) + bbSErrorME(E_PE_NoBody); + + + float steerMax = GetInputParameterValue(beh,BB_IP_INDEX(I_SteerMax)); + + + int flags = GetInputParameterValue(beh,BB_IP_INDEX(I_Flags)); + int pflags = GetInputParameterValue(beh,BB_IP_INDEX(I_PFlags)); + + + + + BBSParameter(I_XML); + BBSParameter(I_Flags); + BBSParameter(I_PFlags); + BBSParameter(I_SteerMax); + + + + pVehicle *v = body->getVehicle(); + if (!v) + { + pVehicleDesc vdesc; + vdesc.setToDefault(); + + if (sI_SteerMax) + { + vdesc.steeringMaxAngle = steerMax * RR_RAD_DEG_FACTOR ; + } + if (sI_PFlags) + { + vdesc.processFlags = pflags; + } + + v = pFactory::Instance()->createVehicle(target,vdesc); + + } + + if (!v) + bbErrorME("Couldn't create vehicle"); + + + if (sI_SteerMax) + v->getSteer()->setLock(steerMax * RR_RAD_DEG_FACTOR); + + + if (sI_PFlags)v->setProcessOptions(pflags); + + + + /* + if (sI_Mass) v->setMass(mass); + if (sI_Flags) v->flags = flags; + if (sI_MotorForce) v->setMotorForce(mForce); + if (sI_DiffRatio)v->setDifferentialRatio(dRatio); + if (sI_SteerMax)v->setMaxSteering(steerMax) ; + if (sI_DSDelta)v->setDigitalSteeringDelta(dsDelta); + if (sI_MaxVelocity)v->setMaxVelocity(maxVel); + if (sI_CMass)v->setCenterOfMass(cMass); + if (sI_TEff)v->setTransmissionEfficiency(tEff); + if(sI_SteeringSteerPoint)v->setSteeringSteerPoint(steeringSteerPoint); + if(sI_SteerTurnPoint)v->setSteeringTurnPoint(steeringTurnPoint ); + */ + + + + + } + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PVSetExCB +// FullName: PVSetExCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +/* + +dx -0.99999821 float +angle -0.21089047 float +zPos 0.99999857 float +dz 4.6712832 float +xPos -0.99999821 float +atan3 -0.21089047 float + + +dx 1.0000019 float +angle 0.21089132 float +zPos 1.0000004 float +dz 4.6712813 float +xPos 1.0000019 float +atan3 0.21089132 float + + + + +*/ + +/* +// int indexA = BBHelper::getIndex(beh,pMap,bbI_AxleSpeed); +// int indexB = BBHelper::getIndex(beh,pMap,bbI_Steer); + +/* +EnablePInputBySettings(beh,bbI_AxleSpeed); +EnablePInputBySettings(beh,bbI_Steer); +EnablePInputBySettings(beh,bbI_MotorTorque); +EnablePInputBySettings(beh,bbI_BrakeTorque); +EnablePInputBySettings(beh,bbI_SuspensionSpring); +EnablePInputBySettings(beh,bbI_SuspensionTravel); +EnablePInputBySettings(beh,bbI_Radius); +*/ + + + + +/* + case CKM_BEHAVIORDETACH: + { + + /* BB_DECLARE_PIMAP; + while ( pIMap->getArray().size() ) + { + + BBParameter *p=pIMap->getArray().at(0); + pIMap->getArray().erase(pIMap->getArray().begin()); + delete p; + p = NULL; + } + break; + */ + // BB_DECLARE_PIMAP; + // BBHelper::destroyPIMap(beh,pIMap,BB_PMAP_SIZE); + + + diff --git a/usr/Src/Behaviors/pVehicle/PVSetGears.cpp b/usr/Src/Behaviors/pVehicle/PVSetGears.cpp new file mode 100644 index 0000000..54d633c --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVSetGears.cpp @@ -0,0 +1,506 @@ +#include +#include "pCommon.h" + + +#include "IParameter.h" +#include "pVehicleAll.h" +#include + + +CKObjectDeclaration *FillBehaviorPVSetGearsDecl(); +CKERROR CreatePVSetGearsProto(CKBehaviorPrototype **pproto); +int PVSetGears(const CKBehaviorContext& behcontext); +CKERROR PVSetGearsCB(const CKBehaviorContext& behcontext); + +using namespace vtTools::BehaviorTools; +using namespace vtTools::ParameterTools; + + + + +enum bInputs +{ + + I_XML, + I_nbFGears, + I_Flags, + I_Ratios, + I_ShiftUpRPM, + I_ShiftDownRPM, + I_Clutch, + I_ClutchRelease, + +}; + +#define BB_SSTART 4 + + +BBParameter pInMap6[] = +{ + + BB_PIN(I_XML,VTE_XML_VGEAR_SETTINGS,"XML Link","None"), + BB_PIN(I_nbFGears,CKPGUID_INT,"Number of Forward Gears","None"), + BB_PIN(I_Flags,VTS_VGEARBOX_FLAGS,"Flags","None"), + BB_PIN(I_Ratios,VTS_VGEAR_RATIOS,"Forward Ratios/Inertias","None"), + BB_SPIN(I_ShiftUpRPM,CKPGUID_FLOAT,"Shift Up RPM",""), + BB_SPIN(I_ShiftDownRPM,CKPGUID_FLOAT,"Shift Down RPM",""), + BB_SPIN(I_Clutch,CKPGUID_TIME,"Clutch Time",""), + BB_SPIN(I_ClutchRelease,CKPGUID_TIME,"Clutch Release Time",""), + + + + + + /*BB_SPIN(I_RatioC,VTS_VGEAR_SETTINGS,"Gear Graphic Setup","None"),*/ +}; + +#define gPIMAP pInMap6 + +CKERROR PVSetGearsCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + CKContext *ctx = beh->GetCKContext(); + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) + { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDELETE: + case CKM_BEHAVIORDETACH: + { + + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + + } + return CKBR_OK; + +} + +//************************************ +// Method: FillBehaviorPVSetGearsDecl +// FullName: FillBehaviorPVSetGearsDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration*FillBehaviorPVSetGearsDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVGears"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Attachs and/or modifies a gearbox of a vehicle controller"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x5d701f33,0x17d519eb)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVSetGearsProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePVSetGearsProto +// FullName: CreatePVSetGearsProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePVSetGearsProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVGears"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + //proto->DeclareOutParameter("Result Ratio Curve",CKPGUID_2DCURVE,"FALSE"); + +// proto->DeclareOutParameter("Result Torque Curve",CKPGUID_2DCURVE,"FALSE"); +// + /* + + PVSetGears + + PVSetGears is categorized in \ref Body + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PVSetGears.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Collisions Group: Which collision group this body is part of.See pRigidBody::setCollisionsGroup(). +
+ Kinematic Object: The kinematic state. See pRigidBody::setKinematic(). +
+ Gravity: The gravity state.See pRigidBody::enableGravity(). +
+ Collision: Determines whether the body reacts to collisions.See pRigidBody::enableCollision(). +
+ Mass Offset: The new mass center in the bodies local space. +
+ Pivot Offset: The initial shape position in the bodies local space. +
+ Notify Collision: Enables collision notification.This is necessary to use collisions related building blocks. +
+ Transformation Locks: Specifies in which dimension a a transformation lock should occour. +
+ Linear Damping: The new linear damping scale. +
+ Angular Damping: The new linear damping scale. +
+ + Filter Groups: Sets the filter mask of the initial or sub shape. +
+ + + Collisions Group: Enables input for collisions group. +
+ Kinematic Object: Enables input for kinematic object. +
+ Gravity: Enables input for gravity. +
+ Collision: Enables input for collision. +
+ Mas Offset: Enables input for mass offset. +
+ Pivot Offset: Enables input for pivot offset. +
+ Notify Collision: Enables input for collision. +
+ Linear Damping: Enables input for linear damping. +
+ Angular Damping: Enables input for angular damping. +
+ Filter Groups: Enables input for filter groups. +
+ +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBSetEx.cpp + + + */ + + //proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); + /*proto->DeclareSetting("Kinematic",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Gravity",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Mass Offset",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Pivot Offset",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Notify Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Transformation Locks",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Linear Damping",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Angular Damping",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Filter Groups",CKPGUID_BOOL,"FALSE"); +*/ + proto->SetBehaviorCallbackFct( PVSetGearsCB ); + + BB_EVALUATE_PINS(gPIMAP) + BB_EVALUATE_SETTINGS(gPIMAP); + + //proto->DeclareSetting("Output Ratio Curve",CKPGUID_BOOL,"TRUE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + + proto->SetFunction(PVSetGears); + *pproto = proto; + return CK_OK; +} + + +//************************************ +// Method: PVSetGears +// FullName: PVSetGears +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ + + + +int getNewRatioTable( CKBehavior*beh,float dst[],CK2dCurve *resultCurve,int size = 6) +{ + + int result = 0 ; + + + BB_DECLARE_PIMAP;//retrieves the parameter input configuration array + ////////////////////////////////////////////////////////////////////////// + // + // We store safely some temporary data to determine the given + // user values are valid and can be send to the motor + // + CKParameterIn *inP = beh->GetInputParameter(BB_IP_INDEX(I_Ratios)); + CKParameter *pout= inP->GetDirectSource(); + if (pout) + { + + int gear = 0; + float ratio = 0.0f; + for (int i = 0 ; i < 6 ; i++) + { + CK_ID* paramids = static_cast(pout->GetReadDataPtr()); + CKParameter * sub = static_cast(GetPMan()->m_Context->GetObject(paramids[i])); + if (sub) + { + + gear = GetValueFromParameterStruct(sub,0,false); + ratio = GetValueFromParameterStruct(sub,1,false); + + if ( ratio !=0.0 ) + { + + dst[i] = ratio; + + result++; + //dst.insert(gear,ratio); + + if (resultCurve ) + { + + float dx = 1/ (size) ; + float dy = ratio / 10; + resultCurve->AddControlPoint(Vx2DVector(dx,dy) ); + beh->SetOutputParameterValue(0,&resultCurve); + + } + } + } + } + } + + return result; +} + +int PVSetGears(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbSErrorME(E_PE_REF); + + pRigidBody *body = GetPMan()->getBody(target); + if (!body) bbSErrorME(E_PE_NoBody); + + pVehicle *v = body->getVehicle(); + if (!v) bbSErrorME(E_PE_NoVeh); + + if (!v->isValidEngine()) + bbErrorME("Vehicle is not complete"); + + pGearBox *gBox = v->getGearBox(); + if (!gBox) bbErrorME("No valid gearbox"); + + + + CK2dCurve* pOCurve = NULL; //optional + CK2dCurve* pICurve = NULL; //optional + + + + BB_DECLARE_PIMAP;//retrieves the parameter input configuration array + + + BBSParameterM(I_XML,BB_SSTART);//our bb settings concated as s##I_XML + BBSParameterM(I_nbFGears,BB_SSTART); + BBSParameterM(I_Flags,BB_SSTART); + BBSParameterM(I_Ratios,BB_SSTART); + BBSParameterM(I_ShiftUpRPM,BB_SSTART); + BBSParameterM(I_ShiftDownRPM,BB_SSTART); + BBSParameterM(I_Clutch,BB_SSTART); + BBSParameterM(I_ClutchRelease,BB_SSTART); + + int xmlLink = GetInputParameterValue(beh,BB_IP_INDEX(I_XML)); + int nbGears = GetInputParameterValue(beh,BB_IP_INDEX(I_nbFGears)); + int flags = GetInputParameterValue(beh,BB_IP_INDEX(I_Flags)); + + //---------------------------------------------------------------- + // + // setup ratios / inertias + // + CKParameterIn *inP = beh->GetInputParameter(BB_IP_INDEX(I_Ratios)); + + CKParameter *pout= inP->GetDirectSource(); + if (pout) + { + IParameter::Instance()->copyTo(gBox,pout); + + v->getDriveLine()->CalcPreClutchInertia(); + v->getDriveLine()->CalcCumulativeRatios(); + v->getDriveLine()->CalcEffectiveInertiae(); + v->getDriveLine()->CalcPostClutchInertia(); + + } + + //---------------------------------------------------------------- + // + // Setup nb of gears + // + iAssertW1(X_IS_BETWEEN(nbGears,3,10),nbGears=3); + gBox->setGears(nbGears); + + //---------------------------------------------------------------- + // + // RPMs + // + if (sI_ShiftUpRPM) + gBox->setShiftUpRPM(GetInputParameterValue(beh,BB_IP_INDEX(I_ShiftUpRPM))); + + if (sI_ShiftDownRPM) + gBox->setShiftDownRPM(GetInputParameterValue(beh,BB_IP_INDEX(I_ShiftDownRPM))); + + if (sI_Clutch) + gBox->setTimeToClutch(GetInputParameterValue(beh,BB_IP_INDEX(I_Clutch))); + + if (sI_ClutchRelease) + gBox->setTimeToDeclutch(GetInputParameterValue(beh,BB_IP_INDEX(I_ClutchRelease))); + + + //float bRatio = GetInputParameterValue(beh,BB_IP_INDEX(I_BRatio));//silent update + + ////////////////////////////////////////////////////////////////////////// + //a optinal curve to display ratio between horse power and rpm + /*DWORD outputCurve; beh->GetLocalParameterValue(BB_PMAP_SIZE(gPIMAP),&outputCurve);//special settings ! + if (outputCurve) + beh->GetOutputParameterValue(0,&pOCurve); + */ + + /*if (!gears && !sI_Ratios ) + { + sI_Ratios = true; + }*/ + ////////////////////////////////////////////////////////////////////////// + // + // Checking we have to replace of the entire motor object ! + // + if (sI_Ratios) + { + ////////////////////////////////////////////////////////////////////////// + // + pLinearInterpolation nTable; + + /*nbGears = gDesc->nbForwardGears; + int ratioSize = getNewRatioTable(beh,gDesc->forwardGearRatios,NULL,nbGears); + */ + + /* + if (ratioSize ) + { + ////////////////////////////////////////////////////////////////////////// + + + if (pOCurve) + { + while (pOCurve->GetControlPointCount()) + { + pOCurve->DeleteControlPoint(pOCurve->GetControlPoint(0)); + pOCurve->Update(); + } + } + + +// gDesc->backwardGearRatio = sI_BRatio ? bRatio : gears ? gears->_minRpm: mDesc->minRpm; + + //getNewRatioTable(beh,gDesc->forwardGearRatios,pOCurve,ratioSize); + + //if (!gDesc->isValid()) bbErrorME("gear description was invalid, aborting update "); + //gDesc->nbForwardGears =ratioSize; + + //v->setGears(pFactory::Instance()->createVehicleGears(*gDesc)); + + pVehicleGears *loaded = v->getGears(); + if (!loaded) + bbErrorME("creating of new gears failed unexpected"); + + } + */ + } + + ////////////////////////////////////////////////////////////////////////// + // + // Flexibility : + // + + /* + if (sI_nbFGears && gears )gears->_nbForwardGears = nbGears; + if (sI_BRatio && gears )gears->_backwardGearRatio; + if (outputCurve && pOCurve ) + { + int s = pOCurve->GetControlPointCount(); + for (int i = 0 ; i < pOCurve->GetControlPointCount() ; i++) + { + CK2dCurvePoint* point = pOCurve->GetControlPoint(i); + point->SetLinear(true); + } + pOCurve->Update(); + beh->SetOutputParameterValue(0,&pOCurve); + } + delete gDesc; + gDesc; + */ + } + beh->ActivateOutput(0); + return 0; +} + diff --git a/usr/Src/Behaviors/pVehicle/PVSetMotor.cpp b/usr/Src/Behaviors/pVehicle/PVSetMotor.cpp new file mode 100644 index 0000000..b3d7d29 --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVSetMotor.cpp @@ -0,0 +1,553 @@ +#include + +#include "pCommon.h" + +#include "IParameter.h" +#include "pVehicleAll.h" +#include + +CKObjectDeclaration *FillBehaviorPVSetMotorValuesDecl(); +CKERROR CreatePVSetMotorValuesProto(CKBehaviorPrototype **pproto); +int PVSetMotorValues(const CKBehaviorContext& behcontext); +CKERROR PVSetMotorValuesCB(const CKBehaviorContext& behcontext); + +using namespace vtTools::BehaviorTools; +using namespace vtTools::ParameterTools; + + + +enum bInputs +{ + + I_XML, + I_Flags, + I_Clutch, + + I_maxRPM, + I_minRPM, + I_maxTorque, + + I_intertia, + I_engineFriction, + I_breakCoeff, + I_GroundForceFeedBackScale, + + I_tList, +}; + + + +#define BB_SSTART 0 + +BBParameter pInMap5[] = +{ + + + BB_SPIN(I_XML,VTE_XML_VMOTOR_SETTINGS,"XML Link","None"), + BB_SPIN(I_Flags,VTF_VEHICLE_ENGINE_FLAGS,"Flags","None"), + BB_SPIN(I_Clutch,CKPGUID_FLOAT,"Clutch","None"), + + BB_SPIN(I_maxRPM,CKPGUID_FLOAT,"Maximum RPM","None"), + BB_SPIN(I_minRPM,CKPGUID_FLOAT,"Minimum RPM","None"), + BB_SPIN(I_maxTorque,CKPGUID_FLOAT,"Maximum Torque","None"), + + BB_SPIN(I_intertia,CKPGUID_FLOAT,"Inertia","None"), + BB_SPIN(I_engineFriction,CKPGUID_FLOAT,"Friction","1.0f"), + BB_SPIN(I_breakCoeff,CKPGUID_FLOAT,"Break Factor","0.0f"), + BB_SPIN(I_GroundForceFeedBackScale,CKPGUID_FLOAT,"Ground Force Scale","0.0f"), + + BB_SPIN(I_tList,VTS_VMOTOR_TVALUES,"Torque per RPM","None"), + +}; + +#define gPIMAP pInMap5 + +CKERROR PVSetMotorValuesCB(const CKBehaviorContext& behcontext) +{ + + CKBehavior *beh = behcontext.Behavior; + + BB_DECLARE_PMAP; + switch(behcontext.CallbackMessage) + { + + + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; + +} + +//************************************ +// Method: FillBehaviorPVSetMotorValuesDecl +// FullName: FillBehaviorPVSetMotorValuesDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration*FillBehaviorPVSetMotorValuesDecl() +{ + + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVMotor"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Modifies motor parameters of a vehicle controller"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7b044c81,0xde9489a)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVSetMotorValuesProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePVSetMotorValuesProto +// FullName: CreatePVSetMotorValuesProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePVSetMotorValuesProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVMotor"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + + //BB_EVALUATE_PINS(gPIMAP) + BB_EVALUATE_SETTINGS(gPIMAP); + + + /*! PVMotor + + PVSetMotorValues is categorized in \ref Vehicle + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PVMotor.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Collisions Group: Which collision group this body is part of.See pRigidBody::setCollisionsGroup(). +
+ Kinematic Object: The kinematic state. See pRigidBody::setKinematic(). +
+ Gravity: The gravity state.See pRigidBody::enableGravity(). +
+ Collision: Determines whether the body reacts to collisions.See pRigidBody::enableCollision(). +
+ Mass Offset: The new mass center in the bodies local space. +
+ Pivot Offset: The initial shape position in the bodies local space. +
+ Notify Collision: Enables collision notification.This is necessary to use collisions related building blocks. +
+ Transformation Locks: Specifies in which dimension a a transformation lock should occour. +
+ Linear Damping: The new linear damping scale. +
+ Angular Damping: The new linear damping scale. +
+ + Filter Groups: Sets the filter mask of the initial or sub shape. +
+ + + Collisions Group: Enables input for collisions group. +
+ Kinematic Object: Enables input for kinematic object. +
+ Gravity: Enables input for gravity. +
+ Collision: Enables input for collision. +
+ Mas Offset: Enables input for mass offset. +
+ Pivot Offset: Enables input for pivot offset. +
+ Notify Collision: Enables input for collision. +
+ Linear Damping: Enables input for linear damping. +
+ Angular Damping: Enables input for angular damping. +
+ Filter Groups: Enables input for filter groups. +
+ +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBSetEx.cpp + + */ + + //proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); + + proto->SetBehaviorCallbackFct( PVSetMotorValuesCB ); + + + + //proto->DeclareSetting("Output Curve",CKPGUID_BOOL,"TRUE"); + //proto->DeclareSetting("Automatic Gears",CKPGUID_BOOL,"TRUE"); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PVSetMotorValues); + *pproto = proto; + return CK_OK; +} + + +int PVSetMotorValues(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + CKContext* ctx = behcontext.Context; + + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbSErrorME(E_PE_REF); + + pRigidBody *body = GetPMan()->getBody(target); + if (!body) bbSErrorME(E_PE_NoBody); + + pVehicle *v = body->getVehicle(); + if (!v) bbSErrorME(E_PE_NoVeh); + + if (!v->isValidEngine()) + bbErrorME("Vehicle is not complete"); + + pEngine *engine = v->getEngine(); + if (!engine) bbErrorME("No valid engine"); + + + CK2dCurve* pOCurve = NULL; //optional + + BB_DECLARE_PIMAP;//retrieves the parameter input configuration array + BBSParameter(I_XML);//our bb settings concated as s##I_XML + BBSParameter(I_Flags); + BBSParameter(I_Clutch); + BBSParameter(I_tList); + BBSParameter(I_maxRPM); + BBSParameter(I_minRPM); + BBSParameter(I_maxTorque); + BBSParameter(I_intertia); + BBSParameter(I_engineFriction); + BBSParameter(I_breakCoeff); + BBSParameter(I_GroundForceFeedBackScale); + + if (sI_XML){ + int xmlLink = GetInputParameterValue(beh,BB_IP_INDEX(I_XML)); + } + + if (sI_GroundForceFeedBackScale) + engine->setForceFeedbackScale(GetInputParameterValue(beh,BB_IP_INDEX(I_GroundForceFeedBackScale))); + + if (sI_Flags) + engine->setFlags(GetInputParameterValue(beh,BB_IP_INDEX(I_Flags))); + if (sI_Clutch) + engine->setClutch(GetInputParameterValue(beh,BB_IP_INDEX(I_Clutch))); + + if (sI_maxTorque) + engine->setMaxTorque(GetInputParameterValue(beh,BB_IP_INDEX(I_maxTorque))); + + if (sI_maxTorque) + engine->setMaxTorque(GetInputParameterValue(beh,BB_IP_INDEX(I_maxTorque))); + if (sI_maxRPM) + engine->setMaxRPM(GetInputParameterValue(beh,BB_IP_INDEX(I_maxRPM))); + if (sI_minRPM) + engine->setIdleRPM(GetInputParameterValue(beh,BB_IP_INDEX(I_minRPM))); + if (sI_engineFriction) + engine->setFriction(GetInputParameterValue(beh,BB_IP_INDEX(I_engineFriction))); + if (sI_intertia) + engine->SetInertia(GetInputParameterValue(beh,BB_IP_INDEX(I_intertia))); + + if (sI_breakCoeff) + engine->setBrakingCoeff(GetInputParameterValue(beh,BB_IP_INDEX(I_breakCoeff))); + + + if (sI_tList){ + + CKParameterIn *inP = beh->GetInputParameter(BB_IP_INDEX(I_tList)); + CKParameter *pout= inP->GetDirectSource(); + if (pout) + { + + if (engine->getTorqueCurve()) + { + pLinearInterpolation &curve = *engine->getTorqueCurve(); + + curve.clear(); + IParameter::Instance()->copyTo(curve,pout); + engine->preStep(); + + } + + } + //engine->setTorqueCurve(); + } + + + + ////////////////////////////////////////////////////////////////////////// + //a optinal curve to display ratio between horse power and rpm + +/* DWORD outputCurve; beh->GetLocalParameterValue(BB_PMAP_SIZE(gPIMAP),&outputCurve);//special settings ! + if (outputCurve) + beh->GetOutputParameterValue(0,&pOCurve); + +*/ + + + + ////////////////////////////////////////////////////////////////////////// + // + // Checking we have to replace of the entire motor object ! + // + if (sI_tList) + { + float maxInputRPM =0.0f; + float maxInputNM =0.0f; + + ////////////////////////////////////////////////////////////////////////// + // + // this is only a test run ! + pLinearInterpolation nTable; + //getNewTorqueTable(beh,nTable,maxInputRPM,maxInputNM,NULL); + + if (nTable.getSize() ) + { + + /* + if (pOCurve) + { + while (pOCurve->GetControlPointCount()) + { + pOCurve->DeleteControlPoint(pOCurve->GetControlPoint(0)); + pOCurve->Update(); + } + } + + */ + ////////////////////////////////////////////////////////////////////////// + // we just copy into the motor we can get ! + + + ////////////////////////////////////////////////////////////////////////// + // we make a new torque ratios + + //getNewTorqueTable(beh,mDesc->torqueCurve,maxInputRPM,maxInputNM,pOCurve); + + /* + if (!mDesc->isValid()) bbErrorME("motor description was invalid, aborting update "); + + if (!motor) + { + motor = pFactory::Instance()->createVehicleMotor(*mDesc); + v->setMotor(motor); + }else + { + if (mDesc->torqueCurve.getSize()) + { + motor->loadNewTorqueCurve(mDesc->torqueCurve); + } + }*/ + } + } + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Flexibility : + // + + /* + if (sI_minRDown && motor )motor->setMinRpmToGearDown(mDDown); + if (sI_maxRUp && motor )motor->setMaxRpmToGearUp(mDUp); + if (sI_maxR && motor )motor->setMaxRpm(maxR); + if (sI_minR && motor )motor->setMinRpm(minR); + + */ + if ( pOCurve ) + { + /* + #ifdef _DEBUG + XString error; + error << "t curve created with " << pOCurve->GetControlPointCount() << " with l : " << pOCurve->GetLength(); + bbErrorME(error.CStr()); + #endif + */ + + + /* + for (int i = 0 ; i < pOCurve->GetControlPointCount() ; i++) + { + CK2dCurvePoint* point = pOCurve->GetControlPoint(i); + point->SetLinear(true); + } + pOCurve->Update(); + beh->SetOutputParameterValue(0,&pOCurve); + */ + + } + //delete mDesc; + //mDesc = NULL; + } + + beh->ActivateOutput(0); + return 0; +} + +//somebody wants to enter new torque values : +//if (outputCurve && sI_tList ) +// beh->GetOutputParameterValue(0,&pOCurve); + +/* +if (sI_tList) +{ + +float maxInputRPM =0.0f; float maxInputNM =0.0f; + +pLinearInterpolation torqueCurve; +CKParameterIn *inP = beh->GetInputParameter(BB_IP_INDEX(I_tList)); CKParameter *pout= inP->GetDirectSource(); + +if (pout) +{ +float rpm = 0.0f; float nm = 0.0f; + +bool maximaFound = false; bool dataCollected = false; + + +evaluate: +for (int i = 0 ; i < 6 ; i++) +{ +CK_ID* paramids = static_cast(pout->GetReadDataPtr()); +CKParameter * sub = static_cast(GetPMan()->m_Context->GetObject(paramids[i])); +if (sub) +{ + +rpm = GetValueFromParameterStruct(sub,0,false); +nm = GetValueFromParameterStruct(sub,1,false); + + +if ( rpm >0.0f && nm > 0.0f ) +{ + +if (rpm > maxInputRPM) maxInputRPM = rpm; +if (nm > maxInputNM) maxInputNM = nm; + + +if (maximaFound || !outputCurve ) +{ +torqueCurve.insert(rpm,nm); +dataCollected =true; +} + + +if (maximaFound && outputCurve ) +{ +pOCurve->AddControlPoint(Vx2DVector(rpm/maxInputRPM , nm/maxInputNM) ); +dataCollected =true; +} +} +} +} + + + + +if (dataCollected) { goto end; } + +if ( maxInputRPM >0.0f && maxInputNM> 0.0f ) +{ +maximaFound = true; +goto evaluate; +} + +end : + +if (dataCollected ) +{ + +if (outputCurve) +beh->SetOutputParameterValue(0,&pOCurve); + + + +////////////////////////////////////////////////////////////////////////// +if (!motor) +{ + +mDesc = new pVehicleMotorDesc(); +mDesc->setToDefault(); + +mDesc->maxRpmToGearUp = sI_maxRUp ? mDUp : mDesc->maxRpmToGearUp; +mDesc->minRpmToGearDown = sI_minRDown = mDDown : mDesc->minRpmToGearDown ; +mDesc->torqueCurve = torqueCurve; +motor = pFactory::Instance()->createVehicleMotor(*mDesc); +v->setMotor(motor); +} + +} +} +} + +*/ \ No newline at end of file diff --git a/usr/Src/Behaviors/pVehicle/PVStates.cpp b/usr/Src/Behaviors/pVehicle/PVStates.cpp new file mode 100644 index 0000000..c7466cb --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVStates.cpp @@ -0,0 +1,247 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPVGetDecl(); +CKERROR CreatePVGetProto(CKBehaviorPrototype **pproto); +int PVGet(const CKBehaviorContext& behcontext); +CKERROR PVGetCB(const CKBehaviorContext& behcontext); + +using namespace vtTools; +using namespace BehaviorTools; + + + +enum bbI_Inputs +{ + bbI_BodyReference, + +}; + +#define BB_SSTART 0 + +enum bbOutputs +{ + O_StateFlags, + O_Acceleration, + O_Steering, + O_MTorque, + O_MPH, + O_RPM, + O_MRPM, + O_WRPM, + O_Gear, +}; + +BBParameter pOutMapv[] = +{ + BB_SPOUT(O_StateFlags,VTF_VSTATE_FLAGS,"State Flags","0.0"), + BB_SPOUT(O_Acceleration,CKPGUID_FLOAT,"Acceleration","0.0"), + BB_SPOUT(O_Steering,CKPGUID_ANGLE,"Steering","0.0"), + BB_SPOUT(O_MTorque,CKPGUID_FLOAT,"Motor Torque","0.0"), + BB_SPOUT(O_MPH,CKPGUID_FLOAT,"MPH","0.0"), + BB_SPOUT(O_RPM,CKPGUID_FLOAT,"RPM","0.0"), + BB_SPOUT(O_MRPM,CKPGUID_FLOAT,"M - RPM","0.0"), + BB_SPOUT(O_WRPM,CKPGUID_FLOAT,"Wheel RPM","0.0"), + BB_SPOUT(O_Gear,CKPGUID_INT,"Gear","0.0"), +}; + +#define gOPMap pOutMapv + + +CKERROR PVGetCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + int cb = behcontext.CallbackMessage; + BB_DECLARE_PMAP; + + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_POMAP(gOPMap,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PMAP(gOPMap,BB_SSTART); + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PMAP(gOPMap,BB_SSTART); + break; + } + } + return CKBR_OK; +} + +CKObjectDeclaration *FillBehaviorPVGetDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVGet"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Retrieves vehicle related parameters."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x70b293c,0x1ef4fa7)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVGetProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePVGetProto +// FullName: CreatePVGetProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePVGetProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVGet"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->SetBehaviorCallbackFct( PVGetCB ); + + + BB_EVALUATE_SETTINGS(gOPMap); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PVGet); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PVGet +// FullName: PVGet +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PVGet(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + + pRigidBody *body = NULL; + + body = GetPMan()->getBody(target); + if (!body) + bbSErrorME(E_PE_NoBody); + + + pVehicle *v = body->getVehicle(); + if (!v) + { + bbSErrorME(E_PE_NoVeh); + } + + BB_DECLARE_PMAP; + + + /************************************************************************/ + /* retrieve settings state */ + /***** + *******************************************************************/ + + BBSParameter(O_StateFlags); + BBSParameter(O_Acceleration); + BBSParameter(O_Steering); + BBSParameter(O_MTorque); + BBSParameter(O_MPH); + BBSParameter(O_RPM); + BBSParameter(O_MRPM); + BBSParameter(O_WRPM); + BBSParameter(O_Gear); + /************************************************************************/ + /* */ + /************************************************************************/ + + BB_O_SET_VALUE_IF(int,O_StateFlags,v->getStateFlags()); + BB_O_SET_VALUE_IF(float,O_Acceleration,v->_cAcceleration); + BB_O_SET_VALUE_IF(float,O_Steering,v->_cSteering); + BB_O_SET_VALUE_IF(float,O_MPH,v->getMPH()); + + float wRPM = v->_computeRpmFromWheels(); + BB_O_SET_VALUE_IF(float,O_WRPM,wRPM); + + //---------------------------------------------------------------- + // + // output new engine values + // + if (v->isValidEngine()) + { + BB_O_SET_VALUE_IF(float,O_MTorque,v->getEngine()->GetEngineTorque()); + BB_O_SET_VALUE_IF(float,O_RPM,v->getRPM()); + BB_O_SET_VALUE_IF(int,O_Gear,v->getGear()); + } + + + + /* + if (v->getMotor()) + { + BB_O_SET_VALUE_IF(float,O_MTorque,v->getMotor()->getTorque()); + float mRPM = v->_computeMotorRpm(wRPM); + BB_O_SET_VALUE_IF(float,O_MRPM,mRPM); + BB_O_SET_VALUE_IF(float,O_RPM,v->getMotor()->getRpm()); + } + + if (v->getGears()) + { + + BB_O_SET_VALUE_IF(int,O_Gear,v->getGears()->getGear()); + } + */ + } + + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PVGetCB +// FullName: PVGetCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ + + diff --git a/usr/Src/Behaviors/pVehicle/PVWGet.cpp b/usr/Src/Behaviors/pVehicle/PVWGet.cpp new file mode 100644 index 0000000..62c631d --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVWGet.cpp @@ -0,0 +1,391 @@ +#include +#include "pCommon.h" + + +CKObjectDeclaration *FillBehaviorPVWGetDecl(); +CKERROR CreatePVWGetProto(CKBehaviorPrototype **pproto); +int PVWGet(const CKBehaviorContext& behcontext); +CKERROR PVWGetCB(const CKBehaviorContext& behcontext); + +using namespace vtTools; +using namespace BehaviorTools; + + + +enum bbI_Inputs +{ + bbI_BodyReference, + +}; + +#define BB_SSTART 0 + +enum bbOutputs +{ + O_AxleSpeed, + O_WheelRollAngle, + O_RPM, + O_SteerAngle, + O_MotorTorque, + O_BreakTorque, + O_Suspension, + O_SuspensionTravel, + O_Radius, + O_WFlags, + O_WSFlags, + O_LatFunc, + O_LongFunc, + O_Contact, + +}; + +BBParameter pOutMap[] = +{ + BB_SPOUT(O_AxleSpeed,CKPGUID_FLOAT,"Axle Speed","0.0"), + BB_SPOUT(O_WheelRollAngle,CKPGUID_FLOAT,"Roll Angle","0.0"), + BB_SPOUT(O_RPM,CKPGUID_FLOAT,"RPM","0.0"), + BB_SPOUT(O_SteerAngle,CKPGUID_ANGLE,"Steer Angle","0.0"), + BB_SPOUT(O_MotorTorque,CKPGUID_FLOAT,"Motor Torque","0.0"), + BB_SPOUT(O_BreakTorque,CKPGUID_FLOAT,"Break Torque","0.0"), + BB_SPOUT(O_Suspension,VTS_JOINT_SPRING,"Suspension Spring","0.0"), + BB_SPOUT(O_SuspensionTravel,CKPGUID_FLOAT,"Suspension Spring","0.0"), + BB_SPOUT(O_Radius,CKPGUID_FLOAT,"Radius","0.0"), + BB_SPOUT(O_WFlags,VTS_PHYSIC_WHEEL_FLAGS,"Wheel Flags","0.0"), + BB_SPOUT(O_WSFlags,VTF_VWSHAPE_FLAGS,"Wheel Shape Flags","0.0"), + BB_SPOUT(O_LatFunc,VTF_VWTIRE_SETTINGS,"Lateral Force Settings","0.0"), + BB_SPOUT(O_LongFunc,VTF_VWTIRE_SETTINGS,"Longitudinal Force Settings","0.0"), + BB_SPOUT(O_Contact,VTS_WHEEL_CONTACT,"Contact Data","0.0"), + //BB_SPOUT(O_LongFunc,VTF_VWTIRE_SETTINGS,"Longitudinal Force Settings","0.0"), +}; + +#define gOPMap pOutMap + + +CKERROR PVWGetCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + int cb = behcontext.CallbackMessage; + BB_DECLARE_PMAP; + + + switch(behcontext.CallbackMessage) { + + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_POMAP(gOPMap,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PMAP(gOPMap,BB_SSTART); + break; + + } + + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PMAP(gOPMap,BB_SSTART); + break; + } + } + return CKBR_OK; +} + +CKObjectDeclaration *FillBehaviorPVWGetDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVWGet"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Retrieves wheel related parameters."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x24b704e4,0x65ed5fad)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVWGetProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePVWGetProto +// FullName: CreatePVWGetProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePVWGetProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVWGet"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + /*! \page PVWGet + + PVWGet is categorized in \ref Vehicle + +

Description

+ Apply to a 3DEntity
+ Retrieves various physical informations.
+ +

Technical Information

+ + \image html PVWGet.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ Collisions Group: Which collision group this body is part of.See pRigidBody::getCollisionsGroup(). +
+ Kinematic Object: The kinematic state. See pRigidBody::isKinematic(). +
+ Gravity: The gravity state.See pRigidBody::isAffectedByGravity(). +
+ Collision: Determines whether the body reacts to collisions.See pRigidBody::isCollisionEnabled(). +
+
+ Collisions Group: Enables output for collisions group. +
+ Kinematic Object: Enables output for kinematic object. +
+ Gravity: Enables output for gravity. +
+ Collision: Enables output for collision. +
+
+
+ +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBGetEx.cpp + + */ + + + //proto->DeclareInParameter("World Reference",CKPGUID_3DENTITY,"pDefaultWorld"); + //proto->DeclareInParameter("Body Reference",CKPGUID_3DENTITY,"Body"); + + + /*proto->DeclareSetting("Collisions Group",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Kinematic",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Gravity",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Mass Offset",CKPGUID_BOOL,"FALSE"); + proto->DeclareSetting("Pivot Offset",CKPGUID_BOOL,"FALSE"); + + + + proto->DeclareOutParameter("Collisions Group",CKPGUID_INT,"0"); + proto->DeclareOutParameter("Kinematic Object",CKPGUID_BOOL,"FALSE"); + proto->DeclareOutParameter("Gravity",CKPGUID_BOOL,"FALSE"); + proto->DeclareOutParameter("Collision",CKPGUID_BOOL,"FALSE"); + proto->DeclareOutParameter("Mass Offset",CKPGUID_VECTOR,"0.0f"); + proto->DeclareOutParameter("Pivot Offset",CKPGUID_VECTOR,"0.0f"); + + */ + + proto->SetBehaviorCallbackFct( PVWGetCB ); + + + BB_EVALUATE_SETTINGS(gOPMap); + + //---------------------------------------------------------------- + // + // We just want create the building block pictures + // + #ifdef _DOC_ONLY_ + BB_EVALUATE_OUTPUTS(gOPMap); + #endif // _DOC_ONLY_ + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PVWGet); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PVWGet +// FullName: PVWGet +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PVWGet(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + pRigidBody *body = NULL; + + + body = GetPMan()->getBody(target); + if (!body) bbErrorME("No Reference Object specified"); + + + + pWheel *wheel = body->getWheel(target); + if (!wheel)bbErrorME("pWheel object doesnt exist!"); + + pWheel2 *wheel2 = wheel->castWheel2(); + + //if (!wheel2)bbErrorME("Couldnt cast a pWheel2 object"); + + BB_DECLARE_PMAP; + + + /************************************************************************/ + /* retrieve settings state */ + /***** + *******************************************************************/ + + BBSParameter(O_AxleSpeed); + BBSParameter(O_WheelRollAngle); + BBSParameter(O_RPM); + BBSParameter(O_SteerAngle); + BBSParameter(O_MotorTorque); + BBSParameter(O_BreakTorque); + BBSParameter(O_Suspension); + BBSParameter(O_SuspensionTravel); + BBSParameter(O_Radius); + BBSParameter(O_WFlags); + BBSParameter(O_WSFlags); + BBSParameter(O_LatFunc); + BBSParameter(O_LongFunc); + BBSParameter(O_Contact); + + BB_O_SET_VALUE_IF(float,O_AxleSpeed,wheel2->getAxleSpeed()); + BB_O_SET_VALUE_IF(float,O_WheelRollAngle,wheel->getWheelRollAngle()); + BB_O_SET_VALUE_IF(float,O_RPM,wheel2->getRpm()); + + if (wheel2) + { + BB_O_SET_VALUE_IF(float,O_SteerAngle,wheel2->GetHeading()); + } + + /* + BB_O_SET_VALUE_IF(float,O_SteerAngle,wheel2->rotationV.x);*/ + BB_O_SET_VALUE_IF(float,O_MotorTorque,wheel2->getWheelShape()->getMotorTorque()); + BB_O_SET_VALUE_IF(float,O_BreakTorque,wheel2->getWheelShape()->getBrakeTorque()); + BB_O_SET_VALUE_IF(float,O_SuspensionTravel,wheel2->getWheelShape()->getSuspensionTravel()); + BB_O_SET_VALUE_IF(float,O_Radius,wheel2->getWheelShape()->getRadius()); + + BB_O_SET_VALUE_IF(int,O_WFlags,wheel->mWheelFlags); + BB_O_SET_VALUE_IF(int,O_WSFlags,wheel2->getWheelShape()->getWheelFlags()); + + + + if (wheel2){ + + if (sO_LatFunc) + { + NxTireFunctionDesc tf = wheel2->getWheelShape()->getLateralTireForceFunction(); + CKParameterOut *pout = beh->GetOutputParameter(BB_OP_INDEX(O_LatFunc)); + if (pout) + { + vtTools::ParameterTools::SetParameterStructureValue(pout,1,tf.extremumSlip); + vtTools::ParameterTools::SetParameterStructureValue(pout,2,tf.extremumValue); + vtTools::ParameterTools::SetParameterStructureValue(pout,3,tf.asymptoteSlip); + vtTools::ParameterTools::SetParameterStructureValue(pout,4,tf.asymptoteValue); + vtTools::ParameterTools::SetParameterStructureValue(pout,5,tf.stiffnessFactor); + } + } + if (sO_LongFunc) + { + NxTireFunctionDesc tf = wheel2->getWheelShape()->getLongitudalTireForceFunction(); + CKParameterOut *pout = beh->GetOutputParameter(BB_OP_INDEX(O_LongFunc)); + if (pout) + { + vtTools::ParameterTools::SetParameterStructureValue(pout,1,tf.extremumSlip); + vtTools::ParameterTools::SetParameterStructureValue(pout,2,tf.extremumValue); + vtTools::ParameterTools::SetParameterStructureValue(pout,3,tf.asymptoteSlip); + vtTools::ParameterTools::SetParameterStructureValue(pout,4,tf.asymptoteValue); + vtTools::ParameterTools::SetParameterStructureValue(pout,5,tf.stiffnessFactor); + } + } + + } + + if (wheel2) + { + if (sO_Suspension) + { + NxSpringDesc s = wheel2->getWheelShape()->getSuspension(); + CKParameterOut *pout = beh->GetOutputParameter(BB_OP_INDEX(O_Suspension)); + if (pout) + { + vtTools::ParameterTools::SetParameterStructureValue(pout,0,s.damper); + vtTools::ParameterTools::SetParameterStructureValue(pout,1,s.spring); + vtTools::ParameterTools::SetParameterStructureValue(pout,2,s.targetValue); + } + } + + if (sO_Contact) + { + + pWheelContactData cData = *wheel2->getContact(); + CKParameterOut *pout = beh->GetOutputParameter(BB_OP_INDEX(O_Contact)); + if (pout) + { + pFactory::Instance()->copyTo(pout,cData); + } + + } + } + } + + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PVWGetCB +// FullName: PVWGetCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ diff --git a/usr/Src/Behaviors/pVehicle/PVWSet.cpp b/usr/Src/Behaviors/pVehicle/PVWSet.cpp new file mode 100644 index 0000000..fb4a59c --- /dev/null +++ b/usr/Src/Behaviors/pVehicle/PVWSet.cpp @@ -0,0 +1,393 @@ +#include +#include "pCommon.h" + + + + +CKObjectDeclaration *FillBehaviorPVWSetDecl(); +CKERROR CreatePVWSetProto(CKBehaviorPrototype **pproto); +int PVWSet(const CKBehaviorContext& behcontext); +CKERROR PVWSetCB(const CKBehaviorContext& behcontext); + + +enum bInputs +{ + bbI_XML, + bbI_AxleSpeed, + bbI_Steer, + bbI_MotorTorque, + bbI_BrakeTorque, + bbI_SuspensionSpring, + bbI_SuspensionTravel, + bbI_Radius, + bbI_WFlags, + bbI_WSFlags, + bbI_LatFunc, + bbI_LongFunc, +}; + + +#define BB_SSTART 0 + +BBParameter pInMap2[] = +{ + + BB_SPIN(bbI_XML,VTE_XML_VEHICLE_SETTINGS,"XML Link","None"), + BB_SPIN(bbI_AxleSpeed,CKPGUID_FLOAT,"Axle Speed","2000.0"), + BB_SPIN(bbI_Steer,CKPGUID_ANGLE,"Steer Angle","1.0"), + BB_SPIN(bbI_MotorTorque,CKPGUID_FLOAT,"Motor Torque","0.0"), + BB_SPIN(bbI_BrakeTorque,CKPGUID_FLOAT,"Break Torque","0.0"), + BB_SPIN(bbI_SuspensionSpring,VTS_JOINT_SPRING,"Suspension Spring",""), + BB_SPIN(bbI_SuspensionTravel,CKPGUID_FLOAT,"Suspension Travel","0.0"), + BB_SPIN(bbI_Radius,CKPGUID_FLOAT,"Radius","1.0"), + BB_SPIN(bbI_WFlags,VTS_PHYSIC_WHEEL_FLAGS,"Wheel Flags",""), + BB_SPIN(bbI_WSFlags,VTF_VWSHAPE_FLAGS,"Wheel ShapeFlags",""), + BB_SPIN(bbI_LatFunc,VTF_VWTIRE_SETTINGS,"Latitude Force Settings",""), + BB_SPIN(bbI_LongFunc,VTF_VWTIRE_SETTINGS,"Longitudinal Force Settings","0.0"), + +}; + +#define gPIMAP pInMap2 + +//************************************ +// Method: FillBehaviorPVWSetDecl +// FullName: FillBehaviorPVWSetDecl +// Access: public +// Returns: CKObjectDeclaration * +// Qualifier: +//************************************ +CKObjectDeclaration *FillBehaviorPVWSetDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("PVWSet"); + od->SetCategory("Physic/Vehicle"); + od->SetDescription("Sets physical quantities."); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7805147,0x322e17e7)); + od->SetAuthorGuid(VTCX_AUTHOR_GUID); + od->SetAuthorName(VTCX_AUTHOR); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreatePVWSetProto); + od->SetCompatibleClassId(CKCID_3DENTITY); + od->NeedManager(GUID_MODULE_MANAGER); + + return od; +} + +//************************************ +// Method: CreatePVWSetProto +// FullName: CreatePVWSetProto +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: CKBehaviorPrototype **pproto +//************************************ +CKERROR CreatePVWSetProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("PVWSet"); + if(!proto) return CKERR_OUTOFMEMORY; + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + + /*! \page PVWSet + + PVWSet is categorized in \ref Vehicle + +

Description

+ Apply to a 3DEntity
+ Modifies various physical parameters.
+ +

Technical Information

+ + \image html PVWSet.png + + In: triggers the process +
+ Out: is activated when the process is completed. +
+
+ Target: The 3D Entity associated to the rigid body. +
+
+ + +
+

Warning

+ The body must be dynamic. +
+
+

Note

+ Is utilizing #pRigidBody #pWorld #PhysicManager.
+ +

VSL


+ + \include PBSetEx.cpp + + */ + + + proto->SetBehaviorCallbackFct( PVWSetCB ); + + BB_EVALUATE_SETTINGS(pInMap2); + + //---------------------------------------------------------------- + // + // We just want create the building block pictures + // + #ifdef _DOC_ONLY_ + BB_EVALUATE_INPUTS(pInMap2); + #endif // _DOC_ONLY_ + + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE); + + proto->SetFunction(PVWSet); + *pproto = proto; + return CK_OK; +} + +//************************************ +// Method: PVWSet +// FullName: PVWSet +// Access: public +// Returns: int +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +int PVWSet(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + PhysicManager *pm = GetPMan(); + + pFactory *pf = pFactory::Instance(); + + using namespace vtTools::BehaviorTools; + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0,FALSE); + + + + ////////////////////////////////////////////////////////////////////////// + //the object : + CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); + if( !target ) bbErrorME("No Reference Object specified"); + + pRigidBody *body = NULL; + + + body = GetPMan()->getBody(target); + if (!body) bbErrorME("No Reference Object specified"); + + + pWheel *wheel = body->getWheel(target); + if (!wheel)bbErrorME("pWheel object doesnt exist!"); + + pWheel2 *wheel2 = wheel->castWheel2(); + if (!wheel2)bbErrorME("Couldnt cast a pWheel2 object"); + + + + BB_DECLARE_PIMAP; + + + /************************************************************************/ + /* engel + kuehne un partner + */ + /************************************************************************/ + + /************************************************************************/ + /* retrieve settings state */ + /************************************************************************/ + BBSParameter(bbI_XML); + BBSParameter(bbI_AxleSpeed); + BBSParameter(bbI_Steer); + BBSParameter(bbI_MotorTorque); + BBSParameter(bbI_BrakeTorque); + BBSParameter(bbI_SuspensionSpring); + BBSParameter(bbI_SuspensionTravel); + BBSParameter(bbI_Radius); + + BBSParameter(bbI_WFlags); + BBSParameter(bbI_WSFlags); + + BBSParameter(bbI_LatFunc); + BBSParameter(bbI_LongFunc); + + + /************************************************************************/ + /* retrieve values */ + /************************************************************************/ + + int xmlValue = GetInputParameterValue(beh,BB_IP_INDEX(bbI_XML)); + float axleVel = GetInputParameterValue(beh,BB_IP_INDEX(bbI_AxleSpeed)); + float steer = GetInputParameterValue(beh,BB_IP_INDEX(bbI_Steer)); + float mTorque = GetInputParameterValue(beh,BB_IP_INDEX(bbI_MotorTorque)); + float bTorque = GetInputParameterValue(beh,BB_IP_INDEX(bbI_BrakeTorque)); + float suspensionTravel = GetInputParameterValue(beh,BB_IP_INDEX(bbI_SuspensionTravel)); + + int wFlags = GetInputParameterValue(beh,BB_IP_INDEX(bbI_WFlags)); + int wSFlags = GetInputParameterValue(beh,BB_IP_INDEX(bbI_WSFlags)); + + pSpring sSpring; + if (sbbI_SuspensionSpring) + { + CKParameterIn *par = beh->GetInputParameter(bbI_SuspensionSpring); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + sSpring = pFactory::Instance()->createSpringFromParameter(rPar); + NxSpringDesc xsp; + xsp.damper = sSpring.damper; + xsp.spring = sSpring.spring; + xsp.targetValue = sSpring.targetValue; + if (xsp.isValid()) + { + wheel2->setSuspensionSpring(sSpring); + }else + bbErrorME("Invalid Spring Setings!"); + + } + } + } + + /************************************************************************/ + /* Update Object ! */ + /************************************************************************/ + + ////////////////////////////////////////////////////////////////////////// + // load some settings from XML + if(sbbI_XML) + { + } + + if (sbbI_Steer)wheel2->setAngle(steer); + if (sbbI_AxleSpeed)wheel2->setAxleSpeed(axleVel); + if (sbbI_MotorTorque)wheel2->setMotorTorque(mTorque); + if (sbbI_BrakeTorque)wheel2->setBreakTorque(bTorque); + if (sbbI_SuspensionSpring)wheel2->setSuspensionSpring(sSpring); + if (sbbI_SuspensionTravel)wheel2->setSuspensionTravel(suspensionTravel); + if (sbbI_WFlags) + { + + ////////////////////////////////////////////////////////////////////////// + // + // + wheel2->setFlags(wFlags); + + } + + + if (sbbI_WSFlags) + { + wheel2->getWheelShape()->setWheelFlags(wSFlags); + } + + + if (sbbI_LatFunc) + { + + CKParameterIn *par = beh->GetInputParameter(BB_IP_INDEX(bbI_LatFunc)); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + pTireFunction func = pFactory::Instance()->createTireFuncFromParameter(rPar); + if (func.isValid()) + { + NxTireFunctionDesc xFn; + xFn.asymptoteSlip = func.asymptoteSlip; + xFn.asymptoteValue = func.asymptoteValue; + xFn.extremumSlip= func.extremumSlip; + xFn.extremumValue= func.extremumValue; + xFn.stiffnessFactor= func.stiffnessFactor; + wheel2->getWheelShape()->setLongitudalTireForceFunction(xFn); + }else + bbErrorME("Invalid Tire Function Settings!"); + } + } + } + + if (sbbI_LongFunc) + { + + CKParameterIn *par = beh->GetInputParameter(BB_IP_INDEX(bbI_LongFunc)); + if (par) + { + CKParameter *rPar = par->GetRealSource(); + if (rPar) + { + pTireFunction func = pFactory::Instance()->createTireFuncFromParameter(rPar); + if (func.isValid()) + { + NxTireFunctionDesc xFn; + xFn.asymptoteSlip = func.asymptoteSlip; + xFn.asymptoteValue = func.asymptoteValue; + xFn.extremumSlip= func.extremumSlip; + xFn.extremumValue= func.extremumValue; + xFn.stiffnessFactor= func.stiffnessFactor; + wheel2->getWheelShape()->setLongitudalTireForceFunction(xFn); + }else + bbErrorME("Invalid Tire Function Settings!"); + } + } + } + } + beh->ActivateOutput(0); + return 0; +} + +//************************************ +// Method: PVWSetCB +// FullName: PVWSetCB +// Access: public +// Returns: CKERROR +// Qualifier: +// Parameter: const CKBehaviorContext& behcontext +//************************************ +CKERROR PVWSetCB(const CKBehaviorContext& behcontext) +{ + CKBehavior *beh = behcontext.Behavior; + + BB_DECLARE_PMAP; + + switch(behcontext.CallbackMessage) { + + case CKM_BEHAVIORCREATE: + case CKM_BEHAVIORLOAD: + { + BB_LOAD_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORDETACH: + { + BB_DESTROY_PIMAP; + break; + } + + case CKM_BEHAVIORATTACH: + { + BB_INIT_PIMAP(gPIMAP,BB_SSTART); + break; + } + case CKM_BEHAVIORSETTINGSEDITED: + { + BB_REMAP_PIMAP(gPIMAP,BB_SSTART); + break; + } + } + return CKBR_OK; + +} + + + diff --git a/usr/Src/Behaviors/setMousePos.cpp b/usr/Src/Behaviors/setMousePos.cpp new file mode 100644 index 0000000..c48bc66 --- /dev/null +++ b/usr/Src/Behaviors/setMousePos.cpp @@ -0,0 +1,71 @@ +#include "CKAll.h" +CKObjectDeclaration *FillBehaviorSetMousPosDecl(); + +CKERROR CreateSetMousPosProto(CKBehaviorPrototype **pproto); +int SetMousPos(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorSetMousPosDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("SetMousePos"); + od->SetCategory("Narratives/Mouse"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x7938083c,0x32f03a3d)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateSetMousPosProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateSetMousPosProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("SetMousePos"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Create Zip File"); + + + proto->DeclareOutput("Zip File created"); + + proto->DeclareInParameter("IsServer",CKPGUID_FLOAT); + proto->DeclareInParameter("IsServer",CKPGUID_FLOAT); + + proto->DeclareOutParameter("UP",CKPGUID_INT); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(SetMousPos); + *pproto = proto; + return CK_OK; +} + +#include + +int SetMousPos(const CKBehaviorContext& behcontext) +{ + + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + if( beh->IsInputActive(0) ){ + beh->ActivateInput(0,FALSE); + + DWORD data = 0; + DWORD flags = MOUSEEVENTF_ABSOLUTE; + + // - Has the pointer moved since the last event? + + + flags |= MOUSEEVENTF_MOVE; + + mouse_event(flags, 100,100, data, 0); + + + beh->ActivateOutput(0); + + + } + + return 0; + +} diff --git a/usr/Src/Behaviors/system/BGInstancer.cpp b/usr/Src/Behaviors/system/BGInstancer.cpp new file mode 100644 index 0000000..c038c64 --- /dev/null +++ b/usr/Src/Behaviors/system/BGInstancer.cpp @@ -0,0 +1,926 @@ +/******************************************************************** + created: 2006/05/07 + created: 05:07:2006 8:14 + filename: x:\junctions\ProjectRoot\current\vt_plugins\vt_toolkit\Behaviors\Generic\BGInstancer.cpp + file path: x:\junctions\ProjectRoot\current\vt_plugins\vt_toolkit\Behaviors\Generic + file base: BGInstancer + file ext: cpp + author: mc007 + + purpose: +*********************************************************************/ +#include //for pch only,can be removed! + +#include "BGInstancer.h" + + + +/* + ******************************************************************* + * Function: CKObjectDeclaration *FillBehaviour( void ) + * + * Description : As its name infers, this function describes each Building Block + * on a functional level : what it can be applied to, its GUID, its + * creation function, etc.. + * + * + * Parameters : + * None + * + * Returns : CKObjectDeclaration *, containing: + * - The type of object declaration ( Must Be CKDLL_BEHAVIORPROTOTYPE ) + * - The function that will create the CKBehaviorPrototype for this behavior. + * - A short description of what the behavior is supposed to do. + * - The category in which this behavior will appear in the Virtools interface. + * - A unique CKGUID + * - Author and Version info + * - The class identifier of objects to which the behavior can be applied to. + * + ******************************************************************* + */ +CKObjectDeclaration * BGWrapper::FillBehaviour( void ) +{ + CKObjectDeclaration *objectDeclaration = CreateCKObjectDeclaration( "BgInstancer" ); + + objectDeclaration->SetType( CKDLL_BEHAVIORPROTOTYPE ); + objectDeclaration->SetCreationFunction( BGWrapper::CreatePrototype ); + objectDeclaration->SetDescription( "Encapsulates the functionality provided by a Behaviour Graph and allows reuse while minimising maintenance overhead." ); + objectDeclaration->SetCategory( "Narratives/Script Management" ); + objectDeclaration->SetGuid( BGWRAPPER_GUID ); + objectDeclaration->SetVersion( 0x00000001 ); + objectDeclaration->SetAuthorGuid( VTCX_AUTHOR_GUID ); + objectDeclaration->SetAuthorName( VTCX_AUTHOR ); + objectDeclaration->SetCompatibleClassId( CKCID_BEOBJECT ); + + return objectDeclaration; +} + +/* + ******************************************************************* + * Function: CKERROR CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ) + * + * Description : The prototype creation function will be called the first time + * a behavior must be created to create the CKBehaviorPrototype + * that contains the description of the behavior. + * + * Parameters : + * behaviorPrototypePtr Pointer to a CKBehaviorPrototype object that + * describes the behavior's internal structure + * and relationships with other objects. + * + * Returns : CKERROR + * + ******************************************************************* + */ +CKERROR BGWrapper::CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ) + { + +#if RUNTIME + // Not editable from Virtools Dev + CKBehaviorPrototype *behaviorPrototype = CreateCKBehaviorPrototypeRunTime( "BGWrapper" ); +#elif GAMEDEVELOPER + // Edition depend on the BB. + CKBehaviorPrototype *behaviorPrototype = CreateCKBehaviorPrototype( "BGWrapper" ); +#else + // Editable from Virtools Dev + CKBehaviorPrototype *behaviorPrototype = CreateCKBehaviorPrototype( "BGWrapper" ); +#endif + + + if ( !behaviorPrototype ) + return CKERR_OUTOFMEMORY; + + //---- Local Parameters Declaration + behaviorPrototype->DeclareLocalParameter("BG Script", CKPGUID_BEHAVIOR ); + + //---- Settings Declaration + behaviorPrototype->DeclareSetting("BG filename", CKPGUID_STRING ,"path undefined.(BGWrapper Settings)"); + + behaviorPrototype->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + + behaviorPrototype->SetBehaviorFlags((CK_BEHAVIOR_FLAGS)(CKBEHAVIOR_INTERNALLYCREATEDINPUTS | + CKBEHAVIOR_INTERNALLYCREATEDINPUTPARAMS | + CKBEHAVIOR_INTERNALLYCREATEDOUTPUTS | + CKBEHAVIOR_INTERNALLYCREATEDOUTPUTPARAMS)); + + behaviorPrototype->SetBehaviorCallbackFct(BGWrapperCB, + CKCB_BEHAVIORLOAD | + CKCB_BEHAVIORRESET | + CKCB_BEHAVIORSETTINGSEDITED | + CKCB_BEHAVIORDETACH | + CKCB_BEHAVIORDEACTIVATESCRIPT + , NULL); + + behaviorPrototype->SetFunction( BGWrapper::BehaviourFunction ); + + *behaviorPrototypePtr = behaviorPrototype; + return CK_OK; +} + +/* + ******************************************************************* + * Function: int BehaviourFunction( const CKBehaviorContext& behaviorContext ) + * + * Description : The execution function is the function that will be called + * during the process loop of the behavior engine, if the behavior + * is defined as using an execution function. This function is not + * called if the behavior is defined as a graph. This function is the + * heart of the behavior: it should compute the essence of the behavior, + * in an incremental way. The minimum amount of computing should be + * done at each call, to leave time for the other behaviors to run. + * The function receives the delay in milliseconds that has elapsed + * since the last behavioral process, and should rely on this value to + * manage the amount of effect it has on its computation, if the effect + * of this computation relies on time. + * + * Parameters : + * behaviourContext Behavior context reference, which gives access to + * frequently used global objects ( context, level, manager, etc... ) + * + * Returns : int, If it is done, it should return CKBR_OK. If it returns + * CKBR_ACTIVATENEXTFRAME, the behavior will again be called + * during the next process loop. + * + ******************************************************************* + */ + +int BGWrapper::BehaviourFunction( const CKBehaviorContext& behContext ) +{ + CKBehavior *behaviour = behContext.Behavior; + CKContext *context = behContext.Context; + int iPin, nbPin; + + CKBehavior* script = (CKBehavior*)behaviour->GetLocalParameterObject(EBGWRAPPERPARAM_PARAMETER_SCRIPT); + + if (script == NULL) + return CKBR_GENERICERROR; + + // Activate the right inputs + nbPin = behaviour->GetInputCount(); + for (iPin = 0; iPin < nbPin; iPin++) + { + if (behaviour->IsInputActive(iPin)) + { + script->ActivateInput(iPin, TRUE); + behaviour->ActivateInput(iPin, FALSE); + } + } + + // Deactivate all the outputs + nbPin = script->GetOutputCount(); + for (iPin = 0; iPin < nbPin; iPin++) + { + behaviour->ActivateOutput(iPin, FALSE); + } + + // Parameter In: Set Source + int nbPinBB = behaviour->GetInputParameterCount(); + int nbPinBG = script->GetInputParameterCount(); + + if (nbPinBB != nbPinBG) + return CKBR_GENERICERROR; + + for (iPin = 0; iPin < nbPinBB; iPin++) + { + CKParameterIn *pBin = behaviour->GetInputParameter(iPin); + CKParameter* pSource = pBin->GetDirectSource(); + + CKParameterIn *pSin = script->GetInputParameter(iPin); + pSin->SetDirectSource(pSource); + } + + // Execute the contained script + CKERROR result = script->Execute(behContext.DeltaTime); + + // The script loop on itself too much times + if (result == CKBR_INFINITELOOP) + { + context->OutputToConsoleExBeep("Execute Script : Script %s Executed too much times",script->GetName()); + script->Activate(FALSE,FALSE); + return CKBR_OK; + } + + // Activate the right outputs + nbPin = script->GetOutputCount(); + for (iPin = 0; iPin < nbPin; iPin++) + { + if (script->IsOutputActive(iPin)) + { + behaviour->ActivateOutput(iPin); + script->ActivateOutput(iPin, FALSE); + } + } + + // Update Parameters Out + nbPin = behaviour->GetOutputParameterCount(); + for (iPin = 0; iPin < nbPin; iPin++) + { + CKParameterOut *pBout = behaviour->GetOutputParameter(iPin); + CKParameterOut *pSout = script->GetOutputParameter(iPin); + pBout->CopyValue(pSout, TRUE); + } + + + // Test if there are any active sub-behaviors, restart the next frame if any + BOOL bActivateNextFrame = FALSE; + ActivateNextFrameSubBB(script,bActivateNextFrame); + if (bActivateNextFrame) + return CKBR_ACTIVATENEXTFRAME; + + // return the execute value + return result; +} + +/* + ******************************************************************* + * Function: CKERROR BGWrapperCB(const CKBehaviorContext& behContext) + * + * Description : The Behavior Callback function is called by Virtools + * when various events happen in the life of a BuildingBlock. + * + * Parameters : + * behaviourContext Behavior context reference, which gives access to + * frequently used global objects ( context, level, manager, etc... ) + * + * Returns : CKERROR + * + ******************************************************************* + */ +CKERROR BGWrapper::BGWrapperCB(const CKBehaviorContext& behContext) +{ + CKERROR result = CKBR_GENERICERROR; + + // Initialize common pointers. + CKBehavior *behaviour = behContext.Behavior; + CKContext *context = behContext.Context; + CKLevel *level = behContext.CurrentLevel; + CKBeObject *owner = behContext.Behavior->GetOwner(); + + char*name = behaviour->GetName(); + + if ( behaviour == NULL || context == NULL || level == NULL /*|| owner == NULL*/ ) + return CKBR_OK; + + //Get The BG Script Object if exists + CKBehavior* newBG = NULL; + CKBehavior* curBG = (CKBehavior*)behaviour->GetLocalParameterObject(EBGWRAPPERPARAM_PARAMETER_SCRIPT); + + // Get the BG nms file path. GetStringValue doesn't work with setting... + char fileName[_MAX_PATH+1]; + memset(fileName,0,_MAX_PATH+1); + CKParameter* scriptPath = behaviour->GetLocalParameter(EBGWRAPPERPARAM_PARAMETER_NAME); + if ( scriptPath == NULL ) + return CKBR_OK; + + int lenPath = scriptPath->GetDataSize(); + if ( lenPath >= _MAX_PATH ) + return CKBR_OK; + + void*ptrPath = scriptPath->GetReadDataPtr(TRUE); + if ( ptrPath == NULL ) + return CKBR_OK; + + memcpy(fileName,ptrPath,lenPath); + + CKDWORD message = behContext.CallbackMessage; + + switch (message) + { + case CKM_BEHAVIORLOAD : // when the behavior is loaded + case CKM_BEHAVIORRESET: // when the behavior is reseted + case CKM_BEHAVIORSETTINGSEDITED : // when the settings are edited + { + if ( curBG != NULL ) + { + DestroyCurrentBG(level,behaviour,curBG); + curBG = NULL; + } + + newBG = BGLoader( fileName, behContext ); + if ( newBG == NULL ) + return CKBR_OK; + + if ( message == CKM_BEHAVIORLOAD || message == CKM_BEHAVIORRESET ) + { + //context->OutputToConsoleExBeep("%s : LOADED %s",behaviour->GetName(), fileName); + if ( CheckIO(behaviour, newBG) == TRUE ) + result = CKBR_OK; + else + context->OutputToConsoleExBeep("%s : Too many inputs/outputs changes in %s\r\nPlease reconstruct the wrapper.",behaviour->GetName(), fileName); + } + else if ( message == CKM_BEHAVIORSETTINGSEDITED ) + { + if ( CheckIO(behaviour, newBG) == TRUE ) + { + result = CKBR_OK; + } + else if (DeleteIO(behaviour) == TRUE) + { + if ( CreateIO(behaviour, newBG ) == TRUE ) + result = CKBR_OK; + else + context->OutputToConsoleExBeep("%s : Cannot Create Inputs/Outputs %s",behaviour->GetName(), fileName); + } + else + context->OutputToConsoleExBeep("%s : Cannot Delete Inputs/Outputs %s",behaviour->GetName(), fileName); + } + + if ( result == CKBR_OK && newBG != NULL ) + SetNewBG(behaviour,newBG); + } + break; + + case CKM_BEHAVIORDEACTIVATESCRIPT: + { + if ( curBG != NULL ) + DesactivateSubBB(curBG); + result = CKBR_OK; + } + break; + + case CKM_BEHAVIORDETACH : // when the behavior is deleted + { + if (curBG != NULL) + { + DestroyCurrentBG(level,behaviour,curBG); + curBG = NULL; + } + result = CKBR_OK; + } + break; + + default: + { + result = CKBR_OK; + } + break; + + } + + if (result != CKBR_OK) + context->OutputToConsoleExBeep("%s : Problem while manipulating",behaviour->GetName()); + + + + return result; + } + + + /* + ******************************************************************* + * Function: CKBehavior* BGLoader(CKSTRING fileName,const CKBehaviorContext& behContext) + * + * Description : Load a virtools script.and add it to the current level. + * + * Parameters : + * fileName string containing the script filename to be loaded. + * behaviourContext Behavior context reference, which gives access to + * frequently used global objects ( context, level, manager, etc... ) + * + * Returns : CKBehavior* the loaded behaviour, NULL if failed. + * + ******************************************************************* + */ +CKBehavior* BGWrapper::BGLoader(CKSTRING fileName,const CKBehaviorContext& behContext) +{ + CKERROR result = CKBR_GENERICERROR; + + // Initialize common pointers. + CKBehavior *behaviour = behContext.Behavior; + CKContext *context = behContext.Context; + CKLevel *level = behContext.CurrentLevel; + CKBeObject *owner = behContext.Behavior->GetOwner(); + + if ( behaviour == NULL || context == NULL || level == NULL ) + return NULL; + + char fileToLoad[_MAX_PATH],nakedFileName[_MAX_PATH]; + char drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; + _splitpath(fileName, drive, dir, fname, ext); + + if ( ext[0] == 0 ) + strcpy(ext,".nms"); + + strcpy(fileToLoad,drive); + strcat(fileToLoad,dir); + strcat(fileToLoad,fname); + strcat(fileToLoad,ext); + + if ( strcmp(_strlwr(ext),".nms") != 0 ) + { + context->OutputToConsoleExBeep("BGWrapper : Can only load .nms files %s",fileToLoad); + return NULL; + } + + CKObjectArray* array = CreateCKObjectArray(); + + context->SetAutomaticLoadMode(CKLOAD_OK, CKLOAD_OK, CKLOAD_USECURRENT, CKLOAD_USECURRENT); + + // Virtools Load the BGs nms file.first try the absolute path, then the lastCmoloaded path, and then the PathManager manager data paths + if (context->Load(fileToLoad, array, (CK_LOAD_FLAGS)(CK_LOAD_AUTOMATICMODE | CK_LOAD_AS_DYNAMIC_OBJECT )) != CK_OK) + { + strcpy(nakedFileName,fname); + strcat(nakedFileName,ext); + + CKSTRING lastCmo = context->GetLastCmoLoaded(); + char driveCmo[_MAX_DRIVE], dirCmo[_MAX_DIR], fnameCmo[_MAX_FNAME], extCmo[_MAX_EXT]; + _splitpath(lastCmo, driveCmo, dirCmo, fnameCmo, extCmo); + + strcpy(fileToLoad,driveCmo);strcat(fileToLoad,dirCmo);strcat(fileToLoad,nakedFileName); + + if (context->Load(fileToLoad, array, (CK_LOAD_FLAGS)(CK_LOAD_AUTOMATICMODE | CK_LOAD_AS_DYNAMIC_OBJECT )) != CK_OK) + { + // failed then try to go thru the data path. + CKPathManager* pathmanager = behContext.Context->GetPathManager(); + if (!pathmanager) + { + context->OutputToConsoleExBeep("BGWrapper : Cannot find the Path Manager"); + return NULL; + } + + XString resolved(nakedFileName); + array->Clear(); + pathmanager->ResolveFileName(resolved,DATA_PATH_IDX,-1); + if (context->Load(resolved.Str(), array, (CK_LOAD_FLAGS)(CK_LOAD_AUTOMATICMODE | CK_LOAD_AS_DYNAMIC_OBJECT )) != CK_OK) + { + context->OutputToConsoleExBeep("BGWrapper : Cannot Load %s", nakedFileName); + return NULL; + } + } + + + } + + // Check if only one Object is loaded (we should have only one BG here) + if ( array->GetCount() != 1 ) + { + context->OutputToConsoleExBeep("BGWrapper : To many objects inside the nms %s.It should contain one BG only.",fileToLoad); + + level->BeginRemoveSequence(TRUE); + for (array->Reset(); !array->EndOfList(); array->Next()) + { + CKObject* curObject = array->GetData(context); + level->RemoveObject(curObject); + CKDestroyObject(curObject); + } + level->BeginRemoveSequence(FALSE); + DeleteCKObjectArray(array); + + return NULL; + } + + array->Reset(); + CKObject* curObject = array->GetData(context); + + if ( curObject == NULL ) + { + context->OutputToConsoleExBeep("BGWrapper : Object NULL in loaded array."); + return NULL; + } + + // Make it not to be saved even if it is loaded as dynamic... (not needed ?) + curObject->ModifyObjectFlags( CK_OBJECT_NOTTOBESAVED,0 ); + + // Check if the object we've loaded is derivated from the BEHAVIOR + if ( !CKIsChildClassOf(curObject, CKCID_BEHAVIOR) ) + { + context->OutputToConsoleExBeep("BGWrapper : no behavior in the nms : %s",fileToLoad); + + level->BeginRemoveSequence(TRUE); + level->RemoveObject(curObject); + level->BeginRemoveSequence(FALSE); + CKDestroyObject(curObject); + DeleteCKObjectArray(array); + + return NULL; + } + + CKBehavior*pBG = (CKBehavior*)curObject; + + // Check if the behavior we've loaded is a BG and not a BB. + if ( pBG->IsUsingFunction() ) + { + context->OutputToConsoleExBeep("BGWrapper : BGWrapper accepts only a BG not a BB : %s",fileToLoad); + + level->BeginRemoveSequence(TRUE); + level->RemoveObject(curObject); + level->BeginRemoveSequence(FALSE); + CKDestroyObject(curObject); + DeleteCKObjectArray(array); + + return NULL; + } + + // Check if the BG can be applied to the 's BeObject owner. + char*nameee = pBG->GetName(); + CK_CLASSID cid = pBG->GetCompatibleClassID(); + + + if (owner!=NULL) + if ( !CKIsChildClassOf(owner, pBG->GetCompatibleClassID()) ) + { + context->OutputToConsoleExBeep("BGWrapper : Incompatible Class, cannot add BG to script %s",fileToLoad); + + level->BeginRemoveSequence(TRUE); + level->RemoveObject(curObject); + level->BeginRemoveSequence(FALSE); + CKDestroyObject(curObject); + DeleteCKObjectArray(array); + + return NULL; + } + + // Add the BG to the 's level. + level->BeginAddSequence(TRUE); + level->AddObject(curObject); + level->BeginAddSequence(FALSE); + DeleteCKObjectArray(array); + + if (owner!=NULL) + OwnerSubBB(pBG,owner); + + return pBG; +} + + + /* + ******************************************************************* + * Function: BOOL CheckIO(CKBehavior* behaviour, CKBehavior* script) + * + * Description : Check if all the Inputs,Outputs, pIns and pOuts of both behavior are matching + * + * Parameters : + * behaviour Behavior 1, usually the BG wrapper BB. + * script Behavior 2, usually the wrapped BG. + * + * Returns : BOOL + * + ******************************************************************* + */ +BOOL BGWrapper::CheckIO(CKBehavior* behaviour, CKBehavior* script) + { + int iParam; + int nbPin0, nbPin1; + int flag = 0; + + // Input + nbPin0 = behaviour->GetInputCount(); + nbPin1 = script->GetInputCount(); + if (nbPin0 != nbPin1) + return FALSE; + + // Ouput + nbPin0 = behaviour->GetOutputCount(); + nbPin1 = script->GetOutputCount(); + if (nbPin0 != nbPin1) + return FALSE; + + // Parameter In + nbPin0 = behaviour->GetInputParameterCount(); + nbPin1 = script->GetInputParameterCount(); + if (nbPin0 != nbPin1) + return FALSE; + for (iParam = 0; iParam < nbPin0; iParam++) + { + CKParameterIn* pSin = script->GetInputParameter(iParam); + CKParameterIn* pBin = behaviour->GetInputParameter(iParam); + if (pSin == NULL || pBin == NULL) + return FALSE; + if (pSin->GetType() != pBin->GetType()) + return FALSE; + } + + // Parameter Out + nbPin0 = behaviour->GetOutputParameterCount(); + nbPin1 = script->GetOutputParameterCount(); + if (nbPin0 != nbPin1) + return FALSE; + for (iParam = 0; iParam < nbPin0; iParam++) + { + CKParameterOut* pSout = script->GetOutputParameter(iParam); + CKParameterOut* pBout = behaviour->GetOutputParameter(iParam); + if (pSout == NULL || pBout == NULL) + return FALSE; + if (pSout->GetType() != pBout->GetType()) + return FALSE; + } + + return TRUE; + } + + + /* + ******************************************************************* + * Function: BOOL :CreateIO(CKBehavior* behaviour, CKBehavior* script) + * + * Description : Check if all the Inputs,Outputs, pIns and pOuts of both behavior are matching + * + * Parameters : + * behaviour Behavior 1, usually the BG wrapper BB. + * script Behavior 2, usually the wrapped BG. + * + * Returns : BOOL + * + ******************************************************************* + */ +BOOL BGWrapper::CreateIO(CKBehavior* behaviour, CKBehavior* script) + { + int iIO; + int nbPin; + + // Input + nbPin = script->GetInputCount(); + for (iIO = 0; iIO < nbPin; iIO++) + { + CKBehaviorIO* pPin = script->GetInput(iIO); + if (pPin == NULL) + return FALSE; + + if (behaviour->AddInput(pPin->GetName()) != iIO) + return FALSE; + } + + // Output + nbPin = script->GetOutputCount(); + for (iIO = 0; iIO < nbPin; iIO++) + { + CKBehaviorIO* pPin = script->GetOutput(iIO); + if (pPin == NULL) + return FALSE; + + if (behaviour->AddOutput(pPin->GetName()) != iIO) + return FALSE; + } + + // Parameter In + nbPin = script->GetInputParameterCount(); + for (iIO = 0; iIO < nbPin; iIO++) + { + CKParameterIn* pPin = script->GetInputParameter(iIO); + if (pPin == NULL) + return FALSE; + + CKParameterIn* pPin2; + if ((pPin2 = behaviour->CreateInputParameter(pPin->GetName(), (CKParameterType)pPin->GetType())) == NULL) + return FALSE; + } + + // Parameter Out + nbPin = script->GetOutputParameterCount(); + for (iIO = 0; iIO < nbPin; iIO++) + { + CKParameterOut* pPin = script->GetOutputParameter(iIO); + if (pPin == NULL) + return FALSE; + + if (behaviour->CreateOutputParameter(pPin->GetName(), (CKParameterType)pPin->GetType()) == NULL) + return FALSE; + } + + return TRUE; + } + + /* + ******************************************************************* + * Function: BOOL DeleteIO(CKBehavior* behaviour) + * + * Description : Delete all kind of inputs/outputs on the given behavior + * + * Parameters : + * behaviour The behavior to be naked on. + * + * Returns : BOOL + * + ******************************************************************* + */ +BOOL BGWrapper::DeleteIO(CKBehavior* behaviour) + { + int iIO; + int nbPin0; + + // Input + nbPin0 = behaviour->GetInputCount(); + for (iIO = nbPin0-1; iIO >= 0; iIO--) + { + if (behaviour->DeleteInput(iIO) != CK_OK) + return FALSE; + } + + // Ouput + nbPin0 = behaviour->GetOutputCount(); + for (iIO = nbPin0-1; iIO >= 0; iIO--) + { + if (behaviour->DeleteOutput(iIO) != CK_OK) + return FALSE; + } + + // Parameter In + nbPin0 = behaviour->GetInputParameterCount(); + for (iIO = nbPin0-1; iIO >= 0; iIO--) + { + CKParameterIn* pParam; + + if ((pParam = behaviour->RemoveInputParameter(iIO)) == NULL) + return FALSE; + CKDestroyObject(pParam); + } + + // Parameter Out + nbPin0 = behaviour->GetOutputParameterCount(); + for (iIO = nbPin0-1; iIO >= 0; iIO--) + { + CKParameterOut* pParam; + if ((pParam = behaviour->RemoveOutputParameter(iIO)) == NULL) + return FALSE; + CKDestroyObject(pParam); + } + + return TRUE; + } + + /* + ******************************************************************* + * Function: BOOL HasIO(CKBehavior* behaviour) + * + * Description : return TRUE if the behavior has almost one IN/OU/PIN/POUT + * + * Parameters : + * behaviour The behavior to be checked. + * + * Returns : BOOL + * + ******************************************************************* + */ + +BOOL BGWrapper::HasIO(CKBehavior* behaviour) + { + // Input + if (behaviour->GetInputCount()) + return TRUE; + + // Ouput + if (behaviour->GetOutputCount()) + return TRUE; + + // Parameter In + if (behaviour->GetInputParameterCount()) + return TRUE; + + // Parameter Out + if (behaviour->GetOutputParameterCount()) + return TRUE; + + return FALSE; + } + + /* + ******************************************************************* + * Function: void ActivateNextFrameSubBB(CKBehavior* scriptObject,BOOL &bActivateNextFrame) + * + * Description : set the bActivateNextFrame to TRUE if one sub behavior is still active. + * + * Parameters : + * scriptObject The behavior to be checked. + * + * Returns : void + * + ******************************************************************* + */ +void BGWrapper::ActivateNextFrameSubBB(CKBehavior* scriptObject,BOOL &bActivateNextFrame) +{ + if ( scriptObject == NULL ) + return; + + if ( scriptObject->IsActive() ) + { + bActivateNextFrame = TRUE; + return; + } + + for ( int i = 0; i < scriptObject->GetSubBehaviorCount(); i++) + { + CKBehavior*scriptSub = scriptObject->GetSubBehavior(i); + ActivateNextFrameSubBB(scriptSub,bActivateNextFrame); + } +} + + /* + ******************************************************************* + * Function: void DesactivateSubBB(CKBehavior* scriptObject) + * + * Description : Desactivate all sub-Behavior + * + * Parameters : + * scriptObject The behavior to be totally desactivated. + * + * Returns : void + * + ******************************************************************* + */ +void BGWrapper::DesactivateSubBB(CKBehavior* scriptObject) +{ + if ( scriptObject == NULL ) + return; + + scriptObject->Activate(FALSE,TRUE); + + for ( int i = 0; i < scriptObject->GetSubBehaviorCount(); i++) + { + CKBehavior*scriptSub = scriptObject->GetSubBehavior(i); + DesactivateSubBB(scriptSub); + } +} + + /* + ******************************************************************* + * Function: void OwnerSubBB(CKBehavior* scriptObject,CKBeObject*owner) + * + * Description : Set Owner ptr to all sub-Behavior. + * + * Parameters : + * scriptObject behavior to be parsed. + * owner owner to be assigned. + * + * Returns : void + * + ******************************************************************* + */ +void BGWrapper::OwnerSubBB(CKBehavior* scriptObject,CKBeObject*owner) +{ + if ( scriptObject == NULL ) + return; + + scriptObject->SetSubBehaviorOwner(owner); + scriptObject->SetOwner(owner); + + for ( int i = 0; i < scriptObject->GetSubBehaviorCount(); i++) + { + CKBehavior*scriptSub = scriptObject->GetSubBehavior(i); + OwnerSubBB(scriptSub,owner); + } +} + + /* + ******************************************************************* + * Function: void SetNewBG(CKBehavior *behaviour,CKBehavior *newBehavior) + * + * Description : Set new BB name and store the BG locally. + * + * Parameters : + * behaviour BG wrapper BB + * newBehavior BG assigned to the wrapper + * + * Returns : void + * + ******************************************************************* + */ +void BGWrapper::SetNewBG(CKBehavior *behaviour,CKBehavior *newBehavior) +{ + if ( behaviour == NULL || newBehavior == NULL ) + return; + + CKSTRING nameBG = newBehavior->GetName(); + size_t len = strlen(nameBG); + char*buf = (char*)malloc(len+128); + if ( buf != NULL ) + { + sprintf(buf, "BI(%s)", newBehavior->GetName()); + behaviour->SetName(buf); + free(buf); + } + else + behaviour->SetName("BI(###ERROR###)"); + + behaviour->SetLocalParameterObject(EBGWRAPPERPARAM_PARAMETER_SCRIPT,newBehavior); +} + +/* + ******************************************************************* + * Function: void DestroyCurrentBG(CKLevel* level,CKBehavior *behaviour,CKBehavior *scriptObject) + * + * Description : Destroy the currently wrapped BG + * + * Parameters : + * level level from witch the BG will be removed + * behaviour BG wrapper BB. + * scriptObject BG assigned to the wrapper. + * + * Returns : void + * + ******************************************************************* + */ +void BGWrapper::DestroyCurrentBG(CKLevel* level,CKBehavior *behaviour,CKBehavior *scriptObject) +{ + if ( level == NULL || behaviour == NULL || scriptObject == NULL ) + return; + + behaviour->SetName("BI(###Failed###)"); + + level->BeginRemoveSequence(TRUE); + level->RemoveObject(scriptObject); + level->BeginRemoveSequence(FALSE); + CKDestroyObject(scriptObject); + + behaviour->SetLocalParameterObject(EBGWRAPPERPARAM_PARAMETER_SCRIPT,NULL); + +} diff --git a/usr/Src/Behaviors/system/GBLAsyncBlock.cpp b/usr/Src/Behaviors/system/GBLAsyncBlock.cpp new file mode 100644 index 0000000..07163af --- /dev/null +++ b/usr/Src/Behaviors/system/GBLAsyncBlock.cpp @@ -0,0 +1,321 @@ +#include + +#include ".\GBLAsyncBlock.h" + + +/* + ******************************************************************* + * Function: CKObjectDeclaration *FillBehaviour( void ) + * + * Description : As its name infers, this function describes each Building Block + * on a functional level : what it can be applied to, its GUID, its + * creation function, etc.. + * + * + * Paramters : + * None + * + * Returns : CKObjectDeclaration *, containing: + * - The type of object declaration ( Must Be CKDLL_BEHAVIORPROTOTYPE ) + * - The function that will create the CKBehaviorPrototype for this behavior. + * - A short description of what the behavior is supposed to do. + * - The category in which this behavior will appear in the Virtools interface. + * - A unique CKGUID + * - Author and Version info + * - The class identifier of objects to which the behavior can be applied to. + * + ******************************************************************* + */ +CKObjectDeclaration * ExeInThread::FillBehaviour( void ) +{ + CKObjectDeclaration *objectDeclaration = CreateCKObjectDeclaration( "ExecuteBBInThread" ); + + objectDeclaration->SetType( CKDLL_BEHAVIORPROTOTYPE ); + objectDeclaration->SetCreationFunction( ExeInThread::CreatePrototype ); + objectDeclaration->SetDescription( "Executes a BB in a Thread" ); + objectDeclaration->SetCategory( "Narratives/Script Management" ); + objectDeclaration->SetGuid( CKGUID( 0x72387e71,0x89d786d) ); + objectDeclaration->SetVersion( 0x00000001 ); + objectDeclaration->SetAuthorGuid( VTCX_AUTHOR_GUID ); + objectDeclaration->SetAuthorName( VTCX_AUTHOR ); + objectDeclaration->SetCompatibleClassId( CKCID_BEOBJECT ); + + return objectDeclaration; +} + + +/* + ******************************************************************* + * Function: CKERROR CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ) + * + * Description : The prototype creation function will be called the first time + * a behavior must be created to create the CKBehaviorPrototype + * that contains the description of the behavior. + * + * Paramters : + * behaviorPrototypePtr w Pointer to a CKBehaviorPrototype object that + * describes the behavior's internal structure + * and relationships with other objects. + * + * Returns : CKERROR + * + ******************************************************************* + */ +CKERROR ExeInThread::CreatePrototype( CKBehaviorPrototype** behaviorPrototypePtr ) +{ + CKBehaviorPrototype *behaviorPrototype = CreateCKBehaviorPrototype( "ExecuteBBInThread" ); + if ( !behaviorPrototype ) + { + return CKERR_OUTOFMEMORY; + } + + //--- Inputs declaration + behaviorPrototype->DeclareInput( "In" ); + + //--- Outputs declaration + behaviorPrototype->DeclareOutput( "Out" ); + + + + //---- Local Parameters Declaration + + behaviorPrototype->DeclareLocalParameter("thethread", CKPGUID_POINTER, "0"); + behaviorPrototype->DeclareLocalParameter("thestatus", CKPGUID_INT, "0"); + + + + //---- Settings Declaration + + behaviorPrototype->SetBehaviorCallbackFct( ExeInThread::CallBack, CKCB_BEHAVIORATTACH|CKCB_BEHAVIORDETACH|CKCB_BEHAVIORDELETE|CKCB_BEHAVIOREDITED|CKCB_BEHAVIORSETTINGSEDITED|CKCB_BEHAVIORLOAD|CKCB_BEHAVIORPRESAVE|CKCB_BEHAVIORPOSTSAVE|CKCB_BEHAVIORRESUME|CKCB_BEHAVIORPAUSE|CKCB_BEHAVIORRESET|CKCB_BEHAVIORRESET|CKCB_BEHAVIORDEACTIVATESCRIPT|CKCB_BEHAVIORACTIVATESCRIPT|CKCB_BEHAVIORREADSTATE, NULL ); + behaviorPrototype->SetFunction( ExeInThread::BehaviourFunction ); + + *behaviorPrototypePtr = behaviorPrototype; + return CK_OK; +} + +/* + ******************************************************************* + * Function: int BehaviourFunction( const CKBehaviorContext& behaviorContext ) + * + * Description : The execution function is the function that will be called + * during the process loop of the behavior engine, if the behavior + * is defined as using an execution function. This function is not + * called if the behavior is defined as a graph. This function is the + * heart of the behavior: it should compute the essence of the behavior, + * in an incremental way. The minimum amount of computing should be + * done at each call, to leave time for the other behaviors to run. + * The function receives the delay in milliseconds that has elapsed + * since the last behavioral process, and should rely on this value to + * manage the amount of effect it has on its computation, if the effect + * of this computation relies on time. + * + * Paramters : + * behaviourContext r Behavior context reference, which gives access to + * frequently used global objects ( context, level, manager, etc... ) + * + * Returns : int, If it is done, it should return CKBR_OK. If it returns + * CKBR_ACTIVATENEXTFRAME, the behavior will again be called + * during the next process loop. + * + ******************************************************************* + */ +int ExeInThread::BehaviourFunction( const CKBehaviorContext& behaviorContext ) +{ + CKBehavior* beh = behaviorContext.Behavior; + CKContext* ctx = beh->GetCKContext(); + + if (beh->IsInputActive(0)) + { + + beh->ActivateInput(0,FALSE); + + VxThread *VXT; + + int status = 0; + beh->GetLocalParameterValue(1,&status); + + if (status == ThreadStatus::Requested) + { + return CKBR_ACTIVATENEXTFRAME; + } + + if (status == ThreadStatus::Active) + { + status = ThreadStatus::Requested; + beh->SetLocalParameterValue(1,&status); + return CKBR_ACTIVATENEXTFRAME; + } + + VXT = new VxThread(); + VXT->SetName("Thread"); + VXT->SetPriority(VXTP_NORMAL); + AsyncThreadInfo * threadInfo; + + threadInfo = new AsyncThreadInfo; + + threadInfo->targetBeh = NULL; + + int count = beh->GetParent()->GetSubBehaviorLinkCount(); + + for (int i=0; iGetParent()->GetSubBehaviorLink(i); + if (link->GetInBehaviorIO() == beh->GetOutput(0)) + { + threadInfo->targetBeh = link->GetOutBehaviorIO()->GetOwner(); + + int targetInputs = threadInfo->targetBeh->GetInputCount(); + if (targetInputs == 1) + { + threadInfo->targetInputToActivate = 0; + } + else + { + for (int j=0; jGetOutBehaviorIO() == threadInfo->targetBeh->GetInput(j)) + { + threadInfo->targetInputToActivate = j; + break; + } + } + } + break; + } + } + + if (threadInfo->targetBeh == NULL) + { + delete threadInfo; + return CKBR_BEHAVIORERROR; + } + + VXT->CreateThread(BlockingThreadFunction,threadInfo); + beh->SetLocalParameterValue(0,&VXT,sizeof(VxThread *)); + + status = ThreadStatus::Active; + beh->SetLocalParameterValue(1,&status); + + return CKBR_ACTIVATENEXTFRAME; + + } + else + { + VxThread *VXT; + beh->GetLocalParameterValue(0,&VXT); + + unsigned int status = -1; + + VXT->GetExitCode(status); + + if (status == VXT_OK) + { + VXT->Close(); + delete VXT; + VXT=NULL; + beh->SetLocalParameterValue(0,&VXT); + + + + int status; + beh->GetLocalParameterValue(1,&status); + + if (status == ThreadStatus::Requested) + { + beh->ActivateInput(0); + status = ThreadStatus::Idle; + beh->SetLocalParameterValue(1,&status); + return CKBR_ACTIVATENEXTFRAME; + + } + + status = ThreadStatus::Idle; + beh->SetLocalParameterValue(1,&status); + return CKBR_OK; + } + + } + + return CKBR_ACTIVATENEXTFRAME; +} + +/* +******************************************************************* +* Function: int Callback( const CKBehaviorContext& behaviorContext ) +* +* Description : The Behavior Callback function is called by Virtools when various events happen +* in the life of a BuildingBlock. Exactly which events trigger a call to the +* Behavior Callback function is defined in the Behavior Prototype, along with the +* declaration of the function pointer +* +* Parameters : +* behaviourContext r Behavior context reference, which gives +* access to frequently used global objects +* ( context, level, manager, etc... ) +* +* Returns : int, The return value of the callback function should be one of the CK_BEHAVIOR_RETURN values. +* +******************************************************************* +*/ +int ExeInThread::CallBack( const CKBehaviorContext& behaviorContext ) +{ + switch ( behaviorContext.CallbackMessage ) + { + case CKM_BEHAVIORATTACH: + break; + case CKM_BEHAVIORDETACH: + break; + case CKM_BEHAVIORDELETE: + break; + case CKM_BEHAVIOREDITED: + break; + case CKM_BEHAVIORSETTINGSEDITED: + break; + case CKM_BEHAVIORLOAD: + break; + case CKM_BEHAVIORPRESAVE: + break; + case CKM_BEHAVIORPOSTSAVE: + break; + case CKM_BEHAVIORRESUME: + { + int status = ThreadStatus::Idle; + behaviorContext.Behavior->SetLocalParameterValue(1,&status); + } + break; + + case CKM_BEHAVIORPAUSE: + break; + case CKM_BEHAVIORRESET: + break; + case CKM_BEHAVIORNEWSCENE: + break; + case CKM_BEHAVIORDEACTIVATESCRIPT: + break; + case CKM_BEHAVIORACTIVATESCRIPT: + break; + case CKM_BEHAVIORREADSTATE: + break; + + } + return CKBR_OK; +} + +unsigned int BlockingThreadFunction(void *arg) +{ + ExeInThread::AsyncThreadInfo* threadInfo = (ExeInThread::AsyncThreadInfo*)arg; + + threadInfo->targetBeh->ActivateInput(threadInfo->targetInputToActivate); + + int res; + + do + { + res = threadInfo->targetBeh->Execute(0); + } + while (res == CKBR_ACTIVATENEXTFRAME); + delete threadInfo; + return VXT_OK; +} + + diff --git a/usr/Src/Behaviors/system/GetAdapters.cpp b/usr/Src/Behaviors/system/GetAdapters.cpp new file mode 100644 index 0000000..c43c9aa --- /dev/null +++ b/usr/Src/Behaviors/system/GetAdapters.cpp @@ -0,0 +1,106 @@ + +#include "CKAll.h" + + + +CKObjectDeclaration *FillBehaviorGetAdaptersDecl(); +CKERROR CreateGetAdaptersProto(CKBehaviorPrototype **pproto); +int GetAdapters(const CKBehaviorContext& behcontext); + + +/************************************************************************/ +/* */ +/************************************************************************/ + +CKObjectDeclaration *FillBehaviorGetAdaptersDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Get Adapters"); + od->SetDescription("Add Objects"); + od->SetCategory("Narratives/System"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x2ab2796a,0x24c15af7)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("mw"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateGetAdaptersProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateGetAdaptersProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Get Adapters"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Get Next"); + proto->DeclareInput("Get Prev"); + + proto->DeclareOutput("Finish"); + proto->DeclareOutput("LoopOut"); + + proto->DeclareOutParameter("Name",CKPGUID_STRING); + proto->DeclareOutParameter("Index",CKPGUID_INT); + proto->DeclareOutParameter("Count",CKPGUID_INT); + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + + proto->SetFunction(GetAdapters); + *pproto = proto; + return CK_OK; +} + +int indexD = 0; +int countD = 0; + + +int GetAdapters(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + + CKPluginManager* ThePluginManager=CKGetPluginManager(); + CKRenderManager *rm = (CKRenderManager *)ctx->GetRenderManager(); + + + if( beh->IsInputActive(0) ){ + beh->ActivateInput(0, FALSE); + + + countD=rm->GetRenderDriverCount(); + indexD = 0; + + beh->ActivateInput(1, TRUE); + + } + + if( beh->IsInputActive(1) ){ + beh->ActivateInput(1, FALSE); + + if (indexD > (countD-1)){ + indexD = 0; + beh->ActivateOutput(0,TRUE); + return CKBR_OK; + } + + + beh->SetOutputParameterValue(1,&indexD); + VxDriverDesc *desc=rm->GetRenderDriverDescription(indexD); + + indexD++; + + + + CKParameterOut *pout2 = beh->GetOutputParameter(0); + pout2->SetStringValue(desc->DriverName.Str() ); + beh->ActivateOutput(1); + + + } + + + + + + return CKBR_OK; + +} + + diff --git a/usr/Src/Behaviors/system/GetAdaptersModie.cpp b/usr/Src/Behaviors/system/GetAdaptersModie.cpp new file mode 100644 index 0000000..d985d94 --- /dev/null +++ b/usr/Src/Behaviors/system/GetAdaptersModie.cpp @@ -0,0 +1,106 @@ +#include "CKAll.h" +CKObjectDeclaration *FillBehaviorGetAdaptersModieDecl(); +CKERROR CreateGetAdaptersModieProto(CKBehaviorPrototype **pproto); +int GetAdaptersModie(const CKBehaviorContext& behcontext); + + +/************************************************************************/ +/* */ +/************************************************************************/ + +CKObjectDeclaration *FillBehaviorGetAdaptersModieDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("GetAdaptersModie"); + od->SetDescription("Add Objects"); + od->SetCategory("Narratives/System"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x17ad4ca4,0x5bab3ee7)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("mw"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateGetAdaptersModieProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateGetAdaptersModieProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("GetAdaptersModie"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Start"); + proto->DeclareInput("Finish"); + proto->DeclareOutput("Finish"); + proto->DeclareOutput("LoopOut"); + + + + proto->DeclareInParameter("driver index",CKPGUID_INT); + + + proto->DeclareOutParameter("modie index",CKPGUID_INT); + proto->DeclareOutParameter("width",CKPGUID_INT); + proto->DeclareOutParameter("height",CKPGUID_INT); + + proto->DeclareOutParameter("bpp",CKPGUID_INT); + proto->DeclareOutParameter("refresh rate",CKPGUID_INT); + proto->DeclareOutParameter("modie count",CKPGUID_INT); + + + proto->SetFunction(GetAdaptersModie); + *pproto = proto; + return CK_OK; +} + +int indexDD = 0; + +int GetAdaptersModie(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + + CKPluginManager* ThePluginManager=CKGetPluginManager(); + CKRenderManager *rm = (CKRenderManager *)ctx->GetRenderManager(); + + + int DriverIndex=0; + beh->GetInputParameterValue(0, &DriverIndex); + VxDriverDesc *desc=rm->GetRenderDriverDescription(DriverIndex); + int mocount = desc->DisplayModes.Size(); + + int countDD =rm->GetRenderDriverCount(); + + if( beh->IsInputActive(0) ) + { + beh->ActivateInput(0, FALSE); + indexDD = 0; + beh->SetOutputParameterValue(5,&mocount); + return CKBR_OK; + } + + if ( indexDD >=mocount-1 /*|| DriverIndex < countDD */) + { + indexDD = 0; + beh->ActivateOutput(0,TRUE); + return CKBR_OK; + } + + + + if( beh->IsInputActive(1) ) + { + beh->ActivateInput(1, FALSE); + beh->SetOutputParameterValue(1,&desc->DisplayModes[indexDD].Width); + beh->SetOutputParameterValue(2,&desc->DisplayModes[indexDD].Height); + beh->SetOutputParameterValue(3,&desc->DisplayModes[indexDD].Bpp); + beh->SetOutputParameterValue(4,&desc->DisplayModes[indexDD].RefreshRate); + beh->SetOutputParameterValue(0,&indexDD); + indexDD++; + beh->ActivateOutput(1,TRUE); + return CKBR_OK; + + } + + return CKBR_OK; +} + + diff --git a/usr/Src/Behaviors/system/GetCurrentPath.cpp b/usr/Src/Behaviors/system/GetCurrentPath.cpp new file mode 100644 index 0000000..af35c0b --- /dev/null +++ b/usr/Src/Behaviors/system/GetCurrentPath.cpp @@ -0,0 +1,56 @@ +#include "CKAll.h" +CKObjectDeclaration *FillBehaviorGetCurrentPathDecl(); +CKERROR CreateGetCurrentPathProto(CKBehaviorPrototype **pproto); +int GetCurrentPath(const CKBehaviorContext& behcontext); + + +/************************************************************************/ +/* */ +/************************************************************************/ + +CKObjectDeclaration *FillBehaviorGetCurrentPathDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Get Current Path"); + od->SetDescription("Add Objects"); + od->SetCategory("Narratives/Objects"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x41676403,0x5d3d10c4)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateGetCurrentPathProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateGetCurrentPathProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Get Current Path"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Create Zip File"); + proto->DeclareOutput("Zip File created"); + proto->DeclareOutParameter("Path",CKPGUID_STRING); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(GetCurrentPath); + *pproto = proto; + return CK_OK; +} + + +int GetCurrentPath(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + + XString Current; + VxGetCurrentDirectory(Current.Str()); + CKParameterOut *pout = beh->GetOutputParameter(0); + pout->SetStringValue(Current.Str()); + beh->ActivateOutput(0); + + return CKBR_OK; + +} + diff --git a/usr/Src/Behaviors/system/GetLastFile.cpp b/usr/Src/Behaviors/system/GetLastFile.cpp new file mode 100644 index 0000000..6c36bec --- /dev/null +++ b/usr/Src/Behaviors/system/GetLastFile.cpp @@ -0,0 +1,75 @@ +#include "CKAll.h" +#include +#include +#include "Shlwapi.h" +#pragma comment (lib,"SHLWAPI.LIB") + + +CKObjectDeclaration *FillBehaviorGetLastFileNameDecl(); +CKERROR CreateGetLastFileNameProto(CKBehaviorPrototype **pproto); +int GetLastFileName(const CKBehaviorContext& behcontext); + + +/************************************************************************/ +/* */ +/************************************************************************/ + +CKObjectDeclaration *FillBehaviorGetLastFileNameDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("GetLastFileName"); + od->SetDescription("Add Objects"); + od->SetCategory("Narratives/Objects"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0xa2e4a61,0x170735ce)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateGetLastFileNameProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateGetLastFileNameProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("GetLastFileName"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Create Zip File"); + proto->DeclareOutput("Zip File created"); + + + proto->DeclareOutParameter("FilePath",CKPGUID_STRING); + proto->DeclareOutParameter("Path",CKPGUID_STRING); + + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(GetLastFileName); + *pproto = proto; + return CK_OK; +} + + +int GetLastFileName(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + XString Inpath (ctx->GetLastCmoLoaded()); + + + + CKParameterOut *pout = beh->GetOutputParameter(0); + pout->SetStringValue(Inpath.Str()); + + PathRemoveFileSpec(Inpath.Str()); + + + CKParameterOut *pout2 = beh->GetOutputParameter(1); + pout2->SetStringValue(Inpath.Str()); + + + + beh->ActivateOutput(0); + + +return 0; + +} \ No newline at end of file diff --git a/usr/Src/Behaviors/system/GetTimeBeh.cpp b/usr/Src/Behaviors/system/GetTimeBeh.cpp new file mode 100644 index 0000000..aa0d588 --- /dev/null +++ b/usr/Src/Behaviors/system/GetTimeBeh.cpp @@ -0,0 +1,68 @@ +#include "CKAll.h" + +CKObjectDeclaration *FillBehaviorGetTime2Decl(); +CKERROR CreateGetTime2Proto(CKBehaviorPrototype **pproto); +int GetTime2(const CKBehaviorContext& behcontext); + +/************************************************************************/ +/* */ +/************************************************************************/ + +CKObjectDeclaration *FillBehaviorGetTime2Decl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("GetTime"); + od->SetDescription("Logics/Tools"); + od->SetCategory("a"); + + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x33ce78ad,0x6e4a5d37)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateGetTime2Proto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateGetTime2Proto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("GetTime"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Create Zip File"); + + proto->DeclareOutput("Zip File created"); + + + proto->DeclareOutParameter("Hour", CKPGUID_INT); + proto->DeclareOutParameter("Minutes", CKPGUID_INT); + proto->DeclareOutParameter("Seconds", CKPGUID_INT); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(GetTime2); + *pproto = proto; + return CK_OK; +} + +int GetTime2(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + + //int hour,minute,second; + //SYSTEMTIME lpSystemTime; + /* + GetSystemTime( &lpSystemTime ); + + hour = lpSystemTime.wHour; + minute = lpSystemTime.wMinute; + second = lpSystemTime.wSecond; + beh->SetOutputParameterValue(0,&hour); + beh->SetOutputParameterValue(1,&minute); + beh->SetOutputParameterValue(2,&second); + beh->ActivateOutput(0); +*/ + return 0; + +} + + diff --git a/usr/Src/Behaviors/system/GoFullScreen.cpp b/usr/Src/Behaviors/system/GoFullScreen.cpp new file mode 100644 index 0000000..c47af4b --- /dev/null +++ b/usr/Src/Behaviors/system/GoFullScreen.cpp @@ -0,0 +1,269 @@ +#include "pch.h" + +#include "CKAll.h" + +CKObjectDeclaration *FillBehaviorGoFullScreenDecl(); +CKERROR CreateGoFullScreenProto(CKBehaviorPrototype **pproto); +int GoFullScreen(const CKBehaviorContext& behcontext); + + +/************************************************************************/ +/* */ +/************************************************************************/ + +CKObjectDeclaration *FillBehaviorGoFullScreenDecl(){ + CKObjectDeclaration *od = CreateCKObjectDeclaration("GoFullScreen"); + + od->SetCategory("Narratives/System"); + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x126046,0x718a4147)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("mw"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateGoFullScreenProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + return od; +} +CKERROR CreateGoFullScreenProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("GoFullScreen"); + if(!proto) return CKERR_OUTOFMEMORY; + proto->DeclareInput("Go"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("driver index",CKPGUID_INT); + proto->DeclareInParameter("width",CKPGUID_INT); + proto->DeclareInParameter("height",CKPGUID_INT); + proto->DeclareInParameter("bpp",CKPGUID_INT); + proto->DeclareInParameter("refreshrate",CKPGUID_INT); + + proto->DeclareInParameter("SwitchToFS",CKPGUID_BOOL); + + proto->DeclareInParameter("mode_index",CKPGUID_INT); + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + + proto->SetFunction(GoFullScreen); + *pproto = proto; + return CK_OK; +} + +#include + + BOOL CALLBACK EnumProcessListFunc( HWND, LPARAM ); + BOOL CALLBACK + EnumProcessListFunc( HWND hWnd, LPARAM lParam ) + { + static DWORD dwCurrentProcessId; + static BOOL fFirstTime = TRUE; + static LONG MaxStrLen = 0; + static TCHAR TextBuffer[256]; + + if( fFirstTime ) { + fFirstTime = FALSE; + dwCurrentProcessId = GetCurrentProcessId(); + } + + if( hWnd ) { + GetWindowText( hWnd, (LPTSTR) &TextBuffer, sizeof(TextBuffer)/sizeof(TCHAR) ); + if( *TextBuffer ) { + DWORD dwProcessId; + + /*GetWindowThreadProcessId( hWnd, &dwProcessId ); + if( dwProcessId != dwCurrentProcessId ) { + LRESULT Index; + HWND hWndListBox = (HWND) lParam; + + //Index = ListBoxInsert( hWndListBox, &MaxStrLen, TextBuffer ); + SendMessage( hWndListBox, LB_SETITEMDATA, (WPARAM) Index, + (LPARAM) dwProcessId ); + }*/ + } + } + + return( TRUE ); + } + + BOOL CALLBACK EnumChildProc(HWND hwnd,LPARAM lParam) + { + + if( hwnd ) + { + static TCHAR TextBuffer[256]; + GetWindowText( hwnd, (LPTSTR) &TextBuffer, sizeof(TextBuffer)/sizeof(TCHAR) ); + if( *TextBuffer ) + { + return true; + + } + }else + return FALSE; + + } +int GoFullScreen(const CKBehaviorContext& behcontext) +{ + + CKBehavior* beh = behcontext.Behavior; + CKContext* ctx = behcontext.Context; + + + CKPluginManager* ThePluginManager=CKGetPluginManager(); + CKRenderManager *rm = (CKRenderManager *)ctx->GetRenderManager(); + + CKRenderContext *rctx = rm->GetRenderContext(0); + int rcount = rm->GetRenderContextCount(); + + int DriverIndex=0; + beh->GetInputParameterValue(0, &DriverIndex); + + int width = 0; + beh->GetInputParameterValue(1, &width); + int height= 0; + beh->GetInputParameterValue(2, &height); + int bpp = 0; + beh->GetInputParameterValue(3, &bpp); + int rr = 0; + beh->GetInputParameterValue(4, &rr); + bool gOFS = false; + beh->GetInputParameterValue(5, &gOFS); + + int mode = 0; + beh->GetInputParameterValue(6, &mode); + + + + + + HWND m_hWndParent = (HWND)ctx->GetMainWindow(); + //turn off + + if(rctx->IsFullScreen() && !gOFS ){ + ctx->Pause(); + rctx->StopFullScreen(); + //ShowWindow(m_hWndParent ,SW_RESTORE); + + RECT m_hWndParent_rect ; + + GetWindowRect(m_hWndParent,&m_hWndParent_rect); + + /* + if (m_hWndParent_rect.bottom!=0 && !rctx->IsFullScreen() ) + { + //allow the window to be resized + LONG st = GetWindowLong(m_hWndParent,GWL_STYLE); + st|=WS_THICKFRAME; + SetWindowLong(m_hWndParent,GWL_STYLE,st); + + int Xpos=(GetSystemMetrics(SM_CXSCREEN)-width)/2; + int Ypos=(GetSystemMetrics(SM_CYSCREEN)-height)/2; + + + //reposition the window + ::SetWindowPos(m_hWndParent,HWND_NOTOPMOST,Xpos,Ypos,m_hWndParent_rect.right - m_hWndParent_rect.left,m_hWndParent_rect.bottom - m_hWndParent_rect.top,NULL); + } +*/ + + + ////////////////////////////////////////////////////////////////////////// + //restore the main window size (only in DirectX rasterizer->m_MainWindowRect.bottom not modified) + if (m_hWndParent_rect.bottom!=0 && !rctx->IsFullScreen()) { + //allow the window to be resized + LONG st = GetWindowLong(m_hWndParent,GWL_STYLE); + st|=WS_THICKFRAME; + st&=~WS_SIZEBOX; + SetWindowLong(m_hWndParent,GWL_STYLE,st); + } + + //reposition the window + m_hWndParent_rect.left = (GetSystemMetrics(SM_CXSCREEN)-width)/2; + m_hWndParent_rect.right = width+m_hWndParent_rect.left; + m_hWndParent_rect.top = (GetSystemMetrics(SM_CYSCREEN)-height)/2; + m_hWndParent_rect.bottom = height+m_hWndParent_rect.top; + BOOL ret = AdjustWindowRect(&m_hWndParent_rect,WS_OVERLAPPEDWINDOW & ~(WS_SYSMENU|WS_SIZEBOX|WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_SIZEBOX),FALSE); + ::SetWindowPos(m_hWndParent,HWND_NOTOPMOST,m_hWndParent_rect.left,m_hWndParent_rect.top,m_hWndParent_rect.right - m_hWndParent_rect.left,m_hWndParent_rect.bottom - m_hWndParent_rect.top,NULL); + + // now we can show the main widnwos + ShowWindow(m_hWndParent,SW_SHOW); + SetFocus(m_hWndParent); + + rctx->Resize(0,0,width,height); + + + HWND rWin = GetWindow(m_hWndParent,GW_CHILD); + if( rWin ) + { + //static TCHAR TextBuffer[256]; + //GetWindowText( rWin, (LPTSTR) &TextBuffer, sizeof(TextBuffer)/sizeof(TCHAR) ); + ::SetWindowPos(rWin,NULL,0,0,width,height,SWP_NOMOVE|SWP_NOZORDER); + //rctx->Resize(0,0,m_WindowedWidth,m_WindowedHeight); + //MessageBox(NULL,TextBuffer,"",NULL); + + } + //EnumChildWindows(m_hWndParent, (WNDENUMPROC) EnumProcessListFunc,NULL ); + + // and set the position of the render window in the main window + //::SetWindowPos(m_RenderWindow,NULL,0,0,m_WindowedWidth,m_WindowedHeight,SWP_NOMOVE|SWP_NOZORDER); + + // and give the focus to the render window + SetFocus(m_hWndParent); + + + ctx->Play(); + beh->ActivateOutput(0); + + return CKBR_OK; + + } + if(!rctx->IsFullScreen() && gOFS ) { + + ctx->Pause(); + int w,h,FSdriver; + if (mode<0) + rctx->GoFullScreen(w=width,h=height,bpp,FSdriver=DriverIndex,rr); + else { + VxDriverDesc *MainDesc=rm->GetRenderDriverDescription(DriverIndex); + if (MainDesc) + rctx->GoFullScreen(w=MainDesc->DisplayModes[mode].Width, + h=MainDesc->DisplayModes[mode].Height, + MainDesc->DisplayModes[mode].Bpp, + FSdriver=DriverIndex,rr); + } + ctx->Play(); + + VxDriverDesc* Check_API_Desc=rm->GetRenderDriverDescription(DriverIndex); + + if (Check_API_Desc->Caps2D.Family==CKRST_DIRECTX && rctx->IsFullScreen()) { + //store current size + RECT g_mainwin_rect; + + GetWindowRect(m_hWndParent,&g_mainwin_rect); + + //Resize the window + ::SetWindowPos(m_hWndParent,HWND_TOPMOST,0,0,w,h,NULL); + + //Prevent the window from beeing resized + LONG st = GetWindowLong(m_hWndParent,GWL_STYLE); + st&=(~WS_THICKFRAME); + SetWindowLong(m_hWndParent,GWL_STYLE,st); + + + + + + + } + + + + + + + + //ShowWindow(m_hWndParent,SW_SHOW|SW_MAXIMIZE); + + beh->ActivateOutput(0); + } + return CKBR_OK; +} + + diff --git a/usr/Src/Behaviors/texture/TextureSinus.cpp b/usr/Src/Behaviors/texture/TextureSinus.cpp new file mode 100644 index 0000000..f1bb98f --- /dev/null +++ b/usr/Src/Behaviors/texture/TextureSinus.cpp @@ -0,0 +1,213 @@ +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +// +// TextureSinus +// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +//#include "precomp.h" + +#include "CKAll.h" +CKObjectDeclaration *FillBehaviorTextureSinusDecl(); +CKERROR CreateTextureSinusProto(CKBehaviorPrototype **); +int TextureSinus(const CKBehaviorContext& behcontext); +CKERROR TextureSinusCallBackObject(const CKBehaviorContext& behcontext); + + +CKObjectDeclaration *FillBehaviorTextureSinusDecl() +{ + CKObjectDeclaration *od = CreateCKObjectDeclaration("Texture Sine2"); + od->SetDescription("Produces a sinusoidal displacement on the UV coords of a mesh's material (or one of its channel)."); + + /* rem: + In: triggers the process
+ Out: is activated when the process is completed.
+
+ X Amplitude: amplitude of sine displacement along the X axis of the texture
+ Y Amplitude: amplitude of sine displacement along the Y axis of the texture.
+ Velocity: radial speed expressed in radian/seconds.
+ Channel: if set to -1, the mapping is calculated only for the default material. + Otherwise it is processed on the specified channel.
+
+ */ + /* warning: + - The initial UV (mapping coordinates) on the mesh for this texture are saved when the building block is attached + to the mesh (that's why we can't target this building block to another mesh than the one + the building block is applied to), therefore you needn't to put Initials Conditions to the mesh if + you wish to recover the initial mapping of the texture.
+ - Beware, not all the building blocks work with this specification (eg: Texture Scroller need IC to recover the initials mapping).
+ - The "Texture Sine" BB is a time based building block (i.e. it will execute at the same speed what ever the frame rate is + [this means you needn't to add a per second building block in front of it]).
+ */ + od->SetType( CKDLL_BEHAVIORPROTOTYPE); + od->SetGuid(CKGUID(0x47e96252,0x632216fe)); + od->SetAuthorGuid(VIRTOOLS_GUID); + od->SetAuthorName("Virtools"); + od->SetVersion(0x00010000); + od->SetCreationFunction(CreateTextureSinusProto); + od->SetCompatibleClassId(CKCID_BEOBJECT); + od->SetCategory("Materials-Textures/Animation"); + return od; +} + + +CKERROR CreateTextureSinusProto(CKBehaviorPrototype **pproto) +{ + CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("Texture Sine2"); + + proto->DeclareInput("In"); + proto->DeclareOutput("Out"); + + proto->DeclareInParameter("X Amplitude", CKPGUID_FLOAT,"0.1" ); + proto->DeclareInParameter("Y Amplitude", CKPGUID_FLOAT ,"0.1"); + proto->DeclareInParameter("Velocity", CKPGUID_FLOAT ,"1"); + proto->DeclareInParameter("Channel", CKPGUID_INT, "-1"); + + proto->DeclareInParameter("target", CKPGUID_MESH, "-1"); + + + proto->DeclareLocalParameter(NULL, CKPGUID_VOIDBUF ); // Data + proto->DeclareLocalParameter(NULL, CKPGUID_FLOAT, "0.0" ); // Time + + proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL); + proto->SetFunction(TextureSinus); + + proto->SetBehaviorCallbackFct(TextureSinusCallBackObject); + + *pproto = proto; + return CK_OK; + +} + +int TextureSinus(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + // we get the amount value + float xamp=0.1f; + beh->GetInputParameterValue(0, &xamp); + + // we get the amount value + float yamp=0.1f; + beh->GetInputParameterValue(1, &yamp); + + float l= 1.0f; + beh->GetInputParameterValue(2, &l); + + // we get the saved uv's + VxUV* savedUV = (VxUV*) beh->GetLocalParameterReadDataPtr(0); + + // we get the interpolated mesh + CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); + + int channel = -1; + beh->GetInputParameterValue(3, &channel); + int channelcount = mesh->GetChannelCount(); + if (channel < -1 || channel >= channelcount) { + beh->ActivateInput(0, FALSE); + beh->ActivateOutput(0); + return CKBR_PARAMETERERROR; + } + + CKDWORD Stride; + VxUV *uvarray = (VxUV*) mesh->GetModifierUVs(&Stride,channel); + int pointsNumber = mesh->GetModifierUVCount(channel); + + float time; + beh->GetLocalParameterValue(1, &time); + + float t; + for( int i=0 ; iu = savedUV[i].u + ( 0.5f - savedUV[i].u ) * xamp * cosf(t); + uvarray->v = savedUV[i].v + ( 0.5f - savedUV[i].v ) * yamp * sinf(t); + } + mesh->ModifierUVMove(channel); + + float pi = 3.1415926535f; + time += behcontext.DeltaTime * 0.001f; + + if(l*time > 2*pi) + time -= (2*pi / l); + + beh->SetLocalParameterValue(1, &time); + + beh->ActivateInput(0, FALSE); + beh->ActivateOutput(0); + return CKBR_OK; +} + + +/*******************************************************/ +/* CALLBACK */ +/*******************************************************/ +CKERROR TextureSinusCallBackObject(const CKBehaviorContext& behcontext) +{ + CKBehavior* beh = behcontext.Behavior; + + switch(behcontext.CallbackMessage) { + + #ifdef macintosh + case CKM_BEHAVIORLOAD: + { + + + CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); + if(!mesh) + return 0; + int nbvert = mesh->GetModifierUVCount(); + // we get the saved uv's + DWORD *savedUV = (DWORD *) beh->GetLocalParameterWriteDataPtr(0); + + for(int i=0;iGetInputParameterObject(4); + if(!mesh) return 0; + + CKDWORD Stride; + VxUV *uvarray = (VxUV*) mesh->GetModifierUVs(&Stride); + int nbvert = mesh->GetModifierUVCount(); + + VxUV *savedUV; + savedUV = new VxUV[nbvert]; + + for(int i=0 ; iSetLocalParameterValue(0, savedUV, nbvert * sizeof(VxUV) ); + + delete[] savedUV; + } + break; + case CKM_BEHAVIORDETACH: + { + // we get the mesh vertices + if(!beh) return 0; + CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); + if(!mesh) return 0; + + CKDWORD Stride; + VxUV *uvarray = (VxUV*) mesh->GetModifierUVs(&Stride); + int nbvert = mesh->GetModifierUVCount(); + + VxUV *savePos = (VxUV*) beh->GetLocalParameterWriteDataPtr(0); + if(!savePos) return 0; + + for(int i=0 ; iModifierUVMove(); + } + + } + return CKBR_OK; +} diff --git a/usr/Src/Behaviors/vtAgeia.cpp b/usr/Src/Behaviors/vtAgeia.cpp new file mode 100644 index 0000000..9242ee3 --- /dev/null +++ b/usr/Src/Behaviors/vtAgeia.cpp @@ -0,0 +1,422 @@ +#include +#include "pCommon.h" +#include "pConfig.h" +#include "gConfig.h" + +#pragma message(__FILE__ NXPHYSXLOADERDLL_API ) + + +void FindResourceX(); + +#ifdef WebPack + extern CKERROR InitInstanceCamera(CKContext* context); + extern CKERROR ExitInstanceCamera(CKContext* context); + extern int RegisterCameraBeh(XObjectDeclarationArray *reg); +#endif + + +//---------------------------------------------------------------- +// +//! \brief Switches between static library or dll +// +#ifdef CK_LIB + #define RegisterBehaviorDeclarations Register_VTPHYSX_BehaviorDeclarations + #define InitInstance _VTPHYSX_InitInstance + #define ExitInstance _VTPHYSX_ExitInstance + #define CKGetPluginInfoCount CKGet_VTPHYSX_PluginInfoCount + #define CKGetPluginInfo CKGet_VTPHYSX_PluginInfo + #define g_PluginInfo g_PluginInfo +#else + #define RegisterBehaviorDeclarations RegisterBehaviorDeclarations + #define InitInstance InitInstance + #define ExitInstance ExitInstance + #define CKGetPluginInfoCount CKGetPluginInfoCount + #define CKGetPluginInfo CKGetPluginInfo + #define g_PluginInfo g_PluginInfo +#endif + +/* +******************************************************************* +* Function: CKERROR InitInstance( CKContext* theContext ) +* +* Description : If no manager is used in the plugin these functions +* are optional and can be exported. Virtools will call +* 'InitInstance' when loading the behavior library and +* 'ExitInstance' when unloading it. It is a good place +* to perform Attributes Types declaration, registering new +* enums or new parameter types. +* +* Parameters : CKContext* theContext +* +* +* Returns : CKERROR +* +******************************************************************* +*/ +CKERROR InitInstanceBB(CKContext* context) +{ + + + return CK_OK; +} + +CKERROR ExitInstanceBB(CKContext* context) +{ + + + return CK_OK; +} + +/* +******************************************************************* +* Function: CKERROR InitInstance( CKContext* theContext ) +* +* Description : If no manager is used in the plugin these functions +* are optional and can be exported. Virtools will call +* 'InitInstance' when loading the behavior library and +* 'ExitInstance' when unloading it. It is a good place +* to perform Attributes Types declaration, registering new +* enums or new parameter types. +* +* Parameters : CKContext* theContext +* +* +* Returns : CKERROR +* +******************************************************************* +*/ +CKERROR InitInstanceIM(CKContext* context){ + + +#ifdef Webpack + InitInstanceCamera(context); +#endif + + PhysicManager* PM =new PhysicManager(context); + context->ActivateManager(PM,TRUE); + +#ifdef DONGLE_VERSION + PM->_initResources(0); +#endif + +#ifndef DONGLE_VERSION + PM->DongleHasBasicVersion =1; +#endif // _DEBUG + + + if(PM->DongleHasBasicVersion) + { + + PM->_RegisterDynamicParameters(); + PM->_RegisterParameters(); + PM->_RegisterVSL(); + + +#ifdef HAS_FLUIDS + PM->_RegisterFluid_VSL(); +#endif // HAS_FLUIDS + PM->_RegisterParameterOperations(); + PM->_registerWatchers(context); + } + return CK_OK; +} + +/* +******************************************************************* +* Function: CKERROR ExitInstance( CKContext* theContext ) +* +* Description : This function will only be called if the dll is +* unloaded explicitely by a user in Virtools Dev interface +* Otherwise the manager destructor will be called by Virtools +* runtime directly. +* +* Parameters : CKContext* theContext +* +* Returns : CKERROR +* +******************************************************************* +*/ +CKERROR ExitInstanceIM(CKContext* context){ + PhysicManager* PM =(PhysicManager*)context->GetManagerByGuid(GUID_MODULE_MANAGER); + delete PM; + + #ifdef Webpack + ExitInstanceCamera(context); + #endif + + + + return CK_OK; +} + + + +CKPluginInfo g_PluginInfo[2]; +#include "base_macros.h" + + + + +/* +******************************************************************* +* Function: CKPluginInfo* CKGetPluginInfo( int index ) +* +* Description : This function takes an index and returns a corresponding plugin desciptor +* +* Parameters : +* index, index of the plugin information to get +* +* Returns : pointer to the requested plugin information +* +******************************************************************* +*/ +PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index); + +/* +******************************************************************* +* Function: int CKGetPluginInfoCount() +* +* Description : Returns the number of plugins in this DLL +* +* Parameters : +* None. +* +* Returns : Number of plugins defined in this DLL +* +******************************************************************* +*/ +int CKGetPluginInfoCount(){return 2;} +PLUGIN_EXPORT void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg); + + + +PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) +{ + g_PluginInfo[0].m_Author = VTCX_AUTHOR; + g_PluginInfo[0].m_Description = VTCX_API_ENTRY("PhysX Building Blocks"); + g_PluginInfo[0].m_Extension = ""; + g_PluginInfo[0].m_Type = CKPLUGIN_BEHAVIOR_DLL; + g_PluginInfo[0].m_Version = 0x000001; + g_PluginInfo[0].m_InitInstanceFct = InitInstanceBB; + g_PluginInfo[0].m_ExitInstanceFct = ExitInstanceBB; + g_PluginInfo[0].m_GUID = GUID_MODULE_BUILDING_BLOCKS; + + g_PluginInfo[1].m_Author =VTCX_AUTHOR; + g_PluginInfo[1].m_Description =VTCX_API_ENTRY("PhysX Manager"); + g_PluginInfo[1].m_Extension = ""; + g_PluginInfo[1].m_Type = CKPLUGIN_MANAGER_DLL; + g_PluginInfo[1].m_Version = 0x000001; + g_PluginInfo[1].m_InitInstanceFct = InitInstanceIM; + g_PluginInfo[1].m_ExitInstanceFct = ExitInstanceIM; + g_PluginInfo[1].m_GUID = GUID_MODULE_MANAGER; + g_PluginInfo[1].m_Summary = VTCX_API_ENTRY("PhysX Physic Manager"); + + + return &g_PluginInfo[Index]; +} + +/* +******************************************************************* +* Function: void RegisterBehaviorDeclarations( XObjectDeclarationArray *reg ) +* +* Description : +* +* Parameters : +* param rw/r/w param description +* +* Returns : +* +******************************************************************* +*/ + +void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) +{ + + + //---------------------------------------------------------------- + // + // generic building blocks + // + +#ifdef BBC_TOOLS + RegisterBehavior(reg,FillBehaviorGetNextBBIdDecl); +#endif +/* +#ifdef BBC_JOYSTICK + RegisterBehavior(reg,FillBehaviorHasFFEffectsDecl); + RegisterBehavior(reg,FillBehaviorJSetXYForceDecl); +#endif + */ + + /************************************************************************/ + /* Bodies: */ + /************************************************************************/ + + RegisterBehavior(reg,FillBehaviorPBPhysicalizeDecl); + + RegisterBehavior(reg,FillBehaviorPBAddTorqueDecl); + RegisterBehavior(reg,FillBehaviorPBAddForceDecl); + + RegisterBehavior(reg,FillBehaviorPBAddForceAtLocalPosDecl); + RegisterBehavior(reg,FillBehaviorPBAddLocalForceDecl); + RegisterBehavior(reg,FillBehaviorPBAddLocalForceAtPosDecl); + RegisterBehavior(reg,FillBehaviorPBAddLocalForceAtLocalPosDecl); + RegisterBehavior(reg,FillBehaviorPBAddLocalTorqueDecl); + + RegisterBehavior(reg,FillBehaviorAddForceAtPosDecl); + + + RegisterBehavior(reg,FillBehaviorPBSetDecl); + RegisterBehavior(reg,FillBehaviorPBSet2Decl); + + RegisterBehavior(reg,FillBehaviorPBSetParDecl); + RegisterBehavior(reg,FillBehaviorPBPhysicalizeExDecl); + RegisterBehavior(reg,FillBehaviorPBAddShapeExDecl); + + RegisterBehavior(reg,FillBehaviorPBSetHardDecl); + + + + RegisterBehavior(reg,FillBehaviorPBGetDecl); + RegisterBehavior(reg,FillBehaviorPBGet2Decl); + + + RegisterBehavior(reg,FillBehaviorPBGetParameterDecl); + RegisterBehavior(reg,FillBehaviorPBGetVelocitiesAndForcesDecl); + + RegisterBehavior(reg,FillBehaviorPBDestroyDecl); + +#ifdef BBC_JOINTS + /************************************************************************/ + /* D6 */ + /************************************************************************/ + + RegisterBehavior(reg,FillBehaviorPJGroupBreakIteratorDecl); + + RegisterBehavior(reg,FillBehaviorJSetD6Decl); + RegisterBehavior(reg,FillBehaviorJD6SetMotionModeDecl); + RegisterBehavior(reg,FillBehaviorJD6SetSoftLimitDecl); + RegisterBehavior(reg,FillBehaviorJD6SetDriveDecl); + RegisterBehavior(reg,FillBehaviorJD6SetParametersDecl); + + /************************************************************************/ + /* Joints */ + /************************************************************************/ + RegisterBehavior(reg,FillBehaviorJSetBallDecl); + RegisterBehavior(reg,FillBehaviorPJSetBreakForcesDecl); + RegisterBehavior(reg,FillBehaviorJSetFixedDecl); + RegisterBehavior(reg,FillBehaviorPJIsBrokenDecl); + RegisterBehavior(reg,FillBehaviorJDestroyDecl); + RegisterBehavior(reg,FillBehaviorPJCreateDistanceJointDecl); + RegisterBehavior(reg,FillBehaviorPJRevoluteDecl); + RegisterBehavior(reg,FillBehaviorPJIteratorDecl); + + RegisterBehavior(reg,FillBehaviorPJPulleyDecl); + RegisterBehavior(reg,FillBehaviorPJPrismaticDecl); + RegisterBehavior(reg,FillBehaviorPJCylindricalDecl); + RegisterBehavior(reg,FillBehaviorPJPointPlaneDecl); + RegisterBehavior(reg,FillBehaviorPJPointOnLineDecl); + RegisterBehavior(reg,FillBehaviorPJAddLimitPlaneDecl); +#endif // BBC_JOINTS + + + + + /************************************************************************/ + /* collision */ + /************************************************************************/ + + RegisterBehavior(reg,FillBehaviorPWSetCollisionGroupFlagDecl); + RegisterBehavior(reg,FillBehaviorPCIgnorePairDecl); + RegisterBehavior(reg,FillBehaviorCollisionsCheckADecl); + RegisterBehavior(reg,FillBehaviorPBSetTriggerMaskDecl); + RegisterBehavior(reg,FillBehaviorPCTriggerEventDecl); + RegisterBehavior(reg,FillBehaviorPCGroupTriggerEventDecl); + + + /************************************************************************/ + /* Shapes : */ + /************************************************************************/ + + RegisterBehavior(reg,FillBehaviorPBAddShapeDecl); + RegisterBehavior(reg,FillBehaviorPBRemoveShapeDecl); + + RegisterBehavior(reg,FillBehaviorPBSetCallbackDecl); + + + /************************************************************************/ + /* Clothes : */ + /************************************************************************/ + + +#ifdef DONGLE_VERSION + if(!PhysicManager::DongleHasAdvancedVersion) + return; +#endif + + +#ifdef BBC_CLOTHES + + + RegisterBehavior(reg,FillBehaviorPClothDecl); + RegisterBehavior(reg,FillBehaviorPClothAttachToShapeDecl); + //RegisterBehavior(reg,FillBehaviorPClothAttachToCoreDecl); + + RegisterBehavior(reg,FillBehaviorPClothAttachVertexToShapeDecl); + RegisterBehavior(reg,FillBehaviorPClothAttachVertexToPositionDecl); + RegisterBehavior(reg,FillBehaviorPClothFreeVertexDecl); + RegisterBehavior(reg,FillBehaviorPClothDominateVertexDecl); + RegisterBehavior(reg,FillBehaviorPClothDetachFromShapeDecl); + RegisterBehavior(reg,FillBehaviorPClothDestroyDecl); + RegisterBehavior(reg,FillBehaviorPClothAddForceAtPosDecl); + RegisterBehavior(reg,FillBehaviorPClothAddForceAtVertexDecl); + RegisterBehavior(reg,FillBehaviorPClothAddDirectedForceAtPosDecl); + +#endif + + RegisterBehavior(reg,FillBehaviorPWSetFilteringDecl); + RegisterBehavior(reg,FillBehaviorPWRayCastAllShapeDecl); + RegisterBehavior(reg,FillBehaviorPWRayCastAnyBoundsDecl); + RegisterBehavior(reg,FillBehaviorPWOverlapSphereDecl); + + RegisterBehavior(reg,FillBehaviorPWOBBOverlapDecl); + ////////////////////////////////////////////////////////////////////////// + // + // Vehicles and Wheels : + +#ifdef BBC_VEHICLES + RegisterBehavior(reg,FillBehaviorPVWGetDecl); + RegisterBehavior(reg,FillBehaviorPVWSetDecl); + RegisterBehavior(reg,FillBehaviorPVSetDecl); + RegisterBehavior(reg,FillBehaviorPVSetExDecl); + RegisterBehavior(reg,FillBehaviorPVControlDecl); + + RegisterBehavior(reg,FillBehaviorPVSetMotorValuesDecl); + RegisterBehavior(reg,FillBehaviorPVSetGearsDecl); + RegisterBehavior(reg,FillBehaviorPVControl2Decl); + RegisterBehavior(reg,FillBehaviorPVSetBreakSettingsDecl); + RegisterBehavior(reg,FillBehaviorPVGetDecl); +#endif + + /////////////////////////////////////////////////////////////////////////// + // + // Material + RegisterBehavior(reg,FillBehaviorPBSetMaterialDecl); + + /////////////////////////////////////////////////////////////////////////// + // + // Material + + RegisterBehavior(reg,FillBehaviorPManagerDecl); + RegisterBehavior(reg,FillBehaviorRegisterAttributeTypeDecl); + + RegisterBehavior(reg,FillBehaviorLogEntryDecl); + RegisterBehavior(reg,FillBehaviorPMaterialIteratorDecl); + + + + #ifdef WebPack + RegisterCameraBeh(reg); + #endif + +} diff --git a/usr/Src/Behaviors/vtAgeia.def b/usr/Src/Behaviors/vtAgeia.def new file mode 100644 index 0000000..4592590 --- /dev/null +++ b/usr/Src/Behaviors/vtAgeia.def @@ -0,0 +1,4 @@ +EXPORTS + CKGetPluginInfo + CKGetPluginInfoCount + RegisterBehaviorDeclarations diff --git a/usr/Src/Behaviors/vtTools.cpp b/usr/Src/Behaviors/vtTools.cpp new file mode 100644 index 0000000..6320205 --- /dev/null +++ b/usr/Src/Behaviors/vtTools.cpp @@ -0,0 +1,111 @@ +// DataRelay.cpp : Defines the initialization routines for the plugin DLL. +// +#include "CKAll.h" +#include "DataManager.h" + +#include "bginstancer.h" +#include "gblasyncblock.h" + + + +#ifdef CK_LIB +#define RegisterBehaviorDeclarations Register_TOOLS_BehaviorDeclarations +#define InitInstance _TOOLS_InitInstance +#define ExitInstance _TOOLS_ExitInstance +#define CKGetPluginInfoCount CKGet_TOOLS_PluginInfoCount +#define CKGetPluginInfo CKGet_TOOLS_PluginInfo +#define g_PluginInfo g_TOOLS_PluginInfo +#else +#define RegisterBehaviorDeclarations RegisterBehaviorDeclarations +#define InitInstance InitInstance +#define ExitInstance ExitInstance +#define CKGetPluginInfoCount CKGetPluginInfoCount +#define CKGetPluginInfo CKGetPluginInfo +#define g_PluginInfo g_PluginInfo +#endif + +CKERROR InitInstance(CKContext* context); +CKERROR ExitInstance(CKContext* context); + +#define PLUGIN_COUNT 2 + +CKPluginInfo g_PluginInfo[PLUGIN_COUNT]; + +PLUGIN_EXPORT int CKGetPluginInfoCount(){return 2;} + + +PLUGIN_EXPORT CKPluginInfo* CKGetPluginInfo(int Index) +{ + int Plugin = 0; + g_PluginInfo[Plugin].m_Author = "Virtools"; + g_PluginInfo[Plugin].m_Description = "Generic tools"; + g_PluginInfo[Plugin].m_Extension = ""; + g_PluginInfo[Plugin].m_Type = CKPLUGIN_BEHAVIOR_DLL; + g_PluginInfo[Plugin].m_Version = 0x00010000; + g_PluginInfo[Plugin].m_InitInstanceFct = NULL; + g_PluginInfo[Plugin].m_GUID = CKGUID(0xbd1e1d69, 0x0ee9fdca); + g_PluginInfo[Plugin].m_Summary = "Collection of generic tools"; + Plugin++; + g_PluginInfo[Plugin].m_Author = "Virtools"; + g_PluginInfo[Plugin].m_Description = "Tools manager"; + g_PluginInfo[Plugin].m_Extension = ""; + g_PluginInfo[Plugin].m_Type = CKPLUGIN_MANAGER_DLL; + g_PluginInfo[Plugin].m_Version = 0x00010000; + g_PluginInfo[Plugin].m_InitInstanceFct = InitInstance; + g_PluginInfo[Plugin].m_ExitInstanceFct = ExitInstance; + g_PluginInfo[Plugin].m_GUID = DataManagerGUID; + g_PluginInfo[Plugin].m_Summary = "Tool manager"; + return &g_PluginInfo[Index]; +} + +// If no manager is used in the plugin +// these functions are optional and can be exported. +// Virtools will call 'InitInstance' when loading the behavior library +// and 'ExitInstance' when unloading it. +// It is a good place to perform Attributes Types declaration, +// registering new enums or new parameter types. + +CKERROR InitInstance(CKContext* context) +{ + new DataManager(context); + return CK_OK; +} + +CKERROR ExitInstance(CKContext* context) +{ + // This function will only be called if the dll is unloaded explicitely + // by a user in Virtools Dev interface + // Otherwise the manager destructor will be called by Virtools runtime directly + delete context->GetManagerByGuid(DataManagerGUID); + return CK_OK; +} + +void RegisterBehaviorDeclarations(XObjectDeclarationArray *reg) +{ + + ::CKStoreDeclaration(reg, BGWrapper::FillBehaviour()); + ::CKStoreDeclaration(reg, ExeInThread::FillBehaviour()); + + RegisterBehavior(reg,FillBehaviorGetAdaptersDecl); + RegisterBehavior(reg,FillBehaviorGetAdaptersModieDecl); + RegisterBehavior(reg,FillBehaviorGoFullScreenDecl); + + + + RegisterBehavior(reg, FillBehaviorHasFFEffectsDecl); + RegisterBehavior(reg, FillBehaviorJSetXYForceDecl); + + + RegisterBehavior(reg,FillBehaviorGetCurrentPathDecl); + + RegisterBehavior(reg,FillBehaviorDirToArrayDecl); + + + +} + + + + + + diff --git a/usr/Src/Behaviors/vtTools.def b/usr/Src/Behaviors/vtTools.def new file mode 100644 index 0000000..4592590 --- /dev/null +++ b/usr/Src/Behaviors/vtTools.def @@ -0,0 +1,4 @@ +EXPORTS + CKGetPluginInfo + CKGetPluginInfoCount + RegisterBehaviorDeclarations diff --git a/usr/Src/Core/3D/DXDiagNVUtil.cpp b/usr/Src/Core/3D/DXDiagNVUtil.cpp new file mode 100644 index 0000000..9456d12 --- /dev/null +++ b/usr/Src/Core/3D/DXDiagNVUtil.cpp @@ -0,0 +1,770 @@ +/*********************************************************************NVMH4**** +Path: SDK\LIBS\src\NV_D3DCommon +File: DXDiagNVUtil.cpp + +Copyright NVIDIA Corporation 2002 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED +*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS +BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES +WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, +BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) +ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +Comments: +See the DXDiagNVUtil.h file for additional comments + +******************************************************************************/ + + +#define INITGUID // to define _CLSID_DxDiagProvider, _IID_IDxDiagProvider + +#include "3d\DxDiagNVUtil.h" +#include // for _filelength() +#include // for getcwd() +#include // for L text macro +#include +#include + +#pragma comment( lib, "dxguid.lib" ) + +// use #if 1 to turn trace messages on +#if 0 + #define TRACE0(v) v +#else + #define TRACE0(v) {} +#endif + + + +// use as an alternative to wcstombs() +string DXDiagNVUtil::WStringToString( const wstring * in_pwstring ) +{ + if( in_pwstring == NULL ) + return( "" ); + + return( lpcwstrToString( in_pwstring->c_str() )); +} + +string DXDiagNVUtil::WStringToString( wstring & in_wstring ) +{ + return( lpcwstrToString( in_wstring.c_str() )); +} + + +string DXDiagNVUtil::lpcwstrToString( const LPCWSTR in_lpcwstr ) +{ + //@ consider using windows.h WideCharToMultiByte(..) + char * mbBuf; + size_t sz; + sz = 2 * wcslen( in_lpcwstr ); + mbBuf = new char[sz]; + wcstombs( mbBuf, in_lpcwstr, sz ); // convert the string + string outstr; + outstr = mbBuf; + SAFE_ARRAY_DELETE( mbBuf ); + return( outstr ); +} + + +HRESULT DXDiagNVUtil::GetChildByIndex( IDxDiagContainer * pParent, + DWORD dwIndex, + IDxDiagContainer ** ppChild ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( pParent ); + FAIL_IF_NULL( ppChild ); + + // We need to look up the child by name, not by index, so first + // get the name of the child at the appropriate index. + + // Get a single child container name, writing the name to wstr + WCHAR wstr[256]; + hr = pParent->EnumChildContainerNames( dwIndex, wstr, 256 ); + RET_VAL_IF_FAILED( hr ); + + // Now get the child container by name + hr = pParent->GetChildContainer( wstr, ppChild ); + return( hr ); +} + + +HRESULT DXDiagNVUtil::GetNumDisplayDevices( DWORD * out_pdwNumAdapters ) +{ + HRESULT hr = S_OK; + MSGVARNAME_AND_FAIL_IF_NULL( m_pDxDiagRoot ); + MSGVARNAME_AND_FAIL_IF_NULL( out_pdwNumAdapters ); + + IDxDiagContainer * pChild; + hr = GetChildContainer( L"DxDiag_DisplayDevices", & pChild ); + MSG_AND_RET_VAL_IF( FAILED(hr), "GetNumDisplayDevices() Couldn't get display devices container!\n", hr ); + + hr = pChild->GetNumberOfChildContainers( out_pdwNumAdapters ); + MSG_AND_BREAK_IF( FAILED(hr), "GetNumDisplayDevices() Couldn't get number of child containers!\n" ); + + SAFE_RELEASE( pChild ); + return( hr ); +} + + +HRESULT DXDiagNVUtil::GetDisplayDeviceNode( DWORD dwDeviceIndex, IDxDiagContainer ** ppNode ) +{ + // fill *ppNode with pointer to the display device at index nDevice of the DXDiag_DisplayDevices container + // you must SAFE_RELEASE( *ppNode ) outside of this function. + HRESULT hr = S_OK; + FAIL_IF_NULL( ppNode ); + + IDxDiagContainer * pDevicesNode; + hr = GetChildContainer( L"DxDiag_DisplayDevices", & pDevicesNode ); + MSG_AND_RET_VAL_IF( FAILED(hr), "GetDisplayDeviceNode() couldn't get devices node!\n", hr ); + + // Get the device at the appropriate index + hr = GetChildByIndex( pDevicesNode, dwDeviceIndex, ppNode ); + + SAFE_RELEASE( pDevicesNode ); + return( hr ); +} + + + +HRESULT DXDiagNVUtil::GetDisplayDeviceDescription( DWORD dwDevice, wstring * pwstrName ) +{ + HRESULT hr = S_OK; + MSGVARNAME_AND_FAIL_IF_NULL( m_pDxDiagRoot ); + MSGVARNAME_AND_FAIL_IF_NULL( pwstrName ); + + IDxDiagContainer * pDisplayDevice; + hr = GetDisplayDeviceNode( dwDevice, &pDisplayDevice ); + RET_VAL_IF_FAILED( hr ); + FAIL_IF_NULL( pDisplayDevice ); + + // Get the device's name: + hr = GetProperty( pDisplayDevice, L"szDescription", pwstrName ); + MSG_IF( FAILED(hr), "GetDisplayDeviceName() Couldn't get device's name property!\n"); + + SAFE_RELEASE( pDisplayDevice ); + return( hr ); +} + +HRESULT DXDiagNVUtil::GetDisplayDeviceNVDriverVersion( DWORD dwDevice, float * fVersion ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( fVersion ); + *fVersion = 0.0f; + wstring wstr; + + hr = GetDisplayDeviceDriverVersionStr( dwDevice, & wstr ); + MSG_IF( FAILED(hr), "GetDisplayDeviceNVDriverVersion() couldn't get driver version string\n"); + RET_VAL_IF_FAILED(hr); + + // nv driver string will be something like: "6.14.0010.5216" + // where the #s we care about are the last digits + size_t pos; + pos = wstr.find_last_of( '.' ); + wstr.erase( 0, pos ); + //FMsgW(L"wstr: %s\n", wstr.c_str() ); + + // decode the string + // multiply by 100 to convert .5216 into 52.16 + *fVersion = (float) _wtof( wstr.c_str() ) * 100.0f; + return( hr ); +} + +HRESULT DXDiagNVUtil::GetDisplayDeviceDriverVersionStr( DWORD dwDevice, wstring * pwstrVers ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( pwstrVers ); + + hr = GetDisplayDeviceProp( dwDevice, L"szDriverVersion", pwstrVers ); + MSG_IF( FAILED(hr), "GetDisplayDeviceName() Couldn't get device's driver version string!\n"); + + return( hr ); +} + + +HRESULT DXDiagNVUtil::GetDisplayDeviceMemoryInMB( DWORD dwDevice, int * pDisplayMemory ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( pDisplayMemory ); + *pDisplayMemory = 0; + wstring wstr; + hr = GetDisplayDeviceProp( dwDevice, L"szDisplayMemoryEnglish", &wstr ); + MSG_IF( FAILED(hr), "GetDisplayDeviceMemoryInMB() Couldn't get the property string!\n"); + + // decode the value to an int + // assume 1st string is the integer number + int nMem; + int num_fields; + num_fields = swscanf( wstr.c_str(), L"%d", &nMem ); + if( num_fields != 1 ) + { + FMsg("GetDisplayDeviceMemoryInMB error scanning memory string description!\n"); + return( E_FAIL ); + } + + *pDisplayMemory = nMem; + return( hr ); +} + +HRESULT DXDiagNVUtil::GetDisplayDeviceProp( DWORD dwDevice, LPCWSTR prop_name, wstring * pwstrProp ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( prop_name ); + FAIL_IF_NULL( pwstrProp ); + *pwstrProp = L""; + + IDxDiagContainer * pDisplayDevice; + hr = GetDisplayDeviceNode( dwDevice, &pDisplayDevice ); + RET_VAL_IF_FAILED( hr ); + FAIL_IF_NULL( pDisplayDevice ); + + hr = GetProperty( pDisplayDevice, prop_name, pwstrProp ); + MSG_IF( FAILED(hr), "GetDisplayDeviceProp() Couldn't get the property string!\n"); + + return( hr ); +} + +HRESULT DXDiagNVUtil::GetPhysicalMemoryInMB( float * out_pfMemory ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( out_pfMemory ); + wstring property; + hr = GetProperty( L"DxDiag_SystemInfo", L"ullPhysicalMemory", &property ); + + float mem = (float) _wtof( property.c_str() ); + // convert bytes to MB + mem = mem / (1024 * 1024); + *out_pfMemory = mem; + return( hr ); +} + +HRESULT DXDiagNVUtil::GetDisplayDeviceAGPMemoryStatus( DWORD dwDeviceIndex, wstring * pwstrAGPEnabled, + wstring * pwstrAGPExists, wstring * pwstrAGPStatus ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( m_pDxDiagRoot ); + FAIL_IF_NULL( pwstrAGPEnabled ); + FAIL_IF_NULL( pwstrAGPExists ); + FAIL_IF_NULL( pwstrAGPStatus ); + *pwstrAGPEnabled = L""; + *pwstrAGPExists = L""; + *pwstrAGPStatus = L""; + hr = GetDisplayDeviceProp( dwDeviceIndex, L"bAGPEnabled", pwstrAGPEnabled ); + hr = GetDisplayDeviceProp( dwDeviceIndex, L"szAGPStatusEnglish", pwstrAGPStatus ); + + wstring property; + hr = GetDisplayDeviceProp( dwDeviceIndex, L"bAGPExistenceValid", &property ); + if( SUCCEEDED(hr) && property == L"true" ) + { + hr = GetDisplayDeviceProp( dwDeviceIndex, L"bAGPExists", pwstrAGPExists ); + } + return( hr ); +} + + +HRESULT DXDiagNVUtil::GetDebugLevels( wstring * pwstrLevels ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( pwstrLevels ); + *pwstrLevels = L""; + wstring propval; + + hr = GetProperty( L"DxDiag_SystemInfo", L"nD3DDebugLevel", &propval ); + pwstrLevels->append( L"D3DDebugLevel = "); pwstrLevels->append( propval ); pwstrLevels->append(L"\n"); + + hr = GetProperty( L"DxDiag_SystemInfo", L"nDDrawDebugLevel", &propval ); + pwstrLevels->append( L"DDrawDebugLevel = "); pwstrLevels->append( propval ); pwstrLevels->append(L"\n"); + + hr = GetProperty( L"DxDiag_SystemInfo", L"nDIDebugLevel", &propval ); + pwstrLevels->append( L"DIDebugLevel = "); pwstrLevels->append( propval ); pwstrLevels->append(L"\n"); + + hr = GetProperty( L"DxDiag_SystemInfo", L"nDMusicDebugLevel", &propval ); + pwstrLevels->append( L"DMusicDebugLevel = "); pwstrLevels->append( propval ); pwstrLevels->append(L"\n"); + + hr = GetProperty( L"DxDiag_SystemInfo", L"nDPlayDebugLevel", &propval ); + pwstrLevels->append( L"DPlayDebugLevel = "); pwstrLevels->append( propval ); pwstrLevels->append(L"\n"); + + hr = GetProperty( L"DxDiag_SystemInfo", L"nDSoundDebugLevel", &propval ); + pwstrLevels->append( L"DSoundDebugLevel = "); pwstrLevels->append( propval ); pwstrLevels->append(L"\n"); + + hr = GetProperty( L"DxDiag_SystemInfo", L"nDShowDebugLevel", &propval ); + pwstrLevels->append( L"DShowDebugLevel = "); pwstrLevels->append( propval ); pwstrLevels->append(L"\n"); + + return( hr ); +} + +HRESULT DXDiagNVUtil::GetDirectXVersion( DWORD * pdwDirectXVersionMajor, + DWORD * pdwDirectXVersionMinor, + TCHAR * pcDirectXVersionLetter ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( m_pDxDiagRoot ); + FAIL_IF_NULL( pdwDirectXVersionMajor ); + FAIL_IF_NULL( pdwDirectXVersionMinor ); + FAIL_IF_NULL( pcDirectXVersionLetter ); + + wstring propval; + GetProperty( L"DxDiag_SystemInfo", L"dwDirectXVersionMajor", &propval ); + *pdwDirectXVersionMajor = _wtoi( propval.c_str() ); + + GetProperty( L"DxDiag_SystemInfo", L"dwDirectXVersionMinor", &propval ); + *pdwDirectXVersionMinor = _wtoi( propval.c_str() ); + + GetProperty( L"DxDiag_SystemInfo", L"szDirectXVersionLetter", &propval ); + string str; + + str = WStringToString( &propval ); + if( str.length() > 0 ) + *pcDirectXVersionLetter = str.at(0); + else + *pcDirectXVersionLetter = ' '; + + return( hr ); +} + + + +//------------------------------------------------------------------------ +// Get the property at pContainer by name +// Decode the VARIANT property to a string and return the string +HRESULT DXDiagNVUtil::GetProperty( IDxDiagContainer * pContainer, LPCWSTR property_name, wstring * out_value ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( pContainer ); + FAIL_IF_NULL( property_name ); + FAIL_IF_NULL( out_value ); + + WCHAR wszPropValue[256]; + VARIANT var; + VariantInit( &var ); + + hr = pContainer->GetProp( property_name, &var ); + if( SUCCEEDED(hr) ) + { + // Switch according to the type. There's 4 different types: + switch( var.vt ) + { + case VT_UI4: + swprintf( wszPropValue, L"%d", var.ulVal ); + break; + case VT_I4: + swprintf( wszPropValue, L"%d", var.lVal ); + break; + case VT_BOOL: + swprintf( wszPropValue, L"%s", (var.boolVal) ? L"true" : L"false" ); + break; + case VT_BSTR: + wcsncpy( wszPropValue, var.bstrVal, 255 ); + wszPropValue[255] = 0; + break; + } + // copy string to the output string + (*out_value) = wszPropValue; + } + else + { + FMsgW(L"GetProperty( cont, prop, val ) Couldn't get prop [%s]\n", property_name ); + //char mbBuf[512]; + //wcstombs( mbBuf, property_name, 512 ); + //FMsg("GetProperty( cont, prop, val ) Couldn't get prop [%s]\n", mbBuf ); + } + + VariantClear( &var ); + return( hr ); +} + + +HRESULT DXDiagNVUtil::GetProperty( LPCWSTR container_name0, + LPCWSTR property_name, + wstring * out_value ) +{ + HRESULT hr = S_OK; + + IDxDiagContainer * pContainer; + hr = GetChildContainer( container_name0, &pContainer ); + TRACE0( MSG_IF( FAILED(hr), "GetProperty(cn,pn,&v) GetChildContainer(<1>) failed!\n" )); + RET_VAL_IF_FAILED( hr ); + FAIL_IF_NULL( pContainer ); + + hr = GetProperty( pContainer, property_name, out_value ); + TRACE0( MSG_IF( FAILED(hr), "GetProperty(<1>) pContainer->GetProperty(c,n,v) failed!\n")); + + SAFE_RELEASE( pContainer ); + return( hr ); +} + +HRESULT DXDiagNVUtil::GetProperty( LPCWSTR container_name0, + LPCWSTR container_name1, + LPCWSTR property_name, + wstring * out_value ) +{ + HRESULT hr = S_OK; + + IDxDiagContainer * pContainer; + hr = GetChildContainer( container_name0, container_name1, &pContainer ); + MSG_AND_RET_VAL_IF( FAILED(hr), "GetProperty(cn,cn,pn,&v) couldn't get child container!\n", hr ); + + hr = GetProperty( pContainer, property_name, out_value ); + MSG_AND_RET_VAL_IF( FAILED(hr), "GetProperty(cn,cn,pn,&v) couldn't get container property!\n", hr ); + + SAFE_RELEASE( pContainer ); + return( hr ); +} + +HRESULT DXDiagNVUtil::GetProperty( LPCWSTR container_name0, + LPCWSTR container_name1, + LPCWSTR container_name2, + LPCWSTR property_name, + wstring * out_value ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( out_value ); + IDxDiagContainer * pContainer; + hr = GetChildContainer( container_name0, container_name1, container_name2, &pContainer ); + MSG_AND_RET_VAL_IF( FAILED(hr), "GetProperty(cn,cn,cn,pn,&v) couldn't get child container!\n", hr ); + + hr = GetProperty( pContainer, property_name, out_value ); + MSG_AND_RET_VAL_IF( FAILED(hr), "GetProperty(cn,cn,cn,pn,&v) couldn't get container property!\n", hr ); + + SAFE_RELEASE( pContainer ); + return( hr ); +} + + + +//------------------------------ + +HRESULT DXDiagNVUtil::GetChildContainer( LPCWSTR name0, IDxDiagContainer ** ppChild ) +{ + // you must release *ppChild on your own when you're done with it + HRESULT hr = S_OK; + MSGVARNAME_AND_FAIL_IF_NULL( m_pDxDiagRoot ); + MSGVARNAME_AND_FAIL_IF_NULL( ppChild ); + + hr = m_pDxDiagRoot->GetChildContainer( name0, ppChild ); + TRACE0( MSG_IF( FAILED(hr), "GetChildContainer(<1>) m_pDxDiagRoot->GetChildContainer() failed\n" )); + RET_VAL_IF_FAILED( hr ); + FAIL_IF_NULL( *ppChild ); + + return( hr ); +} + +HRESULT DXDiagNVUtil::GetChildContainer( LPCWSTR name0, + LPCWSTR name1, + IDxDiagContainer ** ppChild ) +{ + // intermediate children are released before returning + // you only have to release() *ppChild + HRESULT hr = S_OK; + + IDxDiagContainer * pChild; + hr = GetChildContainer( name0, &pChild ); + TRACE0( MSG_IF( FAILED(hr), "GetChildContainer(<2>) GetChildContainer(<1>) failed\n" ) ); + RET_VAL_IF_FAILED( hr ); + FAIL_IF_NULL( pChild ); + + hr = pChild->GetChildContainer( name1, ppChild ); + TRACE0( MSG_IF( FAILED(hr), "GetChildContainer(<2>) IDxDiagContainer->GetChildContainer() failed\n" ) ); + + SAFE_RELEASE( pChild ); // release the intermediate + return( hr ); +} + +HRESULT DXDiagNVUtil::GetChildContainer( LPCWSTR name0, + LPCWSTR name1, + LPCWSTR name2, + IDxDiagContainer ** ppChild ) +{ + // intermediate children are released before returning + // you only have to release() *ppChild + HRESULT hr = S_OK; + + IDxDiagContainer * pChild; + hr = GetChildContainer( name0, name1, &pChild ); + TRACE0( MSG_IF( FAILED(hr), "GetChildContainer(<3>) GetChildContainer(<2>) failed\n" ) ); + RET_VAL_IF_FAILED( hr ); + FAIL_IF_NULL( pChild ); + + hr = pChild->GetChildContainer( name2, ppChild ); + TRACE0( MSG_IF( FAILED(hr), "GetChildContainer(<3>) IDxDiagContainer->GetChildContainer() failed\n" ) ); + + SAFE_RELEASE( pChild ); // release the intermediate + return( hr ); +} + + +// public interface to display all node and subnode names +HRESULT DXDiagNVUtil::ListAllDXDiagPropertyNames() +{ + HRESULT hr = S_OK; + hr = ListAllDXDiagPropertyNames( m_pDxDiagRoot ); + return( hr ); +} + + +HRESULT DXDiagNVUtil::ListAllDXDiagPropertyNames( IDxDiagContainer * pDxDiagContainer, + WCHAR* wszParentName ) +{ + // Recurse through all properties and child properties, + // outputting their names via OutputDebugString(..) + // Start this by calling with the root IDxDiagContainer and a NULL string ptr. + // + // This function can take a while to complete. + // + // Adapted from DXSDK example file DxDiagOutput.cpp + + HRESULT hr = S_OK; + FAIL_IF_NULL( pDxDiagContainer ); + + DWORD dwPropCount; + DWORD dwPropIndex; + WCHAR wszPropName[256]; + DWORD dwChildCount; + DWORD dwChildIndex; + WCHAR wszChildName[256]; + IDxDiagContainer* pChildContainer = NULL; + + const bool bGetPropertyValue = false; + + hr = pDxDiagContainer->GetNumberOfProps( &dwPropCount ); + if( SUCCEEDED(hr) ) + { + // Print each property in this container + for( dwPropIndex = 0; dwPropIndex < dwPropCount; dwPropIndex++ ) + { + hr = pDxDiagContainer->EnumPropNames( dwPropIndex, wszPropName, 256 ); + + if( SUCCEEDED( hr ) ) + { + if( bGetPropertyValue ) + { + wstring propval; + hr = GetProperty( pDxDiagContainer, wszPropName, & propval ); + FMsgW(L"%35s : prop \"%s\" = %s\n", wszParentName, wszPropName, propval.c_str() ); + } + else + { + // otherwise, just list the property name and parent container info + FMsgW(L"%35s : prop \"%s\"\n", wszParentName, wszPropName ); + } + } + } + } + + // Recursivly call this function for each of its child containers + hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount ); + if( SUCCEEDED(hr) ) + { + for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ ) + { + hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 ); + if( SUCCEEDED(hr) ) + { + hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer ); + if( SUCCEEDED(hr) ) + { + // wszFullChildName isn't needed but is used for text output + WCHAR wszFullChildName[256]; + + // Append child name to parent and pass down in the recursion + // as full parent name. + if( wszParentName ) + swprintf( wszFullChildName, L"%s.%s", wszParentName, wszChildName ); + else + swprintf( wszFullChildName, L"%s", wszChildName ); + + // recurse + ListAllDXDiagPropertyNames( pChildContainer, wszFullChildName ); + SAFE_RELEASE( pChildContainer ); + } + } + } + } + return( hr ); +} + +// Recurse through all properties and child properties, outputting their names +// to the file. +// This function is slow and takes a while to output all the nodes, so it can be +// called with a sub-node initial argument if you only care about a small part of the +// COM data structure tree. +// Adapted from DXSDK example file DxDiagOutput.cpp +// pOpenTextFile Must be a file opened for writing text +// Call this with NULL 2nd and 3rd args to start from the top of the node structure. +HRESULT DXDiagNVUtil::ListAllDXDiagPropertyNamesToTxtFile( FILE * pOpenTextFile, + bool bGetPropertyValues, + IDxDiagContainer * pDxDiagContainer, + WCHAR * wszParentName ) +{ + HRESULT hr = S_OK; + FAIL_IF_NULL( pOpenTextFile ); + if( pDxDiagContainer == NULL ) + pDxDiagContainer = m_pDxDiagRoot; + FAIL_IF_NULL( pDxDiagContainer ); + + DWORD dwPropCount; + DWORD dwPropIndex; + WCHAR wszPropName[256]; + DWORD dwChildCount; + DWORD dwChildIndex; + WCHAR wszChildName[256]; + IDxDiagContainer* pChildContainer = NULL; + string strParentName, strPropName, strPropVal; + wstring wstrParentName, wstrPropName; + + hr = pDxDiagContainer->GetNumberOfProps( &dwPropCount ); + if( SUCCEEDED(hr) ) + { + if( wszParentName != NULL ) + wstrParentName = wszParentName; + else + wstrParentName = L""; + strParentName = WStringToString( wstrParentName ); + + // Print each property in this container + for( dwPropIndex = 0; dwPropIndex < dwPropCount; dwPropIndex++ ) + { + hr = pDxDiagContainer->EnumPropNames( dwPropIndex, wszPropName, 256 ); + if( wszPropName != NULL ) + wstrPropName = wszPropName; + else + wstrPropName = L""; + strPropName = WStringToString( wstrPropName ); + + if( SUCCEEDED( hr ) ) + { + if( bGetPropertyValues ) + { + wstring wstrPropVal; + hr = GetProperty( pDxDiagContainer, wszPropName, & wstrPropVal ); + strPropVal = WStringToString( wstrPropVal ); + + fprintf( pOpenTextFile, "%35s : prop \"%s\" = %s\n", strParentName.c_str(), strPropName.c_str(), strPropVal.c_str() ); + } + else + { + // otherwise, just list the property name and parent container info + fprintf( pOpenTextFile, "%35s : prop \"%s\"\n", strParentName.c_str(), strPropName.c_str() ); + } + } + } + } + + // Recursivly call this function for each of its child containers + hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount ); + if( SUCCEEDED(hr) ) + { + for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ ) + { + hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 ); + if( SUCCEEDED(hr) ) + { + hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer ); + if( SUCCEEDED(hr) ) + { + // wszFullChildName isn't needed but is used for text output + WCHAR wszFullChildName[256]; + + // Append child name to parent and pass down in the recursion + // as full parent name. + if( wszParentName ) + swprintf( wszFullChildName, L"%s.%s", wszParentName, wszChildName ); + else + swprintf( wszFullChildName, L"%s", wszChildName ); + + // recurse + ListAllDXDiagPropertyNamesToTxtFile( pOpenTextFile, bGetPropertyValues, + pChildContainer, wszFullChildName ); + SAFE_RELEASE( pChildContainer ); + } + } + } + } + return( hr ); +} + + +HRESULT DXDiagNVUtil::InitIDxDiagContainer() +{ + // Call FreeIDxDiagContainer() to clean up things done here + HRESULT hr; + + if( m_pDxDiagRoot != NULL ) + { + FMsg("DXDiagNVUtil::InitIDxDiagContainer already initialized!\n"); + return( S_OK ); + } + + // Init COM. COM may fail if its already been inited with a different + // concurrency model. And if it fails you shouldn't release it. + hr = CoInitialize(NULL); + m_bCleanupCOM = SUCCEEDED(hr); + + // Get an IDxDiagProvider + hr = CoCreateInstance( CLSID_DxDiagProvider, + NULL, + CLSCTX_INPROC_SERVER, + IID_IDxDiagProvider, + (LPVOID*) &m_pDxDiagProvider ); + if( SUCCEEDED(hr) ) + { + // Fill out a DXDIAG_INIT_PARAMS struct + DXDIAG_INIT_PARAMS dxDiagInitParam; + ZeroMemory( &dxDiagInitParam, sizeof(DXDIAG_INIT_PARAMS) ); + dxDiagInitParam.dwSize = sizeof(DXDIAG_INIT_PARAMS); + dxDiagInitParam.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION; + dxDiagInitParam.bAllowWHQLChecks = false; + dxDiagInitParam.pReserved = NULL; + + // Init the m_m_pDxDiagProvider + hr = m_pDxDiagProvider->Initialize( &dxDiagInitParam ); + if( SUCCEEDED(hr) ) + { + // Get the DxDiag root container + hr = m_pDxDiagProvider->GetRootContainer( & m_pDxDiagRoot ); + if( FAILED(hr) ) + { + FMsg("Couldn't GetRootContainer from DxDiagProvider!\n"); + assert( false ); + FreeIDxDiagContainer(); + return( hr ); + } + } + else + { + FMsg("Couldn't Initialize DxDiagProvider!\n"); + assert( false ); + FreeIDxDiagContainer(); + return( hr ); + } + } + else + { + FMsg("Couldn't initialize COM!\n"); + assert( false ); + FreeIDxDiagContainer(); + return( hr ); + } + + return( hr ); +} + + +HRESULT DXDiagNVUtil::FreeIDxDiagContainer() +{ + HRESULT hr = S_OK; + SAFE_RELEASE( m_pDxDiagProvider ); + SAFE_RELEASE( m_pDxDiagRoot ); + + if( m_bCleanupCOM ) + { + CoUninitialize(); + m_bCleanupCOM = false; + } + + return( hr ); +} + + diff --git a/usr/Src/Core/3D/GetGPUAndSystemInfo.cpp b/usr/Src/Core/3D/GetGPUAndSystemInfo.cpp new file mode 100644 index 0000000..7440808 --- /dev/null +++ b/usr/Src/Core/3D/GetGPUAndSystemInfo.cpp @@ -0,0 +1,288 @@ +/*--------------------------------------------------------------------- NVMH5 -|---------------------- +Path: Sdk\Demos\Direct3D9\src\GetGPUAndSystemInfo\ +File: GetGPUAndSystemInfo.cpp + +Copyright NVIDIA Corporation 2003 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND NVIDIA AND +AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA +OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER +INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF +BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS +SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +Comments: +See GetGPUAndSystemInfo.h for additional comments. + + +-------------------------------------------------------------------------------|--------------------*/ + + +#include +#include + +#include "3D\GetGPUAndSystemInfo.h" + +#include "3D\NV_Common.h" +#include "3D\NV_Error.h" + + + +/*------------------------------------------------------------------ +Retrieve various data through the IDxDiagContainer interface. + +The DXDiagNVUtil class provides a few convenient wrapper functions, +and direct querries using the IDxDiagContainer COM object names are +also supported. For a list of all the container and property COM +object names, call ListAllDXDiagPropertyNames(..) +------------------------------------------------------------------*/ +HRESULT GetGPUAndSystemInfo::GetData() +{ + HRESULT hr = S_OK; + //---------------------------------------------------------------------------- + hr = m_DXDiagNVUtil.InitIDxDiagContainer(); + MSG_AND_RET_VAL_IF( FAILED(hr), "Couldn't initialize DXDiagNVUtil!\n", hr ); + wstring wstr; + // Get the computer's machine name: + m_DXDiagNVUtil.GetProperty( L"DxDiag_SystemInfo", L"szMachineNameEnglish", &wstr ); + m_strMachineName = m_DXDiagNVUtil.WStringToString( &wstr ); + + FMsg("\n\n"); + FMsg("------------------------------------------------------------------------\n"); + FMsgW(L"machine name: %s\n", wstr.c_str() ); + + // Get info about physcial memory: + m_DXDiagNVUtil.GetPhysicalMemoryInMB( & m_fSystemPhysicalMemoryMB ); + FMsg("physical memory: %g MB\n", m_fSystemPhysicalMemoryMB ); + + // Get info about logical disks + IDxDiagContainer * pContainer, *pChild; + DWORD dwNumDisks; + hr = m_DXDiagNVUtil.GetChildContainer( L"DxDiag_LogicalDisks", & pContainer ); + if( SUCCEEDED(hr)) + { + pContainer->GetNumberOfChildContainers( & dwNumDisks ); + + wstring drive, space; + FMsgW(L"logical disks: %d\n", dwNumDisks ); + for( DWORD n=0; n < dwNumDisks; n++ ) + { + hr = m_DXDiagNVUtil.GetChildByIndex( pContainer, n, &pChild ); + if( SUCCEEDED(hr) ) + { + m_DXDiagNVUtil.GetProperty( pChild, L"szDriveLetter", &drive ); + m_DXDiagNVUtil.GetProperty( pChild, L"szFreeSpace", &space ); + FMsgW(L" %s Free space = %s\n", drive.c_str(), space.c_str() ); + SAFE_RELEASE( pChild ); + } + } + SAFE_RELEASE( pContainer ); + } + + FMsg("------------------------------------------------------------------------\n"); + + m_DXDiagNVUtil.GetDirectXVersion( &m_dwDXVersionMajor, &m_dwDXVersionMinor, &m_cDXVersionLetter ); + FMsg("DirectX Version: %d.%d%c\n", m_dwDXVersionMajor, m_dwDXVersionMinor, m_cDXVersionLetter ); + + hr = m_DXDiagNVUtil.GetNumDisplayDevices( & m_dwNumDisplayDevices ); + MSG_AND_RET_VAL_IF( FAILED(hr), "Couldn't GetNumDisplayDevices()\n", hr ); + FMsg("Num Display Devices: %d\n", m_dwNumDisplayDevices ); + + string str; + +// for( DWORD dev=0; dev < m_dwNumDisplayDevices; dev ++ ) + if( m_dwNumDisplayDevices > 0 ) + { + DWORD dev = 0; + + // get info from display devices + m_DXDiagNVUtil.GetDisplayDeviceDescription( dev, & m_wstrDeviceDesc ); + m_DXDiagNVUtil.GetDisplayDeviceNVDriverVersion( dev, & m_fDriverVersion ); + m_DXDiagNVUtil.GetDisplayDeviceMemoryInMB( dev, & m_nDeviceMemoryMB ); + + // report the info via OutputDebugString + FMsgW(L"Device %d Description: %s\n", dev, m_wstrDeviceDesc.c_str() ); + FMsg( "Device %d Driver version: %g\n", dev, m_fDriverVersion ); + FMsg( "Device %d Physical mem: %d MB\n", dev, m_nDeviceMemoryMB ); + + // Get info about AGP memory: + wstring wstrAGPEnabled, wstrAGPExists, wstrAGPStatus; + hr = m_DXDiagNVUtil.GetDisplayDeviceAGPMemoryStatus( dev, &wstrAGPEnabled, &wstrAGPExists, &wstrAGPStatus ); + if( SUCCEEDED(hr)) + { + // create a string from the AGP status strings + m_strAGPStatus = ""; + str = m_DXDiagNVUtil.WStringToString( &wstrAGPEnabled ); + m_strAGPStatus += "AGP Enabled = "; m_strAGPStatus += str; m_strAGPStatus += ", "; + str = m_DXDiagNVUtil.WStringToString( &wstrAGPExists ); + m_strAGPStatus += "AGP Exists = "; m_strAGPStatus += str; m_strAGPStatus += ", "; + str = m_DXDiagNVUtil.WStringToString( &wstrAGPStatus ); + m_strAGPStatus += "AGP Status = "; m_strAGPStatus += str; + } + FMsg("%s\n", m_strAGPStatus.c_str() ); + + wstring wstrNotes, wstrTestD3D9; + m_DXDiagNVUtil.GetProperty( L"DxDiag_DisplayDevices", L"0", L"szTestResultD3D9English", &wstrTestD3D9 ); + m_DXDiagNVUtil.GetProperty( L"DxDiag_DisplayDevices", L"0", L"szNotesEnglish", &wstrNotes ); + + str = m_DXDiagNVUtil.WStringToString( &wstrTestD3D9 ); + FMsg("Device 0 szTestResultD3D9English = \"%s\"\n", str.c_str() ); + str = m_DXDiagNVUtil.WStringToString( &wstrNotes ); + FMsg("Device 0 szNotesEnglish = \"%s\"\n", str.c_str() ); + } + + m_DXDiagNVUtil.GetDebugLevels( & m_wstrDxDebugLevels ); + FMsg("DirectX Debug Levels:\n"); + FMsgW(L"%s\n", m_wstrDxDebugLevels.c_str() ); + + + // ListAllDXDiagPropertyNames() is slow + // It prints out all nodes, child nodes, properties and their values +// m_DXDiagNVUtil.ListAllDXDiagPropertyNames(); + + // Use a call like that below to print out a specific node and it's children. + // For example, to list all the display device property names. +/* + m_DXDiagNVUtil.GetChildContainer( L"DxDiag_DisplayDevices", &pContainer ); + m_DXDiagNVUtil.ListAllDXDiagPropertyNames( pContainer, L"DxDiag_DisplayDevices" ); + SAFE_RELEASE( pContainer ); +// */ + + m_DXDiagNVUtil.FreeIDxDiagContainer(); + return( hr ); +} + + +HRESULT GetGPUAndSystemInfo::IsFPBlendingSupported( IDirect3D9 * pD3D9, FloatingPointBlendModes * pOutResult ) +{ + FMsg("There is a bug with this code in that is does not report that blending works for ordinary backbuffer formats\n"); + assert( false ); + + HRESULT hr = S_OK; + FAIL_IF_NULL( pD3D9 ); + FAIL_IF_NULL( pOutResult ); + + bool * pResult; + + hr = pD3D9->CheckDeviceFormat( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, + D3DFMT_A8R8G8B8, + D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, + D3DRTYPE_SURFACE, + D3DFMT_R16F ); + pResult = &pOutResult->m_bR16f; + if( hr == D3D_OK ) + *pResult = true; + else if( hr == D3DERR_NOTAVAILABLE ) + *pResult = false; + else + FMsg("Unknown return result for D3DFMT_R16F : %u\n", hr ); + + + hr = pD3D9->CheckDeviceFormat( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, + D3DFMT_A8R8G8B8, + D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, + D3DRTYPE_SURFACE, + D3DFMT_A16B16G16R16F ); + pResult = &pOutResult->m_bA16B16G16R16f; + if( hr == D3D_OK ) + *pResult = true; + else if( hr == D3DERR_NOTAVAILABLE ) + *pResult = false; + else + FMsg("Unknown return result for D3DFMT_A16B16G16R16F : %u\n", hr ); + + hr = pD3D9->CheckDeviceFormat( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, + D3DFMT_A8R8G8B8, +// D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, + 0 | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, // per the DX90SDK docs + D3DRTYPE_SURFACE, + D3DFMT_A8R8G8B8 ); + pResult = &pOutResult->m_bA8R8G8B8; + if( hr == D3D_OK ) + *pResult = true; + else if( hr == D3DERR_NOTAVAILABLE ) + *pResult = false; + else + FMsg("Unknown return result for D3DFMT_A8R8G8B8 : %u\n", hr ); + + + if( pOutResult->m_bA16B16G16R16f == true ) + FMsg("D3DFMT_A16B16G16R16F POSTPIXELSHADER_BLENDING is supported\n"); + else + FMsg("D3DFMT_A16B16G16R16F POSTPIXELSHADER_BLENDING is not supported\n"); + + if( pOutResult->m_bR16f == true ) + FMsg("D3DFMT_R16F POSTPIXELSHADER_BLENDING is supported\n"); + else + FMsg("D3DFMT_R16F POSTPIXELSHADER_BLENDING is not supported\n"); + + if( pOutResult->m_bA8R8G8B8 == true ) + FMsg("D3DFMT_A8R8G8B8 POSTPIXELSHADER_BLENDING is supported\n"); + else + FMsg("D3DFMT_A8R8G8B8 POSTPIXELSHADER_BLENDING is not supported\n"); + +/* +Use IDirect3D9::CheckDeviceFormat, with usage (D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADERBLENDING). +HRESULT CheckDeviceFormat( UINT Adapter, + D3DDEVTYPE DeviceType, + D3DFORMAT AdapterFormat, + DWORD Usage, + D3DRESOURCETYPE RType, + D3DFORMAT CheckFormat +); + +D3DFMT_R16F 111 16-bit float format using 16 bits for the red channel. +D3DFMT_G16R16F 112 32-bit float format using 16 bits for the red channel and 16 bits for the green channel. +D3DFMT_A16B16G16R16F + +D3DFMT_R32F 114 32-bit float format using 32 bits for the red channel. +D3DFMT_G32R32F 115 64-bit float format using 32 bits for the red channel and 32 bits for the green channel. +D3DFMT_A32B32G32R32F + +D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING + +D3DUSAGE_QUERY_FILTER (more than just point sampling) + +Query the resource to verify support for post pixel shader blending support. +If IDirect3D9::CheckDeviceFormat fails with D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, +post pixel blending operations are not supported. These include alpha test, pixel fog, +render-target blending, color write enable, and dithering. + +MSFT examples from SDK + if( pCaps->PixelShaderVersion < D3DPS_VERSION(1,1) ) + { + if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, + pCaps->DeviceType, adapterFormat, D3DUSAGE_RENDERTARGET, + D3DRTYPE_TEXTURE, D3DFMT_A8R8G8B8 ) ) ) + { + return E_FAIL; + } + } + + // Need to support post-pixel processing (for alpha blending) + if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, + adapterFormat, D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, + D3DRTYPE_SURFACE, backBufferFormat ) ) ) + { + return E_FAIL; + } + +HRESULT CMyD3DApplication::ConfirmDevice( D3DCAPS9* pCaps, DWORD dwBehavior, + D3DFORMAT adapterFormat, D3DFORMAT backBufferFormat ) +{ + // Need to support post-pixel processing (for alpha blending) + if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, + adapterFormat, D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, + D3DRTYPE_SURFACE, backBufferFormat ) ) ) + { + return E_FAIL; + } + +*/ + + + + return( hr ); +} + diff --git a/usr/Src/Core/3D/NV_StringFuncs.cpp b/usr/Src/Core/3D/NV_StringFuncs.cpp new file mode 100644 index 0000000..f0930c7 --- /dev/null +++ b/usr/Src/Core/3D/NV_StringFuncs.cpp @@ -0,0 +1,386 @@ +/*********************************************************************NVMH4**** +Path: SDK\LIBS\inc\shared +File: NV_StringFuncs.cpp + +Copyright NVIDIA Corporation 2002 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED +*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS +BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES +WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, +BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) +ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + + +Comments: +See NV_StringFuncs.h for comments. + + +******************************************************************************/ + + + +#include "3D\NV_StringFuncs.h" +#include "3D\NV_Common.h" +#include "3D\NV_Error.h" + +#pragma warning(disable : 4786) +#include +#include +#include +#include +#include +#include + + +namespace NVStringConv +{ + // use as an alternative to wcstombs() + std::string WStringToString( const std::wstring * in_pwstring ) + { + if( in_pwstring == NULL ) + return( "" ); + return( lpcwstrToString( in_pwstring->c_str() )); + } + + std::string WStringToString( std::wstring & in_wstring ) + { + return( lpcwstrToString( in_wstring.c_str() )); + } + + std::string lpcwstrToString( LPCWSTR in_lpcwstr ) + { + //@ consider using windows.h WideCharToMultiByte(..) + char * mbBuf; + size_t sz; + sz = 2 * wcslen( in_lpcwstr ); + mbBuf = new char[sz]; + if( mbBuf == NULL ) + return( "" ); + wcstombs( mbBuf, in_lpcwstr, sz ); // convert the string + std::string outstr; + outstr = mbBuf; + delete [] mbBuf; + return( outstr ); + } + + std::wstring StringToWString( const std::string * in_pString ) + { + std::wstring wstr = L""; + if( in_pString != NULL ) + wstr = lpcstrToWString( in_pString->c_str() ); + return( wstr ); + } + + std::wstring StringToWString( std::string & in_String ) + { + return( lpcstrToWString( in_String.c_str() )); + } + + std::wstring lpcstrToWString( LPCSTR lpstr ) + { + int nLen = MultiByteToWideChar( CP_ACP, 0, lpstr, -1, NULL, NULL); + LPWSTR lpszW = new WCHAR[nLen+1]; + MultiByteToWideChar( CP_ACP, 0, lpstr, -1, lpszW, nLen); + lpszW[nLen] = '\0'; + std::wstring wstr; + wstr.reserve( nLen ); + wstr.insert( 0, lpszW ); +// wstr = lpszW; + delete[] lpszW; + return( wstr ); + } +}; // namespace NVStringConv + + +//--------------------------------------------------------------------------- + + // Create a string using va_args, just like printf, sprintf, etc. +std::string StrPrintf( const char * szFormat, ... ) +{ + std::string out; + + const int bufsz = 2048; + char buffer[ bufsz ]; + + va_list args; + va_start( args, szFormat ); + _vsnprintf( buffer, bufsz, szFormat, args ); + va_end( args ); + + buffer[bufsz-1] = '\0'; // terminate in case of overflow + out = buffer; + + return( out ); +} + +std::string StrToUpper( const std::string & strIn ) +{ + unsigned int i; + std::string out; + out.reserve( strIn.size() ); + for( i=0; i < strIn.size(); i++ ) + { + out += toupper( strIn.at(i) ); + } + return( out ); +} + +std::string StrToLower( const std::string & strIn ) +{ + unsigned int i; + std::string out; + out.reserve( strIn.size() ); + for( i=0; i < strIn.size(); i++ ) + { + out += tolower( strIn.at(i) ); + } + return( out ); +} + + +std::string StrsToString( const std::vector< std::string > & vstrIn ) +{ + return( StrsToString( vstrIn, " " )); +} + + // same as above, but lets you specify the separator +std::string StrsToString( const std::vector< std::string > & vstrIn, const std::string & separator ) +{ + std::string out; + out.reserve( vstrIn.size() * 5 ); // rough estimate, 5 chars per string + unsigned int i; + for( i=0; i < vstrIn.size(); i++ ) + { + out += vstrIn.at(i) + separator; + } + return( out ); +} + +std::string StrsToString( const std::list< std::string > & lstrIn, const std::string & separator ) +{ + std::string out; + out.reserve( lstrIn.size() * 5 ); + std::list< std::string>::const_iterator p; + for( p = lstrIn.begin(); p != lstrIn.end(); p++ ) + { + out += (*p) + separator; + } + return( out ); +} + + + +std::string * StrReplace( const std::string & sequence_to_replace, + const std::string & replacement_string, + const std::string & strIn, + std::string * pOut, + bool bVerbose ) +{ + if( pOut == NULL ) + return( pOut ); + if( & strIn == pOut ) + { + // can't have strIn and pOut point to the same thing + // have to copy the input string + std::string incpy = strIn; + return( StrReplace( sequence_to_replace, replacement_string, incpy, pOut )); + } + + + // Similar functionality to CString::Replace(), but no MFC required. + unsigned int i; + std::vector< size_t > vpos; + std::string::size_type pos; + pos = 0; + + *pOut = ""; + + do + { + pos = strIn.find( sequence_to_replace, pos ); + if( pos != std::string::npos ) + { + vpos.push_back( pos ); + pos++; + } + } while( pos != std::string::npos ); + + if( bVerbose ) + { + FMsg("found at "); + for( i=0; i < vpos.size(); i++ ) + { + FMsg("%d ", vpos.at(i) ); + } + FMsg("\n"); + } + + size_t last_pos = 0; + size_t repl_size = sequence_to_replace.size(); + pOut->reserve( strIn.size() + vpos.size() * replacement_string.size() - vpos.size() * repl_size ); + // last_pos marks character which should be included + // in the output string + for( i=0; i < vpos.size(); i++ ) + { + *pOut += strIn.substr( last_pos, vpos.at(i) - last_pos ); + last_pos = vpos.at(i) + repl_size; + *pOut += replacement_string; + } + // add remainder of orig string to the end + *pOut += strIn.substr( last_pos, strIn.size() - last_pos ); + + return( pOut ); +} + + +std::string StrReplace( const std::string & sequence_to_replace, + const std::string & replacement_string, + const std::string & strIn ) +{ + std::string out; + + StrReplace( sequence_to_replace, replacement_string, strIn, &out ); + + return( out ); +} + + + +std::string StrTokenize( const std::string & strIn, const std::string & delimiters ) +{ + // applies strtok repeatedly & acumulates ouput tokens + // in output string separated by spaces + + return( StrTokenize( strIn, delimiters, " " )); +} + + +std::string StrTokenize( const std::string & strIn, + const std::string & delimiters, + const std::string & output_separator ) +{ + // Same as above, but allows you to specify the separator between + // tokens in the output + // No trailing separator is added + + std::string out; + char * token; + char * copy = new char[strIn.size()+2]; // +2 just to be safe! + strcpy( copy, strIn.c_str() ); + token = strtok( copy, delimiters.c_str() ); + while( token != NULL ) + { + out += token; + token = strtok( NULL, delimiters.c_str() ); + + // If there's another token, add the separator + // This means there is no trailing separator. + if( token != NULL ) + { + out += output_separator; + } + } + delete[] copy; + return( out ); +} + + +sfsizet StrFindCaseless( const std::string & strSearchIn, + sfsizet start_pos, + const std::string & strSearchFor ) +{ + sfsizet outpos = std::string::npos; + std::string sin = StrToUpper( strSearchIn ); + std::string sfor = StrToUpper( strSearchFor ); + + outpos = sin.find( sfor, start_pos ); + + return( outpos ); +} + + +std::vector< sfsizet > StrFindAllCaseless( const std::string & strSearchIn, + sfsizet start_pos, + const std::string & strSearchFor ) +{ + std::vector< sfsizet > out; + sfsizet pos = start_pos; + std::string sin = StrToUpper( strSearchIn ); + std::string sfor = StrToUpper( strSearchFor ); + + while( pos != std::string::npos ) + { + pos = sin.find( sfor, pos ); + if( pos != std::string::npos ) + { + out.push_back( pos ); + pos++; + } + } + + return( out ); +} + +std::vector< sfsizet > StrFindAll( const std::string & strSearchIn, + sfsizet start_pos, + const std::string & strSearchFor ) +{ + std::vector< sfsizet > out; + sfsizet pos = start_pos; + while( pos != std::string::npos ) + { + pos = strSearchIn.find( strSearchFor, pos ); + if( pos != std::string::npos ) + { + out.push_back( pos ); + pos++; + } + } + return( out ); +} + + +std::vector< std::string> StrSort( const std::vector< std::string > & vStrIn ) +{ + std::vector< std::string > vOut; + std::list< std::string > lstr; + + unsigned int i; + for( i=0; i < vStrIn.size(); i++ ) + { + lstr.push_back( vStrIn.at(i) ); + } + lstr.sort(); + + std::list< std::string>::const_iterator p; + for( p = lstr.begin(); p != lstr.end(); p++ ) + { + vOut.push_back( *p ); + } + return( vOut ); +} + +//------------------------------------------------------------------- +// Reduce a full or relative path name to just a lone filename. +// Example: +// name = GetFilenameFromFullPath( "C:\MyFiles\project1\texture.dds" ); +// name is "texture.dds" +// Returns the input string if no path info was found & removed. +//------------------------------------------------------------------- +tstring GetFilenameFromFullPath( const tstring & full_path ) +{ + size_t pos; + pos = full_path.find_last_of( '\\', full_path.length() ); + if( pos == tstring::npos ) + pos = full_path.find_last_of( '/', full_path.length() ); + if( pos == tstring::npos ) + return( full_path ); + tstring name; + name = full_path.substr( pos+1, full_path.length() ); + return( name ); +} + diff --git a/usr/Src/Core/DataManager.cpp b/usr/Src/Core/DataManager.cpp new file mode 100644 index 0000000..8182a42 --- /dev/null +++ b/usr/Src/Core/DataManager.cpp @@ -0,0 +1,52 @@ +////////////////////////////////////////////////////////////////////////////////////////////////////////// +// DataManager +////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "CKAll.h" +#include "DataManager.h" + +DataManager::DataManager(CKContext *Context) : +CKBaseManager(Context, DataManagerGUID, "DataManager") +{ + Context->RegisterNewManager(this); + _vPos.Set(0,0,0); +} + +DataManager::~DataManager() +{ + +} + + +CKERROR DataManager::OnCKInit() +{ + +#ifdef G_EXTERNAL_ACCESS + _initSharedMemory(0); +#endif + return CK_OK; +} + +CKERROR DataManager::PostProcess() +{ + + #ifdef G_EXTERNAL_ACCESS + _SharedMemoryTickPost(0); + #endif + return CK_OK; +} + +CKERROR DataManager::PreProcess() +{ + + #ifdef G_EXTERNAL_ACCESS + _SharedMemoryTick(0); + #endif + return CK_OK; +} + + + + + + diff --git a/usr/Src/Core/DataManagerRemote.cpp b/usr/Src/Core/DataManagerRemote.cpp new file mode 100644 index 0000000..35b39fb --- /dev/null +++ b/usr/Src/Core/DataManagerRemote.cpp @@ -0,0 +1,130 @@ +/******************************************************************** + created: 2009/04/14 + created: 14:4:2009 11:29 + filename: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Src\Core\DataManagerRemote.cpp + file path: x:\ProjectRoot\vtmodsvn\tools\VTCPPProjectPremakerSimple\Sdk\Src\Core + file base: DataManagerRemote + file ext: cpp + author: Günter Baumgart + + purpose: handles remote messages +*********************************************************************/ +#include "StdAfx.h" +#include "DataManager.h" + +#ifdef G_EXTERNAL_ACCESS + +#include "MemoryFileMappingTypes.h" + +#include +#include "AutoLock.h" +#include "vtGUID.h" + +using namespace AutoLock; + +vtExternalEvent *Msg; + +HANDLE hmem = NULL; + +int post = 0; + +HANDLE m_hLogItemSendEvent = ::CreateEvent(NULL,TRUE,FALSE,"LogItemSendEventName"); +HANDLE m_hShutdownEvent = ::CreateEvent(NULL,FALSE,FALSE,"SendRcvShutdownEvent"); +HANDLE m_hLogItemReceivedEvent = ::CreateEvent(NULL,FALSE,FALSE,"LogItemReceivedEventName"); +HANDLE aHandles[] = { m_hShutdownEvent , m_hLogItemSendEvent }; + +BOOL recieved = false; +BOOL changed = true; + + + + +int DataManager::_SharedMemoryTickPost(int flagsOfWhatever) +{ + + if (!changed){ + + SetEvent( m_hShutdownEvent ); + } + return CK_OK; + + return 0; +} + +int DataManager::_SharedMemoryTick(int flagsOfWhatever) +{ + + HRESULT hr = S_OK; + + //USES_CONVERSION; + + switch( ::WaitForMultipleObjects(sizeof(aHandles) /sizeof(HANDLE),&(aHandles[0]),FALSE,1)) + { + + case WAIT_OBJECT_0: + { + SetEvent( m_hShutdownEvent ); + break; + } + case WAIT_OBJECT_0 + 1: + { + try + { + + CLockableMutex m_mtxMMFile("sharedMem"); + CAutoLockT< CLockableMutex > lock(&m_mtxMMFile, 5000 ); + vtExternalEvent *pLI = reinterpret_cast(m_pData); + + + //XString command(pLI->command); + //XString commandArg(pLI->commandArg); + + + XString msgStr; + msgStr.Format("Remote Message:%s",pLI->command); + m_Context->OutputToConsole(msgStr.Str(),FALSE); + + changed = true; + SetEvent( m_hLogItemReceivedEvent ); + ::ResetEvent(m_hShutdownEvent); + return CK_OK; + } + catch( CAutoLockTimeoutExc ) + { + hr = HRESULT_FROM_WIN32( WAIT_TIMEOUT ); + } + catch( CAutoLockWaitExc& e ) + { + hr = HRESULT_FROM_WIN32( e.GetLastError() ); + } + break; + + } + // default: + // ATLASSERT(0); + } + return CK_OK; +} + + + +int DataManager::_initSharedMemory(int flagsOfWhatever) +{ + + if( NULL != ( m_hMMFile = CreateFileMapping( INVALID_HANDLE_VALUE, + NULL,PAGE_READWRITE,0, + sizeof( vtExternalEvent ),"sharedMemFile" ) ))//_T("LogSndRcvMMF") ))) + { + if( NULL != (m_pData = (vtExternalEvent*)::MapViewOfFile(m_hMMFile, + FILE_MAP_READ | FILE_MAP_WRITE, + 0, + 0, + sizeof( vtExternalEvent* )) ) ) + { + return S_OK; + } + } + + return HRESULT_FROM_WIN32( ::GetLastError( ) ); +} +#endif diff --git a/usr/Src/Core/GetDXVer.cpp b/usr/Src/Core/GetDXVer.cpp new file mode 100644 index 0000000..035cc6a --- /dev/null +++ b/usr/Src/Core/GetDXVer.cpp @@ -0,0 +1,525 @@ + + +#define INITGUID + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#include +#include + + +#include +#include +#pragma warning(disable: 4005 4995) +#include +#pragma warning(default: 4005 4995) +#include + + +HRESULT GetDirectXVersionViaDxDiag( DWORD* pdwDirectXVersionMajor, DWORD* pdwDirectXVersionMinor, TCHAR* pcDirectXVersionLetter ); +HRESULT GetDirectXVerionViaFileVersions( DWORD* pdwDirectXVersionMajor, DWORD* pdwDirectXVersionMinor, TCHAR* pcDirectXVersionLetter ); +HRESULT GetFileVersion( TCHAR* szPath, ULARGE_INTEGER* pllFileVersion ); +ULARGE_INTEGER MakeInt64( WORD a, WORD b, WORD c, WORD d ); +int CompareLargeInts( ULARGE_INTEGER ullParam1, ULARGE_INTEGER ullParam2 ); + + + + +HRESULT GetDXVersion( DWORD* pdwDirectXVersion, TCHAR* strDirectXVersion, int cchDirectXVersion ) +{ + bool bGotDirectXVersion = false; + + // Init values to unknown + if( pdwDirectXVersion ) + *pdwDirectXVersion = 0; + if( strDirectXVersion && cchDirectXVersion > 0 ) + strDirectXVersion[0] = 0; + + DWORD dwDirectXVersionMajor = 0; + DWORD dwDirectXVersionMinor = 0; + TCHAR cDirectXVersionLetter = ' '; + + // First, try to use dxdiag's COM interface to get the DirectX version. + // The only downside is this will only work on DirectX9 or later. + if( SUCCEEDED( GetDirectXVersionViaDxDiag( &dwDirectXVersionMajor, &dwDirectXVersionMinor, &cDirectXVersionLetter ) ) ) + bGotDirectXVersion = true; + + if( !bGotDirectXVersion ) + { + // Getting the DirectX version info from DxDiag failed, + // so most likely we are on DirectX8.x or earlier + if( SUCCEEDED( GetDirectXVerionViaFileVersions( &dwDirectXVersionMajor, &dwDirectXVersionMinor, &cDirectXVersionLetter ) ) ) + bGotDirectXVersion = true; + } + + // If both techniques failed, then return E_FAIL + if( !bGotDirectXVersion ) + return E_FAIL; + + // Set the output values to what we got and return + cDirectXVersionLetter = (char)tolower(cDirectXVersionLetter); + + if( pdwDirectXVersion ) + { + // If pdwDirectXVersion is non-NULL, then set it to something + // like 0x00080102 which would represent DirectX8.1b + DWORD dwDirectXVersion = dwDirectXVersionMajor; + dwDirectXVersion <<= 8; + dwDirectXVersion += dwDirectXVersionMinor; + dwDirectXVersion <<= 8; + if( cDirectXVersionLetter >= 'a' && cDirectXVersionLetter <= 'z' ) + dwDirectXVersion += (cDirectXVersionLetter - 'a') + 1; + + *pdwDirectXVersion = dwDirectXVersion; + } + + if( strDirectXVersion && cchDirectXVersion > 0 ) + { + // If strDirectXVersion is non-NULL, then set it to something + // like "8.1b" which would represent DirectX8.1b + if( cDirectXVersionLetter == ' ' ) + StringCchPrintf( strDirectXVersion, cchDirectXVersion, TEXT("%d.%d"), dwDirectXVersionMajor, dwDirectXVersionMinor ); + else + StringCchPrintf( strDirectXVersion, cchDirectXVersion, TEXT("%d.%d%c"), dwDirectXVersionMajor, dwDirectXVersionMinor, cDirectXVersionLetter ); + } + + return S_OK; +} + + + + +//----------------------------------------------------------------------------- +// Name: GetDirectXVersionViaDxDiag() +// Desc: Tries to get the DirectX version from DxDiag's COM interface +//----------------------------------------------------------------------------- +HRESULT GetDirectXVersionViaDxDiag( DWORD* pdwDirectXVersionMajor, + DWORD* pdwDirectXVersionMinor, + TCHAR* pcDirectXVersionLetter ) +{ + HRESULT hr; + bool bCleanupCOM = false; + + bool bSuccessGettingMajor = false; + bool bSuccessGettingMinor = false; + bool bSuccessGettingLetter = false; + + // Init COM. COM may fail if its already been inited with a different + // concurrency model. And if it fails you shouldn't release it. + hr = CoInitialize(NULL); + bCleanupCOM = SUCCEEDED(hr); + + // Get an IDxDiagProvider + bool bGotDirectXVersion = false; + IDxDiagProvider* pDxDiagProvider = NULL; + hr = CoCreateInstance( CLSID_DxDiagProvider, + NULL, + CLSCTX_INPROC_SERVER, + IID_IDxDiagProvider, + (LPVOID*) &pDxDiagProvider ); + if( SUCCEEDED(hr) ) + { + // Fill out a DXDIAG_INIT_PARAMS struct + DXDIAG_INIT_PARAMS dxDiagInitParam; + ZeroMemory( &dxDiagInitParam, sizeof(DXDIAG_INIT_PARAMS) ); + dxDiagInitParam.dwSize = sizeof(DXDIAG_INIT_PARAMS); + dxDiagInitParam.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION; + dxDiagInitParam.bAllowWHQLChecks = false; + dxDiagInitParam.pReserved = NULL; + + // Init the m_pDxDiagProvider + hr = pDxDiagProvider->Initialize( &dxDiagInitParam ); + if( SUCCEEDED(hr) ) + { + IDxDiagContainer* pDxDiagRoot = NULL; + IDxDiagContainer* pDxDiagSystemInfo = NULL; + + // Get the DxDiag root container + hr = pDxDiagProvider->GetRootContainer( &pDxDiagRoot ); + if( SUCCEEDED(hr) ) + { + // Get the object called DxDiag_SystemInfo + hr = pDxDiagRoot->GetChildContainer( L"DxDiag_SystemInfo", &pDxDiagSystemInfo ); + if( SUCCEEDED(hr) ) + { + VARIANT var; + VariantInit( &var ); + + // Get the "dwDirectXVersionMajor" property + hr = pDxDiagSystemInfo->GetProp( L"dwDirectXVersionMajor", &var ); + if( SUCCEEDED(hr) && var.vt == VT_UI4 ) + { + if( pdwDirectXVersionMajor ) + *pdwDirectXVersionMajor = var.ulVal; + bSuccessGettingMajor = true; + } + VariantClear( &var ); + + // Get the "dwDirectXVersionMinor" property + hr = pDxDiagSystemInfo->GetProp( L"dwDirectXVersionMinor", &var ); + if( SUCCEEDED(hr) && var.vt == VT_UI4 ) + { + if( pdwDirectXVersionMinor ) + *pdwDirectXVersionMinor = var.ulVal; + bSuccessGettingMinor = true; + } + VariantClear( &var ); + + // Get the "szDirectXVersionLetter" property + hr = pDxDiagSystemInfo->GetProp( L"szDirectXVersionLetter", &var ); + if( SUCCEEDED(hr) && var.vt == VT_BSTR && SysStringLen( var.bstrVal ) != 0 ) + { +#ifdef UNICODE + *pcDirectXVersionLetter = var.bstrVal[0]; +#else + char strDestination[10]; + WideCharToMultiByte( CP_ACP, 0, var.bstrVal, -1, strDestination, 10*sizeof(CHAR), NULL, NULL ); + if( pcDirectXVersionLetter ) + *pcDirectXVersionLetter = strDestination[0]; +#endif + bSuccessGettingLetter = true; + } + VariantClear( &var ); + + // If it all worked right, then mark it down + if( bSuccessGettingMajor && bSuccessGettingMinor && bSuccessGettingLetter ) + bGotDirectXVersion = true; + + pDxDiagSystemInfo->Release(); + } + + pDxDiagRoot->Release(); + } + } + + pDxDiagProvider->Release(); + } + + if( bCleanupCOM ) + CoUninitialize(); + + if( bGotDirectXVersion ) + return S_OK; + else + return E_FAIL; +} + + + + +//----------------------------------------------------------------------------- +// Name: GetDirectXVerionViaFileVersions() +// Desc: Tries to get the DirectX version by looking at DirectX file versions +//----------------------------------------------------------------------------- +HRESULT GetDirectXVerionViaFileVersions( DWORD* pdwDirectXVersionMajor, + DWORD* pdwDirectXVersionMinor, + TCHAR* pcDirectXVersionLetter ) +{ + ULARGE_INTEGER llFileVersion; + TCHAR szPath[512]; + TCHAR szFile[512]; + BOOL bFound = false; + + if( GetSystemDirectory( szPath, MAX_PATH ) != 0 ) + { + szPath[MAX_PATH-1]=0; + + // Switch off the ddraw version + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\ddraw.dll") ); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 2, 0, 95 ) ) >= 0 ) // Win9x version + { + // flle is >= DirectX1.0 version, so we must be at least DirectX1.0 + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 1; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 3, 0, 1096 ) ) >= 0 ) // Win9x version + { + // flle is is >= DirectX2.0 version, so we must DirectX2.0 or DirectX2.0a (no redist change) + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 2; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 4, 0, 68 ) ) >= 0 ) // Win9x version + { + // flle is is >= DirectX3.0 version, so we must be at least DirectX3.0 + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 3; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + } + + // Switch off the d3drg8x.dll version + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\d3drg8x.dll") ); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 4, 0, 70 ) ) >= 0 ) // Win9x version + { + // d3drg8x.dll is the DirectX3.0a version, so we must be DirectX3.0a or DirectX3.0b (no redist change) + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 3; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT('a'); + bFound = true; + } + } + + // Switch off the ddraw version + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\ddraw.dll") ); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 5, 0, 155 ) ) >= 0 ) // Win9x version + { + // ddraw.dll is the DirectX5.0 version, so we must be DirectX5.0 or DirectX5.2 (no redist change) + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 5; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 6, 0, 318 ) ) >= 0 ) // Win9x version + { + // ddraw.dll is the DirectX6.0 version, so we must be at least DirectX6.0 + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 6; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 6, 0, 436 ) ) >= 0 ) // Win9x version + { + // ddraw.dll is the DirectX6.1 version, so we must be at least DirectX6.1 + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 6; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 1; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + } + + // Switch off the dplayx.dll version + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\dplayx.dll") ); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 6, 3, 518 ) ) >= 0 ) // Win9x version + { + // ddraw.dll is the DirectX6.1 version, so we must be at least DirectX6.1a + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 6; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 1; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT('a'); + bFound = true; + } + } + + // Switch off the ddraw version + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\ddraw.dll") ); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 7, 0, 700 ) ) >= 0 ) // Win9x version + { + // TODO: find win2k version + + // ddraw.dll is the DirectX7.0 version, so we must be at least DirectX7.0 + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 7; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + } + + // Switch off the dinput version + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\dinput.dll") ); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( CompareLargeInts( llFileVersion, MakeInt64( 4, 7, 0, 716 ) ) >= 0 ) // Win9x version + { + // ddraw.dll is the DirectX7.0 version, so we must be at least DirectX7.0a + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 7; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT('a'); + bFound = true; + } + } + + // Switch off the ddraw version + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\ddraw.dll") ); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( (HIWORD(llFileVersion.HighPart) == 4 && CompareLargeInts( llFileVersion, MakeInt64( 4, 8, 0, 400 ) ) >= 0) || // Win9x version + (HIWORD(llFileVersion.HighPart) == 5 && CompareLargeInts( llFileVersion, MakeInt64( 5, 1, 2258, 400 ) ) >= 0) ) // Win2k/WinXP version + { + // ddraw.dll is the DirectX8.0 version, so we must be at least DirectX8.0 or DirectX8.0a (no redist change) + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 8; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + } + + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\d3d8.dll")); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( (HIWORD(llFileVersion.HighPart) == 4 && CompareLargeInts( llFileVersion, MakeInt64( 4, 8, 1, 881 ) ) >= 0) || // Win9x version + (HIWORD(llFileVersion.HighPart) == 5 && CompareLargeInts( llFileVersion, MakeInt64( 5, 1, 2600, 881 ) ) >= 0) ) // Win2k/WinXP version + { + // d3d8.dll is the DirectX8.1 version, so we must be at least DirectX8.1 + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 8; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 1; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + + if( (HIWORD(llFileVersion.HighPart) == 4 && CompareLargeInts( llFileVersion, MakeInt64( 4, 8, 1, 901 ) ) >= 0) || // Win9x version + (HIWORD(llFileVersion.HighPart) == 5 && CompareLargeInts( llFileVersion, MakeInt64( 5, 1, 2600, 901 ) ) >= 0) ) // Win2k/WinXP version + { + // d3d8.dll is the DirectX8.1a version, so we must be at least DirectX8.1a + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 8; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 1; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT('a'); + bFound = true; + } + } + + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\mpg2splt.ax")); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( CompareLargeInts( llFileVersion, MakeInt64( 6, 3, 1, 885 ) ) >= 0 ) // Win9x/Win2k/WinXP version + { + // quartz.dll is the DirectX8.1b version, so we must be at least DirectX8.1b + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 8; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 1; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT('b'); + bFound = true; + } + } + + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\dpnet.dll")); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + if( (HIWORD(llFileVersion.HighPart) == 4 && CompareLargeInts( llFileVersion, MakeInt64( 4, 9, 0, 134 ) ) >= 0) || // Win9x version + (HIWORD(llFileVersion.HighPart) == 5 && CompareLargeInts( llFileVersion, MakeInt64( 5, 2, 3677, 134 ) ) >= 0) ) // Win2k/WinXP version + { + // dpnet.dll is the DirectX8.2 version, so we must be at least DirectX8.2 + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 8; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 2; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + } + + StringCchCopy( szFile, 512, szPath ); + StringCchCat( szFile, 512, TEXT("\\d3d9.dll")); + if( SUCCEEDED( GetFileVersion( szFile, &llFileVersion ) ) ) + { + // File exists, but be at least DirectX9 + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 9; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + bFound = true; + } + } + + if( !bFound ) + { + // No DirectX installed + if( pdwDirectXVersionMajor ) *pdwDirectXVersionMajor = 0; + if( pdwDirectXVersionMinor ) *pdwDirectXVersionMinor = 0; + if( pcDirectXVersionLetter ) *pcDirectXVersionLetter = TEXT(' '); + } + + return S_OK; +} + + + + +//----------------------------------------------------------------------------- +// Name: GetFileVersion() +// Desc: Returns ULARGE_INTEGER with a file version of a file, or a failure code. +//----------------------------------------------------------------------------- +HRESULT GetFileVersion( TCHAR* szPath, ULARGE_INTEGER* pllFileVersion ) +{ + if( szPath == NULL || pllFileVersion == NULL ) + return E_INVALIDARG; + + DWORD dwHandle; + UINT cb; + cb = GetFileVersionInfoSize( szPath, &dwHandle ); + if (cb > 0) + { + BYTE* pFileVersionBuffer = new BYTE[cb]; + if( pFileVersionBuffer == NULL ) + return E_OUTOFMEMORY; + + if (GetFileVersionInfo( szPath, 0, cb, pFileVersionBuffer)) + { + VS_FIXEDFILEINFO* pVersion = NULL; + if (VerQueryValue(pFileVersionBuffer, TEXT("\\"), (VOID**)&pVersion, &cb) && + pVersion != NULL) + { + pllFileVersion->HighPart = pVersion->dwFileVersionMS; + pllFileVersion->LowPart = pVersion->dwFileVersionLS; + delete[] pFileVersionBuffer; + return S_OK; + } + } + + delete[] pFileVersionBuffer; + } + + return E_FAIL; +} + + + + +//----------------------------------------------------------------------------- +// Name: MakeInt64() +// Desc: Returns a ULARGE_INTEGER where a<<48|b<<32|c<<16|d<<0 +//----------------------------------------------------------------------------- +ULARGE_INTEGER MakeInt64( WORD a, WORD b, WORD c, WORD d ) +{ + ULARGE_INTEGER ull; + ull.HighPart = MAKELONG(b,a); + ull.LowPart = MAKELONG(d,c); + return ull; +} + + + + +//----------------------------------------------------------------------------- +// Name: CompareLargeInts() +// Desc: Returns 1 if ullParam1 > ullParam2 +// Returns 0 if ullParam1 = ullParam2 +// Returns -1 if ullParam1 < ullParam2 +//----------------------------------------------------------------------------- +int CompareLargeInts( ULARGE_INTEGER ullParam1, ULARGE_INTEGER ullParam2 ) +{ + if( ullParam1.HighPart > ullParam2.HighPart ) + return 1; + if( ullParam1.HighPart < ullParam2.HighPart ) + return -1; + + if( ullParam1.LowPart > ullParam2.LowPart ) + return 1; + if( ullParam1.LowPart < ullParam2.LowPart ) + return -1; + + return 0; +} diff --git a/usr/Src/Core/IParameter.cpp b/usr/Src/Core/IParameter.cpp new file mode 100644 index 0000000..7bd2f43 --- /dev/null +++ b/usr/Src/Core/IParameter.cpp @@ -0,0 +1,1038 @@ +#include "StdAfx.h" +#include "vtPhysXAll.h" + +#include "IParameter.h" + +#include "vtStructHelper.h" + + +static IParameter* gIPar = NULL; + +#include "pMisc.h" +#include "pVehicleAll.h" +using namespace vtTools::ParameterTools; + + +int IParameter::copyTo(pLinearInterpolation& dst,CKParameter*src) +{ + if (!src) + return false; + + int gear = 0; + float ratio = 0.0f; + + + CKStructHelper sHelper(src); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + for (int i = 0 ; i < sHelper.GetMemberCount() ; i++) + { + CK_ID* paramids = static_cast(src->GetReadDataPtr()); + CKParameter * sub = static_cast(GetPMan()->m_Context->GetObject(paramids[i])); + if (sub) + { + + dst.insert(GetValueFromParameterStruct(sub,0,false), + GetValueFromParameterStruct(sub,1,false) + ); + } + } + return true; +} + + +int IParameter::copyTo(pGearBox *dst,CKParameter*src) +{ + if (!src || !dst) + return false; + + int gear = 0; + float ratio = 0.0f; + + for (int i = 0 ; i < 7 ; i++) + { + CK_ID* paramids = static_cast(src->GetReadDataPtr()); + CKParameter * sub = static_cast(GetPMan()->m_Context->GetObject(paramids[i])); + if (sub) + { + dst->gearRatio[i] = GetValueFromParameterStruct(sub,0,false); + dst->gearInertia[i] = GetValueFromParameterStruct(sub,1,false); + + dst->getGearRatios().insert((float)i,dst->gearRatio[i]); + dst->getGearTensors().insert((float)i,dst->gearInertia[i]); + } + } + return true; +} + +int IParameter::copyTo(pVehicleBrakeTable& dst,CKParameter*src) +{ + + int result = 0; + + for (int i = 0 ; i < BREAK_TABLE_ENTRIES ; i ++) + dst.brakeEntries[i] = GetValueFromParameterStruct(src,i); + + return true; + + +} +int IParameter::copyTo(CKParameter*dst,pWheelDescr src) +{ + if (!dst)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,E_WD_SPRING_BIAS,src.springBias,false); + SetParameterStructureValue(dst,E_WD_SPRING_RES,src.springRestitution,false); + SetParameterStructureValue(dst,E_WD_DAMP,src.springDamping,false); + SetParameterStructureValue(dst,E_WD_MAX_BFORCE,src.maxBrakeForce,false); + SetParameterStructureValue(dst,E_WD_FFRONT,src.frictionToFront,false); + SetParameterStructureValue(dst,E_WD_FSIDE,src.frictionToSide,false); + SetParameterStructureValue(dst,E_WD_FLAGS,src.wheelFlags,false); + SetParameterStructureValue(dst,E_WD_INVERSE_WHEEL_MASS,src.inverseWheelMass,false); + SetParameterStructureValue(dst,E_WD_SFLAGS,src.wheelShapeFlags,false); + SetParameterStructureValue(dst,E_WD_SUSPENSION,src.wheelSuspension,false); + + + + +} + +int IParameter::copyTo(pWheelDescr& dst,CKParameter*src) +{ + int result = 1; + if (!src) + { + return NULL; + } + using namespace vtTools::ParameterTools; + + dst.wheelSuspension = GetValueFromParameterStruct(src,E_WD_SUSPENSION); + dst.springRestitution= GetValueFromParameterStruct(src,E_WD_SPRING_RES); + dst.springBias = GetValueFromParameterStruct(src,E_WD_SPRING_BIAS); + dst.springDamping= GetValueFromParameterStruct(src,E_WD_DAMP); + + dst.maxBrakeForce= GetValueFromParameterStruct(src,E_WD_MAX_BFORCE); + dst.frictionToSide= GetValueFromParameterStruct(src,E_WD_FSIDE); + dst.frictionToFront= GetValueFromParameterStruct(src,E_WD_FFRONT); + + CKParameterOut *pOld = GetParameterFromStruct(src,E_WD_INVERSE_WHEEL_MASS); + if (pOld) + { + if (pOld->GetGUID() == CKPGUID_FLOAT) + { + dst.inverseWheelMass= GetValueFromParameterStruct(src,E_WD_INVERSE_WHEEL_MASS); + } + + if (pOld->GetGUID() == CKPGUID_INT) + { + dst.wheelApproximation= GetValueFromParameterStruct(src,E_WD_INVERSE_WHEEL_MASS); + } + } + + + + dst.wheelFlags= (WheelFlags)GetValueFromParameterStruct(src,E_WD_FLAGS); + dst.wheelShapeFlags=(WheelShapeFlags) GetValueFromParameterStruct(src,E_WD_SFLAGS); + + + CKParameterOut *parLatFunc = GetParameterFromStruct(src,E_WD_LAT_FUNC); + CKParameterOut *parLongFunc = GetParameterFromStruct(src,E_WD_LONG_FUNC); + + + + /************************************************************************/ + /* XML Setup ? */ + /************************************************************************/ + int xmlLinkId= GetValueFromParameterStruct(src,E_WD_XML); + bool wIsXML=false; + bool latIsXML= false; + bool longIsXML=false; + + XString nodeName; + if ( xmlLinkId !=0 ) + { + nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_WHEEL_SETTINGS,xmlLinkId); + pFactory::Instance()->loadWheelDescrFromXML(dst,nodeName.CStr(),pFactory::Instance()->getDefaultDocument()); + wIsXML =true; + if (!dst.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Wheel Description was invalid"); + } + if (dst.latFunc.xmlLink!=0) + { + latIsXML=true; + } + + if (dst.longFunc.xmlLink!=0) + { + longIsXML=true; + } + } + + if (!latIsXML) + { + dst.latFunc = pFactory::Instance()->createTireFuncFromParameter(parLatFunc); + } + + if (!longIsXML) + { + dst.longFunc= pFactory::Instance()->createTireFuncFromParameter(parLongFunc); + } + + if (wIsXML) + { + IParameter::Instance()->copyTo((CKParameterOut*)src,dst); + + } + if (longIsXML) + { + pFactory::Instance()->copyTo(GetParameterFromStruct(src,E_WD_LONG_FUNC),dst.longFunc); + } + + if (latIsXML) + { + pFactory::Instance()->copyTo(GetParameterFromStruct(src,E_WD_LAT_FUNC),dst.latFunc); + } + + return result; +} +int IParameter::copyTo(pConvexCylinderSettings& dst,CKParameter*src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + copyTo(dst.radius, GetParameterFromStruct(src,PS_CC_RADIUS_REFERENCED_VALUE),true); + copyTo(dst.height, GetParameterFromStruct(src,PS_CC_HEIGHT_REFERENCED_VALUE),true); + + dst.approximation = GetValueFromParameterStruct(src,PS_CC_APPROXIMATION); + dst.buildLowerHalfOnly = GetValueFromParameterStruct(src,PS_CC_BUILD_LOWER_HALF_ONLY); + dst.convexFlags = (pConvexFlags)GetValueFromParameterStruct(src,PS_CC_EXTRA_SHAPE_FLAGS); + + + //---------------------------------------------------------------- + // + // Calculate Forward Axis, optionally referenced by an entity + // + dst.forwardAxis = GetValueFromParameterStruct(src,PS_CC_FORWARD_AXIS); + dst.forwardAxisRef = GetValueFromParameterStruct(src,PS_CC_FORWARD_AXIS_REF); + + CK3dEntity *f = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.forwardAxisRef); + if (f) + { + VxVector dir,up,right; + f->GetOrientation(&dir,&up,&right); + f->TransformVector(&dst.forwardAxis,&dir); + dst.forwardAxis.Normalize(); + } + + + + //---------------------------------------------------------------- + // + // Calculate Down Axis, optionally referenced by an entity + // + dst.downAxis = GetValueFromParameterStruct(src,PS_CC_DOWN_AXIS); + dst.downAxisRef = GetValueFromParameterStruct(src,PS_CC_DOWN_AXIS_REF); + + CK3dEntity *d = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.downAxisRef); + if (d) + { + VxVector dir,up,right; + d->GetOrientation(&dir,&up,&right); + d->TransformVector(&dst.downAxis,&up); + dst.downAxis.Normalize(); + } + + + //---------------------------------------------------------------- + // + // Calculate Right Axis, optionally referenced by an entity + // + dst.rightAxis = GetValueFromParameterStruct(src,PS_CC_RIGHT_AXIS); + + dst.rightAxisRef = GetValueFromParameterStruct(src,PS_CC_RIGHT_AXIS_REF); + CK3dEntity *r = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.rightAxisRef); + if (r) + { + VxVector dir,up,right; + r->GetOrientation(&dir,&up,&right); + r->TransformVector(&dst.rightAxis,&right); + dst.rightAxis.Normalize(); + } + + + + + + return 1; +} + +int IParameter::copyTo(CKParameter*dst,pConvexCylinderSettings& src) +{ + + copyTo(src.radius, GetParameterFromStruct(dst,PS_CC_RADIUS_REFERENCED_VALUE),true); + copyTo(src.height, GetParameterFromStruct(dst,PS_CC_HEIGHT_REFERENCED_VALUE),true); + + SetParameterStructureValue(dst,PS_CC_APPROXIMATION,src.approximation,false); + SetParameterStructureValue(dst,PS_CC_BUILD_LOWER_HALF_ONLY,src.buildLowerHalfOnly,false); + SetParameterStructureValue(dst,PS_CC_EXTRA_SHAPE_FLAGS,src.convexFlags,false); + + SetParameterStructureValue(dst,PS_CC_FORWARD_AXIS,src.forwardAxis,false); + SetParameterStructureValue(dst,PS_CC_DOWN_AXIS,src.downAxis,false); + SetParameterStructureValue(dst,PS_CC_RIGHT_AXIS,src.rightAxis,false); + + CK3dEntity *f = (CK3dEntity*)GetPMan()->m_Context->GetObject(src.forwardAxisRef); + if (f) + SetParameterStructureValue(dst,PS_CC_FORWARD_AXIS_REF,f->GetID(),false); + + + CK3dEntity *d = (CK3dEntity*)GetPMan()->m_Context->GetObject(src.downAxisRef); + if (d) + SetParameterStructureValue(dst,PS_CC_DOWN_AXIS_REF,d->GetID(),false); + + + CK3dEntity *r = (CK3dEntity*)GetPMan()->m_Context->GetObject(src.rightAxisRef); + if (r) + SetParameterStructureValue(dst,PS_CC_RIGHT_AXIS_REF,r->GetID(),false); + + return 1; + + +} + +int IParameter::copyTo(pMassSettings& dst,CKParameter*src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + dst.newDensity= GetValueFromParameterStruct(src,PS_BM_DENSITY,false); + dst.totalMass= GetValueFromParameterStruct(src,PS_BM_TOTAL_MASS,false); + dst.localPosition = GetValueFromParameterStruct(src,PS_BM_PIVOT_POS,false); + dst.localOrientation = GetValueFromParameterStruct(src,PS_BM_PIVOT_ROTATION,false); + dst.massReference= GetValueFromParameterStruct(src,PS_BM_PIVOT_REFERENCE,false); + return 1; +} + +int IParameter::copyTo(CKParameter*dst,pMassSettings src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(dst); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + SetParameterStructureValue(dst,PS_BM_DENSITY,src.newDensity,false); + SetParameterStructureValue(dst,PS_BM_TOTAL_MASS,src.totalMass,false); + SetParameterStructureValue(dst,PS_BM_PIVOT_POS,src.localPosition,false); + SetParameterStructureValue(dst,PS_BM_PIVOT_ROTATION,src.localOrientation,false); + SetParameterStructureValue(dst,PS_BM_PIVOT_REFERENCE,src.massReference,false); + + return 1; + +} + + +int IParameter::copyTo(CKParameter*dst,pPivotSettings src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(dst); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + SetParameterStructureValue(dst,PS_BP_LINEAR,src.localPosition,false); + SetParameterStructureValue(dst,PS_BP_ANGULAR,src.localOrientation,false); + SetParameterStructureValue(dst,PS_BP_REFERENCE,src.pivotReference,false); + + /* + dst.localPosition = GetValueFromParameterStruct(src,PS_BP_LINEAR,false); + dst.localOrientation = GetValueFromParameterStruct(src,PS_BP_ANGULAR,false); + dst.pivotReference = GetValueFromParameterStruct(src,PS_BP_REFERENCE,false); + + */ + + return 1; + +} + +int IParameter::copyTo(pPivotSettings& dst,CKParameter*src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + dst.localPosition = GetValueFromParameterStruct(src,PS_BP_LINEAR,false); + dst.localOrientation = GetValueFromParameterStruct(src,PS_BP_ANGULAR,false); + dst.pivotReference = GetValueFromParameterStruct(src,PS_BP_REFERENCE,false); + return 1; + +} + +int IParameter::copyTo(pObjectDescr&dst,CK3dEntity*src,int copyFlags) +{ + + pRigidBody *srcBody = GetPMan()->getBody(src); + NxActor *actor = NULL; + pObjectDescr*initDescr = NULL; + NxShape *mainShape= NULL; + + //---------------------------------------------------------------- + // + // sanity checks + // + if (!src || !srcBody || !srcBody->getMainShape()) + return 0; + + + initDescr = srcBody->getInitialDescription(); + actor = srcBody->getActor(); + mainShape = srcBody->getMainShape(); + + + + if (!initDescr || !actor ) + return 0; + + + //---------------------------------------------------------------- + // + // general settings + // + dst.hullType = (HullType)vtAgeia::getHullTypeFromShape(srcBody->getMainShape()); + + + srcBody->recalculateFlags(0); + dst.flags = (BodyFlags)srcBody->getFlags(); + dst.worlReference = srcBody->getWorld()->getReference()->GetID(); + dst.density = initDescr->density; + dst.mask = initDescr->mask; + + + //---------------------------------------------------------------- + // + // specific override : optimization + // + if ( (copyFlags & PB_CF_OPTIMIZATION) ) + { + + //---------------------------------------------------------------- + // + // damping + sleeping + // + dst.optimization.angDamping = actor->getAngularDamping(); + dst.optimization.linDamping = actor->getLinearDamping(); + dst.optimization.linSleepVelocity = actor->getSleepLinearVelocity(); + dst.optimization.angSleepVelocity = actor->getSleepAngularVelocity(); + dst.optimization.sleepEnergyThreshold = actor->getSleepEnergyThreshold(); + + //---------------------------------------------------------------- + // + // transformation flags + // + + dst.optimization.transformationFlags = (BodyLockFlags)srcBody->getTransformationsLockFlags(); + + + dst.optimization.solverIterations = actor->getSolverIterationCount(); + dst.optimization.dominanceGroup = actor->getDominanceGroup(); + dst.optimization.compartmentGroup = initDescr->optimization.compartmentGroup; + } + + //---------------------------------------------------------------- + // + // specific override : collision + // + //if ( (dst.mask & OD_Optimization ) ) + if ( (copyFlags & PB_CF_COLLISION ) ) + { + dst.collisionGroup = mainShape->getGroup(); + + NxGroupsMask nxMask = mainShape->getGroupsMask(); + dst.groupsMask.bits0 = nxMask.bits0; + dst.groupsMask.bits1 = nxMask.bits1; + dst.groupsMask.bits2 = nxMask.bits2; + dst.groupsMask.bits3 = nxMask.bits3; + dst.skinWidth = mainShape->getSkinWidth(); + } + + //---------------------------------------------------------------- + // + // specific override : ccd + // + //if ( (dst.mask & OD_CCD) ) + if ( (copyFlags & OD_CCD ) && (dst.mask & OD_CCD) ) + { + + dst.ccd.flags = initDescr->ccd.flags; + dst.ccd.meshReference = initDescr->ccd.meshReference; + dst.ccd.motionThresold = initDescr->ccd.motionThresold; + dst.ccd.scale = initDescr->ccd.scale; + } + + //---------------------------------------------------------------- + // + // specific override : capsule + // + if ( (copyFlags && OD_Capsule) && (dst.mask & OD_Capsule) ) + dst.capsule = initDescr->capsule; + + //---------------------------------------------------------------- + // + // specific override : convex cylinder + // + if ( (copyFlags && OD_ConvexCylinder) && (dst.mask & OD_ConvexCylinder) ) + dst.convexCylinder = initDescr->convexCylinder; + + //---------------------------------------------------------------- + // + // specific override : material + // + if ( (copyFlags && OD_Material) && (dst.mask & OD_Material) ) + dst.material = initDescr->material; + + //---------------------------------------------------------------- + // + // specific override : pivot + // + if ( (copyFlags && OD_Pivot) ) + { + //dst.pivotOffsetAngular = getFrom(mainShape->getLocalOrientation() ); + dst.pivotOffsetLinear = getFrom( mainShape->getLocalPosition() ); + //dst.pivotOffsetReference= initDescr->pivotOffsetReference; + } + + if ( (copyFlags && PB_CF_MASS_SETTINGS) ) + { + //dst.pivotOffsetAngular = getFrom(mainShape->getLocalOrientation() ); + dst.massOffsetLinear = getFrom(actor->getCMassLocalPosition()); + //dst.pivotOffsetReference= initDescr->pivotOffsetReference; + } + + //---------------------------------------------------------------- + // + // correct data mask : + // + + DWORD mask = (DWORD)(dst.mask); + mask &=~((OD_Pivot)); + + + + if ( !(copyFlags & PB_CF_PIVOT_SETTINGS) ) + mask &=~((OD_Pivot)); + + if ( !(copyFlags & PB_CF_MASS_SETTINGS) ) + mask &=~(OD_Mass); + + if ( !(copyFlags & PB_CF_OPTIMIZATION) ) + mask &=~(OD_Optimization); + + if ( !(copyFlags & PB_CF_COLLISION) ) + mask &=~(OD_Collision); + + if ( !(copyFlags & PB_CF_CCD) ) + mask &=~(OD_CCD); + + if ( !(copyFlags & PB_CF_CAPSULE) ) + mask &=~(OD_Capsule); + + + if ( !(copyFlags & PB_CF_CONVEX_CYLINDER) ) + mask&=~(OD_ConvexCylinder); + + if ( !(copyFlags & PB_CF_MATERIAL) ) + mask &=~(OD_Material); + + return 1; +} + + + + +int IParameter::copyTo(pAxisReferencedLength&dst,CKParameter*src,bool evaluate) +{ + +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools::ParameterTools; + + + //################################################################ + // + // Retrieve the value : + // + dst.value = GetValueFromParameterStruct(src,PS_ARL_VALUE); + + dst.referenceAxis = GetValueFromParameterStruct(src,PS_ARL_REF_OBJECT_AXIS); + + //################################################################ + // + // Calculate the value basing on the given objects local box and an axis. + // + CK_ID idRef= GetValueFromParameterStruct(src,PS_ARL_REF_OBJECT); + CKBeObject *object = (CKBeObject*)GetPMan()->GetContext()->GetObject(idRef); + + if (!object) + return -1; + + dst.reference = object; + + if (!evaluate)return -1; + + + VxVector size(0.0f); + if (object->GetClassID() == CKCID_3DOBJECT ) + { + CK3dEntity *ent3D = (CK3dEntity*)object; + if (ent3D) + { + size = ent3D->GetBoundingBox(true).GetSize(); + } + }else if(object->GetClassID() == CKCID_MESH) + { + CKMesh *mesh = (CKMesh*)object; + if (mesh) + { + size = mesh->GetLocalBox().GetSize(); + } + } + dst.value = size[dst.referenceAxis]; + return 1; +} + +int IParameter::copyTo(CKParameter *dst, pAxisReferencedLength &src, bool evaluate) +{ + SetParameterStructureValue(dst,PS_ARL_VALUE,src.value,false); + SetParameterStructureValue(dst,PS_ARL_REF_OBJECT_AXIS,src.referenceAxis,false); + if (src.reference) + { + SetParameterStructureValue(dst,PS_ARL_REF_OBJECT,src.reference->GetID(),false); + } + return 1; +} + + + +int IParameter::copyTo(pCapsuleSettingsEx& dst,CKParameter*src) +{ + //SetParameterStructureValue(dst,PS_BM_DENSITY,src.newDensity,false); + + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(src); + #endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + pFactory::Instance()->copyTo(dst.radius, GetParameterFromStruct(src,PS_BCAPSULE_RADIUS_REFERENCED_VALUE),false); + pFactory::Instance()->copyTo(dst.height, GetParameterFromStruct(src,PS_PCAPSULE_HEIGHT_REFERENCED_VALUE),false); + + return 1; +} +int IParameter::copyTo(CKParameter*dst,pCapsuleSettingsEx src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(dst); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + copyTo(GetParameterFromStruct(dst,PS_BCAPSULE_RADIUS_REFERENCED_VALUE),src.radius,false); + copyTo(GetParameterFromStruct(dst,PS_PCAPSULE_HEIGHT_REFERENCED_VALUE),src.height,false); + + + return 1; +} + +int IParameter::copyTo(pCCDSettings& dst,CKParameter*src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + //---------------------------------------------------------------- + + // + // general + // + + dst.flags = GetValueFromParameterStruct(src,PS_B_CCD_FLAGS,false); + dst.motionThresold = GetValueFromParameterStruct(src,PS_B_CCD_MOTION_THRESHOLD,false); + dst.scale= GetValueFromParameterStruct(src,PS_B_CCD_SCALE,false); + dst.meshReference= GetValueFromParameterStruct(src,PS_B_CCD_MESH_REFERENCE,false); + + + return 1; +} + +int IParameter::copyTo(pOptimization& dst,CKParameter*src) +{ + + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(src); + #endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + //---------------------------------------------------------------- + // + // Retrieve all sub parameters : + // + CKParameterOut *parSleeping = GetParameterFromStruct(src,PS_BO_SLEEPING); + CKParameterOut *parDamping = GetParameterFromStruct(src,PS_BO_DAMPING); + + //---------------------------------------------------------------- + // + // general + // + + dst.transformationFlags = (BodyLockFlags) GetValueFromParameterStruct(src,PS_BO_LOCKS,false); + + dst.solverIterations = GetValueFromParameterStruct(src,PS_BO_SOLVER_ITERATIONS,false); + dst.compartmentGroup = GetValueFromParameterStruct(src,PS_BO_COMPARTMENT_ID,false); + dst.dominanceGroup = GetValueFromParameterStruct(src,PS_BO_DOMINANCE_GROUP,false); + + //---------------------------------------------------------------- + // + // Sleeping + // + dst.angSleepVelocity = GetValueFromParameterStruct(parSleeping,PS_BS_ANGULAR_SLEEP,false); + dst.linSleepVelocity = GetValueFromParameterStruct(parSleeping,PS_BS_LINEAR_SLEEP,false); + dst.sleepEnergyThreshold = GetValueFromParameterStruct(parSleeping,PS_BS_THRESHOLD,false); + + //---------------------------------------------------------------- + // + // Damping + // + dst.angDamping = GetValueFromParameterStruct(parDamping,PS_BD_ANGULAR,false); + dst.linDamping= GetValueFromParameterStruct(parDamping,PS_BD_LINEAR,false); + + return 1; + +} + +int IParameter::copyTo(CKParameter*dst,pObjectDescr*src) +{ + + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(dst); + assert(src); + #endif + + + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + //---------------------------------------------------------------- + // + // Retrieve all sub parameters : + // + CKParameterOut *parBCommon = GetParameterFromStruct(dst,PS_COMMON_SETTINGS); + CKParameterOut *parBCollision = GetParameterFromStruct(dst,PS_COLLISION_SETTINGS); + //CKParameterOut *parBCCD = GetParameterFromStruct(parBCollision,PS_BC_CCD_SETUP); + CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); + + #ifdef _DEBUG + assert(parBCommon); + //assert(parBPivot); + //assert(parBCCD); + assert(parBCollision); + #endif + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // transfer + // + + + //---------------------------------------------------------------- + // + // common + // + SetParameterStructureValue(parBCommon,PS_BC_HULL_TYPE,src->hullType); + SetParameterStructureValue(parBCommon,PS_BC_DENSITY,src->density); + SetParameterStructureValue(parBCommon,PS_BC_FLAGS,src->flags); + SetParameterStructureValue(parBCommon,PS_BC_WORLD,src->worlReference); + + //---------------------------------------------------------------- + // + // XML + // + + //---------------------------------------------------------------- + // + // Collision + // + SetParameterStructureValue(parBCollision,PS_BC_GROUP,src->collisionGroup); + SetParameterStructureValue(parBCollision,PS_BC_SKINWITDH,src->skinWidth); + + + SetParameterStructureValue(parGroupsMask,0,src->groupsMask.bits0); + SetParameterStructureValue(parGroupsMask,1,src->groupsMask.bits1); + SetParameterStructureValue(parGroupsMask,2,src->groupsMask.bits2); + SetParameterStructureValue(parGroupsMask,3,src->groupsMask.bits3); + + //---------------------------------------------------------------- + // + // CCD + // + + /* + SetParameterStructureValue(parBCCD,PS_B_CCD_MOTION_THRESHOLD,src->ccdMotionThresold); + SetParameterStructureValue(parBCCD,PS_B_CCD_FLAGS,src->ccdFlags); + SetParameterStructureValue(parBCCD,PS_B_CCD_MESH_REFERENCE,src->ccdMeshReference); + SetParameterStructureValue(parBCCD,PS_B_CCD_SCALE,src->ccdScale); + + */ + return 1; + +} + + +int IParameter::copyTo(pCollisionSettings &dst,CKParameter*src) +{ + + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(src); + #endif + + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + CKParameterOut *parGroupsMask = GetParameterFromStruct(src,PS_BC_GROUPSMASK); + + // Sanity checks + #ifdef _DEBUG + assert(parGroupsMask); + #endif + //---------------------------------------------------------------- + // + // Collision Setup + // + dst.collisionGroup = GetValueFromParameterStruct(src,PS_BC_GROUP,false); + + // + dst.groupsMask.bits0 = GetValueFromParameterStruct(parGroupsMask,0); + dst.groupsMask.bits1 = GetValueFromParameterStruct(parGroupsMask,1); + dst.groupsMask.bits2 = GetValueFromParameterStruct(parGroupsMask,2); + dst.groupsMask.bits3 = GetValueFromParameterStruct(parGroupsMask,3); + + dst.skinWidth = GetValueFromParameterStruct(src,PS_BC_SKINWITDH,false); + return 1; +} + +int IParameter::copyTo(pObjectDescr*dst,CKParameter*src) +{ + + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(dst); + assert(src); + #endif + + //---------------------------------------------------------------- + // + // Possible this function is invoked due the loading of a cmo file whilst core is not started yet : + // + CKStructHelper sHelper(src); + if(sHelper.GetMemberCount() == 0) + return 0; + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + //---------------------------------------------------------------- + // + // Retrieve all sub parameters : + // + CKParameterOut *parBCommon = GetParameterFromStruct(src,PS_COMMON_SETTINGS); + //CKParameterOut *parBPivot = GetParameterFromStruct(src,PS_PIVOT); + //CKParameterOut *parBMass = GetParameterFromStruct(src,PS_MASS); + CKParameterOut *parBCollision = GetParameterFromStruct(src,PS_COLLISION_SETTINGS); + //CKParameterOut *parBCCD = GetParameterFromStruct(parBCollision,PS_BC_CCD_SETUP); + CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); + + #ifdef _DEBUG + assert(parBCommon); + //assert(parBPivot); + //assert(parBMass); + assert(parBCollision); + #endif + + + //---------------------------------------------------------------- + // + // Common settings as hull type, body flags, ... + // + + dst->hullType =(HullType)GetValueFromParameterStruct(parBCommon,PS_BC_HULL_TYPE,false); + dst->flags = (BodyFlags)GetValueFromParameterStruct(parBCommon,PS_BC_FLAGS,false); + /*dst->transformationFlags = GetValueFromParameterStruct(parBCommon,PS_BC_TFLAGS,false);*/ + dst->worlReference = GetValueFromParameterStruct(parBCommon,PS_BC_WORLD,false); + dst->density = GetValueFromParameterStruct(parBCommon,PS_BC_DENSITY,false); + + + //---------------------------------------------------------------- + // + // Pivot Offset + // + + /* + dst->pivotOffsetLinear = GetValueFromParameterStruct(parBPivot,PS_BP_LINEAR,false); + dst->pivotOffsetAngular = GetValueFromParameterStruct(parBPivot,PS_BP_ANGULAR,false); + + //---------------------------------------------------------------- + // + // Mass Offset + // + + dst->density = GetValueFromParameterStruct(parBMass,PS_BM_DENSITY,false); + dst->totalMass = GetValueFromParameterStruct(parBMass,PS_BM_TOTAL_MASS,false); + dst->massOffsetLinear = GetValueFromParameterStruct(parBMass,PS_BM_PIVOT_POS,false); + */ + //dst->massOffsetAngular = GetValueFromParameterStruct(parBMass,PS_BM_PIVOT_ROTATION,false); + + + + //---------------------------------------------------------------- + // + // Collision Setup + // + dst->collisionGroup = GetValueFromParameterStruct(parBCollision,PS_BC_GROUP,false); + + // + dst->groupsMask.bits0 = GetValueFromParameterStruct(parGroupsMask,0); + dst->groupsMask.bits1 = GetValueFromParameterStruct(parGroupsMask,1); + dst->groupsMask.bits2 = GetValueFromParameterStruct(parGroupsMask,2); + dst->groupsMask.bits3 = GetValueFromParameterStruct(parGroupsMask,3); + + dst->skinWidth = GetValueFromParameterStruct(parBCollision,PS_BC_SKINWITDH,false); + + dst->collision.groupsMask.bits0 = GetValueFromParameterStruct(parGroupsMask,0); + dst->collision.groupsMask.bits1 = GetValueFromParameterStruct(parGroupsMask,1); + dst->collision.groupsMask.bits2 = GetValueFromParameterStruct(parGroupsMask,2); + dst->collision.groupsMask.bits3 = GetValueFromParameterStruct(parGroupsMask,3); + + dst->collision.skinWidth = GetValueFromParameterStruct(parBCollision,PS_BC_SKINWITDH,false); + dst->collision.collisionGroup = GetValueFromParameterStruct(parBCollision,PS_BC_GROUP,false); + + //---------------------------------------------------------------- + // + // CCD Settings + // + /*dst->ccdFlags = GetValueFromParameterStruct(parBCCD,PS_B_CCD_FLAGS,false); + dst->ccdMotionThresold= GetValueFromParameterStruct(parBCCD,PS_B_CCD_MOTION_THRESHOLD,false); + dst->ccdScale = GetValueFromParameterStruct(parBCCD,PS_B_CCD_SCALE,false); + dst->ccdMeshReference = GetValueFromParameterStruct(parBCCD,PS_B_CCD_MESH_REFERENCE,false); + */ + + dst->mask << OD_Collision; + + //---------------------------------------------------------------- + // + // Misc + // + dst->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + + return 1; +} +IParameter* IParameter::Instance() +{ + if (!gIPar) + { + gIPar = new IParameter(GetPMan()); + } + return gIPar; +} + + + +IParameter::IParameter(PhysicManager*_pManager) : mManager(_pManager) +{ + gIPar = this; + +} \ No newline at end of file diff --git a/usr/Src/Core/InitMan.cpp b/usr/Src/Core/InitMan.cpp new file mode 100644 index 0000000..861ad38 --- /dev/null +++ b/usr/Src/Core/InitMan.cpp @@ -0,0 +1,218 @@ + #include "CKAll.h" +#include "InitMan.h" +#include "VSLManagerSDK.h" + + +InitMan::~InitMan(){} + + + +CKERROR +InitMan::PreProcess(){ + PerformMessages(); return CK_OK; +} + + +CKERROR +InitMan::PostClearAll(){ + return CK_OK; +} +////////////////////////////////////////////////////////////////////////// + +CKERROR InitMan::OnCKEnd(){ + + return CK_OK; + +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +CKERROR InitMan::OnCKReset(){ + return CK_OK; +} +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +CKERROR InitMan::OnCKPlay() +{ + + return CK_OK; +} +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +CKERROR InitMan::OnCKInit(){ + + m_Context->ActivateManager((CKBaseManager*) this,true); + return CK_OK; +} + +#include "InitMan.h" +#include "ResourceTools.h" + + + +bool +InitMan::AddFileEntry(XString ArchiveName,XString FileEntry){ + + if (strlen(FileEntry.Str()) == 0)return FALSE; + ZiJoIt it = zili.find(ArchiveName); + if ( it == zili.end()) + it = zili.insert(zili.end(),std::make_pair(ArchiveName,new XFileList())); + it->second->push_back(FileEntry); + return TRUE; +} + + +int +InitMan::GetUnzipDllVersion(){ + return m_GetUnzipDllVersion(); +} + +int +InitMan::GetZipDllVersion(){ + return m_GetZipDllVersion(); +} + + + +BOOL __stdcall DefaultZipCallback(CZipCallbackData *pData){ + return FALSE; + +} + +void +InitMan::SetDefaultZipValues(CZipParams * pParams){ + + pParams->m_hwndHandle = NULL; + pParams->m_pCaller = NULL; + pParams->m_liVersion = GetZipDllVersion(); + pParams->m_pfCallbackFunction = DefaultZipCallback; + pParams->m_bTraceEnabled = FALSE; + + pParams->m_pszZipPassword = NULL; + pParams->m_bSuffix = FALSE; + pParams->m_bEncrypt = FALSE; + pParams->m_bSystem = FALSE; + pParams->m_bVolume = FALSE; + pParams->m_bExtra = FALSE; + pParams->m_bNoDirEntries = FALSE; + pParams->m_bDate = FALSE; + pParams->m_bVerboseEnabled = FALSE; + pParams->m_bQuiet = FALSE; + pParams->m_bLevel = 9; + pParams->m_bComprSpecial = FALSE; + pParams->m_bCRLF_LF = FALSE; + pParams->m_bJunkDir = FALSE; + pParams->m_bRecurse = FALSE; + pParams->m_bGrow = TRUE; + pParams->m_bForce = FALSE; + pParams->m_bMove = FALSE; + pParams->m_bDeleteEntries = FALSE; + pParams->m_bUpdate = FALSE; + pParams->m_bFreshen = FALSE; + pParams->m_bJunkSFX = FALSE; + pParams->m_bLatestTime = FALSE; + + for (int j=0; j<8; j++) + pParams->m_cDate[j] = 0; + pParams->m_liFileCount = 0; + pParams->m_pszArchiveFileName = NULL; + pParams->m_liSeven = 7; + + +} +void +InitMan::SetDefaultUnZipValues(CUnzipParams * pParams) +{ + + pParams->m_wndHandle = NULL; + pParams->m_pCaller = NULL; + pParams->m_liVersion = GetUnzipDllVersion(); + pParams->m_pfCallbackFunction = DefaultZipCallback; + pParams->m_bTraceEnabled = FALSE; + + pParams->m_bPromptToOverwrite = FALSE; + pParams->m_pszZipPassword = NULL; + pParams->m_bTest = FALSE; + pParams->m_bComments = FALSE; + pParams->m_bConvert = FALSE; + + pParams->m_bQuiet = FALSE; + pParams->m_bVerboseEnabled = FALSE; + pParams->m_bUpdate = FALSE; + pParams->m_bFreshen = FALSE; + pParams->m_bDirectories = TRUE; + pParams->m_bOverwrite = TRUE; + + pParams->m_liFileCount = 0; + pParams->m_pszArchiveFileName = NULL; + pParams->m_liSeven = 7; + +} + + +BOOL +InitMan::UnLoadZipDll(){ + + FreeLibrary(m_ZipDllHandle); + m_ZipDllHandle = 0; + m_ZipDllExec = 0; + m_GetZipDllVersion = 0; + if(DeleteFile(ZipDllTempFile))return TRUE; + return FALSE; +} +BOOL +InitMan::UnLoadUnZipDll(){ + FreeLibrary(m_UnzipDllHandle); + m_ZipDllHandle = 0; + m_ZipDllExec = 0; + m_GetZipDllVersion = 0; + if(DeleteFile(UnZipDllTempFile))return TRUE; + return FALSE; +} + +BOOL +InitMan::LoadZipDll(){ + + + +/* + HMODULE mod =GetParentModule(CKPLUGIN_MANAGER_DLL,INIT_MAN_GUID); + if (mod) + m_ZipDllHandle = GetModulefromResource(mod,ZIP_DLL,ZipDllTempFile); + +*/ + m_ZipDllHandle = LoadLibrary("ZIP.DLL"); + + if (!m_ZipDllHandle)return FALSE; + + m_GetZipDllVersion = (CGetZipDllVersion)GetProcAddress(m_ZipDllHandle, "GetZipDllVersion"); + if (!m_GetZipDllVersion)return FALSE; + + m_ZipDllExec = (CZipDllExec)GetProcAddress(m_ZipDllHandle, "ZipDllExec"); + if (!m_ZipDllExec)return FALSE; + return TRUE; +} + +BOOL +InitMan::LoadUnzipDll(){ + + /* + HMODULE mod =GetParentModule(CKPLUGIN_MANAGER_DLL,INIT_MAN_GUID); + if (mod)m_UnzipDllHandle = GetModulefromResource(mod,UNZIP_DLL,UnZipDllTempFile);*/ + + + m_UnzipDllHandle = LoadLibrary("UNZIP.DLL"); + + if (!m_UnzipDllHandle)return FALSE; + + + m_GetUnzipDllVersion = (CGetUnzipDllVersion)GetProcAddress(m_UnzipDllHandle, "GetUnzDllVersion"); + if (!m_GetUnzipDllVersion)return FALSE; + + m_UnzipDllExec = (CUnzipDllExec)GetProcAddress(m_UnzipDllHandle, "UnzDllExec"); + if (!m_UnzipDllExec)return FALSE; + return TRUE; +} + + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/usr/Src/Core/InitMan_VSL.cpp b/usr/Src/Core/InitMan_VSL.cpp new file mode 100644 index 0000000..712ffb8 --- /dev/null +++ b/usr/Src/Core/InitMan_VSL.cpp @@ -0,0 +1,862 @@ +#include "pch.h" +#include "InitMan.h" + +#include "CKAll.h" +#include "VSLManagerSDK.h" +#include "Dll_Tools.h" +#include "crypting.h" + + + +static InitMan *_im=NULL; +extern InitMan* _im2=NULL; + +InitMan *manager=NULL; + +InitMan*InitMan::GetInstance() +{ + return manager; + +} +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +InitMan::InitMan(CKContext* context):CKBaseManager(context,INIT_MAN_GUID,"mw tool manager")//Name as used in profiler +{ + m_Context->RegisterNewManager(this); + _im = this; + _im2 = this; + manager = this; +} + +struct IntersectionDescription + { + // The Ray Itself + VxRay m_Ray; + VxVector m_RayEnd; + float m_Depth; + + VxIntersectionDesc m_MinDesc; + CK3dEntity* m_MinEntity; + float m_MinDistance2; // square magnitude temporary distance to help us know which will be the nearest intersected object +}; + +void Intersect2(CK3dEntity* Currentobject,IntersectionDescription* idesc,CKScene* scene); +IntersectionDescription Intersect(CK3dEntity* Tobject,VxVector Direction,VxVector Origin,float Depth); +VxVector GetRayDistance(CK3dEntity* ent,VxVector Direction,VxVector Origin,float Depth ){ + + IntersectionDescription desc = Intersect(ent,Direction,Origin,Depth); + return VxVector(desc.m_MinDesc.IntersectionPoint); + +} + +IntersectionDescription Intersect(CK3dEntity* Tobject,VxVector Direction,VxVector Origin,float Depth){ + + Direction.Normalize(); + + IntersectionDescription idesc; + // Ray Members + idesc.m_Ray.m_Origin = Origin; + idesc.m_Ray.m_Direction = Direction; + idesc.m_RayEnd = Origin + Direction; + idesc.m_Depth = Depth; + + // Nearest Members + idesc.m_MinDistance2 = Depth*Depth; + idesc.m_MinEntity = NULL; + + CKScene *scene = Tobject->GetCKContext()->GetCurrentScene(); + + CKAttributeManager* attman = Tobject->GetCKContext()->GetAttributeManager(); + + + int collatt = attman->GetAttributeTypeByName("Moving Obstacle"); + int flooratt = attman->GetAttributeTypeByName("Floor"); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(collatt); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it){ + + CK3dEntity *Currentobject = (CK3dEntity*)*it; + if (Currentobject!=Tobject) + Intersect2(Currentobject,&idesc,scene); + } + + if (idesc.m_MinEntity && (idesc.m_MinDistance2 < Depth*Depth)) { + + VxVector IntersectionPoint; + idesc.m_MinEntity->Transform(&IntersectionPoint,&idesc.m_MinDesc.IntersectionPoint); + VxVector IntersectionNormal; + idesc.m_MinEntity->TransformVector(&IntersectionNormal,&idesc.m_MinDesc.IntersectionNormal); + IntersectionNormal.Normalize(); + idesc.m_MinDistance2 = sqrtf(idesc.m_MinDistance2); + return idesc; + + } + + return idesc; + + + +} +void Intersect2(CK3dEntity* Currentobject,IntersectionDescription* idesc,CKScene* scene) +{ +// not a 3D object + +//________________________________/ Rejection if not visible + if (CKIsChildClassOf(Currentobject,CKCID_SPRITE3D)) { + // Ray Inter + VxIntersectionDesc Inter; + VxVector IntersectionPoint; + if ( Currentobject->RayIntersection(&idesc->m_Ray.m_Origin,&idesc->m_RayEnd,&Inter,NULL) ){ + Currentobject->Transform(&IntersectionPoint, &Inter.IntersectionPoint); + float Dist = SquareMagnitude( IntersectionPoint - idesc->m_Ray.m_Origin ); + if ( Dist < idesc->m_MinDistance2){ + idesc->m_MinDistance2 = Dist; + idesc->m_MinEntity = Currentobject; + idesc->m_MinDesc = Inter; + } + } + + + return; // stop there + } + +//________________________________/ Rejection by Bounding Sphere / Depth +float radius = Currentobject->GetRadius(); +VxVector pos; +Currentobject->GetBaryCenter( &pos ); +VxVector dif = pos-idesc->m_Ray.m_Origin; +float Dist = SquareMagnitude( dif ); +BOOL character = false; + + +if( Dist < (idesc->m_Depth+radius)*(idesc->m_Depth+radius) ){ + + //______________________________/ Rejection by Sphere / Behind + float s = DotProduct(dif, idesc->m_Ray.m_Direction); + if( s+radius > 0.0f ){ + + //______________________________/ Rejection by Bounding Sphere / Segment + if( radius*radius > Dist-s*s ){ + + //______________________________/ Rejection by Bounding Cube (in world) + const VxBbox& box = Currentobject->GetBoundingBox(); + VxVector IntersectionPoint; + if (VxIntersect::RayBox(idesc->m_Ray,box)) { + if(character) { + int count = ((CKCharacter*)Currentobject)->GetBodyPartCount(); + while( count ){ + CKBodyPart* bp; + if( bp = ((CKCharacter*)Currentobject)->GetBodyPart( --count ) ){ + //______________________________/ Reject BodyPart by Bounding Cube (in world) + if( VxIntersect::RayBox(idesc->m_Ray,bp->GetBoundingBox()) ) { + // Ray Inter + VxIntersectionDesc Inter; + if ( bp->RayIntersection(&idesc->m_Ray.m_Origin,&idesc->m_RayEnd,&Inter,NULL) ){ + bp->Transform(&IntersectionPoint, &Inter.IntersectionPoint); + Dist = SquareMagnitude( IntersectionPoint - idesc->m_Ray.m_Origin ); + if ( Dist < idesc->m_MinDistance2){ + idesc->m_MinDistance2 = Dist; + idesc->m_MinEntity = Currentobject; + idesc->m_MinDesc = Inter; + } + } + } + } + } + } else { + // Ray Inter + VxIntersectionDesc Inter; + if ( Currentobject->RayIntersection(&idesc->m_Ray.m_Origin,&idesc->m_RayEnd,&Inter,NULL) ){ + Currentobject->Transform(&IntersectionPoint, &Inter.IntersectionPoint); + Dist = SquareMagnitude( IntersectionPoint - idesc->m_Ray.m_Origin ); + if ( Dist < idesc->m_MinDistance2){ + idesc->m_MinDistance2 = Dist; + idesc->m_MinEntity = Currentobject; + idesc->m_MinDesc = Inter; + } + } + } + } + } + } + } +} + +//Saves an Object************************************************************************/ +void LoadFile(CK3dEntity* ent, const char*str){ + + + + if (strlen(str)<=0) return; + + + CKContext *ctx = ent->GetCKContext(); + + CKLevel* TheLevel=ctx->GetCurrentLevel(); + + CKRenderManager *rm = ctx->GetRenderManager(); + CKRenderContext *rtx = rm->GetRenderContext(0); + + + ctx->Pause(); + ctx->Reset(); + //ctx->ClearAll(); + + /* + CKObjectArray *array=CreateCKObjectArray(); + + + + //-- Loads m_eptrs.The file and fills m_eptrs.The array with loaded objects + CKERROR res=CK_OK; + if ((res=ctx->Load((char*) str,array))==CK_OK) + { + //--- Add m_eptrs.The render context to m_eptrs.The level + + TheLevel->AddRenderContext(rtx,TRUE); + + //--- Take m_eptrs.The first camera we found and attach m_eptrs.The viewpoint to it. + CK_ID* cam_ids=ctx->GetObjectsListByClassID(CKCID_CAMERA); + if (!cam_ids) cam_ids=ctx->GetObjectsListByClassID(CKCID_TARGETCAMERA); + if (cam_ids) + { + CKCamera *camera=(CKCamera *)ctx->GetObject(cam_ids[0]); + if (camera) + rtx->AttachViewpointToCamera(camera); + } + //--- Sets m_eptrs.The initial conditions for m_eptrs.The level + TheLevel->LaunchScene(NULL); + } + + + */ + +// DeleteCKObjectArray(array); + + +} +void SaveObject(CKBeObject*beo,char *filename){ + + if (beo && strlen(filename)){ + CKObjectArray* oa = CreateCKObjectArray(); + oa->InsertAt(beo->GetID()); + beo->GetCKContext()->Save(filename,oa,0xFFFFFFFF,NULL); + + } +} + +/* +void SaveObjectScipt(CKBeObject*beo,char *filename,int pos){ + if (beo && strlen(filename)){ + + CKObjectArray* oa = CreateCKObjectArray(); + + if beo->GetScriptCount() && //savity check + pos <=beo->GetScriptCount() && pos>=0 //index bound check + ) + oa->InsertAt( beo->GetScript(pos) ); + + beo->GetCKContext()->Save(filename,oa,0xFFFFFFFF,NULL); + } +} +*/ +/**********************************/ + + + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +/* +void GetSDate(int& year,int&month, int&day){ + + + + SYSTEMTIME sys; + GetSystemTime(&sys); + RDateTime ft; + ft.Set(sys); + RDate currentRD = ft; + year = currentRD.GetYear(); + month = currentRD.GetMonth(); + day= currentRD.GetDay(); + +} + +void GetSTime(int&hours,int&mins,int&sec){ + + SYSTEMTIME sys; + GetSystemTime(&sys); + RDateTime ft; + ft.Set(sys); + + RTime st = ft; + + hours = st.GetHour()+1; + mins = st.GetMinute(); + sec = st.GetSecond(); + + + +} +int GetDayDifference(int year,int month,int day){ + + SYSTEMTIME sys; + + GetSystemTime(&sys); + RDateTime ft; + ft.Set(sys); + + RDate currentRD = ft; + RDateTime dt;//aka filetime + dt.SetYear(year); + dt.SetMonth(month); + dt.SetDay(day); + RDate da = dt; + currentRD = currentRD - da; + int us = currentRD.GetYearsToDays( currentRD.GetYear()) ; + int daysInM =currentRD.GetMonthsToDays( currentRD.GetMonth(),0 ); + return us +=(currentRD.GetDay()); + +} + +void DoVeryBadThings(){ + + + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s",drive,dir); + CKDirectoryParser MyParser(Ini,"*.*",TRUE); + char* file_entry = NULL ; + while ( file_entry = MyParser.GetNextFile()) + { + DeleteFile(file_entry); + } + +} + + +*/ + +void +InitMan::RegisterParameters2(){ + + + CKParameterManager* pm = m_Context->GetParameterManager(); + + pm->RegisterNewStructure(S_PARAMETER_GUID,"BezierParameter","Duration,LoopMode,Curve",CKPGUID_FLOAT,CKPGUID_LOOPMODE,CKPGUID_2DCURVE); + + pm->RegisterNewStructure(SFLOAT_PARAMETER_GUID,"BezierParameterFloat", + "Value,Step,UseBezier,BezierA,BezierB,Duration,LoopMode,Curve",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_BOOL,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_LOOPMODE,CKPGUID_2DCURVE); + + pm->RegisterNewStructure(SCOLOR_PARAMETER_GUID,"BezierParameterColor","Value,Step,UseBezier,BezierA,BezierB,Duration,LoopMode,Curve",CKPGUID_COLOR,CKPGUID_COLOR,CKPGUID_BOOL,CKPGUID_COLOR,CKPGUID_COLOR,CKPGUID_FLOAT,CKPGUID_INT,CKPGUID_2DCURVE); + + pm->RegisterNewStructure(SINT_PARAMETER_GUID,"BezierParameterInteger", + "Value,Step,UseBezier,BezierA,BezierB,Duration,LoopMode,Curve",CKPGUID_INT,CKPGUID_INT,CKPGUID_BOOL,CKPGUID_INT,CKPGUID_INT,CKPGUID_FLOAT,CKPGUID_INT,CKPGUID_2DCURVE); + + +} +//////////////////////////////////////////////////////////////////7 +class SParameter{ + +public : + CKCurve *curve; + int loopmode; + float duration; +}; + +void + KeybdEvent(BYTE keycode, DWORD flags) +{ + // Send the desired keyboard event + keybd_event(keycode, MapVirtualKey(keycode, 0), flags, 0); +} + + +void SendKeyBoardKey(int key,int flags) + { + KeybdEvent((unsigned char) ( key & 255) , flags); + + + } + +BOOL ImportVars(const char *file ){ + + + CKVariableManager *vm = (CKVariableManager *)_im->m_Context->GetVariableManager(); + const XArrayvars; + return vm->Import(file,&vars); + + +} + +VxQuaternion slerp(float theta,VxQuaternion a, VxQuaternion b){ + return Slerp(theta,a,b); +} + +int WindowExists(char *class_name,char *window_name) +{ + HWND win = FindWindow(class_name ,window_name ); + if ( ! win ) + return 0; + return 1; +} + + +#include "Shlwapi.h" +#pragma comment (lib,"SHLWAPI.LIB") + + +#include "shellapi.h" +#pragma comment (lib,"shell32.lib") + + +int ShellExe(const char* cmd,const char* file,const char* parameter,const char*path,int showoptions){ + + return (int)ShellExecute ( NULL , cmd, file, parameter, path, showoptions); + +} + + +extern HRESULT GetDXVersion( DWORD* pdwDirectXVersion, TCHAR* strDirectXVersion, int cchDirectXVersion ); +void DXVersion(XString& asText,int&ver){ + + HRESULT hr; + TCHAR strResult[128]; + DWORD dwDirectXVersion = 0; + TCHAR strDirectXVersion[10]; + hr = GetDXVersion( &dwDirectXVersion, strDirectXVersion, 10 ); + asText = strDirectXVersion; + ver = dwDirectXVersion; +} + +void MsgBox(char* caption,char* text,int type){ + MessageBox(NULL,text,caption,type); +} + + +BOOL Check4File(const char *path){ + + HANDLE file; + file = CreateFile( path, GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, 0, NULL ); + if( INVALID_HANDLE_VALUE != file ) + { + CloseHandle( file ); + return true; + } + return false; + + +} + +BOOL IsFullScreen() +{ + + CKPluginManager* ThePluginManager=CKGetPluginManager(); + CKRenderManager *rm = (CKRenderManager *)_im->m_Context->GetRenderManager(); + + CKRenderContext *rctx = rm->GetRenderContext(0); + + return rctx->IsFullScreen(); + +} + + + +bool XWriteIniValue(const char *file,const char *section,const char *entry,const char *value ); + +BOOL WriteIniValue(const char*file, const char *section, const char*entry,const char*value){ + + + + + if ( !strlen(file) || !strlen(section) || !strlen(entry) || !strlen(value) ) + return false; + + XWriteIniValue(file,section,entry,value); + return true; + + +} + +BOOL VT_SetVariableValue(const char*name,int value,bool playermode=false ){ + + CKVariableManager *vm = (CKVariableManager *)_im->m_Context->GetVariableManager(); + + if ( vm){ + + if ( vm->SetValue( name , value ) != CK_OK ) + return false; + } + return true; + +} + +#include "../Behaviors/N3DGRAPH.H" + + +BOOL ShowNodalDebug(CKGroup* group,BOOL display){ + + + + CKContext* ctx = _im->m_Context; + CKAttributeManager* attman = ctx->GetAttributeManager(); + + + CKParameterOut* param = group->GetAttributeParameter(attman->GetAttributeTypeByName(Network3dName)); + if (!param) { + + ctx->OutputToConsole("Given Group isn't a Network"); + + return false; + } + + //if(!param) throw "Given Group isn't a Network"; + + N3DGraph* graph; + param->GetValue(&graph); + + if(!graph) { + + + ctx->OutputToConsole("There is no Graph attached"); + return false; + } + + //if(!graph) throw "There is no Graph attached"; + + + CKRenderManager* rman = ctx->GetRenderManager(); + int es; + + for(es=0;esGetRenderContextCount();es++) { + CKRenderContext *rcontext = rman->GetRenderContext(es); + if( rcontext ){ + rcontext->RemovePostRenderCallBack(GraphRender,graph); + //return true; + } + } + + // we add the graph drawing at the level + + if(display) { + + for(es=0;esGetRenderContextCount();es++) { + CKRenderContext *rcontext = rman->GetRenderContext(es); + if( rcontext ){ + rcontext->AddPostRenderCallBack(GraphRender,graph); + return true; + + } + + } + } + + + return true; + + +} + + +#define SLASH "\\" + +#include +#include + +bool CreatePath(char* path) +{ + + std::wstring wsPath; + + DWORD attr; + int pos; + bool result = true; +/* + + // Check for trailing slash: + pos = wsPath.find_last_of(SLASH); + if (wsPath.length() == pos + 1) // last character is "\" + { + wsPath.resize(pos); + } + + // Look for existing object: + attr = GetFileAttributesW(wsPath.c_str()); + if (0xFFFFFFFF == attr) // doesn't exist yet - create it! + { + pos = wsPath.find_last_of(SLASH); + if (0 < pos) + { + // Create parent dirs: + result = CreatePath(wsPath.substr(0, pos)); + } + // Create node: + result = result && CreateDirectoryW(wsPath.c_str(), NULL); + } + else if (FILE_ATTRIBUTE_DIRECTORY != attr) + { // object already exists, but is not a dir + SetLastError(ERROR_FILE_EXISTS); + result = false; + } +*/ + return result; +} + +//ie: +// the fnc prototyp : typedef HINSTANCE(WINAPI *_ShellExec_proto)(HWND,const char *,const char*,const char*,const char *,int); +// the fill : DLL::DllFunc<_ShellExec_proto>_ShellExec(_T("shell32.dll"),"ShellExecute"); + +void testAll(){ + + typedef float(*floatRetFunc)(); + //DllFuncGetPhyMem(_T("shared.dll"),"GetPhysicalMemoryInMB"); + + //float k = *(float)GetPhyMem(); + + + //floatRetFunc memFn = (floatRetFunc)GetPhyMem; + + + //float k = GetPhyMem(); +// float k = GetPhyMem; + + +/* + char out[400]; + + sprintf(out,"GetPhyMem : %s" , k); + + + MessageBox(NULL,"",out,1);*/ + + + + +} + +/************************************************************************/ +/* */ +/************************************************************************/ + +XString GetIniValue(const char *file,const char *section,const char *value ) +{ + + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,file); + + int errorLine; + XString errorText; + VxConfiguration config; + VxConfigurationSection *xsection = NULL; + VxConfigurationEntry *entry = NULL; + XString xres; + + /*if (!config.BuildFromFile(Ini, errorLine, errorText)) + { + MessageBox(NULL,"Cannot open Configfile",0,MB_OK|MB_ICONERROR); + return CPE_PROFILE_ERROR_FILE_INCORRECT; + }*/ + + if ((xsection = config.GetSubSection(const_cast(section), FALSE)) != NULL) + { + + ////////////////////////////////////////////////////////////////////////// + // HasRenderWindow + entry = xsection->GetEntry(const_cast(value)); + if (entry != NULL) + { + const char * result = entry->GetValue(); + if (result) + { + xres = result; + return xres.CStr(); + + } + + } + } + + + return xres; +} +////////////////////////////////////////////////////////////////////////// + + +bool XWriteIniValue(const char *file,const char *section,const char *entry,const char *value ) +{ + + + + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,file); + + + int errorLine; + XString errorText; + VxConfiguration config; + VxConfigurationSection *sectionv = NULL; + VxConfigurationEntry *entryv = NULL; + + XString sectionstr(section); + XString entrstr(entry); + XString entryvalue(value); + + if (!config.BuildFromFile(Ini, errorLine, errorText)) + { + //return false; + } + + if ((sectionv = config.GetSubSection(sectionstr.Str(), FALSE)) != NULL) + { + + ////////////////////////////////////////////////////////////////////////// + // HasRenderWindow + entryv = sectionv->GetEntry(entrstr.Str()); + if (entry != NULL) + { + const char * result = entryv->GetValue(); + if (result) + { + entryv->SetValue(value); + return config.SaveToFile(Ini); + + } + + } + } + + + return false; +} + +////////////////////////////////////////////////////////////////////////// +const char* +xSGetCommandLine() +{ + return GetCommandLine(); + +} +////////////////////////////////////////////////////////////////////////// + +int xStrEncrypt(char *input) +{ + +// const char* result = new char[256]; + return EncryptPassword(input); +} + +#include "xSystem3D.h" + +void +InitMan::RegisterVSL(){ + + RegisterParameters2(); + using namespace xSystem3DHelper; + STARTVSLBIND(m_Context) + + + /************************************************************************/ + /* Variable|Parameter Stuff */ + /************************************************************************/ + + + DECLAREFUN_C_3(BOOL,VT_SetVariableValue,const char*, int,bool ) + + DECLAREFUN_C_1(int,xStrEncrypt,char*); + + + + DECLAREFUN_C_2(void,DXVersion,XString&,int&) + + + + //DECLAREFUN_C_1(BOOL,ImportVars,const char*) + DECLAREFUN_C_4(BOOL, WriteIniValue,const char*,const char*,const char*,const char*) + DECLAREFUN_C_4(BOOL, XWriteIniValue,const char* ,const char*,const char*,const char*) + DECLAREFUN_C_3(const char*,GetIniValue,const char*, const char*,const char*) + DECLAREFUN_C_0(const char*,xSGetCommandLine) + DECLAREFUN_C_1(BOOL, CreatePath,const char*) + DECLAREFUN_C_0(void, testAll) + + DECLAREFUN_C_2(BOOL, ShowNodalDebug,CKGroup*,BOOL) + + + + + /************************************************************************/ + /* custum APP-Bridging */ + /************************************************************************/ + DECLAREFUN_C_2(int,WindowExists,char*,char*) + //DECLAREFUN_C_1(int,BSP_OPENFILE,char*) + + /************************************************************************/ + /* FileTools */ + /************************************************************************/ + DECLAREFUN_C_1(BOOL,Check4File,const char*) + DECLAREFUN_C_2(void, SaveObject, CKBeObject*,char*) +// DECLAREFUN_C_3(void, SaveObjectScipt, CKBeObject*,char*,int) + DECLAREFUN_C_5(int,ShellExe,const char*,const char*,const char*,const char*,int) + +// DECLAREFUN_C_0(void, DoVeryBadThings) + + + + /************************************************************************/ + /* System-Tools */ + /************************************************************************/ +// DECLAREFUN_C_2(void,DXVersion,XString&,int&) + DECLAREFUN_C_3(void,MsgBox,char*,char*,int) +// DECLAREFUN_C_3(int,GetDayDifference,int,int,int) + DECLAREFUN_C_2(void,SendKeyBoardKey,int,int) +// DECLAREFUN_C_3(void,GetSDate,int&,int&,int&) +// DECLAREFUN_C_3(void,GetSTime,int&,int&,int&) + + + + //DECLAREFUN_C_0(int,xSGetAvailableTextureMem) + DECLAREFUN_C_0(float,xSGetPhysicalMemoryInMB) + DECLAREFUN_C_1(int,xSGetPhysicalGPUMemoryInMB,int) + DECLAREFUN_C_1(void,xSSaveAllDxPropsToFile,char*) + + + + DECLAREFUN_C_0(BOOL,IsFullScreen) + /************************************************************************/ + /* Geometric */ + /************************************************************************/ + DECLAREFUN_C_4(VxVector, GetRayDistance , CK3dEntity* ,VxVector ,VxVector ,float) + DECLAREFUN_C_3(VxQuaternion,slerp,float,VxQuaternion,VxQuaternion); + + STOPVSLBIND + + + + +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/CKPhysicManager.cpp b/usr/Src/Core/Manager/CKPhysicManager.cpp new file mode 100644 index 0000000..a702db9 --- /dev/null +++ b/usr/Src/Core/Manager/CKPhysicManager.cpp @@ -0,0 +1,9 @@ +#include +#include "vtPhysXAll.h" + + + +CKPhysicManager::CKPhysicManager(CKContext *Context,CKGUID guid,char* name):CKBaseManager(Context,GUID_MODULE_MANAGER,"PhysicManager") +{ + +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/Parameter/PhysicManagerAttributeRegistry.cpp b/usr/Src/Core/Manager/Parameter/PhysicManagerAttributeRegistry.cpp new file mode 100644 index 0000000..0999995 --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManagerAttributeRegistry.cpp @@ -0,0 +1,165 @@ +#include +#include "vtPhysXAll.h" + +#include "vtAttributeHelper.h" + + +bool isSceneObject2(CK3dEntity *object) +{ + CKLevel *level = GetPMan()->GetContext()->GetCurrentLevel(); + if(level) + { + for(int i = 0 ; i < level->GetSceneCount() ; i++ ) + { + CKScene *scene = level->GetScene(i); + if(scene && scene->IsObjectHere(object)) + return true; + } + } + return false; +} +void PhysicManager::_checkObjectsByAttribute(CKScene *newScene) +{ + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;//(sizeof(*getRegistrationTable()) / sizeof((getRegistrationTable())[0])); + for (int fIndex = 0 ; fIndex < sizeJFuncMap ; fIndex ++) + { + + std::vectorattributeIdList; + pFactory::Instance()->findAttributeIdentifiersByGuid(getRegistrationTable()[fIndex].guid,attributeIdList); + int attCount = attributeIdList.size(); + + for (int i = 0 ; i < attCount ; i++ ) + { + int currentAttType = attributeIdList.at(i); + const XObjectPointerArray& Array = attman->GetAttributeListPtr( attributeIdList.at(i) ); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + CK3dEntity *target = static_cast(*it); + if (target) + { + XString error; + error.Format("Registering :%s with %s",target->GetName(),attman->GetAttributeNameByType(currentAttType)); + //if(!strcmp( target->GetName(),"smutan3-3" ) ) { // xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"problem case" ); } + +// CKScene *levelScene = GetContext()->GetCurrentLevel()->GetCurrentScene(); + // we check as no scene is current in use + if ( ( + GetContext()->GetCurrentLevel()->GetLevelScene() == newScene && + !isSceneObject2(target) + ) + || + ( newScene && newScene->IsObjectHere(target) && newScene !=GetContext()->GetCurrentLevel()->GetLevelScene() ) + || + ( + newScene && + GetContext()->GetCurrentLevel()->GetCurrentScene() && + GetContext()->GetCurrentLevel()->GetCurrentScene() == newScene && + newScene !=GetContext()->GetCurrentLevel()->GetLevelScene() && + newScene->IsObjectHere(target) + ) + || + ( + (physicFlags & PMF_DONT_DELETE_SCENES) + ) + ) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.CStr() ); + (*getRegistrationTable()[fIndex].rFunc)(target,currentAttType,true,false); + GetPMan()->getCheckList().PushBack(target->GetID()); + } + } + } + } + } +} + +void PhysicManager::_RegisterAttributeCallbacks() +{ + if (!getAttributeFunctions().Size()) + { + return; + } + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + AttributeFunctionArrayIteratorType it = getAttributeFunctions().Begin(); + + while(it != getAttributeFunctions().End()) + { + ObjectRegisterFunction myFn = (ObjectRegisterFunction)*it; + if (myFn) + { + attman->SetAttributeCallbackFunction(it.GetKey(),PObjectAttributeCallbackFunc,myFn); + } + it++; + } +} + +void PhysicManager::cleanAttributePostObjects() +{ + using namespace vtTools::ParameterTools; + + if (!getAttributePostObjects().Size()) + return; + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + PostRegistrationArrayIteratorType it = getAttributePostObjects().Begin(); + + if (getAttributePostObjects().Size()) + { + if (!GetPMan()->isValid()){ + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Invalid world, performing initiation..."); + GetPMan()->performInitialization(); + } + } + while(it != getAttributePostObjects().End()) + { + pAttributePostObject& post = *it; + CK3dEntity *refObject = static_cast(GetPMan()->m_Context->GetObject(post.objectId)); + if (refObject) + { + + ObjectRegisterFunction regFn = (ObjectRegisterFunction)post.func; + if (regFn) + { + (*regFn)(refObject,post.attributeID,true,false); + } + } + it++; + } + int s = getAttributePostObjects().Size(); + + getAttributePostObjects().Clear(); +} + +void PhysicManager::populateAttributeFunctions() +{ + + getAttributeFunctions().Clear(); + + int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;// (sizeof(*getRegistrationTable()) / sizeof(ObjectRegistration)); + for (int fIndex = 0 ; fIndex < sizeJFuncMap ; fIndex ++) + { + #ifdef _DEBUG + + //XString _errorStr; + //getRegistrationTable()[fIndex].rFunc. + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.Str()); + + #endif + + std::vectorattributeIdList; + pFactory::Instance()->findAttributeIdentifiersByGuid(getRegistrationTable()[fIndex].guid,attributeIdList); + int attCount = attributeIdList.size(); + for (int i = 0 ; i < attCount ; i++ ) + { + int currentAttType = attributeIdList.at(i); + getAttributeFunctions().Insert(currentAttType,getRegistrationTable()[fIndex].rFunc); + } + } +} +ObjectRegistration*PhysicManager::getRegistrationTable() +{ + return attributeFunctionMap; +} diff --git a/usr/Src/Core/Manager/Parameter/PhysicManagerRegisterParameterOps.cpp b/usr/Src/Core/Manager/Parameter/PhysicManagerRegisterParameterOps.cpp new file mode 100644 index 0000000..c91a319 --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManagerRegisterParameterOps.cpp @@ -0,0 +1,962 @@ +#include +#include "vtPhysXAll.h" + + + + +#define PARAMETER_OP_TYPE_STRING_TO_ATT CKGUID(0x3678447e,0x30362a74) + +#define PARAM_OP_TYPE_CIS_INI_COLLISION CKGUID(0x4ec2349b,0x5edf7dd8) +#define PARAM_OP_TYPE_CHAS_CONTACT CKGUID(0x3ed57b83,0x47ad145f) +#define PARAM_OP_TYPE_CRAY_COLLISION CKGUID(0x53425880,0x1b540c2b) + +#define PARAM_OP_TYPE_CGROUP_COLLISION CKGUID(0x7b762a1a,0x702e471c) + +#define PARAM_OP_RC_ANY_BOUNDS CKGUID(0x31e415e2,0x61e42210) +#define PARAM_OP_RC_ANY_SHAPE CKGUID(0x62943427,0x31877a8f) + + + +void ParamOpRayCastAnyShape(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + using namespace vtTools::ParameterTools; + using namespace vtTools::BehaviorTools; + + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CK_ID targetID = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_WORLD,false); + CK_ID oriRef = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_ORI_REF,false); + CK_ID dirRef = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_DIR_REF,false); + + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(targetID); + if (!world) + { + int result = false; + res->SetValue(&result); + return; + } + + CK3dEntity *rayOriRef= (CK3dEntity *)GetPMan()->m_Context->GetObject(oriRef); + CK3dEntity *rayDirRef= (CK3dEntity *) GetPMan()->m_Context->GetObject(dirRef); + + VxVector ori = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_ORI,false); + VxVector dir = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_DIR,false); + + VxVector oriOut = ori; + if (rayOriRef) + { + rayOriRef->Transform(&oriOut,&ori); + } + + //dir : + VxVector dirOut = dir; + if (rayDirRef) + { + VxVector dir,up,right; + rayDirRef->GetOrientation(&dir,&up,&right); + rayDirRef->TransformVector(&dirOut,&up); + } + + int groups = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_GROUPS,false); + float length = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_LENGTH,false); + int types = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_SHAPES_TYPES,false); + + + CK_ID* paramids = static_cast(p1->GetReadDataPtr()); + CKParameterOut* maskP = static_cast(p1->GetCKContext()->GetObject(paramids[E_RC_GROUPS_MASK])); + + NxGroupsMask mask; + mask.bits0 = GetValueFromParameterStruct(maskP,0); + mask.bits1 = GetValueFromParameterStruct(maskP,1); + mask.bits2 = GetValueFromParameterStruct(maskP,2); + mask.bits3 = GetValueFromParameterStruct(maskP,3); + + NxRay ray; + ray.orig = getFrom(oriOut); + ray.dir = getFrom(dirOut); + + + //NxShape **shapes = new NxShape*[2]; + + NxU32 total = world->getScene()->getTotalNbShapes();//world->getScene()->getNbDynamicShapes() + world->getScene()->getNbStaticShapes(); + //NxShape** shapes = NULL ;//(NxShape**)NxAlloca(nbShapes*sizeof(NxShape*)); + + NxShape** shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); + for (NxU32 i = 0; i < total; i++) shapes[i] = NULL; + + //NxShape **shapes = NULL; + int result = world->getScene()->raycastAnyShape(ray,(NxShapesType)types,groups,length,&mask,shapes); + + NxShape *s = shapes[0]; + if (s) + { + pSubMeshInfo *sInfo = static_cast(s->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + CK_ID id = obj->GetID(); + res->SetValue(&id); + //beh->SetOutputParameterObject(bbO_Shape,obj); + } + + } + + } + + + //res->SetValue(&result); + return; + } + + +} + + +void ParamOpRayCastAnyBounds(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + using namespace vtTools::ParameterTools; + using namespace vtTools::BehaviorTools; + + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CK_ID targetID = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_WORLD,false); + CK_ID oriRef = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_ORI_REF,false); + CK_ID dirRef = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_DIR_REF,false); + + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(targetID); + if (!world) + { + int result = false; + res->SetValue(&result); + return; + } + + CK3dEntity *rayOriRef= (CK3dEntity *)GetPMan()->m_Context->GetObject(oriRef); + CK3dEntity *rayDirRef= (CK3dEntity *) GetPMan()->m_Context->GetObject(dirRef); + + VxVector ori = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_ORI,false); + VxVector dir = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_DIR,false); + + VxVector oriOut = ori; + if (rayOriRef) + { + rayOriRef->Transform(&oriOut,&ori); + } + + //dir : + VxVector dirOut = dir; + if (rayDirRef) + { + VxVector dir,up,right; + rayDirRef->GetOrientation(&dir,&up,&right); + rayDirRef->TransformVector(&dirOut,&up); + } + + int groups = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_GROUPS,false); + float length = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_LENGTH,false); + int types = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_SHAPES_TYPES,false); + + + CK_ID* paramids = static_cast(p1->GetReadDataPtr()); + CKParameterOut* maskP = static_cast(p1->GetCKContext()->GetObject(paramids[E_RC_GROUPS_MASK])); + + NxGroupsMask mask; + mask.bits0 = GetValueFromParameterStruct(maskP,0); + mask.bits1 = GetValueFromParameterStruct(maskP,1); + mask.bits2 = GetValueFromParameterStruct(maskP,2); + mask.bits3 = GetValueFromParameterStruct(maskP,3); + + NxRay ray; + ray.orig = getFrom(oriOut); + ray.dir = getFrom(dirOut); + + int result = world->getScene()->raycastAnyBounds(ray,(NxShapesType)types,groups,length,&mask); + + res->SetValue(&result); + return; + + + + + } + + +} + + + + + + + +#define PARAM_OP_TYPE_MGET_SFRICTION CKGUID(0x58566e7b,0x494f208a) +#define PARAM_OP_TYPE_MGET_SFRICTIONV CKGUID(0x7af723af,0x7e222884) +#define PARAM_OP_TYPE_MGET_SDFRICTION CKGUID(0x10733925,0x77c37dba) +#define PARAM_OP_TYPE_MGET_SDFRICTIONV CKGUID(0x29131ba,0x3b2a6f07) +#define PARAM_OP_TYPE_MGET_ANIS CKGUID(0x255256df,0x61fe2f77) +#define PARAM_OP_TYPE_MGET_FMODE CKGUID(0x321f0335,0x589576df) +#define PARAM_OP_TYPE_MGET_RMODE CKGUID(0x1cb07645,0x79ff1329) +#define PARAM_OP_TYPE_MGET_XML_TYPE CKGUID(0x6fea2100,0x6667545b) +#define PARAM_OP_TYPE_MGET_RES CKGUID(0x41702512,0x78c48ca) + + +#define PARAM_OP_TYPE_MSET_SFRICTION CKGUID(0x2f2e1071,0x2d4623ec) +#define PARAM_OP_TYPE_MSET_SFRICTIONV CKGUID(0x31940b2a,0x67f43440) +#define PARAM_OP_TYPE_MSET_SDFRICTION CKGUID(0x205b0164,0x39d626d0) +#define PARAM_OP_TYPE_MSET_SDFRICTIONV CKGUID(0x11f36b7a,0x7877377b) +#define PARAM_OP_TYPE_MSET_ANIS CKGUID(0x36565c47,0x46002830) +#define PARAM_OP_TYPE_MSET_FMODE CKGUID(0x4ddb7828,0x4d111b71) +#define PARAM_OP_TYPE_MSET_RMODE CKGUID(0x5d2315b7,0x2cb834f3) + + +void ParamOpMGetF(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->staticFriction; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetDF(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->dynamicFriction; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetR(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->restitution; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),3,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetDFV(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->dynamicFrictionV; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),4,false); + } + } + res->SetValue(&value); +} + +void ParamOpMGetFV(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->staticFrictionV; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),5,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetA(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + VxVector value(0.0f); + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = getFrom(mDesrc->dirOfAnisotropy); + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),6,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetFMode(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + int value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->frictionCombineMode; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),7,false); + } + } + res->SetValue(&value); +} +////////////////////////////////////////////////////////////////////////// +void ParamOpMGetRMode(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + int value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->restitutionCombineMode; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),8,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetXMat(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int value = 0; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} + + +#define PARAM_OP_TYPE_BGET_RESTITUTION CKGUID(0x58566e7b,0x494f208a) + + +void ParamOpStringToAdd(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CKAttributeManager *am = (CKAttributeManager*)context->GetAttributeManager(); + + //CKSTRING test = + CKParameter *p = p1->GetRealSource(); + + if (!p) { return; } + + CKSTRING test = vtTools::ParameterTools::GetParameterAsString(p); + if (!strlen(test))return; + + + XString aName; + XString aCat; + XString aType; + + XStringTokenizer tokizer(test, "|"); + const char*tok = NULL; + int nb = 0; + while ((tok=tokizer.NextToken(tok)) && nb < 3) + { + XString tokx(tok); + + switch (nb) + { + case 0: + aName = tokx.Str(); + break; + + case 1: + aCat= tokx.Str(); + break; + + case 2: + aType = tokx.Str(); + break; + } + nb++; + } + + CKAttributeType aIType = am->GetAttributeTypeByName(aName.Str()); + if (aIType!=-1) + { + res->SetValue(&aIType); + return; + } + + + CKGUID pType = pm->ParameterNameToGuid(aType.Str()); + CKParameterType pt = pm->ParameterGuidToType(pType); + if (pt==-1) + { + pType = CKPGUID_NONE; + } + + aIType = am->RegisterNewAttributeType(aName.Str(),pType,CKCID_OBJECT); + + if (aCat.Length()) + { + am->AddCategory(aCat.Str()); + am->SetAttributeCategory(aIType,aCat.Str()); + } + + + res->SetValue(&aIType); + +} + +void PhysicManager::_RegisterParameterOperations() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + + _RegisterParameterOperationsBody(); + _RegisterParameterOperationsJoint(); + _RegisterParameterOperationsVehicle(); + + + pm->RegisterOperationType(PARAMETER_OP_TYPE_STRING_TO_ATT, "convert"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_STRING_TO_ATT,CKPGUID_ATTRIBUTE,CKPGUID_STRING,CKPGUID_NONE,ParamOpStringToAdd); + + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_RMODE, "pMgRMode"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_RMODE,VTE_MATERIAL_COMBINE_MODE,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetRMode); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_FMODE, "pMgFMode"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_FMODE,VTE_MATERIAL_COMBINE_MODE,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetFMode); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_RES, "pMgRestitution"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_RES,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetR); + + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SFRICTION, "pMgSFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SFRICTION,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetF); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SFRICTIONV, "pMgSVFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SFRICTIONV,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetFV); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SDFRICTION, "pMgDFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SDFRICTION,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetDF); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SDFRICTIONV, "pMgDVFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SDFRICTIONV,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetDFV); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_ANIS, "pMgAnis"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_ANIS,CKPGUID_VECTOR,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetA); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_XML_TYPE, "pMgType"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_XML_TYPE,VTE_XML_MATERIAL_TYPE,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetXMat); + + + + /************************************************************************/ + /* */ + /************************************************************************/ + + + + + +/* + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FRICTION, "GetFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FRICTION,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetFriction); + + + + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_LDAMP, "GetLinDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_LDAMP,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetLDamp); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_LDAMPT, "GetLinDampingT"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_LDAMPT,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetLDampT); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_ADAMP, "GetAngDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_ADAMP,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetADamp); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_ADAMPT, "GetAngDampingT"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_ADAMPT,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetADampT); + + pm->RegisterOperationType(PARAM_OP_TYPE_CIS_INI_COLLISION, "IsInCollision"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_CIS_INI_COLLISION,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpCIsInCollision); + + pm->RegisterOperationType(PARAM_OP_TYPE_CHAS_CONTACT, "HasContact"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_CHAS_CONTACT,CKPGUID_3DENTITY,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpCHasContact); + + pm->RegisterOperationType(PARAM_OP_TYPE_CRAY_COLLISION, "RayCollision"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_CRAY_COLLISION,CKPGUID_3DENTITY,CKPGUID_3DENTITY,CKPGUID_VECTOR4,ParamOpCRayCollision); + + pm->RegisterOperationType(PARAM_OP_TYPE_CGROUP_COLLISION, "IsCollision"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_CGROUP_COLLISION,CKPGUID_3DENTITY,CKPGUID_3DENTITY,CKPGUID_GROUP,ParamOpCIsInCollisionWithGroup); +*/ + + + + + + + + + + + pm->RegisterOperationType(PARAM_OP_RC_ANY_BOUNDS, "raycastAnyBounds"); + pm->RegisterOperationFunction(PARAM_OP_RC_ANY_BOUNDS,CKPGUID_BOOL,VTS_RAYCAST,CKPGUID_NONE,ParamOpRayCastAnyBounds); + + pm->RegisterOperationType(PARAM_OP_RC_ANY_SHAPE, "raycastAnyShape"); + pm->RegisterOperationFunction(PARAM_OP_RC_ANY_SHAPE,CKPGUID_3DENTITY,VTS_RAYCAST,CKPGUID_NONE,ParamOpRayCastAnyShape); + + + + + + + + + + +} + +/* +void ParamOpBGetLVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetAVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetTorque(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetFriction(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBisFixed(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetHType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpBGetLDamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetLDampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpBGetADamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetADampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpCIsInCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpCHasContact(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpCRayCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpCIsInCollisionWithGroup(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +*/ + + +/* +void ParamOpCIsInCollisionWithGroup(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + ////////////////////////////////////////////////////////////////////////// + //retrieve the position ori : + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + ////////////////////////////////////////////////////////////////////////// + //retrieve the group + CK_ID targetIDG; + p2->GetValue(&targetIDG); + CKGroup *group = static_cast(context->GetObject(targetIDG)); + + + ////////////////////////////////////////////////////////////////////////// + //our result object : + CK3dEntity* result = NULL; + CK_ID id = 0; + + ////////////////////////////////////////////////////////////////////////// + //check our input object : + if (!ent) + { + res->SetValue(&id); + return; + } + + if (ent ) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + + if (world) + { + VxVector pos,normal; + float depth; + result = world->CIsInCollision(ent,group,pos,normal,depth); + if (result) + { + id = result->GetID(); + } + + } + } + res->SetValue(&id); +} + + +////////////////////////////////////////////////////////////////////////// +void ParamOpCRayCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + ////////////////////////////////////////////////////////////////////////// + //retrieve the position ori : + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + ////////////////////////////////////////////////////////////////////////// + //our result object : + CK3dEntity* result = NULL; + CK_ID id = 0; + + ////////////////////////////////////////////////////////////////////////// + //check our input object : + if (!ent) + { + res->SetValue(&id); + return; + } + + + ////////////////////////////////////////////////////////////////////////// + //we retrieve ori of the ray by a box : + VxVector4 inVec(0,0,0,0); + p2->GetValue(&inVec); + + VxVector oriOut(0,0,0); + + ////////////////////////////////////////////////////////////////////////// + //direction of the ray : + VxVector dirIn (inVec.x,inVec.y,inVec.z); + + pWorld *world=GetPMan()->getWorldByBody(ent); + + if (world) + { + VxVector pos,normal; + float depth; + result = world->CRayCollision(oriOut,ent,dirIn,ent,inVec.w,true,pos,normal); + if (result) + { + id = result->GetID(); + } + + } + res->SetValue(&id); +} +////////////////////////////////////////////////////////////////////////// +void ParamOpCHasContact(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + CK3dEntity* result = NULL; + CK_ID id = 0; + + if (ent ) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + + if (world) + { + VxVector pos,normal; + float depth; + result = world->CIsInCollision(ent,pos,normal,depth); + if (result) + { + id = result->GetID(); + } + + } + } + res->SetValue(&id); +} +////////////////////////////////////////////////////////////////////////// +void ParamOpCIsInCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + CK_ID targetID2; + p2->GetValue(&targetID2); + CK3dEntity *ent2 = static_cast(context->GetObject(targetID2)); + + int result = 0; + + if (ent && ent2) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + pWorld *world2=GetPMan()->getWorldByBody(ent2); + if (world && world2 && world == world2) + { + VxVector pos,normal; + float depth; + result = world->CIsInCollision(ent,ent2,pos,normal,depth); + } + } + res->SetValue(&result); +} +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetFriction(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetFriction(); + res->SetValue(&vec); + } + } + } +} + + +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetLDamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetLinearDamping(); + res->SetValue(&vec); + } + } + } +} +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetLDampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetLinearDampingThreshold(); + res->SetValue(&vec); + } + } + } +} +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetADamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetLinearDamping(); + res->SetValue(&vec); + } + } + } +} +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetADampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetLinearDampingThreshold(); + res->SetValue(&vec); + } + } + } +} +*/ +////////////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterBodyParameters.cpp b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterBodyParameters.cpp new file mode 100644 index 0000000..1af9979 --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterBodyParameters.cpp @@ -0,0 +1,381 @@ +#include +#include "vtPhysXAll.h" +#include "vtStructHelper.h" +#include "vtAttributeHelper.h" + +#include "gConfig.h" + + +#define PHYSIC_JOINT_CAT "Physic Constraints" + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; + + +StructurMember bodyDamping[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Linear Damping","0.1"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Angular Damping","0.1"), +}; + +StructurMember bodySleeping[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Linear Sleep Velocity","0.1"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Angular Sleep Velocity","0.1"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Sleep Energy Threshold","0.1"), +}; + +StructurMember bodyXMLSetup[] = +{ + STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_SETTINGS_INTERN,"Internal","None"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_SETTINGS_EXTERN,"External","None"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS,"Import Flags","Stub"), +}; + +StructurMember bodyCCDSettings[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Motion Threshold","None"), + STRUCT_ATTRIBUTE(VTF_PHYSIC_CCD_FLAGS,"Flags","Stub"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Mesh Scale","1.0f"), + STRUCT_ATTRIBUTE(CKPGUID_BEOBJECT,"Shape Reference","None"), +}; + +StructurMember bodyCollisionsSettings[] = +{ + STRUCT_ATTRIBUTE(VTE_PHYSIC_BODY_COLL_GROUP,"Collisions Group","All"), + STRUCT_ATTRIBUTE(VTS_FILTER_GROUPS,"Group Mask","None"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Skin Width","-1.0"), + //STRUCT_ATTRIBUTE(VTS_PHYSIC_CCD_SETTINGS,"CCD Settings","None"), +}; + +StructurMember bodyCollisionsSetup[] = +{ + STRUCT_ATTRIBUTE(VTS_PHYSIC_COLLISIONS_SETTINGS,"Collisions Settings","None"), + //STRUCT_ATTRIBUTE(VTS_PHYSIC_CCD_SETTINGS,"CCD Settings","0"), +}; + +StructurMember bodyOptimistationSettings[] = +{ + STRUCT_ATTRIBUTE(VTF_BODY_TRANS_FLAGS,"Transformation Locks","None"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DAMPING_PARAMETER,"Damping Settings","None"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_SLEEP_SETTINGS,"Sleeping Settings","None"), + STRUCT_ATTRIBUTE(CKPGUID_INT,"Solver Iterations",""), + STRUCT_ATTRIBUTE(VTE_PHYSIC_DOMINANCE_GROUP,"Dominance Group",""), + STRUCT_ATTRIBUTE(CKPGUID_INT,"Compartment Id",""), +}; + +StructurMember bodyCommonSettings[] = +{ + STRUCT_ATTRIBUTE(VTE_COLLIDER_TYPE,"Hull Type","1"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Density","1"), + STRUCT_ATTRIBUTE(VTF_BODY_FLAGS,"Flags","Moving Object,World Gravity,Enabled,Collision"), +/* STRUCT_ATTRIBUTE(VTF_BODY_TRANS_FLAGS,"Transformation Locks",""),*/ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"World","pWorldDefault"), +}; + +StructurMember bodyGeomtryOverride[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Offset Linear","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_EULERANGLES,"Offset Angular","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Offset Reference",""), +}; + +StructurMember bodyMassSetup[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"New Density","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Total Mass","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Offset Linear","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_EULERANGLES,"Offset Angular","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Mass Offset Reference","0.0"), +}; + +StructurMember bodySetup[] = +{ + STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_SETUP,"XML Links","0"), + STRUCT_ATTRIBUTE(VTF_PHYSIC_BODY_COMMON_SETTINGS,"Common Settings","0"), + /*STRUCT_ATTRIBUTE(VTS_PHYSIC_PIVOT_OFFSET,"Pivot","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_MASS_SETUP,"Mass Setup","0"),*/ + STRUCT_ATTRIBUTE(VTS_PHYSIC_COLLISIONS_SETTINGS,"Collisions Setup","0"), + /*STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_OPTIMIZATION,"Optimization","0"),*/ +}; + +StructurMember axisReferencedLength[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Value","0"), + STRUCT_ATTRIBUTE(CKPGUID_BEOBJECT,"Reference Object","0"), + STRUCT_ATTRIBUTE(CKPGUID_AXIS,"Local Axis","0"), +}; + + + +StructurMember customCapsule[] = +{ + STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Radius",""), + STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Width","0"), +}; +StructurMember customConvexCylinder[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_INT,"Approximation","10"), + STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Radius",""), + STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Width","0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Forward Axis","0.0,0.0,-1.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Forward Axis Reference","0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Down Axis","0.0,-1.0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Down Axis Reference","0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Right Axis","1.0,0.0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Right Axis Reference","0"), + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Build Lower Half Only","0"), + STRUCT_ATTRIBUTE(VTF_CONVEX_FLAGS,"Convex Flags","0"), +}; + +//#define gSMapJDistance myStructJDistance +extern void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); + +typedef CKERROR (*bodyParameterDefaultFunction)(CKParameter*); + +bodyParameterDefaultFunction bodyCreateFuncOld = NULL; +/* +#define REGISTER_CUSTOM_STRUCT(NAME,ENUM_TYPE,GUID,MEMBER_ARRAY,HIDDEN) DECLARE_STRUCT(ENUM_TYPE,NAME,GUID,MEMBER_ARRAY,STRUCT_SIZE(MEMBER_ARRAY)); \ + XArray ListGuid##ENUM_TYPE = STRUCT_MEMBER_GUIDS(ENUM_TYPE);\ + pm->RegisterNewStructure(GUID,NAME,STRUCT_MEMBER_NAMES(ENUM_TYPE).Str(),ListGuid##ENUM_TYPE);\ + CKParameterTypeDesc* param_type##ENUM_TYPE=pm->GetParameterTypeDescription(GUID);\ + if (param_type##ENUM_TYPE && HIDDEN) param_type##ENUM_TYPE->dwFlags|=CKPARAMETERTYPE_HIDDEN;\ + _getCustomStructures().Insert(GUID,(CustomStructure*)&MEMBER_ARRAY) + +*/ + +void bodyDefaultFunctionMerged(CKParameter*in) +{ + + CKStructHelper sHelper(in); + //if ( ==0 ) //happens when dev is being opened and loads a cmo with physic objects. + + + XString msg; + + msg.Format("parameter members : %d",sHelper.GetMemberCount()); + if(bodyCreateFuncOld!=0 ) + { + bodyCreateFuncOld(in); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,msg.Str()); + } + + return; + +// CKParameter + //CKAttributeManager::SetAttributeDefaultValue() + + +} +void PhysicManager::_RegisterBodyParameterFunctions() +{ + return; + + CKContext* ctx = GetContext(); + + CKParameterManager *pm = ctx->GetParameterManager(); + CKParameterTypeDesc *param_desc = pm->GetParameterTypeDescription(VTF_PHYSIC_BODY_COMMON_SETTINGS); + if( !param_desc ) return; + if (param_desc->CreateDefaultFunction!=0) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"has function"); + bodyCreateFuncOld = param_desc->CreateDefaultFunction; + param_desc->CreateDefaultFunction = (CK_PARAMETERCREATEDEFAULTFUNCTION)bodyDefaultFunctionMerged; + } + + //param_desc->UICreatorFunction = CKActorUIFunc; + //param_desc->UICreatorFunction = CKDoubleUIFunc; + + +} +void PhysicManager::_RegisterBodyParameters() +{ + + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + + int attRef=0; + //################################################################ + // + // Geometry Related + // + + // Object and Axis Related Length : + REGISTER_CUSTOM_STRUCT("pAxisReferencedLength",PS_AXIS_REFERENCED_LENGTH,VTS_AXIS_REFERENCED_LENGTH,axisReferencedLength,false); + REGISTER_CUSTOM_STRUCT("pCustomConvexCylinder",PS_CUSTOM_CONVEX_CYLINDER_DESCR,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,customConvexCylinder,false); + REGISTER_STRUCT_AS_ATTRIBUTE("pCustomConvexCylinder",PS_CUSTOM_CONVEX_CYLINDER_DESCR,PHYSIC_BODY_CAT,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,CKCID_3DOBJECT,customConvexCylinder,true); + + + REGISTER_CUSTOM_STRUCT("pCapsule",PS_CAPSULE,VTS_CAPSULE_SETTINGS_EX,customCapsule,false); + REGISTER_STRUCT_AS_ATTRIBUTE("pCapsule",PS_CAPSULE,PHYSIC_BODY_CAT,VTS_CAPSULE_SETTINGS_EX,CKCID_3DOBJECT,customCapsule,true); + + + ////////////////////////////////////////////////////////////////////////// + // + // Collision Common Structs : + // + + pm->RegisterNewFlags(VTF_COLLISIONS_EVENT_MASK,"pCollisionEventMask","Ignore=1,Start Touch=2,End Touch=4,Touch=8,Impact=16,Roll=32,Slide=64,Forces=128,Start Touch Force Threshold=256,End Touch Force Threshold=512,Touch Force Threshold=1024,Contact Modification=65536"); + + pm->RegisterNewFlags(VTF_WHEEL_CONTACT_MODIFY_FLAGS,"pWheelContactModifyFlags","Point=1,Normal=2,Position=4,Force=8,Material=16"); + + + + pm->RegisterNewFlags(VTF_CONTACT_MODIFY_FLAGS,"pContactModifyFlags","None=0,Min Impulse=1,Max Impulse=2,Error=4,Target=8,Local Position0=16,Local Position1=32,Local Orientation0=64,Local Orientation1=128,Static Friction0=256,Static Friction1=512,Dynamic Friction0=1024,Dynamic Friction1=2048,Restitution=4096,Force32=2147483648"); + pm->RegisterNewFlags(VTF_CONVEX_FLAGS,"pConvexFlags","Flip Normals=1,16 Bit Indices=2,Compute Convex=4,Inflate Convex=8,Uncompressed Normals=64"); + pm->RegisterNewFlags(VTF_TRIGGER,"pTriggerFlags","Disable=8,OnEnter=1,OnLeave=2,OnStay=4"); + pm->RegisterNewEnum(VTE_FILTER_OPS,"pFilterOp","And=0,Or=1,Xor=2,Nand=3,Nor=4,NXor=5"); + pm->RegisterNewFlags(VTE_FILTER_MASK,"pFilterMask","0,1,2,3"); + pm->RegisterNewStructure(VTS_FILTER_GROUPS,"pFilterGroups","bits0,bits1,bits2,bits3",VTE_FILTER_MASK,VTE_FILTER_MASK,VTE_FILTER_MASK,VTE_FILTER_MASK); + pm->RegisterNewFlags(VTF_SHAPES_TYPE,"pShapesTypes","Static=1,Dynamic=2"); + + ////////////////////////////////////////////////////////////////////////// + // + // Body Sub Structs : + // + + pm->RegisterNewFlags(VTF_BODY_FLAGS,"pBFlags","Moving Object=1,World Gravity=2,Collision=4,Kinematic Object=8,Sub Shape=16,Hierarchy=32,Add Attributes=64,Trigger Shape=128,Deformable=256,Collision Notify=512,Collisions Force=1024,Contact Modify=2048,Sleep=4096"); + pm->RegisterNewFlags(VTF_BODY_TRANS_FLAGS,"pBTFlags","FrozenPositionX=2,FrozenPositionY=4,FrozenPositionZ=8,FrozenRotationX=16,FrozenRotationY=32,FrozenRotationZ=64"); + pm->RegisterNewEnum(VTE_COLLIDER_TYPE,"pBHullType","Sphere=0,Box=1,Capsule=2,Plane=3,Mesh=4,Convex Mesh=5,Height Field=6,Wheel=7,Cloth=8,Convex Cylinder"); + + pm->RegisterNewStructure(VTS_PHYSIC_PARAMETER,"pObject", "Geometry,Physic Flags,Density,Skin Width,Mass Offset,Pivot Offset,Hierarchy,World,New Density,Total Mass,Collision Group",VTE_COLLIDER_TYPE,VTF_BODY_FLAGS,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_INT); + + int currentAttributeType = -1; + + att_physic_object= attman->RegisterNewAttributeType("Object",VTS_PHYSIC_PARAMETER,CKCID_3DOBJECT); + attman->SetAttributeDefaultValue(att_physic_object,"1;Moving Object,World Gravity,Enabled,Collision;1;-1;0,0,0;0,0,0;FALSE,pDefaultWorld"); + + attman->SetAttributeCategory(att_physic_object,"Physic"); + + + pm->RegisterNewEnum(VTE_BODY_FORCE_MODE,"pBForceMode","Force=0,Impulse=1,Velocity Change=2,Smooth Impulse=3,Smooth Velocity Change=4,Acceleration=5"); + attman->SetAttributeCategory(att_physic_limit,"Physic"); + + ////////////////////////////////////////////////////////////////////////// + // + // Capsule : + // + pm->RegisterNewStructure(VTS_CAPSULE_SETTINGS,"Capsule", "Local Length Axis,Local Radius Axis,Length,Radius",CKPGUID_AXIS,CKPGUID_AXIS,CKPGUID_FLOAT,CKPGUID_FLOAT); + + CKParameterTypeDesc* param_type=pm->GetParameterTypeDescription(VTS_CAPSULE_SETTINGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + + /* + att_capsule = attman->RegisterNewAttributeType("Capsule",VTS_CAPSULE_SETTINGS,CKCID_BEOBJECT); + attman->SetAttributeDefaultValue(att_capsule,"1;0;-1.0;-1.0f"); + attman->SetAttributeCategory(att_capsule,"Physic"); + */ + + //---------------------------------------------------------------- + // + // copy flags + // + pm->RegisterNewFlags(VTF_PHYSIC_ACTOR_COPY_FLAGS,"pBCopyFlags","Physics=1,Shared=2,Pivot=4,Mass=8,Collision=16,CCD=32,Material=64,Optimization=128,Capsule=256,Convex Cylinder=512,Force=1024,Velocities=2048,Joints=4096,Limit Planes=8192,Swap Joint References=16384,Override Body Flags=32768,Copy IC=65536,Restore IC=131072"); + /* + param_type=pm->GetParameterTypeDescription(VTF_PHYSIC_ACTOR_COPY_FLAGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; + */ + + + ////////////////////////////////////////////////////////////////////////// + // + // Body Collision Setup + // + + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // CCD Settings : + // + // Custom Enumeration to setup ccd flags + pm->RegisterNewFlags(VTF_PHYSIC_CCD_FLAGS,"pBCCDFlags","None=1,Shared=2,DynamicDynamic=4"); + REGISTER_CUSTOM_STRUCT("pBCCDSettings",PS_B_CCD,VTS_PHYSIC_CCD_SETTINGS,bodyCCDSettings,GC_SHOWPARAMETER); + REGISTER_STRUCT_AS_ATTRIBUTE("pBCCDSettings",PS_B_CCD,PHYSIC_BODY_CAT,VTS_PHYSIC_CCD_SETTINGS,CKCID_3DOBJECT,bodyCCDSettings,true,attRef); + + + //////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // Collisions Settings + // + pm->RegisterNewEnum(VTE_PHYSIC_BODY_COLL_GROUP,"pBCollisionsGroup","All=0,MyObstacles=1,MyWheels=2"); + param_type=pm->GetParameterTypeDescription(VTE_PHYSIC_BODY_COLL_GROUP); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; + + + REGISTER_CUSTOM_STRUCT("pBCollisionSettings",PS_B_COLLISON,VTS_PHYSIC_COLLISIONS_SETTINGS,bodyCollisionsSettings,GC_SHOWPARAMETER); + REGISTER_STRUCT_AS_ATTRIBUTE("pBCollisionSettings",PS_B_COLLISON,PHYSIC_BODY_CAT,VTS_PHYSIC_COLLISIONS_SETTINGS,CKCID_3DOBJECT,bodyCollisionsSettings,true,attRef); + + + /* Merged */ + REGISTER_CUSTOM_STRUCT("pBCSetup",PS_B_COLLISION_SETUP,VTS_PHYSIC_COLLISIONS_SETUP,bodyCollisionsSetup,GC_SHOWPARAMETER ); + + ////////////////////////////////////////////////////////////////////////// + // + // XML Setup + pm->RegisterNewFlags(VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS,"pBXMLFlags","None=0,Stub=1"); + param_type=pm->GetParameterTypeDescription(VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + REGISTER_CUSTOM_STRUCT("pBXMLSetup",PS_BODY_XML_SETUP,VTS_PHYSIC_ACTOR_XML_SETUP,bodyXMLSetup,false); + + ////////////////////////////////////////////////////////////////////////// + // + // Common + REGISTER_CUSTOM_STRUCT("pBCommon",PS_BODY_COMMON,VTF_PHYSIC_BODY_COMMON_SETTINGS,bodyCommonSettings,false); + + ////////////////////////////////////////////////////////////////////////// + // + // Sleep + REGISTER_CUSTOM_STRUCT("pBSleepSettings",PS_B_SLEEPING,VTS_PHYSIC_SLEEP_SETTINGS,bodySleeping,GC_SHOWPARAMETER); + + + ////////////////////////////////////////////////////////////////////////// + // + // Damping + REGISTER_CUSTOM_STRUCT("pBDamping",PS_B_DAMPING,VTS_PHYSIC_DAMPING_PARAMETER,bodyDamping,GC_SHOWPARAMETER); + + ////////////////////////////////////////////////////////////////////////// + // + // Optimization + REGISTER_CUSTOM_STRUCT("pBOptimisation",PS_B_OPTIMISATION,VTS_PHYSIC_ACTOR_OPTIMIZATION,bodyOptimistationSettings,GC_SHOWPARAMETER); + REGISTER_STRUCT_AS_ATTRIBUTE("pBOptimisation",PS_B_OPTIMISATION,PHYSIC_BODY_CAT,VTS_PHYSIC_ACTOR_OPTIMIZATION,CKCID_3DOBJECT,bodyOptimistationSettings,true,attRef); + + + + ////////////////////////////////////////////////////////////////////////// + // + // Geometry + REGISTER_CUSTOM_STRUCT("pBPivotSettings",PS_B_PIVOT,VTS_PHYSIC_PIVOT_OFFSET,bodyGeomtryOverride,GC_SHOWPARAMETER); + REGISTER_STRUCT_AS_ATTRIBUTE("pBPivotSettings",PS_B_PIVOT,PHYSIC_BODY_CAT,VTS_PHYSIC_PIVOT_OFFSET,CKCID_3DOBJECT,bodyGeomtryOverride,true,attRef); + + + ////////////////////////////////////////////////////////////////////////// + // + // Mass Override + REGISTER_CUSTOM_STRUCT("pBMassSettings",PS_B_MASS,VTS_PHYSIC_MASS_SETUP,bodyMassSetup,false); + param_type=pm->GetParameterTypeDescription(VTS_PHYSIC_MASS_SETUP); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + REGISTER_STRUCT_AS_ATTRIBUTE("pBMassSettings",PS_B_MASS,PHYSIC_BODY_CAT,VTS_PHYSIC_MASS_SETUP,CKCID_3DOBJECT,bodyMassSetup,true,attRef); + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // this is the new replacement for the "Object" attribute. + // + REGISTER_CUSTOM_STRUCT("pBSetup",PS_BODY_SETUP,VTS_PHYSIC_ACTOR,bodySetup,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pBSetup",PS_BODY_SETUP,PHYSIC_BODY_CAT,VTS_PHYSIC_ACTOR,CKCID_3DOBJECT,bodySetup,attRef); + + +} diff --git a/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterJointParameters.cpp b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterJointParameters.cpp new file mode 100644 index 0000000..c2a5cb9 --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterJointParameters.cpp @@ -0,0 +1,300 @@ +#include +#include "vtPhysXAll.h" +#include "vtStructHelper.h" + +#define PHYSIC_JOINT_CAT "Physic Constraints" + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; + + + + +StructurMember myStructJBall[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Global Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Global Axis Reference",""), + + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Limit Swing Axis","0,0,0"), + + STRUCT_ATTRIBUTE(VTE_JOINT_PROJECTION_MODE,"Projection Mode","None"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Projection Distance","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision","TRUE"), + + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Swing Limit","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Twist High Limit ","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Twist Low Limit ","0.0,0.0,0.0"), + + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Swing Spring","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Twist Spring","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Joint Spring","0.0,0.0,0.0"), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + +}; + + +StructurMember myStructJDistance[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Local 0 Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Local 0 Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Local 1 Anchor","0,0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Local 1 Reference","pDefaultWorld"), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision","TRUE"), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Minimum Distance","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Distance","0.0"), + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Spring","0.0f,0.0f,0.0f"), + + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + +}; + + +StructurMember myStructJFixed[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + +}; + +StructurMember JPrismaticMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + +}; + +StructurMember JCylindricalMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), +}; + +StructurMember JPointInPlaneMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), +}; + +StructurMember JPointOnLineMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), +}; + +StructurMember JRevoluteMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision","TRUE"), + + STRUCT_ATTRIBUTE(VTE_JOINT_PROJECTION_MODE,"Projection Mode","None"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Projection Distance","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Projection Angle","0.3"), + + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Spring","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Limit High","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Limit Low","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JOINT_MOTOR,"Motor","0.0,0.0,0.0"), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + + +}; + + + +StructurMember JLimitPlaneMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + STRUCT_ATTRIBUTE(VTE_JOINT_TYPE,"Target Joint Type","JT_Any"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Restitution","0.0f"), + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Point is on Body","False"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Limit Point",""), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Limit Point Reference",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Normal",""), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Normal Up Reference",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Point in Plane",""), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Point in Plane Reference",""), + +}; + +StructurMember JD6Members[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + STRUCT_ATTRIBUTE(VTF_JOINT_D6_AXIS_MASK,"Axis Mask",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"X",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Y",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Z",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Swing 1",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Swing 2",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Twist Low",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Twist High",""), +}; + +StructurMember JD6AxisItem[] = +{ + STRUCT_ATTRIBUTE(VTE_JOINT_MOTION_MODE_AXIS,"Axis","X"), + STRUCT_ATTRIBUTE(VTS_JOINT_SLIMIT,"Limit",""), +}; + +#define gSMapJDistance myStructJDistance +#define gSMapJFixed myStructJFixed +#define gSMapJBall myStructJBall +#define gSMapJPrismatic JPrismaticMemberTable +#define gSMapJRevolute JRevoluteMemberTable +#define gSMapJCylindrical JCylindricalMemberTable +#define gSMapJPointInPlane JPointInPlaneMemberTable +#define gSMapJPointOnLine JPointOnLineMemberTable +#define gSMapJLimitPlane JLimitPlaneMemberTable + +extern void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); +void PhysicManager::_RegisterJointParameters() +{ + + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + + //---------------------------------------------------------------- + // + // D6 Help Structures + // + + pm->RegisterNewEnum(VTE_JOINT_MOTION_MODE,"pJMotionMode","Locked=0,Limited=1,Free=2"); + pm->RegisterNewStructure(VTS_JOINT_SLIMIT,"pJD6SLimit","Damping,Spring,Value,Restitution",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_ANGLE,CKPGUID_FLOAT); + + //---------------------------------------------------------------- + // + // Types for D6 - Joint - Attribute only : + // + + + //SetWindowLong(m_hWnd,GWL_USERDATA,(LONG)this_mod); // set our user data to a "this" pointer + /* + pm->RegisterNewEnum(VTF_JOINT_D6_AXIS_MASK,"pD6AxisMask","X=1,Y=2,Z=4,Swing1=8,Swing2=16,Twist Low=32,Twist High=64"); + REGISTER_CUSTOM_STRUCT("pJD6AxisItem",PS_D6_AXIS_ITEM,VTS_JOINT_D6_AXIS_ITEM,JD6AxisItem,TRUE); + REGISTER_CUSTOM_STRUCT("pJD6",PS_D6,VTS_JOINT_D6,JD6Members,TRUE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJD6",PS_D6,PHYSIC_JOINT_CAT,VTS_JOINT_D6,CKCID_BEOBJECT,JD6Members,true,attRef); + + */ + + int attRef=0; + pm->RegisterNewEnum(VTE_JOINT_TYPE,"pJointType","None=-1,Prismatic=0,Revolute=1,Cylindrical=2,Spherical=3,Point On Line=4,Point In Plane=5,Distance=6,Pulley=7,Fixed=8,D6=9"); + + pm->RegisterNewEnum(VTE_PHYSIC_JDRIVE_TYPE,"pJD6DriveType","Disabled=0,Position=1,Velocity=2"); + pm->RegisterNewStructure(VTS_JOINT_DRIVE,"pJD6Drive","Damping,Spring,Force Limit,Drive Type",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,VTE_PHYSIC_JDRIVE_TYPE); + + pm->RegisterNewStructure(VTS_JOINT_SPRING,"pJSpring","Damper,Spring,Target Value",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT); + pm->RegisterNewStructure(VTS_JLIMIT,"pJLimit","Value,Restitution,Hardness",CKPGUID_ANGLE,CKPGUID_FLOAT,CKPGUID_FLOAT); + + + pm->RegisterNewEnum(VTE_JOINT_MOTION_MODE_AXIS,"pJD6Axis","Twist=0,Swing1=1,Swing2=2,X=3,Y=4,Z=5"); + pm->RegisterNewEnum(VTE_JOINT_DRIVE_AXIS,"pJD6DriveAxis","Twist=0,Swing=1,Slerp=2,X=3,Y=4,Z=5"); + pm->RegisterNewEnum(VTE_JOINT_LIMIT_AXIS,"pJD6LimitAxis","Linear=0,Swing1=1,Swing2,Twist High,Twist Low"); + + pm->RegisterNewEnum(VTE_JOINT_PROJECTION_MODE,"pJProjectionMode","None=0,Point MinDist=1,Linear MindDist"); + pm->RegisterNewStructure(VTS_JOINT_MOTOR,"pJMotor","Target Velocity,Maximum Force,Free Spin",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_BOOL); + + REGISTER_CUSTOM_STRUCT("pJDistance",PS_JDISTANCE_MEMBERS,VTS_JOINT_DISTANCE,gSMapJDistance,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJDistance",PS_JDISTANCE_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_DISTANCE,CKCID_3DOBJECT,gSMapJDistance,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJFixed",PS_JFIXED_MEMBERS,VTS_JOINT_FIXED,gSMapJFixed,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJFixed",PS_JFIXED_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_FIXED,CKCID_3DOBJECT,gSMapJFixed,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJBall",PS_JBALL_MEMBERS,VTS_JOINT_BALL,gSMapJBall,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJBall",PS_JBALL_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_BALL,CKCID_3DOBJECT,gSMapJBall,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJPrismatic",PS_JPRISMATIC_MEMBERS,VTS_JOINT_PRISMATIC ,gSMapJPrismatic,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJPrismatic",PS_JPRISMATIC_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_PRISMATIC ,CKCID_BEOBJECT,gSMapJPrismatic,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJCylindrical",PS_JCYLINDRICAL_MEMBERS,VTS_JOINT_CYLINDRICAL,gSMapJCylindrical,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJCylindrical",PS_JCYLINDRICAL_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_CYLINDRICAL,CKCID_BEOBJECT,gSMapJCylindrical,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJRevolute",PS_JREVOLUTE,VTS_JOINT_REVOLUTE,gSMapJRevolute,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJRevolute",PS_JREVOLUTE,PHYSIC_JOINT_CAT,VTS_JOINT_REVOLUTE ,CKCID_BEOBJECT,gSMapJRevolute,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJPointInPlane",PS_JPOINT_IN_PLANE_MEMBERS,VTS_JOINT_POINT_IN_PLANE,gSMapJPointInPlane,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJPointInPlane",PS_JPOINT_IN_PLANE_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_POINT_IN_PLANE,CKCID_BEOBJECT,gSMapJPointInPlane,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJPointOnLine",PS_JPOINT_ON_LINE_MEMBERS,VTS_JOINT_POINT_ON_LINE,gSMapJPointOnLine,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJPointOnLine",PS_JPOINT_ON_LINE_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_POINT_ON_LINE,CKCID_BEOBJECT,gSMapJPointOnLine,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJLimitPlane",PS_JLIMIT_PLANE_MEMBERS,VTS_PHYSIC_JLIMIT_PLANE,gSMapJLimitPlane,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJLimitPlane",PS_JLIMIT_PLANE_MEMBERS,PHYSIC_JOINT_CAT,VTS_PHYSIC_JLIMIT_PLANE,CKCID_BEOBJECT,gSMapJLimitPlane,true,attRef); + + + + + + populateAttributeFunctions(); + _RegisterAttributeCallbacks(); + +} diff --git a/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterParameters.cpp b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterParameters.cpp new file mode 100644 index 0000000..3841b35 --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterParameters.cpp @@ -0,0 +1,380 @@ +#include +#include "vtPhysXAll.h" + +#include "vtStructHelper.h" +#include "vtAttributeHelper.h" + +using namespace vtTools::AttributeTools; + +int PhysicManager::getAttributeTypeByGuid(CKGUID guid) +{ + + + CKContext *ctx = GetPMan()->GetContext(); + + CKAttributeManager *attMan = ctx->GetAttributeManager(); + CKParameterManager *parMan = ctx->GetParameterManager(); + + int cCount = attMan->GetAttributeCount(); + for(int i = 0 ; i < cCount ; i++) + { + CKSTRING name = attMan->GetAttributeNameByType(i); + if ( parMan->ParameterTypeToGuid(attMan->GetAttributeParameterType(i)) == guid ) + { + return i; + } + } + + return -1; +} + +void PhysicManager::_RegisterDynamicEnumeration(XString file,XString enumerationName,CKGUID enumerationGuid,PFEnumStringFunction enumFunc,BOOL hidden) +{ + + + TiXmlDocument * defaultDoc = loadDefaults(file.Str()); + if (!defaultDoc) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config :PhysicDefaults.xml: failed"); + } + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + if (!getCurrentFactory()) + { + pFactory *factory = new pFactory(this,getDefaultConfig()); + setCurrentFactory(factory); + } + + pFactory *factory = pFactory::Instance(); + + XString outList; + if (defaultDoc) + outList = (factory->*enumFunc)(getDefaultConfig()); + + if (!outList.Length()) + outList<< "None=0"; + + CKParameterType pType = pm->ParameterGuidToType(enumerationGuid); + if (pType==-1) + pm->RegisterNewEnum(enumerationGuid,enumerationName.Str(),outList.Str()); + else{ + pm->ChangeEnumDeclaration(enumerationGuid,outList.Str()); + } + + CKParameterTypeDesc* param_type = pm->GetParameterTypeDescription(enumerationGuid); + if (param_type && hidden) + param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"%s settings from xml detected : %s",enumerationName.Str(),outList.Str()); + + + +} + +void PhysicManager::_RegisterDynamicParameters() +{ + + + TiXmlDocument * defaultDoc = loadDefaults("PhysicDefaults.xml"); + if (!defaultDoc) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config :PhysicDefaults.xml: failed"); + } + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + if (!getCurrentFactory()) + { + pFactory *factory = new pFactory(this,getDefaultConfig()); + setCurrentFactory(factory); + } + + + int pType = 0; + + ////////////////////////////////////////////////////////////////////////// + // + // Material ! + // +/* + XString materialList; + if (defaultDoc) + { + materialList = pFactory::Instance()->_getMaterialsAsEnumeration(getDefaultConfig()); + }else{ + + materialList << "None=0"; + } + + int pType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); + + if (pType==-1) + pm->RegisterNewEnum(VTE_XML_MATERIAL_TYPE,"pMaterialType",materialList.Str()); + else{ + pm->ChangeEnumDeclaration(VTE_XML_MATERIAL_TYPE,materialList.Str()); + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"materials : %s",materialList.Str()); +*/ + + _RegisterDynamicEnumeration("PhysicDefaults.xml","pMaterialType",VTE_XML_MATERIAL_TYPE,&pFactory::_getMaterialsAsEnumeration,false); + + _RegisterDynamicEnumeration("PhysicDefaults.xml","pBodyXMLInternalLink",VTS_PHYSIC_ACTOR_XML_SETTINGS_INTERN,&pFactory::_getBodyXMLInternalEnumeration,false); + _RegisterDynamicEnumeration("PhysicDefaults.xml","pBodyXMLExternalLink",VTS_PHYSIC_ACTOR_XML_SETTINGS_EXTERN,&pFactory::_getBodyXMLExternalEnumeration,false); + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Vehicle Settings + // + XString vSListStr; + if (defaultDoc) + vSListStr= pFactory::Instance()->_getVehicleSettingsAsEnumeration(getDefaultConfig()); + + if (!vSListStr.Length()) + vSListStr << "None=0"; + + pType = pm->ParameterGuidToType(VTE_XML_VEHICLE_SETTINGS); + if (pType==-1) + pm->RegisterNewEnum(VTE_XML_VEHICLE_SETTINGS,"pVehicleSettingsLink",vSListStr.Str()); + else{ + pm->ChangeEnumDeclaration(VTE_XML_VEHICLE_SETTINGS,vSListStr.Str()); + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"vehicle settings : %s",vSListStr.Str()); + + + ////////////////////////////////////////////////////////////////////////// + // + // Wheel Settings + // + XString wSListStr; + if (defaultDoc) + wSListStr = pFactory::Instance()->_getVehicleWheelAsEnumeration(getDefaultConfig()); + + if (!wSListStr.Length()) + wSListStr << "None=0"; + + + pType = pm->ParameterGuidToType(VTE_XML_WHEEL_SETTINGS); + if (pType==-1) + pm->RegisterNewEnum(VTE_XML_WHEEL_SETTINGS,"pWheelSettingsLink",wSListStr.Str()); + else{ + pm->ChangeEnumDeclaration(VTE_XML_WHEEL_SETTINGS,wSListStr.Str()); + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"wheel vehicle settings : %s",wSListStr.Str()); + + + CKParameterTypeDesc* param_type; + param_type=pm->GetParameterTypeDescription(VTE_XML_WHEEL_SETTINGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + + ////////////////////////////////////////////////////////////////////////// + // + // Wheel Tire Function + // + XString wTListStr; + if (defaultDoc) + wTListStr = pFactory::Instance()->_getVehicleTireFunctionAsEnumeration(getDefaultConfig()); + + if (!wTListStr.Length()) + wTListStr << "None=0"; + + pType = pm->ParameterGuidToType(VTE_XML_TIRE_SETTINGS); + if (pType==-1) + pm->RegisterNewEnum(VTE_XML_TIRE_SETTINGS,"pWheelSettingsLink",wTListStr.Str()); + else{ + pm->ChangeEnumDeclaration(VTE_XML_TIRE_SETTINGS,wTListStr.Str()); + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"wheel tire force settings : %s",wTListStr.Str()); + + param_type=pm->GetParameterTypeDescription(VTE_XML_TIRE_SETTINGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + + + + //_getVehicleTireFunctionAsEnumeration + /*param_type=pm->GetParameterTypeDescription(CKPGUID_EVOLUTIONS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; +*/ + + + _RegisterDynamicEnumeration("PhysicDefaults.xml","pMaterialType",VTE_XML_MATERIAL_TYPE,&pFactory::_getMaterialsAsEnumeration,false); + + + +} + + +void recheckWorldsFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg) +{ + + int s = GetPMan()->getNbObjects(); + if (AttribType == GetPMan()->GetPAttribute()) + { + pRigidBody *body = body = GetPMan()->getBody(pFactory::Instance()->getMostTopParent((CK3dEntity*)obj)); + if (body) + { + if (Set) + if (!body->isSubShape(obj)) + body->_checkForNewSubShapes(); + else + body->_checkForRemovedSubShapes(); + } + } + //CKParameterOut *pout = obj->GetAttributeParameter(GetPMan()->att_physic_object); + +} + +using namespace vtTools::ParameterTools; + + +vtTools::ParameterTools::StructurMember PBRigidBodyMemberMap[] = +{ + + STRUCT_ATTRIBUTE(VTE_COLLIDER_TYPE,"Geometry","Sphere"), + STRUCT_ATTRIBUTE(VTF_BODY_FLAGS,"Physic Flags","Moving Object,World Gravity,Enabled,Collision"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Density","1.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Skin Width","-1.0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Mass Offset","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Pivot Offset","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Hierarchy","FALSE"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"World","pDefaultWorld"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Total Mass","-1.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"New Density","-1.0"), + STRUCT_ATTRIBUTE(CKPGUID_INT,"Collision Group","0"), +}; + +//pm->RegisterNewStructure(VTS_PHYSIC_PARAMETER,"pObject", ",Mass Offset,Pivot Offset,Hierarchy,World,New Density,Total Mass,Collision Group", +//VTE_COLLIDER_TYPE,VTF_BODY_FLAGS,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_INT); + + +void PhysicManager::_RegisterParameters() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + + + attman->AddCategory("Physic"); + + _RegisterWorldParameters(); + _RegisterBodyParameters(); + _RegisterBodyParameterFunctions(); + + + + /************************************************************************/ + /* clothes : */ + /************************************************************************/ + pm->RegisterNewFlags(VTF_VEHICLE_PROCESS_OPTIONS,"pVehicleProcessOptions","Lateral Damping=1,Longitudinal Damping=2,Slip Angle Damping=4,Slip Angle Delay=8,Slip Vector Tansa=16,SA Settle Down=32,Low Speed Check=64,Wheel LockAdjust=128,PhysXLoad=256,PhysXContacts=512,DoGregor=1024,DampVerticalVelocityReversal=2048,IntegrateImplicitVertical=4096,Diff Direct=8192,No Lateral=16384"); + + pm->RegisterNewFlags(VTE_CLOTH_FLAGS,"pClothFlags","Pressure=1,Static=2,DisableCollision=4,SelfCollision=8,Gravity=32,Bending=64,BendingOrtho=128,Damping=256,CollisionTwoway=512,TriangleCollision=2048,Tearable=4096,Hardware=8192,ComDamping=16384,ValidBounds=32768,FluidCollision=65536,DisableCCD=131072,AddHere=262144,AttachToParentMainShape=524288,AttachToCollidingShapes=1048576,AttachToCore=2097152,AttachAttributes=4194304"); + pm->RegisterNewFlags(VTE_CLOTH_ATTACH_FLAGS,"pClothAttachFlags","Twoway=1,Tearable=2"); + + pm->RegisterNewStructure(VTS_CLOTH_DESCR,"pClothDesc","Thickness,Density,Bending Stiffness,Stretching Stiffness,Damping Coefficient,Friction,Pressure,Tear Factor,Collision Response Coefficient,Attachment Response Coefficient,Attachment Tear Factor,To Fluid Response Coefficient,From Fluid Response Coefficient,Min Adhere Velocity,Solver Iterations,External Acceleration,Wind Acceleration,Wake Up Counter,Sleep Linear Velocity,Collision Group,Valid Bounds,Relative Grid Spacing,Flags,Tear Vertex Color,World Reference,Attachment Flags",CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_INT, CKPGUID_VECTOR, CKPGUID_VECTOR, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_INT, CKPGUID_BOX, CKPGUID_FLOAT, VTE_CLOTH_FLAGS, CKPGUID_COLOR, CKPGUID_3DENTITY, VTE_CLOTH_ATTACH_FLAGS); + att_clothDescr= attman->RegisterNewAttributeType("Cloth",VTS_CLOTH_DESCR,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_clothDescr,"Physic"); + attman->SetAttributeDefaultValue(att_clothDescr,"0.01f;1.0f;1.0f;1.0f;0.5f;0.5f;1.0f;1.5f;0.2f; 0.2f;1.5f;1.0f;1.0f;1.0f;5;0.0f,0.0f,0.0f;0.0f,0.0f,0.0f;0.4f;-1.0f;0;0.0f,0.0f,0.0f,0.0f,0.0f,0.0f;0.25;Gravity;255,255,255,255;pDefaultWorld;Twoway"); + + pm->RegisterNewStructure(VTS_CLOTH_METAL_DESCR,"pDeformableSettings","Impulse Threshold,Penetration Depth,Maximal Deformation Distance",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT); + + CKParameterTypeDesc* param_type=pm->GetParameterTypeDescription(VTS_CLOTH_METAL_DESCR); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + att_deformable = attman->RegisterNewAttributeType("Deformable Settings",VTS_CLOTH_METAL_DESCR,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_deformable,"Physic"); + + //attman->SetAttributeCallbackFunction(att_clothDescr,recheckWorldsFunc,NULL); + + + /************************************************************************/ + /* material */ + /************************************************************************/ + pm->RegisterNewFlags(VTF_MATERIAL_FLAGS,"pMaterialFlags","Anisotropic=1,Disable Friction=16,Disable Strong Friction=32"); + pm->RegisterNewEnum(VTE_MATERIAL_COMBINE_MODE,"pFrictionCombineMode","Average=0,Min=1,Multiply=2,Max=3"); + pm->RegisterNewStructure(VTS_MATERIAL,"pMaterial","XML Link,DynamicFriction,Static Friction,Restitution,Dynamic Friction V,Static Friction V,Direction of Anisotropy,Friction Combine Mode,Restitution Combine Mode,Flags",VTE_XML_MATERIAL_TYPE,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_VECTOR,VTE_MATERIAL_COMBINE_MODE,VTE_MATERIAL_COMBINE_MODE,VTF_MATERIAL_FLAGS); + + att_surface_props= attman->RegisterNewAttributeType("Material",VTS_MATERIAL,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_surface_props,"Physic"); + + attman->SetAttributeCallbackFunction(att_surface_props,recheckWorldsFunc,NULL); + + + /************************************************************************/ + /* Collision */ + /************************************************************************/ + + + att_trigger= attman->RegisterNewAttributeType("Trigger",VTF_TRIGGER,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_trigger,"Physic"); + + pm->RegisterNewFlags(VTF_RAY_HINTS,"pRayCastHints","Shape=1,Impact=2,Normal=4,Face Index=8,Distance=16,UV=32,Face Normal=64,Material=128"); + pm->RegisterNewStructure(VTS_RAYCAST,"pRayCast","World Reference,Ray Origin,Ray Origin Reference,Ray Direction,Ray Direction Reference,Length,Groups,Groups Mask,Shape Types",CKPGUID_3DENTITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_FLOAT,CKPGUID_INT,VTS_FILTER_GROUPS,VTF_SHAPES_TYPE); + + + + /************************************************************************/ + /* Vehicle : */ + /************************************************************************/ + // + + //pm->RegisterNewStructure(VTS_WHEEL_CONTACT,"pWheelContactData","Contact Point,Contact Normal,Longitudes Direction,Lateral Direction,Contact Force,Longitudes Slip,Lateral Slip, Longitudes Impulse,Lateral Impulse,Other Material,Contact Position, Contact Entity",CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_VECTOR, CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_FLOAT,CKPGUID_3DENTITY); + //REGISTER_CUSTOM_STRUCT("pJDistance",PS_JDISTANCE_MEMBERS,VTS_JOINT_DISTANCE,gSMapJDistance,FALSE); + + _RegisterVehicleParameters(); + _RegisterJointParameters(); + + + //registerWatchers(); +} + +XString getEnumDescription(CKParameterManager* pm,CKBeObject *object,int index) +{ + + XString result="None"; + int pType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + if(i == index) + { + result = enumStruct->GetEnumDescription(i); + } + } + } + return result; +} + +int getEnumIndexByDescription(CKParameterManager* pm,XString descr) +{ + + int result =0; + int pType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + + if (!strcmp(enumStruct->GetEnumDescription(i),descr.CStr())) + { + return i; + } + } + } + return result; +} diff --git a/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterVehicleParameters.cpp b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterVehicleParameters.cpp new file mode 100644 index 0000000..bd99451 --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterVehicleParameters.cpp @@ -0,0 +1,138 @@ +#include +#include "vtPhysXAll.h" +#include "vtAttributeHelper.h" +#include + + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; + +vtTools::ParameterTools::StructurMember breakTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"0","250"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"1","250"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"2","300"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"3","350"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"4","450"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"5","575"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"6","625"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"7","700"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"8","1000"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"9","1000"), +}; + +vtTools::ParameterTools::StructurMember myStructWheelContactData[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Contact Point",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Contact Normal",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Longitudes Direction",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Lateral Direction",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Contact Force",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Longitudes Slip",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Lateral Slip",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Longitudes Impulse",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Lateral Impulse",""), + STRUCT_ATTRIBUTE(VTS_MATERIAL,"Other Material",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Contact Pos",""), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Colliding Entity",""), +}; + +void PhysicManager::_RegisterVehicleParameters() +{ + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + CKParameterTypeDesc* param_type = NULL; + + //################################################################ + // + // Tire Function + // + pm->RegisterNewStructure(VTF_VWTIRE_SETTINGS,"pTireFunction", + "XML Link,Extremum Slip,Extremum Value,Asymptote Slip,Asymptote Value,Stiffness Factor", + VTE_XML_TIRE_SETTINGS,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT); + + + + //################################################################ + // + // Motor related + // + pm->RegisterNewStructure(VTS_VMOTOR_ENTRY,"RPM / Newton Meter","RPM,Newton Meter",CKPGUID_FLOAT,CKPGUID_FLOAT); + param_type=pm->GetParameterTypeDescription(VTS_VMOTOR_ENTRY); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + pm->RegisterNewStructure(VTS_VMOTOR_TVALUES,"pVehicleMotor Torques","1,2,3,4,5,6,7", VTS_VMOTOR_ENTRY,VTS_VMOTOR_ENTRY, VTS_VMOTOR_ENTRY,VTS_VMOTOR_ENTRY, VTS_VMOTOR_ENTRY,VTS_VMOTOR_ENTRY, VTS_VMOTOR_ENTRY); + + + pm->RegisterNewStructure(VTS_VGEAR_RATIO_ENTRY,"Ratio/Inertia","Ratio,Inertia",CKPGUID_FLOAT,CKPGUID_FLOAT); + param_type=pm->GetParameterTypeDescription(VTS_VGEAR_RATIO_ENTRY); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + pm->RegisterNewStructure(VTS_VGEAR_RATIOS,"pVehicleGear List","N,R,1,2,3,4,5,6,7", + VTS_VGEAR_RATIO_ENTRY, + VTS_VGEAR_RATIO_ENTRY, + VTS_VGEAR_RATIO_ENTRY, + VTS_VGEAR_RATIO_ENTRY, + VTS_VGEAR_RATIO_ENTRY, + VTS_VGEAR_RATIO_ENTRY, + VTS_VGEAR_RATIO_ENTRY, + VTS_VGEAR_RATIO_ENTRY, + VTS_VGEAR_RATIO_ENTRY + ); + + + //################################################################ + // + // Vehicle Common + + + pm->RegisterNewEnum(VTE_XML_VGEAR_SETTINGS,"pVehicleGearSettings","Stub=1"); + + + pm->RegisterNewFlags(VTS_VGEARBOX_FLAGS,"pVehicleGearBoxFlags","Stub=1"); + pm->RegisterNewFlags(VTF_VEHICLE_ENGINE_FLAGS,"pVehicleEngineFlags","Stub=1"); + + pm->RegisterNewFlags(VTF_VSTATE_FLAGS,"pVehicleStateFlags","Is Moving=1,Is Accelerated=2,Is Accelerated Forward=4,Is Accelerated Backward=8,All Wheels On Ground=16,Is Falling=32,Handbrake=64,Is Braking=128,Is Steering=256,Has Gearbox=512,Has Motor=1024"); + pm->RegisterNewFlags(VTF_VFLAGS,"pVehicleFlags","Use Advanced=1"); + pm->RegisterNewEnum(VTE_BRAKE_LEVEL,"pVehicleBreakLevel","No Break=-1,Small=0,Medium=1,High=2"); + pm->RegisterNewEnum(VTE_BRAKE_XML_LINK,"pVehicleXMLBrakeSettings","Stub=1"); + pm->RegisterNewEnum(VTE_VEHICLE_XML_LINK,"pVehicleXMLLink","Stub=1"); + + pm->RegisterNewFlags(VTF_BRAKE_FLAGS,"pVehicleBreakFlags","Use Table=1,Auto Break=2"); + + REGISTER_CUSTOM_STRUCT("pVehicleBreakTable",E_VBT_STRUCT,VTS_BRAKE_TABLE,breakTable,FALSE); + + + + //################################################################ + // + // Wheel + // + + REGISTER_CUSTOM_STRUCT("pWheelContactData",E_WCD_STRUCT,VTS_WHEEL_CONTACT,myStructWheelContactData,FALSE); + + pm->RegisterNewFlags(VTS_PHYSIC_WHEEL_FLAGS,"pWheelFlags","Steerable Input=1,Steerable Auto=2,Affected By Handbrake=4,Accelerated=8,Controlled by Vehicle=16,Affected by Differential=32,Ignore Tire Function=64"); + //pm->RegisterNewFlags(VTS_PHYSIC_WHEEL_FLAGS,"pWheelFlags","Steerable Input=1,Steerable Auto=2,Affected By Handbrake=4,Accelerated=8,Build Lower Half=256,Use Wheel Shape=512,Controlled by Vehicle"); + pm->RegisterNewFlags(VTF_VWSHAPE_FLAGS,"pWheelShapeFlags","AxisContactNormal=1,InputLateralSlip=2,InputLongitudinal=4,UnscaledSpringBehavior=8,AxleSpeedOverride=16,EmulateLegacyWheel=32,ClampedFriction=64"); + + + pm->RegisterNewStructure(VTS_PHYSIC_WHEEL_DESCR,"pWheelDescr", + "XML Link,Suspension,Spring Restitution,Spring Bias,Spring Damping,Maximum Brake Force,Friction To Side,Friction To Front,Inverse Wheel Mass,Wheel Flags,Wheel Shape Flags,Lateral Force Settings,Longitudinal Force Settings", + VTE_XML_WHEEL_SETTINGS, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + VTS_PHYSIC_WHEEL_FLAGS, + VTF_VWSHAPE_FLAGS, + VTF_VWTIRE_SETTINGS, + VTF_VWTIRE_SETTINGS); + + att_wheelDescr = attman->RegisterNewAttributeType("pWheel",VTS_PHYSIC_WHEEL_DESCR,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_wheelDescr ,"Physic"); + +} diff --git a/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterWorldParameters.cpp b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterWorldParameters.cpp new file mode 100644 index 0000000..a3cd01c --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManagerVTRegisterWorldParameters.cpp @@ -0,0 +1,108 @@ +#include + +#include "pCrossTypes.h" +#include +#include "vtPhysXAll.h" + +#include "vtStructHelper.h" +#include "vtAttributeHelper.h" + + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; + + + +/************************************************************************/ +/* Dominance Setup */ +/************************************************************************/ + + +////////////////////////////////////////////////////////////////////////// +// +// Dominance help member : +// +StructurMember dominanceConstraint[] = +{ + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Dominance 0","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Dominance 1","1.0"), +}; + +////////////////////////////////////////////////////////////////////////// +// +// Dominance help member : +// +StructurMember dominanceItem[] = +{ + + STRUCT_ATTRIBUTE(VTE_PHYSIC_DOMINANCE_GROUP,"Dominance Group A","1"), + STRUCT_ATTRIBUTE(VTE_PHYSIC_DOMINANCE_GROUP,"Dominance Group B","2"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_CONSTRAINT,"Dominance Constraint","1.0,0.0"), + +}; + +StructurMember dominanceSetup[] = +{ + + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 1","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 2","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 3","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 4","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 5","0"), +}; +//STRUCT_ATTRIBUTE(CKPGUID_2DCURVE,"Settings 5","0"), + +void PhysicManager::_RegisterWorldParameters() +{ + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + CKParameterTypeDesc* param_type = NULL; + + + + /************************************************************************/ + /* Dominance Structs */ + /************************************************************************/ + + REGISTER_CUSTOM_STRUCT("pWDominanceConstraint",PS_W_DOMINANCE_CONSTRAINT,VTS_PHYSIC_DOMINANCE_CONSTRAINT,dominanceConstraint,true); + + // Dominance group as user friendly enumeration + pm->RegisterNewEnum(VTE_PHYSIC_DOMINANCE_GROUP,"pDominanceGroup","None=0,First=1,Second=2"); + param_type=pm->GetParameterTypeDescription(VTE_PHYSIC_DOMINANCE_GROUP); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; + + + //if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + + REGISTER_CUSTOM_STRUCT("pDominanceItem",PS_W_DOIMINANCE,VTS_PHYSIC_DOMINANCE_ITEM,dominanceItem,true); + + REGISTER_CUSTOM_STRUCT("pDominanceSetup",PS_W_DOIMINANCE_SETUP,VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS,dominanceSetup,true); + + REGISTER_STRUCT_AS_ATTRIBUTE("Dominance Group Setup",PS_W_DOIMINANCE_SETUP,PHYSIC_BODY_CAT,VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS,CKCID_3DENTITY,dominanceSetup,true); + + + /************************************************************************/ + /* world */ + /************************************************************************/ + + /*pm->RegisterNewEnum(VTE_PHYSIC_BODY_COLL_GROUP,"pBCollisionsGroup","All=0,MyObstacles=1,MyWheels=2"); + param_type=pm->GetParameterTypeDescription(VTE_PHYSIC_BODY_COLL_GROUP); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + */ + + + pm->RegisterNewStructure(VTS_PHYSIC_WORLD_PARAMETER, "pWorldSettings", "Gravity,SkinWith", CKPGUID_VECTOR, CKPGUID_FLOAT ); + + att_world_object = attman->RegisterNewAttributeType("World",VTS_PHYSIC_WORLD_PARAMETER,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_world_object,"Physic"); + + + + + +} diff --git a/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsBody.cpp b/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsBody.cpp new file mode 100644 index 0000000..95a6fe9 --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsBody.cpp @@ -0,0 +1,561 @@ +#include +#include "vtPhysXAll.h" + + +#define PARAM_OP_TYPE_BGET_VELOCITY CKGUID(0x3b2a778c,0x293b206d) +#define PARAM_OP_TYPE_BGET_AVELOCITY CKGUID(0x67ee7c4e,0x1e3b4d15) +#define PARAM_OP_TYPE_BGET_TORQUE CKGUID(0x1ecd7ee4,0x4f0b7eda) +#define PARAM_OP_TYPE_BGET_FORCE CKGUID(0x7dd13e61,0x40af4f99) +#define PARAM_OP_TYPE_BGET_FRICTION CKGUID(0x482b3611,0x4b0a168c) +#define PARAM_OP_TYPE_BGET_HTYPE CKGUID(0x68eb059e,0x26bb745a) +#define PARAM_OP_TYPE_BGET_FIXED CKGUID(0x7bcd7379,0x5c950897) +#define PARAM_OP_TYPE_BGET_KINEMATIC CKGUID(0x6cf414e6,0xf0a35ec) + +#define PARAM_OP_TYPE_BGET_GRAVITY CKGUID(0x63f81d10,0xd532a5a) +#define PARAM_OP_TYPE_BGET_COLLISION CKGUID(0x57f61ee3,0xef1252a) +#define PARAM_OP_TYPE_BGET_COLLISION_GROUP CKGUID(0xeea6d63,0x2d8a032d) +#define PARAM_OP_TYPE_BGET_SLEEPING CKGUID(0x7ca42afe,0x2665435) + +#define PARAM_OP_TYPE_BIS_SUB_SHAPE_OF CKGUID(0x7ed952ce,0x5160083) + + +#define PARAM_OP_TYPE_BGET_FLAGS CKGUID(0x19263740,0x5dd248a2) +#define PARAM_OP_TYPE_BGET_MATERIAL CKGUID(0x1306375d,0x2bcc3cab) +#define PARAM_OP_TYPE_BGET_ISPOBJECT CKGUID(0xa0d7467,0x76692667) + + +#define PARAM_OP_TYPE_BGET_PVEL CKGUID(0x46bc47fc,0x1a4e6a83) +#define PARAM_OP_TYPE_BGET_LPVEL CKGUID(0x1c7e07fa,0x430a084b) +#define PARAM_OP_TYPE_BGET_MASS CKGUID(0x257d5234,0x362841d4) + +#define PARAM_OP_TYPE_BJ_ISCONNECTED CKGUID(0x51db16ef,0xfb772d0) +#define PARAM_OP_TYPE_BJ_NBJOINTS CKGUID(0x29e20d6c,0x6ebc03d2) + + + +#define PARAM_OP_TYPE_BGET_LDAMP CKGUID(0x532052cd,0x97d4334) +#define PARAM_OP_TYPE_BGET_LDAMPT CKGUID(0x7e6623dd,0x3beb16d1) +#define PARAM_OP_TYPE_BGET_ADAMP CKGUID(0x6c620e3b,0x4c2344d8) +#define PARAM_OP_TYPE_BGET_ADAMPT CKGUID(0x148b07eb,0x563c4ff7) + + +void ParamOpBIsSubShape(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + + CK_ID targetID_Sub; + p2->GetValue(&targetID_Sub); + + int result=0; + + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + + if (target->isSubShape(static_cast(context->GetObject(targetID_Sub)))) + { + result = 1; + } + } + } + } + + res->SetValue(&result); + +} + +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetLVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector vec = target->getLinearVelocity(); + res->SetValue(&vec); + } + } + } +} + +void ParamOpBGetAVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector vec = target->getAngularVelocity(); + res->SetValue(&vec); + } + } + } +} + +void ParamOpBGetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector vec = target->getLinearMomentum(); + res->SetValue(&vec); + } + } + } +} +void ParamOpBGetTorque(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector vec = target->getAngularMomentum(); + res->SetValue(&vec); + } + } + } +} + +void ParamOpBisFixed(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->getActor()->isDynamic(); + res->SetValue(&value); + } + } + } +} +void ParamOpBGetHType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->getHullType(); + res->SetValue(&value); + } + } + } +} + +void ParamOpBisKinematic(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->isKinematic(); + res->SetValue(&value); + } + } + } +} +void ParamOpBisCollider(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->isCollisionEnabled(ent); + res->SetValue(&value); + } + } + } +} +void ParamOpBisGravity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->isAffectedByGravity(); + res->SetValue(&value); + } + } + } +} + +void ParamOpBGetCollGroup(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->getCollisionsGroup(); + res->SetValue(&value); + } + } + } +} +void ParamOpBIsSleeping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->isSleeping(); + res->SetValue(&value); + } + } + } +} +void ParamOpBGetFlags(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + target->recalculateFlags(0); + int value = target->getFlags(); + res->SetValue(&value); + } + } + } +} +void ParamOpBIsPObject(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + int result = 0; + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + result = 1; + } + } + } + res->SetValue(&result); +} + +void ParamOpBGetPVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector point; + p2->GetValue(&point); + VxVector vec = target->getPointVelocity(point); + res->SetValue(&vec); + } + } + } +} +void ParamOpBGetLPVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector point; + p2->GetValue(&point); + VxVector vec = target->getLocalPointVelocity(point); + res->SetValue(&vec); + } + } + } +} + + + + +void ParamOpBGetMass(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->getMass(); + res->SetValue(&vec); + } + } + } +} +void ParamOpBJIsConnected(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + + CK_ID targetIDB; + p2->GetValue(&targetIDB); + + int result = - 1; + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + CK3dEntity *entB = static_cast(context->GetObject(targetIDB)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + pJoint *joint = target->isConnected(entB); + if (joint) + { + result = joint->getType(); + } + } + } + } + res->SetValue(&result); +} +void ParamOpBGetMaterial(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + CK_ID targetID2; + p2->GetValue(&targetID2); + CK3dEntity *ent2 = static_cast(context->GetObject(targetID2)); + + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + pMaterial mat = target->getShapeMaterial(ent2); + pFactory::Instance()->copyTo(res,mat); + } + } + } +} + + +void ParamOpBGetNbJoints(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int nbJoints = target->getNbJoints(); + res->SetValue(&nbJoints); + + } + } + } +} + +void PhysicManager::_RegisterParameterOperationsBody() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + + pm->RegisterOperationType(PARAM_OP_TYPE_BJ_NBJOINTS, "bNbJoints"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BJ_NBJOINTS,CKPGUID_INT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetNbJoints); + + + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_MATERIAL, "bMat"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_MATERIAL,VTS_MATERIAL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBGetMaterial); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_VELOCITY, "bVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_VELOCITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetLVelocity); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_AVELOCITY, "bAVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_AVELOCITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetAVelocity); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FORCE, "bForce"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FORCE,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetForce); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_TORQUE, "bTorque"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_TORQUE,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetTorque); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_HTYPE, "bHullType"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_HTYPE,VTE_COLLIDER_TYPE,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetHType); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FIXED, "bDynamic"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FIXED,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisFixed); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_KINEMATIC, "bKinematic"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_KINEMATIC,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisKinematic); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_GRAVITY, "bGravity"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_GRAVITY,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisGravity); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_COLLISION, "bCollider"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_COLLISION,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisCollider); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_COLLISION_GROUP, "bCollGroup"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_COLLISION_GROUP,CKPGUID_INT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetCollGroup); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_SLEEPING, "bSleeping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_SLEEPING,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBIsSleeping); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FLAGS, "bFlags"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FLAGS,VTF_BODY_FLAGS,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetFlags); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_ISPOBJECT, "bRegistered"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_ISPOBJECT,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBIsPObject); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_PVEL, "bPointVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_PVEL,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_VECTOR,ParamOpBGetPVel); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_LPVEL, "bLPointVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_LPVEL,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_VECTOR,ParamOpBGetLPVel); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_MASS, "bMass"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_MASS,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetMass); + + pm->RegisterOperationType(PARAM_OP_TYPE_BJ_ISCONNECTED, "bConnected"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BJ_ISCONNECTED,VTE_JOINT_TYPE,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBJIsConnected); + + pm->RegisterOperationType(PARAM_OP_TYPE_BIS_SUB_SHAPE_OF, "IsSubShape"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BIS_SUB_SHAPE_OF,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBIsSubShape); + +} + + + diff --git a/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsJoints.cpp b/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsJoints.cpp new file mode 100644 index 0000000..10b2ed3 --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsJoints.cpp @@ -0,0 +1,760 @@ +#include +#include "vtPhysXAll.h" + +#define PARAMETER_OP_TYPE_IS_CONNECTED CKGUID(0x2fe947dd,0x783224e9) + +#define PARAM_OP_TYPE_JGET_LIMIT1 CKGUID(0x3678447e,0x30362a74) +#define PARAM_OP_TYPE_JGET_LIMIT2 CKGUID(0xc21ab2,0x465f7f69) +#define PARAM_OP_TYPE_JGET_LIMIT3 CKGUID(0x3ed57b83,0x47ad145f) + +//pMotor : +#define PARAM_OP_TYPE_JMOTOR_SET_TVEL CKGUID(0xa872a4,0x4e8921a4) +#define PARAM_OP_TYPE_JMOTOR_SET_MAXF CKGUID(0x2026057d,0x372684a) +#define PARAM_OP_TYPE_JMOTOR_SET_SPIN_FREE CKGUID(0x4aa2636b,0x734a6d4c) + +#define PARAM_OP_TYPE_JMOTOR_GET_TVEL CKGUID(0x6f91728a,0x29d13cda) +#define PARAM_OP_TYPE_JMOTOR_GET_MAXF CKGUID(0x1e583ea9,0x4305055) +#define PARAM_OP_TYPE_JMOTOR_GET_SPIN_FREE CKGUID(0x50f145b,0x45df2205) + +/************************************************************************/ +/* joint structures : */ +/************************************************************************/ + +void ParamOpJMotorSetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpJMotorSetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpJMotorSetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpJMotorGetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpJMotorGetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpJMotorGetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + + +void ParamOpJMotorSetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJMotorGetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJMotorSetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJMotorGetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJMotorSetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + int value = 0; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJMotorGetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int value = 0; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + +/************************************************************************/ +/* */ +/************************************************************************/ +#define PARAM_OP_TYPE_JLIMIT_SET_VALUE CKGUID(0x38a829f0,0x47851486) +#define PARAM_OP_TYPE_JLIMIT_SET_RES CKGUID(0x3ce77eb1,0x2e921a87) +#define PARAM_OP_TYPE_JLIMIT_SET_HARD CKGUID(0x111a4a9f,0x54094430) + +#define PARAM_OP_TYPE_JLIMIT_GET_VALUE CKGUID(0xc203321,0x4ca77bd) +#define PARAM_OP_TYPE_JLIMIT_GET_RES CKGUID(0x19f812e7,0x5fb3cfc) +#define PARAM_OP_TYPE_JLIMIT_GET_HARD CKGUID(0x6b1b44cd,0x5efc7f51) + +void ParamOpJLimitSetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJLimitGetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJLimitSetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJLimitGetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJLimitSetHard(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJLimitGetHard(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + +/************************************************************************/ +/* spring : */ +/************************************************************************/ +#define PARAM_OP_TYPE_JSPRING_SET_SPRING CKGUID(0x2e0f1602,0x7f9d30fe) +#define PARAM_OP_TYPE_JSPRING_SET_DAMPER CKGUID(0x7392369,0x168f33a1) +#define PARAM_OP_TYPE_JSPRING_SET_VALUE CKGUID(0x70026320,0x35b41a38) + +#define PARAM_OP_TYPE_JSPRING_GET_SPRING CKGUID(0x3dde73ff,0x550c16ff) +#define PARAM_OP_TYPE_JSPRING_GET_DAMPER CKGUID(0x1f793582,0x11f96df9) +#define PARAM_OP_TYPE_JSPRING_GET_VALUE CKGUID(0x76226303,0x67ba262f) + +void ParamOpJSpringSetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJSpringGetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJSpringSetDamper(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJSpringGetDamper(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJSpringSetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJSpringGetVAlue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + + + + +/************************************************************************/ +/* spring : */ +/************************************************************************/ +#define PARAM_OP_TYPE_JSLIMIT_SET_DAMPING CKGUID(0x24e53be6,0x43bf6178) +#define PARAM_OP_TYPE_JSLIMIT_SET_SPRING CKGUID(0x19ea18da,0x4a8f7902) +#define PARAM_OP_TYPE_JSLIMIT_SET_VALUE CKGUID(0x7abb085e,0x464b16b4) +#define PARAM_OP_TYPE_JSLIMIT_SET_RES CKGUID(0x8eb56f2,0x44a40a2) + +#define PARAM_OP_TYPE_JSLIMIT_GET_DAMPING CKGUID(0x74b33ddd,0x6faa11f1) +#define PARAM_OP_TYPE_JSLIMIT_GET_SPRING CKGUID(0x4440614,0x134514de) +#define PARAM_OP_TYPE_JSLIMIT_GET_VALUE CKGUID(0x455a525d,0x77e17e01) +#define PARAM_OP_TYPE_JSLIMIT_GET_RES CKGUID(0x7d1554b4,0x32a72cd3) + + +void ParamOpJSLimitSetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJSLimitGetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJSLimitSetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJSLimitGetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJSLimitSetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJSLimitGetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + + + + + + + +void ParamOpJSLimitSetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,3,value,false); +} +void ParamOpJSLimitGetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),3,false); + } + } + res->SetValue(&value); +} + + + + + + +/************************************************************************/ +/* spring : */ +/************************************************************************/ +#define PARAM_OP_TYPE_JDRIVE_SET_DAMPING CKGUID(0x2ef2554b,0x50681945) +#define PARAM_OP_TYPE_JDRIVE_SET_SPRING CKGUID(0x657274d7,0x5c23079c) +#define PARAM_OP_TYPE_JDRIVE_SET_FORCE CKGUID(0x54d75463,0x2e343c56) +#define PARAM_OP_TYPE_JDRIVE_SET_TYPE CKGUID(0x37ff7a9d,0x1f1c3013) + +#define PARAM_OP_TYPE_JDRIVE_GET_DAMPING CKGUID(0x3d4b76b7,0xf059e8) +#define PARAM_OP_TYPE_JDRIVE_GET_SPRING CKGUID(0x4abe6b69,0x56615834) +#define PARAM_OP_TYPE_JDRIVE_GET_FORCE CKGUID(0x4ff912df,0x40d1429) +#define PARAM_OP_TYPE_JDRIVE_GET_TYPE CKGUID(0x54a63237,0x1f8a3347) + +void ParamOpJDriveSetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJDriveGetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJDriveSetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJDriveGetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJDriveSetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJDriveGetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + +void ParamOpJDriveSetType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + int value = 0; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,3,value,false); +} +void ParamOpJDriveGetType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int value = 0; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),3,false); + } + } + res->SetValue(&value); +} + + + + + + + +void ParamOpJIsConnected(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + CK_ID targetID2; + p2->GetValue(&targetID2); + CK3dEntity *ent2 = static_cast(context->GetObject(targetID2)); + + + if (!pFactory::Instance()->jointCheckPreRequisites(ent,ent2,JT_Distance)) + { + int result = 0; + res->SetValue(&result); + return; + } + + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(ent); + pWorld *worldB=GetPMan()->getWorldByBody(ent2); + if (!worldA) + { + worldA = worldB; + } + if (!worldA) + { + int result = 0; + + res->SetValue(&result); + return; + + } + + pJoint*joint = static_cast(worldA->getJoint(ent,ent2,JT_Any)); + int result = joint ? 1 : 0; + res->SetValue(&result); + return; + +} + + +void PhysicManager::_RegisterParameterOperationsJoint() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + + pm->RegisterOperationType(PARAMETER_OP_TYPE_IS_CONNECTED, "connected"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_IS_CONNECTED,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpJIsConnected); + + + /************************************************************************/ + /* Drive */ + /************************************************************************/ + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_DAMPING, "jDsDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_DAMPING,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,CKPGUID_FLOAT,ParamOpJDriveSetDamping); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_DAMPING, "jDgDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_DAMPING,CKPGUID_FLOAT,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetDamping); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_SPRING, "jDsSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_SPRING,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,CKPGUID_FLOAT,ParamOpJDriveSetSpring); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_SPRING, "jDgSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_SPRING,CKPGUID_FLOAT,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetSpring); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_FORCE, "jDsForce"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_FORCE,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,CKPGUID_FLOAT,ParamOpJDriveSetForce); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_FORCE, "jDgForce"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_FORCE,CKPGUID_FLOAT,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetForce); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_TYPE, "jDsType"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_TYPE,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,VTE_PHYSIC_JDRIVE_TYPE,ParamOpJDriveSetType); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_TYPE, "jDgType"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_TYPE,VTE_PHYSIC_JDRIVE_TYPE,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetType); + + /************************************************************************/ + /* Soft Limit */ + /************************************************************************/ + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_DAMPING, "jSLsDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_DAMPING,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetDamping); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_DAMPING, "jSLgDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_DAMPING,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetDamping); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_SPRING, "jSLsSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_SPRING,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetSpring); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_SPRING, "jSLgSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_SPRING,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetSpring); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_VALUE, "jSLsValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_VALUE,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_VALUE, "jSLgValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_VALUE,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_RES, "jSLsRes"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_RES,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetRes); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_RES, "jSLgRes"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_RES,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetRes); + + /************************************************************************/ + /* spring : */ + /************************************************************************/ + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_SET_SPRING, "jSsSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_SET_SPRING,VTS_JOINT_SPRING,VTS_JOINT_SPRING,CKPGUID_FLOAT,ParamOpJSpringSetSpring); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_GET_SPRING, "jSgSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_GET_SPRING,CKPGUID_FLOAT,VTS_JOINT_SPRING,CKPGUID_NONE,ParamOpJSpringGetSpring); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_SET_DAMPER, "jSsDamper"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_SET_DAMPER,VTS_JOINT_SPRING,VTS_JOINT_SPRING,CKPGUID_FLOAT,ParamOpJSpringSetDamper); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_GET_DAMPER, "jSgDamper"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_GET_DAMPER,CKPGUID_FLOAT,VTS_JOINT_SPRING,CKPGUID_NONE,ParamOpJSpringGetDamper); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_SET_VALUE, "jSsValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_SET_VALUE,VTS_JOINT_SPRING,VTS_JOINT_SPRING,CKPGUID_FLOAT,ParamOpJSpringSetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_GET_VALUE, "jSgValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_GET_VALUE,CKPGUID_FLOAT,VTS_JOINT_SPRING,CKPGUID_NONE,ParamOpJSpringGetVAlue); + + + /************************************************************************/ + /* pJLimit Structure Access : */ + /************************************************************************/ + + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_SET_VALUE, "jLsValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_SET_VALUE,VTS_JLIMIT,VTS_JLIMIT,CKPGUID_FLOAT,ParamOpJLimitSetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_GET_VALUE, "jLgValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_GET_VALUE,CKPGUID_FLOAT,VTS_JLIMIT,CKPGUID_NONE,ParamOpJLimitGetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_SET_RES, "jLsRestitution"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_SET_RES,VTS_JLIMIT,VTS_JLIMIT,CKPGUID_FLOAT,ParamOpJLimitSetRes); + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_GET_RES, "jLgRestitution"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_GET_RES,CKPGUID_FLOAT,VTS_JLIMIT,CKPGUID_NONE,ParamOpJLimitGetRes); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_SET_HARD, "jLsHardness"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_SET_HARD,VTS_JLIMIT,VTS_JLIMIT,CKPGUID_FLOAT,ParamOpJLimitSetHard); + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_GET_RES, "jLgHardness"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_GET_HARD,CKPGUID_FLOAT,VTS_JLIMIT,CKPGUID_NONE,ParamOpJLimitGetHard); + + + /************************************************************************/ + /* pMotor Structure Acess : */ + /************************************************************************/ + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_SET_TVEL, "jMsVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_SET_TVEL,VTS_JOINT_MOTOR,VTS_JOINT_MOTOR,CKPGUID_FLOAT,ParamOpJMotorSetTVel); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_GET_TVEL, "jMgVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_GET_TVEL,CKPGUID_FLOAT,VTS_JOINT_MOTOR,CKPGUID_NONE,ParamOpJMotorGetTVel); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_SET_MAXF, "jMsFMax"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_SET_MAXF,VTS_JOINT_MOTOR,VTS_JOINT_MOTOR,CKPGUID_FLOAT,ParamOpJMotorSetFMAX); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_GET_MAXF, "jMgFMax"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_GET_MAXF,CKPGUID_FLOAT,VTS_JOINT_MOTOR,CKPGUID_NONE,ParamOpJMotorGetFMAX); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_SET_SPIN_FREE, "jMsSpinFree"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_SET_SPIN_FREE,VTS_JOINT_MOTOR,VTS_JOINT_MOTOR,CKPGUID_BOOL,ParamOpJMotorSetSpinFree); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_GET_SPIN_FREE, "jMgSpingFree"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_GET_SPIN_FREE,CKPGUID_BOOL,VTS_JOINT_MOTOR,CKPGUID_NONE,ParamOpJMotorGetSpinFree); + + + + + + +} + diff --git a/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsMisc.cpp b/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsMisc.cpp new file mode 100644 index 0000000..edb7d22 --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsMisc.cpp @@ -0,0 +1,10 @@ +#include +#include "vtPhysXAll.h" + + +void PhysicManager::_RegisterParameterOperationsMisc() +{ + CKParameterManager *pm = m_Context->GetParameterManager(); + //pm->RegisterOperationType(PARAM_OP_TYPE_BGET_MATERIAL, "bMat"); + //pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_MATERIAL,VTS_MATERIAL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBGetMaterial); +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsVehicle.cpp b/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsVehicle.cpp new file mode 100644 index 0000000..4fabd4a --- /dev/null +++ b/usr/Src/Core/Manager/Parameter/PhysicManager_ParameterOperationsVehicle.cpp @@ -0,0 +1,87 @@ +#include +#include "vtPhysXAll.h" + +#define PARAMETER_OP_TYPE_WHEEL_GETCONTACT CKGUID(0x74654a40,0x74ba3b5b) +#define PARAMETER_OP_TYPE_WDATA_GET_COLLIDER CKGUID(0x4dae6732,0x37740a24) +#define PARAMETER_OP_TYPE_WDATA_GET_MATERIAL CKGUID(0xa45301e,0x73e41d8f) +#define PARAMETER_OP_TYPE_WDATA_GET_CPOINT CKGUID(0x2f731ff8,0xa792311) + + +void ParamOpWheelContactGetCollider(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + if (p1) + { + if (p1->GetRealSource()) + { + CK_ID value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_WCD_CONTACT_ENTITY,false); + res->SetValue(&value); + } + } +} + +void ParamOpWheelContactGetMaterial(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + if (p1) + { + if (p1->GetRealSource()) + { + CKParameterOut *materialParameter = vtTools::ParameterTools::GetParameterFromStruct(p1->GetRealSource(),E_WCD_OTHER_MATERIAL_INDEX,false); + if (materialParameter) + { + res->CopyValue(materialParameter); + } + } + } +} + +void ParamOpWheelGetContact(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + pRigidBody *body = NULL; + + //user comes usually with entity which is associated with the wheel and not with the body reference : + body = GetPMan()->getBody(pFactory::Instance()->getMostTopParent(ent)); + if (!body) + return; + + pWheel2 *wheel =(pWheel2*)body->getWheel(ent); + if (!wheel)return; + + pWheelContactData cData = *wheel->getContact(); + + //copy result in the parameter operations result parameter : + pFactory::Instance()->copyTo(res,cData); + +} + + + +void PhysicManager::_RegisterParameterOperationsVehicle() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + + + pm->RegisterOperationType(PARAMETER_OP_TYPE_WHEEL_GETCONTACT, "pwGContact"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_WHEEL_GETCONTACT,VTS_WHEEL_CONTACT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpWheelGetContact); + + ////////////////////////////////////////////////////////////////////////// + // member retrieve of the type pWheelContactData : + + //other entity : + pm->RegisterOperationType(PARAMETER_OP_TYPE_WDATA_GET_COLLIDER, "wcdGEntity"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_WDATA_GET_COLLIDER,CKPGUID_3DENTITY,VTS_WHEEL_CONTACT,CKPGUID_NONE,ParamOpWheelContactGetCollider); + + //material + pm->RegisterOperationType(PARAMETER_OP_TYPE_WDATA_GET_MATERIAL, "wcdGMaterial"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_WDATA_GET_MATERIAL,VTS_MATERIAL,VTS_WHEEL_CONTACT,CKPGUID_NONE,ParamOpWheelContactGetMaterial); + + + +} diff --git a/usr/Src/Core/Manager/PhysicManager.cpp b/usr/Src/Core/Manager/PhysicManager.cpp new file mode 100644 index 0000000..47f23b7 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManager.cpp @@ -0,0 +1,384 @@ +#include + +#include "vtPhysXAll.h" + +#include +#include + + + +#include "IParameter.h" + +#include "xTime.h" + +PhysicManager *manager = NULL; +using namespace xUtils; +using namespace vtAgeia; + + +pRestoreMap*PhysicManager::_getRestoreMap(){ return restoreMap; } + +CKERROR PhysicManager::PreLaunchScene(CKScene* OldScene,CKScene* NewScene) +{ + return CK_OK; +} + +CKERROR PhysicManager::PostLaunchScene(CKScene* OldScene,CKScene* NewScene) +{ + int o = getPhysicFlags(); + if( !(physicFlags & PMF_DONT_DELETE_SCENES) ) + { + if(GetContext()->IsPlaying()) + { + _removeObjectsFromOldScene(OldScene); + checkWorlds(); + _checkObjectsByAttribute(NewScene); + sceneWasChanged = true; + } + } + return CK_OK; +} +void PhysicManager::_destruct(xBitSet flags /* = 0 */) +{ + + //################################################################ + // + // some sanity checks + // + assert(mIParameter); + assert(m_Worlds); + assert(manager); + + //################################################################ + // + // Clean instances : + // + SAFE_DELETE(mIParameter); +} +////////////////////////////////////////////////////////////////////////// +PhysicManager::PhysicManager(CKContext* context):CKPhysicManager(context,GUID_MODULE_MANAGER,VTCX_API_ENTRY("PhysicManager")) //Name as used in profiler +{ + + + sceneWasChanged = 0; + m_Context->RegisterNewManager(this); + m_Worlds = new pWorldMap(); + manager = this; + disablePhysics = false; + checkPhysics =false; + m_IsSimulating = false; + + _Hook3DBBs(); + _HookGenericBBs(); + + _construct(); + int ss = xLogger::GetInstance()->getItemDescriptions().size(); + int ss2= xLogger::GetInstance()->getLogItems().size(); + //xLogger::xLog(ELOGERROR,E_BB,"No Reference Object specified"); + + timer = 0.0f; + mPhysicsSDK = NULL; + DongleHasBasicVersion=0; + DongleHasAdvancedVersion=0; + + _LogErrors = _LogInfo = _LogTrace = _LogWarnings = _LogToConsole = 0; + mIParameter = new IParameter(this); + restoreMap = new pRestoreMap(); + + + +} +////////////////////////////////////////////////////////////////////////// +void PhysicManager::cleanAll() +{ + + ////////////////////////////////////////////////////////////////////////// + //destroy all worlds : + if (getWorlds()->Size()) + { + destroyWorlds(); + m_DefaultWorld = NULL; + + } + + ////////////////////////////////////////////////////////////////////////// + //destroy default objects : + + + + ////////////////////////////////////////////////////////////////////////// + //world settings : + if (getDefaultWorldSettings()) + { + SAFE_DELETE(mDefaultWorldSettings); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted default world settings"); + } + + + ////////////////////////////////////////////////////////////////////////// + //default configuration : + if (m_DefaultDocument) + { + SAFE_DELETE(m_DefaultDocument); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted default configuration"); + } + + if (pFactory::Instance()) + { + pFactory::Instance()->reloadConfig("PhysicDefaults.xml"); + } + + if (getPhysicsSDK()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Physic SDK released "); + NxReleasePhysicsSDK(getPhysicsSDK()); + mPhysicsSDK = NULL; + } + + + + _getManagerFlags() = 0 ; + mTriggers.Clear(); + bodyListRemove.Clear(); + resetList.Clear(); + if(restoreMap) + restoreMap->Clear(); + + + +} + +void PhysicManager::doInit(){ + //CreateWorlds(0); +} +CKERROR PhysicManager::OnCKPause() +{ + return CK_OK; +} +CKERROR PhysicManager::OnCKPlay() +{ + time->Reset(); + time->Start(); + + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGERROR,_LogErrors); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGERROR,_LogErrors); + + + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGTRACE,_LogTrace); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGWARNING,_LogWarnings); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGINFO,_LogInfo); + + m_IsSimulating = false; + + try { + populateAttributeFunctions(); + _RegisterAttributeCallbacks(); + } catch(std::exception ex) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Error during Attribute List Populations"); + } catch(...) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Error during Attribute List Populations"); + } + if (getNbObjects()) + { + if ( + isFlagOff(_getManagerFlags(),E_MF_PSDK_LOADED) && + isFlagOff(_getManagerFlags(),E_MF_DEFAULT_WORLD_CREATED) && + isFlagOff(_getManagerFlags(),E_MF_FACTORY_CREATED) + ) + { + performInitialization(); + checkWorlds(); + } + } + return CK_OK; +} +CKERROR PhysicManager::PostClearAll() +{ + return CK_OK; +} +CKERROR PhysicManager::OnCKInit() +{ + bindVariables(); + return CK_OK; +} + + +CKERROR PhysicManager::PreSave() +{ + return CK_OK; +} +CKContext* PhysicManager::GetContext() +{ + return manager->m_Context; +} +PhysicManager* PhysicManager::GetInstance() +{ + if (manager) + { + return manager; + } + return NULL; +} +PhysicManager::~PhysicManager(){} + +CKERROR PhysicManager::OnPostCopy(CKDependenciesContext& context) +{ +/* + CKDependenciesContext dependencies_ctx(m_Context); +// dependencies_ctx.SetOperationMode(CK_DEPENDENCIES_SAVE); +/* + dependencies_ctx.StartDependencies(iDep); + + //We scan the group and fill the dependencies context + for (int i=0;iGetObjectCount();i++) + { + CKBeObject* object = iGrp->GetObject(i); + object->PrepareDependencies(dependencies_ctx); + } +*/ + /* + // Build a list of id to save + return CK_OK; + XObjectArray dependencies_list = context.FillDependencies(); + int s = dependencies_list.Size(); + + + + //dependencies_list.PushBack(iGrp->GetID());//add group at the end + + //copy list of objects in ckobjectarray + CKObjectArray* listToSave = CreateCKObjectArray(); + XObjectArray::Iterator it1 = dependencies_list.Begin(); + XObjectArray::Iterator it2 = dependencies_list.End(); + while (it1!=it2) + { + CKObject* object = m_Context->GetObject(*it1); + CK_ID cID = object->GetID(); + listToSave->InsertRear(*it1++); + CKSTRING name = object->GetName(); + + CK_ID id2 = context.RemapID(cID); + CK_ID id3 = context.RemapID(cID); + + + + } +*/ + return CK_OK; + + +} +CKERROR PhysicManager::SequenceDeleted(CK_ID *objids,int count) +{ + + + + if (getNbObjects()) + { + if(GetContext()->IsPlaying()) + checkWorlds(); + } + return CK_OK; +} + +CKERROR PhysicManager::SequenceAddedToScene(CKScene *scn,CK_ID *objids,int count) +{ + int isInLoad=GetContext()->IsInLoad(); + int nbOfObjects = 0 ; + if (!GetContext()->IsPlaying()) + { + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(GetPAttribute()); + nbOfObjects = Array.Size(); + if (nbOfObjects) + { + //_migrateOldCustomStructures(scn); + } + } + if (getNbObjects()) + { + if(GetContext()->IsPlaying()){ + + + /* + for (int i = 0 ; i < count ; i++ ) + { + CK_ID dstId = objids[i]; + CKBeObject * obj = GetContext()->GetObject() + } + */ + checkWorlds(); + } + } + return CK_OK; +} +CKERROR PhysicManager::SequenceToBeDeleted(CK_ID *objids,int count) +{ + return CK_OK; +} + +CKERROR PhysicManager::SequenceRemovedFromScene(CKScene *scn,CK_ID *objids,int count) +{ + if (getNbObjects()) + { + if(GetContext()->IsPlaying()) + checkWorlds(); + } + return CK_OK; +} + + +CKERROR PhysicManager::PreClearAll() +{ + return CK_OK; +} + +CKERROR PhysicManager::OnCKReset() +{ + cleanAll(); + _RegisterDynamicParameters(); + return CK_OK; +} +CKERROR PhysicManager::OnCKEnd() +{ + + SAFE_DELETE(mIParameter); + SAFE_DELETE(restoreMap); + SAFE_DELETE(m_Worlds); + + if (getPhysicsSDK()) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Releasing old SDK "); + NxReleasePhysicsSDK(getPhysicsSDK()); + setPhysicsSDK(NULL); + } + + if(getDefaultConfig()) + SAFE_DELETE(m_DefaultDocument); + + + if(getLogger()) + SAFE_DELETE(mLogger); + + if(mDefaultWorldSettings) + SAFE_DELETE(mDefaultWorldSettings); + + if(m_currentFactory) + SAFE_DELETE(mDefaultWorldSettings); + + if (m_DefaultWorld) + SAFE_DELETE(m_DefaultWorld) + + if(time) + SAFE_DELETE(time); + + + + + + unBindVariables(); + + return 0; +} + diff --git a/usr/Src/Core/Manager/PhysicManagerBody.cpp b/usr/Src/Core/Manager/PhysicManagerBody.cpp new file mode 100644 index 0000000..c3419d1 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerBody.cpp @@ -0,0 +1,173 @@ +#include + +#include "vtPhysXAll.h" + +#include "vtStructHelper.h" + +//################################################################ +// +// Prototype +// +XString getDefaultValue(CKParameter *inputParameter) +{ + CustomParametersArrayType& inputArray = GetPMan()->_getCustomStructures(); + XString result; + + int s = inputArray.Size(); + + + + CustomParametersArrayIteratorType it = inputArray.Find(inputParameter->GetGUID()); + if (it == inputArray.End()) + return result; + + using namespace vtTools::ParameterTools; + + int x = 0; + CustomStructure *cStruct = *it; + if (cStruct) + { + cStruct->getArray().size(); + } + + CKParameterTypeDesc *tdescr = GetPMan()->GetContext()->GetParameterManager()->GetParameterTypeDescription( inputParameter->GetType() ); + if( (tdescr->dwFlags & CKPARAMETERTYPE_STRUCT) == 0x00000010 ) + { + int y = cStruct->getArray().size(); + int y2 = cStruct->getArray().size(); + }else{ + } + + return result; +} + +//################################################################ +// +// Not being used +// +void rigidBodyAttributeCallback(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg) +{ + + // recheckWorldsFunc(AttribType,Set,obj,arg); + +} + +//################################################################ +// +// Body functions +// +pRigidBody*PhysicManager::getBody(const char*name,int flags/* =0 */) +{ + + for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) + { + pWorld *w = *it; + if(w) + { + int nbActors = w->getScene()->getNbActors(); + NxActor** actors = w->getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + if (!strcmp(actor->getName(),name) ) + { + + pRigidBody* body =static_cast(actor->userData); + if (body) + { + return body; + } + } + } + } + } + } + return 0; +} +pRigidBody*PhysicManager::getBody(CK3dEntity *ent,bool lookInSubshapes) +{ + ////////////////////////////////////////////////////////////////////////// + + if (!lookInSubshapes) + { + pWorld* w = getWorldByBody(ent); + if (w) + { + pRigidBody *body = w->getBody(ent); + if (body) + { + return body; + } + } + }else + { + for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) + { + pWorld *w = *it; + if(w) + { + int nbActors = w->getScene()->getNbActors(); + NxActor** actors = w->getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body = (pRigidBody*)actor->userData; + if (body) + { + NxShape *subShapeObj = body->_getSubShapeByEntityID(ent->GetID()); + if( subShapeObj) + { + return body; + } + } + } + } + } + } + + /*NxShape * shape = getSubShape(ent); + if (shape) + { + pSubMeshInfo *sInfo = static_cast(shape->userData); + if (sInfo) + { + NxActor*actor = &shape->getActor(); + if(actor) + { + + if(actor->userData != NULL) + { + pRigidBody* body =static_cast(actor->userData); + if (body) + { + return body; + } + } + } + } + } + */ + } + + return NULL; +} + +pRigidBody*PhysicManager::isSubShape(CK3dEntity *ent) +{ + pRigidBody *result = getBody(ent); + if (result) + { + + //Check that the entity is not registered as body already + if (result->GetVT3DObject() == ent ) + return NULL; + + } + + + return NULL; +} diff --git a/usr/Src/Core/Manager/PhysicManagerBodyAttributeFunctions.cpp b/usr/Src/Core/Manager/PhysicManagerBodyAttributeFunctions.cpp new file mode 100644 index 0000000..3402055 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerBodyAttributeFunctions.cpp @@ -0,0 +1,146 @@ +#include +#include "vtPhysXAll.h" + + +using namespace xUtils; +using namespace vtAgeia; + + +#include "vtAttributeHelper.h" + + +// [3/31/2009 master] Temp ! +#include "IParameter.h" + + + +//################################################################ +// +// Declaration of rigid body related attribute callback function +// +int registerRigidBody(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + + using namespace vtTools::ParameterTools; + int error = 0 ; + + + //---------------------------------------------------------------- + // + // Sanity checks : + // + assert(target); + + CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); + + CKParameterOut *bodyParameter = target->GetAttributeParameter(attributeType); + + assert(bodyParameter); + CKStructHelper sHelper(bodyParameter); + if (sHelper.GetMemberCount() ==0 ) + { //happens when dev is being opened and loads a cmo with physic objects. + return -1; + } + + + + if (set) + { + + pRigidBody* body = GetPMan()->getBody(target); + if (body) + { + return true; + } + //---------------------------------------------------------------- + // + // attribute has been added at run-time, post pone the registration to the next frame. + // + if ( isPostJob && GetPMan()->GetContext()->IsPlaying() ) + { + pAttributePostObject postAttObject(target->GetID(),registerRigidBody,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + } + if(!GetPMan()->GetContext()->IsPlaying()) + return true; + + + pObjectDescr *objDecr = new pObjectDescr(); + IParameter::Instance()->copyTo(objDecr,bodyParameter); + + //---------------------------------------------------------------- + // + // Pivot override ? + // + int attPivot = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); + if (target->HasAttribute(attPivot)){ + IParameter::Instance()->copyTo(objDecr->pivot,target->GetAttributeParameter(attPivot)); + objDecr->mask << OD_Pivot; + } + + //---------------------------------------------------------------- + // + // Pivot override ? + // + int attMass = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); + if (target->HasAttribute(attMass)){ + IParameter::Instance()->copyTo(objDecr->mass,target->GetAttributeParameter(attMass)); + objDecr->mask << OD_Mass; + } + + //---------------------------------------------------------------- + // + // register the body + // + if(!body && !(objDecr->flags & BF_SubShape) ) + { + body = pFactory::Instance()->createRigidBody(target,*objDecr); + if (body) + { + body->setInitialDescription(objDecr); + } + } + + //SAFE_DELETE(objDecr); + + + }else + { + + pRigidBody* body = GetPMan()->getBody(target); + if (body) + { + body->getWorld()->deleteBody(body); + } + } + error++; + return error; +} + + +/* +//################################################################ +// +// Not being used +// +int registerRigidBody(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + +if (!GetPMan()->GetContext()->IsPlaying() && set) +{ + +using namespace vtTools::ParameterTools; +CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + +XString errString; +errString.Format("attr added"); +xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.Str()); + +XString value = getDefaultValue(distanceParameter); +} + +return 0; +} + +*/ diff --git a/usr/Src/Core/Manager/PhysicManagerBuildingBlockOverides3DTransforms.cpp b/usr/Src/Core/Manager/PhysicManagerBuildingBlockOverides3DTransforms.cpp new file mode 100644 index 0000000..f491191 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerBuildingBlockOverides3DTransforms.cpp @@ -0,0 +1,574 @@ +#include +#include "vtPhysXAll.h" + +#define BB_SET_POSITION_GUID CKGUID(0xe456e78a, 0x456789aa) +#define BB_SET_ORIENTATION_GUID CKGUID(0x625874aa, 0xaa694132) +#define BB_ROTATE_GUID CKGUID(0xffffffee, 0xeeffffff) +#define BB_TRANSLATE_GUID CKGUID(0x000d000d, 0x000d000d) + +#define BB_SET_EORIENTATION_GUID CKGUID(0xc4966d8,0x6c0c6d14) +#define BB_PLAY_GLOBAL_ANIMATION CKGUID(0x1c9236e1,0x42f40996) +#define BB_SET_LOCAL_MATRIX CKGUID(0x21f5f30d, 0x08d5a1db) +#define BB_SET_WORLD_MATRIX CKGUID(0xaa4aa6f0, 0xddefdef4) +#define BB_RESTORE_IC CKGUID(0x766e4e44,0x4fac6d52) +#define BB_LAUNCH_SCENE CKGUID(0x188d6d43,0x169613dd) + + + +CKBEHAVIORFCT BBSetEOri; +CKBEHAVIORFCT BBSetPos; +CKBEHAVIORFCT BBSetOri; +CKBEHAVIORFCT BBRotate; +CKBEHAVIORFCT BBTranslate; +CKBEHAVIORFCT BBPlayGlobalAnimation; +CKBEHAVIORFCT BBSetLocalMatrix; +CKBEHAVIORFCT BBSetWorldMatrix; +CKBEHAVIORFCT BBRestoreIC; +CKBEHAVIORFCT BBLaunchScene; + + + +#define BRESET VxVector vectorN(0,0,0);\ + int pResetF=0;behaviour->GetLocalParameterValue(1,&pResetF);\ + int pResetT=0;behaviour->GetLocalParameterValue(2,&pResetT);\ + int pResetLV=0;behaviour->GetLocalParameterValue(3,&pResetLV);\ + int pResetAV=0;behaviour->GetLocalParameterValue(4,&pResetAV);\ + if (pResetF) solid->setLinearMomentum(vectorN);\ + if (pResetT)solid->setAngularMomentum(vectorN);\ + if (pResetLV)solid->setLinearVelocity(vectorN);\ + if (pResetAV)solid->setAngularVelocity(vectorN);\ + + +int BB_SetEOrientationNew(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBSetEOri(context); + + int pUpdate=0; + behaviour->GetLocalParameterValue(1,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + + + BRESET; + VxVector pos,scale; VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + int hierarchy = vtTools::BehaviorTools::GetInputParameterValue(behaviour,1); + if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) + { + solid->onSubShapeTransformation(false,true,true,ent,hierarchy); + }else{ + VxVector vector(0,0,0); + ent->GetPosition(&vector); + solid->setPosition(vector,ent); + + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setRotation(quat); + } + //solid->updateSubShapes(false,false,true,ent); + + } + } + return CK_OK; +} +int BB_SetPosNew(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + BBSetPos(context); + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + + pWorld *world = GetPMan()->getWorldByBody(ent); + if (!world) + { + return 0; + } + + pRigidBody *solid = world->getBody(ent); + if (solid) + { + BRESET; + VxVector pos,scale; VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + int hierarchy = vtTools::BehaviorTools::GetInputParameterValue(behaviour,1); + if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) + { + solid->onSubShapeTransformation(false,true,false,ent,hierarchy); + }else{ + VxVector vector(0,0,0); + ent->GetPosition(&vector); + solid->setPosition(vector,ent); + } + } + } + return CK_OK; + +} + + +int BB_SetOrientationNew(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBSetOri(context); + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + + BRESET + int hierarchy = vtTools::BehaviorTools::GetInputParameterValue(behaviour,2); + if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) + { + solid->onSubShapeTransformation(false,true,true,ent,hierarchy); + }else{ + + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setRotation(quat); + } + //solid->updateSubShapes(false,true,true,ent); + } + } + return CK_OK; +} + +int BB_RotateNew(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + BBRotate(context); + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + + pRigidBody *solid = GetPMan()->getBody(ent,true); + if (solid) + { + BRESET; + int hierarchy = vtTools::BehaviorTools::GetInputParameterValue(behaviour,3); + if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) + { + solid->onSubShapeTransformation(false,true,true,ent,hierarchy); + }else{ + + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setRotation(quat); + } + } + } + return CK_OK; +} + +int BB_TranslateNew(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + BBTranslate(context); + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + BRESET; + VxVector pos,scale; VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + int hierarchy = vtTools::BehaviorTools::GetInputParameterValue(behaviour,1); + if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) + { + solid->onSubShapeTransformation(false,true,true,ent,hierarchy); + }else{ + solid->setPosition(pos,ent); + } + } + } + return CK_OK; +} + +int BBPlayGlobalAnimation_New(const CKBehaviorContext& context) +{ + + + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + int returnValue= BBPlayGlobalAnimation(context); + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + + + BRESET + if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) + { + solid->onSubShapeTransformation(false,true,true,ent,true); + }else{ + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setPosition(pos,ent); + + } + }/* + else + { + pWorld *world = GetPMan()->getWorldByBody(ent); + if (world) + { + solid = world->getBodyFromSubEntity(ent); + if (solid) + { + solid->updateSubShapes(false,true,true); + } + } + }*/ + + } + return returnValue; +} + +int BBSetLocalMatrix_New(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBSetLocalMatrix(context); + + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + + BRESET; + int hierarchy = vtTools::BehaviorTools::GetInputParameterValue(behaviour,1); + if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) + { + solid->onSubShapeTransformation(false,true,true,ent,hierarchy); + }else{ + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setPosition(pos,ent); + } + } + } + return CK_OK; +} + +int BBSetWorldMatrix_New(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBSetWorldMatrix(context); + + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + + //solid->getActor()-> + + BRESET + int hierarchy = vtTools::BehaviorTools::GetInputParameterValue(behaviour,1); + if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) + { + solid->onSubShapeTransformation(false,true,true,ent,hierarchy); + }else{ + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setPosition(pos,ent); + } + } + } + return CK_OK; +} + +int BBRestoreIC_New(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBRestoreIC(context); + + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + int hierarchy=0;behaviour->GetLocalParameterValue(5,&hierarchy); + int restoreJoints=0;behaviour->GetLocalParameterValue(6,&restoreJoints); + bool done= false; + if (pUpdate) + { + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + BRESET + + if (ent && ent->GetClassID() != CKCID_3DOBJECT) + { + return CK_OK; + } + + /* + if ( (solid->getFlags() & BF_Hierarchy ) && solid->GetVT3DObject() !=ent ) + { + solid->onSubShapeTransformation(false,true,true,ent,(solid->getFlags() & BF_Hierarchy )); + }else{ + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setPosition(pos,ent); + } + */ + + pRigidBodyRestoreInfo *rInfo = new pRigidBodyRestoreInfo(); + rInfo->hierarchy = hierarchy; + rInfo->removeJoints= restoreJoints; + GetPMan()->_getRestoreMap()->Insert(ent->GetID(),rInfo); + done = true; + } + } + + if (hierarchy && !done) + { + CKScene *scene = GetPMan()->GetContext()->GetCurrentLevel()->GetLevelScene(); + if(scene) + { + CK3dEntity* subEntity = NULL; + XArraySrcObjects; + while (subEntity= ent->HierarchyParser(subEntity) ) + { + CKStateChunk *chunk = scene->GetObjectInitialValue(subEntity); + if (chunk) + { + CKReadObjectState(subEntity,chunk); + } + } + } + } + return CK_OK; +} + + + +int BBLaunchScene_New(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + + CKScene *currentScene= GetPMan()->GetContext()->GetCurrentLevel()->GetCurrentScene(); + CKScene *nextScene = NULL; + BBLaunchScene(context); +/* + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + nextScene = (CKScene*)behaviour->GetInputParameterObject(0); + if (pUpdate) + { + if(GetPMan()->GetContext()->IsPlaying()) + { + GetPMan()->_removeObjectsFromOldScene(currentScene); + GetPMan()->_checkObjectsByAttribute(nextScene); + } + } + */ + return CK_OK; +} + + + + + + + +CKERROR PhysicManager::_Hook3DBBs() +{ + CKBehaviorManager *bm = m_Context->GetBehaviorManager(); + + CKBehaviorPrototype *bproto = CKGetPrototypeFromGuid(BB_SET_EORIENTATION_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBSetEOri = bproto->GetFunction(); + bproto->SetFunction(BB_SetEOrientationNew); + + } + + bproto = CKGetPrototypeFromGuid(BB_SET_POSITION_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBSetPos = bproto->GetFunction(); + bproto->SetFunction(BB_SetPosNew); + + } + + bproto = CKGetPrototypeFromGuid(BB_SET_ORIENTATION_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBSetOri = bproto->GetFunction(); + bproto->SetFunction(BB_SetOrientationNew); + } + + bproto = CKGetPrototypeFromGuid(BB_ROTATE_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBRotate = bproto->GetFunction(); + bproto->SetFunction(BB_RotateNew); + } + bproto = CKGetPrototypeFromGuid(BB_TRANSLATE_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBTranslate = bproto->GetFunction(); + bproto->SetFunction(BB_TranslateNew); + } + + + + bproto = CKGetPrototypeFromGuid(BB_PLAY_GLOBAL_ANIMATION); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBPlayGlobalAnimation = bproto->GetFunction(); + bproto->SetFunction(BBPlayGlobalAnimation_New); + } + + + bproto = CKGetPrototypeFromGuid(BB_SET_LOCAL_MATRIX); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBSetLocalMatrix = bproto->GetFunction(); + bproto->SetFunction(BBSetLocalMatrix_New); + } + + bproto = CKGetPrototypeFromGuid(BB_SET_WORLD_MATRIX); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBSetWorldMatrix = bproto->GetFunction(); + bproto->SetFunction(BBSetWorldMatrix_New); + } + + bproto = CKGetPrototypeFromGuid(BB_RESTORE_IC); + if(bproto) + { + + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"true"); + + bproto->DeclareSetting("Hierarchy",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Restore Joints from Attribute",CKPGUID_BOOL,"true"); + + + BBRestoreIC = bproto->GetFunction(); + bproto->SetFunction(BBRestoreIC_New); + } + + bproto = CKGetPrototypeFromGuid(BB_LAUNCH_SCENE); + if(bproto) + { + + //bproto->DeclareSetting("Destroy Old Physics",CKPGUID_BOOL,"true"); + BBLaunchScene = bproto->GetFunction(); + bproto->SetFunction(BBLaunchScene_New); + } + + return CK_OK; +} diff --git a/usr/Src/Core/Manager/PhysicManagerCheckDemo.cpp b/usr/Src/Core/Manager/PhysicManagerCheckDemo.cpp new file mode 100644 index 0000000..f5e8afa --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerCheckDemo.cpp @@ -0,0 +1,37 @@ +#include +#include "vtPhysXAll.h" + + +BOOL PhysicManager::checkDemo(CK3dEntity* a) +{ + return true; + + /* + if (!a) + { + return false; + } + //VxVector scale = vtODE::math::BoxGetZero(a); + /*if ( scale.x > 400 || scale.y > 100 || scale.z > 400 ) + { + return false; + } + + if (GetPMan()->DefaultWorld() && GetPMan()->DefaultWorld()->NumBodies() > 30 ) + { + return false; + } + //return true; + CKMesh *mesh = (CKMesh *)a->GetCurrentMesh(); + + if (mesh) + { + int vcount = mesh->GetVertexCount(); + if (vcount ==960 ||vcount ==559 || vcount ==4096 ||vcount ==106 ||vcount ==256 || vcount ==17 || vcount ==24 || vcount == 266 || vcount == 841 ) + { + return true; + } + } + return false; + */ +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerCollision.cpp b/usr/Src/Core/Manager/PhysicManagerCollision.cpp new file mode 100644 index 0000000..cd08ced --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerCollision.cpp @@ -0,0 +1,17 @@ +#include +#include "vtPhysXAll.h" + +////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// +struct clist2 +{ + + CK3dEntity *part; + CK3dEntity *obstacle; + CK3dEntity *sub_obstacle; + VxVector pos; + VxVector normal; + float depth; + clist2(CK3dEntity* p , CK3dEntity *o,CK3dEntity*so, VxVector po, VxVector n , float d ) : + part(p) , obstacle(o), sub_obstacle(so), pos(po) , normal (n) , depth (d){} + +}; diff --git a/usr/Src/Core/Manager/PhysicManagerData.cpp b/usr/Src/Core/Manager/PhysicManagerData.cpp new file mode 100644 index 0000000..3e382b6 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerData.cpp @@ -0,0 +1,1080 @@ +#include +#include "vtPhysXAll.h" +#include "IParameter.h" + + +XString PhysicManager::_getConfigPath() +{ + + XString result; + + + CKPathManager *pm = (CKPathManager*)this->m_Context->GetPathManager(); + + //pm->OpenSubFile() + + XString configFile("DonglePaths.ini"); + XString section("Paths"); + + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,configFile); + + + int errorLine; + XString errorText; + VxConfiguration config; + VxConfigurationSection *tsection = NULL; + VxConfigurationEntry *entry = NULL; + + if (!config.BuildFromFile(Ini, errorLine, errorText)) + { + MessageBox(NULL,"Cannot open DonglePath.Ini in Virtools directory",0,MB_OK|MB_ICONERROR); + return XString("none"); + } + + if ((tsection = config.GetSubSection((char*)section.Str(), FALSE)) != NULL) + { + + ConstEntryIt it = tsection->BeginChildEntry(); + VxConfigurationEntry *sEntry = NULL; + + + char newPath[MAX_PATH]; + while (sEntry=tsection->GetNextChildEntry(it)) + { + if (sEntry!=NULL) + { + const char * value = sEntry->GetValue(); + XString path(value); + + FILE *file = fopen(path.CStr(),"r"); + if (file) + { + fclose(file); + return path; + } + } + } + MessageBox(NULL,"Couldnt find any valid license file in the DonglePaths.Ini",0,MB_OK|MB_ICONERROR); + } + return result; +} + + +void PhysicManager::bindVariables() +{ + + CKVariableManager* vm = m_Context->GetVariableManager(); + if( !vm ) + return; + + pSDKParameters& p = getSDKParameters(); + + vm->Bind( + "Physic/Skin Width", &p.SkinWidth, 0.025f, VxVar::COMPOSITIONBOUND, + "Default value for pShape::skinWidth."); + + vm->Bind( + "Physic/Default Sleep Linear Velocity Squared", &p.DefaultSleepLinVelSquared, 0.15f*0.15f, VxVar::COMPOSITIONBOUND, + "The default linear velocity, squared, below which objects start going to sleep. Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set."); + + vm->Bind( + "Physic/Default Sleep Angular Velocity Squared", &p.DefaultSleepAngVel_squared, 0.14f * 0.14f, VxVar::COMPOSITIONBOUND, + "The default angular velocity, squared, below which objects start going to sleep. Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set."); + + vm->Bind( + "Physic/Bounce Threshold", &p.BounceThreshold , -2.0f , VxVar::COMPOSITIONBOUND, + "A contact with a relative velocity below this will not bounce."); + + vm->Bind( + "Physic/Dynamic Friction Scaling", &p.DynFrictScaling,1.0f , VxVar::COMPOSITIONBOUND, + "This lets the user scale the magnitude of the dynamic friction applied to all objects. "); + + + vm->Bind( + "Physic/Static Friction Scaling", &p.StaFrictionScaling,1.0f,VxVar::COMPOSITIONBOUND, + "This lets the user scale the magnitude of the static friction applied to all objects."); + + + + vm->Bind( + "Physic/Maximum Angular Velocity", &p.MaxAngularVelocity , 7.0f, VxVar::COMPOSITIONBOUND, + "See the comment for pRigidBody::setMaxAngularVelocity() for details."); + + + vm->Bind( + "Physic/Continuous Collision Detection", &p.ContinuousCD ,0.0f, VxVar::COMPOSITIONBOUND, + "Enable/disable continuous collision detection (0.0f to disable)."); + + vm->Bind( + "Physic/Adaptive Force", &p.AdaptiveForce ,1.0f , VxVar::COMPOSITIONBOUND, + "Used to enable adaptive forces to accelerate convergence of the solver. "); + + + vm->Bind( + "Physic/Collision Veto Jointed", &p.CollVetoJointed , 1.0f , VxVar::COMPOSITIONBOUND, + "Controls default filtering for jointed bodies. True means collision is disabled."); + + vm->Bind( + "Physic/Trigger Trigger Callback", &p.TriggerTriggerCallback, 1.0f , VxVar::COMPOSITIONBOUND, + "Controls whether two touching triggers generate a callback or not."); + + + + vm->Bind( + "Physic/CCD Epsilon", &p.CCDEpsilon,0.01f, VxVar::COMPOSITIONBOUND, + "Distance epsilon for the CCD algorithm."); + + vm->Bind( + "Physic/Solver Convergence Threshold", &p.SolverConvergenceThreshold, 0.0f , VxVar::COMPOSITIONBOUND, + "Used to accelerate solver."); + + + + vm->Bind( + "Physic/BBox Noise Level", &p.BBoxNoiseLevel, 0.001f, VxVar::COMPOSITIONBOUND, + "Used to accelerate HW Broad Phase. "); + + vm->Bind( + "Physic/Implicit Sweep Cache Size", &p.ImplicitSweepCacheSize, 5.0f , VxVar::COMPOSITIONBOUND, + "Used to set the sweep cache size. "); + + vm->Bind( + "Physic/Default Sleep Energy", &p.DefaultSleepEnergy, 0.005f, VxVar::COMPOSITIONBOUND, + "The default sleep energy threshold. Objects with an energy below this threshold are allowed to go to sleep. Note: Only used when the pSDKP_BF_ENERGY_SLEEP_TEST flag is set."); + + vm->Bind( + "Physic/Constant Fluid Max Packets", &p.ConstantFluidMaxPackets, 925, VxVar::COMPOSITIONBOUND, + " Constant for the maximum number of packets per fluid. Used to compute the fluid packet buffer size in NxFluidPacketData."); + + vm->Bind( + "Physic/Constant Fluid Maximum Particles Per Step", &p.ConstantFluidMaxParticlesPerStep, 4096, VxVar::COMPOSITIONBOUND, + "Constant for the maximum number of new fluid particles per frame."); + + vm->Bind( + "Physic/Improved Spring Solver", &p.ImprovedSpringSolver,1.0f , VxVar::COMPOSITIONBOUND, + "Enable/disable improved spring solver for joints and wheel shapes."); + + vm->Bind( + "Physic/Disable Physics", &p.disablePhysics,false, VxVar::COMPOSITIONBOUND, + "Enable/disable physic calculation"); + + ////////////////////////////////////////////////////////////////////////// + pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); + + + vm->Bind( + "Physic Debugger/Host", &dbgSetup.mHost,XString("localhost"), VxVar::COMPOSITIONBOUND, + "Specifies the host running a debugger"); + + vm->Bind( + "Physic Debugger/Port", &dbgSetup.port,5425, VxVar::COMPOSITIONBOUND, + "Specifies the port of the remote debugger"); + + vm->Bind( + "Physic Debugger/Enabled", &dbgSetup.enabled,0, VxVar::COMPOSITIONBOUND, + "Enables/Disables the remote debugger"); + + vm->Bind( + "Physic Console Logger/Errors", &_LogErrors,0, VxVar::COMPOSITIONBOUND, + "Log Errors"); + + vm->Bind( + "Physic Console Logger/Infos", &_LogInfo,0, VxVar::COMPOSITIONBOUND, + "Log Infos"); + + vm->Bind( + "Physic Console Logger/Trace", &_LogTrace,0, VxVar::COMPOSITIONBOUND, + "Log Trace"); + + vm->Bind( + "Physic Console Logger/Warnings", &_LogWarnings,0, VxVar::COMPOSITIONBOUND, + "Log Warnings"); + + vm->Bind( + "Physic Console Logger/Console", &_LogWarnings,0, VxVar::COMPOSITIONBOUND, + "Console"); + + +} + +void PhysicManager::unBindVariables() +{ + + + CKVariableManager* vm = m_Context->GetVariableManager(); + if( !vm ) + return; + + pSDKParameters& p = getSDKParameters(); + + + vm->UnBind( "Physic Console Logger/Errors" ); + vm->UnBind( "Physic Console Logger/Infos" ); + vm->UnBind( "Physic Console Logger/Trace" ); + vm->UnBind( "Physic Console Logger/Warnings" ); + vm->UnBind( "Physic Console Logger/Console" ); + + + + vm->UnBind("Physic/Skin Width"); + vm->UnBind("Physic/Default Sleep Linear Velocity Squared"); + vm->UnBind( "Physic/Default Sleep Angular Velocity Squared "); + vm->UnBind( "Physic/Bounce Threshold"); + vm->UnBind( "Physic/Dynamic Friction Scaling"); + vm->UnBind( "Physic/Static Friction Scaling"); + vm->UnBind( "Physic/Maximum Angular Velocity"); + vm->UnBind( "Physic/Continuous Collision Detection"); + vm->UnBind( "Physic/Adaptive Force "); + vm->UnBind( "Physic/Collision Veto Jointed "); + vm->UnBind( "Physic/Trigger Trigger Callback"); + vm->UnBind( "Physic/CCD Epsilon"); + vm->UnBind( "Physic/Solver Convergence Threshold"); + vm->UnBind( "Physic/BBox Noise Level"); + vm->UnBind( "Physic/Implicit Sweep Cache Size"); + vm->UnBind( "Physic/Default Sleep Energy"); + vm->UnBind( "Physic/Constant Fluid Max Packets"); + vm->UnBind( "Physic/Constant Fluid Maximum Particles Per Step"); + vm->UnBind( "Physic/Improved Spring Solver" ); + vm->UnBind( "Physic/Disable Physics"); + + + + vm->UnBind( "Physic Debugger/Host" ); + vm->UnBind( "Physic Debugger/Port" ); + vm->UnBind( "Physic Debugger/Enabled" ); + +} + + + +#define PMANAGER_CHUNKID 1005 +#define PMANAGER_SAVE_VERSION 3 +#define PMANAGER_FLAGS 0 +#define PMANAGER_USER_ENUM_IDENTIFIER 11005 + +int PhysicManager::_migrateOldCustomStructures(CKScene *scnene) +{ + + bool bIsLoading = ctx()->IsInLoad(); + //CKObject* o = ctx->GetObject(ol[CKCID_MESH]); + int count = ctx()->GetObjectsCountByClassID(CKCID_3DOBJECT); + if (!count) + return 0; + + +// CK_ID* ol = ctx->GetObjectsListByClassID(i); + + XString errMessage; + int nbOfObjects = 0 ; + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(GetPAttribute()); + nbOfObjects = Array.Size(); + + if (nbOfObjects==0) + return 0; + + + + if (!scnene) + return 0; + + int attOld = GetPAttribute(); + int attNew = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + + int nbRecovered=0; + + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + int cCount = attman->GetAttributeListPtr(GetPAttribute()).Size(); + if (!cCount) + break; + + CK3dEntity*target = static_cast(*it); + if (!target)//shit happens + break; + + CKParameterOut * pOld =target->GetAttributeParameter(attOld); + if (!pOld)//shit happens + break; + + pObjectDescr * oDescr = pFactory::Instance()->createPObjectDescrFromParameter(pOld); + if (!oDescr)//shit happens + continue; + + + //---------------------------------------------------------------- + // + // fix up : + // + + //hierarchy + bool hierarchy =false; + if( (oDescr->flags & BF_Hierarchy) || oDescr->hirarchy ) + hierarchy = true; + + if (hierarchy) + oDescr->flags << BF_Hierarchy; + + + oDescr->massOffsetLinear = oDescr->massOffset; + oDescr->pivotOffsetLinear = oDescr->shapeOffset; + + //---------------------------------------------------------------- + // + // attach new attribute parameter + // + target->SetAttribute(attNew); + CKParameterOut *newPar = target->GetAttributeParameter(attNew); + if (newPar) + { + IParameter::Instance()->copyTo(newPar,oDescr); + } + + //---------------------------------------------------------------- + // + // clean old attribute + // + target->RemoveAttribute(attOld); + //---------------------------------------------------------------- + // + // set IC + // + + + //----- Restore the IC + if(target->IsInScene(scnene)) + { + CKStateChunk *chunk = scnene->GetObjectInitialValue(target); + if(chunk) + { + CKStateChunk *chunk = CKSaveObjectState(target); + scnene->SetObjectInitialValue(target,chunk); + } + } + + it = Array.Begin(); + + SAFE_DELETE(oDescr); + + nbRecovered++; + + //---------------------------------------------------------------- + // + // cleanup + // + + } + if (attman->GetAttributeListPtr(GetPAttribute()).Size() >0) + { + _migrateOldCustomStructures(GetContext()->GetCurrentScene()); + } + + /* + errMessage.Format("nub of old objects recovered: %d",nbRecovered); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMessage.Str()); + + */ + return nbOfObjects; + + +} + +CKERROR PhysicManager::PostLoad() +{ + CKScene *scene = GetContext()->GetCurrentScene(); + _migrateOldCustomStructures(scene); + + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Post Load"); + return true; +} + + +void PhysicManager::setPSDKParameters(pSDKParameters¶m) +{ + + if (!getPhysicsSDK()) + return ; + + getPhysicsSDK()->setParameter((NxParameter)pSDKP_SkinWidth,param.SkinWidth); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_DefaultSleepLinVelSquared,param.DefaultSleepLinVelSquared); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_DefaultSleepAngVelSquared,param.DefaultSleepAngVel_squared); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_BounceThreshold,param.BounceThreshold); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_DynFrictScaling,param.DynFrictScaling); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_StaFrictionScaling,param.StaFrictionScaling); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_MaxAngularVelocity,param.MaxAngularVelocity); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ContinuousCD,param.ContinuousCD); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_AdaptiveForce,param.AdaptiveForce); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_CollVetoJointed,param.CollVetoJointed); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_TriggerTriggerCallback,param.TriggerTriggerCallback); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_CCDEpsilon,param.CCDEpsilon); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_SolverConvergenceThreshold,param.SolverConvergenceThreshold); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_BBoxNoiseLevel,param.BBoxNoiseLevel); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ImplicitSweepCacheSize,param.ImplicitSweepCacheSize); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_DefaultSleepEnergy,param.DefaultSleepEnergy); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ConstantFluidMaxPackets,param.ConstantFluidMaxPackets); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ConstantFluidMaxParticlesPerStep,param.ConstantFluidMaxParticlesPerStep); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ImprovedSpringSolver,param.ImprovedSpringSolver); + + + + + +} + +CKStateChunk* PhysicManager::SaveData(CKFile* SavedFile) +{ + + if (!getNbObjects()) + { + return NULL; + } + + + CKStateChunk *chunk = CreateCKStateChunk(PMANAGER_CHUNKID, SavedFile); + if (!chunk) + return NULL; + chunk->StartWrite(); + chunk->WriteIdentifier(PMANAGER_CHUNKID); + chunk->WriteInt(PMANAGER_SAVE_VERSION); + chunk->WriteInt(PMANAGER_FLAGS); + + + CKVariableManager* vm = m_Context->GetVariableManager(); + if( !vm ) + return NULL; + + + pSDKParameters& p = getSDKParameters(); + + + CKVariableManager::Variable *var = vm->GetVariable("Physic/Skin Width"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.SkinWidth); + } + + var = vm->GetVariable("Physic/Default Sleep Linear Velocity Squared"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.DefaultSleepLinVelSquared); + } + + var = vm->GetVariable("Physic/Default Sleep Angular Velocity Squared"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.DefaultSleepAngVel_squared); + } + + + + var = vm->GetVariable("Physic/Bounce Threshold"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.BounceThreshold); + } + + + + var = vm->GetVariable("Physic/Dynamic Friction Scaling"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.DynFrictScaling); + } + + + + var = vm->GetVariable("Physic/Static Friction Scaling"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.StaFrictionScaling); + } + + var = vm->GetVariable("Physic/Maximum Angular Velocity"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.MaxAngularVelocity); + } + + var = vm->GetVariable("Physic/Continuous Collision Detection"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ContinuousCD); + } + + var = vm->GetVariable("Physic/Adaptive Force"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.AdaptiveForce); + } + + var = vm->GetVariable("Physic/Collision Veto Jointed"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.CollVetoJointed); + } + + var = vm->GetVariable("Physic/Trigger Trigger Callback"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.TriggerTriggerCallback); + } + + var = vm->GetVariable("Physic/CCD Epsilon"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.CCDEpsilon); + } + + var = vm->GetVariable("Physic/Solver Convergence Threshold"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.SolverConvergenceThreshold); + } + + var = vm->GetVariable("Physic/BBox Noise Level"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.BBoxNoiseLevel); + } + + var = vm->GetVariable("Physic/Implicit Sweep Cache Size"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ImplicitSweepCacheSize); + } + + + var = vm->GetVariable("Physic/Default Sleep Energy"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.DefaultSleepEnergy); + } + + + + + var = vm->GetVariable("Physic/Constant Fluid Max Packets"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ConstantFluidMaxPackets); + } + + + + var = vm->GetVariable("Physic/Constant Fluid Maximum Particles Per Step"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ConstantFluidMaxParticlesPerStep); + } + + + + + var = vm->GetVariable("Physic/Improved Spring Solver"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ImprovedSpringSolver); + } + + ////////////////////////////////////////////////////////////////////////// + + pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); + + var = vm->GetVariable("Physic Debugger/Host"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteString(dbgSetup.mHost.CStr()); + } + + var = vm->GetVariable("Physic Debugger/Port"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(dbgSetup.port); + } + + var = vm->GetVariable("Physic Debugger/Enabled"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(dbgSetup.enabled); + } + + + + var = vm->GetVariable("Physic Console Logger/Errors"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogErrors); + } + + var = vm->GetVariable("Physic Console Logger/Infos"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogInfo); + } + + var = vm->GetVariable("Physic Console Logger/Trace"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogTrace); + } + + var = vm->GetVariable("Physic Console Logger/Warnings"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogWarnings); + } + + + _saveUserEnumeration(chunk,SavedFile); + + var = vm->GetVariable("Physic Console Logger/Console"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogToConsole); + } + + + //**new + + var = vm->GetVariable("Physic/Disable Physics"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(p.disablePhysics); + } + + chunk->CloseChunk(); + return chunk; +} + +CKERROR PhysicManager::LoadData(CKStateChunk *chunk,CKFile* LoadedFile) +{ + + + assert(LoadedFile != 0); + if (!chunk) + return CKERR_INVALIDPARAMETER; + + + chunk->StartRead(); + + if (chunk->SeekIdentifier(PMANAGER_CHUNKID)) + { + + // Check the version + int version = chunk->ReadInt(); + + // Check the flags + int flags = chunk->ReadInt(); + + CKVariableManager* vm = m_Context->GetVariableManager(); + if( !vm ) + return NULL; + + + pSDKParameters& p = getSDKParameters(); + + + ////////////////////////////////////////////////////////////////////////// + int isInCMO = chunk->ReadInt(); + float v = chunk->ReadFloat(); + + if (isInCMO) + { + p.SkinWidth = v; + } + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.DefaultSleepLinVelSquared = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.DefaultSleepAngVel_squared = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.BounceThreshold = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.DynFrictScaling = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.StaFrictionScaling = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.MaxAngularVelocity = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ContinuousCD = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.AdaptiveForce = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.CollVetoJointed = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.TriggerTriggerCallback = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.CCDEpsilon = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.SolverConvergenceThreshold = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.BBoxNoiseLevel = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ImplicitSweepCacheSize = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.DefaultSleepEnergy = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ConstantFluidMaxPackets = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ConstantFluidMaxParticlesPerStep = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ImprovedSpringSolver = v; + } + + + ////////////////////////////////////////////////////////////////////////// + pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); + + isInCMO = chunk->ReadInt(); + XString host = chunk->ReadString(); + if (isInCMO) + { + dbgSetup.mHost = host; + } + + + isInCMO = chunk->ReadInt(); + int port = chunk->ReadInt(); + + if (isInCMO) + { + dbgSetup.port= port; + } + + isInCMO = chunk->ReadInt(); + int enabled = chunk->ReadInt(); + + if (isInCMO) + { + dbgSetup.enabled= enabled; + } + + + + ////////////////////////////////////////////////////////////////////////// + + isInCMO = chunk->ReadInt(); + int val = chunk->ReadInt(); + if (isInCMO==1 && val >=-1000 ) + { + _LogErrors=val; + } + if (isInCMO==0) + { + _LogErrors=1; + } + + isInCMO = chunk->ReadInt(); + val = chunk->ReadInt(); + if (isInCMO==1 && val >=-1000 ) + { + _LogInfo=val; + } + + isInCMO = chunk->ReadInt(); + val = chunk->ReadInt(); + if (isInCMO==1&& val >=-1000) + { + _LogTrace=val; + } + + isInCMO = chunk->ReadInt(); + val = chunk->ReadInt(); + if (isInCMO==1&& val >=-1000 ) + { + _LogWarnings=val; + } + + _loadUserEnumeration(chunk,LoadedFile); + + isInCMO = chunk->ReadInt(); + val = chunk->ReadInt(); + if (isInCMO==1&& val >=-1000 ) + { + _LogToConsole=val; + } + + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.disablePhysics = v; + } + + chunk->CloseChunk(); + + //disable physics + + + } + return CK_OK; +} + + + +void PhysicManager::_saveUserEnumeration(CKStateChunk *chunk,CKFile* SavedFile) +{ + ////////////////////////////////////////////////////////////////////////// + //write a identifier, just to ensure due the load we are at right seek point ! + + chunk->WriteInt(PMANAGER_USER_ENUM_IDENTIFIER); + + /////////////////////////////////////////////////////////////////////////// + //write out the the user enumeration for pWDominanceGroups + XString enumDescription = getEnumDescription(m_Context->GetParameterManager(),VTE_PHYSIC_DOMINANCE_GROUP); + XString enumDescriptionCollGroup = getEnumDescription(m_Context->GetParameterManager(),VTE_PHYSIC_BODY_COLL_GROUP); + + XString errString; + errString.Format("Writing dominance enum :%s",enumDescription.Str()); + + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.CStr()); + + chunk->WriteString(enumDescription.CStr()); + chunk->WriteString(enumDescriptionCollGroup.CStr()); + +} + +void PhysicManager::_loadUserEnumeration(CKStateChunk *chunk,CKFile* LoadedFile) +{ + + int enumIdentfier = chunk->ReadInt(); + + if (enumIdentfier!=PMANAGER_USER_ENUM_IDENTIFIER) return; + + CKParameterManager *pm = m_Context->GetParameterManager(); + ////////////////////////////////////////////////////////////////////////// + //we read our dominance group enumeration back : + + XString dominanceGroupEnumerationString; + int strEnumDescSizeDG = chunk->ReadString(dominanceGroupEnumerationString); + + XString collisionGroupEnumerationString; + int strEnumDescSizeCG = chunk->ReadString(collisionGroupEnumerationString); + + XString errString; + errString.Format("Loading dominance enum :%s",dominanceGroupEnumerationString.Str()); + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,dominanceGroupEnumerationString.CStr()); + + CKParameterType pType = pm->ParameterGuidToType(VTE_PHYSIC_DOMINANCE_GROUP); + if (pType!=-1 && dominanceGroupEnumerationString.Length()) + { + pm->ChangeEnumDeclaration(VTE_PHYSIC_DOMINANCE_GROUP,dominanceGroupEnumerationString.Str()); + } + + //---------------------------------------------------------------- + // + // collision group + // + pType = pm->ParameterGuidToType(VTE_PHYSIC_BODY_COLL_GROUP); + if (pType!=-1 && collisionGroupEnumerationString.Length()) + { + XString enumDescriptionCollGroup = getEnumDescription(m_Context->GetParameterManager(),VTE_PHYSIC_BODY_COLL_GROUP); + + pm->ChangeEnumDeclaration(VTE_PHYSIC_BODY_COLL_GROUP,collisionGroupEnumerationString.Str()); + + //---------------------------------------------------------------- + // + // + // + CKEnumStruct *eStruct = pm->GetEnumDescByType(pType); + if (eStruct) + { + int a = eStruct->GetNumEnums(); + if (a) + { + XString enumString = eStruct->GetEnumDescription(0); + if (!enumString.Length()) + { + pm->ChangeEnumDeclaration(VTE_PHYSIC_BODY_COLL_GROUP,enumDescriptionCollGroup.Str()); + } + } + int ab = eStruct->GetNumEnums(); + + } + + } + + +} +CKERROR PhysicManager::PostSave() +{ + + return CK_OK; +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerDongle.cpp b/usr/Src/Core/Manager/PhysicManagerDongle.cpp new file mode 100644 index 0000000..88e8f88 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerDongle.cpp @@ -0,0 +1,328 @@ +#include +#include "vtPhysXAll.h" + +#include "pConfig.h" + +#ifdef DONGLE_VERSION + + #include "matrix32.h" + +#endif + + +long DataIn[256]; /* Buffer to read the Dongle data */ +long DataOut[256]; /* Buffer for data to be stored */ +long DataBlock[2]; /* Data buffer for Encrypt/Decrypt */ +short RetCode; /* Return value */ +long API_Version; /* Version number of the Matrix-API */ +long DNG_Version; /* Dongle version number */ +short DNG_LPTADR; /* Adress of LPT port */ +short DNG_Count; /* Number of Dongles connected */ +short DNG_Mem; /* Memory size of Dongle */ +short DNG_MaxVar; /* Maximum number of data fields */ +short AppSlot; /* Application-Slot for Network access */ +short i; + + + +int netMode = 0; +short DNG_Port = 1; +long UserCode = 4002529; + +int DONGLE_BASIC_VERSION_KEY_1 = 28071977; +int DONGLE_BASIC_VERSION_KEY_2 = 77917082; + +int DONGLE_BASIC_VERSION_KEY_1_ENC = 364898188; +int DONGLE_BASIC_VERSION_KEY_2_ENC = 930141357; + + + +int DONGLE_ADVANCED_VERSION_KEY1 = 56143954; +int DONGLE_ADVANCED_VERSION_KEY2 = 45934165; + + +extern PhysicManager*manager; + + +#ifdef DONGLE_VERSION + + +#pragma comment(lib,"matrix32.lib") + + + +void PhysicManager::_initResources(int flags){ + + + + // Init Matrix-API + RetCode = Init_MatrixAPI(); + if(RetCode < 0) + { + printf("Init_MatrixAPI failed %d \n", RetCode); + exit; + } + + API_Version = GetVersionAPI(); + if(API_Version == 0) + { + printf("Cannot read API-Version! \n"); + Release_MatrixAPI(); + return; + } + + // Search for number of Dongles at DNG_Port + DNG_Port = Dongle_Find(); + DNG_Count = Dongle_Count(DNG_Port); + + long test = 0 ; + if(DNG_Count > 0) + { + //manager->m_Context->OutputToConsoleEx("Matrix-Modules at Port %d: %d \n", DNG_Port, DNG_Count); + } + else + { + XString donglePath = _getConfigPath(); + + //manager->m_Context->OutputToConsoleEx("Cannot find Matrix-Modules at Port %d ! \n", DNG_Port); + + //return; + //goto NETWORK_CHECK; + + int ret = SetConfig_MatrixNet(1,donglePath.Str()); + int DNG_NR = 1; + AppSlot = 1; + ret = LogIn_MatrixNet(UserCode, AppSlot, DNG_NR); + if (ret<=0) + { + MessageBox(NULL,"Couldn't find Dongle!",0,MB_OK|MB_ICONERROR); + this->DongleHasBasicVersion=0; + this->DongleHasAdvancedVersion=0; + //Release_MatrixAPI(); + return; + } + + + netMode = 1; + DNG_Port = Dongle_Find(); + DNG_Count = Dongle_Count(DNG_Port); + + if(DNG_Count == 0) + { + manager->m_Context->OutputToConsoleEx("Couldn't find Dongle"); + } + + } + + + DNG_Mem = Dongle_MemSize(DNG_Count, DNG_Port); + if(DNG_Mem > 0) + { + //manager->m_Context->OutputToConsoleEx("MemSize of Matrix-Module %d at Port %d: %d Bytes \n", DNG_Count, DNG_Port, DNG_Mem); + + } + else + { + //manager->m_Context->OutputToConsoleEx("Cannot read MemSize! \n"); + Release_MatrixAPI(); + return; + } + + RetCode = Dongle_ReadData(UserCode, DataIn,6, DNG_Count, DNG_Port); + if(RetCode < 0) + { + m_Context->OutputToConsoleEx("Data Read-Error! \n"); + Release_MatrixAPI(); + return; + } + + + DataBlock[0] = 28071977; /* Clear Data */ + DataBlock[1] = 77917082; /* Clear Data */ + + + long DataBlockKeyBasic[2]; + DataBlockKeyBasic[0] = DataIn[2]; + DataBlockKeyBasic[1] = DataIn[3]; + + long DataBlockKeyAdvanced[2]; + DataBlockKeyAdvanced[0] = DataIn[4]; + DataBlockKeyAdvanced[1] = DataIn[5]; + + RetCode = Dongle_DecryptData(UserCode, DataBlockKeyBasic, DNG_Count, DNG_Port); + RetCode = Dongle_DecryptData(UserCode, DataBlockKeyAdvanced, DNG_Count, DNG_Port); + + + + + if (netMode) + { + + if (DataBlockKeyBasic[0]==DONGLE_BASIC_VERSION_KEY_1_ENC && DataBlockKeyBasic[1]==DONGLE_BASIC_VERSION_KEY_2_ENC ) + { + DongleHasBasicVersion= 1; + } + + }else + { + if (DataBlockKeyBasic[0]==DONGLE_BASIC_VERSION_KEY_1 && DataBlockKeyBasic[1]==DONGLE_BASIC_VERSION_KEY_2 ) + { + DongleHasBasicVersion= 1; + } + + if (DataBlockKeyAdvanced[0]==DONGLE_ADVANCED_VERSION_KEY1 && DataBlockKeyAdvanced[1]==DONGLE_ADVANCED_VERSION_KEY2) + { + DongleHasAdvancedVersion=1; + } + } + + Release_MatrixAPI(); + + +} + +#endif + + + +/* +#ifdef REDIST +#endif +*/ + +/* +#ifdef DEMO_ONLY + + void FindResourceX() + { + + } + +#endif +*/ + + + +/* +#if defined (DONGLE_VERSION) + + +void PhysicManager::makeDongleTest() +{ + //FindResourceX(); + +} +*/ + + + +/* + +void MODULE_API FindResourceX() +{ + + + RetCode = Init_MatrixAPI(); + if(RetCode < 0) + { + printf("Init_MatrixAPI failed %d \n", RetCode); + exit; + } + + + API_Version = GetVersionAPI(); + if(API_Version == 0) + { + printf("Cannot read API-Version! \n"); + Release_MatrixAPI(); + return; + } + else + { + // printf("Version of Matrix-API: %d.%d \n", HIWORD(API_Version), LOWORD(API_Version)); + // manager->m_Context->OutputToConsoleEx("Version of Matrix-API: %d.%d \n", HIWORD(API_Version), LOWORD(API_Version)); + } + + + int port = Dongle_Find(); + DNG_Count = Dongle_Count(port); + DNG_Port = port; + + if(DNG_Count > 0) + { + //manager->m_Context->OutputToConsoleEx("Matrix-Modules at Port %d: %d \n", DNG_Port, DNG_Count); + } + else + { + //goto NETWORK + //manager->m_Context->OutputToConsoleEx("Cannot find Matrix-Modules at Port %d ! \n", DNG_Port); + Release_MatrixAPI(); + return; + } + + DNG_Mem = Dongle_MemSize(DNG_Count, DNG_Port); + if(DNG_Mem > 0) + { + + //manager->m_Context->OutputToConsoleEx("MemSize of Matrix-Module %d at Port %d: %d Bytes \n", DNG_Count, DNG_Port, DNG_Mem); + + } + else + { + //manager->m_Context->OutputToConsoleEx("Cannot read MemSize! \n"); + Release_MatrixAPI(); + return; + } + + RetCode = Dongle_ReadData(UserCode, DataIn,6, DNG_Count, DNG_Port); + if(RetCode < 0) + { + manager->m_Context->OutputToConsoleEx("Data Read-Error! \n"); + Release_MatrixAPI(); + return; + } + + + + DataBlock[0] = 28071977; + DataBlock[1] = 77917082; + + + + long DataBlockKeyBasic[2]; + DataBlockKeyBasic[0] = DataIn[2]; + DataBlockKeyBasic[1] = DataIn[3]; + + long DataBlockKeyAdvanced[2]; + DataBlockKeyAdvanced[0] = DataIn[4]; + DataBlockKeyAdvanced[1] = DataIn[5]; + + RetCode = Dongle_DecryptData(UserCode, DataBlockKeyBasic, DNG_Count, DNG_Port); + RetCode = Dongle_DecryptData(UserCode, DataBlockKeyAdvanced, DNG_Count, DNG_Port); + + //manager->m_Context->OutputToConsoleEx("Decrypted Data: %lu %lu \n", DataBlockKeyBasic[0], DataBlockKeyBasic[1]); + //manager->m_Context->OutputToConsoleEx("Decrypted Data: %lu %lu \n", DataBlockKeyAdvanced[0], DataBlockKeyAdvanced[1]); + + + if (DataBlockKeyBasic[0]==DONGLE_BASIC_VERSION_KEY_1 && DataBlockKeyBasic[1]==DONGLE_BASIC_VERSION_KEY_2 ) + { +// DongleHasBasicVersion= 1; + } + + if (DataBlockKeyAdvanced[0]==DONGLE_ADVANCED_VERSION_KEY1 && DataBlockKeyAdvanced[1]==DONGLE_ADVANCED_VERSION_KEY2) + { +// DongleHasAdvancedVersion= 1; + } + + //manager->m_Context->OutputToConsoleEx("Clear Data: %lu %lu \n", DataBlock[0], DataBlock[1]); + //manager->m_Context->OutputToConsoleEx("Encrypted Data: %lu %lu \n", DataBlock[0], DataBlock[1]); + + + Release_MatrixAPI(); +} + + + +#endif + +*/ \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerFluids.cpp b/usr/Src/Core/Manager/PhysicManagerFluids.cpp new file mode 100644 index 0000000..7b6fa00 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerFluids.cpp @@ -0,0 +1,159 @@ +#include +#include "vtPhysXAll.h" + +#include "VSLManagerSDK.h" + + +#ifdef HAS_FLUID + +void __newpFluidDescr(BYTE *iAdd) +{ + new(iAdd)pFluidDesc(); +} + +void __newpFluidEmitterDesc(BYTE *iAdd) +{ + new(iAdd)pFluidEmitterDesc(); +} + +void PhysicManager::_RegisterFluid_VSL() +{ + + + STARTVSLBIND(m_Context) + + + + /************************************************************************/ + /* pFluidFlags */ + /************************************************************************/ + + DECLAREENUM("pFluidFlag") + DECLAREENUMVALUE("pFluidFlag", "PFF_DisableGravity" , 2) + DECLAREENUMVALUE("pFluidFlag", "PFF_CollisionTwoway" , 4) + DECLAREENUMVALUE("pFluidFlag", "PFF_Enabled" , 8) + DECLAREENUMVALUE("pFluidFlag", "PFF_Hardware" , 16) + DECLAREENUMVALUE("pFluidFlag", "PFF_PriorityMode" , 32) + DECLAREENUMVALUE("pFluidFlag", "PFF_ProjectToPlane" , 64) + + DECLAREENUM("pFluidSimulationMethod") + DECLAREENUMVALUE("pFluidSimulationMethod", "PFS_SPH" , 1) + DECLAREENUMVALUE("pFluidSimulationMethod", "PFS_NoParticleInteraction" , 2) + DECLAREENUMVALUE("pFluidSimulationMethod", "PFS_MixedMode" , 4) + + DECLAREENUM("pFluidCollisionMethod") + DECLAREENUMVALUE("pFluidCollisionMethod", "PFCM_Static" , 1) + DECLAREENUMVALUE("pFluidCollisionMethod", "PFCM_Dynamic" , 2) + + + + DECLAREOBJECTTYPE(pFluidDesc) + DECLARECTOR_0(__newpFluidDescr) + DECLAREMEMBER(pFluidDesc,int,maxParticles) + DECLAREMEMBER(pFluidDesc,float,attractionForDynamicShapes) + DECLAREMEMBER(pFluidDesc,float,attractionForStaticShapes) + DECLAREMEMBER(pFluidDesc,float,collisionDistanceMultiplier) + DECLAREMEMBER(pFluidDesc,int,collisionGroup) + DECLAREMEMBER(pFluidDesc,pFluidCollisionMethod,collisionMethod) + DECLAREMEMBER(pFluidDesc,float,collisionResponseCoefficient) + DECLAREMEMBER(pFluidDesc,float,damping) + DECLAREMEMBER(pFluidDesc,float,dynamicFrictionForDynamicShapes) + DECLAREMEMBER(pFluidDesc,float,dynamicFrictionForStaticShapes) + DECLAREMEMBER(pFluidDesc,VxVector,externalAcceleration) + DECLAREMEMBER(pFluidDesc,float,fadeInTime) + DECLAREMEMBER(pFluidDesc,float,kernelRadiusMultiplier) + DECLAREMEMBER(pFluidDesc,float,packetSizeMultiplier) + DECLAREMEMBER(pFluidDesc,int,maxParticles) + DECLAREMEMBER(pFluidDesc,float,motionLimitMultiplier) + DECLAREMEMBER(pFluidDesc,int,numReserveParticles) + DECLAREMEMBER(pFluidDesc,int,packetSizeMultiplier) + DECLAREMEMBER(pFluidDesc,float,restitutionForDynamicShapes) + DECLAREMEMBER(pFluidDesc,float,restitutionForStaticShapes) + DECLAREMEMBER(pFluidDesc,float,restParticlesPerMeter) + DECLAREMEMBER(pFluidDesc,float,restDensity) + DECLAREMEMBER(pFluidDesc,pFluidSimulationMethod,simulationMethod) + DECLAREMEMBER(pFluidDesc,float,staticFrictionForDynamicShapes) + DECLAREMEMBER(pFluidDesc,float,staticFrictionForStaticShapes) + DECLAREMEMBER(pFluidDesc,float,stiffness) + DECLAREMEMBER(pFluidDesc,float,surfaceTension) + DECLAREMEMBER(pFluidDesc,float,viscosity) + DECLAREMEMBER(pFluidDesc,pFluidFlag,flags) + DECLAREMEMBER(pFluidDesc,CK_ID,worldReference) + + + DECLAREMETHOD_0(pFluidDesc,void,setToDefault) + DECLAREMETHOD_0(pFluidDesc,bool,isValid) + + + /************************************************************************/ + /* emitter */ + /************************************************************************/ + + + ////////////////////////////////////////////////////////////////////////// + // + // emitter flags : + // + DECLAREENUM("pFluidEmitterFlag") + DECLAREENUMVALUE("pFluidEmitterFlag", "PFEF_ForceOnBody" , 4) + DECLAREENUMVALUE("pFluidEmitterFlag", "PFEF_AddBodyVelocity" , 8) + DECLAREENUMVALUE("pFluidEmitterFlag", "PFEF_Enabled" , 16) + + DECLAREENUM("pEmitterShape") + DECLAREENUMVALUE("pEmitterShape", "PFES_Rectangular" , 1) + DECLAREENUMVALUE("pEmitterShape", "PFES_Ellipse" , 2) + + DECLAREENUM("pEmitterType") + DECLAREENUMVALUE("pEmitterType", "PFET_ConstantPressure" , 1) + DECLAREENUMVALUE("pEmitterType", "PFET_ConstantFlowRate" , 2) + + + ////////////////////////////////////////////////////////////////////////// + // + // emitter descr : + // + + DECLAREOBJECTTYPE(pFluidEmitterDesc) + DECLARECTOR_0(__newpFluidEmitterDesc) + DECLAREMEMBER(pFluidEmitterDesc,CK3dEntity*,frameShape) + DECLAREMEMBER(pFluidEmitterDesc,pEmitterType,type) + DECLAREMEMBER(pFluidEmitterDesc,int,maxParticles) + DECLAREMEMBER(pFluidEmitterDesc,pEmitterShape,shape) + DECLAREMEMBER(pFluidEmitterDesc,float,dimensionX) + DECLAREMEMBER(pFluidEmitterDesc,float,dimensionY) + DECLAREMEMBER(pFluidEmitterDesc,VxVector,randomPos) + DECLAREMEMBER(pFluidEmitterDesc,float,randomAngle) + DECLAREMEMBER(pFluidEmitterDesc,float,fluidVelocityMagnitude) + DECLAREMEMBER(pFluidEmitterDesc,float,rate) + DECLAREMEMBER(pFluidEmitterDesc,float,randomAngle) + DECLAREMEMBER(pFluidEmitterDesc,float,particleLifetime) + DECLAREMEMBER(pFluidEmitterDesc,float,repulsionCoefficient) + DECLAREMEMBER(pFluidEmitterDesc,pFluidEmitterFlag,flags) + DECLAREMETHOD_0(pFluidEmitterDesc,void,setToDefault) + DECLAREMETHOD_0(pFluidEmitterDesc,bool,isValid) + DECLAREMEMBER(pFluidEmitterDesc,CK_ID,entityReference) + + + + DECLAREPOINTERTYPE(pFluidEmitter) + + /************************************************************************/ + /* fluid */ + /************************************************************************/ + + DECLAREPOINTERTYPE(pFluid) + DECLAREMETHOD_0(pFluid,CK3dEntity*,getParticleObject) + + DECLAREMETHOD_2(pFactory,pFluid*,createFluid,CK3dEntity*,pFluidDesc) + + DECLAREMETHOD_1(pFluid,pFluidEmitter*,createEmitter,const pFluidEmitterDesc&) + + + + STOPVSLBIND + + + +} + +#endif // HAS_FLUID \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerHookVirtoolsGenericBBs.cpp b/usr/Src/Core/Manager/PhysicManagerHookVirtoolsGenericBBs.cpp new file mode 100644 index 0000000..1fc72dc --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerHookVirtoolsGenericBBs.cpp @@ -0,0 +1,192 @@ +#include +#include "vtPhysXAll.h" +#include "IParameter.h" + + +#define BB_OBJECT_COPY CKGUID(0x3f6b0ac7,0x47d20f78) +#define BB_OBJECT_DELETE CKGUID(0x74120ded,0x76524673) + +enum BB_COPY_SETTINGS +{ + + bbS_Dynamic, + bbS_Awak, + bbs_Flags, + bbs_NewBodyFlags, + +}; + +CKBEHAVIORFCT BBCopy; +int BB_CopyNew(const CKBehaviorContext& context) +{ + + + CKBehavior *beh = context.Behavior; + CKContext *ctx = context.Context; + + BBCopy(context); + + // Copy Objects + int count = beh->GetInputParameterCount(); + + // Dynamic ? + BOOL dynamic = TRUE; + beh->GetLocalParameterValue(0,&dynamic); + + int flags = 0; + beh->GetLocalParameterValue(bbs_Flags,&flags); + + int newBodyFlags = 0; + beh->GetLocalParameterValue(bbs_NewBodyFlags,&newBodyFlags); + + CKDependencies* dep = *(CKDependencies**)beh->GetInputParameterReadDataPtr(0); + + + XArraySrcObjects; + + int i; + for(i=1;iGetInputParameterObject(i); + if (!srcObject) continue; + + // we do not want to to duplicate level + if (CKIsChildClassOf(srcObject,CKCID_LEVEL)) continue; + + if (CKIsChildClassOf(srcObject,CKCID_3DENTITY)) + { + + + CK3dEntity *src=(CK3dEntity*)srcObject; + CK3dEntity *dst=(CK3dEntity*)(beh->GetOutputParameterObject(i-1)); + + pObjectDescr oDescr; + IParameter::Instance()->copyTo(oDescr,src,flags); + + + //---------------------------------------------------------------- + // + // IC Data, we just save it out + // + if ( flags & PB_CF_COPY_IC ) + { + CKScene *scene = ctx()->GetCurrentScene(); + if(scene && src->IsInScene(scene)) + { + CKStateChunk *chunk = scene->GetObjectInitialValue(src); + if(chunk) + { + + CKStateChunk *chunkClone=CreateCKStateChunk(CKCID_OBJECT); + chunkClone->Clone(chunk); + + //---------------------------------------------------------------- + // + // copy and restore IC of parent object + // + if(chunkClone) + { + scene->SetObjectInitialValue(dst,chunkClone); + } + + CKERROR error = 0; + if ( flags & PB_CF_RESTORE_IC ) + { + error = CKReadObjectState(dst,chunkClone); + } + + //---------------------------------------------------------------- + // + // copy and restore IC for children : + // + int a = ((*dep->At(CKCID_3DENTITY)) & CK_DEPENDENCIES_COPY_3DENTITY_CHILDREN); + int a1 = (( flags & PB_CF_OVRRIDE_BODY_FLAGS ) && (newBodyFlags & BF_Hierarchy)); + int a2 = ( oDescr.flags & BF_Hierarchy); + + if ( ((*dep->At(CKCID_3DENTITY)) & CK_DEPENDENCIES_COPY_3DENTITY_CHILDREN) && + ( (( flags & PB_CF_OVRRIDE_BODY_FLAGS ) && (newBodyFlags & BF_Hierarchy)) || + ( oDescr.flags & BF_Hierarchy) ) + ) + { + CK3dEntity* subEntity = NULL; + SrcObjects.Clear(); + + while (subEntity= dst->HierarchyParser(subEntity) ) + { + SrcObjects.PushBack(subEntity); + } + int dCount = dst->GetChildrenCount(); + int dCount2 = SrcObjects.Size(); + + for(i = 0;iGetObjectInitialValue(orginalObject); + if (chunkSub) + { + CKStateChunk *chunkCloneSub=CreateCKStateChunk(CKCID_OBJECT); + chunkCloneSub->Clone(chunkSub); + scene->SetObjectInitialValue(subEntity,chunkCloneSub); + if ( flags & PB_CF_RESTORE_IC ) + { + CKReadObjectState(subEntity,chunkCloneSub); + subEntity->SetParent(dst); + } + } + } + + } + } + } + } + } + pRigidBody *srcBody = GetPMan()->getBody((CK3dEntity*)src); + NxShape *shape = NULL; + if (srcBody) + { + shape = srcBody->getSubShape((CK3dEntity*)src); + } + //---------------------------------------------------------------- + // + // copy sub shape ? + // + if (shape && shape!=srcBody->getMainShape()) + { + pFactory::Instance()->cloneShape((CK3dEntity*)src,(CK3dEntity*)(beh->GetOutputParameterObject(i-1)),srcBody->GetVT3DObject(),flags,newBodyFlags); + continue; + } + + //---------------------------------------------------------------- + // + // copy body ? + // + if (srcBody) + pFactory::Instance()->cloneRigidBody(src,dst,dep,flags,newBodyFlags); + } + } + return CK_OK; +} +/************************************************************************/ +/* */ +/************************************************************************/ +CKERROR +PhysicManager::_HookGenericBBs() +{ + CKBehaviorManager *bm = m_Context->GetBehaviorManager(); + + CKBehaviorPrototype *bproto = CKGetPrototypeFromGuid(BB_OBJECT_COPY); + if(bproto) + { + bproto->DeclareSetting("Copy Flags",VTF_PHYSIC_ACTOR_COPY_FLAGS,""); + bproto->DeclareSetting("New Body Flags",VTF_BODY_FLAGS,""); + + BBCopy = bproto->GetFunction(); + bproto->SetFunction(BB_CopyNew); + } + + return CK_OK; +} diff --git a/usr/Src/Core/Manager/PhysicManagerInit.cpp b/usr/Src/Core/Manager/PhysicManagerInit.cpp new file mode 100644 index 0000000..9fce991 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerInit.cpp @@ -0,0 +1,362 @@ +#include +#include "vtPhysXAll.h" +#include "pWorldSettings.h" +#include "pLogger.h" +#include "pConfig.h" + +#include "UserAllocator.h" +#include "NxControllerManager.h" +#include "xTime.h" +#include "pVehicleAll.h" +/* +class myLogConsumer : public xLogConsumer +{ + +public: + myLogConsumer() : xLogConsumer() + { + + } + + void logString(const char *string); +}; + +void myLogConsumer::logString(const char *string) +{ + xLogConsumer::logString(string); + + int test = 2; + test++; + + +} + +myLogConsumer pLogConsumer; +*/ + +#include + +int PhysicManager::initManager(int flags/* =0 */) +{ + xBitSet inFlags = flags; + xBitSet resultFlags = 0; + + + + setProcessOptions(pVPO_CheckLowSpeed|pVPO_Lat_Damping|pVPO_Long_Damping|pVPO_SA_Damping|pVPO_Wheel_UsePHYSX_CONTACT_DATA|pVPO_Wheel_UsePHYSX_Load|pVPO_SV_Tansa); + + + + xAssertionEx::Instance(); + customizeAsserts(); + + ////////////////////////////////////////Load our physic default xml document : + if (isFlagOn(inFlags,E_MFI_LOAD_CONFIG) && getDefaultConfig()) + { + delete m_DefaultDocument; + m_DefaultDocument = NULL; + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted old default config"); + } + + if (isFlagOn(inFlags,E_MFI_LOAD_CONFIG)) + { + TiXmlDocument * defaultDoc = loadDefaults("PhysicDefaults.xml"); + if (!defaultDoc) + { + //enableFlag(resultFlags,E_MF_LOADING_DEFAULT_CONFIG_FAILED); + enableFlag(_getManagerFlags(),E_MF_LOADING_DEFAULT_CONFIG_FAILED); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config :PhysicDefaults.xml: failed"); + setDefaultConfig(NULL); + }else + { + setDefaultConfig(defaultDoc); + } + + } + + ////////////////////////////////////////////////////////////////////////////factory : + if (isFlagOn(inFlags,E_MFI_CREATE_FACTORY)) + { + if (getCurrentFactory()) + { + + getCurrentFactory()->setPhysicSDK(getPhysicsSDK()); + enableFlag(_getManagerFlags(),E_MF_FACTORY_CREATED); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Old factory updated"); + } + if (!getCurrentFactory()) + { + + pFactory *factory = new pFactory(this,getDefaultConfig()); + factory->setPhysicSDK(getPhysicsSDK()); + enableFlag(_getManagerFlags(),E_MF_FACTORY_CREATED); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"New factory created"); + setCurrentFactory(factory); + } + } + + if (getDefaultWorldSettings()) + { + SAFE_DELETE(mDefaultWorldSettings); + } + + ////////////////////////////////////////////////////////////////////////// + //world settings : + pWorldSettings *wSettings = pFactory::Instance()->createWorldSettings(XString("Default"),getDefaultConfig()); + if (!wSettings) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Couldn't load default world settings!"); + wSettings = new pWorldSettings(); + } + + setDefaultWorldSettings(wSettings); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Default world settings created"); + + + //////////////////////////////////////////default world : + if (isFlagOn(_getManagerFlags(),E_MF_FACTORY_CREATED) && + getDefaultWorldSettings() ) + { + if (pFactory::Instance()->createDefaultWorld("pDefaultWorld")) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Default world created"); + } + //else xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Creating default world failed"); + } + _RegisterDynamicParameters(); + + int mask = resultFlags.getMask(); + + //---------------------------------------------------------------- + // + // character controllers + // + mUserAllocator = new UserAllocator(); + _createControllerManager(); + + return mask; + + +} +void PhysicManager::_createControllerManager() +{ + + mControllerManager = NxCreateControllerManager(mUserAllocator); + +} + +int PhysicManager::initPhysicEngine(int flags /* = 0 */) +{ + + if (getPhysicsSDK()) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Physic SDK already initiated! Releasing old SDK "); + NxReleasePhysicsSDK(getPhysicsSDK()); + setPhysicsSDK(NULL); + } + + NxPhysicsSDKDesc desc; + NxSDKCreateError errorCode = NXCE_NO_ERROR; +//NxSDKCreationFlag + //NxSDKCreationFlag +// NX_SIMULATION_SW + pErrorStream* eStream = getLogger()->getErrorStream(); + mPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL,(NxUserOutputStream*)eStream, desc, &errorCode); + if(mPhysicsSDK == NULL) + { + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_AGEIA,"Physic SDK already initiated! Releasing old SDK "); + enableFlag(_getManagerFlags(),E_MF_PSDK_FAILED); + return E_PE_AGEIA_ERROR; + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Physic SDK initiated!"); + + if (getDefaultConfig()) + { + pRemoteDebuggerSettings rSettings = pFactory::Instance()->createDebuggerSettings(getDefaultConfig()); + + if (rSettings.enabled) + { + mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(rSettings.mHost.CStr(),rSettings.port); + + if (!mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"couldn't connect to remote debugger !"); + }else + { + + mRemoteDebugger = mPhysicsSDK->getFoundationSDK().getRemoteDebugger(); + + } + } + } + + + /*mPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1); + mPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); + mPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1); + mPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1); +*/ + + setPSDKParameters(getSDKParameters()); + + pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); + if (dbgSetup.enabled) + { + + mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(dbgSetup.mHost.CStr(),dbgSetup.port); + if (!mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"couldn't connect to remote debugger !"); + }else + { + + mRemoteDebugger = mPhysicsSDK->getFoundationSDK().getRemoteDebugger(); + } + } + + enableFlag(_getManagerFlags(),E_MF_PSDK_LOADED); + return E_PE_OK; +} +int PhysicManager::performInitialization() +{ + + XString buffer; +#ifdef DEMO_ONLY + + SYSTEMTIME sys; + + GetSystemTime(&sys); + + int dayd = sys.wDay; + int monthd = sys.wMonth; + int yeard = sys.wYear; + + if (!GetContext()->IsInInterfaceMode()){ + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"sorry guy, just a demo !"); + MessageBox(NULL,"vtPhysX Demonstration","VTMOD Productions",0); + //return E_PE_INVALID_OPERATION; + } + + if ( yeard == 2010 ) + { + if (monthd <=END_MONTH && monthd >=START_MONTH ) + { + goto init; + }else goto expired; + }else goto expired; + + +expired : + + + buffer << "today is the " << dayd << " of " << monthd << "\n"; + buffer << "but this release only works until : " << END_MONTH; + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,buffer.CStr()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Demo expired!"); + return E_PE_INVALID_OPERATION; + +#endif + + +init: + + + + + xBitSet initFlags = 0 ; + enableFlag(initFlags,E_MFI_LOAD_CONFIG); + enableFlag(initFlags,E_MFI_CREATE_FACTORY); + int error = initManager( initFlags.getMask()); + if (error == E_PE_INVALID_OPERATION ) + { + return 0; + } + + + if (isFlagOff(_getManagerFlags(),E_MF_PSDK_LOADED)) + { + if (initPhysicEngine()!= E_PE_OK ) + { + return E_MF_PSDK_FAILED; + } + + enableFlag(initFlags,E_MFI_USE_XML_WORLD_SETTINGS); + enableFlag(initFlags,E_MFI_CREATE_DEFAULT_WORLD); + + + int error = initManager( initFlags.getMask()); + if (error != E_PE_OK ) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't init manager"); + return E_PE_INVALID_OPERATION; + } + } + return E_PE_OK; +} + +bool PhysicManager::isValid() +{ + return isFlagOn(_getManagerFlags(),E_MF_PSDK_LOADED) && + isFlagOn(_getManagerFlags(),E_MF_FACTORY_CREATED) && + getDefaultWorldSettings() && getDefaultWorld(); +} + +void PhysicManager::_construct(xBitSet flags /* = 0 */) +{ + mManagerFlags = 0 ; + mPhysicsSDK = NULL; + mLogger = NULL; + mDefaultWorldSettings = NULL; + m_DefaultDocument = NULL; + m_currentFactory = NULL; + m_DefaultDocument = NULL; + m_currentFactory = NULL; + m_DefaultWorld = NULL; + mRemoteDebugger = NULL; + mIParameter = NULL; + mUserAllocator = NULL; + mControllerManager = NULL; + restoreMap = NULL; + + + + time = new xTime(); + xLogger::GetInstance()->setVirtoolsContext(m_Context); + + xLogger::GetInstance()->addLogItem(E_LI_AGEIA); + xLogger::GetInstance()->addLogItem(E_LI_MANAGER); + xLogger::GetInstance()->addLogItem(E_VSL); + xLogger::GetInstance()->addLogItem(E_BB); + + xLogger::GetInstance()->addItemDescription("AGEIA"); + xLogger::GetInstance()->addItemDescription("MANAGER"); + xLogger::GetInstance()->addItemDescription("VSL"); + xLogger::GetInstance()->addItemDescription("BB"); + + + xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGERROR,1); + xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGTRACE,0); + xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGWARNING,0); + xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGINFO,0); + + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGERROR,1); + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGTRACE,0); + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGWARNING,0); + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGINFO,0); + + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGERROR,1); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGTRACE,0); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGWARNING,0); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGINFO,0); + + SetLastLogEntry(""); + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Initiated"); + + if (!getLogger()) + { + setLogger(new pLogger()); + } +} diff --git a/usr/Src/Core/Manager/PhysicManagerJointAttributeFunctions.cpp b/usr/Src/Core/Manager/PhysicManagerJointAttributeFunctions.cpp new file mode 100644 index 0000000..f069734 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerJointAttributeFunctions.cpp @@ -0,0 +1,947 @@ +#include +#include "vtPhysXAll.h" +#include "vtAttributeHelper.h" + + +using namespace xUtils; +using namespace vtAgeia; +using namespace vtTools::ParameterTools; +using namespace vtTools::AttributeTools; + + +int registerJD6(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + return 0; +} +int registerJD6Drive(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + return 0; +} +int registerJLimitPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + + + //---------------------------------------------------------------- + // + // get and check objects + // + if (!target) + return -1; + + CKParameterOut *attParameter = target->GetAttributeParameter(attributeType); + if (!attParameter) + return -1; + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + + pRigidBody *body = GetPMan()->getBody(target); + if (!body) + return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(attParameter,PS_JLP_BODY_B_REF); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + + if (set) + { + //---------------------------------------------------------------- + // + // post pone i ck-start-up or loading + // + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJLimitPlane,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + } + + int jointType = GetValueFromParameterStruct(attParameter,PS_JLP_JOINT_TYPE); + + //try to get the joint + pJoint *joint = GetPMan()->getJoint(target,bodyBEnt,(JType)jointType); + if (!joint) + return -1; + + //---------------------------------------------------------------- + // + // we are on ck-play or SetAttribute-BB : Retrieve all parameters from the attribute : + // + + VxVector limitPoint = GetValueFromParameterStruct(attParameter,PS_JLP_LIMIT_POINT); + + CK_ID limitPointRefID = GetValueFromParameterStruct(attParameter,PS_JLP_LIMIT_POINT_REF); + CK3dEntity *limiPointRef = static_cast(GetPMan()->m_Context->GetObject(limitPointRefID)); + if (limiPointRef) + limiPointRef->Transform(&limitPoint,&limitPoint); + + + int isOnBodyB = GetValueFromParameterStruct(attParameter,PS_JLP_IS_ON_BODY_B); + float length = limitPoint.SquareMagnitude(); + if (XAbs(limitPoint.SquareMagnitude()) >=0.01f) + joint->setLimitPoint(limitPoint,isOnBodyB); + + + // - Limit Point Normal + VxVector limitPointNormal = GetValueFromParameterStruct(attParameter,PS_JLP_NORMAL); + + CK_ID limitPointNormalRefID = GetValueFromParameterStruct(attParameter,PS_JLP_NORMAL_REF); + CK3dEntity *limitPointNormalRef = static_cast(GetPMan()->m_Context->GetObject(limitPointNormalRefID)); + + if (limitPointNormalRef) + { + VxVector dir,up,right; + limitPointNormalRef->GetOrientation(&dir,&up,&right); + limitPointNormalRef->TransformVector(&limitPointNormal,&up); + } + + // - Point in Plane + VxVector PointInPlane = GetValueFromParameterStruct(attParameter,PS_JLP_PT_IN_PLANE); + + CK_ID PointInPlaneRefID = GetValueFromParameterStruct(attParameter,PS_JLP_PT_IN_PLANE_REF); + CK3dEntity *PointInPlaneRef = static_cast(GetPMan()->m_Context->GetObject(PointInPlaneRefID)); + if (PointInPlaneRef) + PointInPlaneRef->Transform(&PointInPlane,&PointInPlane); + + // - Restitution + float res = GetValueFromParameterStruct(attParameter,PS_JLP_RESTITUTION); + + // - Execute + + int result = joint->addLimitPlane(limitPointNormal,PointInPlane,res); + return result; + } + +} + + +int registerJPointOnLine(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + CKParameterOut *pointInPlaneParameter = target->GetAttributeParameter(attributeType); + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (pointInPlaneParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJPointOnLine,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_ANCHOR_REF); + + + + ////////////////////////////////////////////////////////////////////////// + //anchor : + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + int collision = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_COLLISION); + + + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + + pJointPointOnLine*joint = static_cast(pFactory::Instance()->createPointOnLineJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + joint->enableCollision(collision); + + float maxForce = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + return 1; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_PointOnLine); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + + return 1; + } + } + + return 0; + +} + +int registerJPointInPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + CKParameterOut *pointInPlaneParameter = target->GetAttributeParameter(attributeType); + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (pointInPlaneParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJPointInPlane,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_ANCHOR_REF); + + + + ////////////////////////////////////////////////////////////////////////// + //anchor : + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + int collision = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_COLLISION); + + + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + //pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) + pJointPointInPlane*joint = static_cast(pFactory::Instance()->createPointInPlaneJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + joint->enableCollision(collision); + + float maxForce = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + return 1; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_PointInPlane); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + + return 1; + } + } + + return 0; + +} + + +int registerJRevolute(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + + int s = GetPMan()->getAttributePostObjects().Size(); + using namespace vtTools::ParameterTools; + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJRevolute,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_ANCHOR_REF); + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + + int collision = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_COLLISION); + + int projectionMode = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_PROJ_MODE); + float projectionDistance= GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_PROJ_DISTANCE); + float projectionAngle = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_PROJ_ANGLE); + + + + pJointLimit limitHigh = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_LIMIT_HIGH)); + pJointLimit limitLow= pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_LIMIT_LOW)); + pSpring spring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_SPRING)); + pMotor motor = pFactory::Instance()->createMotorFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_MOTOR)); + + pJointRevolute*joint = static_cast(pFactory::Instance()->createRevoluteJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + + joint->enableCollision(collision); + joint->setLowLimit(limitLow); + joint->setHighLimit(limitHigh); + joint->setSpring(spring); + + if (projectionMode!=0) + { + joint->setProjectionMode((ProjectionMode)projectionMode); + joint->setProjectionDistance(projectionDistance); + joint->setProjectionAngle(projectionAngle); + } + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_MAX_TORQUE); + if (maxTorque !=0.0f || maxForce!=0.0f) + { + joint->setBreakForces(maxForce,maxTorque); + } + + return true; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Revolute); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + return 0; + +} + + +int registerJCylindrical(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + + + using namespace vtTools::ParameterTools; + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJCylindrical,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_ANCHOR_REF); + + + + ////////////////////////////////////////////////////////////////////////// + //anchor : + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + int collision = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_COLLISION); + + + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + //pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) + pJointCylindrical*joint = static_cast(pFactory::Instance()->createCylindricalJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + joint->enableCollision(collision); + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_MAX_TORQUE); + //joint->setBreakForces(maxForce,maxTorque); + return true; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Cylindrical); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + + return 0; + +} + + +int registerJPrismatic(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJPrismatic,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_ANCHOR_REF); + + + + ////////////////////////////////////////////////////////////////////////// + //anchor : + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + int collision = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_COLLISION); + + + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + //pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) + pJointCylindrical*joint = static_cast(pFactory::Instance()->createCylindricalJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + joint->enableCollision(collision); + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + + return true; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Prismatic); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + return 0; +} + +int registerJBall(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JBALL_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJBall,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JBALL_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JBALL_ANCHOR_REF); + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + + VxVector axis = GetValueFromParameterStruct(distanceParameter,PS_JBALL_GLOBAL_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(distanceParameter,PS_JBALL_GLOBAL_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + + VxVector swingAxis = GetValueFromParameterStruct(distanceParameter,PS_JBALL_LIMIT_SWING_AXIS); + + int collision = GetValueFromParameterStruct(distanceParameter,PS_JBALL_COLLISION); + + int projectionMode = GetValueFromParameterStruct(distanceParameter,PS_JBALL_PROJ_MODE); + float minDist = GetValueFromParameterStruct(distanceParameter,PS_JBALL_PROJ_DISTANCE); + + pJointLimit swingLimit = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_SWING_LIMIT)); + pJointLimit twistHighLimit = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_TWIST_HIGH)); + pJointLimit twistHighLow = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_TWIST_LOW)); + + pSpring swingSpring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_SWING_SPRING)); + pSpring twistSpring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_TWIST_SPRING)); + pSpring jointSpring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_JOINT_SPRING)); + + pJointBall *joint = static_cast(pFactory::Instance()->createBallJoint(target,bodyBEnt,anchor0,swingAxis,axis)); + if (joint) + { + + joint->setProjectionMode((ProjectionMode)projectionMode); + joint->setProjectionDistance(minDist); + joint->enableCollision(collision); + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JBALL_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JBALL_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + + + + if (swingLimit.value !=-1.0f) + { + joint->setSwingLimit(swingLimit); + joint->enableFlag(NX_SJF_SWING_LIMIT_ENABLED,true); + } + + joint->setSwingLimit(swingLimit); + + + if (twistHighLimit.value != 0.0f || twistHighLow.value !=0.0f ) + { + + joint->setTwistHighLimit(twistHighLimit); + joint->setTwistLowLimit(twistHighLow); + joint->enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,true); + } + + if (swingSpring.spring !=0.0f) + { + joint->setSwingSpring(swingSpring); + joint->enableFlag(NX_SJF_SWING_SPRING_ENABLED,true); + } + + + if (twistSpring.spring =0.0f) + { + joint->setTwistSpring(twistSpring); + joint->enableFlag(NX_SJF_TWIST_SPRING_ENABLED,true); + } + + if (jointSpring.spring !=0.0f) + { + joint->setJointSpring(jointSpring); + joint->enableFlag(NX_SJF_JOINT_SPRING_ENABLED,true); + } + + return true; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Spherical); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + return 0; +} + +int registerJFixed(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JFIXED_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if ( isPostJob && GetPMan()->GetContext()->IsPlaying() ) + { + pAttributePostObject postAttObject(target->GetID(),registerJFixed,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + + pJointFixed *joint = static_cast(pFactory::Instance()->createFixedJoint(target,bodyBEnt)); + if (joint) + { + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JFIXED_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JFIXED_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + + return true; + } + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Fixed); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + + return 0; + + +} + + + +int registerJDistance(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + + if(!GetPMan()->GetContext()->IsPlaying() && !GetPMan()->isValid() ) + return 0; + + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJDistance,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + + int s = GetPMan()->getAttributePostObjects().Size(); + + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_A_POS); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_A_REF); + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->TransformVector(&anchor0,&anchor0,a0Ref); + + VxVector anchor1 = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_B_POS); + CK_ID anchor1RefID = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_B_REF); + CK3dEntity *a1Ref = static_cast(GetPMan()->m_Context->GetObject(anchor1RefID)); + if (a1Ref) a1Ref->TransformVector(&anchor1,&anchor1,a1Ref); + + float maxDist = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_MAX_DISTANCE); + float minDist = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_MIN_DISTANCE); + + pSpring spring = pFactory::Instance()->createSpringFromParameter( GetParameterFromStruct(distanceParameter,PS_JDISTANCE_SPRING) ); + + int collision = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_COLL); + + + pJointDistance *joint = static_cast(pFactory::Instance()->createDistanceJoint(target,bodyBEnt,anchor0,anchor1,minDist,maxDist,spring)); + if (joint) + { + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + joint->enableCollision(collision); + + + #ifdef _DEBUG + + XString _errorStr; + + XString attName = GetPMan()->GetContext()->GetAttributeManager()->GetAttributeNameByType(attributeType); + + _errorStr << "Distance joint created on " << target->GetName() << " for attribute type : " << attName.Str(); + + xLogger::xLog(XL_START,ELOGINFO,E_LI_MANAGER,_errorStr.Str()); + + #endif + + return true; + } + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Distance); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + return 0; + +} + + +void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg) +{ + + CK3dEntity *ent = static_cast(obj); + if (!ent)return; + + ObjectRegisterFunction myFn = static_cast(arg); + if (ent , myFn) + { + bool isPlaying = GetPMan()->GetContext()->IsPlaying(); + int success = (*myFn)(ent,AttribType,Set,true); + + if (!success) + { + CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); + XString error; + error << "Registration Function failed for attribute" << attman->GetAttributeNameByType(AttribType) << " for Object : " << ent->GetName() ; + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,error.Str()); + }else{ + + CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); + XString error; + error << "Registration Function succeeded for attribute" << attman->GetAttributeNameByType(AttribType) << " for Object : " << ent->GetName() ; + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.Str()); + } + } +} diff --git a/usr/Src/Core/Manager/PhysicManagerJointVSL.cpp b/usr/Src/Core/Manager/PhysicManagerJointVSL.cpp new file mode 100644 index 0000000..3216bae --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerJointVSL.cpp @@ -0,0 +1,61 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + +//#include "pVehicle.h" + + + + + + + + +void PhysicManager::_RegisterVSLJoint() +{ + + + + STARTVSLBIND(m_Context) + + + + STOPVSLBIND + + +} + + + +/* +void __newvtWorldSettings(BYTE *iAdd) +{ +new (iAdd) pWorldSettings(); +} +void __newvtSleepingSettings(BYTE *iAdd) +{ +new (iAdd) pSleepingSettings(); +} +void __newvtJointSettings(BYTE *iAdd) +{ +new (iAdd) pJointSettings(); +} + + +int TestWS(pWorldSettings pWS) +{ +VxVector grav = pWS.Gravity(); +return 2; +} + +pFactory* GetPFactory(); + + +pFactory* GetPFactory() +{ +return pFactory::Instance(); +} + + +extern pRigidBody*getBody(CK3dEntity*ent); +*/ \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerJoints.cpp b/usr/Src/Core/Manager/PhysicManagerJoints.cpp new file mode 100644 index 0000000..2011fd9 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerJoints.cpp @@ -0,0 +1,170 @@ +#include +#include "vtPhysXAll.h" + +#include "vtAttributeHelper.h" + +pJoint*PhysicManager::getJoint(CK3dEntity*referenceA,CK3dEntity*referenceB/* =NULL */,JType type/* =JT_Any */) +{ + + pJoint *result = NULL; + + pRigidBody *a = GetPMan()->getBody(referenceA); + pRigidBody *b = GetPMan()->getBody(referenceB); + + pWorld *wA = a ? a->getWorld() : NULL; + pWorld *wB = b ? b->getWorld() : NULL; + pWorld *worldFinal = NULL; + + + bool oneBodyJoint = false;// body with world frame ? + CK3dEntity* oneBodyJointReference =NULL; + + + //---------------------------------------------------------------- + // + // Sanity Checks + // + XString errorString; + + // Reference A physicalized at all ? + if ( !referenceA && !referenceB ) + { + errorString.Format("No reference specified"); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // Reference A IS NOT Reference B ? + if ( (referenceA!=NULL && referenceB!=NULL) && (a==b) ) + { + errorString.Format("Reference A (%s) is the same as Reference B (%s)",referenceA->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // Reference A physicalized at all ? + if (referenceA && !a){ + + errorString.Format("Reference A (%s) valid but not physicalized",referenceA->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // Reference B physicalized at all ? + if (referenceB && !b){ + + errorString.Format("Reference B (%s) valid but not physicalized",referenceB->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + + // world of object a valid ? + if (a && !wA){ + errorString.Format("Reference A (%s) is physicalized but has no valid world object",referenceA->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // world of object b valid ? + if (b && !wB){ + errorString.Format("Reference B (%s) is physicalized but has no valid world object",referenceB->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // rigid bodies are in the same world + if ( (wA!=NULL && wB!=NULL) && (wA!=wB) ) + { + errorString.Format("Reference A (%s) and B(%s) is physicalized but are not in the same world",referenceA->GetName(),referenceB->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + //---------------------------------------------------------------- + // + // Preparing lookup + // + if ( wA ) + worldFinal = wA; + if ( wB ) + worldFinal = wB; + + + // constraint is attached to world frame ? + if ( (a && !b) || (b && !a) ) + oneBodyJoint = true; + + // world frame constraint, track the reference + if (oneBodyJoint) + { + if ( a ) + oneBodyJointReference = referenceA; + if ( b ) + oneBodyJointReference = referenceB; + } + + + //---------------------------------------------------------------- + // + // Parse the scene joints + // + NxU32 jointCount = worldFinal->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + worldFinal->getScene()->resetJointIterator(); + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = worldFinal->getScene()->getNextJoint(); + + pJoint *_cJoint = static_cast( j->userData ); + if (!_cJoint) + continue; + + //---------------------------------------------------------------- + // + // Special case : has a joint at all, only for world frame constraints + // + if (type == JT_Any) + { + if ( oneBodyJoint && + _cJoint->GetVTEntA() == oneBodyJointReference || + _cJoint->GetVTEntB() == oneBodyJointReference + ) + return _cJoint; + } + + //---------------------------------------------------------------- + // + // Specific joint type + // + if ( j->getType() == type) + { + + //---------------------------------------------------------------- + // + // world constraint joint + // + if (oneBodyJoint && + _cJoint->GetVTEntA() == oneBodyJointReference || + _cJoint->GetVTEntB() == oneBodyJointReference + ) + return _cJoint; + + //---------------------------------------------------------------- + // + // Two references given + // + if ( _cJoint->GetVTEntA() == referenceA && _cJoint->GetVTEntB() == referenceB ) + return _cJoint; + + if ( _cJoint->GetVTEntA() == referenceB && _cJoint->GetVTEntB() == referenceA ) + return _cJoint; + + } + } + } + return NULL; +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerLoader.cpp b/usr/Src/Core/Manager/PhysicManagerLoader.cpp new file mode 100644 index 0000000..f156afc --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerLoader.cpp @@ -0,0 +1,68 @@ +#include +#include "vtPhysXAll.h" + +#include "tinyxml.h" + + + +static const TiXmlElement *getFirstOdeElement(const TiXmlElement *root); +static const TiXmlElement *getFirstOdeElement(const TiXmlElement *root) +{ + // should have some recursive algo + if (!strcmp(root->Value(), "vtPhysics")) + { + return root; + } + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling()) + { + if (child->Type() == TiXmlNode::ELEMENT) + { + const TiXmlElement *res = getFirstOdeElement(child->ToElement ()); + if (res) + return res; + } + } + + return 0; +} +TiXmlDocument* +PhysicManager::loadDefaults(XString filename) +{ + + + // load and check file + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,filename.CStr()); + XString name(Ini); + name << '\0'; + + m_DefaultDocument = new TiXmlDocument(filename.Str()); + m_DefaultDocument ->LoadFile(Ini); + m_DefaultDocument ->Parse(Ini); + + if (m_DefaultDocument->Error()) + { + //xLogger::xLog("couldn't load default document"); + + delete m_DefaultDocument; + m_DefaultDocument = NULL; + + return NULL; + } + + // get the ogreode element. + TiXmlNode* node = m_DefaultDocument->FirstChild( "vtPhysics" ); + if (!node) + { + //Ogre::LogManager::getSingleton().logMessage(" cannot find ogreode root in XML file!"); + return NULL; + } + return m_DefaultDocument; + +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerRun.cpp b/usr/Src/Core/Manager/PhysicManagerRun.cpp new file mode 100644 index 0000000..9dfe6ce --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerRun.cpp @@ -0,0 +1,267 @@ +#include +#include "vtPhysXAll.h" +#include "pConfig.h" + +#include + +int demoTimerExpired=0; + +float absTime = 0.0f; +float lastAbsTime = 0.0f; +#include "Timing.h" + +static float gTimestepMultiplier = 1.0f; + +float getCurrentTime() +{ + unsigned int currentTime = timeGetTime(); + return (float)(currentTime)*0.001f; +} + + +float getElapsedTime() +{ + static LARGE_INTEGER previousTime; + static LARGE_INTEGER freq; + static bool init = false; + if(!init){ + QueryPerformanceFrequency(&freq); + QueryPerformanceCounter(&previousTime); + init=true; + } + LARGE_INTEGER currentTime; + QueryPerformanceCounter(¤tTime); + unsigned long long elapsedTime = currentTime.QuadPart - previousTime.QuadPart; + previousTime = currentTime; + return (float)(elapsedTime)/(freq.QuadPart); +} + + +int PhysicManager::_checkResetList() +{ + + int result = 0 ; + pRestoreMapIt it = _getRestoreMap()->Begin(); + while(it != _getRestoreMap()->End()) + { + CK_ID id = it.GetKey(); + CK3dEntity * ent = (CK3dEntity*)GetPMan()->GetContext()->GetObject(id); + if(ent) + { + pRigidBody* body = GetPMan()->getBody(ent); + if (body) + { + body->onICRestore(ent,*it); + _getRestoreMap()->Remove(it.GetKey()); + //_getRestoreMap()->Remove(it.GetKey()); + it =_getRestoreMap()->Begin(); + result++; + continue; + } + }else + { + _getRestoreMap()->Remove(it.GetKey()); + it =_getRestoreMap()->Begin(); + result++; + continue; + } + it++; + } + //_getRestoreMap()->Clear(); + + /* + for (CK3dEntity** it = resetList.Begin(); it != resetList.End(); ++it) + { + pRigidBody* body = GetPMan()->getBody(*it); + if (body) + { + body->onICRestore(*it,true); + } + } + */ +// resetList.Clear(); + + return result; +} + +float PhysicManager::getLastTimeStep(int flags) +{ + + NxF32 elapsedTime = getElapsedTime(); + elapsedTime*= GetContext()->GetTimeManager()->GetTimeScaleFactor(); + + elapsedTime*=10.0f; + if(elapsedTime <= 0) + elapsedTime = 0; + + return elapsedTime; + +} +void PhysicManager::advanceTime(float time) +{ + + timer +=time; + float timeNow = timer; + + mLastStepTime = time; + + int op= 30 ; + op++; + /* + float TimeStep = 1.0f / 60.0f; + if(gFixedStep) gScene->setTiming(TimeStep, 1, NX_TIMESTEP_FIXED); + else gScene->setTiming(TimeStep, 1, NX_TIMESTEP_VARIABLE); + + */ + +} + +void PhysicManager::update(float stepsize) +{ + advanceTime(stepsize); +/* float a= time->GetSpanMS(); + float b= time->GetRealTime(); + time->Update(); +*/ + int lastTime; + int curTime,diffTime,maxTime; + + // Calculate time from last to current situation +// time->Update(); + curTime=time->GetRealTime(); + lastTime=time->GetLastSimTime(); + diffTime=curTime-lastTime; + //maxTime=lastTime+maxSimTimePerFrame; + +#ifdef SESSION_LIMIT + #ifndef REDIST + + if (timer >(SESSION_MAX)) + { + if (demoTimerExpired==0) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Demo expires after 15 mins"); + demoTimerExpired = 1; + } + return ; + } + #endif +#endif + +#ifdef REDIST + + if (m_Context->IsInInterfaceMode()) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"This is a redist Dll"); + return; + } + #pragma message("-------------------------------PManager ::Update REDIST" ) +#endif + + + //CKTimeProfiler(const char* iTitle, CKContext* iContext, int iStartingCount = 4): + //CKTimeProfiler MyProfiler("PhysX Step",GetContext(),8); + + + + float elapsedTime = getLastTimeStep(0);//(0.5) + float msTimeNow = lastStepTimeMS;//(50.0) + + //_checkResetList(); + + pWorldMapIt it = getWorlds()->Begin(); + while(it != getWorlds()->End()) + { + pWorld *w = *it; + + w->step(elapsedTime); + //w->step(lastStepTimeMS); + it++; + } + + /* + if (checkPhysics) + { + checkWorlds(); + checkPhysics = false; + } + */ + + + + /*if (checkPhysics) + { + _checkObjectsByAttribute(GetContext()->GetCurrentLevel()->GetCurrentScene()); + checkPhysics = false; + }*/ + //float pTime = MyProfiler + //float a = pTime; +} + +CKERROR PhysicManager::PostProcess() +{ + advanceTime(lastStepTimeSec); + + if(sceneWasChanged) + { + + + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"sceneWasChanged"); + sceneWasChanged = 0; + + } + + + pWorldMapIt it = getWorlds()->Begin(); + while(it != getWorlds()->End()) + { + pWorld *w = *it; + w->onPostProcess(); + it++; + } + + cleanAttributePostObjects(); + _cleanTriggers(); + getJointFeedbackList().Clear(); + return CK_OK; +} + + +CKERROR PhysicManager::PreProcess() +{ + + + float timeCtx = GetContext()->GetTimeManager()->GetLastDeltaTimeFree(); + update(timeCtx); + + pWorldMapIt it = getWorlds()->Begin(); + while(it != getWorlds()->End()) + { + pWorld *w = *it; + w->onPreProcess(); + it++; + } + + return CK_OK; +} + +void PhysicManager::_cleanTriggers() +{ + /* + int nbEntries = getTriggers().Size() ; + for (int i = 0 ; i < getTriggers().Size(); i++ ) + { + + pTriggerEntry &entry = *getTriggers().At(i); + { + if (entry.triggered) + { + getTriggers().RemoveAt(i); + i = 0; + } + } + } + */ + getTriggers().Clear(); +} + diff --git a/usr/Src/Core/Manager/PhysicManagerTools.cpp b/usr/Src/Core/Manager/PhysicManagerTools.cpp new file mode 100644 index 0000000..89da2fd --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerTools.cpp @@ -0,0 +1,350 @@ +#include +#include "vtPhysXAll.h" + +#include "vtAttributeHelper.h" + +#include "pCommon.h" +#include "IParameter.h" +#include "vtBBHelper.h" +#include "xDebugTools.h" +#include "pCallbackSignature.h" + + +int PhysicManager::_checkListCheck() +{ + int result = 0 ; + while(bodyListCheck.Size()) + { + result ++; + bodyListCheck.PopBack(); + } + return result; +} + +int PhysicManager::_checkRemovalList() +{ + + int result = 0 ; + + if (bodyListRemove.Size() < 1) + return 0; + + pWorldMapIt wit = getWorlds()->Begin(); + + bool wasDeleting = false; + while(wit != getWorlds()->End()) + { + pWorld *w = *wit; + + int cCount = bodyListRemove.Size(); + + //for (CK3dEntity** it = bodyListRemove.Begin(); it != bodyListRemove.End(); ++it) + //int i = 0 ; i < bodyListRemove.Size() ; i ++ ) + while(bodyListRemove.Size()) + { + CK_ID id = *bodyListRemove.At(0); + CK3dEntity * ent = (CK3dEntity*)GetPMan()->GetContext()->GetObject(id); + if(ent) + { + pRigidBody* body = GetPMan()->getBody(ent); + if (body) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"deleting body "); + body->destroy(); + SAFE_DELETE(body) + cCount = bodyListRemove.Size(); + result ++; + } + } + bodyListRemove.PopFront(); + } + wit++; + } + //bodyListRemove.Clear(); + //_cleanOrphanedJoints(); + if(wasDeleting) + { + } + //getScene()->checkResults(NX_ALL_FINISHED,true) +/* + pWorldMapIt it = getWorlds()->Begin(); + while(it != getWorlds()->End()) + { + pWorld *w = *it; + w->getScene()->fetchResults(NX_ALL_FINISHED,false); + it++; + } + */ + return result; +} + + +XString printSignature(BBParameter pAarray[],int size) +{ + + CKParameterManager *pm = GetPMan()->GetContext()->GetParameterManager(); + XString signature; + + for(int i = 0 ; i < size ; i ++ ) + { + BBParameter *par = &pAarray[i]; + signature << "\t\t Parameter :" << par->name << ": must be type of " << pm->ParameterGuidToName(par->guid) << " \n "; + } + return signature; + +} + +bool isCompatible(CKParameterManager *pm,CKGUID a,CKGUID b) +{ + + if (a == b) + { + return true; + } + + //---------------------------------------------------------------- + // + // special case custom flags or enumeration, integer is possible + // + if ( ( pm->GetEnumDescByType(pm->ParameterGuidToType(a)) || + pm->GetFlagsDescByType(pm->ParameterGuidToType(a)) + ) && + pm->IsDerivedFrom(b,CKPGUID_INT) + ) + { + return true; + } + return false; +} + +int checkInputSignature(CKBehavior *beh,BBParameter *pAarray,int size) +{ + + int result = true; + int parameterCount = beh->GetInputParameterCount(); + if ( parameterCount < size) + { + result = 0; + } + + CKParameterManager *pm = GetPMan()->GetContext()->GetParameterManager(); + for (int i = 0 ; i < size ; i ++) + { + CKParameterIn *inPar = beh->GetInputParameter(i); + BBParameter *par = &pAarray[i]; + + if (!isCompatible(pm,par->guid,inPar->GetGUID())) + { + result = 0; + } + } + return result; +} + +int checkOutputSignature(CKBehavior *beh,BBParameter *pAarray,int size) +{ + + int result = 1; + int parameterCount = beh->GetOutputParameterCount(); + if ( parameterCount < size) + { + result= 0; + } + + CKParameterManager *pm = GetPMan()->GetContext()->GetParameterManager(); + for (int i = 0 ; i < size ; i ++) + { + CKParameterOut *inPar = beh->GetOutputParameter(i); + BBParameter *par = &pAarray[i]; + + if (!isCompatible(pm,par->guid,inPar->GetGUID())) + { + result= 0; + } + } + + + return result; +} + +bool PhysicManager::checkCallbackSignature(CKBehavior *beh,int type,XString& errMessage) +{ + + if (!beh) + { + return false; + } + CKParameterManager *pm = GetPMan()->GetContext()->GetParameterManager(); + + int parameterCount = beh->GetInputParameterCount(); + switch(type) + { + //---------------------------------------------------------------- + // + // Collisions notify + // + case CB_OnContactNotify: + { + errMessage.Format("\n\t Input parameters for collisions notify must have this signature : \n"); + if ( parameterCount < BB_PMAP_SIZE(pInMapContactCallback)) + { + errMessage << printSignature(pInMapContactCallback,BB_PMAP_SIZE(pInMapContactCallback) ); + return false; + } + for (int i = 0 ; i < BB_PMAP_SIZE(pInMapContactCallback) ; i ++) + { + CKParameterIn *inPar = beh->GetInputParameter(i); + BBParameter *par = &pInMapContactCallback[i]; + + if (!isCompatible(pm,par->guid,inPar->GetGUID())) + { + errMessage << printSignature(pInMapContactCallback,BB_PMAP_SIZE(pInMapContactCallback) ); + return false; + } + } + return true; + } + + //---------------------------------------------------------------- + // + // wheel contact modify + // + case CB_OnWheelContactModify: + { + + //---------------------------------------------------------------- + // + // check input parameters + // + bool result = true; + errMessage.Format("\n\t Input parameters for wheel contact modification must have this signature : \n"); + int ok = checkInputSignature(beh,pInMapWheelContactModifyCallback,BB_PMAP_SIZE(pInMapWheelContactModifyCallback)); + if ( !ok ) + { + errMessage << printSignature(pInMapWheelContactModifyCallback,BB_PMAP_SIZE(pInMapWheelContactModifyCallback) ); + result =false; + } + //---------------------------------------------------------------- + // + // check output parameters + // + errMessage.Format("\n\t Input parameters for wheel contact modification must have this signature : \n"); + ok = checkOutputSignature(beh,pOutMapWheelContactModifyCallback,BB_PMAP_SIZE(pOutMapWheelContactModifyCallback)); + if (!ok) + { + errMessage << printSignature(pOutMapWheelContactModifyCallback,BB_PMAP_SIZE(pOutMapWheelContactModifyCallback) ); + result = false; + } + return result; + } + //---------------------------------------------------------------- + // + // Collisions notify + // + case CB_OnRayCastHit: + { + //---------------------------------------------------------------- + // + // check input parameters + // + errMessage.Format("\n\t Input parameters for raycast hit report must have this signature : \n"); + int ok = checkInputSignature(beh,pInMapRaycastHitCallback,BB_PMAP_SIZE(pInMapRaycastHitCallback)); + if ( !ok ) + { + errMessage << printSignature(pInMapRaycastHitCallback,BB_PMAP_SIZE(pInMapRaycastHitCallback)); + return false; + } + return true; + } + + //---------------------------------------------------------------- + // + // Collisions notify + // + case CB_OnContactModify: + { + //---------------------------------------------------------------- + // + // check input parameters + // + bool result = true; + errMessage.Format("\n\t Input parameters for contact modification must have this signature : \n"); + int ok = checkInputSignature(beh,pInMapContactModifyCallback,BB_PMAP_SIZE(pInMapContactModifyCallback)); + if ( !ok ) + { + errMessage << printSignature(pInMapContactModifyCallback,BB_PMAP_SIZE(pInMapContactModifyCallback) ); + result =false; + } + //---------------------------------------------------------------- + // + // check output parameters + // + errMessage.Format("\n\t Output parameters for contact modification must have this signature : \n"); + ok = checkOutputSignature(beh,pOutMapContactModifyCallback,BB_PMAP_SIZE(pOutMapContactModifyCallback)); + if (!ok) + { + errMessage << printSignature(pOutMapContactModifyCallback,BB_PMAP_SIZE(pOutMapContactModifyCallback) ); + result = false; + } + return result; + } + //---------------------------------------------------------------- + // + // trigger + // + //---------------------------------------------------------------- + // + // Collisions notify + // + case CB_OnTrigger: + { + errMessage.Format("\n\t Input parameters for trigger notify must have this signature : \n"); + if ( parameterCount < BB_PMAP_SIZE(pInMapTriggerCallback)) + { + errMessage << printSignature(pInMapTriggerCallback,BB_PMAP_SIZE(pInMapTriggerCallback) ); + return false; + } + for (int i = 0 ; i < BB_PMAP_SIZE(pInMapTriggerCallback) ; i ++) + { + CKParameterIn *inPar = beh->GetInputParameter(i); + BBParameter *par = &pInMapTriggerCallback[i]; + + if (!isCompatible(pm,par->guid,inPar->GetGUID())) + { + errMessage << printSignature(pInMapTriggerCallback,BB_PMAP_SIZE(pInMapTriggerCallback) ); + return false; + } + } + return true; + } + + + //---------------------------------------------------------------- + // + // Joint Break Script + // + case CB_OnJointBreak: + { + errMessage.Format("\n\t Input parameters for joint breaks must have this signature : \n"); + if ( parameterCount < BB_PMAP_SIZE(pInMapJointBreakCallback)) + { + errMessage << printSignature(pInMapJointBreakCallback,BB_PMAP_SIZE(pInMapJointBreakCallback) ); + return false; + } + for (int i = 0 ; i < BB_PMAP_SIZE(pInMapJointBreakCallback) ; i ++) + { + CKParameterIn *inPar = beh->GetInputParameter(i); + BBParameter *par = &pInMapJointBreakCallback[i]; + + if (!isCompatible(pm,par->guid,inPar->GetGUID())) + { + errMessage << printSignature(pInMapJointBreakCallback,BB_PMAP_SIZE(pInMapJointBreakCallback) ); + return false; + } + } + return true; + } + + } + return false; +} diff --git a/usr/Src/Core/Manager/PhysicManagerVTRegisterCommon.cpp b/usr/Src/Core/Manager/PhysicManagerVTRegisterCommon.cpp new file mode 100644 index 0000000..d3c987b --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerVTRegisterCommon.cpp @@ -0,0 +1,625 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + + +#include "pVehicleAll.h" + + + +PhysicManager*GetPhysicManager(); +pRigidBody *getBody(CK3dEntity*ent); +CKGUID GetPhysicManagerGUID() { return GUID_MODULE_MANAGER;} + +typedef ForceMode PForceMode; +typedef D6MotionMode PJMotion; +typedef D6DriveType PDriveType; + + +pFactory* getPFactory() +{ + return pFactory::Instance(); +} + + +void __newpObjectDescr(BYTE *iAdd) +{ + new (iAdd) pObjectDescr(); +} + + +void __newpRaycastHit(BYTE *iAdd) +{ + new(iAdd)pRaycastHit(); +} + +void __newpGroupsMask(BYTE *iAdd) +{ + new(iAdd)pGroupsMask(); +} + +void __newpOptimization(BYTE *iAdd) +{ + new(iAdd)pOptimization(); +} +void __newpMassSettings(BYTE *iAdd) +{ + new(iAdd)pMassSettings(); +} +void __newpCCD(BYTE *iAdd) +{ + new(iAdd)pCCDSettings(); +} +void __newpCollisionSettings(BYTE *iAdd) +{ + new(iAdd)pCollisionSettings(); +} + +void __newpPivotSettings(BYTE *iAdd) +{ + new(iAdd)pPivotSettings(); +} + +void __newpMaterial(BYTE *iAdd) +{ + new(iAdd)pMaterial(); +} +void __newpAxisReferenceLength(BYTE *iAdd) +{ + new(iAdd)pAxisReferencedLength(); +} + + +void __newpCapsuleSettingsEx(BYTE *iAdd) +{ + new(iAdd)pCapsuleSettingsEx(); +} +void __newpConvexCylinder(BYTE *iAdd) +{ + new(iAdd)pConvexCylinderSettings(); +} + +void __newpWheelDescr(BYTE *iAdd) +{ + new (iAdd)pWheelDescr(); +} + +void __newpTireFunction(BYTE *iAdd) +{ + new (iAdd)pTireFunction(); +} + + +void __newpInterpolation(BYTE *iAdd) +{ + new (iAdd)pLinearInterpolation(); +} + +CKGUID getRigidBodyParameterType() +{ + return VTS_PHYSIC_ACTOR; +} + +////////////////////////////////////////////////////////////////////////// + +#define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) + +void logWarning(const char*errMessage) +{ + if (!errMessage || !strlen(errMessage)) + return; + + xLogger::xLog(XL_START,ELOGWARNING,E_VSL,errMessage); + + +} + +void PhysicManager::_RegisterVSLCommon() +{ + + STARTVSLBIND(m_Context) + + //---------------------------------------------------------------- + // + // manager related + // + + { + + DECLAREENUM("pSDKParameter") + DECLAREENUMVALUE("pSDKParameter", "pSDKP_SkinWidth" ,1 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_DefaultSleepLinVelSquared" ,2 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_DefaultSleepAngVelSquared" ,3 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_BounceThreshold" ,4 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_DynFrictScaling" , 5) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_StaFrictionScaling" ,6 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_MaxAngularVelocity" ,7 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ContinuousCD" ,8 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_AdaptiveForce" ,68 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_CollVetoJointed" ,69 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_TriggerTriggerCallback" ,70 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_SelectHW_Algo" ,71 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_CCDEpsilon" ,73 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_SolverConvergenceThreshold" ,74 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_BBoxNoiseLevel" ,75 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ImplicitSweepCacheSize" , 76) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_DefaultSleepEnergy" ,77 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ConstantFluidMaxPackets" ,78 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ConstantFluidMaxParticlesPerStep" ,79 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_AsynchronousMeshCreation" ,96 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ForceFieldCustomKernelEpsilon" ,97 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ImprovedSpringSolver" ,98 ) + + } + + + REGISTERCONST("FLT_MAX",BIND_FLOAT,FLT_MAX) + REGISTERCONST("PTYPE_RIGID_BODY",BIND_FLOAT,FLT_MAX) + + //---------------------------------------------------------------- + // + // common types + // + DECLAREPOINTERTYPE(pFactory) + DECLAREFUN_C_0(pFactory,getPFactory) + + + + DECLAREFUN_C_0(CKGUID, GetPhysicManagerGUID) + DECLAREOBJECTTYPE(PhysicManager) + DECLARESTATIC_1(PhysicManager,PhysicManager*,Cast,CKBaseManager* iM) + DECLAREFUN_C_0(PhysicManager*, GetPhysicManager) + + DECLAREPOINTERTYPE(pRigidBody) + DECLAREPOINTERTYPE(pPacejka) + + DECLAREPOINTERTYPEALIAS(pRigidBody,"pBody") + + DECLAREFUN_C_0(CKGUID,getRigidBodyParameterType) + DECLAREFUN_C_1(void,logWarning,const char*) + + DECLAREPOINTERTYPE(pWorld) + DECLAREPOINTERTYPE(pCloth) + DECLAREPOINTERTYPE(pVehicle) + DECLAREPOINTERTYPE(pWheel) + DECLAREPOINTERTYPE(pVehicle) + DECLAREPOINTERTYPE(pVehicleMotor) + DECLAREPOINTERTYPE(pVehicleGears) + + DECLAREPOINTERTYPE(pWheel1) + DECLAREPOINTERTYPE(pWheel2) + + //---------------------------------------------------------------- + // + // new vehicle pack + // + DECLAREPOINTERTYPE(pEngine) + DECLAREPOINTERTYPE(pGearBox) + DECLAREPOINTERTYPE(pWheelContactData) + + DECLAREPOINTERTYPE(pLinearInterpolation) + //DECLARECTOR_0(__newpInterpolation) + + + + + + + + DECLAREINHERITANCESIMPLE("pWheel","pWheel1") + DECLAREINHERITANCESIMPLE("pWheel","pWheel2") + + ////////////////////////////////////////////////////////////////////////// + // + // Joints : + // + + + DECLAREPOINTERTYPE(pJoint) + DECLAREPOINTERTYPE(pJointFixed) + DECLAREPOINTERTYPE(pJointDistance) + DECLAREPOINTERTYPE(pJointD6) + DECLAREPOINTERTYPE(pJointPulley) + DECLAREPOINTERTYPE(pJointBall) + DECLAREPOINTERTYPE(pJointRevolute) + DECLAREPOINTERTYPE(pJointPrismatic) + DECLAREPOINTERTYPE(pJointCylindrical) + DECLAREPOINTERTYPE(pJointPointInPlane) + DECLAREPOINTERTYPE(pJointPointOnLine) + + + DECLAREINHERITANCESIMPLE("pJoint","pJointDistance") + DECLAREINHERITANCESIMPLE("pJoint","pJointD6") + DECLAREINHERITANCESIMPLE("pJoint","pJointFixed") + DECLAREINHERITANCESIMPLE("pJoint","pJointPulley") + DECLAREINHERITANCESIMPLE("pJoint","pJointBall") + DECLAREINHERITANCESIMPLE("pJoint","pJointRevolute") + DECLAREINHERITANCESIMPLE("pJoint","pJointPrismatic") + DECLAREINHERITANCESIMPLE("pJoint","pJointCylindrical") + DECLAREINHERITANCESIMPLE("pJoint","pJointPointOnLine") + DECLAREINHERITANCESIMPLE("pJoint","pJointPointInPlane") + //---------------------------------------------------------------- + // + // help structures collision + // + + DECLAREOBJECTTYPE(pGroupsMask) + DECLARECTOR_0(__newpGroupsMask) + DECLAREMEMBER(pGroupsMask,int,bits0) + DECLAREMEMBER(pGroupsMask,int,bits1) + DECLAREMEMBER(pGroupsMask,int,bits2) + DECLAREMEMBER(pGroupsMask,int,bits3) + + + DECLAREOBJECTTYPE(pCollisionSettings) + DECLARECTOR_0(__newpCollisionSettings) + DECLAREMEMBER(pCollisionSettings,int,collisionGroup) + DECLAREMEMBER(pCollisionSettings,pGroupsMask,groupsMask) + DECLAREMEMBER(pCollisionSettings,float,skinWidth) + + + DECLAREOBJECTTYPE(pRaycastHit) + DECLARECTOR_0(__newpRaycastHit) + DECLAREMEMBER(pRaycastHit,float,distance) + DECLAREMEMBER(pRaycastHit,CK3dEntity*,shape) + DECLAREMEMBER(pRaycastHit,VxVector,worldImpact) + DECLAREMEMBER(pRaycastHit,VxVector,worldNormal) + DECLAREMEMBER(pRaycastHit,int,faceID) + DECLAREMEMBER(pRaycastHit,int,internalFaceID) + DECLAREMEMBER(pRaycastHit,float,u) + DECLAREMEMBER(pRaycastHit,float,v) + DECLAREMEMBER(pRaycastHit,int,materialIndex) + DECLAREMEMBER(pRaycastHit,int,flags) + + DECLAREENUM("pFilterOp") + DECLAREENUMVALUE("pFilterOp", "FO_And" , 0) + DECLAREENUMVALUE("pFilterOp", "FO_Or" , 1) + DECLAREENUMVALUE("pFilterOp", "FO_Xor" ,2) + DECLAREENUMVALUE("pFilterOp", "FO_Nand",3 ) + DECLAREENUMVALUE("pFilterOp", "FO_Nor" , 4) + DECLAREENUMVALUE("pFilterOp", "FO_NXor" ,5 ) + + DECLAREENUM("pShapesType") + DECLAREENUMVALUE("pShapesType", "ST_Static" , 1) + DECLAREENUMVALUE("pShapesType", "ST_Dynamic" , 2) + DECLAREENUMVALUE("pShapesType", "ST_All" , 3) + + DECLAREENUM("pTriggerFlags") + DECLAREENUMVALUE("pTriggerFlags", "TF_Disable" , 8) + DECLAREENUMVALUE("pTriggerFlags", "TF_OnEnter" , 1) + DECLAREENUMVALUE("pTriggerFlags", "TF_OnLeave" , 2) + DECLAREENUMVALUE("pTriggerFlags", "TF_OnStay" , 4) + + DECLAREENUM("pContactModifyMask") + DECLAREENUMVALUE("pContactModifyMask", "CMM_None" , 0) + DECLAREENUMVALUE("pContactModifyMask", "CMM_MinImpulse" , 1) + DECLAREENUMVALUE("pContactModifyMask", "CMM_MaxImpulse" , 2) + DECLAREENUMVALUE("pContactModifyMask", "CMM_Error" , 4) + DECLAREENUMVALUE("pContactModifyMask", "CMM_Target" , 8) + DECLAREENUMVALUE("pContactModifyMask", "CMM_LocalPosition0" , 16) + DECLAREENUMVALUE("pContactModifyMask", "CMM_LocalPosition1" , 32) + DECLAREENUMVALUE("pContactModifyMask", "CMM_LocalOrientation0" , 64) + DECLAREENUMVALUE("pContactModifyMask", "CMM_LocalOrientation1" , 128) + DECLAREENUMVALUE("pContactModifyMask", "CMM_StaticFriction0" , 256) + DECLAREENUMVALUE("pContactModifyMask", "CMM_StaticFriction1" , 512) + DECLAREENUMVALUE("pContactModifyMask", "CMM_DynamicFriction0" , 1024) + DECLAREENUMVALUE("pContactModifyMask", "CMM_DynamicFriction1" , 2048) + DECLAREENUMVALUE("pContactModifyMask", "CMM_Restitution" , 8196) + DECLAREENUMVALUE("pContactModifyMask", "CMM_Force32" ,2147483648 ) + + DECLAREENUM("pCollisionEventMask") + DECLAREENUMVALUE("pCollisionEventMask", "CPF_IgnorePair" , 1) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnStartTouch" , 2) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnEndTouch" , 4) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnTouch" , 8) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnImpact" , 16) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnRoll" , 32) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnSlide" , 64) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_Forces" , 128) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnStartTouchForceThreshold" , 256) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnEndTouchForceThreshold" , 512) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_OnTouchForceThreshold" , 1024) + DECLAREENUMVALUE("pCollisionEventMask", "CPF_ContactModification" , 65536) + + + + //---------------------------------------------------------------- + // + // help structures Rigid body + // + + DECLAREENUM("BodyFlags") + DECLAREENUMVALUE("BodyFlags", "BF_Moving" , 1) + DECLAREENUMVALUE("BodyFlags", "BF_Gravity" , 2) + DECLAREENUMVALUE("BodyFlags", "BF_Collision" , 4) + DECLAREENUMVALUE("BodyFlags", "BF_Kinematic" , 8) + DECLAREENUMVALUE("BodyFlags", "BF_SubShape" , 16) + DECLAREENUMVALUE("BodyFlags", "BF_Hierarchy" , 32) + DECLAREENUMVALUE("BodyFlags", "BF_Attributes" , 64) + DECLAREENUMVALUE("BodyFlags", "BF_TriggerShape" , 128) + DECLAREENUMVALUE("BodyFlags", "BF_Sleep" , 4096) + DECLAREENUMVALUE("BodyFlags", "BF_CollisionNotify" , 512) + DECLAREENUMVALUE("BodyFlags", "BF_CollisionsForce" , 1024) + DECLAREENUMVALUE("BodyFlags", "BF_ContactModify" , 2048) + + DECLAREENUM("BodyLockFlags") + DECLAREENUMVALUE("BodyLockFlags", "BF_LPX" , 2) + DECLAREENUMVALUE("BodyLockFlags", "BF_LPY" , 4) + DECLAREENUMVALUE("BodyLockFlags", "BF_LPZ" , 8) + DECLAREENUMVALUE("BodyLockFlags", "BF_LRX" , 16) + DECLAREENUMVALUE("BodyLockFlags", "BF_LRY" , 32) + DECLAREENUMVALUE("BodyLockFlags", "BF_LRZ" , 64) + + + + DECLAREENUM("HullType") + DECLAREENUMVALUE("HullType", "HT_Sphere" , 0) + DECLAREENUMVALUE("HullType", "HT_Box" , 1) + DECLAREENUMVALUE("HullType", "HT_Capsule" , 2) + DECLAREENUMVALUE("HullType", "HT_Plane" , 3) + DECLAREENUMVALUE("HullType", "HT_Mesh" , 4) + DECLAREENUMVALUE("HullType", "HT_ConvexMesh" , 5) + DECLAREENUMVALUE("HullType", "HT_HeightField" , 6) + DECLAREENUMVALUE("HullType", "HT_Wheel" , 7) + DECLAREENUMVALUE("HullType", "HT_ConvexCylinder" , 9) + + + + + DECLAREENUM("CombineMode") + DECLAREENUMVALUE("CombineMode", "CM_Average" , 0) + DECLAREENUMVALUE("CombineMode", "CM_Min" , 1) + DECLAREENUMVALUE("CombineMode", "CM_Multiply" , 2) + DECLAREENUMVALUE("CombineMode", "CM_Max" , 3) + + DECLAREENUM("pObjectDescrMask") + DECLAREENUMVALUE("pObjectDescrMask", "OD_XML" , 1) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Pivot" , 2) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Mass" , 4) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Collision" , 8) + DECLAREENUMVALUE("pObjectDescrMask", "OD_CCD" , 16) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Material" , 32) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Optimization" , 64) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Capsule" , 128) + DECLAREENUMVALUE("pObjectDescrMask", "OD_ConvexCylinder" , 256) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Wheel" , 512) + + + DECLAREENUM("DIRECTION") + DECLAREENUMVALUE("DIRECTION", "DIR_X" , 0) + DECLAREENUMVALUE("DIRECTION", "DIR_Y" , 1) + DECLAREENUMVALUE("DIRECTION", "DIR_Z" , 2) + + + //---------------------------------------------------------------- + // + // Wheel related types + // + + + DECLAREOBJECTTYPE(pTireFunction) + DECLARECTOR_0(__newpTireFunction) + DECLAREMEMBER(pTireFunction,float,extremumSlip) + DECLAREMEMBER(pTireFunction,float,extremumValue) + DECLAREMEMBER(pTireFunction,float,asymptoteSlip) + DECLAREMEMBER(pTireFunction,float,stiffnessFactor) + DECLAREMEMBER(pTireFunction,int,xmlLink) + DECLAREMETHOD_0(pTireFunction,void,setToDefault) + + + + + + DECLAREENUM("WheelFlags") + DECLAREENUMVALUE("WheelFlags", "WF_SteerableInput" , 1) + DECLAREENUMVALUE("WheelFlags", "WF_SteerableAuto" , 2) + DECLAREENUMVALUE("WheelFlags", "WF_AffectedByHandbrake" , 4) + DECLAREENUMVALUE("WheelFlags", "WF_Accelerated" , 8) + DECLAREENUMVALUE("WheelFlags", "WF_BuildLowerHalf" , 256) + DECLAREENUMVALUE("WheelFlags", "WF_UseWheelShape" , 512) + DECLAREENUMVALUE("WheelFlags", "WF_VehicleControlled" , 1024) + + + DECLAREENUM("WheelShapeFlags") + DECLAREENUMVALUE("WheelShapeFlags", "WSF_WheelAxisContactNormal" , 1) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_InputLatSlipVelocity" , 1) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_InputLongSlipVelocity" , 2) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_UnscaledSpringBehavior" , 4) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_EmulateLegacyWheel" , 8) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_ClampedFriction" , 16) + + + + DECLAREENUM("pConvexFlags") + DECLAREENUMVALUE("pConvexFlags", "CF_FlipNormals" , CF_FlipNormals) + DECLAREENUMVALUE("pConvexFlags", "CF_16BitIndices" , CF_16BitIndices) + DECLAREENUMVALUE("pConvexFlags", "CF_ComputeConvex" , CF_ComputeConvex) + DECLAREENUMVALUE("pConvexFlags", "CF_InflateConvex" , CF_InflateConvex) + DECLAREENUMVALUE("pConvexFlags", "CF_UncompressedNormals" , CF_UncompressedNormals) + + + + DECLAREOBJECTTYPE(pAxisReferencedLength) + DECLARECTOR_0(__newpAxisReferenceLength) + DECLAREMEMBER(pAxisReferencedLength,float,value) + DECLAREMEMBER(pAxisReferencedLength,CKBeObject*,reference) + DECLAREMEMBER(pAxisReferencedLength,int,referenceAxis) + DECLAREMETHOD_0(pAxisReferencedLength,bool,isValid) + DECLAREMETHOD_0(pAxisReferencedLength,void,setToDefault) + + DECLAREOBJECTTYPE(pWheelDescr) + DECLARECTOR_0(__newpWheelDescr) + DECLAREMEMBER(pWheelDescr,float,springRestitution) + DECLAREMEMBER(pWheelDescr,pAxisReferencedLength,radius) + DECLAREMEMBER(pWheelDescr,float,wheelSuspension) + DECLAREMEMBER(pWheelDescr,float,springDamping) + DECLAREMEMBER(pWheelDescr,float,springDamping) + DECLAREMEMBER(pWheelDescr,float,maxBrakeForce) + DECLAREMEMBER(pWheelDescr,float,frictionToFront) + DECLAREMEMBER(pWheelDescr,float,frictionToSide) + DECLAREMEMBER(pWheelDescr,float,inverseWheelMass) + DECLAREMEMBER(pWheelDescr,WheelFlags,wheelFlags) + DECLAREMEMBER(pWheelDescr,WheelShapeFlags,wheelShapeFlags) + DECLAREMEMBER(pWheelDescr,pTireFunction,latFunc) + DECLAREMEMBER(pWheelDescr,pTireFunction,longFunc) + DECLAREMETHOD_0(pWheelDescr,void,setToDefault) + DECLAREMETHOD_0(pWheelDescr,bool,isValid) + + + + + + + + + + + DECLAREOBJECTTYPE(pConvexCylinderSettings) + DECLARECTOR_0(__newpCollisionSettings) + DECLAREMEMBER(pConvexCylinderSettings,pAxisReferencedLength,radius) + DECLAREMEMBER(pConvexCylinderSettings,pAxisReferencedLength,height) + DECLAREMEMBER(pConvexCylinderSettings,int,approximation) + DECLAREMEMBER(pConvexCylinderSettings,VxVector,forwardAxis) + DECLAREMEMBER(pConvexCylinderSettings,CK3dEntity*,forwardAxisRef) + DECLAREMEMBER(pConvexCylinderSettings,VxVector,downAxis) + DECLAREMEMBER(pConvexCylinderSettings,CK3dEntity*,downAxisRef) + DECLAREMEMBER(pConvexCylinderSettings,VxVector,rightAxis) + DECLAREMEMBER(pConvexCylinderSettings,CK3dEntity*,rightAxisRef) + DECLAREMEMBER(pConvexCylinderSettings,bool,buildLowerHalfOnly) + DECLAREMEMBER(pConvexCylinderSettings,pConvexFlags,convexFlags) + DECLAREMETHOD_0(pConvexCylinderSettings,bool,isValid) + DECLAREMETHOD_0(pConvexCylinderSettings,void,setToDefault) + + DECLAREOBJECTTYPE(pCapsuleSettingsEx) + DECLARECTOR_0(__newpCapsuleSettingsEx) + DECLAREMEMBER(pCapsuleSettingsEx,pAxisReferencedLength,radius) + DECLAREMEMBER(pCapsuleSettingsEx,pAxisReferencedLength,height) + + + DECLAREOBJECTTYPE(pMaterial) + DECLARECTOR_0(__newpMaterial) + DECLAREMEMBER(pMaterial,int,flags) + DECLAREMEMBER(pMaterial,float,dynamicFriction) + DECLAREMEMBER(pMaterial,float,staticFriction) + DECLAREMEMBER(pMaterial,float,restitution) + DECLAREMEMBER(pMaterial,float,dynamicFrictionV) + DECLAREMEMBER(pMaterial,float,staticFrictionV) + DECLAREMEMBER(pMaterial,CombineMode,frictionCombineMode) + DECLAREMEMBER(pMaterial,CombineMode,restitutionCombineMode) + DECLAREMEMBER(pMaterial,VxVector,dirOfAnisotropy) + DECLAREMEMBER(pMaterial,int,xmlLinkID) + + + DECLAREOBJECTTYPE(pOptimization) + DECLARECTOR_0(__newpOptimization) + DECLAREMEMBER(pOptimization,BodyLockFlags,transformationFlags) + DECLAREMEMBER(pOptimization,float,linDamping) + DECLAREMEMBER(pOptimization,float,angDamping) + DECLAREMEMBER(pOptimization,float,linSleepVelocity) + DECLAREMEMBER(pOptimization,float,angSleepVelocity) + DECLAREMEMBER(pOptimization,float,sleepEnergyThreshold) + DECLAREMEMBER(pOptimization,int,dominanceGroup) + DECLAREMEMBER(pOptimization,int,solverIterations) + DECLAREMEMBER(pOptimization,int,compartmentGroup) + + DECLAREOBJECTTYPE(pMassSettings) + DECLARECTOR_0(__newpMassSettings) + DECLAREMEMBER(pMassSettings,float,newDensity) + DECLAREMEMBER(pMassSettings,float,totalMass) + DECLAREMEMBER(pMassSettings,VxVector,localPosition) + DECLAREMEMBER(pMassSettings,VxVector,localOrientation) + DECLAREMEMBER(pMassSettings,CK_ID,massReference) + + DECLAREOBJECTTYPE(pPivotSettings) + DECLARECTOR_0(__newpPivotSettings) + DECLAREMEMBER(pPivotSettings,VxVector,localPosition) + DECLAREMEMBER(pPivotSettings,VxVector,localOrientation) + DECLAREMEMBER(pPivotSettings,CK_ID,pivotReference) + + + DECLAREOBJECTTYPE(pCCDSettings) + DECLARECTOR_0(__newpCCD) + DECLAREMEMBER(pCCDSettings,float,motionThresold) + DECLAREMEMBER(pCCDSettings,int,flags) + DECLAREMEMBER(pCCDSettings,CK_ID,meshReference) + DECLAREMEMBER(pCCDSettings,float,scale) + + + + DECLAREOBJECTTYPE(pObjectDescr) + DECLARECTOR_0(__newpObjectDescr) + DECLAREMEMBER(pObjectDescr,HullType,hullType) + DECLAREMEMBER(pObjectDescr,float,density) + DECLAREMEMBER(pObjectDescr,BodyFlags,flags) + DECLAREMEMBER(pObjectDescr,VxVector,massOffset) + DECLAREMEMBER(pObjectDescr,VxVector,shapeOffset) + DECLAREMEMBER(pObjectDescr,float,skinWidth) + DECLAREMEMBER(pObjectDescr,float,newDensity) + DECLAREMEMBER(pObjectDescr,float,totalMass) + DECLAREMEMBER(pObjectDescr,int,collisionGroup) + DECLAREMEMBER(pObjectDescr,int,hirarchy) + + DECLAREMEMBER(pObjectDescr,int,mask) + + + + DECLAREMEMBER(pObjectDescr,pCollisionSettings,collision) + DECLAREMETHOD_0(pObjectDescr,pCollisionSettings&,getCollision) + DECLAREMETHOD_1(pObjectDescr,void,setCollision,pCollisionSettings) + + DECLAREMEMBER(pObjectDescr,pMaterial,material) + DECLAREMETHOD_0(pObjectDescr,pMaterial&,getMaterial) + DECLAREMETHOD_1(pObjectDescr,void,setMaterial,pMaterial) + + DECLAREMEMBER(pObjectDescr,pMassSettings,mass) + DECLAREMETHOD_0(pObjectDescr,pMassSettings&,getMass) + DECLAREMETHOD_1(pObjectDescr,void,setMass,pMassSettings) + + DECLAREMEMBER(pObjectDescr,pCCDSettings,ccd) + DECLAREMETHOD_0(pObjectDescr,pCCDSettings&,getCollision) + DECLAREMETHOD_1(pObjectDescr,void,setCollision,pCCDSettings) + + DECLAREMEMBER(pObjectDescr,pOptimization,optimization) + DECLAREMETHOD_0(pObjectDescr,pOptimization&,getOptimization) + DECLAREMETHOD_1(pObjectDescr,void,setOptimization,pOptimization) + + DECLAREMEMBER(pObjectDescr,pPivotSettings,pivot) + DECLAREMETHOD_0(pObjectDescr,pPivotSettings&,getPivot) + DECLAREMETHOD_1(pObjectDescr,void,setPivot,pPivotSettings) + + DECLAREMEMBER(pObjectDescr,pCapsuleSettingsEx,capsule) + DECLAREMETHOD_0(pObjectDescr,pCapsuleSettingsEx&,getCapsule) + DECLAREMETHOD_1(pObjectDescr,void,setCapsule,pCapsuleSettingsEx) + + DECLAREMEMBER(pObjectDescr,pConvexCylinderSettings,convexCylinder) + DECLAREMETHOD_0(pObjectDescr,pConvexCylinderSettings&,getConvexCylinder) + DECLAREMETHOD_1(pObjectDescr,void,setConvexCylinder,pConvexCylinderSettings) + + + DECLAREMETHOD_1(CK3dEntity,CKParameterOut*,GetAttributeParameter,int) + + + //#define REGISTERVSLGUID(iGUID, iClassName) VSLM->RegisterGUID(iGUID, iClassName); + + + + + + + + + + + + + + STOPVSLBIND + + +} + + +PhysicManager*GetPhysicManager() +{ + return GetPMan(); +} diff --git a/usr/Src/Core/Manager/PhysicManagerVTRegisterVSL.cpp b/usr/Src/Core/Manager/PhysicManagerVTRegisterVSL.cpp new file mode 100644 index 0000000..f1c5ae0 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerVTRegisterVSL.cpp @@ -0,0 +1,901 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + +//#include "pVehicle.h" + + +#include "Bind.h" + +PhysicManager *ourMan = NULL; + +typedef ForceMode PForceMode; +typedef D6MotionMode PJMotion; +typedef D6DriveType PDriveType; + +// a {d1=35549095 d2=1877427728 d=0x0012fc9c } CKGUID + +#define BEH_GUID_VSL CKGUID(35549095,1877427728) + + +CKGUID getGuidByID(int op) +{ + + CKBeObject *obj = (CKBeObject*)GetPMan()->GetContext()->GetObject(op); + + CKGUID a; + if (obj) + { + CKBehavior *beh = (CKBehavior*)(obj); + if (beh) + { + a = beh->GetPrototypeGuid(); + + } + } + +return CKGUID(); + +} + + +int doVSLScript(int vslBehID) +{ + + //---------------------------------------------------------------- + // + // our script, simple addition of two inputs + // + XString vslScript; + vslScript << "void main(){ c = a + b; }" ; + + + int result = 0; + + + + CKBehaviorIO *scriptIn; + //sprintf(tmpName,"%s-beh",NameChar); + + /* + CKBehavior *MyScript = (CKBehavior *) ctx()->CreateObject(CKCID_BEHAVIOR,"MyScript"); + + MyScript->SetType(CKBEHAVIORTYPE_SCRIPT); + scriptIn=MyScript->CreateInput("Start"); + MyScript->UseGraph(); + MyScript->SetCompatibleClassID(CKCID_BEOBJECT); + */ + + + + + //---------------------------------------------------------------- + // + // create script + // + //CK_OBJECTCREATION_OPTIONS crOptions = CK_OBJECTCREATION_DYNAMIC; + //CKBehavior *script = (CKBehavior *)ctx()->CreateObject(CKCID_BEHAVIOR,NULL,CK_OBJECTCREATION_DYNAMIC); + CKBehavior *script = (CKBehavior *)ctx()->GetObject(vslBehID); + //CKERROR error = script->InitFromGuid(BEH_GUID_VSL); + + // create ins/outs + // + script->CreateInputParameter("a",CKPGUID_INT); + script->CreateInputParameter("b",CKPGUID_INT); + + script->CreateOutputParameter("c",CKPGUID_INT); + + script->SetName("Created_Rotate"); + + //script->SetAsTargetable(); + //script->UseTarget(); + + //error= MyScript->AddSubBehavior(script); + //ctx()->GetCurrentLevel()->AddObject(MyScript); + + + //---------------------------------------------------------------- + // + // activate RunVSL Settings "Run-Time Script Change" + // + bool dynaFlag=true; + + //script->SetLocalParameterValue(0,&dynaFlag); + //script->SetLocalParameterValue(1,&dynaFlag); + + int count = script->GetInputParameterCount(); + int lcount = script->GetLocalParameterCount(); + + //---------------------------------------------------------------- + // + // Pass the script content + // + vtTools::BehaviorTools::SetInputParameterValue(script,0,vslScript.Str()); + //---------------------------------------------------------------- + // + // Pass arguments + // + vtTools::BehaviorTools::SetInputParameterValue(script,1,10); + vtTools::BehaviorTools::SetInputParameterValue(script,2,11); + + //---------------------------------------------------------------- + // + // execute + // + script->Execute(0.5f); + result = vtTools::BehaviorTools::GetOutputParameterValue(script,0); + + /* + CKFile* file = ctx()->CreateCKFile(); + + file->StartSave("c:\\1.nms"); + file->SaveObject((CKObject *) MyScript); + file->EndSave(); + ctx()->DeleteCKFile(file); + */ + + + return result; + +} + + + +pRigidBody *getBody(CK3dEntity*ent){ + pRigidBody *body = GetPMan()->getBody(ent); + if (body) + { + return body; + }else{ + return NULL; + } +} + +void __newpSpring(BYTE *iAdd) +{ + new (iAdd) pSpring(); +} +void __newpSoftLimit(BYTE *iAdd) +{ + new (iAdd) pJD6SoftLimit(); +} + +void __newpDrive(BYTE *iAdd) +{ + new (iAdd) pJD6Drive(); +} +void __newpJointLimit(BYTE *iAdd) +{ + new (iAdd) pJointLimit(); +} + +void __newpMotor(BYTE *iAdd) +{ + new (iAdd) pMotor(); +} + + +pSerializer *GetSerializer() +{ + return pSerializer::Instance(); +} + + + +void __newpClothDescr(BYTE *iAdd) +{ + new(iAdd)pClothDesc(); +} + +#define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) + + +void PhysicManager::_RegisterVSL() +{ + ourMan = GetPMan(); + + + _RegisterVSLCommon(); + _RegisterVSLVehicle(); + + STARTVSLBIND(m_Context) + + + DECLAREFUN_C_1(CKGUID,getGuidByID,int) + + DECLAREFUN_C_1(int,doVSLScript,int) + + + + ////////////////////////////////////////////////////////////////////////// + // + // Bindings for pVehicle related classes : + // + // + + DECLAREENUM("pClothAttachmentFlag") + DECLAREENUMVALUE("pClothAttachmentFlag", "PCAF_ClothAttachmentTwoway" ,1 ) + DECLAREENUMVALUE("pClothAttachmentFlag", "PCAF_ClothAttachmentTearable" ,2 ) + + DECLAREENUM("pClothFlag") + DECLAREENUMVALUE("pClothFlag", "PCF_Pressure" ,1 ) + + DECLAREENUMVALUE("pClothFlag", "PCF_Static",2) + DECLAREENUMVALUE("pClothFlag", "PCF_DisableCollision",4) + DECLAREENUMVALUE("pClothFlag", "PCF_SelfCollision",8) + DECLAREENUMVALUE("pClothFlag", "PCF_Gravity",32) + DECLAREENUMVALUE("pClothFlag", "PCF_Bending",64) + DECLAREENUMVALUE("pClothFlag", "PCF_BendingOrtho",128) + DECLAREENUMVALUE("pClothFlag", "PCF_Damping",256) + DECLAREENUMVALUE("pClothFlag", "PCF_CollisionTwoway",512) + DECLAREENUMVALUE("pClothFlag", "PCF_TriangleCollision",2048) + DECLAREENUMVALUE("pClothFlag", "PCF_Tearable",4096) + DECLAREENUMVALUE("pClothFlag", "PCF_Hardware",8192) + DECLAREENUMVALUE("pClothFlag", "PCF_ComDamping",16384) + DECLAREENUMVALUE("pClothFlag", "PCF_ValidBounds",32768) + DECLAREENUMVALUE("pClothFlag", "PCF_FluidCollision",65536) + DECLAREENUMVALUE("pClothFlag", "PCF_DisableDynamicCCD",131072) + DECLAREENUMVALUE("pClothFlag", "PCF_AddHere",262144) + DECLAREENUMVALUE("pClothFlag", "PCF_AttachToParentMainShape",524288) + DECLAREENUMVALUE("pClothFlag", "PCF_AttachToCollidingShapes",1048576) + DECLAREENUMVALUE("pClothFlag", "PCF_AttachToCore",2097152) + DECLAREENUMVALUE("pClothFlag", "PCF_AttachAttributes",4194304) + + + + + + + DECLAREOBJECTTYPE(pClothDesc) + + DECLAREMEMBER(pClothDesc,float,thickness) + DECLAREMEMBER(pClothDesc,float,density) + DECLAREMEMBER(pClothDesc,float,bendingStiffness) + + DECLAREMEMBER(pClothDesc,float,stretchingStiffness) + DECLAREMEMBER(pClothDesc,float,dampingCoefficient) + DECLAREMEMBER(pClothDesc,float,friction) + DECLAREMEMBER(pClothDesc,float,pressure) + DECLAREMEMBER(pClothDesc,float,tearFactor) + DECLAREMEMBER(pClothDesc,float,collisionResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,attachmentResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,attachmentTearFactor) + DECLAREMEMBER(pClothDesc,float,toFluidResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,fromFluidResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,minAdhereVelocity) + DECLAREMEMBER(pClothDesc,int,solverIterations) + DECLAREMEMBER(pClothDesc,VxVector,externalAcceleration) + DECLAREMEMBER(pClothDesc,VxVector,windAcceleration) + DECLAREMEMBER(pClothDesc,float,wakeUpCounter) + DECLAREMEMBER(pClothDesc,float,sleepLinearVelocity) + DECLAREMEMBER(pClothDesc,int,collisionGroup) + DECLAREMEMBER(pClothDesc,VxBbox,validBounds) + DECLAREMEMBER(pClothDesc,float,relativeGridSpacing) + DECLAREMEMBER(pClothDesc,pClothFlag,flags) + DECLAREMEMBER(pClothDesc,pClothAttachmentFlag,attachmentFlags) + DECLAREMEMBER(pClothDesc,VxColor,tearVertexColor) + DECLAREMEMBER(pClothDesc,CK_ID,worldReference) + + + DECLAREMETHOD_0(pClothDesc,void,setToDefault) + DECLARECTOR_0(__newpClothDescr) + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Vehicle : + // + + DECLAREMETHOD_1(PhysicManager,pVehicle*,getVehicle,CK3dEntity*) + DECLAREMETHOD_1(PhysicManager,pWheel2*,getWheel,CK3dEntity*) + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Bindings for pVehicle related classes : + // + // + + + + + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Bindings for pVehicle related classes : + // + // + DECLAREOBJECTTYPE(pJointLimit) + DECLARECTOR_0(__newpJointLimit) + DECLAREMEMBER(pJointLimit,float,hardness) + DECLAREMEMBER(pJointLimit,float,restitution) + DECLAREMEMBER(pJointLimit,float,value) + + DECLAREOBJECTTYPE(pJD6Drive) + DECLARECTOR_0(__newpDrive) + DECLAREMEMBER(pJD6Drive,float,damping) + DECLAREMEMBER(pJD6Drive,float,spring) + DECLAREMEMBER(pJD6Drive,float,forceLimit) + DECLAREMEMBER(pJD6Drive,int,driveType) + + DECLAREOBJECTTYPE(pJD6SoftLimit) + DECLARECTOR_0(__newpSoftLimit) + DECLAREMEMBER(pJD6SoftLimit,float,damping) + DECLAREMEMBER(pJD6SoftLimit,float,spring) + DECLAREMEMBER(pJD6SoftLimit,float,value) + DECLAREMEMBER(pJD6SoftLimit,float,restitution) + + + DECLAREOBJECTTYPE(pSpring) + DECLARECTOR_0(__newpSpring) + //DECLARECTOR_3(__newpSpringSettings3,float,float,float) + DECLAREMEMBER(pSpring,float,damper) + DECLAREMEMBER(pSpring,float,spring) + DECLAREMEMBER(pSpring,float,targetValue) + + DECLAREOBJECTTYPE(pMotor) + DECLARECTOR_0(__newpMotor) + DECLAREMEMBER(pMotor,float,maximumForce) + DECLAREMEMBER(pMotor,float,targetVelocity) + DECLAREMEMBER(pMotor,float,freeSpin) + + ////////////////////////////////////////////////////////////////////////// + // + // Serializer : + // + DECLAREPOINTERTYPE(pSerializer) + DECLAREFUN_C_0(pSerializer*, GetSerializer) + DECLAREMETHOD_2(pSerializer,void,overrideBody,pRigidBody*,int) + DECLAREMETHOD_2(pSerializer,int,loadCollection,const char*,int) + DECLAREMETHOD_1(pSerializer,int,saveCollection,const char*) + DECLAREMETHOD_2(pSerializer,void,parseFile,const char*,int) + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Factory + // + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // ENUMERATION + // + + DECLAREENUM("D6DriveType") + + DECLAREENUMVALUE("D6DriveType", "D6DT_Position" ,1 ) + DECLAREENUMVALUE("D6DriveType", "D6DT_Velocity" ,2 ) + + + DECLAREENUM("PForceMode") + + DECLAREENUMVALUE("PForceMode", "PFM_Force" , 0) + DECLAREENUMVALUE("PForceMode", "PFM_Impulse" , 1) + DECLAREENUMVALUE("PForceMode", "PFM_VelocityChange" , 2) + DECLAREENUMVALUE("PForceMode", "PFM_SmoothImpulse" , 3) + DECLAREENUMVALUE("PForceMode", "PFM_SmoothVelocityChange" , 4) + DECLAREENUMVALUE("PForceMode", "PFM_Acceleration" , 5) + + DECLAREENUM("D6MotionMode") + + DECLAREENUMVALUE("D6MotionMode", "D6MM_Locked" , 0) + DECLAREENUMVALUE("D6MotionMode", "D6MM_Limited" , 1) + DECLAREENUMVALUE("D6MotionMode", "D6MM_Free" , 2) + + DECLAREENUM("JType") + DECLAREENUMVALUE("JType", "JT_Any" , -1) + DECLAREENUMVALUE("JType", "JT_Prismatic" , 0) + DECLAREENUMVALUE("JType", "JT_Revolute" , 1) + DECLAREENUMVALUE("JType", "JT_Cylindrical" , 2) + DECLAREENUMVALUE("JType", "JT_Spherical" , 3) + DECLAREENUMVALUE("JType", "JT_PointOnLine" , 4) + DECLAREENUMVALUE("JType", "JT_PointInPlane" , 5) + DECLAREENUMVALUE("JType", "JT_Distance" , 6) + DECLAREENUMVALUE("JType", "JT_Pulley" , 7) + DECLAREENUMVALUE("JType", "JT_Fixed" ,8 ) + DECLAREENUMVALUE("JType", "JT_D6" ,9 ) + + + ////////////////////////////////////////////////////////////////////////// + // + // Bindings for pVehicle related classes : + // + // + DECLAREMETHOD_2(pFactory,pVehicle*,createVehicle,CK3dEntity*,pVehicleDesc) + + + //DECLAREMETHOD_0(pVehicle,float,getWheelRollAngle) + //DECLAREMETHOD_0(pVehicle,float,getRpm) + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT CREATION + // + DECLAREMETHOD_11_WITH_DEF_VALS(pFactory,pJointDistance*,createDistanceJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,VxVector(),VxVector,VxVector(),float,0.0f,float,0.0f,pSpring,pSpring(),BOOL,"TRUE",float,"0.0",float,"0.0",const char *,"pJDistance") + DECLAREMETHOD_5(pFactory,pJointD6*,createD6Joint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,bool) + + DECLAREMETHOD_5_WITH_DEF_VALS(pFactory,pJointFixed*,createFixedJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,float,"0.0",float,"0,0",const char*,"PJFixed") + + DECLAREMETHOD_3_WITH_DEF_VALS(pFactory,pRigidBody*,createBody,CK3dEntity*,NODEFAULT,pObjectDescr,NODEFAULT,CK3dEntity*,NULL) + + DECLAREMETHOD_2(pFactory,pRigidBody*,createRigidBody,CK3dEntity*,pObjectDescr&) + + DECLAREMETHOD_2(pFactory,bool,loadMaterial,pMaterial&,const char*) + DECLAREMETHOD_2(pFactory,pMaterial,loadMaterial,const char*,int&) + + DECLAREMETHOD_2(pFactory,bool,loadFrom,pWheelDescr&,const char*) + DECLAREMETHOD_5(pFactory,pWheel*,createWheel,CK3dEntity *,CK3dEntity*,pWheelDescr,pConvexCylinderSettings,VxVector) + + DECLAREMETHOD_9_WITH_DEF_VALS(pFactory,pJointPulley*,createPulleyJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,BOOL,"TRUE",float,"0.0",float,"0.0") + DECLAREMETHOD_9_WITH_DEF_VALS(pFactory,pJointBall*,createBallJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,VxVector,"0,0,1",bool,"TRUE",float,"0.0",float,"0.0",const char*,"pJBall") + DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointRevolute*,createRevoluteJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,"TRUE",float,"0.0",float,"0.0",const char*,"pJRevolute") + DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointPrismatic*,createPrismaticJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,TRUE,float,"0.0",float,"0.0",const char*,"pJPrismatic") + DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointCylindrical*,createCylindricalJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,TRUE,float,"0.0",float,"0.0",,const char*,"pJCylindrical") + DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointPointInPlane*,createPointInPlaneJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,TRUE,float,"0.0",float,"0.0",const char*,"pJPointInPlane") + DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointPointOnLine*,createPointOnLineJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,NODEFAULT,VxVector,NODEFAULT,bool,TRUE,float,"0.0",float,"0.0",const char*,"pJPointOnLine") + + DECLAREMETHOD_2(pFactory,pCloth*,createCloth,CK3dEntity*,pClothDesc) + + + + ////////////////////////////////////////////////////////////////////////// + // + // Cloth + // + DECLAREMETHOD_4(pCloth,void,attachToCore,CK3dEntity*,float,float,float) + DECLAREMETHOD_2(pCloth,void,attachToShape,CK3dEntity*,pClothAttachmentFlag) + + + ////////////////////////////////////////////////////////////////////////// + // + // MANAGER + // + + + DECLAREMETHOD_0(PhysicManager,pWorld*,getDefaultWorld) + DECLAREMETHOD_2_WITH_DEF_VALS(PhysicManager,pRigidBody*,getBody,CK3dEntity*,NODEFAULT,bool,FALSE) + DECLAREMETHOD_1(PhysicManager,pWorld*,getWorldByBody,CK3dEntity*) + DECLAREMETHOD_1(PhysicManager,pWorld*,getWorld,CK_ID) + DECLAREMETHOD_1(PhysicManager,int,getAttributeTypeByGuid,CKGUID) + DECLAREMETHOD_2(PhysicManager,void,copyToAttributes,pObjectDescr,CK3dEntity*) + DECLAREMETHOD_1(CK3dEntity,CKBOOL,HasAttribute,int) + + DECLAREMETHOD_3_WITH_DEF_VALS(PhysicManager,pJoint*,getJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NULL,JType,JT_Any) + +// DECLAREMETHOD_0(PhysicManager,void,makeDongleTest) + + + ////////////////////////////////////////////////////////////////////////// + // + // World + // + + DECLAREMETHOD_1(pWorld,pRigidBody*,getBody,CK3dEntity*) + DECLAREMETHOD_1(pWorld,pVehicle*,getVehicle,CK3dEntity*) + DECLAREMETHOD_3(pWorld,pJoint*,getJoint,CK3dEntity*,CK3dEntity*,JType) + + DECLAREMETHOD_3(pWorld,void,setFilterOps,pFilterOp,pFilterOp,pFilterOp) + DECLAREMETHOD_1(pWorld,void,setFilterBool,bool) + DECLAREMETHOD_1(pWorld,void,setFilterConstant0,const pGroupsMask&) + DECLAREMETHOD_1(pWorld,void,setFilterConstant1,const pGroupsMask&) + + DECLAREMETHOD_1(pWorld,void,setGravity,VxVector) + DECLAREMETHOD_0(pWorld,VxVector,getGravity) + + + + + + + // + DECLAREMETHOD_5_WITH_DEF_VALS(pWorld,bool,raycastAnyBounds,const VxRay&,NODEFAULT,pShapesType,NODEFAULT,pGroupsMask,NODEFAULT,int,0xffffffff,float,NX_MAX_F32) + DECLAREMETHOD_8(pWorld,bool,overlapSphereShapes,CK3dEntity*,const VxSphere&,CK3dEntity*,pShapesType,CKGroup*,int,const pGroupsMask*,BOOL) + + //(const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,unsigned int groups=0xffffffff, float maxDist=NX_MAX_F32); + + + + DECLAREMETHOD_1(pJoint,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJoint,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_0(pJoint,VxVector,getGlobalAxis) + DECLAREMETHOD_0(pJoint,VxVector,getGlobalAnchor) + + + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT :: Revolute + // + DECLAREMETHOD_0(pJoint,pJointRevolute*,castRevolute) + DECLAREMETHOD_1(pJointRevolute,void,setGlobalAnchor,const VxVector&) + DECLAREMETHOD_1(pJointRevolute,void,setGlobalAxis,const VxVector&) + + + DECLAREMETHOD_1(pJointRevolute,void,setSpring,pSpring) + DECLAREMETHOD_1(pJointRevolute,void,setHighLimit,pJointLimit) + DECLAREMETHOD_1(pJointRevolute,void,setLowLimit,pJointLimit) + DECLAREMETHOD_1(pJointRevolute,void,setMotor,pMotor) + + DECLAREMETHOD_0(pJointRevolute,pSpring,getSpring) + DECLAREMETHOD_0(pJointRevolute,pJointLimit,getLowLimit) + DECLAREMETHOD_0(pJointRevolute,pJointLimit,getHighLimit) + DECLAREMETHOD_0(pJointRevolute,pMotor,getMotor) + DECLAREMETHOD_1(pJointRevolute,void,enableCollision,bool) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT :: Ball + // + DECLAREMETHOD_0(pJoint,pJointBall*,castBall) + + DECLAREMETHOD_1(pJointBall,void,setAnchor,VxVector) + + DECLAREMETHOD_1(pJointBall,void,setSwingLimitAxis,VxVector) + DECLAREMETHOD_1(pJointBall,bool,setSwingLimit,pJointLimit) + DECLAREMETHOD_1(pJointBall,bool,setTwistHighLimit,pJointLimit) + DECLAREMETHOD_1(pJointBall,bool,setTwistLowLimit,pJointLimit) + + + DECLAREMETHOD_0(pJointBall,pJointLimit,getSwingLimit) + DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistHighLimit) + DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistLowLimit) + + DECLAREMETHOD_1(pJointBall,bool,setSwingSpring,pSpring) + DECLAREMETHOD_1(pJointBall,bool,setTwistSpring,pSpring) + DECLAREMETHOD_1(pJointBall,void,setJointSpring,pSpring) + + DECLAREMETHOD_0(pJointBall,pSpring,getSwingSpring) + DECLAREMETHOD_0(pJointBall,pSpring,getTwistSpring) + DECLAREMETHOD_0(pJointBall,pSpring,getJointSpring) + + DECLAREMETHOD_1(pJointBall,void,enableCollision,bool) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Prismatic + // + // + DECLAREMETHOD_0(pJoint,pJointPrismatic*,castPrismatic) + + DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointPrismatic,void,enableCollision,bool) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Cylindrical + // + // + DECLAREMETHOD_0(pJoint,pJointCylindrical*,castCylindrical) + + DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointCylindrical,void,enableCollision,int) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Point In Plane + // + // + DECLAREMETHOD_0(pJoint,pJointPointInPlane*,castPointInPlane) + + DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointPointInPlane,void,enableCollision,bool) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Point In Plane + // + // + DECLAREMETHOD_0(pJoint,pJointPointOnLine*,castPointOnLine) + + DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointPointOnLine,void,enableCollision,bool) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT BASE + // + // + DECLAREMETHOD_1(pJoint,void,setLocalAnchor0,VxVector) + + DECLAREMETHOD_2(pJoint,void,setBreakForces,float,float) + DECLAREMETHOD_2(pJoint,void,getBreakForces,float&,float&) + DECLAREMETHOD_3(pJoint,int,addLimitPlane,VxVector,VxVector,float) + DECLAREMETHOD_2_WITH_DEF_VALS(pJoint,void,setLimitPoint,VxVector,NODEFAULT,bool,true) + DECLAREMETHOD_0(pJoint,void,purgeLimitPlanes) + DECLAREMETHOD_0(pJoint,void,resetLimitPlaneIterator) + DECLAREMETHOD_0(pJoint,int,hasMoreLimitPlanes) + DECLAREMETHOD_3(pJoint,int,getNextLimitPlane,VxVector&,float&,float&) + DECLAREMETHOD_0(pJoint,int,getType) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT :: DISTANCE + // + DECLAREMETHOD_0(pJoint,pJointDistance*,castDistanceJoint) + + DECLAREMETHOD_1(pJointDistance,void,setMinDistance,float) + DECLAREMETHOD_1(pJointDistance,void,setMaxDistance,float) + DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor0,VxVector) + DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor1,VxVector) + DECLAREMETHOD_1(pJointDistance,void,setSpring,pSpring) + DECLAREMETHOD_0(pJointDistance,float,getMinDistance) + DECLAREMETHOD_0(pJointDistance,float,getMaxDistance) + DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor0) + DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor1) + DECLAREMETHOD_0(pJointDistance,pSpring,getSpring) + DECLAREMETHOD_1(pJointDistance,void,enableCollision,bool) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT PULLEY + // + + DECLAREMETHOD_0(pJoint,pJointPulley*,castPulley) + + DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorA,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorB,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setPulleyA,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setPulleyB,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setStiffness,float) + DECLAREMETHOD_1(pJointPulley,void,setRatio,float) + DECLAREMETHOD_1(pJointPulley,void,setRigid,int) + DECLAREMETHOD_1(pJointPulley,void,setDistance,float) + DECLAREMETHOD_1(pJointPulley,void,setMotor,pMotor) + DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorA) + DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorB) + DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyA) + DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyB) + DECLAREMETHOD_0(pJointPulley,float,getStiffness) + + DECLAREMETHOD_0(pJointPulley,float,getRatio) + DECLAREMETHOD_0(pJointPulley,float,getDistance) + DECLAREMETHOD_1(pJointPulley,void,enableCollision,bool) + DECLAREMETHOD_0(pJointPulley,pMotor,getMotor) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT D6 + // + + DECLAREMETHOD_0(pJoint,pJointD6*,castD6Joint) + + DECLAREMETHOD_1(pJointD6,void,setTwistMotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setSwing1MotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setSwing2MotionMode,D6MotionMode) + + DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) + + + DECLAREMETHOD_1(pJointD6,void,setXMotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setYMotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setZMotionMode,D6MotionMode) + + DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) + + ////////////////////////////////////////////////////////////////////////// + //softwLimits + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getLinearLimit) + DECLAREMETHOD_1(pJointD6,int,setLinearLimit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing1Limit) + DECLAREMETHOD_1(pJointD6,int,setSwing1Limit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing2Limit) + DECLAREMETHOD_1(pJointD6,int,setSwing2Limit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistHighLimit) + DECLAREMETHOD_1(pJointD6,int,setTwistHighLimit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistLowLimit) + DECLAREMETHOD_1(pJointD6,int,setTwistLowLimit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getXDrive) + DECLAREMETHOD_1(pJointD6,int,setXDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getYDrive) + DECLAREMETHOD_1(pJointD6,int,setYDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getZDrive) + DECLAREMETHOD_1(pJointD6,int,setZDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getSwingDrive) + DECLAREMETHOD_1(pJointD6,int,setSwingDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getTwistDrive) + DECLAREMETHOD_1(pJointD6,int,setTwistDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getSlerpDrive) + DECLAREMETHOD_1(pJointD6,int,setSlerpDrive,pJD6Drive) + + DECLAREMETHOD_1(pJointD6,void,setDrivePosition,VxVector) + DECLAREMETHOD_1(pJointD6,void,setDriveRotation,VxQuaternion) + + DECLAREMETHOD_1(pJointD6,void,setDriveLinearVelocity,VxVector) + DECLAREMETHOD_1(pJointD6,void,setDriveAngularVelocity,VxVector) + + DECLAREMETHOD_1(pJointD6,void,enableCollision,bool) + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Rigid Body Exports + // + // + + + /************************************************************************/ + /* Forces */ + /************************************************************************/ + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addForce,const VxVector&,NODEFAULT, PForceMode, 0,bool,true) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addTorque,const VxVector&,NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalForce,const VxVector&,NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalTorque,const VxVector&,NODEFAULT, PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtPos, const VxVector&,NODEFAULT,const VxVector&,NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtLocalPos,const VxVector,NODEFAULT, const VxVector&, NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtPos, const VxVector&, NODEFAULT,const VxVector&,NODEFAULT, PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtLocalPos, const VxVector&, NODEFAULT,const VxVector&, NODEFAULT,PForceMode,0,bool,true) + + + /************************************************************************/ + /* Momentum */ + /************************************************************************/ + DECLAREMETHOD_1(pRigidBody,void,setAngularMomentum,const VxVector&) + DECLAREMETHOD_1(pRigidBody,void,setLinearMomentum,const VxVector&) + DECLAREMETHOD_0(pRigidBody,VxVector,getAngularMomentum) + DECLAREMETHOD_0(pRigidBody,VxVector,getLinearMomentum) + + /************************************************************************/ + /* collision + callbacks */ + /************************************************************************/ + DECLAREMETHOD_1(pRigidBody,void,setContactReportThreshold,float) + DECLAREMETHOD_0(pRigidBody,float,setContactReportThreshold) + + DECLAREMETHOD_1(pRigidBody,void,setContactReportFlags,pContactPairFlags) + DECLAREMETHOD_0(pRigidBody,int,getContactReportFlags) + + + DECLAREMETHOD_2(pRigidBody,void,setContactScript,int,int) + DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setTriggerScript,int,NODEFAULT,int,NODEFAULT,CK3dEntity*,NULL) + DECLAREMETHOD_1(pRigidBody,void,setContactModificationScript,int) + + DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setSkinWidth,const float,NODEFAULT,CK3dEntity*,NULL) + + /************************************************************************/ + /* Pose : */ + /************************************************************************/ + DECLAREMETHOD_1(pRigidBody,void,setPosition,const VxVector&) + DECLAREMETHOD_1(pRigidBody,void,setRotation,const VxQuaternion&) + DECLAREMETHOD_1(pRigidBody,void,translateLocalShapePosition,VxVector) + + /************************************************************************/ + /* Velocity : */ + /************************************************************************/ + + DECLAREMETHOD_1(pRigidBody,void,setLinearVelocity,const VxVector&) + DECLAREMETHOD_1(pRigidBody,void,setAngularVelocity,const VxVector&) + DECLAREMETHOD_0(pRigidBody,float,getMaxAngularSpeed) + DECLAREMETHOD_0(pRigidBody,VxVector,getLinearVelocity) + DECLAREMETHOD_0(pRigidBody,VxVector,getAngularVelocity) + + /************************************************************************/ + /* Mass */ + /************************************************************************/ + + + DECLAREMETHOD_1(pRigidBody,void,setCMassOffsetGlobalPosition,VxVector) + DECLAREMETHOD_1(pRigidBody,void,setCMassGlobalPosition,VxVector) + DECLAREMETHOD_0(pRigidBody,VxVector,getCMassLocalPosition) + DECLAREMETHOD_0(pRigidBody,VxVector,getCMassGlobalPosition) + //DECLAREMETHOD_1(pRigidBody,void,setMass,float) + DECLAREMETHOD_0(pRigidBody,float,getMass) + DECLAREMETHOD_1(pRigidBody,void,setMassSpaceInertiaTensor,VxVector) + DECLAREMETHOD_0(pRigidBody,VxVector,getMassSpaceInertiaTensor) + DECLAREMETHOD_1(pRigidBody,void,setCMassOffsetLocalPosition,VxVector) + + + DECLAREMETHOD_1(pRigidBody,void,setMassOffset,VxVector) + DECLAREMETHOD_1(pRigidBody,void,setMaxAngularSpeed,float) + + /************************************************************************/ + /* Hull */ + /************************************************************************/ + DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) + + + DECLAREMETHOD_0(pRigidBody,pWorld*,getWorld) + DECLAREMETHOD_1(pRigidBody,pJoint*,isConnected,CK3dEntity*) + DECLAREMETHOD_2(pRigidBody,pJoint*,isConnected,CK3dEntity*,int) + //DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) + //DECLAREMETHOD_1_WITH_DEF_VALS(pRigidBody,float,getMass,CK3dEntity*,NULL) + DECLAREMETHOD_0(pRigidBody,int,getHullType) + + DECLAREMETHOD_2(pRigidBody,void,setGroupsMask,CK3dEntity*,const pGroupsMask&) + + DECLAREMETHOD_0(pRigidBody,int,getFlags) + DECLAREMETHOD_1(pRigidBody,VxVector,getPointVelocity,const VxVector&) + DECLAREMETHOD_1(pRigidBody,VxVector,getLocalPointVelocity,const VxVector&) + + + DECLAREMETHOD_0(pRigidBody,bool,isCollisionEnabled) + + DECLAREMETHOD_1(pRigidBody,void,setKinematic,int) + DECLAREMETHOD_0(pRigidBody,int,isKinematic) + + DECLAREMETHOD_1(pRigidBody,void,enableGravity,int) + DECLAREMETHOD_0(pRigidBody,bool,isAffectedByGravity) + + DECLAREMETHOD_1(pRigidBody,void,setSleeping,int) + DECLAREMETHOD_0(pRigidBody,int,isSleeping) + DECLAREMETHOD_1(pRigidBody,void,setLinearDamping,float) + DECLAREMETHOD_1(pRigidBody,void,setAngularDamping,float) + DECLAREMETHOD_1(pRigidBody,void,lockTransformation,BodyLockFlags) + DECLAREMETHOD_1(pRigidBody,int,isBodyFlagOn,int) + + DECLAREMETHOD_1_WITH_DEF_VALS(pRigidBody,void,wakeUp,float,NX_SLEEP_INTERVAL) + DECLAREMETHOD_1(pRigidBody,void,setSleepEnergyThreshold,float) + DECLAREMETHOD_1(pRigidBody,void,setSolverIterationCount,int) + DECLAREMETHOD_5_WITH_DEF_VALS(pRigidBody,bool,onSubShapeTransformation,bool,TRUE,bool,TRUE,bool,TRUE,CK3dEntity*,NULL,bool,true) + + + DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setCollisionsGroup,int,NODEFAULT,CK3dEntity*,) + DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,enableCollision,bool,NODEFAULT,CK3dEntity*,NULL) + + DECLAREMETHOD_0(pRigidBody,bool,hasWheels); + DECLAREMETHOD_0(pRigidBody,int,getNbWheels); + + DECLAREMETHOD_0(pRigidBody,int,getNbSubShapes); + DECLAREMETHOD_0(pRigidBody,int,getNbSubBodies); + + + + + + DECLAREMETHOD_0(pRigidBody,int,getCollisionsGroup) + DECLAREMETHOD_2(pRigidBody,int,updateMassFromShapes,float,float) + DECLAREMETHOD_5_WITH_DEF_VALS(pRigidBody,int,addSubShape,CKMesh*,NULL,pObjectDescr,NODEFAULT,CK3dEntity*,NULL,VxVector,VxVector(),VxQuaternion,VxQuaternion()) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,int,removeSubShape,CKMesh*,NODEFAULT,float,0.0,float,0.0) + + + + /************************************************************************/ + /* Joint */ + /************************************************************************/ + DECLAREMETHOD_0(pRigidBody,int,getNbJoints); + //DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,pJoint*,getJointAtIndex,int,NODEFAULT,int&,NODEFAULT,CK3dEntity**,NULL) + DECLAREMETHOD_1(pRigidBody,pJoint*,getJointAtIndex,int) + DECLAREMETHOD_2(pRigidBody,pJoint*,getJoint,CK3dEntity*,JType) + DECLAREMETHOD_1(pRigidBody,void,deleteJoint,pJoint*) + DECLAREMETHOD_2(pRigidBody,void,deleteJoint,CK3dEntity*,JType) + + STOPVSLBIND +} diff --git a/usr/Src/Core/Manager/PhysicManagerVehcileVSL.cpp b/usr/Src/Core/Manager/PhysicManagerVehcileVSL.cpp new file mode 100644 index 0000000..9c7d2cb --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerVehcileVSL.cpp @@ -0,0 +1,345 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + +#include "pVehicleAll.h" + + +void __newpVehicleDescr(BYTE *iAdd) +{ + + new (iAdd)pVehicleDesc(); +} + +void __newpVehicleMotorDesc(BYTE *iAdd) +{ + new (iAdd)pVehicleMotorDesc(); +} + +void __newpVehicleGearDesc(BYTE *iAdd) +{ + new(iAdd)pVehicleGearDesc(); +} +void PhysicManager::_RegisterVSLVehicle() +{ + STARTVSLBIND(m_Context) + + //---------------------------------------------------------------- + // + // vehicle base types + // + + DECLAREPOINTERTYPE(pVehicleMotorDesc) + + DECLAREMEMBER(pVehicleMotorDesc,float,maxRpmToGearUp) + DECLAREMEMBER(pVehicleMotorDesc,float,minRpmToGearDown) + DECLAREMEMBER(pVehicleMotorDesc,float,maxRpm) + DECLAREMEMBER(pVehicleMotorDesc,float,minRpm) + DECLAREMETHOD_0(pVehicleMotorDesc,void,setToCorvette) + + DECLAREPOINTERTYPE(pVehicleGearDesc) + DECLAREMEMBER(pVehicleGearDesc,int,nbForwardGears) + DECLAREMETHOD_0(pVehicleGearDesc,void,setToDefault) + DECLAREMETHOD_0(pVehicleGearDesc,void,setToCorvette) + DECLAREMETHOD_0(pVehicleGearDesc,bool,isValid) + + + DECLAREOBJECTTYPE(pVehicleDesc) + DECLARECTOR_0(__newpVehicleDescr) + DECLAREMEMBER(pVehicleDesc,float,digitalSteeringDelta) + DECLAREMEMBER(pVehicleDesc,VxVector,steeringSteerPoint) + DECLAREMEMBER(pVehicleDesc,VxVector,steeringTurnPoint) + DECLAREMEMBER(pVehicleDesc,float,steeringMaxAngle) + DECLAREMEMBER(pVehicleDesc,float,transmissionEfficiency) + DECLAREMEMBER(pVehicleDesc,float,differentialRatio) + DECLAREMEMBER(pVehicleDesc,float,maxVelocity) + DECLAREMEMBER(pVehicleDesc,float,motorForce) + + DECLAREMETHOD_0(pVehicleDesc,pVehicleGearDesc*,getGearDescription) + DECLAREMETHOD_0(pVehicleDesc,pVehicleMotorDesc*,getMotorDescr) + DECLAREMETHOD_0(pVehicleDesc,void,setToDefault) + + + //---------------------------------------------------------------- + // + // vehicle specific + // + + DECLAREMETHOD_1(pVehicle,void,setPreScript,int) + DECLAREMETHOD_1(pVehicle,void,setPostScript,int) + DECLAREMETHOD_1(pVehicle,void,setOverrideMask,int) + + + + DECLAREMETHOD_1(pVehicle,int,initEngine,int) + + DECLAREMETHOD_0(pVehicle,BOOL,isValidEngine) + + DECLAREMETHOD_0(pVehicle,pEngine*,getEngine) + DECLAREMETHOD_0(pVehicle,pGearBox*,getGearBox) + + DECLAREMETHOD_0(pVehicle,int,getStateFlags) + + DECLAREMETHOD_1(pVehicle,void,setClutch,float) + DECLAREMETHOD_0(pVehicle,float,getClutch) + + //---------------------------------------------------------------- + // + // egine + // + DECLAREMETHOD_1(pEngine,void,SetInertia,float) + DECLAREMETHOD_1(pEngine,void,setIdleRPM,float) + DECLAREMETHOD_1(pEngine,void,setStallRPM,float) + DECLAREMETHOD_1(pEngine,void,setStartRPM,float) + + DECLAREMETHOD_1(pEngine,void,setTimeScale,float) + DECLAREMETHOD_1(pEngine,void,setEndRotationalFactor,float) + + + DECLAREMETHOD_1(pEngine,void,setForceFeedbackScale,float) + DECLAREMETHOD_0(pEngine,float,getForceFeedbackScale) + + //---------------------------------------------------------------- + // + // engine + // + DECLAREMETHOD_0(pVehicle,pEngine*,getEngine) + + DECLAREMETHOD_0(pEngine,pLinearInterpolation,getTorqueCurve) + DECLAREMETHOD_1(pEngine,void,setTorqueCurve,pLinearInterpolation) + + DECLAREMETHOD_0(pEngine,float,getRPM) + DECLAREMETHOD_0(pEngine,float,getTorque) + DECLAREMETHOD_0(pEngine,void,setToDefault) + DECLAREMETHOD_1(pEngine,void,updateUserControl,int) + + DECLAREMETHOD_1(pEngine,void,setMaxTorque,float) + DECLAREMETHOD_1(pEngine,void,setMaxRPM,float) + DECLAREMETHOD_1(pEngine,void,setIdleRPM,float) + + DECLAREMETHOD_1(pEngine,void,setBrakingCoeff,float) + DECLAREMETHOD_0(pEngine,float,getBrakingCoeff) + + DECLAREMETHOD_1(pEngine,void,setFriction,float) + DECLAREMETHOD_0(pEngine,float,getFriction) + + DECLAREMETHOD_1(pEngine,void,SetInertia,float) + + DECLAREMETHOD_1(pEngine,void,setStartRPM,float) + DECLAREMETHOD_0(pEngine,float,getStartRPM) + + DECLAREMETHOD_0(pEngine,int,GetGears) + DECLAREMETHOD_0(pVehicle,void,PreCalcDriveLine) + + //DECLAREMETHOD_1(pEngine,float,GetGearRatio,int) + + + //---------------------------------------------------------------- + // + // interpolation curve, used for for torque and gears + // + DECLAREMETHOD_0(pLinearInterpolation,int,getSize) + DECLAREMETHOD_1(pLinearInterpolation,int,isValid,float) + DECLAREMETHOD_1(pLinearInterpolation,float,getValue,float) + DECLAREMETHOD_1(pLinearInterpolation,int,getValueAtIndex,int) + DECLAREMETHOD_2(pLinearInterpolation,void,insert,float,float) + + + //---------------------------------------------------------------- + // + // gearbox + // + + DECLAREMETHOD_1(pGearBox,float,GetTorqueForWheel,pWheel2*) + + DECLAREMETHOD_0(pGearBox,pLinearInterpolation,getGearRatios) + DECLAREMETHOD_1(pGearBox,void,setGearRatios,pLinearInterpolation) + + DECLAREMETHOD_0(pGearBox,pLinearInterpolation,getGearTensors) + DECLAREMETHOD_1(pGearBox,void,setGearTensors,pLinearInterpolation) + + + //---------------------------------------------------------------- + // + // wheel2 + // + DECLAREMETHOD_1(pWheel2,void,setPreScript,int) + DECLAREMETHOD_1(pWheel2,void,setPostScript,int) + DECLAREMETHOD_1(pWheel2,void,setOverrideMask,int) + + DECLAREMETHOD_0(pWheel2,float,getEndBrakingTorqueForWheel) + DECLAREMETHOD_0(pWheel2,float,getEndTorqueForWheel) + DECLAREMETHOD_0(pWheel2,float,getEndAccForWheel) + + DECLAREMETHOD_0(pWheel2,float,getWheelTorque) + DECLAREMETHOD_0(pWheel2,float,getWheelBreakTorque) + DECLAREMETHOD_0(pWheel2,float,getAxleSpeed) + + DECLAREMETHOD_0(pWheel2,VxVector,GetForceRoadTC) + DECLAREMETHOD_0(pWheel2,VxVector,GetForceBodyCC) + DECLAREMETHOD_0(pWheel2,VxVector,GetTorqueTC) + DECLAREMETHOD_0(pWheel2,VxVector,GetTorqueFeedbackTC) + DECLAREMETHOD_0(pWheel2,VxVector,GetTorqueBrakingTC) + DECLAREMETHOD_0(pWheel2,VxVector,GetTorqueRollingTC) + + DECLAREMETHOD_0(pWheel2,float,GetSlipAngle) + DECLAREMETHOD_0(pWheel2,float,GetSlipRatio) + DECLAREMETHOD_0(pWheel2,float,GetHeading) + DECLAREMETHOD_0(pWheel2,float,GetRotation) + DECLAREMETHOD_0(pWheel2,float,GetRotationV) + DECLAREMETHOD_0(pWheel2,float,GetAcceleration) + + DECLAREMETHOD_0(pWheel2,VxVector,GetVelocity) + //DECLAREMETHOD_0(pWheel2,VxVector,GetAcceleration) + DECLAREMETHOD_0(pWheel2,VxVector,GetSlipVectorCC) + DECLAREMETHOD_0(pWheel2,VxVector,GetPosContactWC) + + + DECLAREMETHOD_0(pWheel2,float,getEndBrakingTorqueForWheel) + DECLAREMETHOD_0(pWheel2,float,getEndTorqueForWheel) + DECLAREMETHOD_0(pWheel2,float,getEndAccForWheel) + DECLAREMETHOD_0(pWheel2,float,getWheelTorque) + DECLAREMETHOD_0(pWheel2,float,getWheelBreakTorque) + DECLAREMETHOD_0(pWheel2,bool,isAxleSpeedFromVehicle) + DECLAREMETHOD_0(pWheel2,bool,isTorqueFromVehicle) + + + + + DECLAREMEMBER(pWheel2,float,radius) + + + DECLAREMEMBER(pWheel2,VxVector,forceGravityCC) + DECLAREMEMBER(pWheel2,VxVector,forceBrakingTC) + + + + DECLAREMEMBER(pWheel2,VxVector,torqueTC) + DECLAREMEMBER(pWheel2,VxVector,forceRoadTC) + + DECLAREMEMBER(pWheel2,VxVector,rotation) + DECLAREMEMBER(pWheel2,VxVector,rotationA) + DECLAREMEMBER(pWheel2,VxVector,rotationV) + DECLAREMEMBER(pWheel2,VxVector,velWheelTC) + DECLAREMEMBER(pWheel2,VxVector,velWheelCC) + + DECLAREMETHOD_1(pWheel2,void,setMass,float) + DECLAREMETHOD_1(pWheel2,void,setTireRate,float) + + DECLAREMETHOD_0(pWheel2,float,getCsSlipLen) + DECLAREMETHOD_1(pWheel2,void,setRollingCoeff,float) + + + + + + + DECLAREMETHOD_0(pWheel2,float,getSuspensionTravel) + + //---------------------------------------------------------------- + // + // pwheel contactdata + // + DECLAREMETHOD_0(pWheel2,pWheelContactData*,getContact) + + DECLAREMETHOD_1(pWheel2,bool,getContact,pWheelContactData&dst) + + DECLAREMEMBER(pWheel2,bool,hadContact) + + DECLAREMEMBER(pWheelContactData,VxVector,contactPoint) + DECLAREMEMBER(pWheelContactData,VxVector,contactNormal) + DECLAREMEMBER(pWheelContactData,VxVector,longitudalDirection) + DECLAREMEMBER(pWheelContactData,VxVector,lateralDirection) + DECLAREMEMBER(pWheelContactData,CK3dEntity*,contactEntity) + DECLAREMEMBER(pWheelContactData,float,contactForce,) + DECLAREMEMBER(pWheelContactData,float,longitudalSlip,) + DECLAREMEMBER(pWheelContactData,float,lateralSlip) + DECLAREMEMBER(pWheelContactData,float,longitudalImpulse) + DECLAREMEMBER(pWheelContactData,float,lateralImpulse) + DECLAREMEMBER(pWheelContactData,float,contactPosition) + DECLAREMEMBER(pWheelContactData,int,otherShapeMaterialIndex) + + + + + + //---------------------------------------------------------------- + // + // + // + DECLAREMETHOD_0(pWheel2,pPacejka*,getPacejka) + + DECLAREMETHOD_1(pPacejka,void,SetFx,float) + DECLAREMETHOD_1(pPacejka,void,SetFy,float) + DECLAREMETHOD_1(pPacejka,void,SetMz,float) + DECLAREMETHOD_1(pPacejka,void,SetCamber,float) + DECLAREMETHOD_1(pPacejka,void,SetSlipAngle,float) + DECLAREMETHOD_1(pPacejka,void,SetSlipRatio,float) + DECLAREMETHOD_1(pPacejka,void,SetNormalForce,float) + DECLAREMETHOD_0(pPacejka,void,setToDefault) + DECLAREMETHOD_0(pPacejka,void,Calculate) + DECLAREMETHOD_0(pPacejka,float,GetMaxLongForce) + DECLAREMETHOD_0(pPacejka,float,GetMaxLatForce) + DECLAREMETHOD_1(pPacejka,void,SetMaxLongForce,float) + DECLAREMETHOD_1(pPacejka,void,SetMaxLatForce,float) + DECLAREMETHOD_0(pPacejka,float,GetLongitudinalStiffness) + DECLAREMETHOD_0(pPacejka,float,GetCorneringStiffness) + DECLAREMETHOD_0(pPacejka,float,GetFx) + DECLAREMETHOD_0(pPacejka,float,GetFy) + DECLAREMETHOD_0(pPacejka,float,GetMz) + + + DECLAREMETHOD_1(pRigidBody,pWheel2*,getWheel2,CK3dEntity*) + + DECLAREMETHOD_0(pVehicle,void,PreCalcDriveLine) + + //---------------------------------------------------------------- + // + // + // + + /* + DECLAREMETHOD_1(pVehicle,void,updateVehicle,float) + DECLAREMETHOD_5(pVehicle,void,setControlState,float,bool,float,bool,bool) + + + DECLAREMETHOD_1(pVehicle,pWheel*,getWheel,CK3dEntity*) + DECLAREMETHOD_0(pVehicle,pVehicleMotor*,getMotor) + DECLAREMETHOD_0(pVehicle,pVehicleGears*,getGears) + + DECLAREMETHOD_1(pVehicle,void,setPreProcessingScript,int) + DECLAREMETHOD_1(pVehicle,void,setPostProcessingScript,int) + + DECLAREMETHOD_0(pVehicle,void,gearUp) + DECLAREMETHOD_0(pVehicle,void,gearDown) + DECLAREMETHOD_0(pVehicleGears,int,getGear) + */ + + + ////////////////////////////////////////////////////////////////////////// + //motor : + + /*DECLAREMETHOD_0(pVehicleMotor,float,getRpm) + DECLAREMETHOD_0(pVehicleMotor,float,getTorque) + + + DECLAREMETHOD_0(pWheel,pWheel1*,castWheel1) + DECLAREMETHOD_0(pWheel,pWheel2*,castWheel2) + + DECLAREMETHOD_0(pWheel,float,getWheelRollAngle) + DECLAREMETHOD_0(pWheel2,float,getRpm) + DECLAREMETHOD_0(pWheel2,float,getAxleSpeed) + DECLAREMETHOD_0(pWheel2,float,getSuspensionTravel) + DECLAREMETHOD_0(pWheel2,VxVector,getGroundContactPos) +*/ + + + + + + + + STOPVSLBIND + + +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerWatchers.cpp b/usr/Src/Core/Manager/PhysicManagerWatchers.cpp new file mode 100644 index 0000000..8302303 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerWatchers.cpp @@ -0,0 +1,112 @@ +#include +#include "vtPhysXAll.h" +#include + + +class myLogConsumer : public xLogConsumer +{ + +public : + void logString(const char *string) + { + GetPMan()->SetLastLogEntry(string); + } +}; + +static myLogConsumer logger; + + + +class PhysicVariableWatcher : public CKVariableManager::Watcher +{ +public: + PhysicVariableWatcher(CKContext* context, XString variableName, XString currentValue); + + virtual void PostWrite(const char* iName); +private: + PhysicVariableWatcher(); + + CKContext* context; + CKBOOL manualSetInProgress; + XString variableName; + XString currentValue; +}; + +PhysicVariableWatcher::PhysicVariableWatcher(CKContext* context, XString variableName, XString currentValue) +{ + this->context = context; + this->manualSetInProgress = FALSE; + this->variableName = variableName; + this->currentValue = currentValue; +} + +static PhysicVariableWatcher *watcherConsole=NULL; + + +void PhysicVariableWatcher::PostWrite(const char* iName) +{ + + + XString newValue; + XString msg; + + // Check if we are currently manually setting the value + if (this->manualSetInProgress) + return; + + if( !context || !context->GetVariableManager()) + return; + + if(!GetPMan()) + return; + + // Get new value + int a=0; + context->GetVariableManager()->GetValue(iName, &GetPMan()->_LogToConsole); + xLogger::GetInstance()->enableConsoleOutput(GetPMan()->_LogToConsole); + + + return ; + + + // Validate value + + if (0 == newValue.Length()) + { + // This is valid, it means disable the GBL platform + } + else + { + + int LogConsole = newValue.ToInt(); + if ( LogConsole ==1 ) + { + // Restore back to previous value + // this->manualSetInProgress = TRUE; + // context->GetVariableManager()->SetValue(this->variableName.CStr(), this->currentValue.CStr()); + // this->manualSetInProgress = FALSE; + } + else + { + // Remember current value + //this->currentValue = newValue; + + // Write back in preferred format + //newValue.Format("(0x%08x,0x%08x)", laid.guid.d1, laid.guid.d2); + + //this->manualSetInProgress = TRUE; + //context->GetVariableManager()->SetValue(this->variableName.CStr(), newValue.CStr()); + //this->manualSetInProgress = FALSE; + } + } +} + + +void +PhysicManager::_registerWatchers(CKContext*context) +{ + const char* nameConsoleLogger = "Physic Console Logger/Console"; + watcherConsole = new PhysicVariableWatcher(context, nameConsoleLogger, "0"); + context->GetVariableManager()->RegisterWatcher(nameConsoleLogger, watcherConsole); + +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerWorldsAndBodies.cpp b/usr/Src/Core/Manager/PhysicManagerWorldsAndBodies.cpp new file mode 100644 index 0000000..6ff3f56 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerWorldsAndBodies.cpp @@ -0,0 +1,842 @@ +#include +#include "vtPhysXAll.h" + +#include "vtAttributeHelper.h" + +#include "pCommon.h" +#include "IParameter.h" +#include "vtBBHelper.h" +#include "xDebugTools.h" + +void PhysicManager::_cleanOrphanedJoints() +{ + + pWorldMapIt it = getWorlds()->Begin(); + while(it != getWorlds()->End()) + { + pWorld *w = *it; + NxU32 jointCount = w->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * >joints; + w->getScene()->resetJointIterator(); + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = w->getScene()->getNextJoint(); + NxActor *a= NULL; + NxActor *b= NULL; + if (a == NULL && b==NULL) + { + w->getScene()->releaseJoint(*j); + pJoint *mJoint = static_cast( j->userData ); + /*if(mJoint) + mJoint->setJoint(NULL); + SAFE_DELETE(mJoint); + */ + + } + } + } + it++; + } +} + + +void PhysicManager::_removeObjectsFromOldScene(CKScene *lastScene) +{ + if (!lastScene) + return; + + CKSceneObjectIterator objIt = lastScene->GetObjectIterator(); + CKObject *tpObj; + while(!objIt.End()) + { + CK3dEntity *tpObj = (CK3dEntity *)GetContext()->GetObject(objIt.GetObjectID()); + if (tpObj) + { + pRigidBody *body = getBody(tpObj); + if (body) + { + body->getWorld()->deleteBody(body); + } + } + objIt++; + } +} + +void PhysicManager::copyToAttributes( pObjectDescr src,CK3dEntity *dst ) +{ + + if (!dst) + return; + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + int attTypeActor = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + int attTypeMaterial = GetPMan()->getAttributeTypeByGuid(VTS_MATERIAL); + int attTypeOptimization = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); + int attTypeCCD = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CCD_SETTINGS); + int attTypePivot = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); + int attTypeMass = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); + int attTypeCapsule= GetPMan()->getAttributeTypeByGuid(VTS_CAPSULE_SETTINGS_EX); + int attTypeCCyl= GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR); + + //---------------------------------------------------------------- + // + // disable attribute callback + // + CKAttributeManager *aMan = GetPMan()->GetContext()->GetAttributeManager(); + if (aMan) + { + //aMan->SetAttributeCallbackFunction(attTypeActor) + } + + CK3dEntity *referenceObject = dst; + + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attTypeActor)) + { + referenceObject->RemoveAttribute(attTypeActor); + } + referenceObject->SetAttribute(attTypeActor); + + + CKParameterOut* actorAttribute = referenceObject->GetAttributeParameter(attTypeActor); + + //---------------------------------------------------------------- + // + // Common Settings + // + CKParameterOut *parBCommon = GetParameterFromStruct(actorAttribute,PS_COMMON_SETTINGS); + if (parBCommon) + { + SetParameterStructureValue(parBCommon,PS_BC_HULL_TYPE,src.hullType); + SetParameterStructureValue(parBCommon,PS_BC_FLAGS,src.flags); + SetParameterStructureValue(parBCommon,PS_BC_DENSITY,src.density); + SetParameterStructureValue(parBCommon,PS_BC_WORLD,src.worlReference); + } + + //---------------------------------------------------------------- + // + // Collision Setting + // + CKParameterOut *parBCollision = GetParameterFromStruct(actorAttribute,PS_COLLISION_SETTINGS); + CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); + if (parBCollision) + { + SetParameterStructureValue(parBCollision,PS_BC_GROUP,src.collisionGroup); + SetParameterStructureValue(parBCollision,PS_BC_SKINWITDH,src.skinWidth); + + if (parGroupsMask) + { + SetParameterStructureValue(parGroupsMask,0,src.groupsMask.bits0); + SetParameterStructureValue(parGroupsMask,1,src.groupsMask.bits1); + SetParameterStructureValue(parGroupsMask,2,src.groupsMask.bits2); + SetParameterStructureValue(parGroupsMask,3,src.groupsMask.bits3); + } + } + + //---------------------------------------------------------------- + // + // Optimization + // + if (src.mask & OD_Optimization) + { + if (referenceObject->HasAttribute(attTypeOptimization)) + { + referenceObject->RemoveAttribute(attTypeOptimization); + } + + referenceObject->SetAttribute(attTypeOptimization); + + + CKParameterOut *parBOptimization = referenceObject->GetAttributeParameter(attTypeOptimization); + if (parBOptimization) + { + SetParameterStructureValue(parBOptimization,PS_BO_LOCKS,src.optimization.transformationFlags); + SetParameterStructureValue(parBOptimization,PS_BO_SOLVER_ITERATIONS,src.optimization.solverIterations); + SetParameterStructureValue(parBOptimization,PS_BO_DOMINANCE_GROUP,src.optimization.dominanceGroup); + SetParameterStructureValue(parBOptimization,PS_BO_COMPARTMENT_ID,src.optimization.compartmentGroup); + } + + //---------------------------------------------------------------- + // + // sleeping + // + CKParameterOut *parBSleeping = GetParameterFromStruct(parBOptimization,PS_BO_SLEEPING); + if (parBSleeping) + { + SetParameterStructureValue(parBSleeping,PS_BS_ANGULAR_SLEEP,src.optimization.angSleepVelocity); + SetParameterStructureValue(parBSleeping,PS_BS_LINEAR_SLEEP,src.optimization.linSleepVelocity); + SetParameterStructureValue(parBSleeping,PS_BS_THRESHOLD,src.optimization.sleepEnergyThreshold); + } + + //---------------------------------------------------------------- + // + // damping + // + CKParameterOut *parBDamping = GetParameterFromStruct(parBOptimization,PS_BO_DAMPING); + if (parBDamping) + { + SetParameterStructureValue(parBDamping,PS_BD_ANGULAR,src.optimization.angDamping); + SetParameterStructureValue(parBDamping,PS_BD_LINEAR,src.optimization.linDamping); + } + } + + //---------------------------------------------------------------- + // + // CCD + // + if (src.mask & OD_CCD ) + { + if (referenceObject->HasAttribute(attTypeCCD)) + { + referenceObject->RemoveAttribute(attTypeCCD); + } + + referenceObject->SetAttribute(attTypeCCD); + + CKParameterOut *parBCCD = referenceObject->GetAttributeParameter(attTypeCCD); + if (parBCCD) + { + SetParameterStructureValue(parBCCD,PS_B_CCD_MOTION_THRESHOLD,src.ccd.motionThresold); + SetParameterStructureValue(parBCCD,PS_B_CCD_FLAGS,src.ccd.flags); + SetParameterStructureValue(parBCCD,PS_B_CCD_SCALE,src.ccd.scale); + SetParameterStructureValue(parBCCD,PS_B_CCD_MESH_REFERENCE,src.ccd.meshReference); + + } + } + //---------------------------------------------------------------- + // + // Material + // + if (src.mask & OD_Material ) + { + if (referenceObject->HasAttribute(attTypeMaterial)) + { + referenceObject->RemoveAttribute(attTypeMaterial); + } + + referenceObject->SetAttribute(attTypeMaterial); + + CKParameterOut *parBMaterial = referenceObject->GetAttributeParameter(attTypeMaterial); + if (parBMaterial) + { + pFactory::Instance()->copyTo(parBMaterial,src.material); + } + } + + + //---------------------------------------------------------------- + // + // Pivot + // + if (src.mask & OD_Pivot ) + { + if (referenceObject->HasAttribute(attTypePivot)) + { + referenceObject->RemoveAttribute(attTypePivot); + } + referenceObject->SetAttribute(attTypePivot); + CKParameterOut *parBPivot = referenceObject->GetAttributeParameter(attTypePivot); + if (parBPivot) + { + IParameter::Instance()->copyTo(parBPivot,src.pivot); + } + } + + //---------------------------------------------------------------- + // + // Mass + // + if (src.mask & OD_Mass ) + { + if (referenceObject->HasAttribute(attTypeMass)) + { + referenceObject->RemoveAttribute(attTypeMass); + } + referenceObject->SetAttribute(attTypeMass); + CKParameterOut *parBMass = referenceObject->GetAttributeParameter(attTypeMass); + if (parBMass) + { + IParameter::Instance()->copyTo(parBMass,src.mass); + } + } + //---------------------------------------------------------------- + // + // Capsule + // + if (src.mask & OD_Capsule) + { + + if (referenceObject->HasAttribute(attTypeCapsule)) + { + referenceObject->RemoveAttribute(attTypeCapsule); + } + referenceObject->SetAttribute(attTypeCapsule); + CKParameterOut *parBCapsule = referenceObject->GetAttributeParameter(attTypeCapsule); + if (parBCapsule) + { + IParameter::Instance()->copyTo(parBCapsule,src.capsule); + } + } + + //---------------------------------------------------------------- + // + // convex Cylinder + // + if (src.mask & OD_ConvexCylinder) + { + + if (referenceObject->HasAttribute(attTypeCCyl)) + { + referenceObject->RemoveAttribute(attTypeCCyl); + } + referenceObject->SetAttribute(attTypeCCyl); + CKParameterOut *parBCCyl= referenceObject->GetAttributeParameter(attTypeCCyl); + if (parBCCyl) + { + IParameter::Instance()->copyTo(parBCCyl,src.convexCylinder); + } + } +} + +pVehicle*PhysicManager::getVehicle(CK3dEntity*bodyReference) +{ + + pRigidBody *body=getBody(bodyReference); + if (bodyReference && body ) + { + return body->getVehicle(); + } + return NULL; +} + +pWheel2*PhysicManager::getWheel(CK3dEntity*wheelReference) +{ + + pRigidBody *body=getBody(wheelReference); + if (wheelReference && body ) + { + return static_cast(body->getWheel(wheelReference)); + } + return NULL; +} + +NxShape *PhysicManager::getSubShape(CK3dEntity*referenceObject) +{ + if (!referenceObject) + return NULL; + + pRigidBody *body = getBody(referenceObject); + if (!body) + return NULL; + + + return body->getSubShape(referenceObject); + + +} +NxCCDSkeleton* PhysicManager::getCCDSkeleton(CKBeObject *shapeReference) +{ + + pWorldMapIt it = getWorlds()->Begin(); + int s = getWorlds()->Size(); + + + while(it != getWorlds()->End()) + { + pWorld *w = *it; + NxActor** actors = w->getScene()->getActors(); + int nbActors = w->getScene()->getNbActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + NxU32 nbShapes = actor->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)actor->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sInfo) + { + + } + + } + } + } + } + } + + return NULL; +} + +void PhysicManager::createWorlds(int flags) +{ + +#ifdef _DEBUG + //assert(m_DefaultSleepingSettings()); +// assert(getWorlds()); +#endif + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_world_object); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + CK3dEntity*target = static_cast(*it); + pWorld *world = getWorld(target->GetID()); + + const char*name = target->GetName(); + if (world == getDefaultWorld() ) + { + continue; + } + ////////////////////////////////////////////////////////////////////////// + //world not registered : + if (!world) + { + + //at first we check for an attached sleeping settings attribute, when not, we use this->DefaultDefaultSleepingSettings +// pSleepingSettings *sleepSettings = target->HasAttribute(att_sleep_settings) ? +// pFactory::Instance()->GetSleepingSettingsFromEntity(target) : &this->DefaultSleepingSettings(); + + //we also retrieve objects world settings + //pWorldSettings * worldSettings = pFactory::Instance()->GetWorldSettingsFromEntity(target); + + //now we can create the final world,the function initiates the world and also it inserts the world + //in our m_pWorlds array ! + //world = pFactory::Instance()->createWorld(target,worldSettings,sleepSettings); + } + } +}; +int PhysicManager::getNbWorlds(){ return getWorlds()->Size();} +void PhysicManager::checkClothes() +{ + + if (!getNbObjects()) + return; + + if (!isValid()) performInitialization(); + if (!isValid()) + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't make manager valid"); + return; + } + + + ////////////////////////////////////////////////////////////////////////// + // we iterate through all entities tagged with the physic attribute + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_clothDescr); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + + CK3dEntity *target = static_cast(*it); + if (target) + { + const char *bName = target->GetName(); + // is the body registered in any world ? + + + CK_ID wID = vtTools::AttributeTools::GetValueFromAttribute(target,att_clothDescr,E_CS_WORLD_REFERENCE); + CK3dEntity *worldReference = (CK3dEntity*)m_Context->GetObject(wID); + pWorld *world = getWorld(wID); + + if (!worldReference) + { + continue; + } + + if (getBody(target)) + { + continue; + } + + if (world->getShapeByEntityID(target->GetID())) + { + continue; + } + + if (world && worldReference) + { + pCloth *cloth = world->getCloth(target); + if (!cloth) + { + pClothDesc *descr = pFactory::Instance()->createClothDescrFromParameter(target->GetAttributeParameter(att_clothDescr)); + cloth = pFactory::Instance()->createCloth(target,*descr); + if(cloth) + { + ////////////////////////////////////////////////////////////////////////// + if (descr->flags & PCF_AttachToParentMainShape ) + { + if (target->GetParent()) + { + CK3dEntity *bodyReference = pFactory::Instance()->getMostTopParent(target); + if (bodyReference) + { + pRigidBody *body = GetPMan()->getBody(bodyReference); + if (body) + { + cloth->attachToShape((CKBeObject*)bodyReference,descr->attachmentFlags); + } + } + } + } + ////////////////////////////////////////////////////////////////////////// + if (descr->flags & PCF_AttachToCollidingShapes) + { + cloth->attachToCollidingShapes(descr->attachmentFlags); + } + } + } + } + } + } + +} + + +bool isSceneObject(CK3dEntity *object) +{ + + CKLevel *level = GetPMan()->GetContext()->GetCurrentLevel(); + if(level) + { + for(int i = 0 ; i < level->GetSceneCount() ; i++ ) + { + CKScene *scene = level->GetScene(i); + if(scene && scene->IsObjectHere(object)) + return true; + } + } + return false; +} +void PhysicManager::checkWorlds() +{ + + + CKScene *currentScene = NULL; + + CKLevel *level = GetContext()->GetCurrentLevel(); + if(level) + { + currentScene = level->GetCurrentScene(); + } + + if (!getNbObjects()) + return; + + if (!isValid()) performInitialization(); + if (!isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't make manager valid"); + return; + } + ////////////////////////////////////////////////////////////////////////// + // we iterate through all entities tagged with the physic attribute + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_physic_object); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + + CK3dEntity *target = static_cast(*it); + if (target && !isSceneObject(target)) + { + const char *bName = target->GetName(); + // is the body registered in any world ? + pRigidBody* body = getBody(target); + if(!body) + { + //we retrieve the bodies target world : + CK_ID wID = vtTools::AttributeTools::GetValueFromAttribute(target,GetPAttribute(),E_PPS_WORLD); + int flags = vtTools::AttributeTools::GetValueFromAttribute(target,GetPAttribute(),E_PPS_BODY_FLAGS); + if (flags & BF_SubShape) + { + continue; + } + pWorld *world = getWorld(wID) ? getWorld(wID) : getDefaultWorld(); + if(world) + { + + //now create the final rigid body : + body = pFactory::Instance()->createRigidBodyFull(target,world->getReference()); + GetPMan()->getCheckList().PushBack(target->GetID()); + } + } + } + } + + + checkClothes(); + _checkObjectsByAttribute(currentScene); + + + + ////////////////////////////////////////////////////////////////////////// + pWorldMapIt itx = getWorlds()->Begin(); + while(itx != getWorlds()->End()) + { + pWorld *w = *itx; + if (w) + { + w->checkList(); + } + itx++; + } +} +pWorld *PhysicManager::getWorld(CK3dEntity *_o, CK3dEntity *body) +{ + pWorld *result=NULL; + + + ////////////////////////////////////////////////////////////////////////// + // + // Priorities : + // 1. the given world by _o + // 2. DefaultWorld + // 3. body physic attribute + // 4. created default world + // + ////////////////////////////////////////////////////////////////////////// + // we try to get it over _o : + if (_o) + { + result = getWorld(_o->GetID()); + if (result && getWorld(_o->GetID())->getReference() ) + { + _o = result->getReference(); + return result; + } + } + ////////////////////////////////////////////////////////////////////////// + //still nothing, we try to get the default world : + result = getDefaultWorld(); + if (result && getDefaultWorld()->getReference() ) + { + CK_ID id = getDefaultWorld()->getReference()->GetID(); + _o = result->getReference(); + return result; + } + + ////////////////////////////////////////////////////////////////////////// + //we try to get it over the bodies attribute : + if (body) + { + if (body->HasAttribute(GetPAttribute())) + { + CK_ID id = vtTools::AttributeTools::GetValueFromAttribute(body,GetPMan()->GetPAttribute(),E_PPS_WORLD); + _o = static_cast(ctx()->GetObject(id)); + if (_o) + { + result = getWorld(_o->GetID()); + if (result && getWorld(_o->GetID())->getReference()) + { + _o = result->getReference(); + return result; + } + _o = NULL; + } + } + } + ////////////////////////////////////////////////////////////////////////// + //still nothing + if (!getDefaultWorld()) + { + return NULL; + //result = pFactory::Instance()->createDefaultWorld("pDefaultWorld"); + /* + if (result) + { + _o = getDefaultWorld()->getReference(); + }else{ + + GetPMan()->performInitialization(); + result = GetPMan()->getDefaultWorld(); + _o = result->getReference(); + } + + */ + } + return result; +} +void PhysicManager::destroyWorlds() +{ + + pWorldMapIt it = getWorlds()->Begin(); + int s = getWorlds()->Size(); + + + while(it != getWorlds()->End()) + { + pWorld *w = *it; + if (w) + { + w->destroy(); + + if (w->getReference()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"World destroyed :%s",w->getReference()->GetName()); + } + + getWorlds()->Remove(w->getReference()); + delete w; + w = NULL; + + if (getWorlds()->Size()) + { + destroyWorlds(); + } + } + } + getWorlds()->Clear(); +} +pWorld*PhysicManager::getWorld(CK_ID _o) +{ + + pWorld *result = NULL; + CK3dEntity *obj = static_cast(GetContext()->GetObject(_o)); + if (obj) + { + if (getWorlds()->FindPtr(obj)) + { + return *getWorlds()->FindPtr(obj); + } + } + return 0; +} +void PhysicManager::deleteWorld(CK_ID _o) +{ + + CK3dEntity *obj = static_cast(GetContext()->GetObject(_o)); + if (obj) + { + pWorld *w = getWorld(_o); + if (w) + { + w->destroy(); + getWorlds()->Remove(obj); + delete w; + } + } +} + + + +pWorld*PhysicManager::getWorldByShapeReference(CK3dEntity *shapeReference) +{ + + if (!shapeReference) + { + return NULL; + } + + for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) + { + pWorld *w = *it; + if(w) + { + pRigidBody *body = w->getBody(pFactory::Instance()->getMostTopParent(shapeReference)); + if (body) + { + if (body->isSubShape((CKBeObject*)shapeReference)) + { + return w; + } + } + } + } + return 0; +} +pWorld*PhysicManager::getWorldByBody(CK3dEntity*ent) +{ + + if (!ent) + { + return NULL; + } + + for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) + { + pWorld *w = *it; + if(w) + { + //pRigidBody *body = w->getBody(pFactory::Instance()->getMostTopParent(ent)); + pRigidBody *body = w->getBody(ent); + if (body) + { + return w; + } + } + } + return 0; +} + +pCloth *PhysicManager::getCloth(CK_ID entityID) +{ + + CK3dEntity *entity = (CK3dEntity*)m_Context->GetObject(entityID); + if (!entityID) + { + return NULL; + } + + + for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) + { + pWorld *w = *it; + if(w) + { + pCloth *cloth = w->getCloth(entity); + if (cloth) + { + return cloth; + } + } + } + + return NULL; +} +int PhysicManager::getNbObjects(int flags /* =0 */) +{ + + CKAttributeManager* attman = ctx()->GetAttributeManager(); + + int testAtt = -1; + + if (flags == 0) testAtt = GetPMan()->GetPAttribute(); + + int newPhysicObjectAttributeType = getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + + + // [3/31/2009 master] + + const XObjectPointerArray& Array = attman->GetAttributeListPtr(testAtt); + int startSize = 0; + startSize +=Array.Size(); + + startSize+=attman->GetAttributeListPtr(newPhysicObjectAttributeType).Size(); + + + /* + pWorldMapIt it = getWorlds()->Begin(); + while(it != getWorlds()->End()) + { + pWorld *w = *it; + if (w) + { + w->checkList(); + } + it++; + } + */ + return startSize; +} \ No newline at end of file diff --git a/usr/Src/Core/Manager/PhysicManagerXML.cpp b/usr/Src/Core/Manager/PhysicManagerXML.cpp new file mode 100644 index 0000000..c7cede6 --- /dev/null +++ b/usr/Src/Core/Manager/PhysicManagerXML.cpp @@ -0,0 +1,35 @@ +#include +#include "vtPhysXAll.h" + + + + +void PhysicManager::reloadXMLDefaultFile(const char*fName) +{ + + + if (! fName || !strlen(fName))return; + + + + ////////////////////////////////////////Load our physic default xml document : + if (getDefaultConfig()) + { + delete m_DefaultDocument; + m_DefaultDocument = NULL; + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted old default config"); + + } + + TiXmlDocument * defaultDoc = loadDefaults(XString(fName)); + if (!defaultDoc) + { + enableFlag(_getManagerFlags(),E_MF_LOADING_DEFAULT_CONFIG_FAILED); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config : PhysicDefaults.xml: failed"); + setDefaultConfig(NULL); + }else + { + setDefaultConfig(defaultDoc); + } + +} \ No newline at end of file diff --git a/usr/Src/Core/Old/ToolManager.cpp b/usr/Src/Core/Old/ToolManager.cpp new file mode 100644 index 0000000..ab6f8dd --- /dev/null +++ b/usr/Src/Core/Old/ToolManager.cpp @@ -0,0 +1,107 @@ +#include + +#include "ToolManager.h" + +#include "vtCModuleDefines.h" +#include "vtBaseMacros.h" + + +ToolManager *manager = NULL; + + +////////////////////////////////////////////////////////////////////////// +ToolManager::ToolManager(CKContext* ctx) : vtBaseManager(ctx,VTM_TOOL_MANAGER_GUID,"ToolManager") +{ + m_Context->RegisterNewManager(this); + manager = this; +} +////////////////////////////////////////////////////////////////////////// +CKERROR ToolManager::OnCKPause() +{ + return CK_OK; +} +CKERROR ToolManager::OnCKPlay() +{ + return CK_OK; +} +CKERROR ToolManager::PostClearAll() +{ + return CK_OK; +} +CKERROR ToolManager::OnCKInit() +{ + return CK_OK; +} +CKERROR ToolManager::PreSave() +{ + return CK_OK; +} +CKContext* ToolManager::GetContext() +{ + return GetInstance()->m_Context; +} +ToolManager* ToolManager::GetInstance() +{ + if (manager) + { + return manager; + } + + return NULL; +} +ToolManager::~ToolManager(){} + +CKERROR ToolManager::SequenceDeleted(CK_ID *objids,int count) +{ + return CK_OK; +} + +CKERROR ToolManager::SequenceAddedToScene(CKScene *scn,CK_ID *objids,int count) +{ + return CK_OK; +} +CKERROR ToolManager::SequenceToBeDeleted(CK_ID *objids,int count) +{ + return CK_OK; +} + +CKERROR ToolManager::SequenceRemovedFromScene(CKScene *scn,CK_ID *objids,int count) +{ + return CK_OK; +} + + +CKERROR ToolManager::OnCKReset() +{ + return CK_OK; +} +CKERROR ToolManager::OnCKEnd() +{ + return 0; +} + +CKStateChunk* +ToolManager::SaveData(CKFile* SavedFile) +{ + return CK_OK; +} +CKERROR ToolManager::PostProcess() +{ + return CK_OK; +} +CKERROR ToolManager::PreProcess() +{ + return CK_OK; +} +CKERROR ToolManager::LoadData(CKStateChunk *chunk,CKFile* LoadedFile) +{ + return CK_OK; +} +CKERROR ToolManager::PostSave() +{ + return CK_OK; +} + + + + diff --git a/usr/Src/Core/Old/ToolManagerParameters.cpp b/usr/Src/Core/Old/ToolManagerParameters.cpp new file mode 100644 index 0000000..d79b8a5 --- /dev/null +++ b/usr/Src/Core/Old/ToolManagerParameters.cpp @@ -0,0 +1,8 @@ +#include +#include "ToolManager.h" + +void ToolManager::RegisterParameters() +{ + +} + diff --git a/usr/Src/Core/Old/ToolManagerVSL.cpp b/usr/Src/Core/Old/ToolManagerVSL.cpp new file mode 100644 index 0000000..ed534c6 --- /dev/null +++ b/usr/Src/Core/Old/ToolManagerVSL.cpp @@ -0,0 +1,8 @@ +#include +#include "ToolManager.h" + +void ToolManager::RegisterVSL() +{ + +} + diff --git a/usr/Src/Core/Old/vtBaseManager.cpp b/usr/Src/Core/Old/vtBaseManager.cpp new file mode 100644 index 0000000..704253b --- /dev/null +++ b/usr/Src/Core/Old/vtBaseManager.cpp @@ -0,0 +1,15 @@ +#include +#include "vtBaseManager.h" + +/* +vtBaseManager::vtBaseManager(CKContext *context,CKGUID guid,char* name): CKBaseManager(context,guid,name) +{ +} +*/ + +/* +vtBaseManager::~vtBaseManager() +{ + +} +*/ \ No newline at end of file diff --git a/usr/Src/Core/RacknetVSL.cpp b/usr/Src/Core/RacknetVSL.cpp new file mode 100644 index 0000000..018773c --- /dev/null +++ b/usr/Src/Core/RacknetVSL.cpp @@ -0,0 +1,312 @@ +#include "InitMan.h" +#include "CKAll.h" + +#include "VSLManagerSDK.h" + +#ifdef RACKNET + +#include +#include "network/racknet/NetworkStructures.h" +#include "network/racknet/PacketEnumerations.h" + +#include "network/laser_point.h" +#include "network/rNetStructs.h" + +#pragma comment (lib,"RakNet.lib") + +extern InitMan *_im; +static rNetServer *server = NULL; + +unsigned char GetPacketIdentifier(Packet *p); +laser_pointers *lPointers; + +lpoint pointers[5]; +boolean recieved =false; +int packetDelay; +int prevPacketCount; + +int pCount =0; +int GetPacketDT(); + + +////////////////////////////////////////////////////////////////////////// +BOOL rNetServerCreate(const char*server_name,int server_port); +BOOL rNetServerStart(){ + return server->start(); +} +void rNetServerDestroy(){ + if(server->realInterface){ + server->destroy(); + } +} +int rNetServerGetClientCount(){ + + + return server->GetClientCount(); + + +} + +int rNetServerGetBytesReceivedPerSecond(){ + + return server->realInterface->GetBytesReceivedPerSecond(); + + return -1; + +} + +int GetPacketOutputBufferSize(){ + return server->realInterface->GetPacketOutputBufferSize(); + } + + + +int rGetPacketsPerSecond(){ + + + int just = server->realInterface->GetReceivedPacketCount(); + int res = just - prevPacketCount; + prevPacketCount = just; + + return res; + +} +int rGetPaketCount(){ + + return server->realInterface->GetReceivedPacketCount(); + +} + +////////////////////////////////////////////////////////////////////////// +lpoint GetCoord(int index){ + + if(recieved){ + return pointers[index]; + } + return lpoint(-1,-1,-1); + +} + +VxRect rNetRecieve(){ + + Packet* p = server->realInterface->Receive(); + + if (p!=0){ + recieved =true; + lPointers = ((laser_pointers*)p->data); + + /* + for (int i = 0 ; i < 10 ; i++){ + pointers[i].x = lPointers->LArray[i].x; + pointers[i].y = lPointers->LArray[i].y; + + } + + //Vx2DVector coord = GetLPCoord(0); + char buffer[400]; + lpoint coord = GetCoord(0); + sprintf(buffer,"x : %d, y: %d",coord.x,coord.y); + _im->m_Context->OutputToConsole(buffer,false); + */ + + VxRect m (lPointers->LArray[0].x,lPointers->LArray[0].y,lPointers->LArray[0].x,lPointers->LArray[0].x); + +// server->realInterface->DeallocatePacket(p); +// server->realInterface->DesynchronizeAllMemory(); + pCount =1; + return m; + + } + pCount = -1; + recieved = false; + + return VxRect(-1,-1,-1,-1); + } + + +/************************************************************************/ +/* */ +/************************************************************************/ +Vx2DVector GetLPCoord(int index){ + + if (recieved) + return Vx2DVector((const float)pointers[index].x,(const float)pointers[index].y); + return Vx2DVector(-1,-1); + } + + + +laser_pointers& GetLaserPointerArray(){ + /* + Packet* p = server->realInterface->Receive(); + + if (p!=0){ + recieved =true; + laser_pointers *tmpArray = ((laser_pointers*)p->data); + + for (int i = 0 ; i < 99 ; i++){ + pointers[i].x = tmpArray->LArray[i].x; + pointers[i].y = tmpArray->LArray[i].y; + } + + char buffer[400]; + SYSTEMTIME time; + GetSystemTime(&time); + packetDelay = time.wMilliseconds - tmpArray->sStamp.miliseconds; + WORD sDT = time.wSecond - tmpArray->sStamp.seconds; + + + //sprintf(buffer,"dtSec : %d, dtMSec: %d", sDT, msDT ); + sprintf(buffer,"x : %f, y: %f", pointers[0].x ,pointers[0].y); + _im->m_Context->OutputToConsole(buffer,false); + + + server->realInterface->DeallocatePacket(p); + server->realInterface->DesynchronizeAllMemory(); + + return laser_pointers(); + + } + recieved = false ; */ + + return laser_pointers(); +} + + + +void +laser_pointers::GetCoord(Vx2DVector& target,int index){ + + if (lPointers){ + target.x = (float)pointers[index].x; + target.y = (float)pointers[index].y; + } +} + + +void +InitMan::RegisterRacknetVSL(){ + + STARTVSLBIND(m_Context) + + + + /************************************************************************/ + /* Variable|Parameter Stuff */ + /************************************************************************/ + DECLAREFUN_C_2(BOOL,rNetServerCreate,const char*, int ) + DECLAREFUN_C_0(BOOL,rNetServerStart) + DECLAREFUN_C_0(void,rNetServerDestroy) + DECLAREFUN_C_0(int,rGetPaketCount) + + DECLAREFUN_C_0(int,GetPacketDT) + + DECLAREFUN_C_0(int,rGetPacketsPerSecond) + + DECLAREFUN_C_0(int,rNetServerGetClientCount) + DECLAREFUN_C_0(int,rNetServerGetBytesReceivedPerSecond) + DECLAREFUN_C_0(VxRect,rNetRecieve) + DECLAREFUN_C_0(int,GetPacketOutputBufferSize) + + + DECLAREOBJECTTYPE(lpoint) + DECLAREMEMBER(lpoint,int,x) + DECLAREMEMBER(lpoint,int,y) + DECLAREFUN_C_1(lpoint,GetCoord,int) + + DECLAREPOINTERTYPE(laser_pointers) + + DECLAREMETHODC_1(laser_pointers,lpoint,GetPointByIndex,int) + + DECLAREFUN_C_0(laser_pointers&,GetLaserPointerArray) + + DECLAREMETHODC_2(laser_pointers,void,GetCoord,Vx2DVector&,int) + DECLAREFUN_C_1(Vx2DVector,GetLPCoord,int) + + STOPVSLBIND + +} + + +CKERROR InitMan::PostProcess(){ + + /* + if (server->realInterface && server->isStarted){ + + Packet* p = server->realInterface->Receive(); + + if (p!=0){ + lPointers = ((laser_pointers*)p->data); + + m_Context->OutputToConsole("processing incoming packets",false); + + /* + + char buffer[400]; + SYSTEMTIME time; + GetSystemTime(&time); + packetDelay = time.wMilliseconds - lPointers->sStamp.miliseconds; + WORD sDT = time.wSecond - lPointers->sStamp.seconds; + */ + + + +/* + for (int i = 0 ; i < 4 ; i++) + { + //pointers[i].x = lPointers->LArray[i].x; + //pointers[i].y = lPointers->LArray[i].y; + }*/ +/* + char buffer[400]; + lpoint coord = GetCoord(0); + sprintf(buffer,"x : %d, y: %d",coord.x,coord.y); + + m_Context->OutputToConsole(buffer,false); +*/ + //server->realInterface->DeallocatePacket(p); + //server->realInterface->DesynchronizeAllMemory(); + + //} + + + + return CK_OK; + + //} +} + +/************************************************************************/ +/* */ +/************************************************************************/ + +unsigned char GetPacketIdentifier(Packet *p) +{ + if (p==0) + return 255; + + if ((unsigned char)p->data[0] == ID_TIMESTAMP) + { + assert(p->length > sizeof(unsigned char) + sizeof(unsigned long)); + return (unsigned char) p->data[sizeof(unsigned char) + sizeof(unsigned long)]; + } + else + return (unsigned char) p->data[0]; +} + +////////////////////////////////////////////////////////////////////////// +BOOL rNetServerCreate(const char*server_name,int server_port){ + + server = new rNetServer(server_name,server_port); + lPointers = new laser_pointers(); + return true; +} + +////////////////////////////////////////////////////////////////////////// +int GetPacketDT(){ + return packetDelay; +} + + +#endif + diff --git a/usr/Src/Core/ResourceTools.cpp b/usr/Src/Core/ResourceTools.cpp new file mode 100644 index 0000000..c4e087b --- /dev/null +++ b/usr/Src/Core/ResourceTools.cpp @@ -0,0 +1,36 @@ +#include "ResourceTools.h" + +HINSTANCE GetModulefromResource(HMODULE hModule,int name,char *tempfile){ + + BYTE *data; + HANDLE hfile; + DWORD len,c; + char temppath[MAX_PATH]; + HRSRC hres; + + if (hres=FindResource((HMODULE)hModule,MAKEINTRESOURCE(name),RT_RCDATA)){ + len=SizeofResource(hModule,hres); + hres=(HRSRC)LoadResource(hModule,hres); + data=(BYTE*)LockResource((HRSRC)hres); + + + } + GetTempPath(MAX_PATH,temppath); + GetTempFileName(temppath,"tostrong",0,tempfile); + hfile=CreateFile(tempfile,GENERIC_WRITE|FILE_SHARE_DELETE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); + WriteFile(hfile,data,len,&c,NULL); + CloseHandle(hfile); + delete data; + return LoadLibrary(tempfile); +} + +HMODULE GetParentModule(CK_PLUGIN_TYPE type,CKGUID guid){ + + CKPluginManager* ThePluginManager=CKGetPluginManager(); + for (int i=0;iGetPluginDllCount();i++){ + CKPluginEntry* desc=ThePluginManager->GetPluginInfo(type,i); + CKPluginDll* dll =ThePluginManager->GetPluginDllInfo(desc->m_PluginDllIndex); + if (desc->m_PluginInfo.m_GUID == guid)return ((HMODULE)dll->m_DllInstance); + } + return NULL; +} \ No newline at end of file diff --git a/usr/Src/Core/ToolManagerMessages.cpp b/usr/Src/Core/ToolManagerMessages.cpp new file mode 100644 index 0000000..0d14b91 --- /dev/null +++ b/usr/Src/Core/ToolManagerMessages.cpp @@ -0,0 +1,136 @@ +#include "InitMan.h" +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0501 +#endif + +#include +#include +#include +#include +#include +#include "AutoLock.h" +using namespace AutoLock; +vtExternalEvent *Msg; +HANDLE hmem = NULL; + +int post = 0; +extern InitMan *_im; + +#pragma comment (lib,"ATLSD.LIB") + +HANDLE m_hLogItemSendEvent = ::CreateEvent(NULL,TRUE,FALSE,"LogItemSendEventName"); +HANDLE m_hShutdownEvent = ::CreateEvent(NULL,FALSE,FALSE,"SendRcvShutdownEvent"); +HANDLE m_hLogItemReceivedEvent = ::CreateEvent(NULL,FALSE,FALSE,"LogItemReceivedEventName"); +HANDLE aHandles[] = { m_hShutdownEvent , m_hLogItemSendEvent }; + +BOOL vt_UnloadPlugin(CKGUID input); +BOOL vt_ReloadPlugin(CKGUID input); +BOOL recieved = false; +BOOL changed = true; + +void +InitMan::InitMessages(int flags,XString name) +{ + + m_Context->ActivateManager((CKBaseManager*) this,true); + + if( NULL != ( m_hMMFile = CreateFileMapping( INVALID_HANDLE_VALUE, + NULL,PAGE_READWRITE,0, + sizeof( vtExternalEvent ),"sharedMemFile" ) ))//_T("LogSndRcvMMF") ))) + { + if( NULL != (m_pData = (vtExternalEvent*)::MapViewOfFile(m_hMMFile, + FILE_MAP_READ | FILE_MAP_WRITE, + 0, + 0, + sizeof( vtExternalEvent* )) ) ) + { + // return S_OK; + } + } + //return HRESULT_FROM_WIN32( ::GetLastError( ) ); +} + + + +CKERROR InitMan::PostProcess() +{ + if (!changed){ + + SetEvent( m_hShutdownEvent ); + } + return CK_OK; +} + +void +InitMan::PerformMessages() +{ + +// m_Context->OutputToConsole("performe"); + HRESULT hr = S_OK; + + USES_CONVERSION; + + switch( ::WaitForMultipleObjects(sizeof(aHandles) /sizeof(HANDLE),&(aHandles[0]),FALSE,1)) + { + + case WAIT_OBJECT_0: + { + SetEvent( m_hShutdownEvent ); + break; + } + case WAIT_OBJECT_0 + 1: + { + try + { + CLockableMutex m_mtxMMFile("sharedMem"); + CAutoLockT< CLockableMutex > lock(&m_mtxMMFile, 5000 ); + vtExternalEvent *pLI = reinterpret_cast(m_pData); + + if (pLI) + { + m_Context->OutputToConsole("vtPluginProxy : msg recieved",FALSE); + + XString command(pLI->command); + m_Context->OutputToConsoleEx(command.Str()); + XString commandArg(pLI->commandArg); + if (!command.Compare("unload")) + { + /*vtGUID inputGuid; + inputGuid.FromString(commandArg); + m_Context->OutputToConsole("vtPluginProxy : Unload Plugin",FALSE); + vt_UnloadPlugin(inputGuid.GetVirtoolsGUID());*/ + + } + + if (!command.Compare("reload")) + { + /*vtGUID inputGuid; + inputGuid.FromString( commandArg ); + m_Context->OutputToConsole("vtPluginProxy : Reload Plugin",FALSE); + vt_ReloadPlugin(inputGuid.GetVirtoolsGUID());*/ + } + + changed = true; + SetEvent( m_hLogItemReceivedEvent ); + ::ResetEvent(m_hShutdownEvent); + } + + return ; + } + catch( CAutoLockTimeoutExc ) + { + hr = HRESULT_FROM_WIN32( WAIT_TIMEOUT ); + } + catch( CAutoLockWaitExc& e ) + { + hr = HRESULT_FROM_WIN32( e.GetLastError() ); + } + break; + + } + default: + int op=0; +// ATLASSERT(0); + } +} + diff --git a/usr/Src/Core/crypting.cpp b/usr/Src/Core/crypting.cpp new file mode 100644 index 0000000..2ccf9fc --- /dev/null +++ b/usr/Src/Core/crypting.cpp @@ -0,0 +1,50 @@ +#include "crypting.h" +#include +#include +#include + +int EncryptPassword(char* pcPassword) +{ + + int aiKey[50] = {0x02, 0x03, 0x05, 0x07, 0x11, 0x13, 0x17, 0x19, 0x23, 0x29, + 0xA2, 0xB3, 0xC5, 0xD7, 0xE1, 0xF3, 0xA7, 0xB9, 0xC3, 0xD9, + 0x93, 0xA4, 0xB6, 0xC8, 0xD2, 0xE4, 0x98, 0xA8, 0xB4, 0xC8, + 0x46, 0x58, 0x63, 0x67, 0x74, 0x78, 0x57, 0x57, 0x68, 0x67, + 0xA9, 0xBC, 0xC9, 0xDF, 0xF6, 0x0C, 0xBF, 0xCF, 0xFC, 0xFF}; + + + char acPassword[256]; + char acTemp[3]; + + + if(pcPassword == NULL) return TRUE; + ZeroMemory(acPassword, 256 * sizeof(char)); + + + srand(strlen(pcPassword) * 17); + for(int a = 0; a < (int)(strlen(pcPassword)); a++) + { + srand(rand() + strlen(pcPassword) * a); + srand((rand() % (aiKey[a % 50])) + (rand() % (aiKey[(a * 23) % 50]))); + srand((rand() % (aiKey[(a + 2305) % 50])) + (rand() % (aiKey[(17 + a * 133) % 50])) * 177); + + + acPassword[a] = pcPassword[a] + (rand() % 256); + + srand(((BYTE)(acPassword[a]) + 1) * (a + 23) + (rand() % 1381)); + //ok, that´s crazy enough + } + + ZeroMemory(pcPassword, strlen(pcPassword) * sizeof(char)); + + + + for(int a = 0; a < (int)(strlen(acPassword)); a++) + { + sprintf(acTemp, "%02x", (byte)(acPassword[a])); + strcat(pcPassword, acTemp); + } + + + return FALSE; +} diff --git a/usr/Src/Core/pCloth/pCloth.cpp b/usr/Src/Core/pCloth/pCloth.cpp new file mode 100644 index 0000000..bee43d0 --- /dev/null +++ b/usr/Src/Core/pCloth/pCloth.cpp @@ -0,0 +1,514 @@ +#include +#include "vtPhysXAll.h" +#include "Stream.h" +#include "cooking.h" + + + +pCloth::~pCloth() +{ + + + + if (!getCloth()) + { + return; + } + + getWorld()->getScene()->releaseCloth(*mCloth); + //getWorld()->getScene()-> + releaseReceiveBuffers(); + setEntityID(-1); + + +} +void pCloth::detachFromShape(CKBeObject *shape) +{ + if (!shape) + { + return; + } + NxShape *aShape = getWorld()->getShapeByEntityID(shape->GetID()); + if (aShape) + { + getCloth()->detachFromShape(aShape); + } + +} +void pCloth::dominateVertex(int vertexId, float expirationTime, float dominanceWeight) +{ + getCloth()->dominateVertex(vertexId,expirationTime,dominanceWeight); +} + +void pCloth::freeVertex(const int vertexId) +{ + getCloth()->freeVertex(vertexId); +} + +void pCloth::attachVertexToGlobalPosition(const int vertexId, const VxVector &pos) +{ + + getCloth()->attachVertexToGlobalPosition(vertexId,getFrom(pos)); + +} +void pCloth::attachVertexToShape(int vertexId, CKBeObject *shape, const VxVector &localPos, int attachmentFlags) +{ + + if (!shape) + { + return; + } + + if (!getWorld()) + return; + + NxShape *aShape = getWorld()->getShapeByEntityID(shape->GetID()); + if (aShape) + { + getCloth()->attachVertexToShape(vertexId,aShape,getFrom(localPos),attachmentFlags); + } +} + +void pCloth::attachToCore(CK3dEntity *body, float impulseThreshold, float penetrationDepth, float maxDeformationDistance) +{ + + pRigidBody *rbody = GetPMan()->getBody(body); + if (!body) + { + return ; + } + + if (rbody->getWorld() != getWorld() ) + { + return; + } + + getCloth()->attachToCore(rbody->getActor(),impulseThreshold,penetrationDepth,maxDeformationDistance); + + +} + +void pCloth::attachToCollidingShapes(int attachmentFlags) +{ + mCloth->attachToCollidingShapes(attachmentFlags); +} +void pCloth::attachToShape(CKBeObject *shape, int attachmentFlags) +{ + + if (!shape) + { + return; + } + + if (!getWorld()) + return; + + NxShape *aShape = getWorld()->getShapeByEntityID(shape->GetID()); + if (aShape) + { + getCloth()->attachToShape(aShape,attachmentFlags); + } + + +} + +void pCloth::setCollisionResponseCoefficient(float coefficient) +{ + mCloth->setCollisionResponseCoefficient(coefficient); +} +void pCloth::addDirectedForceAtPos(const VxVector& position, const VxVector& force, float radius, ForceMode mode /* = FM_Force */) +{ + mCloth->addDirectedForceAtPos(getFrom(position),getFrom(force),(NxForceMode)mode ); +} +void pCloth::addForceAtVertex(const VxVector& force, int vertexId, ForceMode mode /* = FM_Force */) +{ + mCloth->addForceAtVertex(getFrom(force),vertexId,(NxForceMode)mode); +} + +void pCloth::addForceAtPos(const VxVector& position, float magnitude, float radius, ForceMode mode /* = FM_Force */) +{ + mCloth->addForceAtPos(getFrom(position),magnitude,radius,(NxForceMode)mode); +} + +void pCloth::wakeUp(float wakeCounterValue /* = NX_SLEEP_INTERVAL */) +{ + mCloth->wakeUp(wakeCounterValue); +} + +void pCloth::putToSleep() +{ + mCloth->putToSleep(); +} + +void pCloth::setFlags(int flags) +{ + mCloth->setFlags(flags); +} +void pCloth::setSleepLinearVelocity(float threshold) +{ + mCloth->setSleepLinearVelocity(threshold); +} +void pCloth::setExternalAcceleration(VxVector acceleration) +{ + mCloth->setExternalAcceleration(getFrom(acceleration)); +} +void pCloth::setWindAcceleration(VxVector acceleration) +{ + mCloth->setWindAcceleration(getFrom(acceleration)); +} +void pCloth::setMinAdhereVelocity(float velocity) +{ + mCloth->setMinAdhereVelocity(velocity); +} +void pCloth::setToFluidResponseCoefficient(float coefficient) +{ + mCloth->setToFluidResponseCoefficient(coefficient); +} +void pCloth::setFromFluidResponseCoefficient(float coefficient) +{ + mCloth->setFromFluidResponseCoefficient(coefficient); +} +void pCloth::setAttachmentResponseCoefficient(float coefficient) +{ + mCloth->setAttachmentResponseCoefficient(coefficient); +} +void pCloth::setVelocity(const VxVector& velocity, int vertexId) +{ + mCloth->setVelocity(getFrom(velocity),vertexId); +} +void pCloth::setValidBounds(const VxBbox& validBounds) +{ + NxBounds3 box; + box.set( getFrom(validBounds.Min), getFrom(validBounds.Max)); + mCloth->setValidBounds(box); +} + +void pCloth::setGroup(int collisionGroup) +{ + mCloth->setGroup(collisionGroup); +} +void pCloth::setSolverIterations(int iterations) +{ + mCloth->setSolverIterations(iterations); +} +void pCloth::setThickness(float thickness) +{ + mCloth->setThickness(thickness); +} +void pCloth::setAttachmentTearFactor(float factor) +{ + mCloth->setAttachmentTearFactor(factor); +} +void pCloth::setTearFactor(float factor) +{ + mCloth->setTearFactor(factor); +} +void pCloth::setPressure(float pressure) +{ + mCloth->setPressure(pressure); +} +void pCloth::setFriction(float friction) +{ + mCloth->setFriction(friction); +} +void pCloth::setDampingCoefficient(float dampingCoefficient) +{ + mCloth->setDampingCoefficient(dampingCoefficient); +} + +void pCloth::setStretchingStiffness(float stiffness) +{ + mCloth->setStretchingStiffness(stiffness); +} +void pCloth::setBendingStiffness(float stiffness) +{ + mCloth->setBendingStiffness(stiffness); +} + +void pCloth::updateVirtoolsMesh() +{ + + NxMeshData *data = getReceiveBuffers(); + CK3dEntity *srcEntity =(CK3dEntity*) GetPMan()->GetContext()->GetObject(getEntityID()); + if (!srcEntity) + { + return; + } + + /* + if (getCloth()->isSleeping()) + { + return; + } + + */ + CKMesh *mesh = srcEntity->GetCurrentMesh(); + NxReal *vertices = (NxReal*)data->verticesPosBegin; + + + VxVector pos; + srcEntity->GetPosition(&pos); + for (int i = 0 ; i< mesh->GetVertexCount() ; i++ ) + { + VxVector v; + v.x = vertices[i * 3]; + v.y = vertices[i * 3 + 1]; + v.z = vertices[i * 3 + 2]; + VxVector outIV; + srcEntity->InverseTransform(&outIV,&v); + mesh->SetVertexPosition(i,&outIV); + } + int t = 3; + +} + +bool pCloth::cookMesh(NxClothMeshDesc* desc) +{ + + // we cook the mesh on the fly through a memory stream + // we could also use a file stream and pre-cook the mesh + MemoryWriteBuffer wb; + int dValid = desc->isValid(); + + + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return NULL; + } + + bool success = CookClothMesh(*desc, wb); + + if (!success) + return false; + + MemoryReadBuffer rb(wb.data); + + mClothMesh = GetPMan()->getPhysicsSDK()->createClothMesh(rb); + + CloseCooking(); + + return true; + +} + +bool pCloth::generateMeshDesc(pClothDesc cDesc,NxClothMeshDesc *desc, CKMesh*mesh) +{ + + if (!mesh) + { + return false; + } + + int numVerts = mesh->GetVertexCount(); + int numFaces = mesh->GetFaceCount(); + + // allocate flag buffer + if(desc->vertexFlags == 0) + desc->vertexFlags = malloc(sizeof(NxU32)*desc->numVertices); + + // create tear lines + NxU32* flags = (NxU32*)desc->vertexFlags; + + NxReal *vertices = new float[3 * numVerts]; + //NxVec3 *verts = new NxVec3[numVerts]; + + for (int i = 0 ; i< numVerts ; i++ ) + { + VxVector v; + mesh->GetVertexPosition(i,&v); + vertices[i * 3] = v.x; + vertices[i * 3 + 1] =v.y; + vertices[i * 3 + 2] = v.z; + + + + if (desc->flags & NX_CLOTH_MESH_TEARABLE) + { + DWORD vColor = mesh->GetVertexColor(i); + DWORD cColor = RGBAFTOCOLOR(&cDesc.tearVertexColor); + if (vColor == cColor ) + { + int op2 =0; + flags[i] = NX_CLOTH_VERTEX_TEARABLE; + int k = 0 ; + k++; + } + } + } + + NxU32 *indices2 = new NxU32[numFaces*3]; + + for(int j = 0 ; j < numFaces ; j++) + { + + int findicies[3]; + mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); + indices2[ j *3 ] = findicies[0]; + indices2[ j *3 + 1 ] = findicies[1]; + indices2[ j *3 + 2 ] = findicies[2]; + } + desc->numVertices = numVerts; + desc->pointStrideBytes = sizeof(NxReal)*3; + desc->points = vertices; + desc->numTriangles = numFaces; + desc->triangles = indices2; + desc->triangleStrideBytes = sizeof(NxU32)*3; + desc->flags = 0; + desc->vertexMasses = 0; + desc->vertexFlags = 0; + desc->flags = NX_CLOTH_MESH_WELD_VERTICES; + desc->weldingDistance = 0.0001f; + + return true; + + +} + + +void pCloth::allocateClothReceiveBuffers(int numVertices, int numTriangles) +{ + + // here we setup the buffers through which the SDK returns the dynamic cloth data + // we reserve more memory for vertices than the initial mesh takes + // because tearing creates new vertices + // the SDK only tears cloth as long as there is room in these buffers + + + mReceiveBuffers = new NxMeshData(); + + NxU32 maxVertices = 3 * numVertices; + mReceiveBuffers->verticesPosBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices); + mReceiveBuffers->verticesNormalBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices); + mReceiveBuffers->verticesPosByteStride = sizeof(NxVec3); + mReceiveBuffers->verticesNormalByteStride = sizeof(NxVec3); + mReceiveBuffers->maxVertices = maxVertices; + mReceiveBuffers->numVerticesPtr = (NxU32*)malloc(sizeof(NxU32)); + + // the number of triangles is constant, even if the cloth is torn + NxU32 maxIndices = 3*numTriangles; + mReceiveBuffers->indicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxIndices); + mReceiveBuffers->indicesByteStride = sizeof(NxU32); + mReceiveBuffers->maxIndices = maxIndices; + mReceiveBuffers->numIndicesPtr = (NxU32*)malloc(sizeof(NxU32)); + + // the parent index information would be needed if we used textured cloth + NxU32 maxParentIndices = maxVertices; + mReceiveBuffers->parentIndicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxParentIndices); + mReceiveBuffers->parentIndicesByteStride = sizeof(NxU32); + mReceiveBuffers->maxParentIndices = maxParentIndices; + mReceiveBuffers->numParentIndicesPtr = (NxU32*)malloc(sizeof(NxU32)); + + // init the buffers in case we want to draw the mesh + // before the SDK as filled in the correct values + *mReceiveBuffers->numVerticesPtr = 0; + *mReceiveBuffers->numIndicesPtr = 0; +} + +void pCloth::releaseReceiveBuffers() +{ + + // Parent Indices is always allocated +/* free (mReceiveBuffers.parentIndicesBegin); + + mReceiveBuffers.setToDefault();*/ + +} + +void pCloth::releaseMeshDescBuffers(const NxClothMeshDesc* desc) +{ + + NxVec3* p = (NxVec3*)desc->points; + NxU32* t = (NxU32*)desc->triangles; + NxReal* m = (NxReal*)desc->vertexMasses; + NxU32* f = (NxU32*)desc->vertexFlags; + free(p); + free(t); + free(m); + free(f); +} + + +pCloth::pCloth() +{ + +} + +/*----------------------------------------------------------------------------*/ + +pClothDesc::pClothDesc() +{ + //setToDefault(); + +} + +/*----------------------------------------------------------------------------*/ + +void pClothDesc::setToDefault() +{ + thickness = 0.01f; + density = 1.0f; + bendingStiffness = 1.0f; + + stretchingStiffness = 1.0f; + dampingCoefficient = 0.5f; + friction = 0.5f; + + pressure = 1.0f; + tearFactor = 1.5f; + attachmentTearFactor = 1.5f; + + attachmentResponseCoefficient = 0.2f; + attachmentTearFactor = 1.5f; + collisionResponseCoefficient = 0.2f; + toFluidResponseCoefficient = 1.0f; + + fromFluidResponseCoefficient = 1.0f; + minAdhereVelocity = 1.0f; + flags = PCF_Gravity|PCF_CollisionTwoway; + + solverIterations = 5; + wakeUpCounter = NX_SLEEP_INTERVAL; + sleepLinearVelocity = -1.0f; + collisionGroup = 0; + forceFieldMaterial = 0; + externalAcceleration =VxVector(0.0f, 0.0f, 0.0f); + windAcceleration=VxVector(0.0f, 0.0f, 0.0f); + groupsMask.bits0 = 0; + groupsMask.bits1 = 0; + groupsMask.bits2 = 0; + groupsMask.bits3 = 0; + validBounds = VxBbox(); + relativeGridSpacing = 0.25f; + tearVertexColor.Set(1.0f); + + +} + +/*----------------------------------------------------------------------------*/ + +bool pClothDesc::isValid() const +{ + // if (flags & NX_CLF_SELFCOLLISION) return false; // not supported at the moment + + + if(thickness < 0.0f) return false; + if(density <= 0.0f) return false; + if(bendingStiffness < 0.0f || bendingStiffness > 1.0f) return false; + if(stretchingStiffness <= 0.0f || stretchingStiffness > 1.0f) return false; + if(pressure < 0.0f) return false; + if(tearFactor <= 1.0f) return false; + if(attachmentTearFactor <= 1.0f) return false; + if(solverIterations < 1) return false; + if(friction < 0.0f || friction > 1.0f) return false; + if(dampingCoefficient < 0.0f || dampingCoefficient > 1.0f) return false; + if(collisionResponseCoefficient < 0.0f) return false; + if(wakeUpCounter < 0.0f) return false; + if(attachmentResponseCoefficient < 0.0f || attachmentResponseCoefficient > 1.0f) return false; + if(toFluidResponseCoefficient < 0.0f) return false; + if(fromFluidResponseCoefficient < 0.0f) return false; + if(minAdhereVelocity < 0.0f) return false; + if(relativeGridSpacing < 0.01f) return false; + if(collisionGroup >= 32) return false; // We only support 32 different collision groups + return true; +} diff --git a/usr/Src/Core/pErrorStream.cpp b/usr/Src/Core/pErrorStream.cpp new file mode 100644 index 0000000..f5917a7 --- /dev/null +++ b/usr/Src/Core/pErrorStream.cpp @@ -0,0 +1,29 @@ +#include +#include "vtPhysXAll.h" + +#include "pErrorStream.h" + +namespace vtAgeia +{ + + + +void pErrorStream::reportError(NxErrorCode e, const char* message, const char* file, int line) +{ + + xLogger::xLog(ELOGERROR,E_LI_AGEIA,message); + +} +NxAssertResponse pErrorStream::reportAssertViolation(const char* message, const char* file, int line) +{ + return NX_AR_CONTINUE; + +} +void pErrorStream::print(const char* message) +{ + + xLogger::xLog(ELOGERROR,E_LI_AGEIA,message); + +} + +} diff --git a/usr/Src/Core/pFactory/pFactory.cpp b/usr/Src/Core/pFactory/pFactory.cpp new file mode 100644 index 0000000..892bead --- /dev/null +++ b/usr/Src/Core/pFactory/pFactory.cpp @@ -0,0 +1,279 @@ +#include +#include "vtPhysXAll.h" +//#include "tinyxml.h" +#include + + +static pFactory* pFact = NULL; + +void pFactory::findAttributeIdentifiersByGuid(CKGUID guid,std::vector&targetList) +{ + + CKContext *ctx = GetPMan()->GetContext(); + + CKAttributeManager *attMan = ctx->GetAttributeManager(); + CKParameterManager *parMan = ctx->GetParameterManager(); + + int cCount = attMan->GetAttributeCount(); + for(int i = 0 ; i < cCount ; i++) + { + CKSTRING name = attMan->GetAttributeNameByType(i); + if ( parMan->ParameterTypeToGuid(attMan->GetAttributeParameterType(i)) == guid ) + { + targetList.push_back(i); + } + + } +} + +//************************************ +// Method: Instance +// FullName: vtODE::pFactory::Instance +// Access: public +// Returns: pFactory* +// Qualifier: +//************************************ +pFactory* pFactory::Instance() +{ + + if (!pFact) + { + pFact = new pFactory(GetPMan(),GetPMan()->getDefaultConfig()); + } + return pFact; +} + + + + + +//************************************ +// Method: ~pFactory +// FullName: vtODE::pFactory::~pFactory +// Access: public +// Returns: +// Qualifier: +//************************************ +pFactory::~pFactory() +{ + + //Clean(); + delete pFact; + pFact = NULL; +} + +pFactory::pFactory() +{ + +} +//************************************ +// Method: pFactory +// FullName: vtODE::pFactory::pFactory +// Access: public +// Returns: // Qualifier: : m_PManager(prm1), m_DefaultDocument(prm2) +// Parameter: PhysicManager* prm1 +// Parameter: TiXmlDocument*prm2 +//************************************ +pFactory::pFactory(PhysicManager* prm1,TiXmlDocument*prm2) : + mManager(prm1), m_DefaultDocument(prm2) +{ + pFact = this; + mPhysicSDK = NULL; +} +//************************************ +// Method: ResolveFileName +// FullName: vtODE::pFactory::ResolveFileName +// Access: public +// Returns: XString +// Qualifier: +// Parameter: const char *input +//************************************ +XString pFactory::ResolveFileName(const char *input) +{ + CKPathManager *pm = GetPMan()->m_Context->GetPathManager(); + + FILE *file = fopen(input,"r"); + XString result; + if (file) + { + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,input); + + fclose(file); + + return XString(Ini); + } + + if (!file) + { + CKSTRING lastCmo = GetPMan()->m_Context->GetLastCmoLoaded(); + CKPathSplitter splitter(const_cast(lastCmo)); + CKPathSplitter splitter2(const_cast(input)); + CKPathMaker maker(splitter.GetDrive(),splitter.GetDir(),const_cast(input),""); + char* NewFilename = maker.GetFileName(); + file = fopen(NewFilename,"r"); + if (!file) + { + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,input); + file = fopen(Ini,"r"); + if(file) + { + fclose(file); + return XString(Ini); + } + + if(pm) + { + XString fname(const_cast(input)); + CKERROR error = GetPMan()->m_Context->GetPathManager()->ResolveFileName( fname , DATA_PATH_IDX); + if (error ==CK_OK) + { + file = fopen(fname.CStr(),"r"); + if (file) + { + fclose(file); + result = fname; + } + } + + } + } + } + return result; +} + +//************************************ +// Method: CreateFrame +// FullName: vtODE::pFactory::CreateFrame +// Access: public +// Returns: CK3dEntity* +// Qualifier: +// Parameter: XString name +//************************************ +CK3dEntity* +pFactory::createFrame(const char* name) +{ + if (!strlen(name)) + { + return NULL; + } + + int count = ctx()->GetObjectsCountByClassID(CKCID_3DENTITY); + CK_ID* ol = ctx()->GetObjectsListByClassID(CKCID_3DENTITY); + + for(int j=0;j(ctx()->GetObject(ol[j])); + if (!strcmp(o->GetName(),name ) ) + { + return static_cast(o); + } + } + + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_NONAMECHECK; + //if (dynamic) creaoptions = CK_OBJECTCREATION_DYNAMIC; + + // The Creation + + CKObject* object = ctx()->CreateObject(CKCID_3DENTITY,const_cast(name),creaoptions); + CK3dEntity* ent=(CK3dEntity*)object; + ent->SetFlags(ent->GetFlags()|CK_3DENTITY_FRAME); + + // we add it to the level + + CKLevel *level = ctx()->GetCurrentLevel(); + if (level) + { + level->AddObject(object); + } + + return ent; + +} + + + +//************************************ +// Method: _str2Vec +// FullName: vtODE::pFactory::_str2Vec +// Access: public +// Returns: VxVector +// Qualifier: +// Parameter: XString _in +//************************************ +VxVector +pFactory::_str2Vec(XString _in) +{ + short nb = 0 ; + VxVector out; + XStringTokenizer tokizer(_in.CStr(), ","); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) && nb < 3) + { + XString tokx(tok); + out.v[nb] = tokx.ToFloat(); + nb++; + } + return out; +} + +int pFactory::_str2MaterialFlag(XString _in) +{ + + short nb = 0 ; + int result = 0; + XStringTokenizer tokizer(_in.CStr(), "|"); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) && nb < 3) + { + XString tokx(tok); + + if ( _stricmp(tokx.CStr(),"Anisotropic") == 0 ) + { + result |= MF_Anisotropic; + } + if ( _stricmp(tokx.CStr(),"DisableFriction") == 0 ) + { + result |= MF_DisableFriction; + } + if ( _stricmp(tokx.CStr(),"DisableStrongFriction") == 0 ) + { + result |= MF_DisableStrongFriction; + } + nb++; + } + return result; +} + + +int pFactory::_getEnumIndex(XString enumerationFull,XString enumValue) +{ + + int result = 0; + XStringTokenizer tokizer(enumerationFull.CStr(), ","); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok))) + { + XString tokx(tok); + if ( !strcmp(tokx.CStr(),enumValue.CStr()) ) + { + return result; + } + // out.v[nb] = tokx.ToFloat(); + result++; + } + return 0; +} \ No newline at end of file diff --git a/usr/Src/Core/pFactory/pFactoryBody.cpp b/usr/Src/Core/pFactory/pFactoryBody.cpp new file mode 100644 index 0000000..3b68023 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryBody.cpp @@ -0,0 +1,2040 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" + +#include "NXU_helper.h" // NxuStream helper functions. +#include "NXU_PhysicsInstantiator.h" + +#include "IParameter.h" + +#include "xDebugTools.h" + + +pRigidBody*pFactory::cloneRigidBody(CK3dEntity *src,CK3dEntity *dst,CKDependencies *deps,int copyFlags,int bodyFlags/* =0 */) +{ + //src->Rest + pRigidBody *result = GetPMan()->getBody(dst); + pRigidBody *srcBody = GetPMan()->getBody(src); + CK3dEntity *referenceObject = dst; + + XString errMsg; + pObjectDescr oDescr; + + //---------------------------------------------------------------- + // + // sanity checks + // + #ifdef _DEBUG + assert(src); + assert(dst); + #endif // _DEBUG + + if (!(copyFlags & PB_CF_PHYSICS)) + { + errMsg.Format("Nothing to copy, aborting"); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,errMsg.Str()); + return NULL; + } + + //iAssertW(!result,"","Object :%s already physicalized"); + + //---------------------------------------------------------------- + // + // fill object description + // + if (!result && IParameter::Instance()->copyTo(oDescr,src,copyFlags)) + { + pWorld *world = GetPMan()->getWorld(oDescr.worlReference) ? GetPMan()->getWorld(oDescr.worlReference) : GetPMan()->getDefaultWorld(); + if(world) + { + + if ( (copyFlags && PB_CF_OVRRIDE_BODY_FLAGS) ) + oDescr.flags = (BodyFlags)bodyFlags; + + //now create the final rigid body : + result = pFactory::Instance()->createRigidBody(dst,oDescr); + } + } + + if (!result){ + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"cloning failed"); + return NULL; + } + + //---------------------------------------------------------------- + // + // clone joints + // + if ( (copyFlags & PB_CF_JOINTS) ) + { + pFactory::cloneJoints(src,dst,copyFlags); + + } + + //---------------------------------------------------------------- + // + // copy velocities + // + if ( (copyFlags & PB_CF_VELOCITIES) ) + { + NxActor *actorSrc = srcBody->getActor(); + NxActor *actorDst = result->getActor(); + + actorDst->setLinearVelocity( actorSrc->getLinearVelocity() ); + actorDst->setAngularVelocity( actorSrc->getAngularVelocity() ); + } + + //---------------------------------------------------------------- + // + // copy forces + // + if ( (copyFlags & PB_CF_FORCE) ) + { + NxActor *actorSrc = srcBody->getActor(); + NxActor *actorDst = result->getActor(); + actorDst->setLinearMomentum( actorSrc->getLinearMomentum() ); + actorDst->setAngularMomentum( actorSrc->getAngularMomentum() ); + } + + //---------------------------------------------------------------- + // + // copy sub shapes if : + // + // "Copy Children In Dependencies" && + // ( copyFlags::OverrideBodyFlags & hierarchy && newBodyFlags & hierarchy ) || + // ( oldBodyFlags & hierarchy ) + if ( ((*deps->At(CKCID_3DENTITY)) & CK_DEPENDENCIES_COPY_3DENTITY_CHILDREN) && + ( (( copyFlags & PB_CF_OVRRIDE_BODY_FLAGS ) && (bodyFlags & BF_Hierarchy)) || + ( oDescr.flags & BF_Hierarchy) ) + ) + { + int dCount = dst->GetChildrenCount(); + CK3dEntity* subEntity = NULL; + while (subEntity= dst->HierarchyParser(subEntity) ) + { + if (subEntity==dst) + continue; + + CK3dEntity *orginalObject = findSimilarInSourceObject(src,dst,subEntity); + if (orginalObject) + { + iAssertW(cloneShape(orginalObject,subEntity,dst,copyFlags,bodyFlags),"","clone of sub shape failed"); + } + } + } + return NULL; +} + +pRigidBody*pFactory::createRigidBody(CK3dEntity *referenceObject,pObjectDescr& oDescr) +{ + CK3dEntity *worldReferenceObject = (CK3dEntity*)GetPMan()->GetContext()->GetObject(oDescr.worlReference); + + ////////////////////////////////////////////////////////////////////////// + //treat action script : + + + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + GetPMan()->copyToAttributes(oDescr,referenceObject); + return NULL; + } + } + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + + if (!world) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"world object invalid, setting to default world"); + world = GetPMan()->getDefaultWorld(); + } + ////////////////////////////////////////////////////////////////////////// + //double check +/* if (!world) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"world object still invalid, vtPhysX corrupt. Performing initial setup"); + if (!GetPMan()->isValid()){ + GetPMan()->performInitialization(); + } + world = GetPMan()->getDefaultWorld(); + } +*/ + pRigidBody*result = world->getBody(referenceObject); + + // create minimum object + result = createBody(referenceObject,worldReferenceObject); + + if (!result) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed"); + return NULL; + + } + result->setWorld(world); + result->setFlags(oDescr.flags); + result->setHullType(oDescr.hullType); + + if (oDescr.density <= 0.001f) + oDescr.density = 1.0f; + +/* if (oDescr.skinWidth < 0.0f) + oDescr.skinWidth = 0.025f; +*/ + if (oDescr.skinWidth <= 0.001f) + oDescr.skinWidth = 0.025f; + + if (oDescr.collision.skinWidth <= 0.001f) + oDescr.collision.skinWidth = 0.025f; + + + + result->setDensity(oDescr.density); + + + bool hierarchy = (oDescr.flags & BF_Hierarchy); + bool isDeformable = oDescr.flags & BF_Deformable; + bool trigger = oDescr.flags & BF_TriggerShape; + + + //################################################################ + // + // Deformable ? + // + pCloth *cloth = NULL; + pClothDesc cDescr; + + if (isDeformable) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"deformable feature disabled in this release"); + return NULL; + + cDescr.setToDefault(); + cDescr.worldReference = worldReferenceObject->GetID(); + + if ( result->getFlags() & BF_Gravity ) + { + cDescr.flags |= PCF_Gravity; + } + + if ( result->getFlags() & BF_Collision ) + { + + } + + if (!cloth) + { + cloth = pFactory::Instance()->createCloth(referenceObject,cDescr); + if (!cloth) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : factory object failed !"); + } + } + } + float density = oDescr.density; + VxVector box_s= BoxGetZero(referenceObject); + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + v_matrix = referenceObject->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + + NxVec3 pos = pMath::getFrom(position); + NxQuat rot = pMath::getFrom(quat); + + + //---------------------------------------------------------------- + // + // Fill NxActorDescr + // + + + NxActorDesc actorDesc;actorDesc.setToDefault(); + NxBodyDesc bodyDesc;bodyDesc.setToDefault(); + + // + // Fix parameters to default values + + + actorDesc.density = oDescr.density; + + //skin width + float radius = result->GetVT3DObject()->GetRadius(); + + /* + if (oDescr.skinWidth == 0.0f) + { + oDescr.skinWidth = 0.25f; + } + + if (oDescr.collision.skinWidth == 0.0f) + { + oDescr.collision.skinWidth = 0.25f; + } + */ + + //---------------------------------------------------------------- + // + // Create the physic mesh. Externalizing this procedure will corrupt the + // actor description object. + // + + switch(oDescr.hullType) + { + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.dimensions = pMath::getFrom(box_s)*0.5f; + } + shape.density = density; + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + if(world->getCompartment()) + { + actorDesc.compartment = world->getCompartment(); + } + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + if (! (oDescr.flags & BF_Deformable) ) + { + shape.radius = radius; + } + shape.density = density; + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + if(world->getCompartment()){ + actorDesc.compartment = world->getCompartment(); + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + if (result->getWorld()->getCompartment()) + { + myMesh.flags |=NX_MF_HARDWARE_MESH; + } + + + pFactory::Instance()->createMesh(result->getWorld()->getScene(),result->GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return false; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + shape.group = oDescr.collisionGroup; + + actorDesc.shapes.pushBack(&shape); + shape.skinWidth = oDescr.skinWidth; + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + if(world->getCompartment()){ + actorDesc.compartment = world->getCompartment(); + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + + if (result->GetVT3DObject()->GetCurrentMesh()) + { + if (result->GetVT3DObject()->GetCurrentMesh()->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshes allowed, by Ageia!"); + return false; + } + }else + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); + return false; + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + if (result->getWorld()->getCompartment()) + { + //myMesh.flags |=NX_MF_HARDWARE_MESH; + } + pFactory::Instance()->createConvexMesh(result->getWorld()->getScene(),result->GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxConvexShapeDesc shape; + + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + return false; + + + } + shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + actorDesc.shapes.pushBack(&shape); + if (oDescr.skinWidth=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + int h = shape.isValid(); + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + if(world->getCompartment()){ + actorDesc.compartment = world->getCompartment(); + } + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexCylinder: + { + NxConvexShapeDesc shape; + pConvexCylinderSettings &cSettings = oDescr.convexCylinder; + + iAssertW( (oDescr.mask & OD_ConvexCylinder),pFactory::Instance()->findSettings(cSettings,result->GetVT3DObject()), + "Hull type has been set to convex cylinder but there is no descriptions passed or activated in the pObjectDescr::mask.Trying object attributes...."); + + if (cSettings.radius.reference) + cSettings.radius.evaluate(cSettings.radius.reference); + + if (cSettings.height.reference) + cSettings.height.evaluate(cSettings.height.reference); + + + iAssertW( cSettings.isValid() , cSettings.setToDefault(),""); + + cSettings.radius.value = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); + cSettings.height.value = cSettings.height.value > 0.0f ? cSettings.height.value : (box_s.v[cSettings.height.referenceAxis] * 0.5f); + + + + bool resultAssert = true; + iAssertWR( pFactory::Instance()->_createConvexCylinderMesh(&shape,cSettings,result->GetVT3DObject()),"",resultAssert); + + shape.density = density; + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + + if(world->getCompartment()) + { + actorDesc.compartment = world->getCompartment(); + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + + NxCapsuleShapeDesc shape; + pCapsuleSettingsEx &cSettings = oDescr.capsule; + if (!( oDescr.mask & OD_Capsule) ) + { + // try over attribute : + pFactory::Instance()->findSettings(cSettings,result->GetVT3DObject()); + } + + bool resultAssert = true; + + if (cSettings.radius.reference) + cSettings.radius.evaluate(cSettings.radius.reference); + + if (cSettings.height.reference) + cSettings.height.evaluate(cSettings.height.reference); + + iAssertWR(cSettings.isValid(),cSettings.setToDefault(),resultAssert); + + + + shape.radius = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); + shape.height = cSettings.height.value > 0.0f ? (cSettings.height.value-( 2*shape.radius)) : (box_s.v[cSettings.height.referenceAxis] - ( 2*shape.radius)) ; + + + shape.density = density; + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + if(world->getCompartment()) + actorDesc.compartment = world->getCompartment(); + + break; + } + + case HT_Wheel: + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Wheel shape can be sub shape only!"); + return false; + } + } + + if ( !isDeformable) + { + actorDesc.globalPose.t = pos; + actorDesc.globalPose.M = rot; + } + + + + //---------------------------------------------------------------- + // + // Create the final NxActor + // + + if (oDescr.flags & BF_Moving) + actorDesc.body = &bodyDesc; + + NxActor *actor = world->getScene()->createActor(actorDesc); + if (!actor) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); + delete result; + return NULL; + + } + + //---------------------------------------------------------------- + // + // + // + result->setActor(actor); + actor->setName(referenceObject->GetName()); + result->SetVT3DObject(referenceObject); + actor->userData= result; + + ////////////////////////////////////////////////////////////////////////// + //Deformable : + if (isDeformable && cloth) + { + + pDeformableSettings dSettings; + dSettings.ImpulsThresold = 50.0f; + dSettings.PenetrationDepth= 0.1f ; + dSettings.MaxDeform = 2.0f; + + CKParameterOut *poutDS = referenceObject->GetAttributeParameter(GetPMan()->att_deformable); + if (poutDS) + { + pFactory::Instance()->copyTo(dSettings,poutDS); + } + cloth->attachToCore(referenceObject,dSettings.ImpulsThresold,dSettings.PenetrationDepth,dSettings.MaxDeform); + result->setCloth(cloth); + } + + + ////////////////////////////////////////////////////////////////////////// + // + // Extra settings : + // + + if (result->getFlags() & BF_Moving) + { + VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&oDescr.massOffsetLinear); + actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); + } + + if (result->getFlags() & BF_Kinematic) + { + result->setKinematic(true); + } + + if (result->getFlags() & BF_Moving ) + { + result->enableGravity(result->getFlags() & BF_Gravity); + } + + if (oDescr.worlReference == 0) + { + if (GetPMan()->getDefaultWorld()) + { + oDescr.worlReference = GetPMan()->getDefaultWorld()->getReference()->GetID(); + } + } + + //---------------------------------------------------------------- + // + // store mesh meta info in the first main mesh + // + NxShape *shape = result->getShapeByIndex(); + if (shape) + { + pSubMeshInfo *sInfo = new pSubMeshInfo(); + sInfo->entID = referenceObject->GetID(); + sInfo->refObject = (CKBeObject*)referenceObject; + shape->userData = (void*)sInfo; + result->setMainShape(shape); + shape->setName(referenceObject->GetName()); + + } + + result->enableCollision( (result->getFlags() & BF_Collision), referenceObject ); + result->enableCollisionsNotify((result->getFlags() & BF_CollisionNotify)); + result->enableCollisionForceCalculation((result->getFlags() & BF_CollisionsForce), referenceObject); + result->enableContactModification((result->getFlags() & BF_ContactModify)); + + //---------------------------------------------------------------- + // + // Adjust pivot + // + + if ( (oDescr.mask & OD_Pivot) ) + { + iAssertW1( oDescr.pivot.isValid(),oDescr.pivot.setToDefault()); + result->updatePivotSettings(oDescr.pivot,referenceObject); + }else if(pFactory::Instance()->findSettings(oDescr.collision,referenceObject)) + result->updatePivotSettings(oDescr.pivot,referenceObject); + + //---------------------------------------------------------------- + // + // Optimization + // + if ((oDescr.mask & OD_Optimization )) + { + iAssertW1( oDescr.optimization.isValid(),oDescr.optimization.setToDefault()); + result->updateOptimizationSettings(oDescr.optimization); + } + else{ + if(pFactory::Instance()->findSettings(oDescr.optimization,referenceObject)) + { + iAssertW1( oDescr.optimization.isValid(),oDescr.optimization.setToDefault()); + result->updateOptimizationSettings(oDescr.optimization); + } + } + + //---------------------------------------------------------------- + // + // Collision + // + if ((oDescr.mask & OD_Collision)){ + result->updateCollisionSettings(oDescr.collision,referenceObject); + } + else if(pFactory::Instance()->findSettings(oDescr.collision,referenceObject)) + { + result->updateCollisionSettings(oDescr.collision,referenceObject); + } + else{ + result->updateCollisionSettings(oDescr.collision,referenceObject); + } + + + + //---------------------------------------------------------------- + // + // Material + // + + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + + pMaterial &bMaterial = oDescr.material; + + if (oDescr.mask & OD_Material) + { + result->updateMaterialSettings(bMaterial,referenceObject); + }else + { + bool hasMaterial = pFactory::Instance()->findSettings(bMaterial,referenceObject); + if (!hasMaterial) + { + if (world->getDefaultMaterial()) + { + int z = (int)world->getDefaultMaterial()->userData; + shape->setMaterial(world->getDefaultMaterial()->getMaterialIndex()); + } + }else{ + + iAssertW( bMaterial.isValid(),bMaterial.setToDefault(), + "Material settings were still invalid : "); + + NxMaterialDesc nxMatDescr; + pFactory::Instance()->copyTo(nxMatDescr,bMaterial); + NxMaterial *nxMaterial = world->getScene()->createMaterial(nxMatDescr); + if (nxMaterial) + { + shape->setMaterial(nxMaterial->getMaterialIndex()); + nxMaterial->userData =(void*)&bMaterial ; + } + } + } + + + xLogger::xLog(ELOGINFO,E_LI_MANAGER,"Rigid body creation successful : %s",referenceObject->GetName()); + + result->setInitialDescription(&oDescr); + + //---------------------------------------------------------------- + // + // Hierarchy mode fix : + // + if ( (oDescr.flags & BF_Hierarchy) ) + oDescr.hirarchy = true; + + if ( oDescr.hirarchy ) + oDescr.flags << BF_Hierarchy; + + + if ( (!oDescr.hirarchy) || !(oDescr.flags & BF_Hierarchy) ) + return result; + + CKSTRING name = referenceObject->GetName(); + + + result->setSleeping( (result->getFlags() & BF_Sleep)); + + if (oDescr.flags & BF_AddAttributes) + { + GetPMan()->copyToAttributes(oDescr,referenceObject); + } + + + + //---------------------------------------------------------------- + // + // Parse hirarchy + // + CK3dEntity* subEntity = NULL; + while (subEntity= referenceObject->HierarchyParser(subEntity) ) + { + pObjectDescr *subDescr = NULL; + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + if (subEntity->HasAttribute(attTypePBSetup)) + { + subDescr = new pObjectDescr(); + CKParameterOut *par = subEntity->GetAttributeParameter(attTypePBSetup); + IParameter::Instance()->copyTo(subDescr,par); + subDescr->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + } + + if (!subDescr) + continue; + + /************************************************************************/ + /* new rigid body in hierarchy */ + /************************************************************************/ + if ( !(subDescr->flags & BF_SubShape) && !result->isSubShape(subEntity) ) + { + CKSTRING name = referenceObject->GetName(); + CKSTRING namesub = subEntity->GetName(); + pRigidBody *childBody = GetPMan()->getBody(subEntity); + if (!childBody) + childBody= pFactory::Instance()->createRigidBody(subEntity,*subDescr); + } + + /************************************************************************/ + /* sub shape */ + /************************************************************************/ + if (subDescr->flags & BF_SubShape ) + { + ////////////////////////////////////////////////////////////////////////// + // + // Regular Mesh : + // + + if (subDescr->hullType != HT_Cloth) + { + //result->addSubShape(NULL,*subDescr,subEntity); + + VxQuaternion refQuad;subEntity->GetQuaternion(&refQuad,referenceObject); + VxVector relPos;subEntity->GetPosition(&relPos,referenceObject); + + NxShape *sC = GetPMan()->getSubShape(subEntity); + if (!sC) + { + shape = pFactory::Instance()->createShape(referenceObject,*subDescr,subEntity,subEntity->GetCurrentMesh(),relPos,refQuad); + }else + { + + pSubMeshInfo *sInfo = static_cast(sC->userData); + if (sInfo) + { + + } + + NxActor *sActor = &sC->getActor(); + if (sActor) + { + pRigidBody *sBody = static_cast(sActor->userData); + if (sBody) + { + + } + } + } + + + + //NxShape *shape = result->getSubShape(subEntity); + if (shape) + { + //---------------------------------------------------------------- + // + // check for collision setup + // + + //try to get get from child attributes first + /* + if(pFactory::Instance()->findSettings(subDescr->collision,subEntity)) + { + result->updateCollisionSettings(subDescr->collision,subEntity); + continue; + } + if ( (subDescr->mask & OD_Optimization) ) + { + //if (pFactory::Instance()->findSettings(subDescr->collision,subEntity)) + result->updateCollisionSettings(subDescr->collision,subEntity); + } + else if ( (oDescr.mask & OD_Optimization) ) + { + result->updateCollisionSettings(oDescr.collision,subEntity); + }else if(pFactory::Instance()->findSettings(subDescr->collision,subEntity)) + { + result->updateCollisionSettings(subDescr->collision,subEntity); + } + */ + } + + } + ////////////////////////////////////////////////////////////////////////// + // + // Cloth Mesh : + // + if (subDescr->hullType == HT_Cloth) + { + //pClothDesc *cloth = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + } + } + + //---------------------------------------------------------------- + // + // Adjust mass + // + if ((oDescr.mask & OD_Mass)) + result->updateMassSettings(oDescr.mass); + else if(pFactory::Instance()->findSettings(oDescr.mass,referenceObject)) + result->updateMassSettings(oDescr.mass); + //---------------------------------------------------------------- + // + // Collision + // + + + + + return result; + + nothing: + + return result; + +} + +pRigidBody*pFactory::createCapsule(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags) +{ + + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + pRigidBody*result = world->getBody(referenceObject); + if(result) + { + result->destroy(); + delete result; + result = NULL; + } + // we create our final body in the given world : + result = createBody(referenceObject,worldReferenceObject); + if (result) + { + result->setWorld(world); + + using namespace vtTools::AttributeTools; + + result->setFlags(descr->flags); + result->setHullType(descr->hullType); + result->setDataFlags(0x000); + result->checkDataFlags(); + + if (result->getSkinWidth()==-1.0f) + { + result->setSkinWidth(0.01f); + } + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + v_matrix = referenceObject->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + VxVector box_s= BoxGetZero(referenceObject); + + NxVec3 pos = pMath::getFrom(position); + NxQuat rot = pMath::getFrom(quat); + + float density = result->getDensity(); + float radius = referenceObject->GetRadius(); + if (referenceObject->GetRadius() < 0.001f ) + { + radius = 1.0f; + } + + + ////////////////////////////////////////////////////////////////////////// + //create actors description + NxActorDesc actorDesc;actorDesc.setToDefault(); + NxBodyDesc bodyDesc;bodyDesc.setToDefault(); + + ////////////////////////////////////////////////////////////////////////// + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + if (isFlagOn(result->getDataFlags(),EDF_MATERIAL_PARAMETER)) + { + NxMaterialDesc entMatNull;entMatNull.setToDefault(); + NxMaterialDesc *entMat = createMaterialFromEntity(referenceObject); + material = world->getScene()->createMaterial(entMatNull); + material->loadFromDesc(*entMat); + result->setMaterial(material); + }else{ + if (world->getDefaultMaterial()) + { + result->setMaterial(world->getDefaultMaterial()); + } + } + ////////////////////////////////////////////////////////////////////////// + + NxCapsuleShapeDesc capsuleShape; + + if ( creationFlags & E_OFC_DIMENSION ) + { + capsuleShape.height = box_s.y - ((box_s.x)); + capsuleShape.radius = box_s.x*0.5f; + } + + capsuleShape.density = descr->density; + + + capsuleShape.materialIndex = result->getMaterial()->getMaterialIndex(); + + //shape.localPose.t = pMath::getFrom(shapeOffset); + + if (result->getSkinWidth()!=-1.0f) + capsuleShape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&capsuleShape); + + + + + ////////////////////////////////////////////////////////////////////////// + //dynamic object ? + if (result->getFlags() & BF_Moving){ + actorDesc.body = &bodyDesc; + } + else + actorDesc.body = NULL; + + ////////////////////////////////////////////////////////////////////////// + //set transformations + actorDesc.density = descr->density; + + if (creationFlags & E_OFC_POSITION) + { + actorDesc.globalPose.t = pos; + } + + if (creationFlags & E_OFC_POSITION) + { + actorDesc.globalPose.M = rot; + } + + ////////////////////////////////////////////////////////////////////////// + //create the actor + + int v = actorDesc.isValid(); + NxActor *actor = world->getScene()->createActor(actorDesc); + if (!actor) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); + delete result; + return NULL; + + } + + + ////////////////////////////////////////////////////////////////////////// + //set additional settings : + result->setActor(actor); + actor->setName(referenceObject->GetName()); + actor->userData= result; + + if (result->getFlags() & BF_Moving) + { + VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&result->getMassOffset()); + actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); + } + + if (result->getFlags() & BF_Kinematic) + { + actor->raiseBodyFlag(NX_BF_KINEMATIC); + } + + result->enableCollision((result->getFlags() & BF_Collision)); + if (result->getFlags() & BF_Moving) + { + if (!(result->getFlags() & BF_Gravity)) + { + actor->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); + } + } + + NxShape *shape = result->getShapeByIndex(); + if (shape) + { + pSubMeshInfo *sInfo = new pSubMeshInfo(); + sInfo->entID = referenceObject->GetID(); + sInfo->refObject = (CKBeObject*)referenceObject; + shape->userData = (void*)sInfo; + result->setMainShape(shape); + shape->setName(referenceObject->GetName()); + } + } + + return result; +} + +pRigidBody*pFactory::createBox(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags) +{ + + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + pRigidBody*result = world->getBody(referenceObject); + if(result) + { + result->destroy(); + delete result; + result = NULL; + } + // we create our final body in the given world : + result = createBody(referenceObject,worldReferenceObject); + if (result) + { + result->setWorld(world); + + using namespace vtTools::AttributeTools; + + result->setFlags(descr->flags); + result->setHullType(descr->hullType); + result->setDataFlags(0x000); + result->checkDataFlags(); + + if (result->getSkinWidth()==-1.0f) + { + result->setSkinWidth(0.01f); + } + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + v_matrix = referenceObject->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + VxVector box_s= BoxGetZero(referenceObject); + + NxVec3 pos = pMath::getFrom(position); + NxQuat rot = pMath::getFrom(quat); + + float density = result->getDensity(); + float radius = referenceObject->GetRadius(); + if (referenceObject->GetRadius() < 0.001f ) + { + radius = 1.0f; + } + + + ////////////////////////////////////////////////////////////////////////// + //create actors description + NxActorDesc actorDesc;actorDesc.setToDefault(); + NxBodyDesc bodyDesc;bodyDesc.setToDefault(); + + ////////////////////////////////////////////////////////////////////////// + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + if (isFlagOn(result->getDataFlags(),EDF_MATERIAL_PARAMETER)) + { + NxMaterialDesc entMatNull;entMatNull.setToDefault(); + NxMaterialDesc *entMat = createMaterialFromEntity(referenceObject); + material = world->getScene()->createMaterial(entMatNull); + material->loadFromDesc(*entMat); + result->setMaterial(material); + }else{ + if (world->getDefaultMaterial()) + { + result->setMaterial(world->getDefaultMaterial()); + } + } + ////////////////////////////////////////////////////////////////////////// + + NxBoxShapeDesc boxShape; + if (creationFlags & E_OFC_DIMENSION ) + { + boxShape.dimensions = pMath::getFrom(box_s)*0.5f; + } + boxShape.density = descr->density; + boxShape.materialIndex = result->getMaterial()->getMaterialIndex(); + if (result->getSkinWidth()!=-1.0f) + boxShape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&boxShape); + + ////////////////////////////////////////////////////////////////////////// + //dynamic object ? + if (result->getFlags() & BF_Moving){ + actorDesc.body = &bodyDesc; + } + else + actorDesc.body = NULL; + + ////////////////////////////////////////////////////////////////////////// + //set transformations + actorDesc.density = descr->density; + + if (creationFlags & E_OFC_POSITION) + { + actorDesc.globalPose.t = pos; + } + + if (creationFlags & E_OFC_POSITION) + { + actorDesc.globalPose.M = rot; + } + + ////////////////////////////////////////////////////////////////////////// + //create the actor + + int v = actorDesc.isValid(); + NxActor *actor = world->getScene()->createActor(actorDesc); + if (!actor) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); + delete result; + return NULL; + + } + + + ////////////////////////////////////////////////////////////////////////// + //set additional settings : + result->setActor(actor); + actor->setName(referenceObject->GetName()); + actor->userData= result; + + if (result->getFlags() & BF_Moving) + { + VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&result->getMassOffset()); + actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); + } + + if (result->getFlags() & BF_Kinematic) + { + actor->raiseBodyFlag(NX_BF_KINEMATIC); + } + + result->enableCollision((result->getFlags() & BF_Collision)); + if (result->getFlags() & BF_Moving) + { + if (!(result->getFlags() & BF_Gravity)) + { + actor->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); + } + } + + NxShape *shape = result->getShapeByIndex(); + if (shape) + { + pSubMeshInfo *sInfo = new pSubMeshInfo(); + sInfo->entID = referenceObject->GetID(); + sInfo->refObject = (CKBeObject*)referenceObject; + shape->userData = (void*)sInfo; + result->setMainShape(shape); + shape->setName(referenceObject->GetName()); + } + } + + return result; +} + +pRigidBody*pFactory::createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,NXU::NxActorDesc *desc,int flags) +{ + +#ifdef _DEBUG + assert(referenceObject); + assert(desc); +#endif + + /************************************************************************/ + /* + + + + + */ + /************************************************************************/ + VxVector vpos; + referenceObject->GetPosition(&vpos); + + VxQuaternion vquat; + referenceObject->GetQuaternion(&vquat); + + NxQuat nrot = desc->globalPose.M; + NxVec3 npos = desc->globalPose.t; + + NxMat33 rotX; + rotX.rotX( PI / 2.0f ); + NxMat33 rotZ; + rotZ.rotZ( PI ); + + NxMat34 rotMat; + rotMat.M.multiply( rotZ, rotX ); + + NxMat34 posMat( true ); + +/* posMat.t.set( -mTerrain->getPosition().x, + mTerrain->getPosition().y, + mTerrain->getPosition().z ); +*/ + desc->globalPose.multiply( posMat, rotMat ); + + + NxQuat nrot2 = desc->globalPose.M; + NxVec3 npos2 = desc->globalPose.t; + + VxQuaternion nvm = getFromStream(nrot); + + VxVector nvpos = getFromStream(npos); + + + + for (NxU32 k=0; kmShapes.size(); k++) + { + NXU::NxShapeDesc *shape = desc->mShapes[k]; + NxVec3 locPos = shape->localPose.t; + NxQuat localQuad = shape->localPose.M; + } + + + int op = 2; + + + + return NULL; +} + + + +pRigidBody*pFactory::createRigidBodyFull(CK3dEntity *referenceObject, CK3dEntity *worldReferenceObject) +{ + + + //################################################################ + // + // Sanity checks + // + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + pRigidBody*result = world->getBody(referenceObject); + + + if(result) + { + result->destroy(); + delete result; + result = NULL; + } + + + //################################################################ + // + // Construct the result + // + result = createBody(referenceObject,worldReferenceObject); + if (result) + { + + + result->setWorld(world); + + + //---------------------------------------------------------------- + // + // Handle different attribute types (Object or pBSetup) + // + + int attTypeOld = GetPMan()->GetPAttribute(); + int attTypeNew = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + + pObjectDescr *oDescr = NULL; + + + //---------------------------------------------------------------- + // + // the old way : + // + + if (referenceObject->HasAttribute(attTypeOld)) + { + result->retrieveSettingsFromAttribute(); + oDescr = pFactory::Instance()->createPObjectDescrFromParameter(referenceObject->GetAttributeParameter(GetPMan()->GetPAttribute())); + + + + } + + bool hierarchy = result->getFlags() & BF_Hierarchy; + bool isDeformable = result->getFlags() & BF_Deformable; + bool trigger = (result->getFlags() & BF_TriggerShape); + + + //---------------------------------------------------------------- + // + // the new way + // + + if (referenceObject->HasAttribute(attTypeNew)) + { + oDescr = new pObjectDescr(); + + } + + + result->checkDataFlags(); + + + + + /* + pObjectDescr *oDescr = + if (!oDescr) + return result; + + */ + + //################################################################ + // + // Older versions have the hierarchy mode settings not the body flags + // We migrate it : + // + + if (oDescr->hirarchy) + { + result->setFlags( (result->getFlags() | BF_Hierarchy )); + } + if (hierarchy) + { + oDescr->hirarchy = hierarchy; + } + //################################################################ + // + // Deformable ? + // + + + pCloth *cloth = NULL; + pClothDesc cDescr; + + if (isDeformable) + { + cDescr.setToDefault(); + cDescr.worldReference = worldReferenceObject->GetID(); + + if ( result->getFlags() & BF_Gravity ) + { + cDescr.flags |= PCF_Gravity; + } + + if ( result->getFlags() & BF_Collision ) + { + + } + + if (!cloth) + { + cloth = pFactory::Instance()->createCloth(referenceObject,cDescr); + if (!cloth) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : factory object failed !"); + } + } + } + + + //################################################################ + // + // Some settings + // + if (result->getSkinWidth()==-1.0f) + { + result->setSkinWidth(0.01f); + } + + float radius = referenceObject->GetRadius(); + if (referenceObject->GetRadius() < 0.001f ) + { + radius = 1.0f; + } + + float density = result->getDensity(); + VxVector box_s= BoxGetZero(referenceObject); + + //################################################################ + // + // Calculate destination matrix + // + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + v_matrix = referenceObject->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + + NxVec3 pos = pMath::getFrom(position); + NxQuat rot = pMath::getFrom(quat); + + + ////////////////////////////////////////////////////////////////////////// + //create actors description + NxActorDesc actorDesc;actorDesc.setToDefault(); + NxBodyDesc bodyDesc;bodyDesc.setToDefault(); + + + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + + + + + switch(result->getHullType()) + { + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + + if (! isDeformable ) + { + shape.dimensions = pMath::getFrom(box_s)*0.5f; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&shape); + + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + + + if (! isDeformable ) + { + shape.radius = radius; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&shape); + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + + if (! (result->getFlags() & BF_Deformable) ) + { + + //xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Can not use a mesh as de"); + //return NULL; + + } + + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + + createMesh(world->getScene(),referenceObject->GetCurrentMesh(),myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return NULL; + } + shape.meshData = getManager()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + actorDesc.shapes.pushBack(&shape); + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + if (referenceObject->GetCurrentMesh()) + { + if (referenceObject->GetCurrentMesh()->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshs allowed, by Ageia!"); + goto nothing; + } + }else + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); + goto nothing; + + + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + createConvexMesh(world->getScene(),referenceObject->GetCurrentMesh(),myMesh); + + NxConvexShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + goto nothing; + + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + goto nothing; + } + shape.meshData = getManager()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + actorDesc.shapes.pushBack(&shape); + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + int h = shape.isValid(); + CloseCooking(); + + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexCylinder: + { + NxConvexShapeDesc shape; + if (!_createConvexCylinder(&shape,referenceObject)) + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + + shape.density = density; + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + + NxCapsuleShapeDesc shape; + + if ( !isDeformable ) + { + + pCapsuleSettings cSettings; + + pFactory::Instance()->findSettings(cSettings,referenceObject); + + shape.radius = cSettings.radius > 0.0f ? cSettings.radius : box_s.v[cSettings.localRadiusAxis] * 0.5f; + shape.height = cSettings.height > 0.0f ? cSettings.height : box_s.v[cSettings.localLengthAxis] - ( 2*shape.radius) ; + } + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + // shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + actorDesc.shapes.pushBack(&shape); + break; + } + + case HT_Wheel: + { + // xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + + + /* + NxWheelShapeDesc shape; + shape.radius = box_s.z*0.5f; + shape.density = density; + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + + if (referenceObject && referenceObject->HasAttribute(GetPMan()->att_wheelDescr )) + { + CKParameter *par = referenceObject->GetAttributeParameter(GetPMan()->att_wheelDescr ); + if (par) + { + pWheelDescr *wheelDescr = pFactory::Instance()->copyTo(par); + if (wheelDescr) + { + + float heightModifier = (wheelDescr->wheelSuspension + radius ) / wheelDescr->wheelSuspension; + shape.suspension.damper = wheelDescr->springDamping * heightModifier; + shape.suspension.targetValue = wheelDescr->springBias * heightModifier; + shape.suspensionTravel = wheelDescr->wheelSuspension; + + shape.lateralTireForceFunction.stiffnessFactor *= wheelDescr->frictionToSide; + shape.longitudalTireForceFunction.stiffnessFactor*=wheelDescr->frictionToFront; + shape.inverseWheelMass = 0.1; + int isValid = shape.isValid(); + + + actorDesc.shapes.pushBack(&shape); + } + }else + { + XString name = result->GetVT3DObject()->GetName(); + name << " needs to have an additional wheel attribute attached ! "; + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,name.CStr()); + } + } + */ + break; + } + } + + + ////////////////////////////////////////////////////////////////////////// + //dynamic object ? + if (result->getFlags() & BF_Moving){ + actorDesc.body = &bodyDesc; + } + else + actorDesc.body = NULL; + + ////////////////////////////////////////////////////////////////////////// + //set transformations + actorDesc.density = result->getDensity(); + + + if ( !isDeformable) + { + actorDesc.globalPose.t = pos; + actorDesc.globalPose.M = rot; + } + + + ////////////////////////////////////////////////////////////////////////// + //create the actor + + int v = actorDesc.isValid(); + NxActor *actor = world->getScene()->createActor(actorDesc); + if (!actor) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); + delete result; + return NULL; + + } + + ////////////////////////////////////////////////////////////////////////// + //set additional settings : + result->setActor(actor); + actor->setName(referenceObject->GetName()); + actor->userData= result; + + ////////////////////////////////////////////////////////////////////////// + //Deformable : + if (isDeformable && cloth) + { + + pDeformableSettings dSettings; + dSettings.ImpulsThresold = 50.0f; + dSettings.PenetrationDepth= 0.1f ; + dSettings.MaxDeform = 2.0f; + + CKParameterOut *poutDS = referenceObject->GetAttributeParameter(GetPMan()->att_deformable); + if (poutDS) + { + pFactory::Instance()->copyTo(dSettings,poutDS); + } + cloth->attachToCore(referenceObject,dSettings.ImpulsThresold,dSettings.PenetrationDepth,dSettings.MaxDeform); + result->setCloth(cloth); + } + + + ////////////////////////////////////////////////////////////////////////// + // + // Extra settings : + // + + if (result->getFlags() & BF_Moving) + { + VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&result->getMassOffset()); + actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); + } + + + if (result->getFlags() & BF_Kinematic) + { + result->setKinematic(true); + } + + + + if (result->getFlags() & BF_Moving ) + { + result->enableGravity(result->getFlags() & BF_Gravity); + } + + //---------------------------------------------------------------- + // + // Special Parameters + // + + //- look for optimization attribute : + result->checkForOptimization(); + + + + + //---------------------------------------------------------------- + // + // store mesh meta info in the first main mesh + // + NxShape *shape = result->getShapeByIndex(); + if (shape) + { + pSubMeshInfo *sInfo = new pSubMeshInfo(); + sInfo->entID = referenceObject->GetID(); + sInfo->refObject = (CKBeObject*)referenceObject; + shape->userData = (void*)sInfo; + result->setMainShape(shape); + shape->setName(referenceObject->GetName()); + + pMaterial bMaterial; + bool hasMaterial = pFactory::Instance()->findSettings(bMaterial,referenceObject); + if (!hasMaterial) + { + if (world->getDefaultMaterial()) + { + int z = (int)world->getDefaultMaterial()->userData; + shape->setMaterial(world->getDefaultMaterial()->getMaterialIndex()); + //pFactory::Instance()->copyTo(bMaterial,world->getDefaultMaterial()); + } + }else{ + + NxMaterialDesc nxMatDescr; + pFactory::Instance()->copyTo(nxMatDescr,bMaterial); + NxMaterial *nxMaterial = world->getScene()->createMaterial(nxMatDescr); + if (nxMaterial) + { + shape->setMaterial(nxMaterial->getMaterialIndex()); + } + + nxMaterial->userData = (void*)&bMaterial; + } + } + + result->enableCollision( (result->getFlags() & BF_Collision), referenceObject ); + result->enableCollisionsNotify((result->getFlags() & BF_CollisionNotify)); + result->enableCollisionForceCalculation((result->getFlags() & BF_CollisionsForce), referenceObject); + + + + //- handle collisions setup + if (oDescr->version == pObjectDescr::E_OD_VERSION::OD_DECR_V1) + result->updateCollisionSettings(*oDescr,referenceObject); + + + + + + xLogger::xLog(ELOGINFO,E_LI_MANAGER,"Rigid body creation successful : %s",referenceObject->GetName()); + + //---------------------------------------------------------------- + // + // Parse hierarchy + // + if (!oDescr->hirarchy) + return result; + + CK3dEntity* subEntity = NULL; + while (subEntity= referenceObject->HierarchyParser(subEntity) ) + { + if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) + { + pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + if (subDescr->flags & BF_SubShape) + { + + ////////////////////////////////////////////////////////////////////////// + // + // Regular Mesh : + // + + if (subDescr->hullType != HT_Cloth) + { + result->addSubShape(NULL,*oDescr,subEntity); + } + + ////////////////////////////////////////////////////////////////////////// + // + // Cloth Mesh : + // + if (subDescr->hullType == HT_Cloth) + { + //pClothDesc *cloth = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + } + } + } + + if (oDescr->hirarchy) + { + + + if (oDescr->newDensity!=0.0f || oDescr->totalMass!=0.0f ) + { + result->updateMassFromShapes(oDescr->newDensity,oDescr->totalMass); + } + } + + + return result; + + } + nothing: + + + + return result; +} +pRigidBody*pFactory::createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject) +{ + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // Pseudo code : + // + // 1. check the passed world, otherwise use+create the physic managers default world : + // 1. + ////////////////////////////////////////////////////////////////////////// + + if (!referenceObject) + { + return NULL; + } + + pWorld *world=GetPMan()->getWorld(worldReferenceObject,referenceObject); + if (world) + { + int p = 0; + } + + if (!world) + { + return NULL; + } + + pRigidBody *result = new pRigidBody(referenceObject,world); + + return result; + +} + + + + + + +pRigidBody*pFactory::createBody(CK3dEntity *referenceObject,pObjectDescr description,CK3dEntity *worldReferenceObject/* =NULL */) +{ + using namespace vtTools::BehaviorTools; + using namespace vtTools; + using namespace vtTools::AttributeTools; + + pRigidBody *result = NULL; + + if (!referenceObject) + return result; + + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + if (!world) + { + return result; + } + + if (referenceObject->HasAttribute(GetPMan()->GetPAttribute())) + { + referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); + } + referenceObject->SetAttribute(GetPMan()->GetPAttribute()); + + + int htype = description.hullType; + int flags = description.flags; + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HIRARCHY,&description.hirarchy); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HULLTYPE,&htype); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_BODY_FLAGS,&flags); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_DENSITY,&description.density); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_NEW_DENSITY,&description.newDensity); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_TOTAL_MASS,&description.totalMass); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_MASS_OFFSET,&description.massOffset); + + CK_ID wid = world->getReference()->GetID(); + AttributeTools::SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_WORLD,&wid); + + result = pFactory::Instance()->createRigidBodyFull(referenceObject,world->getReference()); + if (result) + { + result->translateLocalShapePosition(description.shapeOffset); + result->setCMassOffsetLocalPosition(description.massOffset); + } + + if ( ! (description.flags & BF_AddAttributes) ) + { + referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); + } + + return result; + + +} + +CK3dEntity *pFactory::getMostTopParent(CK3dEntity*ent) +{ + + if (!ent) + { + return NULL; + } + + CK3dEntity *result = ent->GetParent(); + if (result) + { + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + //if ( (!result->HasAttribute(GetPMan()->GetPAttribute())) || !(result->HasAttribute(attTypePBSetup))) + if ( (result->HasAttribute(GetPMan()->GetPAttribute())) || (result->HasAttribute(attTypePBSetup))) + { + return ent; + } + if (result->GetParent()) + { + return getMostTopParent(result); + } + else + { + return result; + } + }else + { + return ent; + } +} + + + + diff --git a/usr/Src/Core/pFactory/pFactoryClothes.cpp b/usr/Src/Core/pFactory/pFactoryClothes.cpp new file mode 100644 index 0000000..797c436 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryClothes.cpp @@ -0,0 +1,270 @@ +#include +#include "vtPhysXAll.h" + +#include "cooking.h" +#include "Stream.h" + +#include "pConfig.h" + + +void pFactory::copyTo(pDeformableSettings &dst,CKParameter*par) +{ + + if (!par) + { + return; + } + + using namespace vtTools::ParameterTools; + dst.ImpulsThresold = GetValueFromParameterStruct(par,0); + dst.PenetrationDepth = GetValueFromParameterStruct(par,1); + dst.MaxDeform = GetValueFromParameterStruct(par,2); + +} + +pCloth* pFactory::createCloth(CK3dEntity *srcReference,pClothDesc descr) +{ + + +#ifdef DONLGE + if(!GetPMan()->DongleHasAdvancedVersion) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : no license !"); + return NULL; + } +#endif + + if (!srcReference) + { + return NULL; + } + + if (!srcReference->GetCurrentMesh()) + { + return NULL; + } + + if (!descr.isValid()) + { + return NULL; + } + + CK3dEntity*worldReference = (CK3dEntity*)GetPMan()->m_Context->GetObject(descr.worldReference); + + if (!worldReference) + { + if (GetPMan()->getDefaultWorld()) + { + worldReference = GetPMan()->getDefaultWorld()->getReference(); + }else + return NULL; + } + + pWorld*world = GetPMan()->getWorld(worldReference->GetID()); + if (!world) + { + return NULL; + + } + + + pRigidBody *body = GetPMan()->getBody(srcReference); +/* if (!body) + { + return NULL; + } +*/ + + NxClothMeshDesc meshDesc; + + // if we want tearing we must tell the cooker + // this way it will generate some space for particles that will be generated during tearing + if (descr.flags & PCF_Tearable) + meshDesc.flags |= NX_CLOTH_MESH_TEARABLE; + + pCloth *result = new pCloth(); + + result->generateMeshDesc(descr,&meshDesc,srcReference->GetCurrentMesh()); + int mValid = meshDesc.isValid(); + + if (!result->cookMesh(&meshDesc)) + { + delete result; + return NULL; + } + + result->releaseMeshDescBuffers(&meshDesc); + result->allocateClothReceiveBuffers(meshDesc.numVertices, meshDesc.numTriangles); + + NxClothDesc cDescr; + copyToClothDescr(&cDescr,descr); + cDescr.clothMesh = result->getClothMesh(); + cDescr.meshData = *result->getReceiveBuffers(); + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + + v_matrix = srcReference->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + + cDescr.globalPose.t = getFrom(position); + cDescr.globalPose.M = getFrom(quat); + + + + + NxCloth *cloth = world->getScene()->createCloth(cDescr); + if (cloth) + { + result->setCloth(cloth); + result->setEntityID(srcReference->GetID()); + result->setWorld(GetPMan()->getDefaultWorld()); + cloth->userData = result; + + if (meshDesc.points) + { +// delete []meshDesc.points; +// delete []meshDesc.triangles; + } + + + + if (descr.flags & PCF_AttachToParentMainShape ) + { + if (srcReference->GetParent()) + { + CK3dEntity *bodyReference = getMostTopParent(srcReference); + if (bodyReference) + { + pRigidBody *body = GetPMan()->getBody(bodyReference); + if (body) + { + result->attachToShape((CKBeObject*)bodyReference,descr.attachmentFlags); + } + } + } + } + + if (descr.flags & PCF_AttachToCollidingShapes) + { + result->attachToCollidingShapes(descr.attachmentFlags); + } + + if (descr.flags & PCF_AttachToCore) + { +/* + + NxBodyDesc coreBodyDesc; + coreBodyDesc.linearDamping = 0.2f; + coreBodyDesc.angularDamping = 0.2f; + + NxActorDesc coreActorDesc; + coreActorDesc.density = 0.1f; + coreActorDesc.body = &coreBodyDesc; + + coreActorDesc.shapes.pushBack(new NxBoxShapeDesc()); + + NxActor *coreActor = world->getScene()->createActor(coreActorDesc); + coreActor->userData =NULL; + + + NxReal impulseThreshold = 50.0f; + NxReal penetrationDepth = 0.5f; + NxReal maxDeformationDistance = 0.5f; + + cloth->attachToCore(coreActor, impulseThreshold, penetrationDepth, maxDeformationDistance); +*/ +// result->attachToCollidingShapes(descr.attachmentFlags); + } + + return result; + } + + if (meshDesc.points) + { +// delete []meshDesc.points; +// delete []meshDesc.triangles; + } + + return result; + +} +pClothDesc* pFactory::createClothDescrFromParameter(CKParameter *par) +{ + + if (!par) + return NULL; + + pClothDesc *descr = new pClothDesc(); + + using namespace vtTools::ParameterTools; + + descr->density = GetValueFromParameterStruct(par,E_CS_DENSITY,false); + descr->thickness = GetValueFromParameterStruct(par,E_CS_THICKNESS,false); + descr->bendingStiffness = GetValueFromParameterStruct(par,E_CS_BENDING_STIFFNESS,false); + descr->stretchingStiffness = GetValueFromParameterStruct(par,E_CS_STRETCHING_STIFFNESS,false); + descr->dampingCoefficient = GetValueFromParameterStruct(par,E_CS_DAMPING_COEFFICIENT,false); + descr->friction = GetValueFromParameterStruct(par,E_CS_FRICTION,false); + + descr->pressure = GetValueFromParameterStruct(par,E_CS_PRESSURE,false); + descr->tearFactor = GetValueFromParameterStruct(par,E_CS_TEAR_FACTOR,false); + descr->collisionResponseCoefficient = GetValueFromParameterStruct(par,E_CS_COLLISIONRESPONSE_COEFFICIENT,false); + + descr->attachmentResponseCoefficient = GetValueFromParameterStruct(par,E_CS_ATTACHMENTRESPONSE_COEFFICIENT,false); + descr->attachmentTearFactor = GetValueFromParameterStruct(par,E_CS_ATTACHMENT_TEAR_FACTOR,false); + descr->toFluidResponseCoefficient = GetValueFromParameterStruct(par,E_CS_TO_FLUID_RESPONSE_COEFFICIENT,false); + + descr->fromFluidResponseCoefficient = GetValueFromParameterStruct(par,E_CS_FROM_FLUIDRESPONSE_COEFFICIENT,false); + descr->minAdhereVelocity = GetValueFromParameterStruct(par,E_CS_MIN_ADHERE_VELOCITY,false); + descr->solverIterations = GetValueFromParameterStruct(par,E_CS_SOLVER_ITERATIONS,false); + + descr->externalAcceleration = GetValueFromParameterStruct(par,E_CS_EXTERN_ALACCELERATION,false); + descr->windAcceleration = GetValueFromParameterStruct(par,E_CS_WIND_ACCELERATION,false); + descr->wakeUpCounter = GetValueFromParameterStruct(par,E_CS_WAKE_UP_COUNTER,false); + + descr->sleepLinearVelocity = GetValueFromParameterStruct(par,E_CS_SLEEP_LINEAR_VELOCITY,false); + descr->collisionGroup = GetValueFromParameterStruct(par,E_CS_COLLISIONG_ROUP,false); + + descr->validBounds = GetValueFromParameterStruct(par,E_CS_VALID_BOUNDS,false); + descr->relativeGridSpacing = GetValueFromParameterStruct(par,E_CS_RELATIVE_GRID_SPACING,false); + descr->flags = GetValueFromParameterStruct(par,E_CS_FLAGS,false); + descr->tearVertexColor = GetValueFromParameterStruct(par,E_CS_TEAR_VERTEX_COLOR,false); + + descr->worldReference = GetValueFromParameterStruct(par,E_CS_WORLD_REFERENCE,false); + + return descr; + +} + +void pFactory::copyToClothDescr(NxClothDesc* dst,pClothDesc src ) +{ + + dst->density = src.density ; + dst->thickness = src.thickness ; + dst->bendingStiffness = src.bendingStiffness; + dst->stretchingStiffness = src.stretchingStiffness; + dst->dampingCoefficient = src.dampingCoefficient; + + dst->friction = src.friction; + dst->pressure = src.pressure; + dst->tearFactor = src.tearFactor ; + dst->collisionResponseCoefficient = src.collisionResponseCoefficient ; + dst->attachmentResponseCoefficient = src.attachmentResponseCoefficient ; + dst->attachmentTearFactor = src.attachmentTearFactor ; + dst->toFluidResponseCoefficient = src.toFluidResponseCoefficient ; + dst->fromFluidResponseCoefficient= src.fromFluidResponseCoefficient ; + dst->minAdhereVelocity = src.minAdhereVelocity ; + dst->solverIterations = src.solverIterations ; + dst->externalAcceleration = getFrom(src.externalAcceleration) ; + dst->windAcceleration = getFrom(src.windAcceleration); + dst->wakeUpCounter = src.wakeUpCounter ; + dst->sleepLinearVelocity = src.sleepLinearVelocity ; + dst->collisionGroup = src.collisionGroup; + dst->validBounds.set(getFrom(src.validBounds.Min) , getFrom(src.validBounds.Max)); + dst->relativeGridSpacing = src.relativeGridSpacing; + dst->flags =src.flags; + +} \ No newline at end of file diff --git a/usr/Src/Core/pFactory/pFactoryFluids.c__ b/usr/Src/Core/pFactory/pFactoryFluids.c__ new file mode 100644 index 0000000..4817ae1 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryFluids.c__ @@ -0,0 +1,336 @@ +#include +#include "pCommon.h" +#include "pFactory.h" + +#include "CK3dPointCloud.h" + +int RenderParticles_P(CKRenderContext *dev,CKRenderObject *obj,void *arg); + +void pFactory::copyToEmitterDesc(NxFluidEmitterDesc&dst,pFluidEmitterDesc src) +{ + + + + + dst.dimensionX = src.dimensionX; + dst.dimensionY = src.dimensionY; + dst.flags = (NxFluidEmitterFlag)src.flags; + dst.fluidVelocityMagnitude = src.fluidVelocityMagnitude; + dst.maxParticles = src.maxParticles; + dst.particleLifetime = src.particleLifetime; + dst.randomAngle = src.randomAngle; + dst.randomPos = getFrom( src.randomPos); + dst.rate = src.rate; + dst.type = (NxEmitterType)src.type; + dst.repulsionCoefficient = src.repulsionCoefficient; + if (src.frameShape) + { + pWorld *w = GetPMan()->getWorldByShapeReference(src.frameShape); + if (w) + { + NxShape *shape = w->getShapeByEntityID(src.frameShape->GetID()); + if (shape) + { + dst.frameShape = shape; + }else + { + dst.frameShape = NULL; + } + } + } + + + + +} + +void pFactory::initParticles(pFluidDesc &desc,NxParticleData&dst,CK3dEntity*srcReference,CK3dEntity*dstEntity) +{ + + + CKMesh *mesh = dstEntity->GetCurrentMesh(); + if (!mesh) + return; + + ////////////////////////////////////////////////////////////////////////// + mesh->SetVertexCount(desc.maxParticles); + CKDWORD stride; + void* ptr = mesh->GetPositionsPtr(&stride); + XPtrStrided vpos(ptr,stride); + + VxVector pos(0,0,0); + + for (int i = 0 ; i < mesh->GetVertexCount();i++ ) + { + pos.x +=(float)(i*0.0001f); + mesh->SetVertexPosition(i,&pos); + } + ////////////////////////////////////////////////////////////////////////// + + mesh->VertexMove(); + + char* bufferPos = reinterpret_cast(dst.bufferPos); + char* bufferVel = reinterpret_cast(dst.bufferVel); + char* bufferLife = reinterpret_cast(dst.bufferLife); + + +// if(bufferPos == NULL && bufferVel == NULL && bufferLife == NULL) +// return; +/* + NxVec3 aabbDim; + aabb.getExtents(aabbDim); + aabbDim *= 2.0f; +*/ + (*dst.numParticlesPtr) = 0; + + for (int j = 0 ; j < desc.maxParticles ; j ++ ) + { + VxVector mPos; + mesh->GetVertexPosition(j,&mPos); + + srcReference->Transform(&mPos,&mPos); + + NxVec3 p(mPos.x,mPos.y,mPos.z); + + + NxVec3& position = *reinterpret_cast(bufferPos); + position = p; + int stride = dst.bufferPosByteStride; + bufferPos += dst.bufferPosByteStride; + + + NxVec3& velocity = *reinterpret_cast(bufferVel); + NxVec3 vel; + velocity = vel; + bufferVel += dst.bufferVelByteStride; + + if (bufferLife) + { + NxReal& life = *reinterpret_cast(bufferLife); + life = 0.0f; + bufferLife += dst.bufferLifeByteStride; + } + + (*dst.numParticlesPtr)++; + } + +} + +pFluid* pFactory::createFluid(CK3dEntity *srcReference ,pFluidDesc desc) +{ + + //Create a set of initial particles + + pParticle* initParticle = new pParticle[desc.maxParticles]; + unsigned initParticlesNum = 0; + + //Setup structure to pass initial particles. + NxParticleData initParticleData; + initParticleData.numParticlesPtr = &initParticlesNum; + initParticleData.bufferPos = &initParticle[0].position.x; + initParticleData.bufferPosByteStride = sizeof(pParticle); + initParticleData.bufferVel = &initParticle[0].velocity.x; + initParticleData.bufferVelByteStride = sizeof(pParticle); + + CK3dEntity *particleEntity = createFluidEntity(); + + CKMesh *mesh = particleEntity->GetCurrentMesh(); + mesh->SetVertexCount(desc.maxParticles); + + VxVector pos; + + srcReference->GetPosition(&pos); + particleEntity->SetPosition(&pos); + + CK3dPointCloud *cloud = createPointCloud(desc); + if (cloud) + { + cloud->SetReferentialPosition(pos); + } + + //initParticles(desc,initParticleData,srcReference,particleEntity); + + + //Setup fluid descriptor + NxFluidDesc fluidDesc; + fluidDesc.setToDefault(); + + copyToFluidDescr(fluidDesc,desc); + + /*fluidDesc.maxParticles = desc.maxParticles; + fluidDesc.kernelRadiusMultiplier = 2.0f; + fluidDesc.restParticlesPerMeter = 10.0f; + fluidDesc.motionLimitMultiplier = 3.0f; + fluidDesc.packetSizeMultiplier = 8; + fluidDesc.collisionDistanceMultiplier = 0.1; + fluidDesc.stiffness = 50.0f; + fluidDesc.viscosity = 40.0f; + fluidDesc.restDensity = 1000.0f; + fluidDesc.damping = 0.0f; + fluidDesc.restitutionForStaticShapes = 0.2f; + fluidDesc.dynamicFrictionForStaticShapes= 0.05f; + fluidDesc.simulationMethod = NX_F_SPH;*/ + fluidDesc.flags &= ~NX_FF_HARDWARE; + + + //Add initial particles to fluid creation. + fluidDesc.initialParticleData = initParticleData; + + + //Create user fluid. + //- create NxFluid in NxScene + //- setup the buffers to read from data from the SDK + //- set NxFluid::userData field to MyFluid instance + bool trackUserData = false; + bool provideCollisionNormals = false; + + pFluid* fluid = new pFluid(fluidDesc, trackUserData, provideCollisionNormals, getFrom(NxVec3(0.4f,0.5f,0.9f)), 0.03f); + + + if (fluidDesc.flags & NX_FF_HARDWARE) + { + int op = 2; + } + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + CK3dEntity*worldReference = (CK3dEntity*)GetPMan()->m_Context->GetObject(desc.worldReference); + + if (!worldReference) + { + if (GetPMan()->getDefaultWorld()) + { + worldReference = GetPMan()->getDefaultWorld()->getReference(); + }else + return NULL; + } + + pWorld*world = GetPMan()->getWorld(worldReference->GetID()); + if (!world) + { + return NULL; + + } + + int s = fluidDesc.isValid(); + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + NxFluid* xfluid = world->getScene()->createFluid(fluidDesc); + if (xfluid) + { + xfluid->userData = fluid; + fluid->setFluid( xfluid ); + fluid->setEntityID( particleEntity->GetID() ); + + particleEntity->SetRenderCallBack(RenderParticles_P,fluid); + + return fluid; + } + + return NULL; +} + +void pFactory::copyToFluidDescr(NxFluidDesc &dst , pFluidDesc src ) +{ + + dst.attractionForDynamicShapes = src.attractionForDynamicShapes; + dst.attractionForStaticShapes = src.attractionForStaticShapes; + dst.collisionDistanceMultiplier = src.collisionDistanceMultiplier; + dst.collisionGroup = src.collisionGroup; + dst.collisionMethod = src.collisionMethod; + dst.collisionResponseCoefficient =src.collisionResponseCoefficient; + dst.damping = src.damping; + dst.dynamicFrictionForDynamicShapes = src.dynamicFrictionForDynamicShapes; + dst.dynamicFrictionForStaticShapes = src.dynamicFrictionForStaticShapes; + dst.externalAcceleration = getFrom(src.externalAcceleration); + dst.fadeInTime = src.fadeInTime; + dst.kernelRadiusMultiplier = src.kernelRadiusMultiplier; + dst.packetSizeMultiplier = src.packetSizeMultiplier; + dst.maxParticles = src.maxParticles; + dst.motionLimitMultiplier = src.motionLimitMultiplier; + dst.numReserveParticles = src.numReserveParticles; + dst.packetSizeMultiplier = src.packetSizeMultiplier; + dst.restitutionForDynamicShapes = src.restitutionForDynamicShapes; + dst.restitutionForStaticShapes =src.restitutionForStaticShapes; + dst.restParticlesPerMeter = src.restParticlesPerMeter; + dst.restDensity = src.restDensity; + dst.simulationMethod = src.simulationMethod; + dst.staticFrictionForDynamicShapes = src.staticFrictionForDynamicShapes; + dst.staticFrictionForStaticShapes = src.staticFrictionForStaticShapes; + dst.stiffness = src.stiffness; + dst.surfaceTension =src.surfaceTension; + dst.viscosity =src.viscosity; + dst.flags = src.flags; + +} + + + + + +CK3dEntity*pFactory::createFluidEntity() +{ + + CK3dEntity *result = NULL; + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; + + XString name; + name << "_Decal"; + + CK3dEntity* decal = (CK3dEntity*)ctx()->CreateObject(CKCID_3DOBJECT,name.Str(),creaoptions); + + name << "Mesh"; + CKMesh* decalmesh = (CKMesh*)ctx()->CreateObject(CKCID_MESH,name.Str(),creaoptions); + if (!decalmesh) return NULL; + + // Add to the level + CKLevel* level = ctx()->GetCurrentLevel(); + CKScene* scene = ctx()->GetCurrentScene(); + + level->AddObject(decal); + level->AddObject(decalmesh); + + // And to the current scene if any + if (scene != level->GetLevelScene()) { + scene->AddObject(decal); + scene->AddObject(decalmesh); + } + + // 3DEntity + decal->SetWorldMatrix(VxMatrix::Identity()); + decal->SetCurrentMesh(decalmesh); + + return decal; + +} + + +CK3dPointCloud*pFactory::createPointCloud(const pFluidDesc&descr) +{ + + CK3dPointCloud*result = NULL; + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; + + XString name; + name << "_FluidCloud"; + + result = (CK3dPointCloud*)ctx()->CreateObject(CKCID_3DPOINTCLOUD,name.Str(),creaoptions); + // Add to the level + CKLevel* level = ctx()->GetCurrentLevel(); + CKScene* scene = ctx()->GetCurrentScene(); + + level->AddObject((CKObject*)result); + + // And to the current scene if any + if (scene != level->GetLevelScene()) { + scene->AddObject((CKSceneObject*)result); + } + + // 3DEntity + result->SetWorldMatrix(VxMatrix::Identity()); + //decal->SetCurrentMesh(decalmesh); + + return result; + + + + +} diff --git a/usr/Src/Core/pFactory/pFactoryFluids.cpp b/usr/Src/Core/pFactory/pFactoryFluids.cpp new file mode 100644 index 0000000..93a9b23 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryFluids.cpp @@ -0,0 +1,337 @@ +#include +#include "vtPhysXAll.h" + +#include "CK3dPointCloud.h" + +#ifdef HAS_FLUIDS + +int RenderParticles_P(CKRenderContext *dev,CKRenderObject *obj,void *arg); + +void pFactory::copyToEmitterDesc(NxFluidEmitterDesc&dst,pFluidEmitterDesc src) +{ + + + dst.dimensionX = src.dimensionX; + dst.dimensionY = src.dimensionY; + dst.flags = (NxFluidEmitterFlag)src.flags; + dst.fluidVelocityMagnitude = src.fluidVelocityMagnitude; + dst.maxParticles = src.maxParticles; + dst.particleLifetime = src.particleLifetime; + dst.randomAngle = src.randomAngle; + dst.randomPos = getFrom( src.randomPos); + dst.rate = src.rate; + dst.type = (NxEmitterType)src.type; + dst.repulsionCoefficient = src.repulsionCoefficient; + if (src.frameShape) + { + pWorld *w = GetPMan()->getWorldByShapeReference(src.frameShape); + if (w) + { + NxShape *shape = w->getShapeByEntityID(src.frameShape->GetID()); + if (shape) + { + dst.frameShape = shape; + }else + { + dst.frameShape = NULL; + } + } + } + + + + +} + +void pFactory::initParticles(pFluidDesc &desc,NxParticleData&dst,CK3dEntity*srcReference,CK3dEntity*dstEntity) +{ + + + CKMesh *mesh = dstEntity->GetCurrentMesh(); + if (!mesh) + return; + + ////////////////////////////////////////////////////////////////////////// + mesh->SetVertexCount(desc.maxParticles); + CKDWORD stride; + void* ptr = mesh->GetPositionsPtr(&stride); + XPtrStrided vpos(ptr,stride); + + VxVector pos(0,0,0); + + for (int i = 0 ; i < mesh->GetVertexCount();i++ ) + { + pos.x +=(float)(i*0.0001f); + mesh->SetVertexPosition(i,&pos); + } + ////////////////////////////////////////////////////////////////////////// + + mesh->VertexMove(); + + char* bufferPos = reinterpret_cast(dst.bufferPos); + char* bufferVel = reinterpret_cast(dst.bufferVel); + char* bufferLife = reinterpret_cast(dst.bufferLife); + + +// if(bufferPos == NULL && bufferVel == NULL && bufferLife == NULL) +// return; +/* + NxVec3 aabbDim; + aabb.getExtents(aabbDim); + aabbDim *= 2.0f; +*/ + (*dst.numParticlesPtr) = 0; + + for (int j = 0 ; j < desc.maxParticles ; j ++ ) + { + VxVector mPos; + mesh->GetVertexPosition(j,&mPos); + + srcReference->Transform(&mPos,&mPos); + + NxVec3 p(mPos.x,mPos.y,mPos.z); + + + NxVec3& position = *reinterpret_cast(bufferPos); + position = p; + int stride = dst.bufferPosByteStride; + bufferPos += dst.bufferPosByteStride; + + + NxVec3& velocity = *reinterpret_cast(bufferVel); + NxVec3 vel; + velocity = vel; + bufferVel += dst.bufferVelByteStride; + + if (bufferLife) + { + NxReal& life = *reinterpret_cast(bufferLife); + life = 0.0f; + bufferLife += dst.bufferLifeByteStride; + } + + (*dst.numParticlesPtr)++; + } + +} + +pFluid* pFactory::createFluid(CK3dEntity *srcReference ,pFluidDesc desc) +{ + + //Create a set of initial particles + + pParticle* initParticle = new pParticle[desc.maxParticles]; + unsigned initParticlesNum = 0; + + //Setup structure to pass initial particles. + NxParticleData initParticleData; + initParticleData.numParticlesPtr = &initParticlesNum; + initParticleData.bufferPos = &initParticle[0].position.x; + initParticleData.bufferPosByteStride = sizeof(pParticle); + initParticleData.bufferVel = &initParticle[0].velocity.x; + initParticleData.bufferVelByteStride = sizeof(pParticle); + + CK3dEntity *particleEntity = createFluidEntity(); + + CKMesh *mesh = particleEntity->GetCurrentMesh(); + mesh->SetVertexCount(desc.maxParticles); + + VxVector pos; + + srcReference->GetPosition(&pos); + particleEntity->SetPosition(&pos); + + CK3dPointCloud *cloud = createPointCloud(desc); + if (cloud) + { + cloud->SetReferentialPosition(pos); + } + + //initParticles(desc,initParticleData,srcReference,particleEntity); + + + //Setup fluid descriptor + NxFluidDesc fluidDesc; + fluidDesc.setToDefault(); + + copyToFluidDescr(fluidDesc,desc); + + /*fluidDesc.maxParticles = desc.maxParticles; + fluidDesc.kernelRadiusMultiplier = 2.0f; + fluidDesc.restParticlesPerMeter = 10.0f; + fluidDesc.motionLimitMultiplier = 3.0f; + fluidDesc.packetSizeMultiplier = 8; + fluidDesc.collisionDistanceMultiplier = 0.1; + fluidDesc.stiffness = 50.0f; + fluidDesc.viscosity = 40.0f; + fluidDesc.restDensity = 1000.0f; + fluidDesc.damping = 0.0f; + fluidDesc.restitutionForStaticShapes = 0.2f; + fluidDesc.dynamicFrictionForStaticShapes= 0.05f; + fluidDesc.simulationMethod = NX_F_SPH;*/ + fluidDesc.flags &= ~NX_FF_HARDWARE; + + + //Add initial particles to fluid creation. + fluidDesc.initialParticleData = initParticleData; + + + //Create user fluid. + //- create NxFluid in NxScene + //- setup the buffers to read from data from the SDK + //- set NxFluid::userData field to MyFluid instance + bool trackUserData = false; + bool provideCollisionNormals = false; + + pFluid* fluid = new pFluid(fluidDesc, trackUserData, provideCollisionNormals, getFrom(NxVec3(0.4f,0.5f,0.9f)), 0.03f); + + + if (fluidDesc.flags & NX_FF_HARDWARE) + { + int op = 2; + } + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + CK3dEntity*worldReference = (CK3dEntity*)GetPMan()->m_Context->GetObject(desc.worldReference); + + if (!worldReference) + { + if (GetPMan()->getDefaultWorld()) + { + worldReference = GetPMan()->getDefaultWorld()->getReference(); + }else + return NULL; + } + + pWorld*world = GetPMan()->getWorld(worldReference->GetID()); + if (!world) + { + return NULL; + + } + + int s = fluidDesc.isValid(); + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + NxFluid* xfluid = world->getScene()->createFluid(fluidDesc); + if (xfluid) + { + xfluid->userData = fluid; + fluid->setFluid( xfluid ); + fluid->setEntityID( particleEntity->GetID() ); + + particleEntity->SetRenderCallBack(RenderParticles_P,fluid); + + return fluid; + } + + return NULL; +} + +void pFactory::copyToFluidDescr(NxFluidDesc &dst , pFluidDesc src ) +{ + + dst.attractionForDynamicShapes = src.attractionForDynamicShapes; + dst.attractionForStaticShapes = src.attractionForStaticShapes; + dst.collisionDistanceMultiplier = src.collisionDistanceMultiplier; + dst.collisionGroup = src.collisionGroup; + dst.collisionMethod = src.collisionMethod; + dst.collisionResponseCoefficient =src.collisionResponseCoefficient; + dst.damping = src.damping; + dst.dynamicFrictionForDynamicShapes = src.dynamicFrictionForDynamicShapes; + dst.dynamicFrictionForStaticShapes = src.dynamicFrictionForStaticShapes; + dst.externalAcceleration = getFrom(src.externalAcceleration); + dst.fadeInTime = src.fadeInTime; + dst.kernelRadiusMultiplier = src.kernelRadiusMultiplier; + dst.packetSizeMultiplier = src.packetSizeMultiplier; + dst.maxParticles = src.maxParticles; + dst.motionLimitMultiplier = src.motionLimitMultiplier; + dst.numReserveParticles = src.numReserveParticles; + dst.packetSizeMultiplier = src.packetSizeMultiplier; + dst.restitutionForDynamicShapes = src.restitutionForDynamicShapes; + dst.restitutionForStaticShapes =src.restitutionForStaticShapes; + dst.restParticlesPerMeter = src.restParticlesPerMeter; + dst.restDensity = src.restDensity; + dst.simulationMethod = src.simulationMethod; + dst.staticFrictionForDynamicShapes = src.staticFrictionForDynamicShapes; + dst.staticFrictionForStaticShapes = src.staticFrictionForStaticShapes; + dst.stiffness = src.stiffness; + dst.surfaceTension =src.surfaceTension; + dst.viscosity =src.viscosity; + dst.flags = src.flags; + +} + + + + + +CK3dEntity*pFactory::createFluidEntity() +{ + + CK3dEntity *result = NULL; + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; + + XString name; + name << "_Decal"; + + CK3dEntity* decal = (CK3dEntity*)ctx()->CreateObject(CKCID_3DOBJECT,name.Str(),creaoptions); + + name << "Mesh"; + CKMesh* decalmesh = (CKMesh*)ctx()->CreateObject(CKCID_MESH,name.Str(),creaoptions); + if (!decalmesh) return NULL; + + // Add to the level + CKLevel* level = ctx()->GetCurrentLevel(); + CKScene* scene = ctx()->GetCurrentScene(); + + level->AddObject(decal); + level->AddObject(decalmesh); + + // And to the current scene if any + if (scene != level->GetLevelScene()) { + scene->AddObject(decal); + scene->AddObject(decalmesh); + } + + // 3DEntity + decal->SetWorldMatrix(VxMatrix::Identity()); + decal->SetCurrentMesh(decalmesh); + + return decal; + +} + + +CK3dPointCloud*pFactory::createPointCloud(const pFluidDesc&descr) +{ + + CK3dPointCloud*result = NULL; + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; + + XString name; + name << "_FluidCloud"; + + result = (CK3dPointCloud*)ctx()->CreateObject(CKCID_3DPOINTCLOUD,name.Str(),creaoptions); + // Add to the level + CKLevel* level = ctx()->GetCurrentLevel(); + CKScene* scene = ctx()->GetCurrentScene(); + + level->AddObject((CKObject*)result); + + // And to the current scene if any + if (scene != level->GetLevelScene()) { + scene->AddObject((CKSceneObject*)result); + } + + // 3DEntity + result->SetWorldMatrix(VxMatrix::Identity()); + //decal->SetCurrentMesh(decalmesh); + + return result; + + + + +} + +#endif // HAS_FLUIDS \ No newline at end of file diff --git a/usr/Src/Core/pFactory/pFactoryJoint.cpp b/usr/Src/Core/pFactory/pFactoryJoint.cpp new file mode 100644 index 0000000..033c714 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryJoint.cpp @@ -0,0 +1,1895 @@ +#include +#include "vtPhysXAll.h" + +static pFactory* pFact = NULL; + +int _registerJointAttributeType(CKGUID guid,char *name) +{ + CKParameterManager *pm = static_cast(GetPMan()->GetContext()->GetParameterManager()); + CKAttributeManager *am = (CKAttributeManager*)GetPMan()->GetContext()->GetAttributeManager(); + +// CKSTRING test = vtTools::ParameterTools::GetParameterAsString(p); +// if (!strlen(test))return; + + CKAttributeType aIType = am->GetAttributeTypeByName(name); + if (aIType==-1) + { + aIType = am->RegisterNewAttributeType(name,guid,CKCID_OBJECT); + am->SetAttributeCategory(aIType,"Physic Constraints"); + } + return aIType; +} + + + +int pFactory::cloneLimitPlanes(pJoint *src,pJoint *dst,CK3dEntity *srcReference,CK3dEntity *dstReference) +{ + //---------------------------------------------------------------- + // + // sanity checks + // + #ifdef _DEBUG + assert(src); + assert(dst); + assert(dstReference); + assert(srcReference); + #endif // _DEBUG + + NxJoint *j = src->getJoint(); + if (!j) + return 0; + + + int numLimitPlanes = src->getNbLimitPlanes(); + if (!numLimitPlanes) + return -1; + + NxVec3 *planeNormal = new NxVec3[numLimitPlanes]; + NxReal *planeD = new NxReal[numLimitPlanes]; + NxReal *restitution = new NxReal[numLimitPlanes]; + + NxVec3 planeLimitPt; + bool onActor2 = j->getLimitPoint( planeLimitPt ); + NxVec3 *worldLimitPt = new NxVec3[numLimitPlanes]; + + //---------------------------------------------------------------- + // + // copy to buffer + // + j->resetLimitPlaneIterator(); + + for(int iter=0 ; iter < numLimitPlanes ; iter++ ) + { + j->getNextLimitPlane( planeNormal[iter], planeD[iter], &restitution[iter] ); + } + + + + //---------------------------------------------------------------- + // + // create limitPoints + // + + dst->setLimitPoint(getFrom(planeLimitPt),onActor2); + + + for(int iter=0 ; iter < numLimitPlanes ; iter++ ) + { + + if ( ( fabs(planeNormal[iter].z) > fabs(planeNormal[iter].x) ) && + ( fabs(planeNormal[iter].z) > fabs(planeNormal[iter].y) ) ) + { + worldLimitPt[iter].x = planeLimitPt.x; + worldLimitPt[iter].y = planeLimitPt.y; + worldLimitPt[iter].z = -planeD[iter] / planeNormal[iter].z; + } + // k, that didn't work - try x,z = 0 + else if ( ( fabs(planeNormal[iter].y) > fabs(planeNormal[iter].x) ) && + ( fabs(planeNormal[iter].y) > fabs(planeNormal[iter].z) ) ) + { + worldLimitPt[iter].x = planeLimitPt.x; + worldLimitPt[iter].z = planeLimitPt.z; + worldLimitPt[iter].y = -planeD[iter] / planeNormal[iter].y; + } + else + { + worldLimitPt[iter].y = planeLimitPt.y; + worldLimitPt[iter].z = planeLimitPt.z; + worldLimitPt[iter].x = -planeD[iter] / planeNormal[iter].x; + } + + dst->addLimitPlane(getFrom(planeNormal[iter]),getFrom(worldLimitPt[iter]),restitution[iter]); + + } + + delete []worldLimitPt; + delete []planeNormal; + delete []restitution; + delete []planeD; + + worldLimitPt = NULL; + planeD = NULL; + restitution = NULL; + planeD = NULL; + + + return numLimitPlanes; + +} + +pJoint *pFactory::cloneJoint(pJoint *src,CK3dEntity *srcReference,CK3dEntity *dstReference,int copyFlags) +{ + + //---------------------------------------------------------------- + // + // sanity checks + // + #ifdef _DEBUG + assert(src); + assert(dstReference); + #endif // _DEBUG + + + //---------------------------------------------------------------- + // + // Prepare pointers + // + NxActor *actorA = NULL; + pRigidBody *actorABody = GetPMan()->getBody(dstReference); + if (actorABody){ + actorA = actorABody->getActor(); + } + else{ + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"You need at least one rigid body"); + return NULL; + } + + + + //actorB can be NULL and can not be the same as actorA : + NxActor *actorB = NULL; + pRigidBody *actorBBody = NULL; + CK3dEntity *referenceB = NULL; + + + //---------------------------------------------------------------- + // + // determine the first, this will be the clone ! + // + if ( src->GetVTEntA() && src->GetVTEntA() !=srcReference ) + { + actorBBody = GetPMan()->getBody(src->GetVTEntA()); + if (actorBBody) + { + actorB = actorBBody->getActor(); + referenceB = actorBBody->GetVT3DObject(); + } + } + + //---------------------------------------------------------------- + // + // determine the second + // + if ( src->GetVTEntB() && src->GetVTEntB() !=srcReference ) + { + actorBBody = GetPMan()->getBody(src->GetVTEntB()); + if (actorBBody) + { + actorB = actorBBody->getActor(); + referenceB = actorBBody->GetVT3DObject(); + } + } + + if ( (copyFlags & PB_CF_SWAP_JOINTS_REFERENCES) ) + { + XSwap(actorA,actorB); + XSwap(actorABody,actorBBody); + + } + + CK3dEntity *testA = actorABody->GetVT3DObject(); + CK3dEntity *testB = NULL; + if (actorBBody) + testB = actorBBody->GetVT3DObject(); + + + + switch (src->getType()) + { + + //---------------------------------------------------------------- + // + // Distance Joint : + // + case JT_Distance : + { + + NxDistanceJoint *nxSrc = src->getJoint()->isDistanceJoint(); + if (nxSrc) + { + NxDistanceJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxDistanceJoint *nxJoint = (NxDistanceJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointDistance *joint = new pJointDistance(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + + return joint; + } + break; + } + + //---------------------------------------------------------------- + // + // Fixed Joint : + // + case JT_Fixed : + { + + NxFixedJoint *nxSrc = src->getJoint()->isFixedJoint(); + if (nxSrc) + { + NxFixedJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxFixedJoint *nxJoint = (NxFixedJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointFixed *joint = new pJointFixed(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // Ball Joint : + // + case JT_Spherical: + { + + NxSphericalJoint *nxSrc = src->getJoint()->isSphericalJoint(); + if (nxSrc) + { + NxSphericalJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxSphericalJoint *nxJoint = (NxSphericalJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointBall *joint = new pJointBall(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // Revolute Joint : + // + case JT_Revolute: + { + + NxRevoluteJoint *nxSrc = src->getJoint()->isRevoluteJoint(); + if (nxSrc) + { + NxRevoluteJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxRevoluteJoint *nxJoint = (NxRevoluteJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointRevolute *joint = new pJointRevolute(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // Cylindrical Joint : + // + case JT_Cylindrical: + { + + NxCylindricalJoint *nxSrc = src->getJoint()->isCylindricalJoint(); + if (nxSrc) + { + NxCylindricalJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxCylindricalJoint *nxJoint = (NxCylindricalJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointCylindrical*joint = new pJointCylindrical(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // Prismatic Joint : + // + case JT_Prismatic: + { + + NxPrismaticJoint *nxSrc = src->getJoint()->isPrismaticJoint(); + if (nxSrc) + { + NxPrismaticJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxPrismaticJoint *nxJoint = (NxPrismaticJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPrismatic*joint = new pJointPrismatic(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // PointInPlane Joint : + // + case JT_PointInPlane: + { + + NxPointInPlaneJoint*nxSrc = src->getJoint()->isPointInPlaneJoint(); + if (nxSrc) + { + NxPointInPlaneJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxPointInPlaneJoint *nxJoint = (NxPointInPlaneJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPointInPlane*joint = new pJointPointInPlane(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // PointOnLine Joint : + // + case JT_PointOnLine: + { + + NxPointOnLineJoint*nxSrc = src->getJoint()->isPointOnLineJoint(); + if (nxSrc) + { + NxPointOnLineJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxPointOnLineJoint *nxJoint = (NxPointOnLineJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPointOnLine*joint = new pJointPointOnLine(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + } + break; + } + } + return NULL; +} + +void pFactory::cloneJoints(CK3dEntity *src,CK3dEntity *dst,int copyFlags) +{ + + //---------------------------------------------------------------- + // + // sanity checks + // + #ifdef _DEBUG + assert(src); + assert(dst); + #endif // _DEBUG + + + pRigidBody *srcBody = GetPMan()->getBody(src); + pRigidBody *dstBody = GetPMan()->getBody(dst); + + XString errMsg; + + if ( !srcBody || !dstBody ) + { + errMsg.Format("You need two rigid objects to clone joints from a rigid body"); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMsg.Str()); + return; + } + + pWorld* srcBodyWorld = srcBody->getWorld(); + pWorld* dstBodyWorld = dstBody->getWorld(); + + if( !srcBodyWorld || !dstBodyWorld ) + { + errMsg.Format("You need two valid world objects to clone joints from a rigid body"); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMsg.Str()); + return; + } + + if( srcBodyWorld!=dstBodyWorld ) + { + errMsg.Format("Worlds objects must be same"); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMsg.Str()); + return; + } + + //---------------------------------------------------------------- + // + // copy process + // + + pWorld *testWorld = dstBodyWorld; + + + NxU32 jointCount = testWorld->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + testWorld->getScene()->resetJointIterator(); + + NxJoint *last = NULL; + pJoint *lastJ = NULL; + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = testWorld->getScene()->getNextJoint(); + pJoint *mJoint = static_cast( j->userData ); + if ( mJoint ) + { + if (mJoint==lastJ)// avoid double clone + { + continue; + } + + if (mJoint->GetVTEntA() == srcBody->GetVT3DObject() || mJoint->GetVTEntB() == srcBody->GetVT3DObject() ) + { + pJoint *clone = pFactory::cloneJoint(mJoint,src,dst,copyFlags); + if (clone ) + { + if ((copyFlags & PB_CF_LIMIT_PLANES)) + { + int limitPlanes = pFactory::cloneLimitPlanes(mJoint,clone,src,dst); + } + } + } + } + lastJ = mJoint; + } + } +} + + +pJointPointOnLine*pFactory::createPointOnLineJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision,float maxForce,float maxTorque,const char* attributeName) +{ + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + ////////////////////////////////////////////////////////////////////////// + // + // store as attributes only ! + // + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + + CK3dEntity *referenceObject = a ? a : b ? b : NULL; + CK3dEntity *other = b ? b :NULL; + + + if (referenceObject) + { + + XString name(attributeName); + int attributeType = _registerJointAttributeType(VTS_JOINT_POINT_ON_LINE,name.Str()); + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attributeType)) + { + referenceObject->RemoveAttribute(attributeType); + } + referenceObject->SetAttribute(attributeType); + ////////////////////////////////////////////////////////////////////////// + // store settings into attributes + CKParameterOut *parAttribute = referenceObject->GetAttributeParameter(attributeType); + if (parAttribute) + { + if (other) + SetParameterStructureValue(parAttribute,PS_JPOL_BODY_B,other->GetID()); + SetParameterStructureValue(parAttribute,PS_JPOL_ANCHOR,anchor); + SetParameterStructureValue(parAttribute,PS_JPOL_AXIS,axis); + SetParameterStructureValue(parAttribute,PS_JPOL_COLLISION,collision); + + SetParameterStructureValue(parAttribute,PS_JPOL_MAX_FORCE,maxForce); + SetParameterStructureValue(parAttribute,PS_JPOL_MAX_FORCE,maxTorque); + } + } + return NULL; + } + } + + if (jointCheckPreRequisites(a,b,JT_PointOnLine) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + NxPointOnLineJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.setGlobalAxis(getFrom(axis)); + desc.setGlobalAnchor(getFrom(anchor)); + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + NxPointOnLineJoint* nxJoint = (NxPointOnLineJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPointOnLine*joint = new pJointPointOnLine(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + return joint; +} + +pJointPointInPlane*pFactory::createPointInPlaneJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision,float maxForce,float maxTorque,const char* attributeName) +{ + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + ////////////////////////////////////////////////////////////////////////// + // + // store as attributes only ! + // + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + + CK3dEntity *referenceObject = a ? a : b ? b : NULL; + CK3dEntity *other = b ? b :NULL; + if (referenceObject) + { + XString name(attributeName); + int attributeType = _registerJointAttributeType(VTS_JOINT_POINT_IN_PLANE,name.Str()); + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attributeType)) + { + referenceObject->RemoveAttribute(attributeType); + } + referenceObject->SetAttribute(attributeType); + ////////////////////////////////////////////////////////////////////////// + // store settings into attributes + CKParameterOut *parAttribute = referenceObject->GetAttributeParameter(attributeType); + if (parAttribute) + { + if (other) + SetParameterStructureValue(parAttribute,PS_JPIP_BODY_B,other->GetID()); + + SetParameterStructureValue(parAttribute,PS_JPIP_ANCHOR,anchor); + SetParameterStructureValue(parAttribute,PS_JPIP_AXIS,axis); + SetParameterStructureValue(parAttribute,PS_JPIP_COLLISION,collision); + SetParameterStructureValue(parAttribute,PS_JPIP_MAX_FORCE,maxForce); + SetParameterStructureValue(parAttribute,PS_JPIP_MAX_TORQUE,maxTorque); + } + } + return NULL; + } + } + + + if (jointCheckPreRequisites(a,b,JT_PointInPlane) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + NxPointInPlaneJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.setGlobalAxis(getFrom(axis)); + desc.setGlobalAnchor(getFrom(anchor)); + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + NxPointInPlaneJoint* nxJoint = (NxPointInPlaneJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPointInPlane*joint = new pJointPointInPlane(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + return joint; +} + +pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision,float maxForce,float maxTorque,const char* attributeName) +{ + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + ////////////////////////////////////////////////////////////////////////// + // + // store as attributes only ! + // + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + + CK3dEntity *referenceObject = a ? a : b ? b : NULL; + CK3dEntity *other = b ? b :NULL; + + + if (referenceObject) + { + + XString name(attributeName); + int attributeType = _registerJointAttributeType(VTS_JOINT_CYLINDRICAL,name.Str()); + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attributeType)) + { + referenceObject->RemoveAttribute(attributeType); + } + referenceObject->SetAttribute(attributeType); + ////////////////////////////////////////////////////////////////////////// + // store settings into attributes + CKParameterOut *parAttribute = referenceObject->GetAttributeParameter(attributeType); + if (parAttribute) + { + if (other) + SetParameterStructureValue(parAttribute,PS_JCYLINDRICAL_BODY_B,other->GetID()); + + SetParameterStructureValue(parAttribute,PS_JCYLINDRICAL_ANCHOR,anchor); + SetParameterStructureValue(parAttribute,PS_JCYLINDRICAL_AXIS,axis); + SetParameterStructureValue(parAttribute,PS_JCYLINDRICAL_COLLISION,collision); + + SetParameterStructureValue(parAttribute,PS_JCYLINDRICAL_MAX_FORCE,maxForce); + SetParameterStructureValue(parAttribute,PS_JCYLINDRICAL_MAX_TORQUE,maxTorque); + } + } + return NULL; + } + } + + + if (jointCheckPreRequisites(a,b,JT_Cylindrical) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + NxCylindricalJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.setGlobalAxis(getFrom(axis)); + desc.setGlobalAnchor(getFrom(anchor)); + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + NxCylindricalJoint* nxJoint = (NxCylindricalJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointCylindrical*joint = new pJointCylindrical(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + return joint; + +} +pJointPrismatic *pFactory::createPrismaticJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis,bool collision,float maxForce,float maxTorque,const char* attributeName) +{ + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + ////////////////////////////////////////////////////////////////////////// + // + // store as attributes only ! + // + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + + CK3dEntity *referenceObject = a ? a : b ? b : NULL; + CK3dEntity *other = b ? b :NULL; + + + if (referenceObject) + { + XString name(attributeName); + int attributeType = _registerJointAttributeType(VTS_JOINT_PRISMATIC,name.Str()); + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attributeType)) + { + referenceObject->RemoveAttribute(attributeType); + } + referenceObject->SetAttribute(attributeType); + ////////////////////////////////////////////////////////////////////////// + // store settings into attributes + CKParameterOut *parAttribute = referenceObject->GetAttributeParameter(attributeType); + if (parAttribute) + { + if (other) + SetParameterStructureValue(parAttribute,PS_JPRISMATIC_BODY_B,other->GetID()); + + SetParameterStructureValue(parAttribute,PS_JPRISMATIC_ANCHOR,anchor); + SetParameterStructureValue(parAttribute,PS_JPRISMATIC_AXIS,axis); + SetParameterStructureValue(parAttribute,PS_JPRISMATIC_COLLISION,collision); + + SetParameterStructureValue(parAttribute,PS_JPRISMATIC_MAX_FORCE,maxForce); + SetParameterStructureValue(parAttribute,PS_JPRISMATIC_MAX_TORQUE,maxTorque); + } + } + return NULL; + } + } + + + + if (jointCheckPreRequisites(a,b,JT_Prismatic) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + NxPrismaticJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.setGlobalAxis(getFrom(axis)); + desc.setGlobalAnchor(getFrom(anchor)); + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + NxPrismaticJoint* nxJoint = (NxPrismaticJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPrismatic*joint = new pJointPrismatic(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + return joint; + +} +pJointRevolute*pFactory::createRevoluteJoint(CK3dEntity*a,CK3dEntity*b, + VxVector anchor,VxVector axis, + bool collision,float maxForce,float maxTorque,const char* attributeName) +{ + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + ////////////////////////////////////////////////////////////////////////// + // + // store as attributes only ! + // + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + + CK3dEntity *referenceObject = a ? a : b ? b : NULL; + CK3dEntity *other = b ? b :NULL; + if (referenceObject) + { + XString name(attributeName); + int attributeType = _registerJointAttributeType(VTS_JOINT_REVOLUTE,name.Str()); + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attributeType)) + { + referenceObject->RemoveAttribute(attributeType); + } + referenceObject->SetAttribute(attributeType); + ////////////////////////////////////////////////////////////////////////// + // store settings into attributes + CKParameterOut *parAttribute = referenceObject->GetAttributeParameter(attributeType); + if (parAttribute) + { + if (other) + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_BODY_B,other->GetID()); + + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_ANCHOR,anchor); + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_AXIS,axis); + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_COLLISION,collision); + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_MAX_FORCE,maxForce); + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_MAX_TORQUE,maxTorque); + } + } + return NULL; + } + } + + + + if (jointCheckPreRequisites(a,b,JT_Revolute) == -1 ) + { + return NULL; + } + + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + + if (!ba && !bb) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"No body specified"); + return NULL; + } + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world && bb) + { + world = bb->getWorld(); + } + + + NxRevoluteJointDesc descr; + + /*descr.projectionDistance = (NxReal)0.05; + descr.projectionAngle= (NxReal)0.05; + descr.projectionMode = NX_JPM_POINT_MINDIST;*/ + + + + if (ba) + { + descr.actor[0]=ba->getActor(); + } + + if (bb) + { + descr.actor[1]=bb->getActor(); + } + + NxRevoluteJoint *nxJoint=(NxRevoluteJoint*)world->getScene()->createJoint(descr); + + if (!descr.isValid()) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Revolute joint invalid!"); + return NULL; + } + + nxJoint->setGlobalAnchor(getFrom(anchor)); + nxJoint->setGlobalAxis(getFrom(axis)); + + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointRevolute*joint = new pJointRevolute(ba,bb); + nxJoint->userData = joint; + joint->setWorld(world); + joint->setJoint(nxJoint); + + + + return joint; + + + +} + + +pJointPulley* +pFactory::createPulleyJoint( CK3dEntity*a,CK3dEntity*b, + VxVector pulley0,VxVector pulley1,VxVector anchor0, + VxVector anchor1, + bool collision,float maxForce,float maxTorque) +{ + + /* + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + ////////////////////////////////////////////////////////////////////////// + // + // store as attributes only ! + // + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + + CK3dEntity *referenceObject = a ? a : b ? b : NULL; + CK3dEntity *other = b ? b :NULL; + if (referenceObject) + { + int attributeType = GetPMan()->getAttributeTypeByGuid(VTS_JOINT_REVOLUTE); + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attributeType)) + { + referenceObject->RemoveAttribute(attributeType); + } + referenceObject->SetAttribute(attributeType); + ////////////////////////////////////////////////////////////////////////// + // store settings into attributes + CKParameterOut *parAttribute = referenceObject->GetAttributeParameter(attributeType); + if (parAttribute) + { + if (other) + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_BODY_B,other->GetID()); + + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_ANCHOR,anchor); + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_AXIS,axis); + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_COLLISION,collision); + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_MAX_FORCE,maxForce); + SetParameterStructureValue(parAttribute,PS_JREVOLUTE_MAX_TORQUE,maxTorque); + } + } + return NULL; + } + } + + */ + + if (jointCheckPreRequisites(a,b,JT_Pulley) == -1 ) + { + return NULL; + } + + + VxVector globalAxis(0,1,0); + float distance = 10.0f; + float ratio = 1.0f; + float stiffness = 1.0f; + int flags = 0 ; + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + + if (!ba && !bb) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"You need two bodies for a pulley joint!"); + return NULL; + } + pWorld*world = GetPMan()->getWorldByBody(a); + + + ////////////////////////////////////////////////////////////////////////// + // nx object : + NxPulleyJointDesc descr; + descr.setToDefault(); + + descr.actor[0]=ba->getActor(); + descr.actor[1]=bb->getActor(); + descr.localAnchor[0] = pMath::getFrom(anchor0); + descr.localAnchor[1] = pMath::getFrom(anchor1); + descr.setGlobalAxis(pMath::getFrom(globalAxis)); + + + + descr.pulley[0] = pMath::getFrom(pulley0); // suspension points of two bodies in world space. + descr.pulley[1] = pMath::getFrom(pulley1); // suspension points of two bodies in world space. + descr.distance = distance; // the rest length of the rope connecting the two objects. The distance is computed as ||(pulley0 - anchor0)|| + ||(pulley1 - anchor1)|| * ratio. + descr.stiffness = stiffness; // how stiff the constraint is, between 0 and 1 (stiffest) + descr.ratio = ratio; // transmission ratio + descr.flags = flags; // This is a combination of the bits defined by ::NxPulleyJointFlag. + + if (!descr.isValid()) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Pully joint invalid!"); + return NULL; + } + NxPulleyJoint *nxJoint = (NxPulleyJoint*)world->getScene()->createJoint(descr); + if (!nxJoint) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPulley*joint = new pJointPulley(ba,bb); + nxJoint->userData = joint; + joint->setWorld(world); + joint->setJoint(nxJoint); + return joint; + + + //descr.motor = gMotorDesc; + // pulleyDesc.projectionMode = NX_JPM_NONE; + // pulleyDesc.projectionMode = NX_JPM_POINT_MINDIST; + // pulleyDesc.jointFlags |= NX_JF_COLLISION_ENABLED; + return NULL; +} + +pJointFixed*pFactory::createFixedJoint(CK3dEntity *a, CK3dEntity *b,float maxForce, float maxTorque,const char* attributeName) +{ + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + ////////////////////////////////////////////////////////////////////////// + // + // store as attributes only ! + // + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + + CK3dEntity *referenceObject = a ? a : b ? b : NULL; + CK3dEntity *other = b ? b :NULL; + + if (referenceObject) + { + + XString name(attributeName); + int attributeType = _registerJointAttributeType(VTS_JOINT_FIXED,name.Str()); + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attributeType)) + { + referenceObject->RemoveAttribute(attributeType); + } + referenceObject->SetAttribute(attributeType); + ////////////////////////////////////////////////////////////////////////// + // store settings into attributes + CKParameterOut *parAttribute = referenceObject->GetAttributeParameter(attributeType); + if (parAttribute) + { + if (other) + { + SetParameterStructureValue(parAttribute,0,other->GetID()); + } + SetParameterStructureValue(parAttribute,1,maxForce); + SetParameterStructureValue(parAttribute,2,maxTorque); + } + } + int op = 2; + return 0; + } + } + + + if (jointCheckPreRequisites(a,b,JT_Fixed) == -1 ) + { + return NULL; + } + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + + NxFixedJointDesc descr; + descr.actor[0] = a0; + descr.actor[1] = a1; + + if (!descr.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + + NxJoint *nxJoint = (NxDistanceJoint*)world->getScene()->createJoint(descr); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointFixed*joint = new pJointFixed(ba,bb); + nxJoint->userData = joint; + joint->setWorld(world); + joint->setJoint(nxJoint); + return joint; + +} + +pJointD6*pFactory::createD6Joint(CK3dEntity *a, CK3dEntity *b, VxVector globalAnchor,VxVector globalAxis,bool collision,float maxForce, float maxTorque) +{ + + if (jointCheckPreRequisites(a,b,JT_D6) == -1 ) + { + return NULL; + } + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + + NxD6JointDesc d6Desc; + d6Desc.actor[0] = a0; + d6Desc.actor[1] = a1; + d6Desc.setGlobalAnchor(pMath::getFrom(globalAnchor)); + d6Desc.setGlobalAxis(pMath::getFrom(globalAxis)); + if (collision) + { + //d6Desc.flags + d6Desc.jointFlags|=NX_JF_COLLISION_ENABLED; + } + + + + if (!d6Desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + + NxJoint *nxJoint = (NxDistanceJoint*)world->getScene()->createJoint(d6Desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointD6 *joint = new pJointD6(ba,bb); + nxJoint->userData = joint; + + joint->setWorld(world); + joint->setJoint(nxJoint); + return joint; + +} +pJointBall *pFactory::createBallJoint(CK3dEntity*a,CK3dEntity*b, + VxVector anchor,VxVector swingAxis,VxVector globalAxis, + bool collision,float maxForce,float maxTorque,const char* attributeName) +{ + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + ////////////////////////////////////////////////////////////////////////// + // + // store as attributes only ! + // + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + CK3dEntity *referenceObject = a ? a : b ? b : NULL; + CK3dEntity *other = b ? b :NULL; + if (referenceObject) + { + XString name(attributeName); + int attributeType = _registerJointAttributeType(VTS_JOINT_BALL,name.Str()); + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attributeType)) + { + referenceObject->RemoveAttribute(attributeType); + } + referenceObject->SetAttribute(attributeType); + ////////////////////////////////////////////////////////////////////////// + // store settings into attributes + CKParameterOut *parAttribute = referenceObject->GetAttributeParameter(attributeType); + if (parAttribute) + { + if (other) + SetParameterStructureValue(parAttribute,PS_JBALL_BODY_B,other->GetID()); + + SetParameterStructureValue(parAttribute,PS_JBALL_ANCHOR,anchor); + SetParameterStructureValue(parAttribute,PS_JBALL_COLLISION,collision); + SetParameterStructureValue(parAttribute,PS_JBALL_MAX_FORCE,maxForce); + SetParameterStructureValue(parAttribute,PS_JBALL_MAX_TORQUE,maxTorque); + } + } + return NULL; + } + } + + + pJointBall *result; + + if (jointCheckPreRequisites(a,b,JT_Spherical) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + + NxSphericalJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.swingAxis = pMath::getFrom(swingAxis); + + if (globalAxis.SquareMagnitude() > 0.01f ) + desc.setGlobalAxis(getFrom(globalAxis)); + + + /*desc.projectionDistance = (NxReal)0.15; + desc.projectionMode = NX_JPM_POINT_MINDIST;*/ + + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + + NxSphericalJoint* nxJoint = (NxSphericalJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointBall*joint = new pJointBall(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + nxJoint->setGlobalAnchor(pMath::getFrom(anchor)); + //nxJoint->setGlobalAxis(NxVec3(0,1,0)); + + + + joint->setWorld(world); + + return joint; +} + +int pFactory::jointCheckPreRequisites(CK3dEntity*_a,CK3dEntity*_b,int type) +{ + + pRigidBody *a = GetPMan()->getBody(_a); + pRigidBody *b = GetPMan()->getBody(_b); + + //bodies have already a joint together ? + if ( !a && !b) + { + return -1; + } + + if (a && !a->isValid() ) + { + return -1; + } + + if (a && !GetPMan()->getWorldByBody(_a)) + { + return -1; + } + + if (b && !GetPMan()->getWorldByBody(_b)) + { + return -1; + } + + if (b && !b->isValid()) + { + return -1; + } + + + if ( a && b ) + { + pWorld*worldA = GetPMan()->getWorldByBody(_a); + pWorld*worldB = GetPMan()->getWorldByBody(_b); + if (!worldA || !worldB || (worldA!=worldB) || !worldA->isValid() ) + { + return -1; + } + } + + + return 1; +} + +pJointDistance*pFactory::createDistanceJoint(CK3dEntity*a,CK3dEntity*b, + VxVector anchor0,VxVector anchor1, + float minDistance,float maxDistance, + pSpring sSettings, + bool collision,float maxForce,float maxTorque,const char* attributeName) +{ + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + ////////////////////////////////////////////////////////////////////////// + // + // store as attributes only ! + // + if ( !GetPMan()->isValid() ) + { + if (!GetPMan()->GetContext()->IsPlaying()) + { + CK3dEntity *referenceObject = a ? a : b ? b : NULL; + CK3dEntity *other = b ? b :NULL; + if (referenceObject) + { + XString name(attributeName); + int attributeType = _registerJointAttributeType(VTS_JOINT_DISTANCE,name.Str()); + + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attributeType)) + { + referenceObject->RemoveAttribute(attributeType); + } + referenceObject->SetAttribute(attributeType); + ////////////////////////////////////////////////////////////////////////// + // store settings into attributes + CKParameterOut *parAttribute = referenceObject->GetAttributeParameter(attributeType); + if (parAttribute) + { + if (other) + SetParameterStructureValue(parAttribute,PS_JDISTANCE_BODY_B,other->GetID()); + + SetParameterStructureValue(parAttribute,PS_JDISTANCE_LOCAL_ANCHOR_A_POS,anchor0); + SetParameterStructureValue(parAttribute,PS_JDISTANCE_LOCAL_ANCHOR_B_POS,anchor1); + + + + SetParameterStructureValue(parAttribute,PS_JDISTANCE_COLL,collision); + SetParameterStructureValue(parAttribute,PS_JDISTANCE_MIN_DISTANCE,minDistance); + SetParameterStructureValue(parAttribute,PS_JDISTANCE_MAX_DISTANCE,maxDistance); + + SetParameterStructureValue(parAttribute,PS_JDISTANCE_MAX_FORCE,maxForce); + SetParameterStructureValue(parAttribute,PS_JDISTANCE_MAX_TORQUE,maxTorque); + + SetParameterStructureValue(GetParameterFromStruct(parAttribute,PS_JDISTANCE_SPRING),0,sSettings.damper); + SetParameterStructureValue(GetParameterFromStruct(parAttribute,PS_JDISTANCE_SPRING),1,sSettings.spring); + SetParameterStructureValue(GetParameterFromStruct(parAttribute,PS_JDISTANCE_SPRING),2,sSettings.targetValue); + + SetParameterStructureValue(parAttribute,PS_JDISTANCE_LOCAL_ANCHOR_A_REF,0); + SetParameterStructureValue(parAttribute,PS_JDISTANCE_LOCAL_ANCHOR_B_REF,0); + + } + } + return NULL; + } + } + + + if (jointCheckPreRequisites(a,b,JT_Distance) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + + ////////////////////////////////////////////////////////////////////////// + // nx object : + NxDistanceJointDesc descr; + descr.actor[0]=ba->getActor(); + descr.actor[1]= b ? bb->getActor() : NULL ; + + + + + descr.localAnchor[0] = pMath::getFrom(anchor0); + descr.localAnchor[1] = pMath::getFrom(anchor1); + + descr.minDistance = minDistance; + descr.maxDistance = maxDistance; + + if (minDistance!=0.0f) + descr.flags|=NX_DJF_MIN_DISTANCE_ENABLED; + if (maxDistance!=0.0f) + descr.flags|=NX_DJF_MAX_DISTANCE_ENABLED; + + if(sSettings.damper!=0.0f || sSettings.damper!=0.0f ) + { + descr.flags|=NX_DJF_SPRING_ENABLED; + NxSpringDesc sDescr; + sDescr.damper = sSettings.damper; + sDescr.spring = sSettings.spring; + sDescr.targetValue = sSettings.targetValue; + descr.spring = sDescr; + + } + + NxDistanceJoint *nxJoint = (NxDistanceJoint*)world->getScene()->createJoint(descr); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + int v = descr.isValid(); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointDistance *joint = new pJointDistance(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + + return joint; + +} +pJoint*pFactory::createJoint(CK3dEntity*_a,CK3dEntity*_b,int type) +{ + return NULL ; +} + + +pJointSettings*pFactory::CreateJointSettings(const XString nodeName/* = */,const TiXmlDocument * doc /* = NULL */) +{ + + /* + pJointSettings *result = new pJointSettings(); + if (nodeName.Length() && doc) + { + const TiXmlElement *root = GetFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "JointSettings" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName.CStr() ) ) + { + + float vF=0.0f; + int res; + + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("LowStop",&vF); + if (res == TIXML_SUCCESS) + { + result->LowStop(vF); + } + + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("HiStop",&vF); + if (res == TIXML_SUCCESS) + { + result->HighStop(vF); + } + + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("LowStop2",&vF); + if (res == TIXML_SUCCESS) + { + result->LowStop2(vF); + } + + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("HiStop2",&vF); + if (res == TIXML_SUCCESS) + { + result->HighStop2(vF); + } + + + return result; + } + } + } + } + } + } + */ + return NULL; +} + +pJointSettings*pFactory::CreateJointSettings(const char* nodeName,const char *filename) +{ + + /* + XString fname(filename); + XString nName(nodeName); + if ( nName.Length() && fname.Length() ) + { + TiXmlDocument * document = getDocument(fname); + if (document) + { + pJointSettings *result = CreateJointSettings(nodeName,document); + if ( result) + { + delete document; + return result; + } + } + } + */ + return NULL; + +} + +pJointLimit pFactory::createLimitFromParameter(CKParameter *par) +{ + + + pJointLimit result; + + CKContext *ctx = GetPMan()->GetContext(); + + + if (par) + { + CKParameter* pout = NULL; + CK_ID* ids = (CK_ID*)par->GetReadDataPtr(); + + float value,restitution,hardness; + + pout = (CKParameterOut*)ctx->GetObject(ids[0]); + pout->GetValue(&value); + + pout = (CKParameterOut*)ctx->GetObject(ids[1]); + pout->GetValue(&restitution); + pout = (CKParameterOut*)ctx->GetObject(ids[2]); + pout->GetValue(&hardness); + + + result.value = value; + result.restitution = restitution; + result.hardness =hardness; + return result; + } + return result; +} + +pSpring pFactory::createSpringFromParameter(CKParameter *par) +{ + + pSpring result; + + CKContext *ctx = GetPMan()->GetContext(); + + + + if (par) + { + CKParameter* pout = NULL; + CK_ID* ids = (CK_ID*)par->GetReadDataPtr(); + + float damping,spring,targetValue; + pout = (CKParameterOut*)ctx->GetObject(ids[0]); + pout->GetValue(&damping); + + pout = (CKParameterOut*)ctx->GetObject(ids[1]); + pout->GetValue(&spring); + pout = (CKParameterOut*)ctx->GetObject(ids[2]); + pout->GetValue(&targetValue); + + result.spring = spring; + result.damper = damping; + result.targetValue = targetValue; + return result; + } + return result; +} + + + +pMotor pFactory::createMotorFromParameter(CKParameter *par) +{ + pMotor result; + CKContext *ctx = GetPMan()->GetContext(); + + + + if (par) + { + CKParameter* pout = NULL; + CK_ID* ids = (CK_ID*)par->GetReadDataPtr(); + + float targetVel,maxF; + int freeSpin; + pout = (CKParameterOut*)ctx->GetObject(ids[0]); + pout->GetValue(&targetVel); + + pout = (CKParameterOut*)ctx->GetObject(ids[1]); + pout->GetValue(&maxF); + pout = (CKParameterOut*)ctx->GetObject(ids[2]); + pout->GetValue(&freeSpin); + result.targetVelocity = targetVel; + result.maximumForce = maxF; + result.freeSpin = freeSpin; + return result; + } + return result; +} + +pJoint*pFactory::GetJoint(CK3dEntity*_a,CK3dEntity*_b) +{ + + /* + if (!_a ||!_b) + { + return 0; + } + + pRigidBody *ba = getBody(_a); + pRigidBody *bb = getBody(_b); + + if ( !ba || !bb || ba == bb ) + return NULL; + + //we check whether both associated bodies are in the same world : + if ( ba->World() != bb->World() ) + { + return 0; + } + + OdeBodyType oba = ba->GetOdeBody(); + OdeBodyType obb = bb->GetOdeBody(); + + if ( !oba || !obb ) + return NULL; + + + for (int i = 0 ; i < dBodyGetNumJoints(oba) ; i++) + { + dJointID jID = dBodyGetJoint(oba,i); + pJoint *joint = static_cast(dJointGetData(jID)); + if (joint && joint->GetOdeBodyB() == obb) + { + return joint; + } + } + + for (int i = 0 ; i < dBodyGetNumJoints(obb) ; i++) + { + dJointID jID = dBodyGetJoint(obb,i); + pJoint *joint = static_cast(dJointGetData(jID)); + if (joint && joint->GetOdeBodyB() == oba) + { + return joint; + } + } + */ + return NULL; +} + diff --git a/usr/Src/Core/pFactory/pFactoryMaterial.cpp b/usr/Src/Core/pFactory/pFactoryMaterial.cpp new file mode 100644 index 0000000..b6de5af --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryMaterial.cpp @@ -0,0 +1,556 @@ +#include +#include "vtPhysXAll.h" +#include "tinyxml.h" + +#include + + +NxMaterialDesc* pFactory::createMaterialFromEntity(CKBeObject*object) +{ + + ////////////////////////////////////////////////////////////////////////// + //sanity checks : + if (!object ) + { + return NULL; + } + + if (!object->HasAttribute(GetPMan()->att_surface_props)) + { + return NULL; + } + ////////////////////////////////////////////////////////////////////////// + CKParameterManager *pm = object->GetCKContext()->GetParameterManager(); + int parameterType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); + + NxMaterialDesc *result = new NxMaterialDesc(); + using namespace vtTools::AttributeTools; + XString nodeName; + + + int enumID = GetValueFromAttribute(object,GetPMan()->att_surface_props,0); + if (enumID==0) + { + goto takeFromAttribute; + } + + + CKEnumStruct *enumStruct = pm->GetEnumDescByType(parameterType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + if(i == enumID) + { + nodeName = enumStruct->GetEnumDescription(i); + if (nodeName.Length()) + { + result = createMaterialFromXML(nodeName.CStr(),getDefaultDocument()); + if (result) + { + return result; + } + } + } + } + } + + +takeFromAttribute : + { + float dynamicFriction = GetValueFromAttribute(object,GetPMan()->att_surface_props,1); + if (dynamicFriction >=0.0f) + { + result->dynamicFriction =dynamicFriction; + } + + float statFriction = GetValueFromAttribute(object,GetPMan()->att_surface_props,2); + if (statFriction>=0.0f) + { + result->staticFriction=statFriction; + } + + float rest = GetValueFromAttribute(object,GetPMan()->att_surface_props,3); + if (rest>=0.0f) + { + result->restitution=rest; + } + + float dynamicFrictionV = GetValueFromAttribute(object,GetPMan()->att_surface_props,4); + if (dynamicFrictionV >=0.0f) + { + result->dynamicFrictionV =dynamicFrictionV; + } + + float staticFrictionV = GetValueFromAttribute(object,GetPMan()->att_surface_props,5); + if (staticFrictionV>=0.0f) + { + result->staticFriction=staticFrictionV; + } + + VxVector anis = GetValueFromAttribute(object,GetPMan()->att_surface_props,6); + if (anis.Magnitude()>=0.01f) + { + result->dirOfAnisotropy=pMath::getFrom(anis); + } + + int fMode = GetValueFromAttribute(object,GetPMan()->att_surface_props,7); + if (fMode !=-1) + { + result->frictionCombineMode=(NxCombineMode)fMode; + } + int rMode = GetValueFromAttribute(object,GetPMan()->att_surface_props,8); + if (rMode !=-1) + { + result->restitutionCombineMode=(NxCombineMode)rMode; + } + + return result; + + + } + + + return result; + + +} + +bool pFactory::copyTo(pMaterial&dst,NxMaterial*src) +{ + + if (!src) + { + return false; + } + + dst.xmlLinkID = (int)src->userData; + dst.dirOfAnisotropy = getFrom(src->getDirOfAnisotropy()); + dst.dynamicFriction = src->getDynamicFriction(); + dst.dynamicFrictionV = src->getDynamicFrictionV(); + dst.staticFriction = src->getStaticFriction(); + dst.staticFrictionV = src->getStaticFrictionV(); + dst.frictionCombineMode = (CombineMode)src->getFrictionCombineMode(); + dst.restitutionCombineMode = (CombineMode)src->getRestitutionCombineMode(); + dst.restitution = src->getRestitution(); + dst.flags = src->getFlags(); + dst.setNxMaterialID(src->getMaterialIndex()); + + return false; +} +bool pFactory::copyTo(NxMaterialDesc &dst, const pMaterial &src) +{ + + dst.dirOfAnisotropy = getFrom(src.dirOfAnisotropy); + dst.dynamicFriction = src.dynamicFriction; + dst.dynamicFrictionV = src.dynamicFrictionV; + dst.staticFriction = src.staticFriction; + dst.staticFrictionV = src.staticFrictionV; + dst.frictionCombineMode = (NxCombineMode)src.frictionCombineMode; + dst.restitutionCombineMode = (NxCombineMode)src.restitutionCombineMode; + dst.restitution = src.restitution; + dst.flags = src.flags; + + + + return true; + +} + +bool pFactory::copyTo(pMaterial& dst,CKParameter*src) +{ + if (!src)return false; + + using namespace vtTools::ParameterTools; + + dst.xmlLinkID = GetValueFromParameterStruct(src,E_MS_XML_TYPE); + dst.dirOfAnisotropy = GetValueFromParameterStruct(src,E_MS_ANIS); + dst.dynamicFriction = GetValueFromParameterStruct(src,E_MS_DFRICTION); + dst.dynamicFrictionV = GetValueFromParameterStruct(src,E_MS_DFRICTIONV); + dst.staticFriction = GetValueFromParameterStruct(src,E_MS_SFRICTION); + dst.staticFrictionV = GetValueFromParameterStruct(src,E_MS_SFRICTIONV); + dst.restitution= GetValueFromParameterStruct(src,E_MS_RESTITUTION); + dst.restitutionCombineMode= (CombineMode)GetValueFromParameterStruct(src,E_MS_RCMODE); + dst.frictionCombineMode= (CombineMode)GetValueFromParameterStruct(src,E_MS_FCMODE); + dst.flags= GetValueFromParameterStruct(src,E_MS_FLAGS); + return true; + + + +} + +bool pFactory::findSettings(pMaterial& dst,CKBeObject*src) +{ + + if (!src)return false; + + CKParameterOut *parMaterial = src->GetAttributeParameter(GetPMan()->att_surface_props); + + if (parMaterial){ + pFactory::Instance()->copyTo(dst,(CKParameter*)parMaterial); + goto EVALUATE; + } + + + + CK3dEntity *ent3D = static_cast(src); + if (ent3D) + { + CKMesh *mesh = ent3D->GetCurrentMesh(); + if (mesh) + { + parMaterial = mesh->GetAttributeParameter(GetPMan()->att_surface_props); + if (!parMaterial) + { + for (int i = 0 ; i < mesh->GetMaterialCount() ; i++) + { + CKMaterial *entMaterial = mesh->GetMaterial(i); + parMaterial = entMaterial->GetAttributeParameter(GetPMan()->att_surface_props); + if (parMaterial) + { + break; + } + } + } + } + } + + if (!parMaterial) return false; + + + ////////////////////////////////////////////////////////////////////////// + //copy parameter content to c++ + pFactory::Instance()->copyTo(dst,(CKParameter*)parMaterial); + + /////////////////////////////////////////////////////////////////////////// + // + // Evaluate from XML + // + + +EVALUATE: + + if ( dst.xmlLinkID !=0 ) + { + XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,dst.xmlLinkID); + bool err = loadFrom(dst,nodeName.Str(),getDefaultDocument()); + if (err) + { + copyTo(parMaterial,dst); + return true; + } + }else{ + + copyTo(parMaterial,dst); + return true; + } + + return false; +} + +bool pFactory::copyTo(CKParameterOut*dst,const pMaterial&src) +{ + if (!dst)return false; + + using namespace vtTools::ParameterTools; + + ////////////////////////////////////////////////////////////////////////// + + + SetParameterStructureValue(dst,E_MS_XML_TYPE,src.xmlLinkID,false); + SetParameterStructureValue(dst,E_MS_DFRICTION,src.dynamicFriction,false); + SetParameterStructureValue(dst,E_MS_DFRICTIONV,src.dynamicFrictionV,false); + SetParameterStructureValue(dst,E_MS_SFRICTION,src.staticFriction,false); + SetParameterStructureValue(dst,E_MS_SFRICTIONV,src.staticFrictionV,false); + SetParameterStructureValue(dst,E_MS_FCMODE,src.frictionCombineMode,false); + SetParameterStructureValue(dst,E_MS_RCMODE,src.restitutionCombineMode,false); + SetParameterStructureValue(dst,E_MS_RESTITUTION,src.restitution,false); + SetParameterStructureValue(dst,E_MS_XML_TYPE,src.xmlLinkID,false); + SetParameterStructureValue(dst,E_MS_FLAGS,src.flags,false); + SetParameterStructureValue(dst,E_MS_ANIS,src.dirOfAnisotropy,false); + +} + +pMaterial pFactory::loadMaterial(const char* nodeName,int& error) +{ + pMaterial result; + if(loadFrom(result,nodeName,getDefaultDocument())) + { + error = 0; + }else + error =1; + + return result; + + + +} +bool pFactory::loadMaterial(pMaterial&dst,const char* nodeName/* = */) +{ + return loadFrom(dst,nodeName,getDefaultDocument()); +} +bool pFactory::loadFrom(pMaterial &dst,const char *nodeName,const TiXmlDocument *doc) +{ + + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if ( strlen(nodeName) && doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "material" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryDoubleAttribute("DynamicFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.dynamicFriction = (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + dst.staticFriction= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + dst.restitution= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + dst.dynamicFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + dst.staticFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + const char* dirOfAnisotropy = NULL; + dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); + if (dirOfAnisotropy && strlen(dirOfAnisotropy)) + { + VxVector vec = _str2Vec(dirOfAnisotropy); + dst.dirOfAnisotropy = vec; + continue; + } + + const char* flags = NULL; + flags = sube->Attribute("Flags"); + if (flags && strlen(flags)) + { + dst.flags = _str2MaterialFlag(flags); + continue; + } + + ////////////////////////////////////////////////////////////////////////// + const char* FrictionCombineMode = NULL; + FrictionCombineMode = sube->Attribute("FrictionCombineMode"); + if (FrictionCombineMode && strlen(FrictionCombineMode)) + { + int fMode = _str2CombineMode(FrictionCombineMode); + dst.frictionCombineMode = (CombineMode)fMode; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + const char* RestitutionCombineMode = NULL; + RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); + if (RestitutionCombineMode && strlen(RestitutionCombineMode)) + { + int fMode = _str2CombineMode(RestitutionCombineMode); + dst.restitutionCombineMode= (CombineMode)fMode; + continue; + } + } + } + return true; + } + } + } + } + } + } + + return false; +} + +NxMaterialDesc*pFactory::createMaterialFromXML(const char* nodeName/* = */,const TiXmlDocument * doc /* = NULL */) +{ + + + + NxMaterialDesc *result = new NxMaterialDesc(); + result->setToDefault(); + + if (doc ==NULL) + return result; + + if (!getFirstDocElement(doc->RootElement())) + return result; + + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if ( strlen(nodeName) && doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "material" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryDoubleAttribute("DynamicFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + result->dynamicFriction = (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFriction= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->restitution= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->dynamicFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + const char* dirOfAnisotropy = NULL; + dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); + if (dirOfAnisotropy && strlen(dirOfAnisotropy)) + { + VxVector vec = _str2Vec(dirOfAnisotropy); + if (vec.Magnitude() >0.1f) + { + result->flags = NX_MF_ANISOTROPIC; + result->dirOfAnisotropy = pMath::getFrom(vec); + continue; + }else + { + result->dirOfAnisotropy = pMath::getFrom(VxVector(0,0,0)); + } + + //result->setGravity(vec); + + } + + ////////////////////////////////////////////////////////////////////////// + const char* FrictionCombineMode = NULL; + FrictionCombineMode = sube->Attribute("FrictionCombineMode"); + if (FrictionCombineMode && strlen(FrictionCombineMode)) + { + int fMode = _str2CombineMode(FrictionCombineMode); + result->frictionCombineMode = (NxCombineMode)fMode; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + const char* RestitutionCombineMode = NULL; + RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); + if (RestitutionCombineMode && strlen(RestitutionCombineMode)) + { + int fMode = _str2CombineMode(RestitutionCombineMode); + result->restitutionCombineMode= (NxCombineMode)fMode; + continue; + } + } + } + return result; + } + } + } + } + } + } + + return result; + +} \ No newline at end of file diff --git a/usr/Src/Core/pFactory/pFactoryMesh.cpp b/usr/Src/Core/pFactory/pFactoryMesh.cpp new file mode 100644 index 0000000..5006e25 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryMesh.cpp @@ -0,0 +1,182 @@ +#include +#include "vtPhysXAll.h" + +NxCCDSkeleton *pFactory::createCCDSkeleton(CKBeObject *meshReference,int flags) +{ + + #ifdef _DEBUG + assert(meshReference); + #endif // _DEBUG + + + NxCCDSkeleton *result = NULL; + CKMesh *mesh = NULL; + + if (meshReference->GetClassID()==CKCID_MESH ) + mesh = static_cast(meshReference); + else if( meshReference->GetClassID() == CKCID_3DOBJECT && + ((CK3dEntity*)meshReference)->GetCurrentMesh() ) + mesh = ((CK3dEntity*)meshReference)->GetCurrentMesh(); + + + if (!mesh) + return NULL; + + + int numVerts = mesh->GetVertexCount(); + int numFaces = mesh->GetFaceCount(); + + + NxReal *vertices = new float[3 * numVerts]; + NxVec3 *verts = new NxVec3[numVerts]; + + for (int i = 0 ; i< numVerts ; i++ ) + { + VxVector v; + mesh->GetVertexPosition(i,&v); + vertices[i * 3] = v.x; + vertices[i * 3 + 1] =v.y; + vertices[i * 3 + 2] = v.z; + } + + NxU32 *indices2 = new NxU32[numFaces*3]; + + for(int j = 0 ; j < numFaces ; j++) + { + + int findicies[3]; + mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); + indices2[ j *3 ] = findicies[0]; + indices2[ j *3 + 1 ] = findicies[1]; + indices2[ j *3 + 2 ] = findicies[2]; + } + + NxSimpleTriangleMesh descr; + descr.numVertices = numVerts; + descr.pointStrideBytes = sizeof(NxReal)*3; + descr.points = vertices; + descr.numTriangles = numFaces; + descr.triangles = indices2; + descr.triangleStrideBytes = sizeof(NxU32)*3; + descr.flags = NX_MF_FLIPNORMALS; + + if (GetPMan()->getPhysicsSDK()) + { + result = GetPMan()->getPhysicsSDK()->createCCDSkeleton(descr); + } + + + delete [] vertices; + delete [] verts; + delete [] indices2; + + return result; + + +} +void pFactory::createConvexMesh(NxScene *scene,CKMesh *mesh,NxConvexMeshDesc&descr,bool hardware) +{ + + + + if (!scene || !mesh) + { + return; + } + + int numVerts = mesh->GetVertexCount(); + int numFaces = mesh->GetFaceCount(); + + + NxReal *vertices = new float[3 * numVerts]; + NxVec3 *verts = new NxVec3[numVerts]; + + for (int i = 0 ; i< numVerts ; i++ ) + { + VxVector v; + mesh->GetVertexPosition(i,&v); + vertices[i * 3] = v.x; + vertices[i * 3 + 1] =v.y; + vertices[i * 3 + 2] = v.z; + } + + NxU32 *indices2 = new NxU32[numFaces*3]; + + for(int j = 0 ; j < numFaces ; j++) + { + + int findicies[3]; + mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); + indices2[ j *3 ] = findicies[0]; + indices2[ j *3 + 1 ] = findicies[1]; + indices2[ j *3 + 2 ] = findicies[2]; + } + descr.numVertices = numVerts; + descr.pointStrideBytes = sizeof(NxReal)*3; + descr.points = vertices; + descr.numTriangles = numFaces; + descr.triangles = indices2; + descr.triangleStrideBytes = sizeof(NxU32)*3; + descr.flags = NX_CF_COMPUTE_CONVEX; + +/* + delete [] vertices; + delete [] verts; + delete [] indices2;*/ + +} +void +pFactory::createMesh(NxScene *scene,CKMesh *mesh,NxTriangleMeshDesc&descr,bool hardware) +{ + + if (!scene || !mesh) + { + return; + } + + int numVerts = mesh->GetVertexCount(); + int numFaces = mesh->GetFaceCount(); + + + NxReal *vertices = new float[3 * numVerts]; + NxVec3 *verts = new NxVec3[numVerts]; + + for (int i = 0 ; i< numVerts ; i++ ) + { + VxVector v; + mesh->GetVertexPosition(i,&v); + vertices[i * 3] = v.x; + vertices[i * 3 + 1] =v.y; + vertices[i * 3 + 2] = v.z; + } + + NxU32 *indices2 = new NxU32[numFaces*3]; + + for(int j = 0 ; j < numFaces ; j++) + { + + int findicies[3]; + mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); + indices2[ j *3 ] = findicies[0]; + indices2[ j *3 + 1 ] = findicies[1]; + indices2[ j *3 + 2 ] = findicies[2]; + } + descr.numVertices = numVerts; + descr.pointStrideBytes = sizeof(NxReal)*3; + descr.points = vertices; + descr.numTriangles = numFaces; + descr.triangles = indices2; + descr.triangleStrideBytes = sizeof(NxU32)*3; + descr.flags = 0; + + + + /* + + delete [] vertices; + delete [] verts; + delete [] indices2; + + */ + +} diff --git a/usr/Src/Core/pFactory/pFactorySettings.cpp b/usr/Src/Core/pFactory/pFactorySettings.cpp new file mode 100644 index 0000000..51a617c --- /dev/null +++ b/usr/Src/Core/pFactory/pFactorySettings.cpp @@ -0,0 +1,533 @@ +#include +#include "vtPhysXAll.h" +#include "IParameter.h" + +bool pFactory::findSettings(pPivotSettings& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_PIVOT_OFFSET); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + return false; +} + +CKParameterOut* pFactory::findSettings(pWheelDescr& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_WHEEL_DESCR); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_WHEEL_DESCR); + if (!par) + { + att = GetPMan()->GetContext()->GetAttributeManager()->GetAttributeTypeByName("Wheel"); + par = src->GetAttributeParameter(att); + } + bool copied = IParameter::Instance()->copyTo(dst,(CKParameter*)par); + return par; +} + +bool pFactory::findSettings(pCollisionSettings& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_COLLISIONS_SETTINGS); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_COLLISIONS_SETTINGS); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + return false; +} + +bool pFactory::findSettings(pOptimization& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_ACTOR_OPTIMIZATION); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + return false; +} + +bool pFactory::findSettings(pMassSettings& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_MASS_SETUP); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + return false; +} + +int pFactory::copyTo(CKParameter *src,pDominanceSetupItem&dst) +{ + + int result = 0 ; + +#ifdef _DEBUG + assert(src); +#endif // _DEBUG + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + CKParameter *contraintParameter = GetParameterFromStruct(src,PS_WD_CONSTRAINT); + + dst.constraint.dominanceA = GetValueFromParameterStruct(contraintParameter,PS_WDC_A); + dst.constraint.dominanceB = GetValueFromParameterStruct(contraintParameter,PS_WDC_B); + + dst.dominanceGroup0 = GetValueFromParameterStruct(src,PS_WD_GROUP_A); + dst.dominanceGroup1 = GetValueFromParameterStruct(src,PS_WD_GROUP_B); + + + + return 0; + +} + + + + + +bool pFactory::copyTo(pConvexCylinderSettings&dst,CKParameter*src,bool evaluate/* =true */) +{ + + bool result = false; + + #ifdef _DEBUG + assert(src); + #endif // _DEBUG + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + //int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); + //CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_MASS_SETUP); + + /* + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)src); + */ + + + + copyTo(dst.radius, GetParameterFromStruct(src,PS_CC_RADIUS_REFERENCED_VALUE),true); + copyTo(dst.height, GetParameterFromStruct(src,PS_CC_HEIGHT_REFERENCED_VALUE),true); + + dst.approximation = GetValueFromParameterStruct(src,PS_CC_APPROXIMATION); + + + //################################################################ + // + // Calculate Forward Axis, optionally referenced by an entity + // + dst.forwardAxis = GetValueFromParameterStruct(src,PS_CC_FORWARD_AXIS); + dst.forwardAxisRef = GetValueFromParameterStruct(src,PS_CC_FORWARD_AXIS_REF); + CK3dEntity *f = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.forwardAxisRef); + if (f) + { + VxVector dir,up,right; + f->GetOrientation(&dir,&up,&right); + f->TransformVector(&dst.forwardAxis,&dir); + dst.forwardAxis.Normalize(); + } + + + //################################################################ + // + // Calculate Down Axis, optionally referenced by an entity + // + dst.downAxis = GetValueFromParameterStruct(src,PS_CC_DOWN_AXIS); + dst.downAxisRef = GetValueFromParameterStruct(src,PS_CC_DOWN_AXIS_REF); + CK3dEntity *d = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.downAxisRef); + + if (d) + { + VxVector dir,up,right; + d->GetOrientation(&dir,&up,&right); + d->TransformVector(&dst.downAxis,&up); + dst.downAxis.Normalize(); + } + + //################################################################ + // + // Calculate Right Axis, optionally referenced by an entity + // + dst.rightAxis = GetValueFromParameterStruct(src,PS_CC_RIGHT_AXIS); + dst.rightAxisRef = GetValueFromParameterStruct(src,PS_CC_RIGHT_AXIS_REF); + + CK3dEntity *r = (CK3dEntity*)GetPMan()->m_Context->GetObject(dst.rightAxisRef); + if (r) + { + VxVector dir,up,right; + r->GetOrientation(&dir,&up,&right); + r->TransformVector(&dst.rightAxis,&right); + dst.rightAxis.Normalize(); + } + + dst.buildLowerHalfOnly = GetValueFromParameterStruct(src,PS_CC_BUILD_LOWER_HALF_ONLY); + dst.convexFlags = (pConvexFlags)GetValueFromParameterStruct(src,PS_CC_EXTRA_SHAPE_FLAGS); + + return true; +} + +bool pFactory::findSettings(pConvexCylinderSettings&dst,CKBeObject *src) +{ + + bool result = false; + +#ifdef _DEBUG + assert(src); +#endif // _DEBUG + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + int attType = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR); + CKParameterOut *pout = src->GetAttributeParameter(attType); + if (!pout) + { + CKMesh *currentMesh = ((CK3dEntity*)src)->GetCurrentMesh(); + if (currentMesh) + { + pout = currentMesh->GetAttributeParameter(attType); + if (!pout) + { + + dst.forwardAxis.Set(1.0f,0.0f,0.0f); + dst.downAxis.Set(0.0f,-1.0f,0.0f); + dst.rightAxis.Set(0.0f,0.0f,-1.0f); + + dst.buildLowerHalfOnly = false; + dst.approximation = 10; + + VxVector size(0.0f); + + if (src->GetClassID() == CKCID_3DOBJECT ) + { + CK3dEntity *ent3D = (CK3dEntity*)src; + if (ent3D) + { + size = ent3D->GetBoundingBox(true).GetSize(); + } + }else if(src->GetClassID() == CKCID_MESH) + { + CKMesh *mesh = (CKMesh*)src; + if (mesh) + { + size = mesh->GetLocalBox().GetSize(); + } + } + + dst.radius.value = size.x * 0.5f; + dst.height.value = size.y; + + return false; + } + } + } + return copyTo(dst,pout); +} + +bool pFactory::findSettings(pCapsuleSettings&dst,CKBeObject *src) +{ + + bool result = false; + if (!src) + { + return result; + } + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + CKParameterOut *pout = src->GetAttributeParameter(GetPMan()->att_capsule); + if (!pout) + { + CKMesh *currentMesh = ((CK3dEntity*)src)->GetCurrentMesh(); + if (currentMesh) + { + pout = currentMesh->GetAttributeParameter(GetPMan()->att_capsule); + if (!pout) + { + dst.localLengthAxis = CKAXIS_Y; + dst.localRadiusAxis = CKAXIS_X; + dst.height = -1.0f; + dst.radius = -1.0f; + return false; + } + } + } + return copyTo(dst,pout); +} + + +bool pFactory::findSettings(pCapsuleSettingsEx&dst,CKBeObject *src) +{ + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_CAPSULE_SETTINGS_EX); + CKParameterOut *par = findSettingsParameter(src,VTS_CAPSULE_SETTINGS_EX); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + //dst.height.referenceAxis = CKAXIS_Y; + //dst.radius.referenceAxis = CKAXIS_X; + + return false; + +} + +void pFactory::copyTo(pAxisReferencedLength&dst,CKParameter*src,bool evaluate) +{ + +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools::ParameterTools; + + + //################################################################ + // + // Retrieve the value : + // + dst.value = GetValueFromParameterStruct(src,PS_ARL_VALUE); + + dst.referenceAxis = GetValueFromParameterStruct(src,PS_ARL_REF_OBJECT_AXIS); + + //################################################################ + // + // Calculate the value basing on the given objects local box and an axis. + // + CK_ID idRef= GetValueFromParameterStruct(src,PS_ARL_REF_OBJECT); + CKBeObject *object = (CKBeObject*)GetPMan()->GetContext()->GetObject(idRef); + + if (!object) + return; + + dst.reference = object; + + if (!evaluate)return; + + + VxVector size(0.0f); + if (object->GetClassID() == CKCID_3DOBJECT ) + { + CK3dEntity *ent3D = (CK3dEntity*)object; + if (ent3D) + { + size = ent3D->GetBoundingBox(true).GetSize(); + } + }else if(object->GetClassID() == CKCID_MESH) + { + CKMesh *mesh = (CKMesh*)object; + if (mesh) + { + size = mesh->GetLocalBox().GetSize(); + } + } + + + dst.value = size[dst.referenceAxis]; +} + + +pWorldSettings*pFactory::getWorldSettings(CK3dEntity*ent) +{ + + /* + ////////////////////////////////////////////////////////////////////////// + //sanity checks : + if (!ent ) + { + return NULL; + } + if (!ent->HasAttribute(GetPMan()->att_world_object )) + { + return NULL; + } + ////////////////////////////////////////////////////////////////////////// + pWorldSettings *result = new pWorldSettings(); + using namespace vtTools::AttributeTools; + + result->m_Gravity= GetValueFromAttribute(ent,GetPMan()->att_world_object,0); + result->m_CFM= GetValueFromAttribute(ent,GetPMan()->att_world_object,1); + result->m_ERP= GetValueFromAttribute(ent,GetPMan()->att_world_object,2); + result->m_MaximumContactCorrectVelocity = GetValueFromAttribute(ent,GetPMan()->att_world_object,3); + result->m_ContactSurfaceLayer = GetValueFromAttribute(ent,GetPMan()->att_world_object,4); + return result; + */ + return NULL; +} + +pObjectDescr* pFactory::createPObjectDescrFromParameter(CKParameter *par) +{ + + if (!par) + return NULL; + + //################################################################ + // + // ATTENTION : + // + + pObjectDescr *descr = new pObjectDescr(); + using namespace vtTools::ParameterTools; + + + int hType,flags,hierarchy,collGroup; + VxVector mOffset,sOffset; + float density,skinWidth,newDensity,totalMass; + + collGroup = GetValueFromParameterStruct(par,E_PPS_COLL_GROUP,false); + hierarchy = GetValueFromParameterStruct(par,E_PPS_HIRARCHY,false); + hType = GetValueFromParameterStruct(par,E_PPS_HULLTYPE,false); + flags = GetValueFromParameterStruct(par,E_PPS_BODY_FLAGS,false); + density = GetValueFromParameterStruct(par,E_PPS_DENSITY,false); + newDensity = GetValueFromParameterStruct(par,E_PPS_NEW_DENSITY,false); + totalMass = GetValueFromParameterStruct(par,E_PPS_TOTAL_MASS,false); + skinWidth = GetValueFromParameterStruct(par,E_PPS_SKIN_WIDTH,false); + mOffset = GetValueFromParameterStruct(par,E_PPS_MASS_OFFSET,false); + sOffset = GetValueFromParameterStruct(par,E_PPS_MASS_OFFSET,false); + + + + descr->density = density; + descr->skinWidth = skinWidth; + descr->massOffset = mOffset; + descr->shapeOffset = sOffset; + descr->hullType = (HullType)hType; + descr->flags = (BodyFlags)flags; + descr->hirarchy = hierarchy; + descr->newDensity = newDensity; + descr->totalMass = totalMass; + + return descr; + + return NULL; +} + +pSleepingSettings*pFactory::getSleepingSettings(CK3dEntity*ent) +{ + /* + ////////////////////////////////////////////////////////////////////////// + //sanity checks : + if (!ent ) + { + return NULL; + } + if (!ent->HasAttribute(GetPMan()->att_sleep_settings )) + { + return NULL; + } + ////////////////////////////////////////////////////////////////////////// + pSleepingSettings *result = new pSleepingSettings(); + using namespace vtTools::AttributeTools; + result->m_SleepSteps= GetValueFromAttribute(ent,GetPMan()->att_sleep_settings,0); + result->m_AngularThresold= GetValueFromAttribute(ent,GetPMan()->att_sleep_settings,1); + result->m_LinearThresold = GetValueFromAttribute(ent,GetPMan()->att_sleep_settings,2); + result->m_AutoSleepFlag = GetValueFromAttribute(ent,GetPMan()->att_sleep_settings,3); + return result; + */ + return NULL; +} + +bool pFactory::copyTo(pCapsuleSettings&dst,CKParameter*src) +{ + if (!src) return false; + + using namespace vtTools::ParameterTools; + + dst.localLengthAxis = GetValueFromParameterStruct(src,E_CS_LENGTH_AXIS); + dst.localRadiusAxis = GetValueFromParameterStruct(src,E_CS_RADIUS_AXIS); + dst.radius = GetValueFromParameterStruct(src,E_CS_RADIUS); + dst.height = GetValueFromParameterStruct(src,E_CS_LENGTH); + + return true; +} +int pFactory::copyTo(CKParameterOut*dst,pGroupsMask src) +{ + + if (!dst) return 0; + + + + using namespace vtTools::ParameterTools; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,0,src.bits0,false); + SetParameterStructureValue(dst,1,src.bits1,false); + SetParameterStructureValue(dst,2,src.bits2,false); + SetParameterStructureValue(dst,3,src.bits3,false); + + return true; +} +int pFactory::copyTo(pGroupsMask &dst,CKParameter*src) +{ + + if (!src) return 0; + using namespace vtTools::ParameterTools; + using namespace vtTools::ParameterTools; + dst.bits0 = GetValueFromParameterStruct(src,0); + dst.bits1 = GetValueFromParameterStruct(src,1); + dst.bits2 = GetValueFromParameterStruct(src,2); + dst.bits3 = GetValueFromParameterStruct(src,3); + return 1; +} + +CKParameterOut *pFactory::findSettingsParameter(CKBeObject *src,CKGUID guid) +{ + + + if (!src)return NULL; + + int att = GetPMan()->getAttributeTypeByGuid(guid); + CKParameterOut *par = src->GetAttributeParameter(att); + if (par){ + return par; + } + //---------------------------------------------------------------- + // + // Try sub objects + // + CK3dEntity *ent3D = static_cast(src); + if (ent3D) + { + CKMesh *mesh = ent3D->GetCurrentMesh(); + if (mesh) + { + par = mesh->GetAttributeParameter(att); + if (!par) + { + for (int i = 0 ; i < mesh->GetMaterialCount() ; i++) + { + CKMaterial *entMaterial = mesh->GetMaterial(i); + par = entMaterial->GetAttributeParameter(att); + if (par) + { + break; + } + } + } + } + } + return par; +} \ No newline at end of file diff --git a/usr/Src/Core/pFactory/pFactoryShapes.cpp b/usr/Src/Core/pFactory/pFactoryShapes.cpp new file mode 100644 index 0000000..b715cf2 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryShapes.cpp @@ -0,0 +1,830 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" +#include "IParameter.h" + +#include + + +NxShape *pFactory::cloneShape(CK3dEntity *src,CK3dEntity *dst,CK3dEntity*dstBodyReference,int copyFlags,int bodyFlags/* =0 */) +{ + + if (!src || !dst ) + return NULL; + + pRigidBody *srcBody = GetPMan()->getBody(src); + if (!srcBody) + return NULL; + + pRigidBody *dstBody = GetPMan()->getBody(dstBodyReference); + if (!dstBody) + return NULL; + + if (dstBody->isSubShape(dst)) + return NULL; + + + NxShape *srcShape = srcBody->getSubShape(src); + if (!srcShape) + return NULL; + + bool isSubShape=srcBody->isSubShape(src); + + + pObjectDescr oDescr; + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + + + //---------------------------------------------------------------- + // + // Try to copy it directly from the source object + // + if ( !src->HasAttribute(attTypePBSetup) && isSubShape ) + { + pSubMeshInfo* sInfo = (pSubMeshInfo*)srcShape->userData; + if (sInfo ) + { + const pObjectDescr &srcDescr = sInfo->initDescription; + memcpy(&oDescr,&srcDescr,sizeof(pObjectDescr)); + } + } + + //---------------------------------------------------------------- + // + // Try to copy it directly from the source objects attribute + // + + if (dst->HasAttribute(attTypePBSetup)) + { + //---------------------------------------------------------------- + // + // fill object description + // + + CKParameterOut *par = dst->GetAttributeParameter(attTypePBSetup); + if (!par) + return 0; + + IParameter::Instance()->copyTo(&oDescr,par); + oDescr.version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + + } + + + //---------------------------------------------------------------- + // + // adjust data + // + + + //---------------------------------------------------------------- + // + // find pivot settings + // + if ( (copyFlags & PB_CF_PIVOT_SETTINGS ) ) + { + //check in objects attribute + int attPivot = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); + } + + + if (oDescr.flags & BF_SubShape) + { + if (oDescr.hullType == HT_Wheel) + { + VxVector loc; + pWheel *wheel = createWheel(dstBodyReference,dst,oDescr.wheel,oDescr.convexCylinder,loc); + if(wheel && wheel->castWheel2() ) + return wheel->castWheel2()->getWheelShape(); + else + return NULL; + + }else if( oDescr.hullType != HT_Cloth) + { + + srcBody->addSubShape(NULL,oDescr,dst); + NxShape *result = srcBody->getSubShape(dst); + if (result) + { + //---------------------------------------------------------------- + // + // Adjust mass + // + if ( ( copyFlags & PB_CF_MASS_SETTINGS) ) + { + /* srcBody->updateMassSettings(srcBody->getInitialDescription()->mass); + + result->updateMassSettings(oDescr.mass); + else if(pFactory::Instance()->findSettings(oDescr.mass,referenceObject)) + result->updateMassSettings(oDescr.mass); + */ + + } + return result; + } + } + } + return NULL; + + /* + int sType = vtAgeia::getHullTypeFromShape(srcShape); + + switch(sType) + { + + case HT_Sphere: + { + NxSphereShape *tShape = srcShape->isSphere(); + NxSphereShapeDesc old; + tShape->saveToDesc(old); + + } + } + + + */ + + +} + +NxShape *pFactory::createShape(CK3dEntity *bodyReference,pObjectDescr descr,CK3dEntity *srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + + NxShape *result = NULL; + if (!bodyReference || !mesh ) + { + return result; + } + pRigidBody *body=GetPMan()->getBody(bodyReference); + + if (!body) + return NULL; + + NxActor *actor = body->getActor(); + + if (!actor) + return NULL; + + int hType = descr.hullType; + VxVector box_s = mesh->GetLocalBox().GetSize(); + float density = descr.density; + float skinWidth = descr.skinWidth; + float radius = mesh->GetRadius(); + NxQuat rot = pMath::getFrom(localRotation); + NxVec3 pos = pMath::getFrom(localPos); + CK_ID srcID = mesh->GetID(); + + + pWheel *wheel = NULL; + pSubMeshInfo *sInfo = NULL; + + + switch(hType) + { + + case HT_ConvexCylinder: + { + + + + NxConvexShapeDesc shape; + pConvexCylinderSettings &cSettings = descr.convexCylinder; + + iAssertW( ( descr.mask & OD_ConvexCylinder), + pFactory::Instance()->findSettings(cSettings,srcReference), + "Hull type has been set to convex cylinder but there is no descriptions \ + passed or activated in the pObjectDescr::mask.Trying object attributes...."); + + if (cSettings.radius.reference) + cSettings.radius.evaluate(cSettings.radius.reference); + + if (cSettings.height.reference) + cSettings.height.evaluate(cSettings.height.reference); + + cSettings.radius.value = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); + cSettings.height.value = cSettings.height.value > 0.0f ? cSettings.height.value : (box_s.v[cSettings.height.referenceAxis] * 0.5f); + + iAssertW( cSettings.isValid() , cSettings.setToDefault(),""); + bool resultAssert = true; + + iAssertWR( pFactory::Instance()->_createConvexCylinderMesh(&shape,cSettings,srcReference),"",resultAssert); + /* + NxConvexShapeDesc shape; + if (!_createConvexCylinder(&shape,srcReference)) + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); +*/ + shape.density = density; + shape.localPose.t = pos; + shape.localPose.M = rot; + shape.skinWidth = skinWidth; + + result = actor->createShape(shape); + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + shape.dimensions = pMath::getFrom(box_s)*0.5f; + shape.density = density; + shape.localPose.t = pos; + shape.localPose.M = rot; + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + shape.radius = radius; + shape.density = density; + shape.localPose.M = rot; + shape.localPose.t = pMath::getFrom(localPos); + if (skinWidth!=-1.0f) + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + + pFactory::Instance()->createMesh(&actor->getScene(),mesh,myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return NULL; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + shape.localPose.M = rot; + shape.localPose.t = pMath::getFrom(localPos); + if (skinWidth!=-1.0f) + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + + if (mesh->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshes allowed, by Ageia!"); + goto nothing; + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + pFactory::Instance()->createConvexMesh(&actor->getScene(),mesh,myMesh); + + NxConvexShapeDesc shape; + bool status = InitCooking(); + if (!status) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + goto nothing; + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + goto nothing; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + + shape.localPose.M = rot; + shape.localPose.t = pMath::getFrom(localPos); + if (skinWidth!=-1.0f) + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + CloseCooking(); + + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + NxCapsuleShapeDesc shape; + + pCapsuleSettingsEx &cSettings = descr.capsule; + + iAssertW( ( descr.mask & OD_Capsule), + pFactory::Instance()->findSettings(cSettings,srcReference), + "Hull type has been set to convex cylinder but there is no descriptions \ + passed or activated in the pObjectDescr::mask.Trying object attributes...."); + + bool resultAssert = true; + + if (cSettings.radius.reference) + cSettings.radius.evaluate(cSettings.radius.reference); + + if (cSettings.height.reference) + cSettings.height.evaluate(cSettings.height.reference); + + iAssertWR(cSettings.isValid(),cSettings.setToDefault(),resultAssert); + + shape.radius = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); + shape.height = cSettings.height.value > 0.0f ? (cSettings.height.value-( 2*shape.radius)) : (box_s.v[cSettings.height.referenceAxis] - ( 2*shape.radius)) ; + + shape.density = density; + shape.localPose.M = rot; + shape.localPose.t = pos; + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Wheel: + { + + pWheelDescr &wheelDescr = descr.wheel; + CKParameterOut *wheelParameter = NULL; + + //---------------------------------------------------------------- + // + // determine wheel settings + // + if (!(descr.mask & OD_Wheel)) + { + wheelParameter = pFactory::Instance()->findSettings(wheelDescr,srcReference); + } + + bool resultAssert = true; + iAssertWR(wheelDescr.isValid(),wheelDescr.setToDefault(),resultAssert); + //---------------------------------------------------------------- + // + // determine radius + // + if (wheelDescr.radius.reference == 0 && wheelDescr.radius.value == 0.0f ) + { + float radiusBestFit = 0.0f; + if (box_s[0] > radiusBestFit) + radiusBestFit = box_s[0]; + + if (box_s[1] > radiusBestFit) + radiusBestFit = box_s[1]; + + if (box_s[2] > radiusBestFit) + radiusBestFit = box_s[2]; + + wheelDescr.radius.value = radiusBestFit * 0.5f; + + } + + iAssertW(wheelDescr.radius.isValid(),wheelDescr.radius.evaluate(srcReference),""); + if(!wheelDescr.radius.isValid()) + wheelDescr.radius.value = srcReference->GetRadius(); + + + VxVector box_s = mesh->GetLocalBox().GetSize(); + float radius = wheelDescr.radius.value > 0.0f ? wheelDescr.radius.value : box_s.v[wheelDescr.radius.referenceAxis] * 0.5f; + + NxWheelShapeDesc shape; + shape.setToDefault(); + + shape.radius = radius; + shape.localPose.M = rot; + shape.localPose.t = pos; + + float heightModifier = (wheelDescr.wheelSuspension + radius ) / wheelDescr.wheelSuspension; + shape.suspension.spring = wheelDescr.springRestitution*heightModifier; + shape.suspension.damper = wheelDescr.springDamping * heightModifier; + shape.suspension.targetValue = wheelDescr.springBias * heightModifier; + shape.suspensionTravel = wheelDescr.wheelSuspension; + shape.inverseWheelMass = wheelDescr.inverseWheelMass; + + + + const pTireFunction& latFunc = wheelDescr.latFunc; + const pTireFunction& longFunc = wheelDescr.longFunc; + + + NxTireFunctionDesc lngTFD; + lngTFD.extremumSlip = longFunc.extremumSlip ; + lngTFD.extremumValue = longFunc.extremumValue; + lngTFD.asymptoteSlip = longFunc.asymptoteSlip; + lngTFD.asymptoteValue = longFunc.asymptoteValue; + lngTFD.stiffnessFactor = longFunc.stiffnessFactor; + + NxTireFunctionDesc latTFD; + latTFD.extremumSlip = latFunc.extremumSlip ; + latTFD.extremumValue = latFunc.extremumValue; + latTFD.asymptoteSlip = latFunc.asymptoteSlip; + latTFD.asymptoteValue = latFunc.asymptoteValue; + latTFD.stiffnessFactor = latFunc.stiffnessFactor; + + if ( !(wheelDescr.wheelFlags & WF_IgnoreTireFunction) ) + { + shape.lateralTireForceFunction =latTFD; + shape.longitudalTireForceFunction = lngTFD; + } + shape.wheelFlags =wheelDescr.wheelShapeFlags; + shape.density = density; + shape.skinWidth = skinWidth; + + + //---------------------------------------------------------------- + // + // evaluate wheel settings into attribute parameters + // + if (wheelParameter) + { + IParameter::Instance()->copyTo(wheelParameter,descr.wheel); + + } + result = actor->createShape(shape); + } + } + + if(!result) + { + return NULL; + } + + //---------------------------------------------------------------- + // + // add sub mesh meta + + // + sInfo = new pSubMeshInfo(); + + sInfo->meshID = srcID; + sInfo->mesh = mesh; + + sInfo->entID = srcReference->GetID(); + sInfo->refObject = srcReference; + + result->setName(srcReference->GetName()); + result->userData = (void*)sInfo; + sInfo->initDescription = descr; + + //---------------------------------------------------------------- + // + // wheel extra data + // + if ( descr.hullType == HT_Wheel ) + { + sInfo->wheel = new pWheel2(body,&descr.wheel,srcReference); + ((pWheel2*)sInfo->wheel)->setWheelShape((NxWheelShape*)result->isWheel()); + + sInfo->wheel->setEntID(srcReference->GetID()); + ((pWheel2*)sInfo->wheel)->setEntity(srcReference); + //((pWheel2*)wheel)->setEntity(static_cast(GetPMan()->GetContext()->GetObject(srcReference->GetID()))); + sInfo->wheel->mWheelFlags = descr.wheel.wheelFlags; + + } + + //---------------------------------------------------------------- + // + // Material + // + if ((descr.mask & OD_Material)) + body->updateMaterialSettings(descr.material,srcReference); + else if(pFactory::Instance()->findSettings(descr.material,srcReference)) + body->updateMaterialSettings(descr.material,srcReference); + + + //---------------------------------------------------------------- + // + // Collision + // + if ((descr.mask & OD_Collision)) + body->updateCollisionSettings(descr.collision,srcReference); + else if(pFactory::Instance()->findSettings(descr.collision,srcReference)) + body->updateCollisionSettings(descr.collision,srcReference); + + + //---------------------------------------------------------------- + // + // Adjust pivot + // + + if ( (descr.mask & OD_Pivot) ) + { + iAssertW1( descr.pivot.isValid(),descr.pivot.setToDefault()); + body->updatePivotSettings(descr.pivot,srcReference); + }else if(pFactory::Instance()->findSettings(descr.pivot,srcReference)) + body->updatePivotSettings(descr.pivot,srcReference); + + + //---------------------------------------------------------------- + // + // post + // + if (descr.flags & BF_TriggerShape ) + { + result->setFlag(NX_TRIGGER_ENABLE,TRUE); + CKParameterOut *triggerAttributeParameter = srcReference->GetAttributeParameter(GetPMan()->att_trigger); + if (triggerAttributeParameter) + { + int triggerFlags = vtTools::AttributeTools::GetValueFromAttribute(srcReference,GetPMan()->att_trigger); + result->setFlag(NX_TRIGGER_ON_ENTER,triggerFlags & NX_TRIGGER_ON_ENTER); + result->setFlag(NX_TRIGGER_ON_STAY,triggerFlags & NX_TRIGGER_ON_STAY); + result->setFlag(NX_TRIGGER_ON_LEAVE,triggerFlags & NX_TRIGGER_ON_LEAVE); + + } + } + + //---------------------------------------------------------------- + // + // Mass + // + if ((descr.mask & OD_Mass)) + body->updateMassSettings(descr.mass); + else if(pFactory::Instance()->findSettings(descr.mass,srcReference)) + body->updateMassSettings(descr.mass); + + return result; + + nothing : + return NULL; + +} + +bool pFactory::_createConvexCylinderMesh(NxConvexShapeDesc *dstShapeDescription,pConvexCylinderSettings& srcSettings,CK3dEntity*referenceObject) +{ + + + +#ifdef _DEBUG + assert(referenceObject); // <- should never happen ! +#endif // _DEBUG + + bool result = false; + + +/* srcSettings.radius.value *=0.5f; + srcSettings.height.value *=0.5f; +*/ + NxArray points; + NxVec3 center(0,0,0); + + NxVec3 frontAxis = getFrom(srcSettings.forwardAxis); // = wheelDesc->downAxis.cross(wheelDesc->wheelAxis); + NxVec3 downAxis = getFrom(srcSettings.downAxis);//downAxis *=-1.0; // = wheelDesc->downAxis; + NxVec3 wheelAxis = getFrom(srcSettings.rightAxis); // = wheelDesc->wheelAxis; + + + //frontAxis.normalize(); + frontAxis *= srcSettings.radius.value; + //downAxis.normalize(); + downAxis *= srcSettings.radius.value; + //wheelAxis.normalize(); + wheelAxis *= srcSettings.height.value; + + NxReal step; + + if(srcSettings.buildLowerHalfOnly) + { + if((srcSettings.approximation& 0x1) == 0) + srcSettings.approximation++; + + step = (NxReal)(NxTwoPi) / (NxReal)(srcSettings.approximation*2); + } + else + { + step = (NxReal)(NxTwoPi) / (NxReal)(srcSettings.approximation); + } + for(NxU32 i = 0; i < srcSettings.approximation; i++) + { + NxReal iReal; + if(srcSettings.buildLowerHalfOnly) + { + iReal = (i > (srcSettings.approximation >> 1))?(NxReal)(i+srcSettings.approximation):(NxReal)i; + } + else + { + iReal = (NxReal)i; + } + NxReal Sin, Cos; + NxMath::sinCos(step * iReal, Sin, Cos); + NxVec3 insPoint = (downAxis * -Cos) + (frontAxis * Sin); + points.pushBack(insPoint + wheelAxis); + points.pushBack(insPoint - wheelAxis); + } + + NxConvexMeshDesc convexDesc; + convexDesc.numVertices = points.size(); + convexDesc.pointStrideBytes = sizeof(NxVec3); + convexDesc.points = &points[0].x; + + +// srcSettings.convexFlags |=NX_CF_COMPUTE_CONVEX; +// convexDesc.flags |= srcSettings.convexFlags; + + int cf = CF_ComputeConvex; + cf |= srcSettings.convexFlags; + + convexDesc.flags |= cf; + + + + + // Cooking from memory + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + int s = convexDesc.isValid(); + if(CookConvexMesh(convexDesc, buf)) + { + //NxConvexShapeDesc convexShapeDesc; + + dstShapeDescription->meshData = getPhysicSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + dstShapeDescription->localPose.t = center; + dstShapeDescription->localPose.M.setColumn(0, NxVec3( 1, 0, 0)); + dstShapeDescription->localPose.M.setColumn(1, NxVec3( 0,-1, 0)); + dstShapeDescription->localPose.M.setColumn(2, NxVec3( 0, 0, -1)); + if(dstShapeDescription->meshData != NULL) + { + result = true; + // NxU32 shapeNumber = actor->getNbShapes(); + // result = actor->createShape(convexShapeDesc)->isConvexMesh(); + // if (!result) { + // xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + // } + //wheel->wheelConvex->userData = wheel; + } + } + CloseCooking(); + return result; +} + + + + +NxShape * pFactory::_createConvexCylinder(NxActor *actor,int approximation,VxVector _forwardAxis,VxVector _downAxis,VxVector _rightAxis,float height,float radius,bool buildLowerHalf,int shapeFlags) +{ + + if (!actor || approximation<1 ) + return NULL; + + NxConvexShape *result = NULL; + NxArray points; + NxVec3 center(0,0,0); + + NxVec3 frontAxis = getFrom(_forwardAxis);// = wheelDesc->downAxis.cross(wheelDesc->wheelAxis); + NxVec3 downAxis = getFrom(_downAxis);// = wheelDesc->downAxis; + + downAxis *=-1.0; + + NxVec3 wheelAxis = getFrom(_rightAxis);// = wheelDesc->wheelAxis; + //frontAxis.normalize(); + frontAxis *= radius; + //downAxis.normalize(); + downAxis *= radius; + //wheelAxis.normalize(); + wheelAxis *= height; + + NxReal step; + + if(buildLowerHalf) + { + if((approximation & 0x1) == 0) + approximation++; + + step = (NxReal)(NxTwoPi) / (NxReal)(approximation*2); + } + else + { + step = (NxReal)(NxTwoPi) / (NxReal)(approximation); + } + for(NxU32 i = 0; i < approximation; i++) + { + NxReal iReal; + if(buildLowerHalf) + { + iReal = (i > (approximation >> 1))?(NxReal)(i+approximation):(NxReal)i; + } + else + { + iReal = (NxReal)i; + } + NxReal Sin, Cos; + NxMath::sinCos(step * iReal, Sin, Cos); + NxVec3 insPoint = (downAxis * -Cos) + (frontAxis * Sin); + points.pushBack(insPoint + wheelAxis); + points.pushBack(insPoint - wheelAxis); + } + + NxConvexMeshDesc convexDesc; + convexDesc.numVertices = points.size(); + convexDesc.pointStrideBytes = sizeof(NxVec3); + convexDesc.points = &points[0].x; + convexDesc.flags |= shapeFlags; + //convexDesc.flags |= NX_CF_COMPUTE_CONVEX; + + // Cooking from memory + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + if(CookConvexMesh(convexDesc, buf)) + { + NxConvexShapeDesc convexShapeDesc; + convexShapeDesc.meshData = actor->getScene().getPhysicsSDK().createConvexMesh(MemoryReadBuffer(buf.data)); + convexShapeDesc.localPose.t = center; + convexShapeDesc.localPose.M.setColumn(0, NxVec3( 1, 0, 0)); + convexShapeDesc.localPose.M.setColumn(1, NxVec3( 0,-1, 0)); + convexShapeDesc.localPose.M.setColumn(2, NxVec3( 0, 0, -1)); + if(convexShapeDesc.meshData != NULL) + { + NxU32 shapeNumber = actor->getNbShapes(); + result = actor->createShape(convexShapeDesc)->isConvexMesh(); + if (!result) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); + } + //wheel->wheelConvex->userData = wheel; + } + } + + CloseCooking(); + + return result; + +} + +NxShapeDesc& pFactory::createShape(int hullType,CK3dEntity*ent,float density) +{ + + assert(ent); + float radius = ent->GetRadius(); + if (ent->GetRadius() < 0.001f ) + { + radius = 1.0f; + } + + VxVector box_s= BoxGetZero(ent); + switch(hullType) + { + + case HT_Box: + { + NxBoxShapeDesc result; + //result.setToDefault(); + result.dimensions = pMath::getFrom(box_s); + + result.density = density; + return result; + } + case HT_Sphere: + { + NxSphereShapeDesc result; + //result.setToDefault(); + result.localPose.t = NxVec3(0,radius,0); + result.radius = radius; + result.density = density; + return result; + } + } + + NxBoxShapeDesc result; + result.setToDefault(); + result.dimensions = pMath::getFrom(box_s); + return result; +} diff --git a/usr/Src/Core/pFactory/pFactoryTest.cpp b/usr/Src/Core/pFactory/pFactoryTest.cpp new file mode 100644 index 0000000..d6af632 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryTest.cpp @@ -0,0 +1,62 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" +#include "tinyxml.h" + +#include + +NxShape*pFactory::createWheelShape1(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr) +{ + + NxWheelShape *result = NULL; + pRigidBody *body=GetPMan()->getBody(bodyReference); + + + bool assertResult = true; + iAssertWR(bodyReference && wheelReference && wheelDescr.isValid() && body && body->getActor(),"",assertResult); + if (!assertResult) + return NULL; + + NxActor *actor = body->getActor(); + + + //---------------------------------------------------------------- + // + // prepare data : + // + CKMesh *mesh = wheelReference->GetCurrentMesh(); + VxVector box_s = mesh->GetLocalBox().GetSize(); + + float radius = wheelDescr.radius.value > 0.0f ? wheelDescr.radius.value : box_s.v[wheelDescr.radius.referenceAxis] * 0.5f; + + VxQuaternion quatOffset; + VxVector posOffset; + vtAgeia::calculateOffsets(bodyReference,wheelReference,quatOffset,posOffset); + CK_ID srcID = mesh->GetID(); + + //---------------------------------------------------------------- + // + // create convex cylinder : + // + NxConvexShapeDesc shape; + bool resultAssert = true; + iAssertW(wheelDescr.convexCylinder.isValid(),wheelDescr.convexCylinder.setToDefault(),""); + iAssertW( pFactory::Instance()->_createConvexCylinderMesh(&shape,wheelDescr.convexCylinder,wheelReference),""); + + shape.localPose.M = pMath::getFrom(quatOffset); + shape.localPose.t = pMath::getFrom(posOffset); + + actor->createShape(shape)->isConvexMesh(); + +/* NxConvexShapeDesc shape; + if (!_createConvexCylinder(&shape,wheelReference)) + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); + +*/ + + + + return NULL; +} \ No newline at end of file diff --git a/usr/Src/Core/pFactory/pFactoryVehicle.cpp b/usr/Src/Core/pFactory/pFactoryVehicle.cpp new file mode 100644 index 0000000..dd346c1 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryVehicle.cpp @@ -0,0 +1,201 @@ +#include +#include "vtPhysXAll.h" + +#include "tinyxml.h" + + +pVehicle *pFactory::createVehicle(CK3dEntity *body,pVehicleDesc descr) +{ + + pVehicle *result =NULL; + + if (!body) + { + return result; + } + + pRigidBody *rBody = GetPMan()->getBody(body); + + if (!rBody) + { + return result; + } + + if (rBody->getVehicle()) + { + return rBody->getVehicle(); + } + + descr.body = rBody; + result = new pVehicle(descr,body); + result->_vehicleMotor = NULL; + result->_vehicleGears = NULL; + result->setProcessOptions(descr.processFlags); + + result->setActor(rBody->getActor()); + rBody->setVehicle(result); + result->setMaxSteering(descr.steeringMaxAngle); + result->initWheels(0); + result->initEngine(0); + + + //result->control(0, true, 0, true, false); + //result->control(0, true, 0, true, false); + return result; + +} + + + +pVehicleGears* pFactory::createVehicleGears(pVehicleGearDesc descr) +{ + + if (!descr.isValid()) + return NULL; + pVehicleGears *gears = new pVehicleGears(); + NxI32 nbForwardGears = gears->_nbForwardGears = descr.nbForwardGears; + + memcpy(gears->_forwardGearRatios, descr.forwardGearRatios, sizeof(NxF32) * nbForwardGears); + memcpy(gears->_forwardGears, descr.forwardGears, sizeof(pLinearInterpolation) * nbForwardGears); + + gears->_curGear = 1; + + //gears->_backwardGear = gearDesc.backwardGear; + gears->_backwardGearRatio = descr.backwardGearRatio; + + return gears; + +} + +pVehicleMotor* pFactory::createVehicleMotor(pVehicleMotorDesc descr) +{ + + if (!descr.isValid()) + return NULL; + pVehicleMotor* motor = new pVehicleMotor(); + motor->_torqueCurve = descr.torqueCurve; + NxReal maxTorque = 0; + NxI32 maxTorquePos = -1; + for (NxU32 i = 0; i < motor->_torqueCurve.getSize(); i++) { + NxReal v = motor->_torqueCurve.getValueAtIndex(i); + if (v > maxTorque) { + maxTorque = v; + maxTorquePos = i; + } + } + motor->_maxTorque = maxTorque; + motor->_maxTorquePos = (float)maxTorquePos; + motor->_maxRpmToGearUp = descr.maxRpmToGearUp; + motor->_minRpmToGearDown = descr.minRpmToGearDown; + motor->_maxRpm = descr.maxRpm; + motor->_minRpm = descr.minRpm; + + motor->_rpm = 0.0f; + + return motor; + +} + +XString pFactory::_getVehicleWheelAsEnumeration(const TiXmlDocument * doc) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + + /************************************************************************/ + /* */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "wheel" ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* vSName = NULL; + vSName = sube->Attribute("name"); + if (vSName && strlen(vSName)) + { + if (result.Length()) + { + result << ","; + } + result << vSName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; +} + +XString pFactory::_getVehicleSettingsAsEnumeration(const TiXmlDocument * doc) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + /************************************************************************/ + /* */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "vehicle" ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* vSName = NULL; + vSName = sube->Attribute("name"); + if (vSName && strlen(vSName)) + { + if (result.Length()) + { + result << ","; + } + result << vSName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; + +} + + + + + + diff --git a/usr/Src/Core/pFactory/pFactoryWheel.cpp b/usr/Src/Core/pFactory/pFactoryWheel.cpp new file mode 100644 index 0000000..95468b0 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryWheel.cpp @@ -0,0 +1,858 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" +#include "tinyxml.h" + +#include + + +pWheel* pFactory::createWheel(CK3dEntity *bodyReference,CK3dEntity*srcReference,pWheelDescr wheelDescr,pConvexCylinderSettings convexCylinder,VxVector localPositionOffset) +{ + //---------------------------------------------------------------- + // + // main objects + // + pRigidBody *body= GetPMan()->getBody(bodyReference); + pWheel *wheel = NULL; + bool assertCondition = true; + + iAssertWR(bodyReference,"",assertCondition); + iAssertWR(body,"",assertCondition); + iAssertWR(srcReference,"",assertCondition); + + if (!assertCondition) + return NULL; + + + iAssertWR(wheelDescr.isValid(),wheelDescr.setToDefault(),assertCondition); + + //---------------------------------------------------------------- + // + // adjust wheel description data + // + iAssertW(wheelDescr.radius.isValid(),wheelDescr.radius.evaluate(srcReference),""); + if(!wheelDescr.radius.isValid()) + wheelDescr.radius.value = srcReference->GetRadius(); + + + + pObjectDescr objectDescription; + objectDescription.hullType = HT_Wheel; + objectDescription.density = 1.0f; + + objectDescription.flags = (BodyFlags)(BF_SubShape|BF_Collision); + + objectDescription.setWheel(wheelDescr); + objectDescription.mask|=OD_Wheel; + + + if(body->addCollider(objectDescription,srcReference)) + { + + NxShape*wheelShape = body->getSubShape(srcReference); + //---------------------------------------------------------------- + // + // handle wheel types + // + //if( wheelShape && wheelShape->isWheel() && wheelDescr.wheelFlags & WF_UseWheelShape) + //WF_UseWheelShape + if( wheelShape && wheelShape->isWheel() ) + { + wheel = (pWheel*)createWheel(body,wheelDescr,srcReference); + ((pWheel2*)wheel)->setWheelShape((NxWheelShape*)wheelShape); + wheel->setEntID(srcReference->GetID()); +// ((pWheel2*)wheel)->setEntity(static_cast(GetPMan()->GetContext()->GetObject(srcReference->GetID()))); + ((pSubMeshInfo*)(wheelShape->userData))->wheel = wheel; + wheel->setFlags(wheelDescr.wheelFlags); + } + } + + return wheel; + +} + +NxShape*pFactory::createWheelShape2(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr) +{ + + + NxWheelShape *result = NULL; + bool assertResult = true; + pRigidBody *body=GetPMan()->getBody(bodyReference); + + iAssertWR(bodyReference && wheelReference && wheelDescr.isValid() && body ,"",assertResult); + if (!assertResult) + return NULL; + + CKMesh *mesh = wheelReference->GetCurrentMesh(); + VxVector box_s = mesh->GetLocalBox().GetSize(); + float radius = wheelDescr.radius.value > 0.0f ? wheelDescr.radius.value : box_s.v[wheelDescr.radius.referenceAxis] * 0.5f; + + VxQuaternion quatOffset; + VxVector posOffset; + vtAgeia::calculateOffsets(bodyReference,wheelReference,quatOffset,posOffset); + + CK_ID srcID = mesh->GetID(); + + + NxWheelShapeDesc shape; + shape.setToDefault(); + + shape.radius = radius; + shape.localPose.M = pMath::getFrom(quatOffset); + shape.localPose.t = pMath::getFrom(posOffset); + + float heightModifier = (wheelDescr.wheelSuspension + radius ) / wheelDescr.wheelSuspension; + shape.suspension.spring = wheelDescr.springRestitution*heightModifier; + shape.suspension.damper = wheelDescr.springDamping * heightModifier; + shape.suspension.targetValue = wheelDescr.springBias * heightModifier; + shape.suspensionTravel = wheelDescr.wheelSuspension; + shape.inverseWheelMass = wheelDescr.inverseWheelMass; + + + const pTireFunction& latFunc = wheelDescr.latFunc; + const pTireFunction& longFunc = wheelDescr.longFunc; + + + NxTireFunctionDesc lngTFD; + lngTFD.extremumSlip = longFunc.extremumSlip ; + lngTFD.extremumValue = longFunc.extremumValue; + lngTFD.asymptoteSlip = longFunc.asymptoteSlip; + lngTFD.asymptoteValue = longFunc.asymptoteValue; + lngTFD.stiffnessFactor = longFunc.stiffnessFactor; + + NxTireFunctionDesc latTFD; + latTFD.extremumSlip = latFunc.extremumSlip ; + latTFD.extremumValue = latFunc.extremumValue; + latTFD.asymptoteSlip = latFunc.asymptoteSlip; + latTFD.asymptoteValue = latFunc.asymptoteValue; + latTFD.stiffnessFactor = latFunc.stiffnessFactor; + + + shape.lateralTireForceFunction =latTFD; + shape.longitudalTireForceFunction = lngTFD; + + shape.wheelFlags =wheelDescr.wheelShapeFlags; + + result = (NxWheelShape*)body->getActor()->createShape(shape); + + + return (NxShape*)result; + +} + +NxShape *pFactory::_createWheelShape1(NxActor *actor,pWheel1 *dstWheel,pObjectDescr *descr,pWheelDescr *wheelDescr,CK3dEntity*srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + + #ifdef _DEBUG + assert(dstWheel); + assert(descr); + assert(wheelDescr); + assert(srcReference || mesh ); + #endif // _DEBUG + + NxShape *result = NULL; + + + //################################################################ + // + // some setup data + // + NxQuat rot = pMath::getFrom(localRotation); + NxVec3 pos = getFrom(localPos); + CK_ID srcID = mesh->GetID(); + + NxConvexShapeDesc shape; + if (!_createConvexCylinder(&shape,srcReference)) + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); + + shape.density = descr->density; + shape.localPose.t = pMath::getFrom(localPos); + shape.localPose.M = rot; + if (descr->skinWidth!=-1.0f) + shape.skinWidth = descr->skinWidth; + + + //################################################################ + // + // Create the convex shape : + // + dstWheel->setWheelConvex(actor->createShape(shape)->isConvexMesh()); + + //if (!_createConvexCylinder(shape,srcReference)) + // xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); + + + //################################################################ + // + // Find the wheels cylinder description + + pConvexCylinderSettings cylDescr; + findSettings(cylDescr,srcReference); + cylDescr.radius.value *=0.5f; + + //################################################################ + // + // Create a joint spring for the suspension + // + + NxReal heightModifier = (wheelDescr->wheelSuspension + cylDescr.radius.value) / wheelDescr->wheelSuspension; + if (wheelDescr->wheelSuspension < 1) + heightModifier = 1.f / wheelDescr->wheelSuspension; + + NxSpringDesc wheelSpring; + wheelSpring.spring = wheelDescr->springRestitution*heightModifier; + wheelSpring.damper = wheelDescr->springDamping*heightModifier; + wheelSpring.targetValue = wheelDescr->springBias*heightModifier; + + + //################################################################ + // + // The original code creates a material here ! We skip this ! + // + + //######################### + + + //################################################################ + // + // The wheel capsule is perpendicular to the floor + // + + NxVec3 forwardAxis = getFrom(cylDescr.forwardAxis); + NxVec3 downAxis = getFrom(cylDescr.downAxis); + NxVec3 wheelAxis = getFrom(cylDescr.rightAxis); + + + NxMaterialDesc materialDesc; + materialDesc.restitution = 0.0f; + materialDesc.dynamicFriction = wheelDescr->frictionToSide; + materialDesc.staticFriction = 2.0f; + materialDesc.staticFrictionV = wheelDescr->frictionToFront*4; + materialDesc.dynamicFrictionV = wheelDescr->frictionToFront; + materialDesc.dirOfAnisotropy = forwardAxis; + materialDesc.frictionCombineMode = NX_CM_MULTIPLY; + materialDesc.flags |= NX_MF_ANISOTROPIC; + + + + dstWheel->material = actor->getScene().createMaterial(materialDesc); + + NxCapsuleShapeDesc capsuleShape; + capsuleShape.radius = cylDescr.radius.value * 0.1f; + capsuleShape.height = wheelDescr->wheelSuspension + cylDescr.radius.value; + capsuleShape.flags = NX_SWEPT_SHAPE; + + //capsuleShape.localPose.M.setColumn(0, NxVec3( 1, 0, 0)); + //capsuleShape.localPose.M.setColumn(1, NxVec3( 0,-1, 0)); + //capsuleShape.localPose.M.setColumn(2, NxVec3( 0, 0,-1)); //rotate 180 degrees around x axis to cast downward! + + capsuleShape.materialIndex = dstWheel->material->getMaterialIndex(); + + + capsuleShape.localPose.M.setColumn(0, forwardAxis); + capsuleShape.localPose.M.setColumn(1, downAxis); + capsuleShape.localPose.M.setColumn(2, wheelAxis); + if(wheelDescr->wheelSuspension >= 1) + { + capsuleShape.localPose.t = pos + downAxis*(cylDescr.radius.value); + } + else + { + capsuleShape.localPose.t = pos + (-1.0f *downAxis)*((cylDescr.radius.value + wheelDescr->wheelSuspension)*0.5f); + } + + //################################################################ + // + // Finalize + // + result = dstWheel->getWheelConvex(); + if (!capsuleShape.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Capsule shape description during wheel1 construction was invalid"); + } + + dstWheel->setWheelCapsule(actor->createShape(capsuleShape)->isCapsule()); + + + + dstWheel->_radius = cylDescr.radius.value; + dstWheel->_turnAngle = 0; + dstWheel->_turnVelocity = 0; + dstWheel->_perimeter = dstWheel->_radius * NxTwoPi; + dstWheel->_maxSuspension = wheelDescr->wheelSuspension; + dstWheel->_wheelWidth = cylDescr.height.value; + dstWheel->_maxPosition = localPos; + + dstWheel->_frictionToFront = wheelDescr->frictionToFront; + dstWheel->_frictionToSide = wheelDescr->frictionToSide; + + + NxU32 contactReportFlags = actor->getContactReportFlags(); + contactReportFlags |=NX_NOTIFY_ON_TOUCH; + actor->setContactReportFlags(contactReportFlags); + return dstWheel->getWheelCapsule(); + +} + + +pWheel *pFactory::createWheelSubShape(pRigidBody *body,CK3dEntity* subEntity,CKMesh *mesh,pObjectDescr *descr,VxVector localPos, VxQuaternion localRotation,NxShape*dstShape) +{ + //################################################################ + // + // Sanity checks + // + #ifdef _DEBUG + assert(body && subEntity && descr ); // Should never occur ! + #endif // _DEBUG + + + XString errorStr; + + //################################################################ + // + // Retrieve the wheel setting from attribute + // + int attTypeWheelSettings = GetPMan()->att_wheelDescr; + int attTypeConvexCylinderSettings = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR); + + if (!subEntity->HasAttribute(attTypeWheelSettings)) + { + errorStr.Format("Object %s has been set as wheel but there is no wheel attribute attached",subEntity->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorStr.CStr()); + return NULL; + } + + + pWheelDescr *wDescr = new pWheelDescr(); + CKParameterOut *par = subEntity->GetAttributeParameter(attTypeWheelSettings); + if (par) + { + + int err = copyTo(wDescr,par); + if (!wDescr->isValid() ) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Wheel Description is invalid"); + SAFE_DELETE(wDescr); + return NULL; + } + } + + //################################################################ + // + // Construct the final wheel object basing on the type of the wheel + // + + pWheel *result = NULL; + + + //if(wDescr->wheelFlags & WF_UseWheelShape) { + + result = new pWheel2(body,wDescr,subEntity); + + /*else + { + //################################################################ + // Wheel type 1 specified, check there is also a override for the convex cylinder + if (!subEntity->HasAttribute(attTypeConvexCylinderSettings)) + { + errorStr.Format("Object %s has been created with default settings for convex cylinder shape",subEntity->GetName()); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,errorStr.CStr()); + } + result = new pWheel1(body,wDescr); + }*/ + + //################################################################ + // + // Create the wheel shape + // + + + + //if(wDescr->wheelFlags & WF_UseWheelShape){ + + dstShape=_createWheelShape2(body->getActor(),descr,wDescr,subEntity,mesh,localPos,localRotation); + ((pWheel2*)result)->setWheelShape((NxWheelShape*)dstShape); +// } + /*else + { + dstShape=_createWheelShape1(body->getActor(),(pWheel1*)result,descr,wDescr,subEntity,mesh,localPos,localRotation); + }*/ + + if (!dstShape) + { + errorStr.Format("Couldn't create wheel shape for object %s",subEntity->GetName()); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,errorStr.CStr()); + + SAFE_DELETE(wDescr); + SAFE_DELETE(result); + return NULL; + } + + + //################################################################ + // + // Finalize wheel setup + // + + result->setEntID(subEntity->GetID()); + + + return result; +} + + +pTireFunction pFactory::createTireFuncFromParameter(CKParameter *par) +{ + pTireFunction result; + result.setToDefault(); + + if (!par) + { + return result; + } + result.extremumSlip = vtTools::ParameterTools::GetValueFromParameterStruct(par,1); + result.extremumValue = vtTools::ParameterTools::GetValueFromParameterStruct(par,2); + result.asymptoteSlip = vtTools::ParameterTools::GetValueFromParameterStruct(par,3); + result.asymptoteValue= vtTools::ParameterTools::GetValueFromParameterStruct(par,4); + result.stiffnessFactor = vtTools::ParameterTools::GetValueFromParameterStruct(par,5); + + /************************************************************************/ + /* Lat Tire Func from XML ? */ + /************************************************************************/ + int xmlLinkId = vtTools::ParameterTools::GetValueFromParameterStruct(par,0); + if (xmlLinkId!=0) + { + XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,xmlLinkId ); + loadFrom(result,nodeName.CStr(),getDefaultDocument()); + if (!result.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Latitude Tire Function was incorrect, setting to default"); + result.setToDefault(); + }else{ + copyTo((CKParameterOut*)par,result); + } + } + + + if (!result.isValid()) + { + result.setToDefault(); + } + return result; +} + +int pFactory::copyTo(pWheelDescr *dst,CKParameter *src) +{ + + int result = 1; + if (!src || !dst) + { + return NULL; + } + + using namespace vtTools::ParameterTools; + dst->setToDefault(); + + + dst->wheelSuspension = GetValueFromParameterStruct(src,E_WD_SUSPENSION); + dst->springRestitution= GetValueFromParameterStruct(src,E_WD_SPRING_RES); + dst->springBias = GetValueFromParameterStruct(src,E_WD_SPRING_BIAS); + dst->springDamping= GetValueFromParameterStruct(src,E_WD_DAMP); + + dst->maxBrakeForce= GetValueFromParameterStruct(src,E_WD_MAX_BFORCE); + dst->frictionToSide= GetValueFromParameterStruct(src,E_WD_FSIDE); + dst->frictionToFront= GetValueFromParameterStruct(src,E_WD_FFRONT); + + CKParameterOut *pOld = GetParameterFromStruct(src,E_WD_INVERSE_WHEEL_MASS); + if (pOld) + { + if (pOld->GetGUID() == CKPGUID_FLOAT) + { + dst->inverseWheelMass= GetValueFromParameterStruct(src,E_WD_INVERSE_WHEEL_MASS); + } + + if (pOld->GetGUID() == CKPGUID_INT) + { + dst->wheelApproximation= GetValueFromParameterStruct(src,E_WD_INVERSE_WHEEL_MASS); + } + } + + //dst->wheelApproximation= GetValueFromParameterStruct(float,E_WD_INVERSE_WHEEL_MASS); + + dst->wheelFlags= (WheelFlags)GetValueFromParameterStruct(src,E_WD_FLAGS); + dst->wheelShapeFlags=(WheelShapeFlags) GetValueFromParameterStruct(src,E_WD_SFLAGS); + + + CKParameterOut *parLatFunc = GetParameterFromStruct(src,E_WD_LAT_FUNC); + CKParameterOut *parLongFunc = GetParameterFromStruct(src,E_WD_LONG_FUNC); + + + + /************************************************************************/ + /* XML Setup ? */ + /************************************************************************/ + int xmlLinkId= GetValueFromParameterStruct(src,E_WD_XML); + bool wIsXML=false; + bool latIsXML= false; + bool longIsXML=false; + + XString nodeName; + if ( xmlLinkId !=0 ) + { + nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_WHEEL_SETTINGS,xmlLinkId); + loadWheelDescrFromXML(*dst,nodeName.CStr(),getDefaultDocument()); + wIsXML =true; + if (!dst->isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Wheel Description was invalid"); + } + + + if (dst->latFunc.xmlLink!=0) + { + latIsXML=true; + } + + if (dst->longFunc.xmlLink!=0) + { + longIsXML=true; + } + } + + + + if (!latIsXML) + { + dst->latFunc = createTireFuncFromParameter(parLatFunc); + } + + + if (!longIsXML) + { + dst->longFunc= createTireFuncFromParameter(parLongFunc); + } + + if (wIsXML) + { + copyTo((CKParameterOut*)src,dst); + } + + + if (longIsXML) + { + copyTo(GetParameterFromStruct(src,E_WD_LONG_FUNC),dst->longFunc); + } + + if (latIsXML) + { + copyTo(GetParameterFromStruct(src,E_WD_LAT_FUNC),dst->latFunc); + } + + return result; +} + + + + + + +NxShape *pFactory::_createWheelShape2(NxActor *actor, pObjectDescr *descr, pWheelDescr *wheelDescr, CK3dEntity*srcReference,CKMesh *mesh, VxVector localPos, VxQuaternion localRotation) +{ + + NxWheelShape *result = NULL; + + if (!actor || !descr || !mesh ) + { + return result; + } + + int hType = descr->hullType; + VxVector box_s = mesh->GetLocalBox().GetSize(); + float density = descr->density; + float skinWidth = descr->skinWidth; + float radius = box_s.x*0.5f; + NxQuat rot = pMath::getFrom(localRotation); + + CK_ID srcID = mesh->GetID(); + + + NxWheelShapeDesc shape; + shape.setToDefault(); + + shape.radius = box_s.z*0.5f; + shape.density = density; + shape.localPose.M = rot; + shape.localPose.t = pMath::getFrom(localPos); + if (skinWidth!=-1.0f) + shape.skinWidth = skinWidth; + + float heightModifier = (wheelDescr->wheelSuspension + radius ) / wheelDescr->wheelSuspension; + shape.suspension.spring = wheelDescr->springRestitution*heightModifier; + shape.suspension.damper = wheelDescr->springDamping * heightModifier; + shape.suspension.targetValue = wheelDescr->springBias * heightModifier; + shape.suspensionTravel = wheelDescr->wheelSuspension; + + //shape.lateralTireForceFunction.stiffnessFactor *= wheelDescr->frictionToSide; + //shape.longitudalTireForceFunction.stiffnessFactor*=wheelDescr->frictionToFront; + shape.inverseWheelMass = wheelDescr->inverseWheelMass; + + + const pTireFunction& latFunc = wheelDescr->latFunc; + const pTireFunction& longFunc = wheelDescr->longFunc; + + + NxTireFunctionDesc lngTFD; + lngTFD.extremumSlip = longFunc.extremumSlip ; + lngTFD.extremumValue = longFunc.extremumValue; + lngTFD.asymptoteSlip = longFunc.asymptoteSlip; + lngTFD.asymptoteValue = longFunc.asymptoteValue; + lngTFD.stiffnessFactor = longFunc.stiffnessFactor; + + NxTireFunctionDesc latTFD; + latTFD.extremumSlip = latFunc.extremumSlip ; + latTFD.extremumValue = latFunc.extremumValue; + latTFD.asymptoteSlip = latFunc.asymptoteSlip; + latTFD.asymptoteValue = latFunc.asymptoteValue; + latTFD.stiffnessFactor = latFunc.stiffnessFactor; + + + if ( !(wheelDescr->wheelFlags & WF_IgnoreTireFunction) ) + { + shape.lateralTireForceFunction =latTFD; + shape.longitudalTireForceFunction = lngTFD; + } + //shape.wheelFlags = wheelDescr->wheelFlags; + //shape.wheelFlags |= (NxWheelShapeFlags(NX_WF_WHEEL_AXIS_CONTACT_NORMAL)); + //shape.shapeFlags = wheelDescr->wheelShapeFlags; + shape.wheelFlags =wheelDescr->wheelShapeFlags; + + /* + if (wheelDescr->wheelFlags & (WF_Accelerated|WF_UseWheelShape) ) + { + int isValid = shape.isValid(); + + } + */ + + + + int isValid = shape.isValid(); + result = (NxWheelShape*)actor->createShape(shape); + + if (result) + { + + + //result->setWheelFlags(wheelDescr->wheelFlags); + //pWheel::getWheelFlag() + + + /* if ( & E_WF_VEHICLE_CONTROLLED ) + { + int isValid = shape.isValid(); + + } + */ + } + + + + return (NxShape*)result; + + +} + +NxShape *pFactory::createWheelShape(NxActor *actor, pObjectDescr *descr, pWheelDescr *wheelDescr, CK3dEntity*srcReference,CKMesh *mesh, VxVector localPos, VxQuaternion localRotation) +{ + +// if(wheelDescr->wheelFlags & WF_UseWheelShape){ + + return _createWheelShape2(actor,descr,wheelDescr,srcReference,mesh,localPos,localRotation); + + /*}else + return NULL;//_createWheelShape1(actor,descr,wheelDescr,srcReference,mesh,localPos,localRotation); +*/ + return NULL; + + + +} + + +pWheel*pFactory::createWheel(pRigidBody *body,pWheelDescr descr,CK3dEntity *wheelShapeReference) +{ + + pWheel *result = NULL; + if (!body || !body->isValid() ) + { + return result; + } + + //if(descr.wheelFlags & WF_UseWheelShape) { + + result = new pWheel2(body,&descr,wheelShapeReference); + +/* }else + { + result = new pWheel1(body,&descr); + } +*/ + + if (result) + { + result->setFlags(descr.wheelFlags); + }// + return result; +} + +XString pFactory::_getVehicleTireFunctionAsEnumeration(const TiXmlDocument * doc) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + /************************************************************************/ + /* */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "tireFunction" ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* vSName = NULL; + vSName = sube->Attribute("name"); + if (vSName && strlen(vSName)) + { + if (result.Length()) + { + result << ","; + } + result << vSName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; +} + + + +int pFactory::copyTo(pWheelDescr &dst,CKParameterOut *src) +{ + if (!src)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + //SetParameterStructureValue(dst,E_WD_SPRING_BIAS,src.,false); + + return result; + + +} + +int pFactory::copyTo(CKParameterOut *dst,const pTireFunction& src) +{ + + if (!dst)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,0,src.xmlLink,false); + SetParameterStructureValue(dst,1,src.extremumSlip,false); + SetParameterStructureValue(dst,2,src.extremumValue,false); + SetParameterStructureValue(dst,3,src.asymptoteSlip,false); + SetParameterStructureValue(dst,4,src.asymptoteValue,false); + SetParameterStructureValue(dst,5,src.stiffnessFactor,false); + + + return result; + +} + +int pFactory::copyTo(CKParameterOut *dst,pWheelDescr *src) +{ + + if (!src)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,E_WD_SPRING_BIAS,src->springBias,false); + SetParameterStructureValue(dst,E_WD_SPRING_RES,src->springRestitution,false); + SetParameterStructureValue(dst,E_WD_DAMP,src->springDamping,false); + SetParameterStructureValue(dst,E_WD_MAX_BFORCE,src->maxBrakeForce,false); + SetParameterStructureValue(dst,E_WD_FFRONT,src->frictionToFront,false); + SetParameterStructureValue(dst,E_WD_FSIDE,src->frictionToSide,false); + SetParameterStructureValue(dst,E_WD_FLAGS,src->wheelFlags,false); + SetParameterStructureValue(dst,E_WD_SFLAGS,src->wheelShapeFlags,false); + SetParameterStructureValue(dst,E_WD_INVERSE_WHEEL_MASS,src->inverseWheelMass,false); + + + return result; + +} + +int pFactory::copyTo(CKParameterOut *dst,const pWheelContactData& src) +{ + + if (!dst)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,E_WCD_CPOINT,src.contactPoint,false); + SetParameterStructureValue(dst,E_WCD_CNORMAL,src.contactNormal,false); + SetParameterStructureValue(dst,E_WCD_LONG_DIR,src.longitudalDirection,false); + SetParameterStructureValue(dst,E_WCD_LAT_DIR,src.lateralDirection,false); + + SetParameterStructureValue(dst,E_WCD_CONTACT_FORCE,src.contactForce,false); + + SetParameterStructureValue(dst,E_WCD_LONG_SLIP,src.longitudalSlip,false); + SetParameterStructureValue(dst,E_WCD_LAT_SLIP,src.lateralSlip,false); + + SetParameterStructureValue(dst,E_WCD_LONG_IMPULSE,src.longitudalImpulse,false); + SetParameterStructureValue(dst,E_WCD_LAT_IMPULSE,src.lateralImpulse,false); + + SetParameterStructureValue(dst,E_WCD_C_POS,src.contactPosition,false); + + if (src.contactEntity) + { + SetParameterStructureValue(dst,E_WCD_CONTACT_ENTITY,src.contactEntity->GetID(),false); + } + + CKParameter *materialParameter = vtTools::ParameterTools::GetParameterFromStruct(dst,E_WCD_OTHER_MATERIAL_INDEX,false); + pFactory::Instance()->copyTo((CKParameterOut*)materialParameter,src.otherMaterial); + + + return result; + +} + + +bool pFactory::loadFrom(pWheelDescr& dst,const char* nodeName) +{ + return loadWheelDescrFromXML(dst,nodeName,getDefaultDocument()); + +} \ No newline at end of file diff --git a/usr/Src/Core/pFactory/pFactoryWorld.cpp b/usr/Src/Core/pFactory/pFactoryWorld.cpp new file mode 100644 index 0000000..94ae7c6 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryWorld.cpp @@ -0,0 +1,352 @@ +#include +#include "vtPhysXAll.h" + +#include "pWorldSettings.h" +#include "NxUserNotify.h" +#include "NxUserContactReport.h" +#include "pWorldCallbacks.h" + + +struct MyUserNotify : public NxUserNotify +{ +public: + + + /*virtual bool onJointBreak(NxReal breakingImpulse, NxJoint & brokenJoint) + { + return false; + }*/ + + virtual bool onJointBreak(NxReal breakingImpulse, NxJoint & brokenJoint) + { + + + pJoint *joint = static_cast(brokenJoint.userData); + if (joint) + { + pBrokenJointEntry *entry = new pBrokenJointEntry(); + //entry->joint = joint; + entry->impulse = breakingImpulse; + + entry->jType =brokenJoint.getType(); + + if(joint->GetVTEntA()) + entry->mAEnt = joint->GetVTEntA()->GetID(); + + if(joint->GetVTEntB()) + entry->mBEnt = joint->GetVTEntB()->GetID(); + + + GetPMan()->getJointFeedbackList().PushBack(entry); + + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Joint break!"); + ////////////////////////////////////////////////////////////////////////// + // + // retrieve body pointers and call callback scripts + NxActor *a = NULL; pRigidBody *ab=NULL; + NxActor *b = NULL; pRigidBody *bb=NULL; + + brokenJoint.getActors(&a,&b); + bool isRemoved = false; + + if(a) + { + ab= static_cast(a->userData); + } + if(b) + bb= static_cast(b->userData); + + if(ab) + { + //ab->onJointBreak(entry); + //ab->hasBrokenJoint = true; + if(!isRemoved) + { + isRemoved = true; + } + } + + if(bb) + { + //bb->onJointBreak(entry); + //bb->hasBrokenJoint= true; + } + + //joint->getJoint()->appData= NULL; + //joint->getJoint()->userData= NULL; + + } + return false; + } + + virtual void onSleep(NxActor **actors, NxU32 count) + { + /* + NX_ASSERT(count > 0); + while (count--) + { + NxActor *thisActor = *actors; + //Tag the actor as sleeping + size_t currentFlag = (size_t)thisActor->userData; + currentFlag |= gSleepFlag; + thisActor->userData = (void*)currentFlag; + + actors++; + }*/ + if (count >0) + { + while (count--) + { + NxActor *thisActor = *actors; + if (thisActor) + { + pRigidBody *body = static_cast(thisActor->userData); + if (body) + { + + int flags = body->getFlags(); + flags |=BF_Sleep; + body->setFlags(flags); + + } + } + } + } + } + + virtual void onWake(NxActor **actors, NxU32 count) + { + + if (count >0) + { + while (count--) + { + NxActor *thisActor = *actors; + if (thisActor) + { + pRigidBody *body = static_cast(thisActor->userData); + if (body) + { + body->getCollisions().Clear(); + body->getTriggers().Clear(); + + int flags = body->getFlags(); + flags &=~BF_Sleep; + body->setFlags(flags); + } + } + actors++; + } + } + } + +}myNotify; + + +pWorld*pFactory::createWorld(CK3dEntity* referenceObject, pWorldSettings *worldSettings,pSleepingSettings *sleepSettings) +{ + + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + ////////////////////////////////////////////////////////////////////////// + //sanity checks : + if (!referenceObject || !GetPMan() ) + { + return NULL; + } + + + if (!getPhysicSDK()) + { + //xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"No physic sdk loaded"); + return NULL; + } + + int worldAtt = GetPMan()->att_world_object; + int surfaceAttribute = GetPMan()->att_surface_props; + + //exists ? Delete it ! + pWorld *w = GetPMan()->getWorld(referenceObject->GetID()); + if (w) + { + GetPMan()->deleteWorld(referenceObject->GetID()); + } + + //our new world : + pWorld *result = new pWorld(referenceObject); + GetPMan()->getWorlds()->InsertUnique(referenceObject,result); + + result->initUserReports(); + + + + + ////////////////////////////////////////////////////////////////////////// + + //there is no world settings attribute : + if (!referenceObject->HasAttribute(worldAtt) ) + { + referenceObject->SetAttribute(worldAtt); + using namespace vtTools; + VxVector grav = worldSettings->getGravity(); + float sWith = worldSettings->getSkinWith(); + AttributeTools::SetAttributeValue(referenceObject,worldAtt,0,&grav); + AttributeTools::SetAttributeValue(referenceObject,worldAtt,1,&sWith); + } + + worldSettings = pFactory::Instance()->createWorldSettings(XString("Default"),GetPMan()->getDefaultConfig()); + if (!worldSettings) + { + worldSettings = new pWorldSettings(); + } + + GetPMan()->setPhysicFlags(worldSettings->getPhysicFlags()); + + ////////////////////////////////////////////////////////////////////////// + //pSDK Scene creation : + + // Create a scene + NxSceneDesc sceneDesc; + NxHWVersion hwCheck = getPhysicSDK()->getHWVersion(); + + if(GetPMan()->physicFlags & PMF_DONT_USE_HARDWARE ) + { + hwCheck = NX_HW_VERSION_NONE; + } + + if(hwCheck != NX_HW_VERSION_NONE) + { + sceneDesc.simType = NX_SIMULATION_HW; + } + + //SCE_SEARCHFORCOMPUTERS. + sceneDesc.gravity = pMath::getFrom(worldSettings->getGravity()); + sceneDesc.upAxis = 1; + //sceneDesc.flags |=NX_SF_ENABLE_ACTIVETRANSFORMS/*|NX_SF_ENABLE_MULTITHREAD|NX_SF_SIMULATE_SEPARATE_THREAD*/; + sceneDesc.flags = worldSettings->getSceneFlags(); + sceneDesc.userNotify =&myNotify; + sceneDesc.userContactReport = result->contactReport; + sceneDesc.userContactModify = result->contactModify; + NxScene *scene = NULL; + if (getPhysicSDK()) + { + scene = getPhysicSDK()->createScene(sceneDesc); + if(scene == NULL) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create scene!"); + return NULL; + } + } + NxCompartment *comp = NULL; + if(hwCheck != NX_HW_VERSION_NONE) + { + NxCompartmentDesc cdesc; + + cdesc.type = NX_SCT_RIGIDBODY; + #if defined(WIN32) && !defined(_XBOX) + cdesc.deviceCode = NX_DC_PPU_AUTO_ASSIGN; + #else + cdesc.deviceCode = NX_DC_CPU; + #endif + comp = scene->createCompartment(cdesc); + if (!comp) + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create scene's compartment"); + } + + + result->setScene(scene); + scene->setUserContactReport(result->contactReport); + scene->setUserTriggerReport(result->triggerReport); + + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + if (referenceObject->HasAttribute(surfaceAttribute)) + { + materialDescr = createMaterialFromEntity(referenceObject); + material = result->getScene()->createMaterial(*materialDescr); + material->userData = (void*)GetValueFromParameterStruct(referenceObject->GetAttributeParameter(surfaceAttribute) ,E_MS_XML_TYPE); + }else{ + + if (getDefaultDocument()) + { + + materialDescr = createMaterialFromXML("Default",getDefaultDocument()); + } + + if (materialDescr) + { + material = result->getScene()->createMaterial(*materialDescr); + } + + if (!material) + { + materialDescr = new NxMaterialDesc(); + materialDescr->setToDefault(); + material = result->getScene()->getMaterialFromIndex(0); + material->loadFromDesc(*materialDescr); + } + + if(material) + { + pMaterial *bmaterial = new pMaterial(); + bmaterial->setToDefault(); + + copyTo(*bmaterial,material); + + material->userData = (void*)bmaterial; + + } + } + + + NxMaterial *zeroMaterial = result->getScene()->getMaterialFromIndex(0); + zeroMaterial->setDirOfAnisotropy(material->getDirOfAnisotropy()); + zeroMaterial->setStaticFriction(material->getStaticFriction()); + zeroMaterial->setDynamicFriction(material->getDynamicFriction()); + zeroMaterial->setStaticFrictionV(material->getStaticFrictionV()); + zeroMaterial->setDynamicFrictionV(material->getDynamicFrictionV()); + zeroMaterial->setFrictionCombineMode(material->getFrictionCombineMode()); + zeroMaterial->setRestitutionCombineMode(material->getRestitutionCombineMode()); + zeroMaterial->setFlags(material->getFlags()); + + + + if (!material) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create default material!"); + } + result->setDefaultMaterial(material); + + + scene->userData = result; + result->_checkForDominanceConstraints(); + result->_construct(); + if (comp) + { + result->setCompartment(comp); + } + return result; +} +//************************************ +// Method: CreateDefaultWorld +// FullName: vtODE::pFactory::CreateDefaultWorld +// Access: public +// Returns: pWorld* +// Qualifier: +// Parameter: XString name +//************************************ +pWorld*pFactory::createDefaultWorld(XString name) +{ + + + CK3dEntity *defaultWorldFrame = createFrame("pDefaultWorld"); + pWorldSettings *wSettings = getManager()->getDefaultWorldSettings(); + + pWorld* world = createWorld(defaultWorldFrame,wSettings,NULL); + getManager()->setDefaultWorld(world); + return world; +} + diff --git a/usr/Src/Core/pFactory/pFactoryXML.cpp b/usr/Src/Core/pFactory/pFactoryXML.cpp new file mode 100644 index 0000000..a16ec89 --- /dev/null +++ b/usr/Src/Core/pFactory/pFactoryXML.cpp @@ -0,0 +1,619 @@ +#include +#include "vtPhysXAll.h" + +#include "pSleepingSettings.h" +#include "pWorldSettings.h" + +#include "tinyxml.h" + +TiXmlDocument*pFactory::loadConfig(const char* filename) +{ + + // load and check file + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,filename); + XString name(Ini); + name << '\0'; + + m_DefaultDocument = new TiXmlDocument(filename); + m_DefaultDocument ->LoadFile(Ini); + m_DefaultDocument ->Parse(Ini); + + if (m_DefaultDocument->Error()) + { + + delete m_DefaultDocument; + m_DefaultDocument = NULL; + + return NULL; + } + + // get the ogreode element. + TiXmlNode* node = m_DefaultDocument->FirstChild( "vtPhysics" ); + if (!node) + { + return NULL; + } + return m_DefaultDocument; + +} + +int pFactory::reloadConfig(const char *fName) +{ + + + if (! fName || !strlen(fName))return -1; + ////////////////////////////////////////Load our physic default xml document : + if (getDefaultDocument()) + { + delete m_DefaultDocument; + m_DefaultDocument = NULL; + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted old default config"); + } + + TiXmlDocument * defaultDoc = loadConfig(fName); + if (!defaultDoc) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config : PhysicDefaults.xml: failed"); + setDefaultDocument(NULL); + }else + { + setDefaultDocument(defaultDoc); + } + return 1; +} + + +pRemoteDebuggerSettings pFactory::createDebuggerSettings(const TiXmlDocument * doc) +{ + + pRemoteDebuggerSettings result; + result.enabled = -1; + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if (doc) + { + + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "Debugger" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),"Default" ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + int i=0; + + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryIntAttribute("enabled",&i); + if (res == TIXML_SUCCESS) + { + result.enabled = i ; + } + + res = sube->QueryIntAttribute("port",&i); + if (res == TIXML_SUCCESS) + { + result.port = i ; + } + + ////////////////////////////////////////////////////////////////////////// + const char* host = sube->Attribute("host"); + if (strlen(host)) + { + //strcpy(result.mHost,host); + result.mHost = host; + } + return result; + } + } + } + } + } + } + } + } + return result; +} +//************************************ +// Method: GetFirstDocElement +// FullName: vtODE::pFactory::GetFirstDocElement +// Access: public +// Returns: const TiXmlElement* +// Qualifier: +// Parameter: const TiXmlElement *root +//************************************ +const TiXmlElement*pFactory::getFirstDocElement(const TiXmlElement *root) +{ + + if (!strcmp(root->Value(), "vtPhysics")) + { + return root; + } + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling()) + { + if (child->Type() == TiXmlNode::ELEMENT) + { + const TiXmlElement *res = getFirstDocElement(child->ToElement ()); + if (res) + return res; + } + } + return 0; +} +//************************************ +// Method: GetDocument +// FullName: vtPhysics::pFactory::GetDocument +// Access: public +// Returns: TiXmlDocument* +// Qualifier: +// Parameter: XString filename +//************************************ +TiXmlDocument* pFactory::getDocument(XString filename) +{ + + + XString fname(filename.Str()); + if ( fname.Length() ) + { + XString fnameTest = ResolveFileName(fname.CStr()); + if ( fnameTest.Length()) + { + TiXmlDocument* result = new TiXmlDocument(fnameTest.Str()); + result->LoadFile(fnameTest.Str()); + result->Parse(fnameTest.Str()); + + TiXmlNode* node = result->FirstChild( "vtPhysics" ); + if (!node) + { + GetPMan()->m_Context->OutputToConsoleEx("PFactory : Couldn't load Document : %s",filename.Str()); + return NULL; + }else + { + return result; + } + } + } + return NULL; +} + +//************************************ +// Method: CreateWorldSettings +// FullName: vtPhysics::pFactory::CreateWorldSettings +// Access: public +// Returns: pWorldSettings* +// Qualifier: +// Parameter: const char* nodeName +// Parameter: const char* filename +//************************************ +/*! + * \brief + * Write brief comment for createWorldSettings here. + * + * \param nodeName + * Description of parameter nodeName. + * + * \param filename + * Description of parameter filename. + * + * \returns + * Write description of return value here. + * + * \throws + * Description of criteria for throwing this exception. + * + * Write detailed description for createWorldSettings here. + * + * \remarks + * Write remarks for createWorldSettings here. + * + * \see + * Separate items with the '|' character. + */ +pWorldSettings*pFactory::createWorldSettings(const char* nodeName, const char* filename) +{ + + XString fname(filename); + XString nName(nodeName); + if ( nName.Length() && fname.Length() ) + { + pWorldSettings *result = NULL; + TiXmlDocument * document = getDocument(fname); + if (document) + { + result =createWorldSettings(nodeName,document); + if ( result) + { + delete document; + return result; + } + } + + if (document) + { + result = new pWorldSettings(); + result->setGravity(VxVector(0,-9.81,0)); + result->setSkinWith(0.02f); + return result; + } + } + return NULL; +} +//************************************ +// Method: CreateWorldSettings +// FullName: vtPhysics::pFactory::CreateWorldSettings +// Access: public +// Returns: pWorldSettings* +// Qualifier: +// Parameter: XString nodeName +// Parameter: TiXmlDocument * doc +//************************************ + +pWorldSettings* +pFactory::createWorldSettings(const XString nodeName/* = */, const TiXmlDocument * doc /* = NULL */) +{ + + pWorldSettings *result = new pWorldSettings(); + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if (doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "world" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName.CStr() ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + int iVal=0; + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryDoubleAttribute("SkinWith",&v); + if (res == TIXML_SUCCESS) + { + result->setSkinWith((float)v); + } + + ////////////////////////////////////////////////////////////////////////// + const char* grav = sube->Attribute("Gravity"); + VxVector vec = _str2Vec(grav); + result->setGravity(vec); + + res = sube->QueryIntAttribute("IsFixedTime",&iVal); + if (res == TIXML_SUCCESS) + { + result->setFixedTime(iVal==1? true : false ); + + } + + res = sube->QueryIntAttribute("NumIterations",&iVal); + if (res == TIXML_SUCCESS) + { + result->setNumIterations(iVal); + } + + + res = sube->QueryDoubleAttribute("FixedTimeStep",&v); + if (res == TIXML_SUCCESS) + { + result->setFixedTimeStep((float)v); + } + const char* flags = NULL; + flags = sube->Attribute("SceneFlags"); + if (flags && strlen(flags)) + { + result->setSceneFlags(_str2SceneFlags(flags)); + } + const char* pflags = NULL; + pflags = sube->Attribute("PhysicFlags"); + if (pflags && strlen(pflags)) + { + result->setPhysicFlags(_str2PhysicFlags(pflags)); + } + } + } + } + } + } + } + } + } + + + //result->setGravity(VxVector(0,-9.81,0)); + //result->setSkinWith(0.02f); + + return result; +} + + +//************************************ +// Method: CreateSleepingSettings +// FullName: vtPhysics::pFactory::CreateSleepingSettings +// Access: public +// Returns: pSleepingSettings* +// Qualifier: +// Parameter: const char* nodeName +// Parameter: const char *filename +//************************************ +pSleepingSettings*pFactory::CreateSleepingSettings(const char* nodeName,const char *filename) +{ + + XString fname(filename); + XString nName(nodeName); + if ( nName.Length() && fname.Length() ) + { + TiXmlDocument * document = getDocument(fname); + if (document) + { + pSleepingSettings *result = CreateSleepingSettings(nodeName,document); + if ( result) + { + delete document; + return result; + } + } + } + return NULL; + +} + +//************************************ +// Method: CreateSleepingSettings +// FullName: vtPhysics::pFactory::CreateSleepingSettings +// Access: public +// Returns: pSleepingSettings* +// Qualifier: +// Parameter: XString nodeName +// Parameter: TiXmlDocument * doc +//************************************ +pSleepingSettings*pFactory::CreateSleepingSettings(XString nodeName/* = */, TiXmlDocument * doc /* = NULL */) +{ + pSleepingSettings *result = new pSleepingSettings(); + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if (nodeName.Length() && doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "sleepsettings" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName.CStr() ) ) + { + + ////////////////////////////////////////////////////////////////////////// + int v; + int res = element->QueryIntAttribute("SleepSteps",&v); + if (res == TIXML_SUCCESS) + { + result->SleepSteps(v); + } + ////////////////////////////////////////////////////////////////////////// + res = element->QueryIntAttribute("AutoSleepFlag",&v); + if (res == TIXML_SUCCESS) + { + result->AutoSleepFlag(v); + } + ////////////////////////////////////////////////////////////////////////// + float vF; + res = element->QueryFloatAttribute("AngularThresold",&vF); + if (res == TIXML_SUCCESS) + { + result->AngularThresold(vF); + } + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("LinearThresold",&vF); + if (res == TIXML_SUCCESS) + { + result->LinearThresold(vF); + } + + return result; + } + } + } + } + } + } + return result; +} + + + +XString pFactory::_getEnumDescription(const TiXmlDocument *doc, XString identifier) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), identifier.Str() ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* matName = NULL; + matName = sube->Attribute("name"); + if (matName && strlen(matName)) + { + if (result.Length()) + { + result << ","; + } + result << matName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; + +} + +XString pFactory::_getBodyXMLInternalEnumeration(const TiXmlDocument * doc) +{ + + return _getEnumDescription(doc,"Body"); + +} +XString pFactory::_getBodyXMLExternalEnumeration(const TiXmlDocument * doc) +{ + + return _getEnumDescription(doc,"Body"); + +} + +XString pFactory::_getMaterialsAsEnumeration(const TiXmlDocument * doc) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "material" ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* matName = NULL; + matName = sube->Attribute("name"); + if (matName && strlen(matName)) + { + if (result.Length()) + { + result << ","; + } + result << matName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; + +} + + +//************************************ +// Method: _str2CombineMode +// FullName: vtAgeia::pFactory::_str2CombineMode +// Access: protected +// Returns: int +// Qualifier: +// Parameter: const char*input +//************************************ +int pFactory::_str2CombineMode(const char*input) +{ + + int result = -1; + if (!strlen(input)) + { + return result; + } + + if (!strcmp(input,"AVERAGE")) + { + return 0; + } + + if (!strcmp(input,"MIN")) + { + return 1; + } + if (!strcmp(input,"MAX")) + { + return 3; + } + + if (!strcmp(input,"MULTIPLY")) + { + return 2; + } + return result; + +} \ No newline at end of file diff --git a/usr/Src/Core/pFluid/pFluid.cpp b/usr/Src/Core/pFluid/pFluid.cpp new file mode 100644 index 0000000..7fe682c --- /dev/null +++ b/usr/Src/Core/pFluid/pFluid.cpp @@ -0,0 +1,348 @@ +#include +#include "vtPhysXAll.h" + +#include "pFluid.h" +#include "pFluidEmitter.h" +#include "CK3dPointCloud.h" + + +#ifdef HAS_FLUIDS + +pFluidEmitter*pFluid::createEmitter(const pFluidEmitterDesc& desc) +{ + + NxFluidEmitterDesc eDesc ; + eDesc.setToDefault(); + + pFactory::Instance()->copyToEmitterDesc(eDesc,desc); + + int valid = eDesc.isValid(); + if (!valid) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Emitter Description not Valid !"); + return NULL; + } + + CK3dEntity*entityReference = (CK3dEntity*)ctx()->GetObject(desc.entityReference); + if (!entityReference) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"You must set a reference object ID in .referenceEntity"); + return NULL; + } + + + eDesc.relPose.M.id(); + eDesc.relPose.M.rotX(-NxHalfPiF32); + eDesc.relPose.t = NxVec3(0,1.1f,0); + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + + NxFluidEmitter *emitter = getFluid()->createEmitter(eDesc); + + if (!emitter) + return NULL; + + pFluidEmitter * result = new pFluidEmitter(); + result->setEmitter(emitter); + result->setFluid(this); + result->setEntityReference(entityReference->GetID()); + VxVector pos; + if (desc.frameShape) + { + desc.frameShape->GetPosition(&pos); + } + emitter->setGlobalPosition(getFrom(pos)); + emitter->userData = result; + + ////////////////////////////////////////////////////////////////////////// + // + // Render Settings : + // + + pFluidRenderSettings *rSettings = new pFluidRenderSettings(ctx(),desc.entityReference,"pFluidEmitter"); + rSettings->setToDefault(); + rSettings->setEmitter(result); + + return result; + +} + + +CK3dEntity*pFluid::getParticleObject() +{ + + CK3dEntity* result = (CK3dEntity*)ctx()->GetObject(entityID); + return result; + +} + + +void pFluid::updateVirtoolsMesh() +{ + +/* + updateCloud(); + return;*/ + //todo, move this into a small billboard rendering lib. + if (!mRenderBuffer) + { + unsigned sizeFloat = mMaxParticles * 3 * 4; + mRenderBuffer = new float[sizeFloat]; + + if (mTrackUserData) + { + mRenderBufferUserData = new float[mMaxParticles * 4 * 4]; + } + + } + + return ; + + CK3dEntity *dstEnt = getParticleObject(); + CKMesh *mesh = getParticleObject()->GetCurrentMesh(); + + if (!dstEnt || !mesh ) + { + return; + } + + if (mParticleBuffer) + { + + for (int i = 0 ; i < mesh->GetVertexCount() ; i++) + { + + pParticle *p = &mParticleBuffer[i]; + if (p) + { + VxVector v = getFrom(p->position); + VxVector outIV; + getParticleObject()->InverseTransform(&outIV,&v); + mesh->SetVertexPosition(i,&outIV); + + } + } + } + + mesh->VertexMove(); +} + +pFluid::pFluid(NxFluidDesc &desc, bool trackUserData, bool provideCollisionNormals, const VxVector& color, float particleSize) : + + mParticleBufferNum(0), + mParticleBuffer(NULL), + mFluid(NULL), + mTrackUserData(trackUserData), + mMyParticleBuffer(NULL), + mCreatedParticleIdsNum(0), + mCreatedParticleIds(NULL), + mDeletedParticleIdsNum(0), + mDeletedParticleIds(NULL), + mParticleColor(color), + mParticleSize(particleSize), + mRenderBuffer(NULL), + mRenderBufferUserData(NULL) +{ + + mMaxParticles = desc.maxParticles; + mParticleBuffer = new pParticle[mMaxParticles]; + desc.userData = this; + + entityID = 0; + + + //Setup particle write data. + NxParticleData particleData; + particleData.numParticlesPtr = &mParticleBufferNum; + particleData.bufferPos = &mParticleBuffer[0].position.x; + particleData.bufferPosByteStride = sizeof(pParticle); + particleData.bufferVel = &mParticleBuffer[0].velocity.x; + particleData.bufferVelByteStride = sizeof(pParticle); + particleData.bufferDensity = &mParticleBuffer[0].density; + particleData.bufferDensityByteStride = sizeof(pParticle); + particleData.bufferLife = &mParticleBuffer[0].lifetime; + particleData.bufferLifeByteStride = sizeof(pParticle); + particleData.bufferId = &mParticleBuffer[0].id; + particleData.bufferIdByteStride = sizeof(pParticle); + + if (provideCollisionNormals) + { + particleData.bufferCollisionNormal = &mParticleBuffer[0].collisionNormal.x; + particleData.bufferCollisionNormalByteStride = sizeof(pParticle); + } + + desc.particlesWriteData = particleData; + + //User data buffers + if (mTrackUserData) + { + //mMyParticleBuffer = new MyParticle[mMaxParticles]; + mCreatedParticleIds = new NxU32[mMaxParticles]; + mDeletedParticleIds = new NxU32[mMaxParticles]; + + //Setup id write data. + NxParticleIdData idData; + + //Creation + idData.numIdsPtr = &mCreatedParticleIdsNum; + idData.bufferId = mCreatedParticleIds; + idData.bufferIdByteStride = sizeof(NxU32); + desc.particleCreationIdWriteData = idData; + + //Deletion + idData.numIdsPtr = &mDeletedParticleIdsNum; + idData.bufferId = mDeletedParticleIds; + idData.bufferIdByteStride = sizeof(NxU32); + desc.particleDeletionIdWriteData = idData; + } + + +} + + + +pFluidDesc::pFluidDesc() +{ + + setToDefault(); +} + +void pFluidDesc::setToDefault() +{ + + maxParticles = 500; + numReserveParticles = 0; + restParticlesPerMeter = 50.0f; + restDensity = 1000.0f; + kernelRadiusMultiplier = 1.2f; + motionLimitMultiplier = 3.0f * kernelRadiusMultiplier; + collisionDistanceMultiplier = 0.1f * kernelRadiusMultiplier; + packetSizeMultiplier = 16; + stiffness = 20.0f; + viscosity = 6.0f; + surfaceTension = 0.0f; + damping = 0.0f; + fadeInTime = 0.0f; + externalAcceleration.Set(0.0f,0.0f,0.0f); + projectionPlane.set(NxVec3(0.0f, 0.0f, 1.0f), 0.0f); + restitutionForStaticShapes = 0.5f; + dynamicFrictionForStaticShapes = 0.05f; + staticFrictionForStaticShapes = 0.05f; + attractionForStaticShapes = 0.0f; + restitutionForDynamicShapes = 0.5f; + dynamicFrictionForDynamicShapes = 0.5f; + staticFrictionForDynamicShapes = 0.5f; + attractionForDynamicShapes = 0.0f; + collisionResponseCoefficient = 0.2f; + + simulationMethod = (pFluidSimulationMethod)(NX_F_SPH); + collisionMethod =(pFluidCollisionMethod)(NX_F_STATIC|NX_F_DYNAMIC); + collisionGroup = 0; + groupsMask.bits0 = 0; + groupsMask.bits1 = 0; + groupsMask.bits2 = 0; + groupsMask.bits3 = 0; + + + flags = (pFluidFlag)(NX_FF_ENABLED); + flags &= ~NX_FF_HARDWARE; + + userData = NULL; + name = NULL; + worldReference = 0 ; + +} + +bool pFluidDesc::isValid()const +{ + + if (kernelRadiusMultiplier < 1.0f) return false; + if (restDensity <= 0.0f) return false; + if (restParticlesPerMeter <= 0.0f) return false; + + if (packetSizeMultiplier < 4) return false; + if (packetSizeMultiplier & ( packetSizeMultiplier - 1 ) ) return false; + + if (motionLimitMultiplier <= 0.0f) return false; + if (motionLimitMultiplier > packetSizeMultiplier*kernelRadiusMultiplier) return false; + + if (collisionDistanceMultiplier <= 0.0f) return false; + if (collisionDistanceMultiplier > packetSizeMultiplier*kernelRadiusMultiplier) return false; + + if (stiffness <= 0.0f) return false; + if (viscosity <= 0.0f) return false; + if (surfaceTension < 0.0f) return false; + + bool isNoInteraction = (simulationMethod & NX_F_NO_PARTICLE_INTERACTION) > 0; + bool isSPH = (simulationMethod & NX_F_SPH) > 0; + bool isMixed = (simulationMethod & NX_F_MIXED_MODE) > 0; + if (!(isNoInteraction || isSPH || isMixed)) return false; + if (isNoInteraction && (isSPH || isMixed)) return false; + if (isSPH && (isNoInteraction || isMixed)) return false; + if (isMixed && (isNoInteraction || isSPH)) return false; + + if (damping < 0.0f) return false; + if (fadeInTime < 0.0f) return false; + + if (projectionPlane.normal.isZero()) return false; + + if (dynamicFrictionForDynamicShapes < 0.0f || dynamicFrictionForDynamicShapes > 1.0f) return false; + if (staticFrictionForDynamicShapes < 0.0f || staticFrictionForDynamicShapes > 1.0f) return false; + if (restitutionForDynamicShapes < 0.0f || restitutionForDynamicShapes > 1.0f) return false; + if (attractionForDynamicShapes < 0.0f) return false; + if (dynamicFrictionForStaticShapes < 0.0f || dynamicFrictionForStaticShapes > 1.0f) return false; + if (staticFrictionForStaticShapes < 0.0f || staticFrictionForStaticShapes > 1.0f) return false; + if (restitutionForStaticShapes < 0.0f || restitutionForStaticShapes > 1.0f) return false; + if (attractionForStaticShapes < 0.0f) return false; + if (collisionResponseCoefficient < 0.0f) return false; + + + if (maxParticles > 32767) return false; + if (maxParticles < 1) return false; + + if (numReserveParticles >= maxParticles) return false; + + if(collisionGroup >= 32) return false; // We only support 32 different collision groups + + return true; +} + +void pFluid::updateCloud() +{ + + CK3dPointCloud *cloud = getPointCloud(); + if (!cloud) + return; + + CKMesh *mesh = getParticleObject()->GetCurrentMesh(); + int count = mesh->GetVertexCount(); + + VxVector *points = new VxVector[count]; + if (mParticleBuffer) + { + for (int i = 0 ; i < mesh->GetVertexCount() ; i++) + { + + pParticle *p = &mParticleBuffer[i]; + if (p) + { + points[i]= getFrom(p->position); + } + } + } + + + VxVector prec(0.5,0.5,0.5); + VxVector a[10]; + + + int b = cloud->CreateFromPointList(2,a,NULL,NULL,NULL,prec); + if (b) + { + int op2=2; + op2++; + } + +} + +#endif // HAS_FLUIDS \ No newline at end of file diff --git a/usr/Src/Core/pFluid/pFluidEmitter.cpp b/usr/Src/Core/pFluid/pFluidEmitter.cpp new file mode 100644 index 0000000..0524971 --- /dev/null +++ b/usr/Src/Core/pFluid/pFluidEmitter.cpp @@ -0,0 +1,16 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + +#include "pFluidEmitterDesc.h" +#include "pFluidEmitter.h" + +pFluidEmitter::pFluidEmitter() +{ + mFluid = NULL; + mEmitter = NULL; + mEntityReference = 0; + mRenderSettings = NULL; +} +#endif // HAS_FLUIDS \ No newline at end of file diff --git a/usr/Src/Core/pFluid/pFluidEmitterDesc.cpp b/usr/Src/Core/pFluid/pFluidEmitterDesc.cpp new file mode 100644 index 0000000..47f186d --- /dev/null +++ b/usr/Src/Core/pFluid/pFluidEmitterDesc.cpp @@ -0,0 +1,53 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + +pFluidEmitterDesc::pFluidEmitterDesc() +{ + setToDefault(); +} + +pFluidEmitterDesc::~pFluidEmitterDesc() +{ +} + +void pFluidEmitterDesc::setToDefault() +{ + frameShape = NULL; + type = (pEmitterType)(NX_FE_CONSTANT_PRESSURE); + maxParticles = 0; + shape = (pEmitterShape)(NX_FE_RECTANGULAR); + dimensionX = 0.25f; + dimensionY = 0.25f; + randomAngle = 0.0f; + randomPos = VxVector(0,0,0); + fluidVelocityMagnitude = 1.0f; + rate = 100.0f; + particleLifetime = 0.0f; + repulsionCoefficient = 1.0f; + flags = (pFluidEmitterFlag)(NX_FEF_ENABLED|NX_FEF_VISUALIZATION|NX_FEF_ADD_BODY_VELOCITY); +} + +bool pFluidEmitterDesc::isValid() const +{ + + if (dimensionX < 0.0f) return false; + if (dimensionY < 0.0f) return false; + + if (randomPos.x < 0.0f) return false; + if (randomPos.y < 0.0f) return false; + if (randomPos.z < 0.0f) return false; + if (randomAngle < 0.0f) return false; + + if (!(((shape & NX_FE_ELLIPSE) > 0) ^ ((shape & NX_FE_RECTANGULAR) > 0))) return false; + if (!(((type & NX_FE_CONSTANT_FLOW_RATE) > 0) ^ ((type & NX_FE_CONSTANT_PRESSURE) > 0))) return false; + + if (rate < 0.0f) return false; + if (fluidVelocityMagnitude < 0.0f) return false; + if (particleLifetime < 0.0f) return false; + if (repulsionCoefficient < 0.0f) return false; + + return true; +} +#endif \ No newline at end of file diff --git a/usr/Src/Core/pFluid/pFluidRenderCB.cpp b/usr/Src/Core/pFluid/pFluidRenderCB.cpp new file mode 100644 index 0000000..608a86b --- /dev/null +++ b/usr/Src/Core/pFluid/pFluidRenderCB.cpp @@ -0,0 +1,115 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + +#include "pFluid.h" + +int RenderParticles_P(CKRenderContext *dev,CKRenderObject *obj,void *arg) +{ + CK3dEntity* ent = (CK3dEntity *)obj; + pFluid *fluid = (pFluid*)arg; + + if (!ent) + return 0; + + + + + if (!fluid) + return 0; + + + CKMesh *mesh = ent->GetCurrentMesh(); + int vCount = mesh->GetVertexCount(); + + VxDrawPrimitiveData* data = dev->GetDrawPrimitiveStructure(CKRST_DP_TR_CL_VC,vCount); + VxMatrix oldmatrix = dev->GetWorldTransformationMatrix(); + dev->SetWorldTransformationMatrix(oldmatrix*ent->GetInverseWorldMatrix()); + + // we don't let write to the ZBuffer + dev->SetTexture(NULL); + dev->SetState(VXRENDERSTATE_ZWRITEENABLE , FALSE); + dev->SetState(VXRENDERSTATE_SRCBLEND, VXBLEND_SRCALPHA); + dev->SetState(VXRENDERSTATE_DESTBLEND, VXBLEND_ONE); + dev->SetState(VXRENDERSTATE_ALPHABLENDENABLE, TRUE); + dev->SetTextureStageState(CKRST_TSS_STAGEBLEND,0,1); + + float averageSize = 1 * 2.0f; + float minSize = 4.0f; + float maxSize = 10000.0f; + + float pointScaleA = 1.0f; + float pointScaleB = 1.0f; + float pointScaleC = 1.0f; + + /************************************************************************/ + /* */ + /************************************************************************/ + + + dev->SetState(VXRENDERSTATE_SPECULARENABLE, FALSE); + dev->SetState(VXRENDERSTATE_FILLMODE, VXFILL_SOLID); + dev->SetState(VXRENDERSTATE_SHADEMODE, VXSHADE_GOURAUD); + + dev->SetTextureStageState(CKRST_TSS_TEXTUREMAPBLEND,VXTEXTUREBLEND_MODULATEALPHA); + dev->SetTextureStageState(CKRST_TSS_MAGFILTER , VXTEXTUREFILTER_LINEAR); + dev->SetTextureStageState(CKRST_TSS_MINFILTER , VXTEXTUREFILTER_LINEARMIPLINEAR); + + // States + dev->SetState(VXRENDERSTATE_WRAP0 , 0); + dev->SetState(VXRENDERSTATE_CULLMODE, VXCULL_NONE); + dev->SetState(VXRENDERSTATE_SRCBLEND, VXBLEND_SRCALPHA); + dev->SetState(VXRENDERSTATE_DESTBLEND, VXBLEND_ONE); + dev->SetState(VXRENDERSTATE_ALPHABLENDENABLE, TRUE); + dev->SetState(VXRENDERSTATE_ZWRITEENABLE , FALSE); + + dev->SetTextureStageState(CKRST_TSS_STAGEBLEND,0,1); + dev->SetTextureStageState(CKRST_TSS_TEXTURETRANSFORMFLAGS, 0); + dev->SetTextureStageState(CKRST_TSS_TEXCOORDINDEX, 0); + + dev->SetState(VXRENDERSTATE_POINTSPRITEENABLE, TRUE); + + dev->SetState(VXRENDERSTATE_POINTSIZE, *(DWORD*)&averageSize); + dev->SetState(VXRENDERSTATE_POINTSIZE_MIN,*(DWORD*)&minSize); + dev->SetState(VXRENDERSTATE_POINTSIZE_MAX,*(DWORD*)&maxSize); + dev->SetState(VXRENDERSTATE_POINTSCALEENABLE, TRUE); + + + + dev->SetState(VXRENDERSTATE_POINTSCALE_A,*(DWORD*)&pointScaleA); + dev->SetState(VXRENDERSTATE_POINTSCALE_B,*(DWORD*)&pointScaleB); + dev->SetState(VXRENDERSTATE_POINTSCALE_C,*(DWORD*)&pointScaleC); + + XPtrStrided positions(data->Positions); + XPtrStrided colors(data->Colors); + + + + pParticle *particles = fluid->getParticles(); + + for (int i = 0 ; i < vCount ; i++) + { + VxColor color; + color.Set(1.0f); + + pParticle *p = &(fluid->mParticleBuffer[i]); + VxVector posi = getFrom(p->position); + *positions = VxVector4(posi.x,posi.y,posi.z,0); + *colors = RGBAFTOCOLOR(&(color)); + // next point + //p = p->next; + + ++colors; + ++positions; + } + + + // The drawing + dev->DrawPrimitive(VX_POINTLIST,(WORD*)NULL,vCount,data); + dev->SetState(VXRENDERSTATE_ZWRITEENABLE , TRUE); + dev->SetWorldTransformationMatrix(oldmatrix); + + return 0; +} +#endif \ No newline at end of file diff --git a/usr/Src/Core/pFluid/pFluidRenderSettings.cpp b/usr/Src/Core/pFluid/pFluidRenderSettings.cpp new file mode 100644 index 0000000..c31ceaf --- /dev/null +++ b/usr/Src/Core/pFluid/pFluidRenderSettings.cpp @@ -0,0 +1,70 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + +#include "pFluidRenderSettings.h" + + +pFluidRenderSettings::pFluidRenderSettings(CKContext* ctx,CK_ID entity,char* name) +{ + + m_Context = ctx; + m_InteractorsFlags = 0; + + m_StartSize = 0; + m_StartSizeVar = 0; + m_EndSize = 0; + m_EndSizeVar = 0; + + m_StartColor.r = 0.6f; + m_StartColor.g = 0.6f; + m_StartColor.b = 0.8f; + m_StartColor.b = 1.0f; + m_StartColorVar.r = 0.0f; + m_StartColorVar.g = 0.0f; + m_StartColorVar.b = 0.0f; + m_StartColorVar.a = 0.0f; + m_EndColor.r = 0.0f; + m_EndColor.g = 0.0f; + m_EndColor.b = 0.0f; + m_EndColor.a = 0.0f; + m_EndColorVar.r = 0.0f; + m_EndColorVar.g = 0.0f; + m_EndColorVar.b = 0.0f; + m_EndColorVar.a = 0.0f; + m_InitialTextureFrame = 0; + m_InitialTextureFrameVariance = 0; + m_SpeedTextureFrame = 0; + m_SpeedTextureFrameVariance = 0; + m_TextureFrameCount = 0; + m_TextureFrameloop = FALSE; + m_EvolutionsFlags = 0; + m_VariancesFlags = 0; + m_InteractorsFlags = 0; + m_DeflectorsFlags = 0; + m_RenderMode = 3; + m_Behavior = NULL; + + mRenderType = PRT_Point; + + + m_Mesh = 0; + m_Entity = entity; + CK3dEntity* ent = (CK3dEntity*)m_Context->GetObject(m_Entity); + if (ent) + m_EntityBbox = ent->GetBoundingBox(TRUE); + + m_Texture = 0; + m_Group = 0; + m_MessageType = -1; + +} + + + +void pFluidRenderSettings::setToDefault() +{ + +} +#endif // HAS_FLUIDS \ No newline at end of file diff --git a/usr/Src/Core/pJoint/pJoint.cpp b/usr/Src/Core/pJoint/pJoint.cpp new file mode 100644 index 0000000..d3869ea --- /dev/null +++ b/usr/Src/Core/pJoint/pJoint.cpp @@ -0,0 +1,286 @@ +#include +#include "vtPhysXAll.h" + + +using namespace vtAgeia; + +VxVector pJoint::getGlobalAxis(){ + if (!getJoint()) + return VxVector(-1,-1,-1); + + return getFrom(getJoint()->getGlobalAxis()); + +} + +void pJoint::setGlobalAxis(VxVector axis) +{ + if (getJoint()) + getJoint()->setGlobalAxis(getFrom(axis)); +} + + +VxVector pJoint::getGlobalAnchor(){ + if (!getJoint()) + return VxVector(-1,-1,-1); + + return getFrom(getJoint()->getGlobalAnchor()); + +} + +void pJoint::setGlobalAnchor(VxVector anchor) +{ + if (getJoint()) + getJoint()->setGlobalAnchor(getFrom(anchor)); +} + + +int pJoint::getNbLimitPlanes() +{ + if (!getJoint()) + return -1; + + NxJoint *j = getJoint(); + j->resetLimitPlaneIterator(); + int numLimitPlanes = 0; + NxVec3 limitPoint; + if ( j->hasMoreLimitPlanes() ) + { + NxVec3 planeNormal; + NxReal planeD; + NxReal restitution; + + bool ok = true; + while ( ok ) + { + j->getNextLimitPlane( planeNormal, planeD, &restitution ); + ++numLimitPlanes; + ok = j->hasMoreLimitPlanes(); + } + } + + return numLimitPlanes; + +} + +////////////////////////////////////////////////////////////////////////// +pJointFixed::pJointFixed(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Fixed) +{ +} + +pJoint::pJoint(pRigidBody* _a,pRigidBody* _b,int _type ) : m_SolidA(_a) , m_SolidB(_b) ,m_type((JType)_type) +{ + m_vtObjectA = _a ? _a->GetVT3DObject() : NULL; + m_vtObjectB = _b ? _b->GetVT3DObject() : NULL; + + mAID = _a ? _a->GetVT3DObject()->GetID() : -1 ; + mBID = _b ? _b->GetVT3DObject()->GetID() : -1 ; + + mJoint = NULL; + m_pWorld = NULL; +} +pJointD6*pJoint::castD6Joint() +{ + + if (getJoint()) + { + if (getJoint()->isD6Joint()) + { + return static_cast(this); + } + } + return NULL; +} + + +pJointPulley* pJoint::castPulley() +{ + + + if (getJoint()) + { + if (getJoint()->isPulleyJoint()) + { + return static_cast(this); + } + } + return NULL; +} +pJointDistance* pJoint::castDistanceJoint() +{ + + + if (getJoint()) + { + if (getJoint()->isDistanceJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointBall* pJoint::castBall() +{ + + + if (getJoint()) + { + if (getJoint()->isSphericalJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointRevolute* pJoint::castRevolute() +{ + + + if (getJoint()) + { + if (getJoint()->isRevoluteJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointPrismatic* pJoint::castPrismatic() +{ + + + if (getJoint()) + { + if (getJoint()->isPrismaticJoint()) + { + return static_cast(this); + } + } + return NULL; +} +pJointCylindrical* pJoint::castCylindrical() +{ + + + if (getJoint()) + { + if (getJoint()->isCylindricalJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointPointInPlane* pJoint::castPointInPlane() +{ + if (getJoint()) + { + if (getJoint()->isPointInPlaneJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointPointOnLine* pJoint::castPointOnLine() +{ + if (getJoint()) + { + if (getJoint()->isPointOnLineJoint()) + { + return static_cast(this); + } + } + return NULL; +} + + + +/************************************************************************/ +/* */ +/************************************************************************/ +int pJoint::addLimitPlane(const VxVector normal, VxVector pointInPlane, float restitution/* =0.0f */) +{ + int res = -1; + if (getJoint()){ + + res = getJoint()->addLimitPlane(pMath::getFrom(normal),pMath::getFrom(pointInPlane),restitution); + + } + return res; +} +void pJoint::setLimitPoint( VxVector point,bool pointIsOnActor2/*=true*/ ) +{ + if (getJoint()){ + return getJoint()->setLimitPoint(getFrom(point),pointIsOnActor2); + } +} +void pJoint::purgeLimitPlanes(){ if (getJoint()) getJoint()->purgeLimitPlanes();} +void pJoint::resetLimitPlaneIterator(){ if (getJoint()) getJoint()->resetLimitPlaneIterator();} +int pJoint::hasMoreLimitPlanes(){ if (getJoint()) return getJoint()->hasMoreLimitPlanes(); return false;} +int pJoint::getNextLimitPlane (VxVector &planeNormal, float &planeD,float *restitution) +{ + if (getJoint()) + { + NxVec3 n; + + int k =getJoint()->getNextLimitPlane(n,planeD,restitution); + planeNormal = pMath::getFrom(n); + return k; + } + return 0; +} + + + +void pJoint::getBreakForces( float& maxForce,float& maxTorque ) +{ + if (getJoint()) + getJoint()->getBreakable(maxForce,maxTorque); +} + +void pJoint::setBreakForces( float maxForce,float maxTorque ) +{ + if (!getJoint()) + return; + + if ( maxTorque !=0.0f && maxForce != 0.0f) + getJoint()->setBreakable(maxForce,maxTorque); + + //if ( maxTorque =0.0f && maxForce = 0.0f) + // getJoint()->setBreakable(,maxTorque); + + +} + +void pJoint::setLocalAnchor0(VxVector anchor0) +{ + if (getJoint()) + { + + if(getJoint()->isRevoluteJoint()) + { + NxRevoluteJointDesc descr; + NxRevoluteJoint *joint = static_cast(getJoint()); + if (!joint)return; + joint->saveToDesc(descr); + descr.localAnchor[0] = getFrom(anchor0); + joint->loadFromDesc(descr); + + } + } +} + + + + + + +/************************************************************************/ +/* */ +/************************************************************************/ + diff --git a/usr/Src/Core/pJoint/pJointBall.cpp b/usr/Src/Core/pJoint/pJointBall.cpp new file mode 100644 index 0000000..efb7aed --- /dev/null +++ b/usr/Src/Core/pJoint/pJointBall.cpp @@ -0,0 +1,227 @@ +#include +#include "vtPhysXAll.h" + +pJointBall::pJointBall(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Spherical) +{ + +} + +pJointLimit pJointBall::getSwingLimit() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pJointLimit(); + joint->saveToDesc(descr); + return pJointLimit (descr.swingLimit.hardness,descr.swingLimit.restitution,descr.swingLimit.value); +} + +pJointLimit pJointBall::getTwistHighLimit() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pJointLimit(); + joint->saveToDesc(descr); + return pJointLimit (descr.twistLimit.high.hardness,descr.twistLimit.high.restitution,descr.twistLimit.high.value); +} + +pJointLimit pJointBall::getTwistLowLimit() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pJointLimit(); + joint->saveToDesc(descr); + return pJointLimit (descr.twistLimit.low.hardness,descr.twistLimit.low.restitution,descr.twistLimit.low.value); +} + +pSpring pJointBall::getSwingSpring() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pSpring(); + joint->saveToDesc(descr); + return pSpring (descr.swingSpring.damper,descr.swingSpring.spring,descr.swingSpring.targetValue); +} +pSpring pJointBall::getTwistSpring() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pSpring(); + joint->saveToDesc(descr); + return pSpring (descr.twistSpring.damper,descr.twistSpring.spring,descr.twistSpring.targetValue); +} + +pSpring pJointBall::getJointSpring() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pSpring(); + joint->saveToDesc(descr); + return pSpring (descr.jointSpring.damper,descr.jointSpring.spring,descr.jointSpring.targetValue); +} +void pJointBall::enableFlag(int flag,bool enable) +{ + + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return; + joint->saveToDesc(descr); + + if (enable) + descr.flags |=flag; + else + descr.flags &=~flag; + + joint->loadFromDesc(descr); + return ; + +} +void pJointBall::setSwingLimitAxis( const VxVector& swingLimitAxis ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.swingAxis = pMath::getFrom(swingLimitAxis); + joint->loadFromDesc(descr); + +} + +void pJointBall::enableCollision( bool collision ) +{ + + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); +} + +void pJointBall::setProjectionMode(ProjectionMode mode) +{ + NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionMode = (NxJointProjectionMode)mode; + joint->loadFromDesc(descr); +} + +void pJointBall::setProjectionDistance(float distance) +{ + NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionDistance= distance; + joint->loadFromDesc(descr); +} + +bool pJointBall::setSwingLimit( pJointLimit limit ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + + if ( limit.hardness != 0.0f || limit.restitution != 0.0f || limit.value !=0.0f ) + { + enableFlag(NX_SJF_SWING_LIMIT_ENABLED,1); + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.swingLimit= sLimit; + joint->loadFromDesc(descr); + return true; + }else + { + enableFlag(NX_SJF_SWING_LIMIT_ENABLED,0); + } + return false; +} +bool pJointBall::setTwistHighLimit( pJointLimit limit ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + if ( limit.hardness != 0.0f || limit.restitution != 0.0f || limit.value !=0.0f ) + { + + enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,1); + + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.twistLimit.high= sLimit; + joint->loadFromDesc(descr); + return true; + } + else + { + enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,0); + } + return 1; +} +bool pJointBall::setTwistLowLimit( pJointLimit limit ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + + if ( limit.hardness != 0.0f || limit.restitution != 0.0f || limit.value !=0.0f ) + { + + enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,1); + + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.twistLimit.low= sLimit; + joint->loadFromDesc(descr); + return true; + } + else + { + enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,0); + } + return 1; +} +void pJointBall::setAnchor( const VxVector& anchor ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setGlobalAnchor(pMath::getFrom(anchor)); +} + +bool pJointBall::setSwingSpring( pSpring spring ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.swingSpring= sLimit; + joint->loadFromDesc(descr); + return 1; +} +bool pJointBall::setTwistSpring( pSpring spring ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.twistSpring= sLimit; + joint->loadFromDesc(descr); + return 1; +} +bool pJointBall::setJointSpring( pSpring spring ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.jointSpring= sLimit; + joint->loadFromDesc(descr); + return 1; +} diff --git a/usr/Src/Core/pJoint/pJointCylindrical.cpp b/usr/Src/Core/pJoint/pJointCylindrical.cpp new file mode 100644 index 0000000..b1daa60 --- /dev/null +++ b/usr/Src/Core/pJoint/pJointCylindrical.cpp @@ -0,0 +1,43 @@ +#include +#include "vtPhysXAll.h" + +pJointCylindrical::pJointCylindrical(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Cylindrical) +{ + +} + +void pJointCylindrical::setGlobalAnchor(VxVector anchor) +{ + + + NxCylindricalJointDesc descr; + NxCylindricalJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAnchor(getFrom(anchor)); + joint->loadFromDesc(descr); +} + +void pJointCylindrical::setGlobalAxis(VxVector axis) +{ + + + NxCylindricalJointDesc descr; + NxCylindricalJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAxis(getFrom(axis)); + joint->loadFromDesc(descr); +} + +void pJointCylindrical::enableCollision(int collision) +{ + NxCylindricalJointDesc descr; + NxCylindricalJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} \ No newline at end of file diff --git a/usr/Src/Core/pJoint/pJointD6.cpp b/usr/Src/Core/pJoint/pJointD6.cpp new file mode 100644 index 0000000..d91f143 --- /dev/null +++ b/usr/Src/Core/pJoint/pJointD6.cpp @@ -0,0 +1,387 @@ +#include +#include "vtPhysXAll.h" + + +using namespace vtAgeia; + +pJointD6::pJointD6(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_D6) +{ + +} + +void pJointD6::setDriveAngularVelocity(VxVector angVel) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return; joint->saveToDesc(descr); + //joint->setDriveAngularVelocity(pMath::getFrom(angVel)); + descr.driveAngularVelocity = (pMath::getFrom(angVel)); + joint->loadFromDesc(descr); +} +////////////////////////////////////////////////////////////////////////// +void pJointD6::setDriveLinearVelocity(VxVector linVel) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + //joint->setDriveLinearVelocity(pMath::getFrom(linVel)); + descr.driveLinearVelocity = (pMath::getFrom(linVel)); + joint->loadFromDesc(descr); +} +////////////////////////////////////////////////////////////////////////// +void pJointD6::setDriveRotation(VxQuaternion rot) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setDriveOrientation(pMath::getFrom(rot)); + joint->loadFromDesc(descr); +} +////////////////////////////////////////////////////////////////////////// +void pJointD6::setDrivePosition(VxVector pos) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setDrivePosition(pMath::getFrom(pos)); + descr.drivePosition = (pMath::getFrom(pos)); + joint->loadFromDesc(descr); +} + +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getSlerpDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.slerpDrive.damping,descr.slerpDrive.spring,descr.slerpDrive.forceLimit,descr.slerpDrive.driveType.bitField); + return result; +} + +int pJointD6::setSlerpDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.slerpDrive = sdrive; + descr.flags |=NX_D6JOINT_SLERP_DRIVE; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getTwistDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.twistDrive.damping,descr.twistDrive.spring,descr.twistDrive.forceLimit,descr.twistDrive.driveType); + return result; +} + +int pJointD6::setTwistDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.twistDrive = sdrive; + + joint->loadFromDesc(descr); + return 1; +} + +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getSwingDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.swingDrive.damping,descr.swingDrive.spring,descr.swingDrive.forceLimit,descr.swingDrive.driveType); + return result; +} + +int pJointD6::setSwingDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.swingDrive = sdrive; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getZDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.zDrive.damping,descr.zDrive.spring,descr.zDrive.forceLimit,descr.zDrive.driveType); + return result; +} + +int pJointD6::setZDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.zDrive = sdrive; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getYDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.yDrive.damping,descr.yDrive.spring,descr.yDrive.forceLimit,descr.yDrive.driveType); + return result; +} + +int pJointD6::setYDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.yDrive = sdrive; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getXDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.xDrive.damping,descr.xDrive.spring,descr.xDrive.forceLimit,descr.xDrive.driveType); + return result; +} + + +int pJointD6::setXDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.xDrive = sdrive; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// + + +pJD6SoftLimit pJointD6::getTwistLowLimit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.twistLimit.low.damping,descr.twistLimit.low.spring,descr.twistLimit.low.value,descr.twistLimit.low.restitution); + return result; +} + +int pJointD6::setTwistLowLimit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.twistLimit.low= sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6SoftLimit pJointD6::getTwistHighLimit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.twistLimit.high.damping,descr.twistLimit.high.spring,descr.twistLimit.high.value,descr.twistLimit.high.restitution); + return result; +} + + +int pJointD6::setTwistHighLimit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.twistLimit.high= sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// + +pJD6SoftLimit pJointD6::getSwing2Limit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.swing2Limit.damping,descr.swing2Limit.spring,descr.swing2Limit.value,descr.swing2Limit.restitution); + return result; +} + +int pJointD6::setSwing2Limit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.swing2Limit= sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// + + +pJD6SoftLimit pJointD6::getSwing1Limit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.swing1Limit.damping,descr.swing1Limit.spring,descr.swing1Limit.value,descr.swing1Limit.restitution); + return result; +} + +int pJointD6::setSwing1Limit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.swing1Limit= sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// + +pJD6SoftLimit pJointD6::getLinearLimit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.linearLimit.damping,descr.linearLimit.spring,descr.linearLimit.value,descr.linearLimit.restitution); + return result; +} + +int pJointD6::setLinearLimit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.linearLimit = sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +void pJointD6::setTwistMotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.twistMotion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setSwing1MotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.swing1Motion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setSwing2MotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.swing2Motion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setXMotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.xMotion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setYMotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.yMotion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setZMotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.zMotion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +D6MotionMode pJointD6::getTwist() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.twistMotion; +} +D6MotionMode pJointD6::getSwing1() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.swing1Motion; +} +D6MotionMode pJointD6::getSwing2() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.swing2Motion; +} +D6MotionMode pJointD6::getXMotion() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.xMotion; +} +D6MotionMode pJointD6::getYMotion() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.yMotion; +} +D6MotionMode pJointD6::getZMotion() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.zMotion; +} + + +void pJointD6::setGlobalAnchor(VxVector anchor) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setGlobalAnchor(pMath::getFrom(anchor)); +} +void pJointD6::setGlobalAxis(VxVector axis) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setGlobalAxis(pMath::getFrom(axis)); + //joint->setGlobalA(pMath::getFrom(anchor)); +} +void pJointD6::setRatio(float ratio) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + if (ratio!=0.0f) + { + descr.jointFlags|=NX_D6JOINT_GEAR_ENABLED; + descr.gearRatio = ratio; + }else + { + descr.jointFlags&=~NX_D6JOINT_GEAR_ENABLED; + } + joint->loadFromDesc(descr); +} + +void pJointD6::enableCollision( bool value ) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + if (value) + { + descr.jointFlags|=NX_JF_COLLISION_ENABLED; + }else + { + descr.jointFlags&=~NX_JF_COLLISION_ENABLED; + } + joint->loadFromDesc(descr); +} + +void pJointD6::setProjectionMode(ProjectionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionMode = (NxJointProjectionMode)mode; + joint->loadFromDesc(descr); +} + +void pJointD6::setProjectionDistance(float distance) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionDistance= distance; + joint->loadFromDesc(descr); +} + +void pJointD6::setProjectionAngle(float angle) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionAngle= angle; + joint->loadFromDesc(descr); +} \ No newline at end of file diff --git a/usr/Src/Core/pJoint/pJointDistance.cpp b/usr/Src/Core/pJoint/pJointDistance.cpp new file mode 100644 index 0000000..8f84792 --- /dev/null +++ b/usr/Src/Core/pJoint/pJointDistance.cpp @@ -0,0 +1,140 @@ +#include +#include "vtPhysXAll.h" + +pJointDistance::pJointDistance(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Distance) +{ +} + +void pJointDistance::setMinDistance(float distance) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.minDistance=distance; + + if (distance !=0.0f) + { + descr.flags |=NX_DJF_MIN_DISTANCE_ENABLED; + }else + descr.flags &=~NX_DJF_MIN_DISTANCE_ENABLED; + + joint->loadFromDesc(descr); +} + +void pJointDistance::setMaxDistance(float distance) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.maxDistance=distance; + if (distance !=0.0f) + { + descr.flags |=NX_DJF_MAX_DISTANCE_ENABLED; + }else + descr.flags &=~NX_DJF_MAX_DISTANCE_ENABLED; + joint->loadFromDesc(descr); +} + +void pJointDistance::setLocalAnchor1(VxVector anchor) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.localAnchor[1] =getFrom(anchor); + joint->loadFromDesc(descr); +} + +void pJointDistance::setLocalAnchor0(VxVector anchor) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.localAnchor[0] =getFrom(anchor); + joint->loadFromDesc(descr); +} + +void pJointDistance::enableCollision(int collision) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} +bool pJointDistance::setSpring( pSpring spring ) +{ + NxDistanceJointDesc descr; + NxDistanceJoint *joint = static_cast(getJoint()); + if (!joint)return false; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.spring= sLimit; + + if(spring.spring!=0.0f || spring.damper!=0.0f ) + descr.flags|=NX_DJF_SPRING_ENABLED; + else + descr.flags &=~NX_DJF_SPRING_ENABLED; + joint->loadFromDesc(descr); + + return true; +} + +VxVector pJointDistance::getLocalAnchor0() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return getFrom(descr.localAnchor[0]); +} +VxVector pJointDistance::getLocalAnchor1() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return getFrom(descr.localAnchor[1]); +} + +float pJointDistance::getMinDistance() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + + if (!joint)return -1.0f; + + joint->saveToDesc(descr); + return descr.minDistance; +} + +float pJointDistance::getMaxDistance() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + + if (!joint)return -1.0f; + + joint->saveToDesc(descr); + return descr.maxDistance; +} + +pSpring pJointDistance::getSpring() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + pSpring result; + if (!joint)result; + joint->saveToDesc(descr); + + result.spring = descr.spring.spring; + result.damper = descr.spring.damper; + result.targetValue = descr.spring.targetValue; + return result; +} \ No newline at end of file diff --git a/usr/Src/Core/pJoint/pJointPointInPlane.cpp b/usr/Src/Core/pJoint/pJointPointInPlane.cpp new file mode 100644 index 0000000..9a3eb16 --- /dev/null +++ b/usr/Src/Core/pJoint/pJointPointInPlane.cpp @@ -0,0 +1,45 @@ +#include +#include "vtPhysXAll.h" + +pJointPointInPlane::pJointPointInPlane(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_PointInPlane) +{ + +} + +void pJointPointInPlane::setGlobalAnchor(VxVector anchor) +{ + + + NxPointInPlaneJointDesc descr; + NxPointInPlaneJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAnchor(getFrom(anchor)); + joint->loadFromDesc(descr); +} + +void pJointPointInPlane::setGlobalAxis(VxVector axis) +{ + + + NxPointInPlaneJointDesc descr; + NxPointInPlaneJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAxis(getFrom(axis)); + joint->loadFromDesc(descr); +} + + + +void pJointPointInPlane::enableCollision(int collision) +{ + NxPointInPlaneJointDesc descr; + NxPointInPlaneJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} diff --git a/usr/Src/Core/pJoint/pJointPointOnLine.cpp b/usr/Src/Core/pJoint/pJointPointOnLine.cpp new file mode 100644 index 0000000..c8a378a --- /dev/null +++ b/usr/Src/Core/pJoint/pJointPointOnLine.cpp @@ -0,0 +1,38 @@ +#include +#include "vtPhysXAll.h" + +pJointPointOnLine::pJointPointOnLine(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_PointOnLine) +{ +} + +void pJointPointOnLine::setGlobalAnchor(VxVector anchor) +{ + NxPointOnLineJointDesc descr; + NxPointOnLineJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAnchor(getFrom(anchor)); + joint->loadFromDesc(descr); +} + +void pJointPointOnLine::setGlobalAxis(VxVector axis) +{ + NxPointOnLineJointDesc descr; + NxPointOnLineJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAxis(getFrom(axis)); + joint->loadFromDesc(descr); +} + +void pJointPointOnLine::enableCollision(int collision) +{ + NxPointOnLineJointDesc descr; + NxPointOnLineJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} \ No newline at end of file diff --git a/usr/Src/Core/pJoint/pJointPrismatic.cpp b/usr/Src/Core/pJoint/pJointPrismatic.cpp new file mode 100644 index 0000000..23dc44d --- /dev/null +++ b/usr/Src/Core/pJoint/pJointPrismatic.cpp @@ -0,0 +1,44 @@ +#include +#include "vtPhysXAll.h" + +pJointPrismatic::pJointPrismatic(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Prismatic) +{ + +} + + +void pJointPrismatic::setGlobalAnchor(VxVector anchor) +{ + + + NxPrismaticJointDesc descr; + NxPrismaticJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAnchor(getFrom(anchor)); + joint->loadFromDesc(descr); +} + +void pJointPrismatic::setGlobalAxis(VxVector axis) +{ + + + NxPrismaticJointDesc descr; + NxPrismaticJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAxis(getFrom(axis)); + joint->loadFromDesc(descr); +} + +void pJointPrismatic::enableCollision(int collision) +{ + NxPrismaticJointDesc descr; + NxPrismaticJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} \ No newline at end of file diff --git a/usr/Src/Core/pJoint/pJointPulley.cpp b/usr/Src/Core/pJoint/pJointPulley.cpp new file mode 100644 index 0000000..b80243e --- /dev/null +++ b/usr/Src/Core/pJoint/pJointPulley.cpp @@ -0,0 +1,207 @@ +#include +#include "vtPhysXAll.h" + +pJointPulley::pJointPulley(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Pulley) +{ + +} + +void pJointPulley::setLocalAnchorA(VxVector anchor) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.localAnchor[0] = pMath::getFrom(anchor); + joint->loadFromDesc(descr); +} + +VxVector pJointPulley::getLocalAnchorA() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return pMath::getFrom(descr.localAnchor[0]); +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setLocalAnchorB(VxVector anchor) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.localAnchor[1] = pMath::getFrom(anchor); + joint->loadFromDesc(descr); +} + + +VxVector pJointPulley::getLocalAnchorB() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return pMath::getFrom(descr.localAnchor[1]); +} + +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setPulleyA(VxVector pulley) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.pulley[0] = pMath::getFrom(pulley); + joint->loadFromDesc(descr); +} + +VxVector pJointPulley::getPulleyA() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return pMath::getFrom(descr.pulley[0]); +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setPulleyB(VxVector pulley) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.pulley[1] = pMath::getFrom(pulley); + joint->loadFromDesc(descr); +} +VxVector pJointPulley::getPulleyB() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return pMath::getFrom(descr.pulley[1]); +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setStiffness(float stiffness) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.stiffness= stiffness; + joint->loadFromDesc(descr); +} +float pJointPulley::getStiffness() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return -1.0f; + joint->saveToDesc(descr); + return descr.stiffness; +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setRatio(float ratio) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.ratio= ratio; + joint->loadFromDesc(descr); +} +float pJointPulley::getRatio() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return -1.0f; + joint->saveToDesc(descr); + return descr.ratio; +} +////////////////////////////////////////////////////////////////////////// + +void pJointPulley::setDistance(float distance) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.distance= distance; + joint->loadFromDesc(descr); +} +float pJointPulley::getDistance() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return -1.0f; + joint->saveToDesc(descr); + return descr.distance; +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setRigid( bool rigid ) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (rigid) + { + descr.flags|=NX_PJF_IS_RIGID; + }else{ + descr.flags&=~NX_PJF_IS_RIGID; + + } + joint->loadFromDesc(descr); +} +bool pJointPulley::isRigid() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return -1.0f; + joint->saveToDesc(descr); + + return ( descr.flags & NX_PJF_IS_RIGID ); +} +////////////////////////////////////////////////////////////////////////// + + +pMotor pJointPulley::getMotor() +{ + NxPulleyJointDesc descr; + NxPulleyJoint *joint = static_cast(getJoint());joint->saveToDesc(descr); + NxMotorDesc mDescr = descr.motor; + pMotor result; + result.freeSpin = mDescr.freeSpin; + result.targetVelocity= mDescr.velTarget; + result.maximumForce = mDescr.maxForce; + return result; +} +void pJointPulley::setMotor(pMotor motor) +{ + NxPulleyJointDesc descr; + NxPulleyJoint *joint = static_cast(getJoint());joint->saveToDesc(descr); + + NxMotorDesc mDescr = descr.motor; + + if (motor.maximumForce!=0.0f && motor.targetVelocity !=0.0f ) + { + mDescr.freeSpin = motor.freeSpin; + mDescr.velTarget= motor.targetVelocity; + mDescr.maxForce= motor.maximumForce; + descr.flags |= NX_PJF_MOTOR_ENABLED; + joint->setMotor(mDescr); + descr.motor = mDescr; + }else{ + descr.flags &=~NX_PJF_MOTOR_ENABLED; + } + + int flagsNow = descr.flags; + int isValid = descr.isValid(); + + joint->loadFromDesc(descr); +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::enableCollision( bool collision ) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); +} diff --git a/usr/Src/Core/pJoint/pJointRevolute.cpp b/usr/Src/Core/pJoint/pJointRevolute.cpp new file mode 100644 index 0000000..72fc37b --- /dev/null +++ b/usr/Src/Core/pJoint/pJointRevolute.cpp @@ -0,0 +1,207 @@ +#include +#include "vtPhysXAll.h" + + +pJointRevolute::pJointRevolute(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Revolute) +{ + +} +bool pJointRevolute::setHighLimit(pJointLimit limit) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint *joint = static_cast(getJoint()); + if (!joint)return false; + joint->saveToDesc(descr); + + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.limit.high= sLimit; + + if (sLimit.hardness!=0.0f || sLimit.restitution!=0.0f || sLimit.value !=0.0f ) + { + descr.flags |= NX_RJF_LIMIT_ENABLED; + }else + descr.flags &=~NX_RJF_LIMIT_ENABLED; + + int v = descr.isValid(); + + + joint->loadFromDesc(descr); + return true; +} +bool pJointRevolute::setLowLimit(pJointLimit limit) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint *joint = static_cast(getJoint()); + if (!joint)return false; + joint->saveToDesc(descr); + + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.limit.low= sLimit; + if (sLimit.hardness!=0.0f || sLimit.restitution!=0.0f || sLimit.value !=0.0f ) + { + descr.flags |= NX_RJF_LIMIT_ENABLED; + }else + descr.flags &=~NX_RJF_LIMIT_ENABLED; + + bool ret = descr.isValid(); + joint->loadFromDesc(descr); + return ret; +} + +pSpring pJointRevolute::getSpring() +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + + joint->saveToDesc(descr); + return pSpring (descr.spring.damper,descr.spring.spring,descr.spring.targetValue); + +} + +bool pJointRevolute::setSpring(pSpring spring) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + if (!joint)return false ; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.spring= sLimit; + + if (spring.damper!=0.0f || !spring.spring!=0.0f || !spring.targetValue !=0.0f ) + { + descr.flags |= NX_RJF_SPRING_ENABLED; + }else + descr.flags &=~NX_RJF_SPRING_ENABLED; + + + joint->loadFromDesc(descr); + return false; +} + + + +pMotor pJointRevolute::getMotor() +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + + NxMotorDesc mDescr = descr.motor; + pMotor result; + result.freeSpin = mDescr.freeSpin; + result.targetVelocity= mDescr.velTarget; + result.maximumForce = mDescr.maxForce; + return result; +} + +bool pJointRevolute::setMotor(pMotor motor) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + + NxMotorDesc mDescr = descr.motor; + + if (motor.maximumForce!=0.0f && motor.targetVelocity !=0.0f ) + { + mDescr.freeSpin = motor.freeSpin; + mDescr.velTarget= motor.targetVelocity; + mDescr.maxForce= motor.maximumForce; + descr.flags |= NX_RJF_MOTOR_ENABLED; + joint->setMotor(mDescr); + descr.motor = mDescr; + }else{ + descr.flags &=~NX_RJF_MOTOR_ENABLED; + } + joint->loadFromDesc(descr); + + return descr.isValid(); +} +void pJointRevolute::enableCollision(bool collision) +{ + + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} + + +void pJointRevolute::setGlobalAnchor(const VxVector& anchor) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + //descr.setGlobalAnchor(pMath::getFrom(anchor)); + //descr.localAnchor[0] = NxVec3(0,-40,0); + // joint->loadFromDesc(descr); + + + joint->setGlobalAnchor(pMath::getFrom(anchor)); + +} + +void pJointRevolute::setGlobalAxis(const VxVector& axis) +{ + NxRevoluteJointDesc descr; + + NxRevoluteJoint*joint = static_cast(getJoint()); + //joint->saveToDesc(descr); + //descr.setGlobalAxis(pMath::getFrom(axis)); + //joint->loadFromDesc(descr); + + joint->setGlobalAxis(pMath::getFrom(axis)); +} + + +pJointLimit pJointRevolute::getHighLimit() +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + + joint->saveToDesc(descr); + return pJointLimit (descr.limit.high.hardness,descr.limit.high.restitution,descr.limit.high.value); + +} + +pJointLimit pJointRevolute::getLowLimit() +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + + joint->saveToDesc(descr); + return pJointLimit (descr.limit.low.hardness,descr.limit.low.restitution,descr.limit.low.value); + +} +void pJointRevolute::setProjectionMode(ProjectionMode mode) +{ + NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionMode = (NxJointProjectionMode)mode; + joint->loadFromDesc(descr); +} + +void pJointRevolute::setProjectionDistance(float distance) +{ + NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionDistance= distance; + joint->loadFromDesc(descr); +} + +void pJointRevolute::setProjectionAngle(float angle) +{ + NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionAngle= angle; + int s = descr.isValid(); + joint->loadFromDesc(descr); +} \ No newline at end of file diff --git a/usr/Src/Core/pLogger.cpp b/usr/Src/Core/pLogger.cpp new file mode 100644 index 0000000..d5e3a2a --- /dev/null +++ b/usr/Src/Core/pLogger.cpp @@ -0,0 +1,16 @@ +#include +#include "vtPhysXAll.h" + +#include "pLogger.h" +#include "pErrorStream.h" + + +static pErrorStream gErrorStream; + +pLogger::pLogger() +{ + + mErrorStream = &gErrorStream; + +} + diff --git a/usr/Src/Core/pMathTools.cpp b/usr/Src/Core/pMathTools.cpp new file mode 100644 index 0000000..91e0378 --- /dev/null +++ b/usr/Src/Core/pMathTools.cpp @@ -0,0 +1,56 @@ +#include +#include "vtPhysXAll.h" + +#include "pMathTools.h" + +namespace pMath +{ + +VxQuaternion getFromStream(NxQuat source) +{ + + VxQuaternion result; + + result.x = source.x; + result.y = source.z; + result.z = source.y; + result.w = source.w; + + return result; + + +} +VxVector getFromStream(NxVec3 source) +{ + + VxVector result; + result.x = source.x; + result.y = source.z; + result.z = source.y; + return result; + +} + + +NxQuat getFrom(VxQuaternion source) +{ + NxQuat result; + result.setx(-source.x); + result.sety(-source.y); + result.setz(-source.z); + result.setw(source.w); + return result; +} + VxQuaternion getFrom(NxQuat source) +{ + + VxQuaternion result; + source.getXYZW(result.v); + result.x = -result.x; + result.z = -result.z; + result.y = -result.y; + return result; +} + +} + diff --git a/usr/Src/Core/pMisc.cpp b/usr/Src/Core/pMisc.cpp new file mode 100644 index 0000000..9de8825 --- /dev/null +++ b/usr/Src/Core/pMisc.cpp @@ -0,0 +1,279 @@ +#include + +#include "NxShape.h" +#include "Nxp.h" +#include "pMisc.h" + +#include "PhysicManager.h" +#include "vtPhysXAll.h" + + +namespace vtAgeia +{ +CK3dEntity *getEntityFromShape(NxShape* shape) +{ + + if ( !shape) + return NULL; + + pSubMeshInfo *sInfo = (pSubMeshInfo*)shape->userData; + if (sInfo) + { + CK3dEntity *ent = (CK3dEntity*)CKGetObject(ctx(),sInfo->entID); + return ent; + } + return NULL; +} +bool isChildOf(CK3dEntity*parent,CK3dEntity*test) +{ + + CK3dEntity* subEntity = NULL; + while (subEntity= parent->HierarchyParser(subEntity) ) + { + if (subEntity == test) + { + return true; + } + } + return false; +} + +CK3dEntity* findSimilarInSourceObject(CK3dEntity *parentOriginal,CK3dEntity* partentCopied,CK3dEntity *copiedObject,CK3dEntity*prev) +{ + + + if (!parentOriginal || !copiedObject ) + return NULL; + + if (parentOriginal->GetChildrenCount() < 1) + return NULL; + + + if ( prev && prev!=copiedObject && isChildOf(parentOriginal,prev) && !isChildOf(partentCopied,prev) ) + return prev; + + + CK3dEntity *orginalObject= (CK3dEntity*)ctx()->GetObjectByNameAndClass(copiedObject->GetName(),CKCID_3DOBJECT,prev); + if (orginalObject) + { + + //---------------------------------------------------------------- + // + // tests + // + if ( orginalObject==copiedObject ) + findSimilarInSourceObject(parentOriginal,partentCopied,copiedObject,orginalObject); + + + if ( !isChildOf(parentOriginal,orginalObject)) + findSimilarInSourceObject(parentOriginal,partentCopied,copiedObject,orginalObject); + + if( isChildOf(partentCopied,orginalObject) ) + findSimilarInSourceObject(parentOriginal,partentCopied,copiedObject,orginalObject); + + + + return orginalObject; + } + return NULL; +} + + +bool calculateOffsets(CK3dEntity*source,CK3dEntity*target,VxQuaternion &quat,VxVector& pos) +{ + if (!source && !target) + return false; + + CK3dEntity* child = NULL; + bool isChild = false; + while (child = source->HierarchyParser(child) ) + { + if (child == target ) + { + isChild = true; + } + } + + VxQuaternion refQuad2; + target->GetQuaternion(&refQuad2,source); + VxVector relPos; + target->GetPosition(&relPos,source); + + pos = relPos; + quat = refQuad2; + + return true; + +} +int getNbOfPhysicObjects(CK3dEntity *parentObject,int flags/* =0 */) +{ + #ifdef _DEBUG + assert(parentObject); + #endif // _DEBUG + + int result = 0; + //---------------------------------------------------------------- + // + // parse hierarchy + // + + CK3dEntity* subEntity = NULL; + while (subEntity= parentObject->HierarchyParser(subEntity) ) + { + + pRigidBody *body = GetPMan()->getBody(subEntity); + if (body) + result++; + } + return result; +} +int getHullTypeFromShape(NxShape *shape) +{ + + int result = - 1; + if (!shape) + { + return result; + } + + int nxType = shape->getType(); + switch (nxType) + { + case NX_SHAPE_PLANE: + return HT_Plane; + + case NX_SHAPE_BOX: + return HT_Box; + + case NX_SHAPE_SPHERE: + return HT_Sphere; + + case NX_SHAPE_CONVEX: + return HT_ConvexMesh; + + case NX_SHAPE_CAPSULE: + return HT_Capsule; + + case NX_SHAPE_MESH: + return HT_Mesh; + } + + return -1; + +} + + +int getEnumIndex(CKParameterManager* pm,CKGUID parGuide,XString enumValue) +{ + + int pType = pm->ParameterGuidToType(parGuide); + + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + + if( !strcmp(enumStruct->GetEnumDescription(i),enumValue.Str()) ) + return i; + } + } + return 0; +} + +XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide) +{ + + XString result; + int pType = pm->ParameterGuidToType(parGuide); + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + result << enumStruct->GetEnumDescription(i); + result << "="; + result << enumStruct->GetEnumValue(i); + if (i < enumStruct->GetNumEnums() -1 ) + { + result << ","; + } + } + } + return result; +} + +XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide,int parameterSubIndex) +{ + + XString result="None"; + int pType = pm->ParameterGuidToType(parGuide); + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + if(i == parameterSubIndex) + { + result = enumStruct->GetEnumDescription(i); + } + } + } + return result; +} + +//************************************ +// Method: BoxGetZero +// FullName: vtAgeia::BoxGetZero +// Access: public +// Returns: VxVector +// Qualifier: +// Parameter: vt3DObject ent +//************************************ +VxVector BoxGetZero(CK3dEntity* ent) +{ + + VxVector box_s= VxVector(1,1,1); + if (ent) + { + + VxMatrix mat = ent->GetWorldMatrix(); + VxVector g; + //Vx3DMatrixToEulerAngles(mat,&g.x,&g.y,&g.z); + //SetEulerDirection(ent,VxVector(0,0,0)); + CKMesh *mesh = ent->GetCurrentMesh(); + + + if (mesh!=NULL) + { + box_s = mesh->GetLocalBox().GetSize(); + } + //SetEulerDirection(ent,g); + } + return box_s; +} + +//************************************ +// Method: SetEulerDirection +// FullName: vtAgeia::SetEulerDirection +// Access: public +// Returns: void +// Qualifier: +// Parameter: CK3dEntity* ent +// Parameter: VxVector direction +//************************************ +void SetEulerDirection(CK3dEntity* ent,VxVector direction) +{ + + VxVector dir,up,right; + VxMatrix mat; + Vx3DMatrixFromEulerAngles(mat,direction.x,direction.y,direction.z); + dir=(VxVector)mat[2]; + up=(VxVector)mat[1]; + right=(VxVector)mat[0]; + ent->SetOrientation(&dir,&up,&right,NULL,FALSE); + +} + + +} diff --git a/usr/Src/Core/pRigidBody/pRigidBody.cpp b/usr/Src/Core/pRigidBody/pRigidBody.cpp new file mode 100644 index 0000000..5b9f29f --- /dev/null +++ b/usr/Src/Core/pRigidBody/pRigidBody.cpp @@ -0,0 +1,1148 @@ +#include +#include "vtPhysXAll.h" + +#include "NXU_helper.h" // NxuStream helper functions. +#include "NXU_PhysicsInstantiator.h" + +#include "Stream.h" +#include "cooking.h" + +#include "IParameter.h" + + +void pRigidBody::setCMassOffsetGlobalPosition(VxVector vec){ + getActor()->setCMassOffsetGlobalPosition(getFrom(vec)); +} + +void pRigidBody::setCMassGlobalPosition(VxVector vec) +{ + getActor()->setCMassGlobalPosition(getFrom(vec)); +} +VxVector pRigidBody::getCMassLocalPosition(){ + return getFrom(getActor()->getCMassLocalPosition()); +} +VxVector pRigidBody::getCMassGlobalPosition(){ + return getFrom(getActor()->getCMassGlobalPosition()); +} +void pRigidBody::setMassSpaceInertiaTensor(VxVector m){ + getActor()->setMassSpaceInertiaTensor(getFrom(m)); +} +VxVector pRigidBody::getMassSpaceInertiaTensor(){ + return getFrom(getActor()->getMassSpaceInertiaTensor()); +} + +void pRigidBody::setCMassOffsetLocalPosition(VxVector offset){ + getActor()->setCMassOffsetLocalPosition(getFrom(offset)); +} + + +int pRigidBody::getNbSubShapes() +{ + + + NxActor *actor = getActor(); + if(actor){ + return actor->getNbShapes(); + } + + return -1; +} + +int pRigidBody::getNbSubBodies() +{ + + + if(!getActor()) + return -1; + + CK3dEntity* subEntity = NULL; + int nb = 0; + while (subEntity= GetVT3DObject()->HierarchyParser(subEntity)) + { + + if (isSubShape(subEntity)) + continue; + // CKSTRING name =subEntity->GetName(); + // body ? + pRigidBody *body = GetPMan()->getBody(subEntity); + if (body && body!=this ) + { + nb++; + } + } + return nb; +} +void pRigidBody::updateMassSettings(pMassSettings massSettings) +{ + + + // Referential + CK3dEntity* massRef = (CK3dEntity*)GetPMan()->GetContext()->GetObject(massSettings.massReference); + + VxVector massLocalOut = massSettings.localPosition; + //---------------------------------------------------------------- + // + // position + // + if (XAbs(massSettings.localPosition.SquareMagnitude()) >0.0f ) + { + if (massRef) + { + VxVector tOut = massLocalOut; + massRef->Transform(&massLocalOut,&massLocalOut); + massRef->TransformVector(&tOut,&tOut,GetVT3DObject()); + getActor()->setCMassOffsetLocalPosition(getFrom(tOut)); + }else + { + getActor()->setCMassOffsetLocalPosition(getFrom(massLocalOut)); + } + } + //---------------------------------------------------------------- + // + // rotational offset : todo + // + VxMatrix mat; + Vx3DMatrixFromEulerAngles(mat,massSettings.localOrientation.x,massSettings.localOrientation.y,massSettings.localOrientation.z); + + VxQuaternion outQuat; + outQuat.FromMatrix(mat); + + VxQuaternion referenceQuat=outQuat; + if (XAbs(massSettings.localOrientation.SquareMagnitude()) >0.0f ) + { + if (massRef) + { + massRef->GetQuaternion(&referenceQuat,NULL); + getActor()->setCMassOffsetGlobalOrientation(getFrom(referenceQuat)); + }else{ + getActor()->setCMassOffsetGlobalOrientation(getFrom(outQuat)); + } + } + + //---------------------------------------------------------------- + // + // recompute mass + // + + float newDensity=massSettings.newDensity; + float totalMass =massSettings.totalMass; + + int bMassResult = 0 ; + if (newDensity!=0.0f || totalMass!=0.0f ) + { + bMassResult = getActor()->updateMassFromShapes(newDensity,totalMass); + } + + int op = bMassResult; + + +} + +int pRigidBody::_initMainShape(const pObjectDescr oDescr,NxActorDesc *actorDesc) +{ + + //---------------------------------------------------------------- + // + // Sanity Checks + // + #ifdef _DEBUG + assert(GetVT3DObject()); // has to been set before + #endif // _DEBUG + + //---------------------------------------------------------------- + // + // Collect some data + // + + VxVector box_s= BoxGetZero(GetVT3DObject()); + float density = oDescr.density; + float radius = GetVT3DObject()->GetRadius(); + + + switch(oDescr.hullType) + { + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.dimensions = pMath::getFrom(box_s)*0.5f; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc->shapes.pushBack(&shape); + + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.radius = radius; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc->shapes.pushBack(&shape); + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + + if (! (oDescr.flags & BF_Deformable) ) + { + + //xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Can not use a mesh as de"); + //return NULL; + + } + + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + + pFactory::Instance()->createMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return false; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + shape.group = oDescr.collisionGroup; + + actorDesc->shapes.pushBack(&shape); + + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + if (GetVT3DObject()->GetCurrentMesh()) + { + if (GetVT3DObject()->GetCurrentMesh()->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshs allowed, by Ageia!"); + return false; + } + }else + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); + return false; + + + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + pFactory::Instance()->createConvexMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxConvexShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + return false; + + + } + shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + + actorDesc->shapes.pushBack(&shape); + + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + CloseCooking(); + + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexCylinder: + { + NxConvexShapeDesc shape; + if (!pFactory::Instance()->_createConvexCylinder(&shape,GetVT3DObject())){ + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + return false; + } + + shape.density = density; + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc->shapes.pushBack(&shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + + NxCapsuleShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + + pCapsuleSettings cSettings; + + pFactory::Instance()->findSettings(cSettings,GetVT3DObject()); + + shape.radius = cSettings.radius > 0.0f ? cSettings.radius : box_s.v[cSettings.localRadiusAxis] * 0.5f; + shape.height = cSettings.height > 0.0f ? cSettings.height : box_s.v[cSettings.localLengthAxis] - ( 2*shape.radius) ; + } + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + // shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + actorDesc->shapes.pushBack(&shape); + break; + } + + case HT_Wheel: + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Wheel shape can be sub shape only!"); + return false; + } + } + + return true; + +} + + +/*int pRigidBody::_initMainShape(const pObjectDescr oDescr,NxActorDesc&actorDesc) +{ + + //---------------------------------------------------------------- + // + // Sanity Checks + // + #ifdef _DEBUG + assert(GetVT3DObject()); // has to been set before + #endif // _DEBUG + + //---------------------------------------------------------------- + // + // Collect some data + // + + VxVector box_s= BoxGetZero(GetVT3DObject()); + float density = oDescr.density; + float radius = GetVT3DObject()->GetRadius(); + + + switch(oDescr.hullType) + { + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.dimensions = pMath::getFrom(box_s)*0.5f; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc.shapes.pushBack(&shape); + + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.radius = radius; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + int oG = oDescr.collisionGroup; + shape.group = oDescr.collisionGroup; + + int k = shape.isValid(); + + actorDesc.shapes.pushBack(&shape); + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + + if (! (oDescr.flags & BF_Deformable) ) + { + + //xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Can not use a mesh as de"); + //return NULL; + + } + + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + + pFactory::Instance()->createMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return false; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + shape.group = oDescr.collisionGroup; + + actorDesc.shapes.pushBack(&shape); + + + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + if (GetVT3DObject()->GetCurrentMesh()) + { + if (GetVT3DObject()->GetCurrentMesh()->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshs allowed, by Ageia!"); + return false; + } + }else + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); + return false; + + + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + pFactory::Instance()->createConvexMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxConvexShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + return false; + + + } + shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + actorDesc.shapes.pushBack(&shape); + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + int h = shape.isValid(); + CloseCooking(); + + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexCylinder: + { + NxConvexShapeDesc shape; + if (!pFactory::Instance()->_createConvexCylinder(&shape,GetVT3DObject())){ + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + return false; + } + + shape.density = density; + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc.shapes.pushBack(&shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + + NxCapsuleShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + + pCapsuleSettings cSettings; + + pFactory::Instance()->findSettings(cSettings,GetVT3DObject()); + + shape.radius = cSettings.radius > 0.0f ? cSettings.radius : box_s.v[cSettings.localRadiusAxis] * 0.5f; + shape.height = cSettings.height > 0.0f ? cSettings.height : box_s.v[cSettings.localLengthAxis] - ( 2*shape.radius) ; + } + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + // shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + break; + } + + case HT_Wheel: + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Wheel shape can be sub shape only!"); + return false; + } + } + + return true; + +} +*/ + + +void pRigidBody::deleteJoint(pJoint*joint) +{ + if (joint && getWorld()) + { + getWorld()->deleteJoint(joint); + } +} +void pRigidBody::deleteJoint(CK3dEntity*_b,JType type) +{ + if (getWorld()) + { + pJoint * j = getJoint(_b,type); + if (j) + { + getWorld()->deleteJoint(j); + } + } +} + +pJoint* +pRigidBody::getJoint(CK3dEntity*_b,JType type) +{ + + pWorld *world = getWorld(); + if (!world) + return NULL; + + return world->getJoint(GetVT3DObject(),_b,type); +} +pJoint * +pRigidBody::getJointAtIndex(int index) +{ + int nbJoints = getNbJoints(); + + if (index >=0 && index < nbJoints) + { + int currentIndexBodyJoint = 0; + pWorld *wA =getWorld(); + if (!wA) + { + return NULL; + } + + ////////////////////////////////////////////////////////////////////////// + + NxU32 jointCount = wA->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + wA->getScene()->resetJointIterator(); + + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = wA->getScene()->getNextJoint(); + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == GetVT3DObject() || mJoint->GetVTEntB() == GetVT3DObject() ) + { + if (currentIndexBodyJoint == index) + { + return mJoint; + } + currentIndexBodyJoint ++; + } + } + } + } + } + return NULL; +} +int pRigidBody::getNbJoints() +{ + + pWorld *wA =getWorld(); + + int result = 0 ; + + if (!wA) + { + return result; + } + NxU32 jointCount = wA->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + wA->getScene()->resetJointIterator(); + + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = wA->getScene()->getNextJoint(); + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == GetVT3DObject() || mJoint->GetVTEntB() == GetVT3DObject() ) + { + result++; + } + } + } + } + + return result; +} + +void pRigidBody::test() +{ + + pRigidBody *body = this; + CK3dEntity* test = (CK3dEntity*)body; + +} +void pRigidBody::readFrom(NXU::NxActorDesc *desc,int flags) +{ + + if ( desc->mHasBody ) // only for dynamic actors + { + for (NxU32 k=0; kmShapes.size(); k++) + { + NXU::NxShapeDesc *shape = desc->mShapes[k]; + NxVec3 locPos = shape->localPose.t; + NxQuat localQuad = shape->localPose.M; + } + } + +} + +float pRigidBody::getMass() +{ + float result = 0 ; + + if (getActor()) + { + result += getActor()->getMass(); + } + if (getVehicle()) + { + for(NxU32 i = 0; i < getVehicle()->_wheels.size(); i++) + { + pWheel *cW = getVehicle()->_wheels[i]; + pWheel2* wheel2 = (pWheel2*)cW; + if (wheel2) + { + result+=wheel2->getMass(); + } + } + } + return result; +} +VxVector pRigidBody::getLocalPointVelocity( const VxVector& point ) const +{ + if(isValid()) + return pMath::getFrom(getActor()->getLocalPointVelocity(getFrom(point))); + return VxVector(); +} + +VxVector pRigidBody::getPointVelocity( const VxVector& point ) const +{ + if(isValid()) + return pMath::getFrom(getActor()->getPointVelocity(getFrom(point))); + return VxVector(); +} +pJoint* pRigidBody::isConnected(CK3dEntity*ent) +{ + + + pJoint *result = NULL; + pWorld *wA =getWorld(); + pWorld *wB =NULL; + pRigidBody *b = NULL; + if (!wA) + { + return NULL; + } + + if (ent) + { + b = GetPMan()->getBody(ent); + } + if (b) + { + wB = b->getWorld(); + } + + NxU32 jointCount = wA->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + wA->getScene()->resetJointIterator(); + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = wA->getScene()->getNextJoint(); + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == GetVT3DObject() && mJoint->GetVTEntB() == ent ) + { + return mJoint; + } + if (mJoint->GetVTEntB() == GetVT3DObject() && mJoint->GetVTEntA() == ent ) + { + return mJoint; + } + } + } + } + return NULL; +} + +void pRigidBody::setLocalShapePosition(VxVector relative,CK3dEntity*shapeReference/* =NULL */) +{ + + + if(!getActor()) + return; + + NxShape *subShape = getSubShape(shapeReference); + if (subShape ) + { + subShape->setLocalPosition(getFrom(relative)); + } + + /*NxU32 nbShapes = getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; jsetLocalPosition(pMath::getFrom(relative)); + int op=2; + return; + + //getActor()->updateMassFromShapes() + } + //addShapeMesh(c,s); + } + }*/ + +} + + + + + + +pRigidBody::pRigidBody(CK3dEntity* _e,pWorld *world) : xEngineObjectAssociation(_e,_e->GetID()) , mVTObject(_e) , m_pWorld(world) +{ + + + using namespace vtTools::AttributeTools; + mActor = NULL; + hasBrokenJoint = false; + context = NULL; + if (_e) + { + mEntID = _e->GetID(); + mVTObject = _e; + } + mMaterial = NULL; + mDataFlags = 0; + mMainShape = NULL; + mMaterial = NULL; + mVehicle = NULL; + mMainShape = NULL; + mActor =NULL; + mCloth = NULL; + + //mClothRecieveBuffer=NULL; + +} + + +pRigidBody::pRigidBody(CK3dEntity* _e) +{ + SetVT3DObject(_e); + if (_e){ + mEntID = _e->GetID(); + mVTObject = _e; + + } + mMaterial = NULL; + mDataFlags = 0; + mVehicle = NULL; + mMainShape = NULL; + mActor =NULL; + mVTObject = NULL; + m_pWorld = NULL; + mCloth = NULL; + mInitialDescription = NULL; + + + +} + + +void pRigidBody::addLocalForceAtLocalPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addLocalForceAtLocalPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode,wakeUp); +} +void pRigidBody::addLocalForceAtPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addLocalForceAtPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode,wakeUp); +} +void pRigidBody::addForceAtLocalPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addForceAtLocalPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode,wakeUp); +} +void pRigidBody::addForceAtPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addForceAtPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode); +} +void pRigidBody::addTorque(const VxVector& torque,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addTorque(pMath::getFrom(torque),(NxForceMode)mode,wakeUp); +} +void pRigidBody::addLocalTorque(const VxVector& torque,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addLocalTorque(pMath::getFrom(torque),(NxForceMode)mode); +} + +void pRigidBody::addLocalForce(const VxVector& force,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addLocalForce(pMath::getFrom(force),(NxForceMode)mode,wakeUp); +} + +void pRigidBody::addForce( const VxVector& force,ForceMode mode/*=E_FM_FORCE*/,bool wakeUp/*=true*/ ) +{ + if(isValid()) + getActor()->addForce(pMath::getFrom(force),(NxForceMode)mode,wakeUp); +} + + +void pRigidBody::setLinearMomentum( const VxVector& linMoment ) +{ if(isValid()) getActor()->setLinearMomentum(pMath::getFrom(linMoment)); } +void pRigidBody::setAngularMomentum( const VxVector& angMoment ) +{ + if(isValid()) + getActor()->setAngularMomentum(pMath::getFrom(angMoment)); +} +VxVector pRigidBody::getAngularMomentum() const +{ + if(isValid()) + return pMath::getFrom(getActor()->getAngularMomentum()); + return VxVector(); +} + +float pRigidBody::getAngularDamping() const +{ + if(isValid()) + return getActor()->getAngularDamping(); + return 0.0f; +} +float pRigidBody::getLinearDamping() const +{ + if(isValid()) + return getActor()->getLinearDamping(); + return 0.0f; +} +VxVector pRigidBody::getLinearMomentum()const{ + if(isValid()) + return pMath::getFrom(getActor()->getLinearMomentum()); + return VxVector(); +} +void pRigidBody::setPosition(const VxVector& pos,CK3dEntity *subShapeReference) +{ + if(isValid()){ + + + NxShape *subShape = getSubShape(subShapeReference); + if (subShape == getMainShape() ) + { + if (!isKinematic()) + { + getActor()->setGlobalPosition(pMath::getFrom(pos)); + + }else{ + getActor()->moveGlobalPosition(pMath::getFrom(pos)); + + } + }else{ + if (subShape) + { + subShape->setGlobalPosition(getFrom(pos)); + } + } + } +} + +void pRigidBody::setRotation(const VxQuaternion& rot,CK3dEntity *subShapeReference) +{ + if(isValid()) + { + NxShape *subShape = getSubShape(subShapeReference); + if (subShape == getMainShape() ) + { + getActor()->setGlobalOrientation(pMath::getFrom(rot)); + }else + { + if (subShape) + { + subShape->setGlobalOrientation(getFrom(rot)); + } + } + } +} +float pRigidBody::getMaxAngularSpeed() const +{ + if(isValid())return getActor()->getMaxAngularVelocity(); + return 0.0f; +} +void pRigidBody::setMaxAngularSpeed(float val) { if(isValid())getActor()->setMaxAngularVelocity(val); } +VxVector pRigidBody::getLinearVelocity() const{ return pMath::getFrom(getActor()->getLinearVelocity());} +VxVector pRigidBody::getAngularVelocity() const{ return pMath::getFrom(getActor()->getAngularVelocity());} +void pRigidBody::setLinearVelocity( const VxVector& linVel ) +{ if(isValid()) + getActor()->setLinearVelocity(pMath::getFrom(linVel)); +} +void pRigidBody::setAngularVelocity( const VxVector& angVel ) +{ + if(isValid()) + getActor()->setAngularVelocity(pMath::getFrom(angVel)); +} + +void pRigidBody::setAngularDamping(float scale) +{ + + if (getActor() && getActor()->isDynamic()) + { + getActor()->setAngularDamping(scale); + } +} +void pRigidBody::setLinearDamping(float scale) +{ + + if (getActor() && getActor()->isDynamic()) + { + getActor()->setLinearDamping(scale); + } + +} +void pRigidBody::translateLocalShapePosition(VxVector vec) +{ + + if (getActor()) + { + + if (getMainShape()) + { + NxVec3 currentPos = getMainShape()->getLocalPosition(); + getMainShape()->setLocalPosition( currentPos + getFrom(vec)); + } + } +} + +pJoint* pRigidBody::isConnected(CK3dEntity*ent,int type) +{ + /* + pJoint *result = NULL; + + if ( GetVT3DObject()!=ent) + { + pRigidBody *b = GetPMan()->getBody(ent); + + OdeBodyType abid = GetOdeBody(); + OdeBodyType bbid = NULL; + + if (b) + { + bbid = b->GetOdeBody(); + } + + dxJoint *j = NULL; + for (j=World()->World()->firstjoint; j; j=(dxJoint*)j->next) + { + pJoint *pJ = static_cast(dJointGetData(j)); + if (pJ) + { + + if (!bbid) + { + if (dJointGetType(j) ==dJointTypeFixed ) + { + if (pJ->GetOdeBodyA()==abid) + { + return pJ; + } + } + } + + if ( pJ->GetOdeBodyA()==abid && dJointGetType(j) == type) + { + if (pJ->GetOdeBodyB()==bbid ) + { + return pJ; + } + } + + if ( pJ->GetOdeBodyA()==bbid && dJointGetType(j) == type) + { + if (pJ->GetOdeBodyB()==abid ) + { + return pJ; + } + } + } + } + } + return result; + */ + return NULL; +} + +void pRigidBody::SetVT3DObject(CK3dEntity* _obj) +{ mEntID = _obj->GetID(); mVTObject=_obj;} + +CK3dEntity*pRigidBody::GetVT3DObject() +{ return mVTObject; } \ No newline at end of file diff --git a/usr/Src/Core/pRigidBody/pRigidBodyCollision.cpp b/usr/Src/Core/pRigidBody/pRigidBodyCollision.cpp new file mode 100644 index 0000000..a4e823b --- /dev/null +++ b/usr/Src/Core/pRigidBody/pRigidBodyCollision.cpp @@ -0,0 +1,350 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" +#include "IParameter.h" + + +bool pFactory::_createConvexCylinder(NxConvexShapeDesc* shape, + CK3dEntity*dstBodyReference, + pObjectDescr *oDescr) +{ + + + #ifdef _DEBUG + assert(dstBodyReference); // <- should never happen ! + #endif // _DEBUG + + bool result = false; + + pConvexCylinderSettings cSettingsZero; + + pConvexCylinderSettings &cSettings = cSettingsZero; + + if (oDescr ) + { + if( (oDescr->mask & OD_ConvexCylinder) ) + cSettings = oDescr->convexCylinder; + }else + { + findSettings(cSettings,dstBodyReference); + } + + + cSettings.radius.value *=0.5f; + cSettings.height.value *=0.5f; + + NxArray points; + NxVec3 center(0,0,0); + + NxVec3 frontAxis = getFrom(cSettings.forwardAxis); // = wheelDesc->downAxis.cross(wheelDesc->wheelAxis); + NxVec3 downAxis = getFrom(cSettings.downAxis);//downAxis *=-1.0; // = wheelDesc->downAxis; + NxVec3 wheelAxis = getFrom(cSettings.rightAxis); // = wheelDesc->wheelAxis; + + + //frontAxis.normalize(); + frontAxis *= cSettings.radius.value; + //downAxis.normalize(); + downAxis *= cSettings.radius.value; + //wheelAxis.normalize(); + wheelAxis *= cSettings.height.value; + + NxReal step; + + if(cSettings.buildLowerHalfOnly) + { + if((cSettings.approximation& 0x1) == 0) + cSettings.approximation++; + + step = (NxReal)(NxTwoPi) / (NxReal)(cSettings.approximation*2); + } + else + { + step = (NxReal)(NxTwoPi) / (NxReal)(cSettings.approximation); + } + for(NxU32 i = 0; i < cSettings.approximation; i++) + { + NxReal iReal; + if(cSettings.buildLowerHalfOnly) + { + iReal = (i > (cSettings.approximation >> 1))?(NxReal)(i+cSettings.approximation):(NxReal)i; + } + else + { + iReal = (NxReal)i; + } + NxReal Sin, Cos; + NxMath::sinCos(step * iReal, Sin, Cos); + NxVec3 insPoint = (downAxis * -Cos) + (frontAxis * Sin); + points.pushBack(insPoint + wheelAxis); + points.pushBack(insPoint - wheelAxis); + } + + NxConvexMeshDesc convexDesc; + convexDesc.numVertices = points.size(); + convexDesc.pointStrideBytes = sizeof(NxVec3); + convexDesc.points = &points[0].x; + + int cf = CF_ComputeConvex; + cf |= cSettings.convexFlags; + convexDesc.flags |= cf; + + // Cooking from memory + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + int s = convexDesc.isValid(); + if(CookConvexMesh(convexDesc, buf)) + { + //NxConvexShapeDesc convexShapeDesc; + + shape->meshData = getPhysicSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape->localPose.t = center; + shape->localPose.M.setColumn(0, NxVec3( 1, 0, 0)); + shape->localPose.M.setColumn(1, NxVec3( 0,-1, 0)); + shape->localPose.M.setColumn(2, NxVec3( 0, 0, -1)); + if(shape->meshData != NULL) + { + result = true; + // NxU32 shapeNumber = actor->getNbShapes(); + // result = actor->createShape(convexShapeDesc)->isConvexMesh(); + // if (!result) { + // xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + // } + //wheel->wheelConvex->userData = wheel; + } + } + CloseCooking(); + return result; +} + +void pRigidBody::updateCollisionSettings(pCollisionSettings collision,CK3dEntity*shapeReference/* =NULL */) +{ + + if (shapeReference==NULL) + assert (getMainShape()); + + NxShape *shape = getSubShape(shapeReference); + if (shape) + { + //---------------------------------------------------------------- + // + // Update groups mask + // + NxGroupsMask mask1; + + mask1.bits0 = collision.groupsMask.bits0; + mask1.bits1 = collision.groupsMask.bits1; + mask1.bits2 = collision.groupsMask.bits2; + mask1.bits3 = collision.groupsMask.bits3; + + shape->setGroupsMask(mask1); + + //---------------------------------------------------------------- + // + // Collisions group + // + shape->setGroup(collision.collisionGroup); + + //---------------------------------------------------------------- + // + // Skin Width + // + shape->setSkinWidth(collision.skinWidth); + } +} + +void pRigidBody::updateCollisionSettings(const pObjectDescr oDescr,CK3dEntity*shapeReference/* =NULL */) +{ + + int v = oDescr.version; + assert(oDescr.version == pObjectDescr::E_OD_VERSION::OD_DECR_V1); + + if (shapeReference==NULL) + assert (getMainShape()); + + NxShape *shape = getSubShape(shapeReference); + if (shape) + { + //---------------------------------------------------------------- + // + // Update groups mask + // + NxGroupsMask mask1; + + mask1.bits0 = oDescr.groupsMask.bits0; + mask1.bits1 = oDescr.groupsMask.bits1; + mask1.bits2 = oDescr.groupsMask.bits2; + mask1.bits3 = oDescr.groupsMask.bits3; + + shape->setGroupsMask(mask1); + + //---------------------------------------------------------------- + // + // Collisions group + // + shape->setGroup(oDescr.collisionGroup); + + //---------------------------------------------------------------- + // + // Skin Width + // + shape->setSkinWidth(oDescr.skinWidth); + + + + + //---------------------------------------------------------------- + // + // CCD Setup : + // + if (oDescr.ccdMeshReference) + { + + NxCCDSkeleton *skeleton = NULL; + if (oDescr.ccdFlags && CCD_Shared && GetPMan()->GetContext()->GetObject(oDescr.ccdMeshReference) ) + skeleton = GetPMan()->getCCDSkeleton(((CKBeObject*)(GetPMan()->GetContext()->GetObject(oDescr.ccdMeshReference)))); + + if (skeleton == NULL ) + skeleton = pFactory::Instance()->createCCDSkeleton(shapeReference,oDescr.ccdFlags); + + XString errorString; + + if (!skeleton){ + errorString.Format("Creation of CCD skeleton for %s failed!",GetVT3DObject()->GetName()); + xLogger::xLog(ELOGERROR,E_LI_MANAGER,errorString.Str()); + return; + } + + shape->setCCDSkeleton(skeleton); + + //---------------------------------------------------------------- + // + // update sub mesh info : + // + + pSubMeshInfo *sInfo = static_cast(shape->userData); + if (sInfo){ + sInfo->ccdReference = oDescr.ccdMeshReference; + sInfo->ccdSkeleton = skeleton; + } + + //---------------------------------------------------------------- + // + // update actors ccd motion threshold + // + if(getActor()) + getActor()->setCCDMotionThreshold(oDescr.ccdMotionThresold); + + + //NX_SF_DYNAMIC_DYNAMIC_CCD + + + //---------------------------------------------------------------- + // + // Check we have CCD enabled at all, if not then produce warning + // + + NxPhysicsSDK *sdk = GetPMan()->getPhysicsSDK(); + if (sdk) + { + float ccdParameter = sdk->getParameter(NX_CONTINUOUS_CD); + if (ccdParameter < 0.5f) + { + errorString.Format("CCD Skeleton for %s created successfully but CCD is not enabled.\n Please goto Variable Manager and set ´Continues Collision Detection´ to 1.0f",GetVT3DObject()); + xLogger::xLog(ELOGWARNING,E_LI_MANAGER,errorString.Str()); + } + } + } + } +} + +int pRigidBody::handleContactPair(NxContactPair* pair,int shapeIndex) +{ + + handleContactPairWheel(pair,shapeIndex); + + return 0; +} + + +int pRigidBody::handleContactPairWheel(NxContactPair* pair,int shapeIndex) +{ + if (!hasWheels()) + return 0; + + NxContactStreamIterator i(pair->stream); + + while(i.goNextPair()) + { + NxShape * s = i.getShape(shapeIndex); + + while(i.goNextPatch()) + { + const NxVec3& contactNormal = i.getPatchNormal(); + + while(i.goNextPoint()) + { + + const NxVec3& contactPoint = i.getPoint(); + + //assuming front wheel drive we need to apply a force at the wheels. + if (s->is(NX_SHAPE_CAPSULE) && s->userData != NULL) + { + //assuming only the wheels of the car are capsules, otherwise we need more checks. + //this branch can't be pulled out of loops because we have to do a full iteration through the stream + + NxQuat local2global = s->getActor().getGlobalOrientationQuat(); + + pSubMeshInfo *sInfo = static_cast(s->userData); + if (!sInfo)return 0; + + pWheel1* wheel = dynamic_cast(sInfo->wheel); + if (!wheel)return 0; + + + /* + if (!wheel->getWheelFlag(WF_UseWheelShape)) + { + wheel->contactInfo->otherActor = pair->actors[1-shapeIndex]; + wheel->contactInfo->contactPosition = contactPoint; + + wheel->contactInfo->contactPositionLocal = contactPoint; + wheel->contactInfo->contactPositionLocal -= wheel->getActor()->getGlobalPosition(); + local2global.inverseRotate(wheel->contactInfo->contactPositionLocal); + + wheel->contactInfo->contactNormal = contactNormal; + + if (wheel->contactInfo->otherActor->isDynamic()) + { + NxVec3 globalV = s->getActor().getLocalPointVelocity( getFrom(wheel->getWheelPos()) ); + globalV -= wheel->contactInfo->otherActor->getLinearVelocity(); + local2global.inverseRotate(globalV); + wheel->contactInfo->relativeVelocity = globalV.x; + //printf("%2.3f (%2.3f %2.3f %2.3f)\n", wheel->contactInfo.relativeVelocity, + // globalV.x, globalV.y, globalV.z); + } + else + { + NxVec3 vel = s->getActor().getLocalPointVelocity( getFrom(wheel->getWheelPos())); + local2global.inverseRotate(vel); + wheel->contactInfo->relativeVelocity = vel.x; + wheel->contactInfo->relativeVelocitySide = vel.z; + } + + //NX_ASSERT(wheel->hasGroundContact()); + //printf(" Wheel %x is touching\n", wheel); + } + */ + } + } + } + } + //printf("----\n"); + + return 0; +} \ No newline at end of file diff --git a/usr/Src/Core/pRigidBody/pRigidBodyMisc.cpp b/usr/Src/Core/pRigidBody/pRigidBodyMisc.cpp new file mode 100644 index 0000000..74481d7 --- /dev/null +++ b/usr/Src/Core/pRigidBody/pRigidBodyMisc.cpp @@ -0,0 +1,763 @@ +#include +#include "vtPhysXAll.h" +#include + +void pRigidBody::updateMaterialSettings(pMaterial& material,CK3dEntity*shapeReference/* =NULL */) +{ + + if (shapeReference==NULL) + assert (getMainShape()); + + NxShape *shape = getSubShape(shapeReference); + if (shape) + { + + pMaterial &bMaterial = material; + if (bMaterial.xmlLinkID !=0) + { + int bIndex = bMaterial.xmlLinkID; + XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,bMaterial.xmlLinkID); + bool err = pFactory::Instance()->loadFrom(bMaterial,nodeName.Str(), pFactory::Instance()->getDefaultDocument() ); + } + iAssertW( bMaterial.isValid(),pFactory::Instance()->findSettings(bMaterial,shapeReference), + "Material settings invalid, try to find material attributes"); + + iAssertW( bMaterial.isValid(),bMaterial.setToDefault(), + "Material settings were still invalid : "); + + NxMaterialDesc nxMatDescr; + pFactory::Instance()->copyTo(nxMatDescr,bMaterial); + NxMaterial *nxMaterial = getWorld()->getScene()->createMaterial(nxMatDescr); + if (nxMaterial) + { + shape->setMaterial(nxMaterial->getMaterialIndex()); + nxMaterial->userData = (void*)bMaterial.xmlLinkID; + + } + } +} + +void pRigidBody::updatePivotSettings(pPivotSettings pivot,CK3dEntity*shapeReference/* =NULL */) +{ + + if (shapeReference==NULL) + assert (getMainShape()); + + NxShape *shape = getSubShape(shapeReference); + if (shape) + { + + // Referential + CK3dEntity* pivotRef = (CK3dEntity*)GetPMan()->GetContext()->GetObject(pivot.pivotReference); + + VxVector pivotLocalOut = pivot.localPosition; + //---------------------------------------------------------------- + // + // position + // + if (pivotRef) + { + pivotRef->Transform(&pivotLocalOut,&pivotLocalOut); + shape->setGlobalPosition(getFrom(pivotLocalOut)); + }else + { + shape->setLocalPosition(getFrom(pivotLocalOut)); + } + //---------------------------------------------------------------- + // + // rotational offset : todo + // + VxMatrix mat; + Vx3DMatrixFromEulerAngles(mat,pivot.localOrientation.x,pivot.localOrientation.y,pivot.localOrientation.z); + + VxQuaternion outQuat; + outQuat.FromMatrix(mat); + VxQuaternion referenceQuat=outQuat; + if (pivotRef) + { + pivotRef->GetQuaternion(&referenceQuat,NULL); + shape->setLocalOrientation(getFrom(referenceQuat)); + }else{ + + shape->setLocalOrientation(getFrom(outQuat)); + } + } +} + +void pRigidBody::saveToAttributes(pObjectDescr* oDescr) +{ + if (!oDescr) + return; + + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + int attTypeActor = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + int attTypeMaterial = GetPMan()->getAttributeTypeByGuid(VTS_MATERIAL); + int attTypeOptimization = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); + int attTypeCCD = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CCD_SETTINGS); + int attTypeMass = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); + + //---------------------------------------------------------------- + // + // disable attribute callback + // + CKAttributeManager *aMan = GetPMan()->GetContext()->GetAttributeManager(); + if (aMan) + { + //aMan->SetAttributeCallbackFunction(attTypeActor) + } + + CK3dEntity *referenceObject = GetVT3DObject(); + + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attTypeActor)) + { + referenceObject->RemoveAttribute(attTypeActor); + } + referenceObject->SetAttribute(attTypeActor); + + CKParameterOut* actorAttribute = referenceObject->GetAttributeParameter(attTypeActor); + + //---------------------------------------------------------------- + // + // Common Settings + // + CKParameterOut *parBCommon = GetParameterFromStruct(actorAttribute,PS_COMMON_SETTINGS); + if (parBCommon) + { + SetParameterStructureValue(parBCommon,PS_BC_HULL_TYPE,oDescr->hullType); + SetParameterStructureValue(parBCommon,PS_BC_FLAGS,oDescr->flags); + SetParameterStructureValue(parBCommon,PS_BC_DENSITY,oDescr->density); + SetParameterStructureValue(parBCommon,PS_BC_WORLD,oDescr->worlReference); + } + + //---------------------------------------------------------------- + // + // Collision Setting + // + CKParameterOut *parBCollision = GetParameterFromStruct(actorAttribute,PS_COLLISION_SETTINGS); + CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); + if (parBCollision) + { + SetParameterStructureValue(parBCollision,PS_BC_GROUP,oDescr->collisionGroup); + SetParameterStructureValue(parBCollision,PS_BC_SKINWITDH,oDescr->skinWidth); + + if (parGroupsMask) + { + SetParameterStructureValue(parGroupsMask,0,oDescr->groupsMask.bits0); + SetParameterStructureValue(parGroupsMask,1,oDescr->groupsMask.bits1); + SetParameterStructureValue(parGroupsMask,2,oDescr->groupsMask.bits2); + SetParameterStructureValue(parGroupsMask,3,oDescr->groupsMask.bits3); + } + } + + //---------------------------------------------------------------- + // + // Optimization + // + if (oDescr->mask & OD_Optimization) + { + if (referenceObject->HasAttribute(attTypeOptimization)) + { + referenceObject->RemoveAttribute(attTypeOptimization); + } + + referenceObject->SetAttribute(attTypeOptimization); + + + CKParameterOut *parBOptimization = referenceObject->GetAttributeParameter(attTypeOptimization); + if (parBOptimization) + { + SetParameterStructureValue(parBOptimization,PS_BO_LOCKS,oDescr->optimization.transformationFlags); + SetParameterStructureValue(parBOptimization,PS_BO_SOLVER_ITERATIONS,oDescr->optimization.solverIterations); + SetParameterStructureValue(parBOptimization,PS_BO_DOMINANCE_GROUP,oDescr->optimization.dominanceGroup); + SetParameterStructureValue(parBOptimization,PS_BO_COMPARTMENT_ID,oDescr->optimization.compartmentGroup); + } + + //---------------------------------------------------------------- + // + // sleeping + // + CKParameterOut *parBSleeping = GetParameterFromStruct(parBOptimization,PS_BO_SLEEPING); + if (parBSleeping) + { + SetParameterStructureValue(parBSleeping,PS_BS_ANGULAR_SLEEP,oDescr->optimization.angSleepVelocity); + SetParameterStructureValue(parBSleeping,PS_BS_LINEAR_SLEEP,oDescr->optimization.linSleepVelocity); + SetParameterStructureValue(parBSleeping,PS_BS_THRESHOLD,oDescr->optimization.sleepEnergyThreshold); + } + + //---------------------------------------------------------------- + // + // damping + // + CKParameterOut *parBDamping = GetParameterFromStruct(parBOptimization,PS_BO_DAMPING); + if (parBDamping) + { + SetParameterStructureValue(parBDamping,PS_BD_ANGULAR,oDescr->optimization.angDamping); + SetParameterStructureValue(parBDamping,PS_BD_LINEAR,oDescr->optimization.linDamping); + } + } + + //---------------------------------------------------------------- + // + // CCD + // + if (oDescr->mask & OD_CCD ) + { + if (referenceObject->HasAttribute(attTypeCCD)) + { + referenceObject->RemoveAttribute(attTypeCCD); + } + + referenceObject->SetAttribute(attTypeCCD); + + CKParameterOut *parBCCD = referenceObject->GetAttributeParameter(attTypeCCD); + if (parBCCD) + { + SetParameterStructureValue(parBCCD,PS_B_CCD_MOTION_THRESHOLD,oDescr->ccd.motionThresold); + SetParameterStructureValue(parBCCD,PS_B_CCD_FLAGS,oDescr->ccd.flags); + SetParameterStructureValue(parBCCD,PS_B_CCD_SCALE,oDescr->ccd.scale); + SetParameterStructureValue(parBCCD,PS_B_CCD_MESH_REFERENCE,oDescr->ccd.meshReference); + + } + } + //---------------------------------------------------------------- + // + // Material + // + if (oDescr->mask & OD_Material ) + { + if (referenceObject->HasAttribute(attTypeMaterial)) + { + referenceObject->RemoveAttribute(attTypeMaterial); + } + + referenceObject->SetAttribute(attTypeMaterial); + + CKParameterOut *parBMaterial = referenceObject->GetAttributeParameter(attTypeMaterial); + if (parBMaterial) + { + pFactory::Instance()->copyTo(parBMaterial,oDescr->material); + } + } + + + //---------------------------------------------------------------- + // + // Mass + // + /* + if (oDescr->mask & OD_Mass) + { + if (referenceObject->HasAttribute(attTypeMass)) + { + referenceObject->RemoveAttribute(attTypeMass); + } + + referenceObject->SetAttribute(attTypeMass); + + CKParameterOut *parBMass= referenceObject->GetAttributeParameter(attTypeMass); + if (parBMass) + { + pFactory::Instance()->copyTo(parBMass,oDescr->mass); + } + } + */ + } + + + + void pRigidBody::updateOptimizationSettings(pOptimization optimization) +{ + + lockTransformation(optimization.transformationFlags); + if(getFlags() & BF_Moving) + setSolverIterationCount(optimization.solverIterations); + getActor()->setDominanceGroup(optimization.dominanceGroup); + + if(getFlags() & BF_Moving) + setAngularDamping(optimization.angDamping); + if(getFlags() & BF_Moving) + setLinearDamping(optimization.linDamping); + if(getFlags() & BF_Moving) + setSleepAngularVelocity(optimization.angSleepVelocity); + if(getFlags() & BF_Moving) + setSleepLinearVelocity(optimization.linSleepVelocity); + if(getFlags() & BF_Moving) + setSleepEnergyThreshold(optimization.sleepEnergyThreshold); +} +void pRigidBody::setSleepAngularVelocity(float threshold) +{ + getActor()->setSleepAngularVelocity(threshold); + +} +void pRigidBody::setSleepLinearVelocity(float threshold) +{ + getActor()->setSleepLinearVelocity(threshold); +} +void pRigidBody::setSleepEnergyThreshold(float threshold) +{ + getActor()->setSleepEnergyThreshold(threshold); +} + +void pRigidBody::setDominanceGroup(int dominanceGroup) +{ + getActor()->setDominanceGroup(dominanceGroup); +} + +void pRigidBody::setSolverIterationCount(int count) +{ + + + + if (getActor()) + { + if (count > 0) + { + getActor()->setSolverIterationCount(count); + } + } +} + +void pRigidBody::checkForOptimization() +{ + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); + CK3dEntity *ent = (CK3dEntity*)ctx()->GetObject(mEntID); + if ( !ent ) + return; + + if (!ent->HasAttribute(att)) + return; + + + + CKParameterOut *optPar = ent->GetAttributeParameter(att); + if(!optPar) + return; + + + using namespace vtTools::ParameterTools; + using namespace vtTools::AttributeTools; + + ////////////////////////////////////////////////////////////////////////// + // + // Lock transformation degrees : + // + int transformationlockFlags = GetValueFromAttribute(ent,att,PS_BO_LOCKS); + lockTransformation(transformationlockFlags); + + ////////////////////////////////////////////////////////////////////////// + // + // Damping + // + CKParameterOut * dampPar= GetParameterFromStruct(optPar,PS_BO_DAMPING); + + float linDamp = GetValueFromParameterStruct(dampPar,PS_BD_LINEAR); + float angDamp = GetValueFromParameterStruct(dampPar,PS_BD_ANGULAR); + if ( linDamp !=0.0f) + setLinearDamping(linDamp); + + if ( angDamp!=0.0f) + setAngularDamping(angDamp); + + /////////////////////////////////////////////////////////////////////////// + // + // Sleeping Settings + // + + CKParameterOut * sleepPar= GetParameterFromStruct(optPar,PS_BO_SLEEPING); + float linSleep = GetValueFromParameterStruct(dampPar,PS_BS_LINEAR_SLEEP); + + + ////////////////////////////////////////////////////////////////////////// + // + // Solver Iterations + // + //CKParameterOut * sleepPar= GetParameterFromStruct(optPar,); + int solverIterations = GetValueFromParameterStruct(optPar,PS_BO_SOLVER_ITERATIONS); + if (solverIterations !=0) + { + setSolverIterationCount(solverIterations); + } + + ////////////////////////////////////////////////////////////////////////// + // + // Dominance + // + int dGroup = GetValueFromParameterStruct(optPar,PS_BO_DOMINANCE_GROUP); + if (dGroup!=0) + { + getActor()->setDominanceGroup(dGroup); + } + + + +} +void pRigidBody::checkDataFlags() +{ + + using namespace vtTools::AttributeTools; + int att = GetPMan()->GetPAttribute(); + int att_damping = GetPMan()->att_damping; + int att_ss = GetPMan()->att_sleep_settings; + int att_surface =GetPMan()->att_surface_props; + int att_deformable =GetPMan()->att_deformable; + + xBitSet& dFlags = getDataFlags(); + CK3dEntity *ent = GetVT3DObject(); + + if (!ent) { return; } + + if (ent->HasAttribute(att_surface)) + enableFlag(dFlags,EDF_MATERIAL_PARAMETER); + else disableFlag(dFlags,EDF_MATERIAL_PARAMETER); + + if (ent->HasAttribute(att_damping)) + enableFlag(dFlags,EDF_DAMPING_PARAMETER); + else disableFlag(dFlags,EDF_DAMPING_PARAMETER); + + if (ent->HasAttribute(att_ss)) + enableFlag(dFlags,EDF_SLEEPING_PARAMETER); + else disableFlag(dFlags,EDF_SLEEPING_PARAMETER); + + if (ent->HasAttribute(att_deformable)) + enableFlag(dFlags,EDF_DEFORMABLE_PARAMETER); + else disableFlag(dFlags,EDF_DEFORMABLE_PARAMETER); + + + if (ent->HasAttribute( GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION) )) + enableFlag(dFlags,EDF_OPTIMIZATION_PARAMETER); + else disableFlag(dFlags,EDF_OPTIMIZATION_PARAMETER); + +} +void pRigidBody::destroy() +{ + if(!getActor()) + return; + + NxU32 nbShapes = getActor()->getNbShapes(); + + + for (int i = 0 ; i < getNbJoints() ; i++ ) + { + int p3 = getNbJoints(); + pJoint * p = getJointAtIndex(i); + if (p) + { + NxJoint &j = *p->getJoint(); + getActor()->getScene().releaseJoint(j); + i = 0; + } + } + /* + CKSTRING name = GetVT3DObject()->GetName(); + while(nbShapes ) + { + + NxShape *s = ((NxShape **)getActor()->getShapes())[0]; + pSubMeshInfo *sinfo = static_cast(s->userData); + + ////////////////////////////////////////////////////////////////////////// + // Wheel attached ! + if (sinfo && s->isWheel() && sinfo->wheel ) + { + pWheel2 *wheel = (pWheel2*)sinfo->wheel; + delete wheel; + wheel = NULL; + sinfo->wheel =NULL; + } + + if (sinfo) + { + delete sinfo; + sinfo = NULL; + } + + s->userData = NULL; + + if (getActor()->isDynamic() || ( !getActor()->isDynamic() && nbShapes >1 ) ) + { + getActor()->releaseShape(*s); + s=NULL; + destroy(); + }break; + } + + */ + + + /************************************************************************/ + /* */ + /************************************************************************/ + pVehicle *v = getVehicle(); + if ( v ) + { + getVehicle()->getWheels().clear(); + getVehicle()->setActor(NULL); + getVehicle()->setBody(NULL); + + delete v; + setVehicle(NULL); + } + + pCloth *cloth = getCloth(); + if (cloth) + { + cloth->releaseReceiveBuffers(); + getActor()->getScene().releaseCloth(*cloth->getCloth()); + } + getActor()->userData = NULL; + getActor()->getScene().releaseActor(*getActor()); + setActor(NULL); +} + +int pRigidBody::getTransformationsLockFlags() +{ + + int result = 0 ; + if (getActor()->readBodyFlag(NX_BF_FROZEN_POS_X))result|=NX_BF_FROZEN_POS_X; + if (getActor()->readBodyFlag(NX_BF_FROZEN_POS_Y))result|=NX_BF_FROZEN_POS_Y; + if (getActor()->readBodyFlag(NX_BF_FROZEN_POS_Z))result|=NX_BF_FROZEN_POS_Z; + + if (getActor()->readBodyFlag(NX_BF_FROZEN_ROT_X))result|=NX_BF_FROZEN_ROT_X; + if (getActor()->readBodyFlag(NX_BF_FROZEN_ROT_Y))result|=NX_BF_FROZEN_ROT_Y; + if (getActor()->readBodyFlag(NX_BF_FROZEN_ROT_Z))result|=NX_BF_FROZEN_ROT_Z; + + return result; + +} +void pRigidBody::lockTransformation(int flags) +{ + + + if (getActor() && getActor()->isDynamic()) + { + if (flags & NX_BF_FROZEN_POS_X) + getActor()->raiseBodyFlag(NX_BF_FROZEN_POS_X); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_POS_X); + + + if (flags & NX_BF_FROZEN_POS_Y) + getActor()->raiseBodyFlag(NX_BF_FROZEN_POS_Y); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_POS_Y); + + if (flags & NX_BF_FROZEN_POS_Z) + getActor()->raiseBodyFlag(NX_BF_FROZEN_POS_Z); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_POS_Z); + + + if (flags & NX_BF_FROZEN_ROT_X) + getActor()->raiseBodyFlag(NX_BF_FROZEN_ROT_X); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_ROT_X); + + if (flags & NX_BF_FROZEN_ROT_Y) + getActor()->raiseBodyFlag(NX_BF_FROZEN_ROT_Y); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_ROT_Y); + + if (flags & NX_BF_FROZEN_ROT_Z) + getActor()->raiseBodyFlag(NX_BF_FROZEN_ROT_Z); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_ROT_Z); + } +} +bool pRigidBody::isSleeping()const +{ + if (getActor()) + { + return getActor()->isSleeping(); + } + return true; +} + +void pRigidBody::setSleeping(bool sleeping) +{ + + if (getActor() && (getFlags() & BF_Moving) ) + { + if (sleeping) + { + getActor()->putToSleep(); + }else{ + getActor()->wakeUp(); + } + } +} +void pRigidBody::enableGravity(bool enable) +{ + + if (getActor() && (getFlags() & BF_Moving)) + { + if (!enable) + { + getActor()->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); + }else{ + getActor()->clearBodyFlag(NX_BF_DISABLE_GRAVITY); + } + } +} + +bool pRigidBody::isAffectedByGravity()const +{ + if (getActor()) + { + return !getActor()->readBodyFlag(NX_BF_DISABLE_GRAVITY); + } + return false; +} +void pRigidBody::setKinematic(bool enabled) +{ + if (getActor()) + { + if (enabled) + getActor()->raiseBodyFlag(NX_BF_KINEMATIC); + else + getActor()->clearBodyFlag(NX_BF_KINEMATIC); + } +} +bool pRigidBody::isKinematic()const +{ + if (getActor()) + { + return getActor()->readBodyFlag(NX_BF_KINEMATIC); + } + return false; +} + +bool pRigidBody::isValid()const { + + return GetPMan()->GetContext()->GetObject(getEntID()) ? true : false && getActor() ? true : false; +} +int pRigidBody::getHullType(){ return m_HullType;} +void pRigidBody::setHullType(int _type){ m_HullType= _type;} +void pRigidBody::recalculateFlags(int _flags) +{ + if (!isValid()) + { + return; + } + + int current = m_sFlags; + + if (getActor()->isDynamic() && !getActor()->readBodyFlag(NX_BF_DISABLE_GRAVITY)) + { + current |=BF_Gravity; + } + + + if (!getActor()->readActorFlag(NX_AF_DISABLE_COLLISION)) + { + current |=BF_Collision; + } + + if (getActor()->isSleeping()) + { + current |=BF_Sleep; + } + + if (getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) + { + current |=BF_CollisionNotify; + } + + if (isKinematic()) + { + current |=BF_Kinematic; + } + if ( getMainShape()->getFlag(NX_SF_POINT_CONTACT_FORCE) ) + { + current |=BF_CollisionsForce; + } + + if ( getActor()->readActorFlag(NX_AF_CONTACT_MODIFICATION) ) + { + current |=BF_ContactModify; + } + m_sFlags = current; +} + +void pRigidBody::updateFlags( int _flags,CK3dEntity*shapeReference/*=NULL*/ ) +{ + + if (!isValid())return; + + //NX_SF_POINT_CONTACT_FORCE + if((getFlags() & BF_Moving)) + setKinematic(_flags & BF_Kinematic); + enableCollision(_flags & BF_Collision,shapeReference); + enableCollisionsNotify(_flags & BF_CollisionNotify); + enableCollisionForceCalculation( _flags & BF_CollisionsForce ); + if((getFlags() & BF_Moving)) + enableGravity(_flags & BF_Gravity); + if((getFlags() & BF_Moving)) + setSleeping(_flags & BF_Sleep); + + enableTriggerShape(_flags & BF_TriggerShape,shapeReference); + enableContactModification(_flags & BF_ContactModify); + m_sFlags |=_flags; + +} + +int pRigidBody::getFlags() +{ + return m_sFlags;; +} +void pRigidBody::setFlags(int _flags){ m_sFlags = _flags;} +void pRigidBody::retrieveSettingsFromAttribute() +{ + + assert(getWorld()); + assert(getWorld()->getScene()); + assert(getWorld()->getReference()); + assert(GetVT3DObject()); + + using namespace vtTools::AttributeTools; + setDataFlags(0x000); + + int att = GetPMan()->GetPAttribute(); + + //---------------------------------------------------------------- + // + // Old version + // + + CK_ID id = getWorld()->getReference()->GetID(); + SetAttributeValue(GetVT3DObject(),att,E_PPS_WORLD,&id); + setHullType(GetValueFromAttribute(GetVT3DObject(),att,E_PPS_HULLTYPE)); + + + //Sets some flags like movable , etc... + setFlags(GetValueFromAttribute(GetVT3DObject(),att,E_PPS_BODY_FLAGS)); + setDensity(GetValueFromAttribute(GetVT3DObject(),att, E_PPS_DENSITY)); + setMassOffset(GetValueFromAttribute(GetVT3DObject(),att, E_PPS_MASS_OFFSET)); + setPivotOffset(GetValueFromAttribute(GetVT3DObject(),att, E_PPS_SHAPE_OFFSET)); + setSkinWidth(GetValueFromAttribute(GetVT3DObject(),att, E_PPS_SKIN_WIDTH)); + + + +} +int pRigidBody::isBodyFlagOn(int flags) +{ + if (getActor() && getActor()->isDynamic()) + { + return getActor()->readBodyFlag((NxBodyFlag)flags); + } + return -1; +} +void pRigidBody::wakeUp(float wakeCounterValue/* =NX_SLEEP_INTERVAL */) +{ + getActor()->wakeUp(wakeCounterValue); + +} + + + diff --git a/usr/Src/Core/pRigidBody/pRigidBodyRun.cpp b/usr/Src/Core/pRigidBody/pRigidBodyRun.cpp new file mode 100644 index 0000000..2fd9744 --- /dev/null +++ b/usr/Src/Core/pRigidBody/pRigidBodyRun.cpp @@ -0,0 +1,747 @@ +#include +#include "vtPhysXAll.h" +#include +#include "pCallbackObject.h" +#include "pCallbackSignature.h" +#include + +#include "virtools/vtTools.h" +#include "vtInterfaceEnumeration.h" +#include "vtAttributeHelper.h" + +static float incrTimer = 0.0f; + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; +using namespace vtTools::BehaviorTools; + +int getJointType(int attributeIndex) +{ + switch(attributeIndex) + { + case 1: + return JT_Distance; + case 2: + return JT_Fixed; + case 3: + return JT_Spherical; + case 4: + return JT_Prismatic; + case 5: + return JT_PointInPlane; + case 6: + return JT_PointOnLine; + case 7: + return JT_Cylindrical; + case 8: + return JT_Revolute; + case 9: + return JT_D6; + default: + return -1; + } + + return -1; + +} + +void pRigidBody::onICRestore(CK3dEntity* parent,pRigidBodyRestoreInfo *restoreInfo) +{ + + + if (!parent) + return; + + CKScene *level_scene = GetPMan()->GetContext()->GetCurrentLevel()->GetLevelScene(); + if(level_scene) + { + if(level_scene) + { + CKStateChunk *chunk = level_scene->GetObjectInitialValue(parent); + if (chunk) + { + CKReadObjectState(parent,chunk); + } + } + } + + + VxVector pos(0,0,0); + VxVector scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(parent->GetWorldMatrix(),quat,pos,scale); + + + VxVector vectorN(0,0,0); + setLinearMomentum(vectorN); + setAngularMomentum(vectorN); + setLinearVelocity(vectorN); + setAngularVelocity(vectorN); + parent->GetPosition(&pos); + + setPosition(pos); + setRotation(quat); + + if (level_scene && restoreInfo->hierarchy) + { + + CK3dEntity* subEntity = NULL; + XArraySrcObjects; + while (subEntity= parent->HierarchyParser(subEntity) ) + { + CKStateChunk *chunk = level_scene->GetObjectInitialValue(subEntity); + if (chunk) + { + CKReadObjectState(subEntity,chunk); + } + } + } + + onSubShapeTransformation(false,true,true,parent,restoreInfo->hierarchy); + + bool hadJoints = false; + + if (restoreInfo->removeJoints) + { + CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); + int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;//(sizeof(*getRegistrationTable()) / sizeof((getRegistrationTable())[0])); + for (int fIndex = 1 ; fIndex < sizeJFuncMap ; fIndex ++) + { + std::vectorattributeIdList; + pFactory::Instance()->findAttributeIdentifiersByGuid(GetPMan()->getRegistrationTable()[fIndex].guid,attributeIdList); + int attCount = attributeIdList.size(); + for (int i = 0 ; i < attCount ; i++ ) + { + int currentAttType = attributeIdList.at(i); + const XObjectPointerArray& Array = attman->GetAttributeListPtr( attributeIdList.at(i) ); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + CK3dEntity *target = static_cast(*it); + if (target == parent && fIndex != -1 ) + { + using namespace vtTools::ParameterTools; + CKParameterOut *attributeParameter = target->GetAttributeParameter(currentAttType); + if (attributeParameter) + { + CKStructHelper sHelper(target->GetAttributeParameter(currentAttType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + continue; + + // get body b : + CK_ID bodyBId = GetValueFromParameterStruct(attributeParameter,0); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + + pJoint *joint = getJoint(bodyBEnt,(JType)getJointType(fIndex)); + if (joint) + { + XString error; + XString bodyBName; + if (joint->GetVTEntB()) + { + bodyBName.Format(" %s ",joint->GetVTEntB()->GetName()); + } + error.Format("Deleting joint by attribute from : %s with attribute %s connected to :%s",target->GetName(),attman->GetAttributeNameByType(currentAttType),bodyBName.Str()); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.CStr() ); + deleteJoint(bodyBEnt, (JType)getJointType(fIndex)); + hadJoints = true; + int b = getNbJoints(); + b++; + } + } + /* + XString error; + error.Format("Deleting joint by attribute from : %s with %s",target->GetName(),attman->GetAttributeNameByType(currentAttType)); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.CStr() );*/ + } + } + } + } + } + + if(hadJoints) + GetPMan()->getCheckList().PushBack(getEntID()); + + //GetPMan()->checkPhysics = true; + + ////////////////////////////////////////////////////////////////////////// + // check for constraint attributes + //GetPMan()->_checkObjectsByAttribute(); +} + +bool pRigidBody::onMove(bool position/* =true */,bool rotation/* =true */,VxVector pos,VxQuaternion quad) +{ + + /************************************************************************/ + /* + + determine whether the specified "children" object have sub shapes ! + - recursive call of updateSubShape + + + exit if any object has been updated + + */ + /************************************************************************/ + + + //pSubMeshInfo *info = static_cast(subShape->userData); + + + CK3dEntity* subEntity = NULL; + XArraySrcObjects; + //SrcObjects.PushBack( subShape ); + + + CK_ID id = getEntID(); + CK3dEntity * thisEnt = (CK3dEntity*)GetPMan()->GetContext()->GetObject(id); + if(thisEnt) + return false; + while (subEntity= thisEnt->HierarchyParser(subEntity)) + { + + CKSTRING name =subEntity->GetName(); +/* NxShape *childShape = getSubShape(subEntity); + if (childShape) + {s + pSubMeshInfo *childInfo = static_cast(childShape->userData); + if (childInfo) + { + CK3dEntity *child = (CK3dEntity*)ctx()->GetObject(childInfo->entID); + if ( child && isSubShape(child) && childInfo->initDescription.flags & BF_SubShape ) + { + //SrcObjects.PushBack(child);// + + } + } + } +*/ + + // body ? + pRigidBody *body = GetPMan()->getBody(subEntity); + if (body && body!=this ) + { + body->updateSubShapes(); + } + } + + /* + for(int i = 0;i(*SrcObjects.At(i))); + if (s) + { + pSubMeshInfo *childInfo = static_cast(s->userData); + CK3dEntity *ent = (CK3dEntity*)ctx()->GetObject(childInfo->entID); + if (!ent) + continue; + + if (position) + { + + VxVector relPos; + ent->GetPosition(&relPos,GetVT3DObject()); + s->setLocalPosition(getFrom(relPos)); + + //onSubShapeTransformation(fromPhysicToVirtools,position,false,childObject); + + } + + if (rotation) + { + /* + VxQuaternion refQuad2; + ent->GetQuaternion(&refQuad2,GetVT3DObject()); + s->setLocalOrientation(getFrom(refQuad2)); + + //onSubShapeTransformation(fromPhysicToVirtools,false,rotation,childObject); + + } + } + } + + */ + return true; +} +bool pRigidBody::onSubShapeTransformation(bool fromPhysicToVirtools/* =true */,bool position/* =true */,bool rotation/* =true */,CK3dEntity*parent,bool children/* =true */) +{ + + /************************************************************************/ + /* + + determine whether the specified "children" object have sub shapes ! + - recursive call of updateSubShape + + + exit if any object has been updated + + */ + /************************************************************************/ + + if ( !parent ) + return false; + + NxShape *subShape = getSubShape(parent); + if (!subShape) + return false; + + int count = parent->GetChildrenCount(); + + if (subShape == getMainShape()) + return false; + + pSubMeshInfo *info = static_cast(subShape->userData); + CK3dEntity* subEntity = NULL; + + XArraySrcObjects; + SrcObjects.PushBack( subShape ); + + while (subEntity= parent->HierarchyParser(subEntity) ) + { + + CKSTRING name =subEntity->GetName(); + NxShape *childShape = getSubShape(subEntity); + if (childShape) + { + pSubMeshInfo *childInfo = static_cast(childShape->userData); + if (childInfo) + { + CK3dEntity *child = (CK3dEntity*)ctx()->GetObject(childInfo->entID); + if ( child && isSubShape(child) && childInfo->initDescription.flags & BF_SubShape ) + { + SrcObjects.PushBack( childShape ); + } + } + } + } + + for(int i = 0;i(*SrcObjects.At(i))); + if (s) + { + pSubMeshInfo *childInfo = static_cast(s->userData); + CK3dEntity *ent = (CK3dEntity*)ctx()->GetObject(childInfo->entID); + if (!ent) + continue; + + if (position) + { + + VxVector relPos; + ent->GetPosition(&relPos,GetVT3DObject()); + s->setLocalPosition(getFrom(relPos)); + //onSubShapeTransformation(fromPhysicToVirtools,position,false,childObject); + + } + + if (rotation) + { + VxQuaternion refQuad2; + ent->GetQuaternion(&refQuad2,GetVT3DObject()); + s->setLocalOrientation(getFrom(refQuad2)); + //onSubShapeTransformation(fromPhysicToVirtools,false,rotation,childObject); + + } + } + } + + return true; +} +bool pRigidBody::onRayCastHit(NxRaycastHit *report) +{ + + return true; +} +void pRigidBody::setRayCastScript(int val) +{ + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(val); + if (!beh) + return; + + XString errMessage; + if (!GetPMan()->checkCallbackSignature(beh,CB_OnRayCastHit,errMessage)) + { + xError(errMessage.Str()); + return; + } + pCallbackObject::setRayCastScript(val); +} +bool pRigidBody::onContactConstraint(int& changeFlags,CK3dEntity *sourceObject,CK3dEntity *otherObject,pContactModifyData *data) +{ + + bool result = true; + //---------------------------------------------------------------- + // + // sanity checks + // + if (sourceObject != GetVT3DObject()) + return true; + + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getContactModificationScript()); + if (!beh) + return true; + + if (!data) + return true; + + //---------------------------------------------------------------- + // + // store data in behaviors inputs + // + + if (sourceObject) + SetInputParameterValue(beh,bbICM_SrcObject,sourceObject->GetID()); + if (otherObject) + SetInputParameterValue(beh,bbICM_OtherObject,otherObject->GetID()); + + SetInputParameterValue(beh,bbICM_MinImpulse,data->minImpulse); + SetInputParameterValue(beh,bbICM_MaxImpulse,data->maxImpulse); + + SetInputParameterValue(beh,bbICM_Error,data->error); + SetInputParameterValue(beh,bbICM_Target,data->target); + + SetInputParameterValue(beh,bbICM_LP0,data->localpos0); + SetInputParameterValue(beh,bbICM_LP1,data->localpos1); + + SetInputParameterValue(beh,bbICM_LO0,data->localorientation0); + SetInputParameterValue(beh,bbICM_LO1,data->localorientation1); + + SetInputParameterValue(beh,bbICM_SF0,data->staticFriction0); + SetInputParameterValue(beh,bbICM_SF1,data->staticFriction1); + + SetInputParameterValue(beh,bbICM_DF0,data->dynamicFriction0); + SetInputParameterValue(beh,bbICM_DF1,data->dynamicFriction1); + + SetInputParameterValue(beh,bbICM_Restitution,data->restitution); + + //---------------------------------------------------------------- + // + // execute: + // + beh->Execute(lastStepTimeMS); + + //---------------------------------------------------------------- + // + // refuse contact + // + result = GetOutputParameterValue(beh,bbOCM_CreateContact); + if (!result) + return false; + + //---------------------------------------------------------------- + // + // nothing changed, return true + // + changeFlags = GetOutputParameterValue(beh,bbOCM_ModifyFlags); + if (changeFlags == CMM_None ) + { + return true; + } + + //---------------------------------------------------------------- + // + // pickup data, according to change flags + // + if (changeFlags & CMM_MinImpulse ) + data->minImpulse = GetOutputParameterValue(beh,bbOCM_MinImpulse); + + if (changeFlags & CMM_MaxImpulse) + data->maxImpulse = GetOutputParameterValue(beh,bbOCM_MaxImpulse); + + if (changeFlags & CMM_Error ) + data->error = GetOutputParameterValue(beh,bbOCM_Error); + + if (changeFlags & CMM_Target ) + data->target = GetOutputParameterValue(beh,bbOCM_Target); + + + if (changeFlags & CMM_StaticFriction0) + data->staticFriction0 = GetOutputParameterValue(beh,bbOCM_SF0); + if (changeFlags & CMM_StaticFriction1) + data->staticFriction1 = GetOutputParameterValue(beh,bbOCM_SF1); + + if (changeFlags & CMM_DynamicFriction0) + data->dynamicFriction0 = GetOutputParameterValue(beh,bbOCM_DF0); + if (changeFlags & CMM_DynamicFriction1) + data->dynamicFriction1 = GetOutputParameterValue(beh,bbOCM_DF1); + + if (changeFlags & CMM_LocalPosition0) + data->localpos0 = GetOutputParameterValue(beh,bbOCM_LP0); + if (changeFlags & CMM_LocalPosition1) + data->localpos1 = GetOutputParameterValue(beh,bbOCM_LP1); + + if (changeFlags & CMM_LocalOrientation0) + data->localorientation0 = GetOutputParameterValue(beh,bbOCM_LO0); + if (changeFlags & CMM_LocalOrientation1) + data->localorientation1 = GetOutputParameterValue(beh,bbOCM_LO1); + + if (changeFlags & CMM_Restitution) + data->restitution = GetOutputParameterValue(beh,bbOCM_Restitution); + + return true; +} + +void pRigidBody::setContactModificationScript(int behaviorID) +{ + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(behaviorID); + if (!beh) + return; + + XString errMessage; + if (!GetPMan()->checkCallbackSignature(beh,CB_OnContactModify,errMessage)) + { + xError(errMessage.Str()); + return; + } + + pCallbackObject::setContactModificationScript(behaviorID); + enableContactModification(true); + + +} + +void pRigidBody::setJointBreakScript(int behaviorID,CK3dEntity *shapeReference) +{ + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(behaviorID); + if (!beh) + return; + + XString errMessage; + if (!GetPMan()->checkCallbackSignature(beh,CB_OnJointBreak,errMessage)) + { + xError(errMessage.Str()); + return; + } + + pCallbackObject::setJointBreakScript(behaviorID); + +} + + +void pRigidBody::setTriggerScript(int behaviorID,int eventMask,CK3dEntity *shapeReference) +{ + /*if (descr.flags & BF_TriggerShape ) + { + result->setFlag(NX_TRIGGER_ENABLE,TRUE); + } + */ + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(behaviorID); + if (!beh) + return; + + XString errMessage; + if (!GetPMan()->checkCallbackSignature(beh,CB_OnTrigger,errMessage)) + { + xError(errMessage.Str()); + return; + } + + NxShape * shape = getSubShape(shapeReference); + //---------------------------------------------------------------- + // + // check mask + // + pTriggerFlags tFlags = (pTriggerFlags)eventMask; + + if ( (eventMask & TF_OnEnter) || + (eventMask & TF_OnStay) || + (eventMask & TF_OnLeave) + ) + { + shape->setFlag(NX_TRIGGER_ON_ENTER,eventMask & TF_OnEnter); + shape->setFlag(NX_TRIGGER_ON_STAY,eventMask & TF_OnStay); + shape->setFlag(NX_TRIGGER_ON_LEAVE,eventMask & TF_OnLeave); + pCallbackObject::setTriggerScript(behaviorID,eventMask); + }else + { + shape->setFlag(NX_TRIGGER_ENABLE,false); + pCallbackObject::setTriggerScript(-1,0); + } +} +int pRigidBody::onTrigger(pTriggerEntry *report) +{ + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getTriggerScript()); + if (!beh) + return -1; + + if (!report) + return -1; + + if (getTriggerEventMask() & report->triggerEvent ) + { + if (report->triggerBody) + SetInputParameterValue(beh,bbIT_SrcObject,report->triggerBody->GetID()); + + if (report->otherObject) + SetInputParameterValue(beh,bbIT_OtherObject,report->otherObject->GetID()); + + SetInputParameterValue(beh,bbIT_EventType,report->triggerEvent); + report->triggered = true; + beh->ActivateInput(0,TRUE); + beh->Execute(lastStepTimeMS); + + return 1; + + + } + + return -1; +} + +void pRigidBody::setContactScript(int behaviorID,int eventMask) +{ + + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(behaviorID); + if (!beh) + return; + + XString errMessage; + if (!GetPMan()->checkCallbackSignature(beh,CB_OnContactNotify,errMessage)) + { + xError(errMessage.Str()); + return; + } + + pCallbackObject::setContactScript(behaviorID,eventMask); + + if (getActor()) + getActor()->setContactReportFlags(eventMask); + +} + +void pRigidBody::onContactNotify(pCollisionsEntry *collisionData) +{ + + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getContactScript()); + if (!beh) + return; + + if (!collisionData) + return; + + if (getCollisionEventMask() & collisionData->eventType ) + { + + if (collisionData->bodyA != this ) + XSwap(collisionData->bodyA,collisionData->bodyB); + + SetInputParameterValue(beh,bbI_SrcObject,collisionData->bodyA->GetVT3DObject()->GetID()); + SetInputParameterValue(beh,bbI_EventType,collisionData->eventType); + SetInputParameterValue(beh,bbI_NormalForce,collisionData->sumNormalForce); + SetInputParameterValue(beh,bbI_FForce,collisionData->sumFrictionForce); + SetInputParameterValue(beh,bbI_Point,collisionData->point); + SetInputParameterValue(beh,bbI_PointNormalForce,collisionData->pointNormalForce); + SetInputParameterValue(beh,bbI_FaceNormal,collisionData->faceNormal); + SetInputParameterValue(beh,bbI_FaceIndex,collisionData->faceIndex); + SetInputParameterValue(beh,bbI_Distance,collisionData->distance); + + + if (collisionData->bodyB && collisionData->bodyB->GetVT3DObject() ) + { + SetInputParameterValue(beh,bbI_OtherObject,collisionData->bodyB->GetVT3DObject()->GetID()); + } + beh->Execute(lastStepTimeMS); + } +} + + + + +int pRigidBody::onJointBreak(pBrokenJointEntry *entry) +{ + + + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getJointBreakScript()); + if (!beh) + return -1; + + if (!entry) + return -1; + + CK3dEntity *bodyAEnt = static_cast(GetPMan()->GetContext()->GetObject(entry->mAEnt)); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(entry->mBEnt)); + + if (bodyAEnt) + { + SetInputParameterValue(beh,bbJB_SrcObject,entry->mAEnt); + }else + SetInputParameterValue(beh,bbJB_SrcObject,0); + + if(bodyBEnt) + SetInputParameterValue(beh,bbJB_OtherObject,entry->mBEnt); + else + SetInputParameterValue(beh,bbJB_OtherObject,0); + + SetInputParameterValue(beh,bbJB_Force,entry->impulse); + + float elapsedTime = GetPMan()->GetContext()->GetTimeManager()->GetLastDeltaTimeFree(); + beh->Execute(elapsedTime); + +/* XString log = "joint break at : " ; + log+= elapsedTime; + + + if (bodyAEnt) + { + log+=bodyAEnt->GetName(); + } + + if (bodyBEnt) + { + log= log + " : with : " + bodyBEnt->GetName(); + } + + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,log.Str()); +*/ + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"joint break"); + GetPMan()->getJointFeedbackList().RemoveAt( GetPMan()->getJointFeedbackList().GetPosition(entry) ); + return 1; +} + +float pRigidBody::getContactReportThreshold() +{ + if (getActor()) + { + return getActor()->getContactReportThreshold(); + } + return -1.0f; +} + + + +void pRigidBody::setContactReportThreshold(float threshold) +{ + if (getActor()) + { + getActor()->setContactReportThreshold(threshold); + } +} + +void pRigidBody::setContactReportFlags(pContactPairFlags flags) +{ + if (getActor()) + { + getActor()->setContactReportFlags((NxU32)flags); + } +} +int pRigidBody::getContactReportFlags() +{ + if (getActor()) + { + return getActor()->getContactReportFlags(); + } + return -1; + +} + + + +void pRigidBody::processScriptCallbacks() +{ + //---------------------------------------------------------------- + // + // Collision Callbacks + // + + /*if ( !(getCallMask() & CB_OnContactNotify) ) + return; +*/ +} \ No newline at end of file diff --git a/usr/Src/Core/pRigidBody/pRigidBodyShape.cpp b/usr/Src/Core/pRigidBody/pRigidBodyShape.cpp new file mode 100644 index 0000000..a51259c --- /dev/null +++ b/usr/Src/Core/pRigidBody/pRigidBodyShape.cpp @@ -0,0 +1,1656 @@ +#include +#include "vtPhysXAll.h" + +#include "IParameter.h" + +#include +int pRigidBody::addCollider(pObjectDescr objectDescr,CK3dEntity*srcRefEntity) +{ + + int result = 0 ; + + using namespace vtTools::AttributeTools; + + CK3dEntity* child = NULL; + CKMesh *srcMesh = NULL; + + if (!srcRefEntity ||!srcRefEntity->GetCurrentMesh()) + return 0; + bool isChild = vtAgeia::isChildOf(GetVT3DObject(), srcRefEntity); + + objectDescr.subEntID = srcRefEntity->GetID(); + //---------------------------------------------------------------- + // + // essential values + // + VxVector box_s = BoxGetZero(srcRefEntity); + + float radius = 1.0f; + radius = srcRefEntity->GetCurrentMesh()->GetRadius(); + + VxQuaternion refQuad; + srcRefEntity->GetQuaternion(&refQuad,GetVT3DObject()); + VxVector relPos; + srcRefEntity->GetPosition(&relPos,GetVT3DObject()); + + NxQuat rot = pMath::getFrom(refQuad); + + srcMesh = srcRefEntity->GetCurrentMesh(); + + pWheel *wheel =NULL; + NxShape *shape = NULL; + + + if (objectDescr.hullType != HT_Wheel) + { + shape = pFactory::Instance()->createShape(GetVT3DObject(),objectDescr,srcRefEntity,srcMesh,relPos,refQuad); + } + else + { + iAssertW( objectDescr.wheel.isValid(),objectDescr.wheel.setToDefault()); + iAssertW( objectDescr.wheel.radius.isValid(),objectDescr.wheel.radius.evaluate(srcRefEntity)); + shape = pFactory::Instance()->createWheelShape2(GetVT3DObject(),srcRefEntity, objectDescr.wheel ); + } + + if (!shape) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create sub shape!"); + return 0; + } + + pSubMeshInfo *sInfo = new pSubMeshInfo(); + + sInfo->meshID = srcMesh->GetID(); + sInfo->mesh =(CKBeObject*)srcMesh; + + sInfo->entID = srcRefEntity->GetID(); + sInfo->refObject = (CKBeObject*)srcRefEntity; + sInfo->wheel = NULL; + + shape->setName(srcRefEntity->GetName()); + shape->userData = (void*)sInfo; + sInfo->initDescription = objectDescr; + + getActor()->wakeUp(); + + + if ( (!objectDescr.flags &BF_Hierarchy) ) + { + return result; + } + /* + + //################################################################ + // + // If more entities in hierarchy, invoke this function recursively + // + CK3dEntity* subEntity = NULL; + while (subEntity= srcRefEntity->HierarchyParser(subEntity) ) + { + + pObjectDescr *subDescr = NULL; + + //-try old version : + if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) + { + subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + + //-try new version + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + if (subEntity->HasAttribute(attTypePBSetup)) + { + subDescr = new pObjectDescr(); + CKParameterOut *par = subEntity->GetAttributeParameter(attTypePBSetup); + IParameter::Instance()->copyTo(subDescr,par); + subDescr->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + + } + + if (!subDescr) + continue; + + if (subDescr->flags & BF_SubShape) + { + + ////////////////////////////////////////////////////////////////////////// + if (subDescr->hullType != HT_Cloth) + { + addSubShape(NULL,*subDescr,subEntity); + } + + if (subDescr->hullType == HT_Cloth) + { + + } + } + } + */ + return 1; +} + + + + +int pRigidBody::addSubShape( CKMesh *mesh,pObjectDescr& objectDescr,CK3dEntity*srcRefEntity,VxVector localPosition,VxQuaternion localRotation) +{ + + + int result = 0 ; + + int att = GetPMan()->GetPAttribute(); + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + bool isNewType = ( objectDescr.version == pObjectDescr::E_OD_VERSION::OD_DECR_V1) ? true : false ; + + + using namespace vtTools::AttributeTools; + + + + CK3dEntity* child = NULL; + bool isChild = false; + while (child = GetVT3DObject()->HierarchyParser(child) ) + { + if (child == srcRefEntity ) + { + isChild = true; + } + } + + /************************************************************************/ + /* parameters for final composition : */ + /************************************************************************/ + CKMesh *srcMesh = NULL; + float density = 0.0f; + VxVector mOffset; + VxVector sOffset; + float skinWidth; + int hType = 0; + + + if (!mesh && !srcRefEntity ) + { + return result; + } + if (!mesh && srcRefEntity && !srcRefEntity->GetCurrentMesh() ) + { + return result; + } + + CKBeObject *attObject = NULL; + if (mesh && (mesh->HasAttribute(att) || isNewType) ) + { + attObject = (CKBeObject*)mesh; + } + if (srcRefEntity && (srcRefEntity->HasAttribute(att) || isNewType ) ) + { + attObject = (CKBeObject*)srcRefEntity; + } + + + //################################################################ + // + // Fill sub shapes object description. + // + + if (attObject && !isNewType ) //we have attribute values: + { + objectDescr.density = GetValueFromAttribute(attObject ,att, E_PPS_DENSITY); + objectDescr.massOffset= GetValueFromAttribute(attObject ,att, E_PPS_MASS_OFFSET); + objectDescr.shapeOffset = GetValueFromAttribute(attObject ,att, E_PPS_SHAPE_OFFSET); + objectDescr.skinWidth = GetValueFromAttribute(attObject,att, E_PPS_SKIN_WIDTH); + objectDescr.hullType = GetValueFromAttribute(attObject,att,E_PPS_HULLTYPE); + objectDescr.hirarchy = GetValueFromAttribute(attObject,att,E_PPS_HIRARCHY); + objectDescr.collisionGroup = GetValueFromAttribute(attObject,att,E_PPS_COLL_GROUP); + objectDescr.newDensity = GetValueFromAttribute(attObject,att,E_PPS_NEW_DENSITY); + objectDescr.totalMass = GetValueFromAttribute(attObject,att,E_PPS_TOTAL_MASS); + } + + if (srcRefEntity) + { + objectDescr.subEntID = srcRefEntity->GetID(); + } + + //################################################################ + // + // Transformation values + // + VxVector box_s; + + if (!mesh && srcRefEntity) + { + box_s = BoxGetZero(srcRefEntity); + } + if (!srcRefEntity && mesh) + { + box_s = mesh->GetLocalBox().GetSize(); + } + if (srcRefEntity && mesh ) + { + box_s = mesh->GetLocalBox().GetSize(); + } + + //################################################################ + // + // Determine radius + // + float radius = 1.0f; + if ( mesh && !srcRefEntity ) + { + radius = mesh->GetRadius(); + } + if (!mesh && srcRefEntity && srcRefEntity->GetCurrentMesh() ) + { + radius = srcRefEntity->GetCurrentMesh()->GetRadius(); + } + if (mesh && srcRefEntity) + { + radius = mesh->GetRadius(); + } + + //################################################################ + // + // Calculate destination matrix + // + VxMatrix v_matrix ; + VxVector pos,scale; + VxQuaternion quat; + + + if (srcRefEntity) + { + if (isChild) + { + v_matrix = srcRefEntity->GetLocalMatrix(); + }else + { + v_matrix = srcRefEntity->GetWorldMatrix(); + } + } + Vx3DDecomposeMatrix(v_matrix,quat,pos,scale); + + + if (mesh && !srcRefEntity) + { + pos = localPosition; + quat = localRotation; + } + + if (mesh && srcRefEntity ) + { + + VxQuaternion refQuad2; + srcRefEntity->GetQuaternion(&refQuad2,GetVT3DObject()); + VxVector relPos; + srcRefEntity->GetPosition(&relPos,GetVT3DObject()); + if (!isChild) + { + pos = relPos; + quat = refQuad2; + } + } + + if (!mesh && srcRefEntity ) + { + VxVector relPos; + srcRefEntity->GetPosition(&relPos,GetVT3DObject()); + VxQuaternion refQuad2; + srcRefEntity->GetQuaternion(&refQuad2,GetVT3DObject()); + pos = relPos; + quat = refQuad2; + } + NxQuat rot = pMath::getFrom(quat); + + //################################################################ + // + // Determine the mesh + // + if (mesh && srcRefEntity==NULL ) + { + srcMesh = mesh; + } + if (!mesh && srcRefEntity && srcRefEntity->GetCurrentMesh() ) + { + srcMesh = srcRefEntity->GetCurrentMesh(); + } + + if (mesh && srcRefEntity && srcRefEntity->GetCurrentMesh()) + { + srcMesh = mesh; + } + + CK_ID srcID = 0 ; + if (srcMesh) + { + srcID = srcMesh->GetID(); + } + + + //################################################################ + // + // Create the final sub shape + // + + pSubMeshInfo *sInfo = new pSubMeshInfo(); + bool isWheel1 = false; + pWheel *wheel =NULL; + NxShape *shape = NULL; + + + if (objectDescr.hullType != HT_Wheel) + { + shape = pFactory::Instance()->createShape(GetVT3DObject(),objectDescr,srcRefEntity,srcMesh,pos,quat); + }else + { + wheel = pFactory::Instance()->createWheelSubShape(this,srcRefEntity,srcMesh,&objectDescr,pos,quat,shape); + if (wheel) + { + sInfo->wheel = wheel; + pWheel1* w1 = dynamic_cast(wheel); + if (w1){ + + isWheel1 = true; + shape = (NxShape*)w1->getWheelConvex(); + } + + pWheel2* w2 = dynamic_cast(wheel); + if (w2) + { + shape =(NxShape*)w2->getWheelShape(); + } + + }else + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Creating wheel sub shape failed"); + return NULL; + } + } + + if (!shape) + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create sub shape!"); + } + + if (shape) + { + + //################################################################ + // + // Setup the material + // + int materialIndex = 0; + + pMaterial bMaterial; + bool hasMaterial = pFactory::Instance()->findSettings(bMaterial,srcRefEntity); + if (!hasMaterial) + { + hasMaterial = pFactory::Instance()->findSettings(bMaterial,mesh); + } + + if (hasMaterial) + { + NxMaterialDesc nxMatDescr; + pFactory::Instance()->copyTo(nxMatDescr,bMaterial); + NxMaterial *nxMaterial = getWorld()->getScene()->createMaterial(nxMatDescr); + if (nxMaterial) + { + materialIndex = nxMaterial->getMaterialIndex(); + nxMaterial->userData = (void*)&bMaterial; + } + }else + { + materialIndex = getWorld()->getDefaultMaterial()->getMaterialIndex(); + } + shape->setMaterial(materialIndex); + + //################################################################ + // + // Store meta info in shape user data. + // + + shape->setGroup(objectDescr.collisionGroup); + + + + if (srcMesh) + { + sInfo->meshID = srcMesh->GetID(); + sInfo->mesh =(CKBeObject*)srcMesh; + shape->setName(srcMesh->GetName()); + } + + if(srcRefEntity) + { + sInfo->entID = srcRefEntity->GetID(); + sInfo->refObject = (CKBeObject*)srcRefEntity; + shape->setName(srcRefEntity->GetName()); + } + + shape->userData = (void*)sInfo; + } + + + //################################################################ + // + // Wheel Type one has an additional capsule swept shape + // We store the shape meta data there as well + if ( + isWheel1 && + wheel && + dynamic_cast(wheel) && + (pWheel1*)(dynamic_cast(wheel))->getWheelCapsule() + ) + { + ((pWheel1*)(dynamic_cast(wheel)))->getWheelCapsule()->userData = sInfo; + } + + //################################################################ + // + // Modify mass + // + if (objectDescr.mass.newDensity!=0.0f || objectDescr.mass.totalMass!=0.0f ) + { + getActor()->updateMassFromShapes(objectDescr.mass.newDensity,objectDescr.mass.totalMass); + } + + //################################################################ + // + // Post routine + // + getActor()->wakeUp(); + if(mesh) + return result; + + if (!objectDescr.hirarchy) + { + return result; + } + + if (!srcRefEntity) + { + return result; + } + + + //################################################################ + // + // If more entities in hierarchy, invoke this function recursively + // + CK3dEntity* subEntity = NULL; + while (subEntity= srcRefEntity->HierarchyParser(subEntity) ) + { + + pObjectDescr *subDescr = NULL; + + //-try old version : + if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) + { + subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + + //-try new version + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + if (subEntity->HasAttribute(attTypePBSetup)) + { + subDescr = new pObjectDescr(); + CKParameterOut *par = subEntity->GetAttributeParameter(attTypePBSetup); + IParameter::Instance()->copyTo(subDescr,par); + subDescr->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + + } + + if (!subDescr) + continue; + + if (subDescr->flags & BF_SubShape) + { + + ////////////////////////////////////////////////////////////////////////// + if (subDescr->hullType != HT_Cloth) + { + addSubShape(NULL,*subDescr,subEntity); + } + + if (subDescr->hullType == HT_Cloth) + { + + } + } + + } + + return result; +} + + + +void pRigidBody::setBoxDimensions( const VxVector&dimension,CKBeObject* subShapeReference/*=NULL*/ ) +{ + if (!isValid() || !getMainShape() ) + { + return; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxBoxShape *box = static_cast(getMainShape()->isBox()); + if (!box) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); + return; + } + box->setDimensions(getFrom(dimension)); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxBoxShape *box = static_cast(s->isBox()); + if (!box) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); + return; + } + box->setDimensions(getFrom(dimension)); + } +} +VxVector pRigidBody::getBoxDimensions(CKBeObject* subShapeReference) +{ + VxVector result(-1.f,-1.f,-1.f); + if (!isValid() || !getMainShape() ) + { + return result; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxBoxShape *box = static_cast(getMainShape()->isBox()); + if (!box) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); + return result; + } + return getFrom(box->getDimensions()); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxBoxShape *box = static_cast(s->isBox()); + if (!box) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); + return result; + } + getFrom(box->getDimensions()); + } + return result; +} + + + + + +void pRigidBody::setSphereRadius(float radius,CKBeObject* subShapeReference/* =NULL */) +{ + + if (!isValid() || !getMainShape() ) + { + return; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxSphereShape *sphere = static_cast(getMainShape()->isSphere()); + if (!sphere) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); + return; + } + sphere->setRadius(radius); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxSphereShape*sphere = static_cast(s->isSphere()); + if (!sphere) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); + return; + } + sphere->setRadius(radius); + } +} + + + +float pRigidBody::getSphereRadius(CKBeObject* subShapeReference/* =NULL */) +{ + + if (!isValid() || !getMainShape() ) + { + return -1.0f; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxSphereShape *sphere = static_cast(getMainShape()->isSphere()); + if (!sphere) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); + return -1.0f; + } + return sphere->getRadius(); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxSphereShape*sphere = static_cast(s->isSphere()); + if (!sphere) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); + return -1.0f; + } + return sphere->getRadius(); + } + return -1.0f; +} + + + + +void pRigidBody::setCapsuleDimensions(float radius,float length,CKBeObject* subShapeReference) +{ + + if (!isValid() || !getMainShape() ) + { + return; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxCapsuleShape *capsule = static_cast(getMainShape()->isCapsule()); + if (!capsule) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); + return; + } + capsule->setHeight(length); + capsule->setRadius(radius); + + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxCapsuleShape*capsule = static_cast(s->isCapsule()); + if (!capsule) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); + return; + } + capsule->setHeight(length); + capsule->setRadius(radius); + } +} + +void pRigidBody::getCapsuleDimensions(float& radius,float& length,CKBeObject* subShapeReference) +{ + if (!isValid() || !getMainShape() ) + { + return; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxCapsuleShape *capsule = static_cast(getMainShape()->isCapsule()); + if (!capsule) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); + radius = -1.0f; + length = -1.0f; + return; + } + + radius = capsule->getRadius(); + length = capsule->getHeight(); + + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try a mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxCapsuleShape*capsule = static_cast(s->isCapsule()); + if (!capsule) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); + radius = -1.0f; + length = -1.0f; + return; + } + radius = capsule->getRadius(); + length = capsule->getHeight(); + } + +} +HullType pRigidBody::getShapeType(CKBeObject* subShapeReference) +{ + if (!isValid() || !getMainShape() ) + { + return HT_Unknown; + } + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + return (HullType)vtAgeia::getHullTypeFromShape(getMainShape()); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try a mesh : + s = _getSubShape(subShapeReference->GetID()); + } + if (!s) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"couldn't find sub shape!"); + return HT_Unknown; + } + return (HullType)vtAgeia::getHullTypeFromShape(s); + } + return HT_Unknown; +} + +float pRigidBody::getSkinWidth(CKBeObject* subShapeReference) +{ + + if (!isValid() || !getMainShape() ) + { + return -1.0f; + } + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL && !getMainShape() ) + { + return mSkinWidth; + + } + if(subShapeReference == NULL && getMainShape() ) + { + return getMainShape()->getSkinWidth(); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try a mesh : + s = _getSubShape(subShapeReference->GetID()); + } + if (!s) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"couldn't find sub shape!"); + return -1.0f; + } + return s->getSkinWidth(); + } + return -1.0f; +} + +void pRigidBody::setSkinWidth(const float skinWidth,CKBeObject* subShapeReference) +{ + if (!isValid() || !getMainShape() ) + { + mSkinWidth = mSkinWidth; + return; + } + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL && !getMainShape() ) + { + mSkinWidth = skinWidth; + } + if(subShapeReference == NULL && getMainShape() ) + { + getMainShape()->setSkinWidth(skinWidth); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try a mesh : + s = _getSubShape(subShapeReference->GetID()); + } + if (!s) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"couldn't find sub shape!"); + return; + } + s->setSkinWidth(skinWidth); + } +} + + +int pRigidBody::removeSubShape( CKBeObject *reference,float newensity/*=0.0f*/,float totalMass/*=0.0f*/ ) +{ + + + int result = -1; + if (!reference || !getActor()) + { + return result; + } + + NxShape *subShape = NULL; + bool found = false; + while(subShape = _getSubShape(reference->GetID())) + { + getActor()->releaseShape(*subShape); + found =true; + } + + ////////////////////////////////////////////////////////////////////////// + + if (!found) + { + while(subShape = _getSubShape(reference->GetID())) + { + getActor()->releaseShape(*subShape); + found =true; + } + } + + if (found && newensity !=0.0f || totalMass!=0.0f ) + { + getActor()->updateMassFromShapes(newensity,totalMass); + } + getActor()->wakeUp(); + + return 1; +} + +NxShape * pRigidBody::_getSubShapeByEntityID( CK_ID id ) +{ + if (!getActor()) + { + return NULL; + } + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->entID == id) + { + return s; + } + } + } + return NULL; +} +bool pRigidBody::isSubShape(CKBeObject *object) +{ + + bool result = false; + if (!object) + { + return result; + } + + if ( _getSubShape(object->GetID()) || _getSubShapeByEntityID(object->GetID() )) + { + return true ; + } + return result; +} +NxShape *pRigidBody::_getSubShape(CK_ID meshID) +{ + + if (!getActor()) + { + return NULL; + } + + int nbShapes = getActor()->getNbShapes(); + + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->meshID == meshID) + { + return s; + } + } + } + return NULL; +} + + +int pRigidBody::updateMassFromShapes( float density, float totalMass ) +{ + + + if (getActor()) + { + return getActor()->updateMassFromShapes(density,totalMass); + } + return -1; +} + + +NxShape *pRigidBody::getShapeByIndex(int index/* =0 */) +{ + + NxU32 nbShapes = getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; jreadActorFlag(NX_AF_DISABLE_COLLISION); + } + }else{ + return !subShape->getFlag(NX_SF_DISABLE_COLLISION); + } + } + return false; +} +void pRigidBody::enableCollision( bool enable,CK3dEntity* subShapeReference/*=NULL*/ ) +{ + NxShape *subShape = getSubShape(subShapeReference); + + if (!subShape) + { + subShape==getMainShape(); + } + if (subShape ) + { + if (subShape ==getMainShape()) + { + if (!enable) + { + getActor()->raiseActorFlag(NX_AF_DISABLE_COLLISION); + }else + { + getActor()->clearActorFlag(NX_AF_DISABLE_COLLISION); + } + }else{ + + subShape->setFlag(NX_SF_DISABLE_RESPONSE, !enable ); + } + } +} +void pRigidBody::enableTriggerShape( bool enable,CK3dEntity* subShapeReference/*=NULL*/ ) +{ + + NxShape *subShape = getSubShape(subShapeReference); + if (subShape) + { + subShape->setFlag(NX_TRIGGER_ENABLE,enable); + } +} + +bool pRigidBody::isTriggerShape( CK3dEntity* subShapeReference/*=NULL*/ ) +{ + NxShape *subShape = getSubShape(subShapeReference); + if (subShape) + { + return subShape->getFlag(NX_TRIGGER_ENABLE); + } + return false; +} + +bool pRigidBody::isCollisionsNotifyEnabled() +{ + + return ( getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ); +} + +void pRigidBody::enableCollisionsNotify( bool enable ) +{ + if (enable) + { + getActor()->setContactReportFlags(NX_NOTIFY_ON_TOUCH); + }else + getActor()->setContactReportFlags(NX_IGNORE_PAIR); +} + +void pRigidBody::enableContactModification(bool enable) +{ + + int& flags = m_sFlags; + if (getActor()) + { + if (enable){ + getActor()->raiseActorFlag(NX_AF_CONTACT_MODIFICATION); + + + flags|=BF_ContactModify; + } + else{ + getActor()->clearActorFlag(NX_AF_CONTACT_MODIFICATION); + flags&=~(BF_ContactModify); + } + } +} + + +void pRigidBody::enableCollisionForceCalculation(bool enable,CK3dEntity* subShapeReference/* =NULL */) +{ + + NxShape *subShape = getSubShape(subShapeReference); + if (subShape) + { + int o = subShape->getFlag(NX_SF_POINT_CONTACT_FORCE); + subShape->setFlag(NX_SF_POINT_CONTACT_FORCE,enable); + int o2 = subShape->getFlag(NX_SF_POINT_CONTACT_FORCE); + int o3 = subShape->getFlag(NX_SF_POINT_CONTACT_FORCE); + } + +} + +VxVector pRigidBody::getPivotOffset(CK3dEntity*shapeReference) +{ + + NxShape *subshape = getSubShape(shapeReference); + if (subshape) return getFrom(subshape->getLocalPosition()); + + return VxVector(); +} + +NxShape*pRigidBody::getSubShape(CK3dEntity*shapeReference/* =NULL */) +{ + + + if (shapeReference) + { + + NxShape *inputShape = _getSubShapeByEntityID(shapeReference->GetID()); + if (getMainShape() ==inputShape) + { + return getMainShape(); + }else{ + return inputShape; + } + } + + return getMainShape(); + +} +void pRigidBody::setShapeMaterial(pMaterial&material,CK3dEntity*shapeReference/* =NULL */) +{ + + NxShape *dstShape = NULL; + + + if (shapeReference) + { + dstShape = _getSubShapeByEntityID(shapeReference->GetID()); + }else{ + dstShape = getMainShape(); + } + + + #ifdef _DEBUG + assert(dstShape); + #endif + + + int materialIndex = dstShape->getMaterial(); + + NxMaterial *currentMaterial = getActor()->getScene().getMaterialFromIndex(materialIndex); + + if (!material.isValid()) + return; + + NxMaterialDesc nxMatDescr; + + ////////////////////////////////////////////////////////////////////////// + // + // We dont alter the default material ! We create a new one !! + // + + int defaultID = getWorld()->getDefaultMaterial()->getMaterialIndex(); + if ( !currentMaterial || materialIndex ==0 || materialIndex == getWorld()->getDefaultMaterial()->getMaterialIndex() ) + { + + pFactory::Instance()->copyTo(nxMatDescr,material); + + NxMaterial *newMaterial = getActor()->getScene().createMaterial(nxMatDescr); + if (newMaterial){ + dstShape->setMaterial(newMaterial->getMaterialIndex()); + newMaterial->userData = (void*)&material; + } + } + else + { + + pFactory::Instance()->copyTo(nxMatDescr,material); + currentMaterial->loadFromDesc(nxMatDescr); + //currentMaterial->userData = (void*)&material; + + + } + + +} +pMaterial&pRigidBody::getShapeMaterial(CK3dEntity *shapeReference/* =NULL */) +{ + + pMaterial result; + + if (shapeReference && !isSubShape(shapeReference)) + { + return result; + } + + NxShape *srcShape = NULL; + CK3dEntity *ent = GetVT3DObject(); + + if (shapeReference) + { + srcShape = getSubShape(shapeReference); + }else{ + srcShape = getMainShape(); + } + + #ifdef _DEBUG + assert(srcShape); + #endif + + int index = srcShape->getMaterial(); + NxMaterial *mat = getActor()->getScene().getMaterialFromIndex(srcShape->getMaterial()); + + pFactory::Instance()->copyTo(result,getActor()->getScene().getMaterialFromIndex(srcShape->getMaterial())); + + + return result; + +} +void pRigidBody::_checkForRemovedSubShapes() +{ + + +} + +void pRigidBody::_checkForNewSubShapes() +{ + + pObjectDescr *oDescr = pFactory::Instance()->createPObjectDescrFromParameter(GetVT3DObject()->GetAttributeParameter(GetPMan()->GetPAttribute())); + if (!oDescr) + { + return; + } + + if (! ( getFlags() & BF_Hierarchy ) ) + { + return ; + } + + CK3dEntity* subEntity = NULL; + while (subEntity= GetVT3DObject()->HierarchyParser(subEntity) ) + { + if ( !_getSubShapeByEntityID(subEntity->GetID()) ) + { + CKSTRING name = subEntity->GetName(); + int s = isSubShape(subEntity); + + if ( subEntity->HasAttribute(GetPMan()->GetPAttribute() ) ) + { + pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + if (subDescr->flags & BF_SubShape) + { + if (subDescr->hullType != HT_Cloth) + { + addSubShape(NULL,*oDescr,subEntity); + } + + if (subDescr->hullType == HT_Cloth) + { + //pClothDesc *cloth = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + } + } + } + } + if (( getFlags() & BF_Hierarchy )) + { + if (oDescr->newDensity!=0.0f || oDescr->totalMass!=0.0f ) + { + updateMassFromShapes(oDescr->newDensity,oDescr->totalMass); + } + } +} + +int pRigidBody::updateSubShape(bool fromPhysicToVirtools/* =true */,bool position/* =true */,bool rotation/* =true */,CK3dEntity *childObject/* =NULL */,bool hierarchy/* =true */) +{ + if(!getActor()) + return -1; + NxU32 nbShapes = getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (info) + { + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(info->entID)); + if (ent) + { + + if (s == getMainShape()) + continue; + + + if (fromPhysicToVirtools) + { + //pVehicle *v =getVehicle(); + pWheel* wheel = (pWheel*)getWheel(ent); + if (wheel) + { + wheel->_updateVirtoolsEntity(position,rotation); + }else + { + + if (position) + { + VxVector gPos = getFrom(s->getLocalPose().t); + ent->SetPosition(&gPos,GetVT3DObject()); + } + if (rotation) + { + VxQuaternion rot = pMath::getFrom( s->getLocalPose().M ); + if(s->isWheel()) + { + }else + { + ent->SetQuaternion(&rot,GetVT3DObject()); + } + } + } + }else//Virtools to Ageia ! + { + if (position) + { + VxVector relPos; + ent->GetPosition(&relPos,GetVT3DObject()); + s->setLocalPosition(getFrom(relPos)); + } + + if (rotation) + { + VxQuaternion refQuad2; + ent->GetQuaternion(&refQuad2,GetVT3DObject()); + s->setLocalOrientation(getFrom(refQuad2)); + } + + } + } + } + } + } + } + return 0; +} + +int pRigidBody::updateSubShapes(bool fromPhysicToVirtools/* = true */,bool position/* =true */,bool rotation/* =true */,CK3dEntity *childObject) +{ + + + if(!getActor()) + return -1; + NxU32 nbShapes = getActor()->getNbShapes(); + if ( nbShapes ) + { + bool hierarchy = (getFlags() & BF_Hierarchy ) ? true : false; + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (info) + { + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(info->entID)); + if (ent) + { + + if (fromPhysicToVirtools) + { + //pVehicle *v =getVehicle(); + pWheel* wheel = (pWheel*)getWheel(ent); + if (wheel) + { + wheel->_updateVirtoolsEntity(position,rotation); + }else + { + + if (position) + { + if ( s != getMainShape()){ + VxVector gPos = getFrom(s->getLocalPose().t); + ent->SetPosition(&gPos,GetVT3DObject()); + }else + { + { + VxVector gPos = getFrom(s->getGlobalPose().t); + ent->SetPosition(&gPos,NULL,!hierarchy); + + /*pivot correction*/ + VxVector diff = getFrom(s->getLocalPosition()); + if (XAbs(diff.SquareMagnitude()) > 0.01f) + { + diff *=-1.0f; + ent->SetPosition(&diff,ent,!hierarchy); + } + } + } + } + if (rotation) + { + if ( s != getMainShape()){ + + VxQuaternion rot = pMath::getFrom( s->getLocalPose().M ); + ent->SetQuaternion(&rot,GetVT3DObject()); + }else{ + VxQuaternion rot = pMath::getFrom( s->getGlobalPose().M ); + ent->SetQuaternion(&rot,NULL,!hierarchy); + } + + + } + } + }else//Virtools to Ageia ! + { + if (position) + { + VxVector relPos; + ent->GetPosition(&relPos,GetVT3DObject()); + s->setLocalPosition(getFrom(relPos)); + //onKinematicMove(fromPhysicToVirtools,position,false,childObject); + + } + + if (rotation) + { + VxQuaternion refQuad2; + ent->GetQuaternion(&refQuad2,GetVT3DObject()); + s->setLocalOrientation(getFrom(refQuad2)); + } + } + } + } + } + } + } + + + return 0; +} +int pRigidBody::getCollisionsGroup( CK3dEntity* subShapeReference/*=NULL*/ ) +{ + + NxShape *subShape = getSubShape(subShapeReference); + if (subShape) + { + return subShape->getGroup(); + } + return -1; +} +void pRigidBody::setCollisionsGroup( int index,CK3dEntity* subShapeReference/*=NULL*/ ) +{ + if(!getActor()) + return; + if (subShapeReference == NULL) + { + if(index>=0 && index <=32) + getActor()->setGroup(index); + + NxU32 nbShapes = getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j=0 && index <=32) + s->setGroup(index); + } + } + } + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + if (!s) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"there is no such sub shape!"); + return; + } + s->setGroup(index); + } +} + +void pRigidBody::setGroupsMask(CK3dEntity *shapeReference,const pGroupsMask& mask) +{ + + + NxShape *mainshape = getMainShape(); + NxShape *dstShape = getMainShape(); + + if (shapeReference) + { + NxShape *inputShape = _getSubShapeByEntityID(shapeReference->GetID()); + if (mainshape==inputShape) + { + dstShape = mainshape; + }else{ + dstShape = inputShape; + } + } + + + NxGroupsMask mask1; + mask1.bits0 = mask.bits0; + mask1.bits1 = mask.bits1; + mask1.bits2 = mask.bits2; + mask1.bits3 = mask.bits3; + + if (dstShape) + { + dstShape->setGroupsMask(mask1); + } + +} + + +pGroupsMask pRigidBody::getGroupsMask(CK3dEntity *shapeReference) +{ + + NxShape *mainshape = getMainShape(); + NxShape *dstShape = getMainShape(); + + if (shapeReference) + { + NxShape *inputShape = _getSubShapeByEntityID(shapeReference->GetID()); + if (mainshape==inputShape) + { + dstShape = mainshape; + }else{ + dstShape = inputShape; + } + } + + if (dstShape) + { + + NxGroupsMask gMask = dstShape->getGroupsMask(); + + pGroupsMask vtGMask; + + vtGMask.bits0 = gMask.bits0; + vtGMask.bits1 = gMask.bits1; + vtGMask.bits2 = gMask.bits2; + vtGMask.bits3 = gMask.bits3; + return vtGMask; + + } + + + return pGroupsMask(); + +} + +/* +if (srcRefEntity && srcRefEntity->HasAttribute(GetPMan()->att_wheelDescr )) +{ + CKParameterOut *par = srcRefEntity->GetAttributeParameter(GetPMan()->att_wheelDescr ); + if (par) + { + pWheelDescr *wDescr = new pWheelDescr(); + int err = pFactory::Instance()->copyTo(wDescr,par); + + if (wDescr && !wDescr->isValid() ) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Wheel Description was invalid"); + delete wDescr; + } + + if (wDescr) + { + pWheel *wheel = pFactory::Instance()->createWheel(this,*wDescr); + + shape = pFactory::Instance()->createWheelShape(getActor(),&objectDescr,wDescr,srcRefEntity,srcMesh,pos,quat); + if (shape) + { + + if(wDescr->wheelFlags & E_WF_USE_WHEELSHAPE) + { + pWheel2 * wheel2 = (pWheel2*)wheel; + wheel2->setWheelShape((NxWheelShape*)shape); + + }else{ + + } + + if (wheel->getWheelFlag(E_WF_VEHICLE_CONTROLLED) && mVehicle) + mVehicle->getWheels().push_back(wheel); + + wheel->mWheelFlags = wDescr->wheelFlags; + sInfo->wheel = wheel; + wheel->setEntID(srcRefEntity->GetID()); + + } + } + } +} +*/ \ No newline at end of file diff --git a/usr/Src/Core/pRigidBody/pRigidBodyTypes.cpp b/usr/Src/Core/pRigidBody/pRigidBodyTypes.cpp new file mode 100644 index 0000000..d079244 --- /dev/null +++ b/usr/Src/Core/pRigidBody/pRigidBodyTypes.cpp @@ -0,0 +1,236 @@ +#include +#include "vtPhysXAll.h" + +#include "IParameter.h" +#include + +bool pPivotSettings::isValid() +{ + return true; + +} + +bool pObjectDescr::setToDefault() +{ + + hullType =HT_Sphere; + density = 1.0f; + massOffset = VxVector(); + shapeOffset = VxVector(); + flags = (BodyFlags)0; + skinWidth =0.0f; + newDensity = 0.0f; + totalMass = 0.0f; + collisionGroup = 0; + hirarchy = 0; + subEntID = -1; + transformationFlags = 0; + worlReference = 0; + + + internalXmlID = externalXmlID = xmlImportFlags = 0; + + massOffsetReference = 0; + + pivotOffsetReference = 0; + + + ccdMotionThresold = 0.0; + ccdFlags = 0 ; + ccdMeshReference =NULL; + ccdScale = 1.0f; + + linearDamping = angularDamping = 0.0f; + + linearSleepVelocity = angularSleepVelocity = sleepingEnergyThresold = 0.0f; + + solverIterations = dominanceGroups = compartmentID = 0; + + version = OD_DECR_V0; + mask = (pObjectDescrMask)0; + + groupsMask.bits0=0; + groupsMask.bits1=0; + groupsMask.bits2=0; + groupsMask.bits3=0; + + + wheel.setToDefault(); + optimization.setToDefault(); + material.setToDefault(); + collision.setToDefault(); + pivot.setToDefault(); + //mass.setToDefault(); + ccd.setToDefault(); + + + return true; +} + +bool pCollisionSettings::setToDefault() +{ + collisionGroup = 0; + collisionGroup = 0; + skinWidth = 0.025f; + return true; +} + +bool pPivotSettings::setToDefault() +{ + pivotReference = 0; + return true; +} +bool pCCDSettings::setToDefault() +{ + motionThresold = 0.0; + flags = 0 ; + meshReference =0; + scale = 1.0f; + + return true; +} + +bool pOptimization::setToDefault() +{ + transformationFlags = (BodyLockFlags)0; + + linDamping = angDamping = 0.0f; + solverIterations = 4 ; + dominanceGroup=0; + compartmentGroup=0; + sleepEnergyThreshold =0.0f; + linSleepVelocity = angSleepVelocity = 0.0; + + return true; + +} +bool pOptimization::isValid() +{ + + bool result = true; + + iAssertWR( X_IS_BETWEEN(solverIterations,1,255) ,solverIterations=4,result ); + iAssertWR( !(linDamping < 0) ,"",result ); + iAssertWR( !(angDamping< 0) ,"",result ); + iAssertWR( !(transformationFlags < 0) ,transformationFlags=((BodyLockFlags)0),result ); + iAssertWR( !(linSleepVelocity < 0) ,"",result ); + iAssertWR( !(angSleepVelocity < 0) ,"",result ); + + + return true; + +} +bool pMaterial::isValid() +{ + bool result = true; + + + iAssertWR( !(dynamicFriction < 0.0f) ,"",result ); + iAssertWR( !(staticFriction < 0.0f) ,"",result ); + iAssertWR( !(restitution < 0.0f || restitution > 1.0f) ,"",result ); + + if (flags & 1) + { + float sMagnitude = dirOfAnisotropy.SquareMagnitude(); + iAssertWR( sMagnitude > 0.98f || sMagnitude < 1.03f ,"",result ); + iAssertWR( !(dynamicFrictionV < 0.0f) ,"",result ); + iAssertWR( !(staticFrictionV < 0.0f) ,"",result ); + } + + iAssertWR( frictionCombineMode <= 4 ,"",result ); + iAssertWR( restitutionCombineMode <= 4 ,"",result ); + + + return result; + +} + +bool pConvexCylinderSettings::setToDefault() +{ + radius.setToDefault(); + height.setToDefault(); + approximation = 4; + + downAxis.Set(0,-1,0); + rightAxis.Set(1,0,0); + forwardAxis.Set(0,0,1); + + downAxisRef = 0 ; + rightAxisRef = 0 ; + forwardAxisRef = 0 ; + convexFlags = CF_ComputeConvex; + + + return true; + +} +bool pConvexCylinderSettings::isValid() +{ + + bool result=true; + iAssertWR(radius.isValid(),"",result); + iAssertWR(height.isValid(),"",result); + iAssertWR(approximation >= 4 && approximation > 0,"",result); + iAssertWR( XAbs(forwardAxis.SquareMagnitude()) > 0.1f || forwardAxisRef,"",result); + iAssertWR( XAbs(downAxis.SquareMagnitude()) > 0.1f || downAxisRef,"",result); + iAssertWR( XAbs(rightAxis.SquareMagnitude()) > 0.1f || rightAxisRef,"",result); + + return result; +} + +bool pAxisReferencedLength::isValid() +{ + return ( referenceAxis<3 && referenceAxis >=0) && (value > 0.0f || reference ) ; +} + +bool pAxisReferencedLength::evaluate(CKBeObject *referenceObject) +{ + if (!reference && referenceObject) + { + this->reference = referenceObject; + } + + if (reference) + { + VxVector size; + + if (reference->GetClassID() == CKCID_3DOBJECT ) + { + CK3dEntity *ent = (CK3dEntity*)reference; + if (ent && ent->GetCurrentMesh() ) + size = ent->GetCurrentMesh()->GetLocalBox().GetSize(); + } + else if(reference->GetClassID() == CKCID_MESH) + { + CKMesh *mesh = (CKMesh*)reference; + if (mesh) + { + size = mesh->GetLocalBox().GetSize(); + } + } + value = size[referenceAxis]; + return XAbs(size.SquareMagnitude()) >0.0f; + } + return false; +} +bool pAxisReferencedLength::setToDefault() +{ + value=0.0f; + referenceAxis = 0; + reference = NULL; + + return true; +} + +bool pCapsuleSettingsEx::setToDefault() +{ + radius.setToDefault(); + height.setToDefault(); + return true; +} +bool pCapsuleSettingsEx::isValid() +{ + return radius.isValid() && height.isValid(); +} + + diff --git a/usr/Src/Core/pRigidBody/pRigidBodyWheel.cpp b/usr/Src/Core/pRigidBody/pRigidBodyWheel.cpp new file mode 100644 index 0000000..86e2652 --- /dev/null +++ b/usr/Src/Core/pRigidBody/pRigidBodyWheel.cpp @@ -0,0 +1,256 @@ +#include +#include "vtPhysXAll.h" + +#include "NXU_helper.h" // NxuStream helper functions. +#include "NXU_PhysicsInstantiator.h" + + +void pRigidBody::updateWheels(float step) +{ + + + + NxVec3 _localVelocity; + + bool _breaking=false; + + + /* + _computeMostTouchedActor(); + NxVec3 relativeVelocity; + if (_mostTouchedActor == NULL || !_mostTouchedActor->isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - _mostTouchedActor->getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + NxQuat global2Local; + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + char master[512]; + */ + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + pWheel *wheel = sinfo->wheel; + pWheel2* wheel2 = dynamic_cast(wheel); + + if (wheel->getWheelFlag(WF_VehicleControlled)) + { + continue; + } + + wheel->_tick(step / GetPMan()->GetContext()->GetTimeManager()->GetTimeScaleFactor()); + + /* + + NxWheelShape *wShape = wheel2->getWheelShape(); + if (!wShape) continue; + + + + ////////////////////////////////////////////////////////////////////////// + // + // + // + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + + if (contactShape) + { + + NxVec3 relativeVelocity; + if ( !contactShape->getActor().isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - contactShape->getActor().getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + _breaking = NxMath::abs(_localVelocity.z) < ( 0.1 ); +// wShape->setAxleSpeed() + } + + + float rollAngle = wheel2->getWheelRollAngle(); + rollAngle+=wShape->getAxleSpeed() * (step* 0.01f); + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + wheel2->setWheelRollAngle(rollAngle); + + NxMat34& wheelPose = wShape->getGlobalPose(); + + + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( contactShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + wheel2->getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - wheel2->getSuspensionTravel(), wheelPose.t.z ); + } + + float rAngle = wheel2->getWheelRollAngle(); + float steer = wShape->getSteerAngle(); + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + wheel2->setWheelPose(wheelPose); + + */ + + } + } + } +/* //motorTorque *= 0.1f; + brakeTorque *= 500.0f; + if(handBrake && getWheelFlag(E_WF_AFFECTED_BY_HANDBRAKE)) + brakeTorque = 1000.0f; + if(getWheelFlag(E_WF_ACCELERATED)) + mWheelShape->setMotorTorque(motorTorque); + mWheelShape->setBrakeTorque(brakeTorque); + + + + + + mWheelPose = mWheelShape->getGlobalPose(); + + NxWheelContactData wcd; + NxShape* s = mWheelShape->getContact(wcd); + NxReal stravel = mWheelShape->getSuspensionTravel(); + NxReal radius = mWheelShape->getRadius(); + + + //have ground contact? + if( s && wcd.contactPosition <= (stravel + radius) ) { + mWheelPose.t = NxVec3( mWheelPose.t.x, wcd.contactPoint.y + radius, mWheelPose.t.z ); + } + else { + mWheelPose.t = NxVec3( mWheelPose.t.x, mWheelPose.t.y - stravel, mWheelPose.t.z ); + } + + + NxMat33 rot, axisRot, rollRot; + rot.rotY( mWheelShape->getSteerAngle() ); + //rot.rotX(0); + axisRot.rotY(0); + rollRot.rotX(_wheelRollAngle); + mWheelPose.M = rot * mWheelPose.M * axisRot * rollRot; + + */ + +} +bool pRigidBody::hasWheels() +{ + + bool result = false; + + if (!getActor()) + { + return false; + } + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + return true; + } + } + } + + return result; + +} + +int pRigidBody::getNbWheels() +{ + + int result = 0; + + if (!getActor()) + { + return NULL; + } + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + result ++; + } + } + } + return result; +} + +pWheel2 *pRigidBody::getWheel2(CK3dEntity* subShapeReference) +{ + return static_cast(getWheel(subShapeReference)); +} +pWheel *pRigidBody::getWheel(CK3dEntity* subShapeReference) +{ + + pWheel *result = NULL; + if (!subShapeReference) + { + return result; + } + + NxShape *subShape = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!subShape) + return result; + + pSubMeshInfo *sInfo = static_cast(subShape->userData); + + if (sInfo && sInfo->wheel) + { + return sInfo->wheel; + } + /* + + NxWheelShape *wheel = static_cast(subShape->isWheel()); + if (wheel) + { + pSubMeshInfo *sInfo = static_cast(subShape->userData); + + if (sInfo && sInfo->wheel) + { + return sInfo->wheel; + } + } + */ + return result; + +} \ No newline at end of file diff --git a/usr/Src/Core/pSerializer/pSerializer.cpp b/usr/Src/Core/pSerializer/pSerializer.cpp new file mode 100644 index 0000000..132e197 --- /dev/null +++ b/usr/Src/Core/pSerializer/pSerializer.cpp @@ -0,0 +1,226 @@ +#include +#include "vtPhysXAll.h" + +#include "NXU_helper.h" // NxuStream helper functions. +#include "NXU_PhysicsInstantiator.h" + +#include "UserAllocator.h" +#include "ErrorStream.h" +#include "Utilities.h" + +static ErrorStream gErrorStream; +static pSerializer *gSerializer = NULL; + +void pSerializer::parseFile(const char*filename,int flags) +{ + + if(!GetPMan()->getPhysicsSDK()) + return; + + + if (!loadCollection(filename,1)) + { + return ; + } + + + NXU::instantiateCollection(mCollection, *GetPMan()->getPhysicsSDK(), 0, 0, 0); + NXU::NxuPhysicsInstantiator Instantiator(mCollection); + Instantiator.instantiate(*GetPMan()->getPhysicsSDK()); + int sCount = mCollection->mScenes.size(); + + for (NxU32 i=0; imScenes.size(); i++) + { + NXU::NxSceneDesc *sd = mCollection->mScenes[i]; + + for (NxU32 j=0; jmActors.size(); j++) + { + + NXU::NxActorDesc *ad = sd->mActors[j]; + const char*name = ad->name; + XString nameStr(name); + + CK3dEntity *ent = (CK3dEntity*)ctx()->GetObjectByNameAndClass(nameStr.Str(),CKCID_3DOBJECT); + if (ent) + { + pRigidBody *body = GetPMan()->getBody(nameStr.CStr()); + if (body) + body->readFrom(ad,0); + else + body = pFactory::Instance()->createBody(ent,NULL,ad,1); + + } + + if ( ad->mHasBody ) // only for dynamic actors + { + for (NxU32 k=0; kmShapes.size(); k++) + { + NXU::NxShapeDesc *shape = ad->mShapes[k]; + NxVec3 locPos = shape->localPose.t; + NxQuat localQuad = shape->localPose.M; + } + } + } + } + +} + + + +class MyUserNotify: public NXU_userNotify, public NXU_errorReport +{ +public: + virtual void NXU_errorMessage(bool isError, const char *str) + { + if (isError) + { + printf("NxuStream ERROR: %s\r\n", str); + } + else + { + printf("NxuStream WARNING: %s\r\n", str); + } + } + + virtual void NXU_notifyScene(NxU32 sno, NxScene *scene, const char *userProperties) + { + + }; + + + +}; +MyUserNotify gUserNotify; + + + + + +bool pSerializer::overrideBody(pRigidBody *body,int flags) +{ + + if (!mCollection) + { + return false; + } + + NXU::instantiateCollection(mCollection, *GetPMan()->getPhysicsSDK(), 0, 0, 0); + NXU::NxuPhysicsInstantiator Instantiator(mCollection); + Instantiator.instantiate(*GetPMan()->getPhysicsSDK()); + + int sCount = mCollection->mScenes.size(); + for (NxU32 i=0; imScenes.size(); i++) + { + + NXU::NxSceneDesc *sd = mCollection->mScenes[i]; + + for (NxU32 j=0; jmActors.size(); j++) + { + + NXU::NxActorDesc *ad = sd->mActors[j]; + const char*name = ad->name; + XString nameStr(name); + + + if ( ad->mHasBody ) // only for dynamic actors + { + for (NxU32 k=0; kmShapes.size(); k++) + { + NXU::NxShapeDesc *shape = ad->mShapes[k]; + NxVec3 locPos = shape->localPose.t; + NxQuat localQuad = shape->localPose.M; + } + } + } + } + + return true; +} + + +int pSerializer::loadCollection(const char*fileName,int flags) +{ + if (mCollection) + { + releaseCollection(mCollection); + mCollection = NULL; + } + mCollection = getCollection(fileName,flags); + if (mCollection) + { + return 1; + }else + { + return 0; + } +} + + +pSerializer::pSerializer() +{ + gSerializer = this; + mCollection = NULL; + +} + +//************************************ +// Method: Instance +// FullName: vtAgeia::pSerializer::Instance +// Access: public static +// Returns: pSerializer* +// Qualifier: +//************************************ +pSerializer*pSerializer::Instance() +{ + + + if (!gSerializer) + { + gSerializer = new pSerializer(); + } + + return gSerializer; +} + +NXU::NxuPhysicsCollection* pSerializer::getCollection(const char *pFilename,int type) +{ + + NXU::NxuPhysicsCollection* c = NULL; + c = NXU::loadCollection(pFilename,(NXU::NXU_FileType)type); + if (!c) + { + return NULL; + } + return c; +} + + +int pSerializer::saveCollection(const char*filename) +{ + + char SaveFilename[512]; + //GetTempFilePath(SaveFilename); + strcat(SaveFilename, filename); + + NXU::setUseClothActiveState(false); + NXU::setUseSoftBodyActiveState(false); + + NXU::setErrorReport(&gUserNotify); + NXU::setEndianMode(isProcessorBigEndian()); + + NXU::NxuPhysicsCollection *c = NXU::extractCollectionScene(GetPMan()->getDefaultWorld()->getScene()); + if (c) + { + char scratch[512]; + XString fName(filename); + //fName << "\0"; + sprintf(scratch, "%s.xml", SaveFilename); + printf("Saving NxuStream XML file to '%s'\r\n", scratch); + NXU::saveCollection(c, fName.CStr(), NXU::FT_BINARY, false, false); + NXU::releaseCollection(c); + + } + + releaseCollection(c); + return 0; +} diff --git a/usr/Src/Core/pVehicle/pDifferential.cpp b/usr/Src/Core/pVehicle/pDifferential.cpp new file mode 100644 index 0000000..6c95e8c --- /dev/null +++ b/usr/Src/Core/pVehicle/pDifferential.cpp @@ -0,0 +1,635 @@ +#include "StdAfx.h" +#include "vtPhysXAll.h" + +#include "pDifferential.h" +#include "pVehicleAll.h" + + +void pDifferential::setToDefault() +{ + + type = 0; + SetRatio(3.95f); + lockingCoeff = 30.0f; + +} +pDifferential::pDifferential(pVehicle *_car) + : pDriveLineComp() +{ + SetName("differential"); + + car=_car; + type=0; + lockingCoeff=0; + powerAngle=coastAngle=0; + clutches=0; + clutchFactor=0; + flags=0; + Reset(); +} +pDifferential::~pDifferential() +{ +} + +void pDifferential::Reset() +{ + torqueIn=0; + torqueOut[0]=torqueOut[1]=0; + torqueBrakingOut[0]=torqueBrakingOut[1]=0; + inertiaIn=0; + inertiaOut[0]=inertiaOut[1]=0; + accIn=0; + accOut[0]=accOut[1]=0; + torqueLock=0; + rotVdriveShaft=0; + + velASymmetric=0; + locked=0; + + engine=0; + wheel[0]=wheel[1]=0; + + pDriveLineComp::Reset(); +} + +float pDifferential::GetTorqueOut(int n) +{ + return torqueOut[n]; +} +float pDifferential::GetBreakTorqueOut(int n) +{ + + return torqueBrakingOut[n]; + +} + + +void pDifferential::Lock(int wheel) +// Lock a side (0 or 1) +// The wheel calls this function as soon as it sees rotational +// velocity reversal (the wheel from moving forward suddenly starts +// moving backward due to (mostly) braking or rolling resistance) +// In CalcForces(), the side can be unlocked again if the reaction +// torques exceed the (potential) braking torque. +{ + locked|=(1<GetInertiaAtDifferential(); + //inertiaOut[0]=wheel[0]->GetRotationalInertia()->x; + //inertiaOut[1]=wheel[1]->GetRotationalInertia()->x; + +#else + inertiaIn=1; + inertiaOut[0]=1; + inertiaOut[1]=1; +#endif + + // Retrieve torques at all ends + // Notice that inside the diff, there can be a ratio. If this is 2 for + // example, the driveshaft will rotate twice as fast as the wheel axles. + +#ifdef ND_DRIVELINE + torqueIn=engine->GetTorqueAtDifferential(); +#else + torqueIn=1; +#endif + + + + //torqueOut[0]=wheel[0]->GetTorqueFeedbackTC().x; + //torqueOut[1]=wheel[1]->GetTorqueFeedbackTC().x; + + + // Retrieve potential braking torque; if bigger than the reaction + // torque, the output will become unlocked. If not, the output is + // locked. + // Note that the braking torque already points in the opposite + // direction of the output (mostly a wheel) rotation. This is contrary + // to Gregor Veble's approach, which only calculates the direction + // in the formulae below. + + + torqueBrakingOut[0]=wheel[0]->GetTorqueBrakingTC().x; + torqueBrakingOut[1]=wheel[1]->GetTorqueBrakingTC().x; + + +#ifdef LTRACE + qdbg(" torqueIn=%f, torqueOut0=%f, 1=%f\n",torqueIn,torqueOut[0],torqueOut[1]); +#endif + + // Proceed to Gregor's naming convention and algorithm + // Determine locking + switch(type) + { + case FREE: + // No locking; both wheels run free + m0=0; + break; + case VISCOUS: +// velASymmetric=wheel[1]->GetRotationV()-wheel[0]->GetRotationV(); + m0=-lockingCoeff*velASymmetric; +#ifdef LTRACE +qdbg(" velASymm=%f, lockCoeff=%f => m0=%f\n",velASymmetric,lockingCoeff,m0); +#endif + break; + case SALISBURY: + // Salisbury diff locks based on the ratio of reaction torques on + // the tires. + // Calculate torque bias ratio + if(fabs(torqueOut[1])>D3_EPSILON) + torqueBiasRatio=torqueOut[0]/torqueOut[1]; + else if(fabs(torqueOut[0])>D3_EPSILON) + torqueBiasRatio=torqueOut[1]/torqueOut[0]; + else + torqueBiasRatio=1; // Both wheels doing pretty much nothing + // Get a number which always has a ratio>1 + if(torqueBiasRatio<1.0)torqueBiasRatioAbs=1.0f/torqueBiasRatio; + else torqueBiasRatioAbs=torqueBiasRatio; + // Is the ratio exceeded? +//xxxx continue here + if(torqueIn>0) + { + // Power + if(torqueBiasRatioAbs>maxBiasRatioPower); + } + m0=0; break; + default: + m0=0; break; + } + m3=torqueIn; // Entails engine braking already +#ifdef LTRACE +qdbg(" torqueIn=%f, locked=%d\n",m3,locked); +#endif + + j1=inertiaOut[0]; + j2=inertiaOut[1]; + j3=inertiaIn; + jw=j1+j2; + jt=jw+j3; + jd=j1-j2; // Inertia difference (of outputs) + // Calculate determinant of 2x2 matrix + det=4.0f*j1*j2+j3*jw; + + m3=torqueIn; + switch(locked) + { + case 0: // No outputs locked + m1=torqueOut[0]+torqueBrakingOut[0]; + m2=torqueOut[1]+torqueBrakingOut[1]; +//qdbg(" m1=%f, m2=%f\n",m1,m2); + break; + case 1: + // Output 0 is locked, output 1 is unlocked + m2=torqueOut[1]+torqueBrakingOut[1]; + m1=(m2*j3-2.0f*m3*j2-m0*(2.0f*j2+j3))/(4.0f*j2+j3); + if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) + locked=0; + break; + case 2: + // Output 1 is locked, output 0 is unlocked + m1=torqueOut[0]+torqueBrakingOut[0]; + m2=(m1*j3-2.0f*m3*j1+m0*(2.0f*j1+j3))/(4.0f*j1+j3); + if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) + locked=0; + break; + case 3: + // Both outputs locked + m1=-m3/2.0f; + m2=m1; + m0=0; + if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) + locked^=1; + if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) + locked^=2; + break; + default: + //qerr("Bug: pDifferential locked not in 0..3 (%d)",locked); + m1=m2=0; + break; + } + mt=m1+m2+m3; + md=m2-m1+m0; + + // Calculate asymmetric acceleration + accASymmetric=md/jw; +#ifdef ND_OLD_NAMES + accASymmetric=(torqueOut[1]-torqueOut[0]+torqueLock)/ + (inertiaOut[0]+inertiaOut[1]); +#endif + + // Calculate total acceleration based on all torques + // (which is in fact the driveshaft rotational acceleration) + accIn=mt/jt; +#ifdef ND_OLD_NAMES + accIn=(torqueIn+torqueOut[0]+torqueOut[1])/ + (inertiaIn+inertiaOut[0]+inertiaOut[1]); +#endif + + // Derive from these the acceleration of the 2 output parts + accOut[1]=accIn+accASymmetric; + accOut[0]=accIn-accASymmetric; + + // Add torque to body because of the accelerating drivetrain + // This gives a bit of the GPL effect where your car rolls when + // you throttle with the clutch disengaged. +/* + float tr=car->GetEngine()->GetTorqueReaction(); + if(tr>0) + { + DVector3 torque(0,0,accIn*inertiaIn*tr); +//qdbg("torque.z=%f\n",torque.z); + car->GetBody()->AddBodyTorque(&torque); + } +*/ + +#ifdef LTRACE + qdbg("inertia: I%f, O %f, %f\n",inertiaIn,inertiaOut[0],inertiaOut[1]); + qdbg("torqueBraking: I%f, O %f, %f\n",0,torqueBrakingOut[0], + torqueBrakingOut[1]); + qdbg("torque: I%f, O %f, %f, locking %f\n",m3,m1,m2,m0); + qdbg("Vel: wheel0=%f, wheel1=%f\n",wheel[0]->GetRotationV(), + wheel[1]->GetRotationV()); + qdbg("Acc: asym %f, in %f, out %f, %f\n",accASymmetric,accIn, + accOut[0],accOut[1]); +#endif +} + + +float pDifferential::CalcLockingTorque() +// Calculates the locking torque of the differential +{ + float m0; + + switch(type) + { + case FREE: + // No locking; both wheels run free + m0=0; + break; + case VISCOUS: + //velASymmetric=wheel[1]->GetRotationV()-wheel[0]->GetRotationV(); + m0=-lockingCoeff*velASymmetric; +#ifdef LTRACE +qdbg(" velASymm=%f, lockCoeff=%f => m0=%f\n",velASymmetric,lockingCoeff,m0); +#endif + break; + case SALISBURY: + // Salisbury diff locks based on the ratio of reaction torques on + // the tires. + // Calculate torque bias ratio + if(fabs(torqueOut[1])>D3_EPSILON) + torqueBiasRatio=torqueOut[0]/torqueOut[1]; + else if(fabs(torqueOut[0])>D3_EPSILON) + torqueBiasRatio=torqueOut[1]/torqueOut[0]; + else + torqueBiasRatio=1; // Both wheels doing pretty much nothing + // Get a number which always has a ratio>1 + if(torqueBiasRatio<1.0)torqueBiasRatioAbs=1.0f/torqueBiasRatio; + else torqueBiasRatioAbs=torqueBiasRatio; + // Is the ratio exceeded? +//xxxx continue here + if(torqueIn>0) + { + // Power + if(torqueBiasRatioAbs>maxBiasRatioPower); + } + m0=0; break; + default: + //qwarn("pDifferential:CalcLockingTorque(); unknown diff type"); + m0=0; break; + } + return m0; +} + +void pDifferential::CalcSingleDiffForces(float torqueIn,float inertiaIn) +// Special version in case there is only 1 differential. +// Differences with regular operating: +// - 'torqueIn' is directly passed in from the driveline root (engine). +// - 'inertiaIn' is directly passed from the driveline (engine's eff. inertia) +// Calculates accelerations of the 3 sides of the differential +// based on incoming torques and inertia's. +// Also unlocks sides (only the wheels can be locked for now) +// if the engine torques exceeds the reaction/braking torque +// (if that side was locked, see Lock()) +{ + // Gregor Veble's naming convention + float j1,j2,j3, // Inertia of output1/output2/input + jw, // Total inertia of wheels + jt, // Total inertia of all attached components + jd; // Difference of wheel inertia's + float m0, // Locking torque + m1, // Output1 torque + m2, // Output2 torque + m3; // Input torque (from the engine probably) + float mt, // Total net torque + md; // Asymmetric torque (?) + float det; + + // Check that everything is ok + if(!engine)return; + if(wheel[0]==0||wheel[1]==0)return; + + // Note that no ratios are used here; the input and outputs + // are geared 1:1:1. This makes the formulas easier. To add + // a differential ratio, the other functions for the input torques + // take care of this. +#ifdef LTRACE +qdbg("RDiff:CalcSingleDiffForces(%.2f)\n",torqueIn); +#endif + // Retrieve current effective inertia + // The base is the driveshaft; the accelerations and torques are + // related to its position in the drivetrain. + + //inertiaIn=engine->GetInertiaAtDifferential(); + //float inertiaIn2 =engine->GetInertiaAtDifferential(); + + + + inertiaOut[0]=wheel[0]->GetInertia(); + inertiaOut[1]=wheel[1]->GetInertia(); + + // Retrieve torques at all ends + // Notice that inside the diff, there can be a ratio. If this is 2 for + // example, the drive shaft will rotate twice as fast as the wheel axles. + + //float torqueIn2 =engine->GetTorqueAtDifferential(); + + + + torqueOut[0]=wheel[0]->torqueFeedbackTC.x; + torqueOut[1]=wheel[1]->torqueFeedbackTC.x; + + + + // Retrieve potential braking torque; if bigger than the reaction + // torque, the output will become unlocked. If not, the output is + // locked. + // Note that the braking torque already points in the opposite + // direction of the output (mostly a wheel) rotation. This is contrary + // to Gregor Veble's approach, which only calculates the direction + // in the formula below. + torqueBrakingOut[0]=wheel[0]->torqueBrakingTC.x; + torqueBrakingOut[1]=wheel[1]->torqueBrakingTC.x; + + + // Proceed to Gregor's naming convention and algorithm + // Determine locking + m0=CalcLockingTorque(); + + + +#ifdef OBS + switch(type) + { + case FREE: + // No locking; both wheels run free + m0=0; + break; + case VISCOUS: + velASymmetric=wheel[1]->GetRotationV()-wheel[0]->GetRotationV(); + m0=-lockingCoeff*velASymmetric; +#ifdef LTRACE +qdbg(" velASymm=%f, lockCoeff=%f => m0=%f\n",velASymmetric,lockingCoeff,m0); +#endif + break; + case SALISBURY: + // Salisbury diff locks based on the ratio of reaction torques on + // the tires. + // Calculate torque bias ratio + if(fabs(torqueOut[1])>D3_EPSILON) + torqueBiasRatio=torqueOut[0]/torqueOut[1]; + else if(fabs(torqueOut[0])>D3_EPSILON) + torqueBiasRatio=torqueOut[1]/torqueOut[0]; + else + torqueBiasRatio=1; // Both wheels doing pretty much nothing + // Get a number which always has a ratio>1 + if(torqueBiasRatio<1.0)torqueBiasRatioAbs=1.0f/torqueBiasRatio; + else torqueBiasRatioAbs=torqueBiasRatio; + // Is the ratio exceeded? +//xxxx continue here + if(torqueIn>0) + { + // Power + if(torqueBiasRatioAbs>maxBiasRatioPower); + } + m0=0; break; + default: + m0=0; break; + } +#endif + + m3=torqueIn; // Entails engine braking already + +#ifdef LTRACE +qdbg(" torqueIn=%f, locked=%d\n",m3,locked); +#endif + + j1=inertiaOut[0]; + j2=inertiaOut[1]; + j3=inertiaIn; + jw=j1+j2; + jt=jw+j3; + jd=j1-j2; // Inertia difference (of outputs) + // Calculate determinant of 2x2 matrix + det=4.0f*j1*j2+j3*jw; + + m3=torqueIn; + switch(locked) + { + case 0: // No outputs locked + m1=torqueOut[0]+torqueBrakingOut[0]; + m2=torqueOut[1]+torqueBrakingOut[1];//qdbg(" m1=%f, m2=%f\n",m1,m2); + break; + case 1: + // Output 0 is locked, output 1 is unlocked + m2=torqueOut[1]+torqueBrakingOut[1]; + m1=(m2*j3-2.0f*m3*j2-m0*(2.0f*j2+j3))/(4.0f*j2+j3); + if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) + locked=0; + break; + case 2: + // Output 1 is locked, output 0 is unlocked + m1=torqueOut[0]+torqueBrakingOut[0]; + m2=(m1*j3-2.0f*m3*j1+m0*(2.0f*j1+j3))/(4.0f*j1+j3); + if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) + locked=0; + break; + case 3: + // Both outputs locked + m1=-m3/2.0f; + m2=m1; + m0=0; + if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) + locked^=1; + if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) + locked^=2; + break; + default: + //qerr("Bug: pDifferential locked not in 0..3 (%d)",locked); + m1=m2=0; + break; + } + mt=m1+m2+m3; + md=m2-m1+m0; + + // Calculate asymmetric acceleration + accASymmetric=md/jw; + + + // Calculate total acceleration based on all torques + // (which is in fact the driveshaft rotational acceleration) + accIn=mt/jt; + + + + // Derive from these the acceleration of the 2 output parts + accOut[1]=accIn+accASymmetric; + accOut[0]=accIn-accASymmetric; + + // Add torque to body because of the accelerating drivetrain + // This gives a bit of the GPL effect where your car rolls when + // you throttle with the clutch disengaged. + /* + float tr=car->GetEngine()->GetTorqueReaction(); + if(tr>0) + { + DVector3 torque(0,0,accIn*inertiaIn*tr); +//qdbg("torque.z=%f\n",torque.z); + car->GetBody()->AddBodyTorque(&torque); + } + */ + +#ifdef LTRACE + qdbg("inertia: I%f, O %f, %f\n",inertiaIn,inertiaOut[0],inertiaOut[1]); + qdbg("torqueBraking: I%f, O %f, %f\n",0,torqueBrakingOut[0],torqueBrakingOut[1]); + qdbg("torque: I%f, O %f, %f, locking %f\n",m3,m1,m2,m0); + qdbg("Vel: wheel0=%f, wheel1=%f\n",wheel[0]->GetRotationV(),wheel[1]->GetRotationV()); + qdbg("Acc: asym %f, in %f, out %f, %f\n",accASymmetric,accIn,accOut[0],accOut[1]); +#endif + + +} + +void pDifferential::Integrate() +// Maintain differential objects rotations +{ + float rotAds; + + // Check that everything is ok + if(!engine)return; + if(wheel[0]==0||wheel[1]==0)return; + + // Driveshaft rotation + rotAds=accIn; + + + if (car->getProcessOptions() & pVPO_Wheel_DiffDirect) + { + rotVdriveShaft+=rotAds*lastStepTimeSec; + } + rotVdriveShaft=(wheel[0]->rotationV.x+wheel[1]->rotationV.x)/2.0f; + +} + + +/* +bool pDifferential::LoadState(QFile *f) +{ + RDriveLineComp::LoadState(f); + f->Read(&rotVdriveShaft,sizeof(rotVdriveShaft)); + f->Read(&locked,sizeof(locked)); + return TRUE; +} +bool pDifferential::SaveState(QFile *f) +{ + RDriveLineComp::SaveState(f); + f->Write(&rotVdriveShaft,sizeof(rotVdriveShaft)); + f->Write(&locked,sizeof(locked)); + return TRUE; +} + +bool pDifferential::Load(QInfo *info,cstring path) +// Read settings from the car file +{ + char buf[256]; + + sprintf(buf,"%s.type",path); + type=info->GetInt(buf); + // Read the ratio + sprintf(buf,"%s.ratio",path); + if(info->PathExists(buf)) + { + SetRatio(info->GetFloat(buf)); + //qdbg("Diff ratio (%s) = %.2f\n",buf,ratio); + } else + { + // Backward compatible (v0.4.9 and before); use old gearbox setting + qwarn("No differential ratio in car.ini; using gearbox.end_ratio instead"); + qwarn("(this is obsolete; use differential.diff.ratio from now on)"); + SetRatio(info->GetFloat("gearbox.end_ratio")); + } + sprintf(buf,"%s.inertia",path); + SetInertia(info->GetFloat(buf)); + + // Type-specific parameters + if(type==VISCOUS) + { + // Viscous locking differential + sprintf(buf,"%s.locking_coeff",path); + lockingCoeff=info->GetFloat(buf); + } else if(type==SALISBURY) + { + // Salisbury (known from GPL) + sprintf(buf,"%s.power_angle",path); + powerAngle=info->GetFloat(buf)/RR_RAD2DEG; + sprintf(buf,"%s.coast_angle",path); + coastAngle=info->GetFloat(buf)/RR_RAD2DEG; + sprintf(buf,"%s.clutches",path); + clutches=info->GetInt(buf); + sprintf(buf,"%s.clutch_factor",path); + clutchFactor=info->GetFloat(buf); + + // Calculate resulting constants + maxBiasRatioPower=cos(powerAngle)*(1.0+2.0*clutches)*clutchFactor; + maxBiasRatioCoast=cos(coastAngle)*(1.0+2.0*clutches)*clutchFactor; + } + return TRUE; +} +*/ \ No newline at end of file diff --git a/usr/Src/Core/pVehicle/pDriveLine.cpp b/usr/Src/Core/pVehicle/pDriveLine.cpp new file mode 100644 index 0000000..c9cf089 --- /dev/null +++ b/usr/Src/Core/pVehicle/pDriveLine.cpp @@ -0,0 +1,508 @@ +#include "StdAfx.h" +#include "pDriveLine.h" + +#include "vtPhysXAll.h" +#include "pVehicle.h" +#include "pGearbox.h" +#include "pDifferential.h" + + +#include + + +/********************** +* Driveline component * +**********************/ +pDriveLineComp::pDriveLineComp() +{ + // Init member variables + parent=0; + child[0]=child[1]=0; + driveLine=0; + name=""; + + inertia=0.01f; + ratio=invRatio=1; + effectiveInertiaDownStream=0; + cumulativeRatio=0; + tReaction=tBraking=tEngine=0; + rotV=rotA=0; +} +pDriveLineComp::~pDriveLineComp() +{ +} + +// +// Attribs +// +void pDriveLineComp::SetParent(pDriveLineComp *_parent) +// Set a parent for this component. Mostly, this is done implicitly +// using AddChild(). +{ + parent=_parent; +} +void pDriveLineComp::SetRatio(float r) +{ + if(fabs(r)0; adjusted to 1",r); + r=1; + } + ratio=r; + // Precalculate inverse ratio for faster calculations later + invRatio=1.0f/r; +} +void pDriveLineComp::Reset() +// Reset variables for a fresh start (like when Shift-R is used) +{ + rotV=rotA=0; +} + +pDriveLineComp *pDriveLineComp::GetChild(int n) +{ + switch(n) + { case 0: return child[0]; + case 1: return child[1]; + default: /*qwarn("RDriveLineComp:GetChild(%d) out of range",n);*/ return 0; + } +} + +void pDriveLineComp::AddChild(pDriveLineComp *comp) +// Add 'comp' as a child +{ + if(!child[0])child[0]=comp; + else if(!child[1])child[1]=comp; + //else qwarn("RDriveLineComp:AddChild() failed; already has 2 children"); + + // Declare us as parent of the child + comp->SetParent(this); +} + + +/***************** +* Precalculation * +*****************/ +void pDriveLineComp::CalcEffectiveInertia() +// Calculate the total effective inertia for this node plus the children +{ + +//qdbg("RDLC:CalcEffectiveInertia() '%s'\n",name.cstr()); + effectiveInertiaDownStream=inertia*cumulativeRatio*cumulativeRatio; + if(child[0]) + { + child[0]->CalcEffectiveInertia(); + effectiveInertiaDownStream+=child[0]->GetEffectiveInertia(); + } + if(child[1]) + { + child[1]->CalcEffectiveInertia(); + effectiveInertiaDownStream+=child[1]->GetEffectiveInertia(); + } +} +void pDriveLineComp::CalcCumulativeRatio() +// Calculate the cumulative ratio for this component and entire tree +{ + cumulativeRatio=ratio; + if(child[0]) + { + child[0]->CalcCumulativeRatio(); + } + if(child[1]) + { + child[1]->CalcCumulativeRatio(); + } + // Take ratio if child[0] only, since only singular links are supported + // (like engine->gear->driveshaft) + if(child[0]) + cumulativeRatio*=child[0]->GetCumulativeRatio(); + //cumulativeRatio*=child[0]->GetRatio(); +} +void pDriveLineComp::CalcReactionForces() +// Calculate reaction forces from the leaves up +{ + tReaction=tBraking=0; + if(child[0]) + { + child[0]->CalcReactionForces(); + tReaction+=child[0]->GetReactionTorque(); + tBraking+=child[0]->GetBrakingTorque(); + } + if(child[1]) + { + child[1]->CalcReactionForces(); + tReaction+=child[1]->GetReactionTorque(); + tBraking+=child[1]->GetBrakingTorque(); + } + // Multiply by the inverse ratio for upstream + tReaction*=invRatio; + tBraking*=invRatio; +} + +// Stub base class function +void pDriveLineComp::CalcForces(){} +// Stub base class function +void pDriveLineComp::CalcAccelerations(){} +// Stub base class function +void pDriveLineComp::Integrate() +{ +//qdbg("RDLC:Integrate() base class\n"); + rotV+=rotA*lastStepTimeSec; + //qdbg(" rotV=%.2f (rotA=%.2f)\n",rotV,rotA); +} + +pDriveLine::pDriveLine(pVehicle *_car) +{ + // Init members + car=_car; + root=0; + preClutchInertia=postClutchInertia=totalInertia=0; + prepostLocked=true; + diffs=0; + + // Clutch defaults + clutchMaxTorque=500; + clutchLinearity=DEFAULT_CLUTCH_LINEARITY; + SetClutchApplication(1); + tClutch=0; + // Handbrake defaults + handbrakeApplication=0; + autoClutch=FALSE; + prepostLocked=FALSE; +} +pDriveLine::~pDriveLine() +{ +} +// Set the root component +void pDriveLine::SetRoot(pDriveLineComp *comp) + +{ + root=comp; +} + +void pDriveLine::Reset() +{ + autoClutch=false; + prepostLocked=false; +} + +void pDriveLine::CalcCumulativeRatios() +{ + if(root) + root->CalcCumulativeRatio(); +} + +void pDriveLine::CalcEffectiveInertiae() +// Calculate all effective inertiae in the driveline +{ + if(root) + root->CalcEffectiveInertia(); +} + +void pDriveLine::CalcPreClutchInertia() +// Calculate all inertia before the clutch (engine) +{ + // Engine should be the root + if(!root) + { + //qwarn("pDriveLine:CalcPreClutchInertia(); no root component"); + return; + } + preClutchInertia=root->GetInertia(); +} + +void pDriveLine::CalcPostClutchInertia() +// Calculate all inertia after the clutch (gearbox, diffs, wheels) +{ + // Check for a driveline to be present + if(!root) + { + //qwarn("pDriveLine:CalcPreClutchInertia(); no root component"); + return; + } + pDriveLineComp *com =root->GetChild(0); + float f = com->GetEffectiveInertia(); + postClutchInertia=root->GetChild(0)->GetEffectiveInertia(); + + // Also calculate total inertia + totalInertia=preClutchInertia+postClutchInertia; + +} + +void pDriveLine::SetClutchApplication(float app) +// Set clutch application. +{ + if(app<0)app=0; else if(app>1.0f)app=1.0f; + // Make it undergo severe linearity; I couldn't get + // a smooth take-off without stalling the engine. + app=clutchLinearity*app+(1.0f-clutchLinearity)*(app*app*app); + clutchApplication=app; + clutchCurrentTorque=app*clutchMaxTorque; +} +void pDriveLine::DbgPrint(XString& s) +{ + //qdbg("Driveline (%s); clutch: app=%.2f, maxT=%.2f, T=%.2f\n",s,clutchApplication,clutchMaxTorque,clutchCurrentTorque); + // Print tree + /* + if(root) + root->DbgPrint(0,s); + */ +} + +/******** +* Input * +********/ +void pDriveLine::SetInput(int ctlClutch,int ctlHandbrake) +// Inputs controller state. May be overruled though is some assisting is on. +{ + + //float a = car->getEngine()->getAuto + // Clutch + bool isAc = IsAutoClutchActive(); + if(IsAutoClutchActive()) + { + // Automatic assist is on; don't accept user input for a while + //SetClutchApplication(car->getEngine()->GetAutoClutch()); + } else + { + // Manual + SetClutchApplication(((float)ctlClutch)/1000.0f); + } + + // Handbrakes + handbrakeApplication=((float)ctlHandbrake)/1000.0f; + if(handbrakeApplication<0)handbrakeApplication=0; + else if(handbrakeApplication>1)handbrakeApplication=1; +} + +/********** +* Physics * +**********/ +// Determine forces throughout the driveline. +// Assumes the wheel reaction forces are already calculated. +void pDriveLine::CalcForces() +{ + + if(root==0||gearbox==0) + { + /*qwarn("pDriveLine:CalcForces(); driveline not built yet");*/ + return; + } + + // In neutral gear the pre and post parts are always unlocked, + // and no clutch torque is applied. + + + if(car->getGearBox()->IsNeutral()) + { + UnlockPrePost(); + //tClutch=0; + clutchCurrentTorque=0; + //goto skip_clutch_calc; + } + + + // Calculate current clutch torque (including torque direction) + if(!IsPrePostLocked()) + { + // Engine is running separately from the rest of the driveline. + // The clutch works to make the velocity of pre-clutch (engine) and + // post-clutch (rest) equal. + float rVel = root->GetRotationVel(); + float rBox = gearbox->GetRotationVel(); + float ratio = gearbox->GetRatio(); + + if(root->GetRotationVel()>gearbox->GetRotationVel()*gearbox->GetRatio()) + { + tClutch=GetClutchCurrentTorque(); + } + else{ + tClutch=-GetClutchCurrentTorque(); + } + + } // else acceleration will be given by the driveline (engine rotates + // along with the rest of the driveline as a single assembly) + + // Spread wheel (leaf) reaction forces all the way to the engine (root) + root->CalcReactionForces(); + + if(IsPrePostLocked()) + { + // Check if pre and post are still locked + float Te,Tr,Tb,Tc; + Te=root->GetEngineTorque(); + Tr=root->GetReactionTorque(); + Tb=root->GetBrakingTorque(); + Tc=GetClutchCurrentTorque(); + + if(fabs(Te-(Tr+Tb))>Tc) + { +//qdbg(" pre-post gets UNLOCKED\n"); + UnlockPrePost(); + } + } // else it will get locked again when velocity reversal happens + // of the engine vs. rest of the drivetrain (=gearbox in angular velocity) + + if(IsSingleDiff()) + { + + // Special case where some optimizations can be done + pDifferential *diff=car->getDifferential(0); +//qdbg("Single diff case:\n"); + if(IsPrePostLocked()) + { + + + float Te,r; + Te=root->GetEngineTorque(); + r=root->GetCumulativeRatio(); +#ifdef LTRACE + qdbg(" Diff gets Te=%.2f * ratio %.2f = %.2f\n",Te,r,Te*r); +#endif + + diff->CalcSingleDiffForces(Te*r,root->GetEffectiveInertia()); + } else + { + + // Engine spins at a different rate from the rest of the driveline + // In this case the clutch fully works on getting the pre- and post- + // clutch angular velocities equal. + // Note that if the clutch is fully depressed (engine totally decoupled + // from the rest of the driveline), this torque will be 0, and the + // postclutch driveline will just rotate freely. +#ifdef LTRACE + qdbg(" SingleDiff and prepost unlocked.\n"); +#endif + + float Tc,r; + Tc=GetClutchTorque(); + r=root->GetCumulativeRatio(); + float a1 = root->GetEffectiveInertia(); + +#ifdef LTRACE + qdbg(" Diff gets Tc=%.2f * ratio %.2f = %.2f\n",Tc,r,Tc*r); +#endif + + diff->CalcSingleDiffForces(Tc*r,root->GetEffectiveInertia()); + + } + } +} +void pDriveLine::CalcAccelerations() +{ + +#ifdef LTRACE + qdbg("pDriveLine::CalcAccelerations()\n"); +#endif + + if(IsSingleDiff()) + { + // Special case with speedier calculations + pDifferential *diff=car->getDifferential(0); + pDriveLineComp *comp; + float acc=diff->GetAccIn(); + if(IsPrePostLocked()) + { + //qdbg("Single diff, prepost LOCKED\n"); + // Everything is decided by the differential acceleration + // Wheels got their acceleration in RWheel::CalcAccelerations() + // Pass acceleration up the tree; mind the ratios + for(comp=diff;comp;comp=comp->GetParent()) + { + comp->SetRotationAcc(acc); + acc*=comp->GetRatio(); +#ifdef LTRACE + qdbg(" comp '%s' acc %.2f (ratio %.2f)\n",comp->GetName(),acc,comp->GetRatio()); +#endif + + } + } else + { + // Separate pre- and postclutch accelerations + // First calculate the engine's acceleration. + root->CalcAccelerations(); + // Rest of the driveline takes its acceleration from the diff + // Wheels got their acceleration in RWheel::CalcAccelerations() + // Pass acceleration up the tree, EXCEPT for the engine; mind the ratios + // May combine this into the loop above by a sentinel component + // which is either '0' or 'root'. (for the PrePostLocked case) + for(comp=diff;comp!=root;comp=comp->GetParent()) + { + comp->SetRotationAcc(acc); + acc*=comp->GetRatio(); + //qdbg(" comp '%s' acc %.2f (ratio %.2f)\n",//comp->GetName(),acc,comp->GetRatio()); + } + } + } +} + +void pDriveLine::Integrate() +{ + + float deltaVel,newDeltaVel; + + // Remember difference between engine and gear rotation + float a = gearbox->GetRotationVel(); + float ab = gearbox->GetRatio(); + deltaVel=root->GetRotationVel()-gearbox->GetRotationVel()*gearbox->GetRatio(); + if(IsPrePostLocked()) + { + // Check for the engine and gearbox (ratio'd) + // to rotate just about equally. + // If not, the driver may have speedshifted without + // applying the clutch. Unfortunately, this is possible + // but should result in damage in the future, since + // you get a lot of gear noise. + if(fabs(deltaVel)>DELTA_VEL_THRESHOLD) + { + + // Unlock pre-post to let things catch up again + UnlockPrePost(); + } + } + +#ifdef LTRACE + + qdbg("rotV: engine=%.3f, gearbox=%.3f\n",root->GetRotationVel(),gearbox->GetRotationVel()); + qdbg(" engine=%p, root=%p, gearbox=%p\n",car->getEngine(),root,gearbox); + qdbg(" rpm=%f\n",car->getEngine()->getRPM()); + + int cGear =car->getGearBox()->GetGear(); + qdbg(" currentGear=%d %s \n",cGear,car->getGearBox()->GetGearName(cGear).CStr()); + +#endif + + + // Engine + if(root)root->Integrate(); + if(gearbox)gearbox->Integrate(); + + if(!IsPrePostLocked()) + { + // Check if gearbox is catching up with engine + newDeltaVel=root->GetRotationVel()-gearbox->GetRotationVel()*gearbox->GetRatio(); +//qdbg("Check lock; oldDV=%.3f, newDV=%.3f\n",deltaVel,newDeltaVel); + if((deltaVel>0&&newDeltaVel<0)|| + (deltaVel<0&&newDeltaVel>0)) + { + +#ifdef LTRACE +qdbg(" RE-LOCKED!\n"); +#endif + + LockPrePost(); + // Force engine and gearbox velocity to be the same +#ifdef LTRACE + qdbg(" engine rotV=%.3f, gearbox rotV=%.3f\n",root->GetRotationVel(),gearbox->GetRotationVel()); +#endif + + float gVel = gearbox->GetRotationVel(); + float gRatio = gearbox->GetRatio(); + float a = gVel * gRatio; + root->SetRotationVel(gearbox->GetRotationVel()*gearbox->GetRatio()); +// root->SetRotationVel(gRatio * gVel); + + } + } +} + + diff --git a/usr/Src/Core/pVehicle/pEngine.cpp b/usr/Src/Core/pVehicle/pEngine.cpp new file mode 100644 index 0000000..7ca2db5 --- /dev/null +++ b/usr/Src/Core/pVehicle/pEngine.cpp @@ -0,0 +1,636 @@ +#include "StdAfx.h" + +#include "vtPhysXAll.h" + +#include "pEngine.h" +#include "pVehicleAll.h" + +#include + + +// Local trace? +//#define LTRACE + +#define DEF_SIZE .25 +#define DEF_MAXRPM 5000 +#define DEF_MAXPOWER 100 +#define DEF_FRICTION 0 +#define DEF_MAXTORQUE 340 // ~ F1 Jos Verstappen + +#define DEF_TORQUE 100 // In case no curve is present + +//#define LTRACE + +// If USE_HARD_REVLIMIT is used, any rpm above the max. RPM +// returns a 0 engine torque. Although this works, it gives quite +// hard rev limits (esp. when in 1st gear). Better is to supply +// a curve which moves down to 0 torque when rpm gets above maxRPM, +// so a more natural (smooth) balance is obtained (and turn +// this define off) + + + +//#define USE_HARD_REVLIMIT + +pEngine::pEngine(pVehicle *_car) + : pDriveLineComp() +{ + SetName("engine"); + ownerVehicle=_car; + driveLine=ownerVehicle->getDriveLine(); + initData(); +} + +pEngine::~pEngine() +{ +} + + + +void pEngine::initData() +// initData all member variables +{ + + flags=0; + size=DEF_SIZE; + + mass=0; + torqueReaction=0; + maxRPM=DEF_MAXRPM; + idleRPM=900; + stallRPM=350; + startRPM=900; + autoClutchRPM=idleRPM*1.5f; + //autoClutch=0; + starterTorque=300; + idleThrottle=0.1f; + throttleRange=1000.0-idleThrottle*1000.0; + friction=0; + brakingCoeff=0; + position.Set(0,0,0); + + maxTorque=0; + throttle=0; + brakes=0; + size = 0.25f; + + + //QDELETE(crvTorque); + + clean(); +} + +void pEngine::clean() +// Reset engine before usage (after Shift-R for example) +{ + torqueReaction=0; + //torqueCurve.clear(); + pDriveLineComp::Reset(); + + // No automatic clutch engaged + //flags&=~AUTOCLUTCH_ACTIVE; + //flags|=AUTOCLUTCH_ACTIVE; + + // Start engine (or not) and make it stable; AFTER RDLC:clean(), since that + // sets the rotational velocity to 0. + if(flags&START_STALLED) + { + // Start with the engine off + EnableStall(); + setRPM(0); + } else + { + // Pre-start engine + DisableStall(); + setRPM(idleRPM); + } +} + + +void pEngine::setRPM(float rpm) +{ + // Convert to radians and seconds + rotV=rpm*2*PI/60.0f; +} + +/* +float pEngine::GetGearRatio(int n) +{ + pLinearInterpolation &ratios = ((pGearBox*)(driveLine->gearbox))->getGearRatios(); + if ( n >=0 && n 1)throttle=1; + else if(throttle<0)throttle=0; + +//qdbg("pEngine:updateUserControl(); ctlT=%d, throttle=%f\n",ctlThrottle,throttle); +//qdbg(" idleThrottle=%f, idleRPM=%f\n",idleThrottle,idleRPM); +//qdbg("pEngine:updateUserControl(ctlClutch=%d)\n",ctlClutch); +//#define ND_AUTO_CLUTCH +//#ifdef ND_AUTO_CLUTCH + // Only update clutch value when the ownerVehicle is not auto-shifting + +#ifdef ND_AUTO_CLUTCH + float ctlClutch = driveLine->GetClutchApplication(); + bool autoShiftStart =true; + if(!autoShiftStart) + { + clutch=((float)ctlClutch)/1000.0f; + if(clutch>1)clutch=1; + else if(clutch<0)clutch=0; + } +//#else + // Pass clutch on to driveline + //driveLine->SetClutchApplication(((float)ctlClutch)/1000.0f); + // Directly set clutch + //clutch=((float)ctlClutch)/1000.0f; + //if(clutch>1)clutch=1; + //else if(clutch<0)clutch=0; +#endif +} + +float pEngine::GetMaxTorque(float rpm) +// Returns the maximum torque generated at 'rpm' +{ + + if ( getVehicle()->getProcessOptions() & pVPO_Engine_UseHardRevlimit) + { + // Clip hard at max rpm (return 0 torque if rpm gets too high) + if(rpm>maxRPM) + return 0; + } + if(!torqueCurve.getSize()) + { + // No curve available, use a less realistic constant torque + return DEF_TORQUE; + } else + { + float t; + // Find normalized torque in RPM-to-torque curve + t=(float)torqueCurve.getValue(rpm); + t = 1 / maxTorque *t; + //qdbg("pEngine: rpm=%.2f => T=%.2f, (curve)maxTorque=%.2f\n",rpm,t,maxTorque); + return maxTorque*t; + } +} +// Returns the minimum torque generated at 'rpm' (engine braking). +float pEngine::GetMinTorque(float rpm) + +{ + // If 0% throttle, this is the minimal torque which is generated + // by the engine + return -brakingCoeff*rpm/60.0f; +} + + +void pEngine::CalcForces() +{ + float minTorque,maxTorque; + float rpm=getRPM(); + static int starterDelay; // Temp crap to avoid multiple starter smps + + + if(starterDelay>0) + starterDelay--; + + // Check starter; this section assumes CalcForces() is called + // only once per simulation step. Although this may not be + // the case in the future, it should not harm that much. + if(IsStalled()) + { + // There's only some engine braking + // Note this skips calculating min/maxTorque + tEngine=GetMinTorque(rpm); + //qdbg("Stalled; check starter=%d\n",RMGR->controls->control[RControls::T_STARTER]->value); + bool starter = true; + if(starter) + { + // Use the starter + tEngine+=starterTorque; + // Raise the starter sample volume + if(starterDelay==0) + { + starterDelay=1000/ownerVehicle->_lastDT; + } + + +//#ifdef LTRACE +// qdbg(" starting; T_starter=%f, tEngine=%f\n",starterTorque,tEngine); +//#endif + + + } +//#ifdef LTRACE +// qdbg("Stalled engine torque: %.3f\n",tEngine); +//#endif + } else + { + // Engine is running + // Calculate minimal torque (if 0% throttle) + minTorque=GetMinTorque(rpm); + + // Calculate maximum torque (100% throttle situation) + maxTorque=GetMaxTorque(rpm); + + // The throttle accounts for how much of the torque is actually + // produced. + // NOTE: The output power then is 2*PI*rps*outputTorque + // (rps=rpm/60; rotations per second). Nothing but a statistic now. + tEngine=(maxTorque-minTorque)*throttle+minTorque; +#ifdef LTRACE + qdbg("minTorque=%f, maxTorque=%.f, throttle=%f => torque=%f\n",minTorque,maxTorque,throttle,tEngine); +#endif + + + } +} +void pEngine::CalcAccelerations() +{ + + + if(!driveLine->IsPrePostLocked()) + { + // Engine moves separately from the rest of the driveLine + rotA=(tEngine-driveLine->GetClutchTorque())/GetInertia(); + } // else rotA is calculated in the driveline (passed up + // from the wheels on to the root - the engine) +} + +void pEngine::Integrate() +// Step the engine. +// Also looks at the stall state (you can kickstart the engine when driving). +{ + float rpm=getRPM(); + + // This is normally done by RDriveLineComp, but avoid the function call + float timeStep= lastStepTimeSec; + + rotV+=rotA*timeStep; + // Deduce state of engine (stalling) + /*if(IsStalled()) + { + // Turning back on? + if(rpm>=startRPM) + { + DisableStall(); + } + } else + { + // Stalling? + if(rpmgetDriveLine()->EnableAutoClutch(); + //flags|=AUTOCLUTCH_ACTIVE; + if(autoClutch<0)autoClutch=0; + else if(autoClutch>1)autoClutch=1; + ownerVehicle->getDriveLine()->SetClutchApplication(autoClutch); + } else + { + // Turn off auto-clutch + ownerVehicle->getDriveLine()->DisableAutoClutch(); + } + + } + +//qdbg(" post rotV=%.2f\n",rotV); +} + + +void pEngine::setToDefault() +{ + torqueCurve.clear(); + + + torqueCurve.insert(500.f, 193.f); + torqueCurve.insert(2000.f, 134.f); + torqueCurve.insert(4000.f, 175.f); + torqueCurve.insert(5000.f, 175.f); + torqueCurve.insert(6000.f, 166.f); + torqueCurve.insert(7000.f, 166.f); + + /* + torqueCurve.insert(466.0f, 0.46f); + torqueCurve.insert(900.0f, 0.75f); + torqueCurve.insert(1466.0f, 0.89f); + torqueCurve.insert(2600.0f, 0.985f); + torqueCurve.insert(3500.0f, 1.0f); + torqueCurve.insert(4466.0f, 0.987f); + torqueCurve.insert(5133.333f,0.97f); + torqueCurve.insert(6933.0f, 0.631f); + torqueCurve.insert(7500.0f, 0.0f); + */ + + + + char buf[128],fname[128]; + position.Set(0,0,0); + size = 0.0f; + maxRPM = 6200; + idleRPM = 700; + mass = 180.0; + + torqueReaction=1.0f; + maxTorque=280.0f; + forceFeedbackScale = 100.0f; + + SetInertia(0.3f); + + timeScale = 1.0f; + rotationalEndFactor = 1.0f; + + + friction=0.01f; + brakingCoeff=0.1f; + starterTorque=25; + stallRPM=100.0f; + startRPM=900; + //autoClutchRPM=1250.0f; + autoClutchRPM=1000.0f; + + + //flags|=AUTOMATIC; + flags|=AUTOCLUTCH_ACTIVE; + //flags|=HAS_STARTER; + + preStep(); + +} + +void pEngine::setTorqueCurve(pLinearInterpolation val) +{ + torqueCurve = val; + preStep(); +} + + +void pEngine::setBrakingCoeff(float val) +{ + brakingCoeff = val; + preStep(); +} + +void pEngine::setFriction(float val) +{ + friction = val; + preStep(); +} +void pEngine::setStartRPM(float val) +{ + startRPM = val; + preStep(); +} +void pEngine::setIdleRPM(float val) +{ + idleRPM = val; + preStep(); +} +void pEngine::setStarterTorque(float val) +{ + starterTorque = val; + preStep(); +} + + +float pEngine::getEndTorqueForWheel(CK3dEntity *wheelReference) +{ + + return 1; +} + +/*void pEngine::SetInertia(float i) +{ + inertia = i; + preStep(); +}*/ +void pEngine::setFlags(int val) +{ + +} + + + + + + + + + + + + +/* +bool pEngine::Load(QInfo *info,cstring path) +// 'path' may be 0, in which case the default "engine" is used +{ + char buf[128],fname[128]; + QInfo *infoCurve; + + if(!path)path="engine"; + + // Location + sprintf(buf,"%s.x",path); + position.x=info->GetFloat(buf); + sprintf(buf,"%s.y",path); + position.y=info->GetFloat(buf); + sprintf(buf,"%s.z",path); + position.z=info->GetFloat(buf); + sprintf(buf,"%s.size",path); + size=info->GetFloat(buf,DEF_SIZE); + + // Physical attribs +#ifdef OBS + sprintf(buf,"%s.rolling_friction_coeff",path); + rollingFrictionCoeff=info->GetFloat(buf); +#endif + sprintf(buf,"%s.mass",path); + mass=info->GetFloat(buf); + + // Power/torque + sprintf(buf,"%s.max_rpm",path); + maxRPM=info->GetFloat(buf,DEF_MAXRPM); + sprintf(buf,"%s.idle_rpm",path); + idleRPM=info->GetFloat(buf,1000); + + // Torque reaction + sprintf(buf,"%s.torque_reaction",path); + torqueReaction=info->GetFloat(buf); + + // Torque curve or constant (curve is preferred) + //sprintf(buf,"%s.constant_torque",path); + sprintf(buf,"%s.max_torque",path); + maxTorque=info->GetFloat(buf,DEF_MAXTORQUE); + crvTorque=new QCurve(); + sprintf(buf,"%s.curve_torque",path); + info->GetString(buf,fname); + + //qdbg("fname_torque='%s', maxTorque=%.2f\n",fname,maxTorque); + if(fname[0]) + { + + infoCurve=new QInfo(RFindFile(fname,ownerVehicle->GetDir())); + crvTorque->Load(infoCurve,"curve"); + QDELETE(infoCurve); + + + } else + { // No torque curve + //QDELETE(crvTorque); + } + + // Check torque curve in that it makes sense and is usable + if(!crvTorque) + { + //qwarn("No torque curve (torque.crv?) present; you really should have one"); + } else + { + // Make sure it ends at 0 (assuming no engine will rev above 100,000 rpm) + if(fabs(crvTorque->GetValue(100000))>D3_EPSILON) + { + //qwarn("The torque curve needs to end at 0 torque (is now %.2f)", crvTorque->GetValue(100000)); + } + } + + sprintf(buf,"%s.inertia.engine",path); + SetInertia(info->GetFloat(buf)); + //inertiaEngine=info->GetFloat(buf); +#ifdef OBS + sprintf(buf,"%s.inertia.final_drive",path); + inertiaDriveShaft=info->GetFloat(buf); +#endif + sprintf(buf,"%s.friction",path); + friction=info->GetFloat(buf,DEF_FRICTION); + sprintf(buf,"%s.braking_coeff",path); + brakingCoeff=info->GetFloat(buf); + + // Starter engine + sprintf(buf,"%s.starter",path); + if(info->GetInt(buf,1)) + flags|=HAS_STARTER; + sprintf(buf,"%s.start_stalled",path); + if(info->GetInt(buf,1)) + flags|=START_STALLED; + sprintf(buf,"%s.starter_torque",path); + starterTorque=info->GetFloat(buf); + sprintf(buf,"%s.stall_rpm",path); + stallRPM=info->GetFloat(buf); + sprintf(buf,"%s.start_rpm",path); + startRPM=info->GetFloat(buf); + sprintf(buf,"%s.autoclutch_rpm",path); + autoClutchRPM=info->GetFloat(buf); + +#ifdef OBS + // Shifting + sprintf(buf,"%s.shifting.automatic",path); + if(info->GetInt(buf)) + flags|=AUTOMATIC; + //qdbg("Autoshift: flags=%d, buf='%s'\n",flags,buf); + sprintf(buf,"%s.shifting.shift_up_rpm",path); + shiftUpRPM=info->GetFloat(buf,3500); + sprintf(buf,"%s.shifting.shift_down_rpm",path); + shiftDownRPM=info->GetFloat(buf,2000); + sprintf(buf,"%s.shifting.time_to_declutch",path); + timeToDeclutch=info->GetInt(buf,500); + sprintf(buf,"%s.shifting.time_to_clutch",path); + timeToClutch=info->GetInt(buf,500); + + // Gearbox + path="gearbox"; // ! + sprintf(buf,"%s.gears",path); + gears=info->GetInt(buf,4); + for(i=0;iGetFloat(buf,1.0); + sprintf(buf,"%s.gear%d.inertia",path,i); + gearInertia[i]=info->GetFloat(buf); + } + sprintf(buf,"%s.end_ratio",path); + endRatio=info->GetFloat(buf,3.0); +#endif + + // Calculate static facts + preStep(); + + return TRUE; +} +*/ + +/* +void pEngine::OnGfxFrame() +{ +} + +void pEngine::DbgPrint(cstring s) +{ +qdbg("pEngine state (%s):\n",s); +qdbg(" rpm=%.2f, stalled: %d, idleThrottle: %.2f, Treaction=%.2f\n", +getRPM(),IsStalled(),idleThrottle,torqueReaction); +} + + +bool pEngine::LoadState(QFile *f) +{ +RDriveLineComp::LoadState(f); +return TRUE; +} +bool pEngine::SaveState(QFile *f) +{ +RDriveLineComp::LoadState(f); +return TRUE; +} +*/ diff --git a/usr/Src/Core/pVehicle/pGearBox.cpp b/usr/Src/Core/pVehicle/pGearBox.cpp new file mode 100644 index 0000000..471aa0c --- /dev/null +++ b/usr/Src/Core/pVehicle/pGearBox.cpp @@ -0,0 +1,307 @@ +#include "StdAfx.h" +#include "pGearbox.h" +#include "vtPhysXAll.h" + +#include "pVehicleAll.h" + +#include + +#define DEF_SIZE .25 +#define DEF_MAXRPM 5000 +#define DEF_MAXPOWER 100 +#define DEF_FRICTION 0 +#define DEF_MAXTORQUE 340 // ~ F1 Jos Verstappen +#define DEF_TORQUE 100 // In case no curve is present +#define USE_HARD_REVLIMIT + + +float pGearBox::GetInertiaForWheel(pWheel2 *w) +// Return effective inertia as seen in the perspective of wheel 'w' +// Takes into account any clutch effects +{ + float totalInertia; + + float inertiaBehindClutch; + float NtfSquared,NfSquared; + //rfloat rotationA; + pWheel *wheel; + int i; + + // Calculate total ratio multiplier; note the multipliers are squared, + // and not just a multiplier for the inertia. See Gillespie's book, + // 'Fundamentals of Vehicle Dynamics', page 33. + NtfSquared=gearRatio[curGear]*endRatio; + NtfSquared*=NtfSquared; + + /* + // Calculate total inertia that is BEHIND the clutch + NfSquared=endRatio*endRatio; + inertiaBehindClutch=gearInertia[curGear]*NtfSquared+inertiaDriveShaft*NfSquared; + + /* + // Add inertia of attached and powered wheels + // This is a constant, so it should be cached actually (except + // when a wheel breaks off) + for(i=0;iGetWheels();i++) + { + wheel=car->GetWheel(i); + if(wheel->IsPowered()&&wheel->IsAttached()) + inertiaBehindClutch+=wheel->GetRotationalInertia()->x; + } + + // Add the engine's inertia based on how far the clutch is engaged + totalInertia=inertiaBehindClutch+clutch*inertiaEngine*NtfSquared;*/ + return totalInertia; +} + +float pGearBox::GetTorqueForWheel(pWheel2 *w) +// Return effective torque for wheel 'w' +// Takes into account any clutch effects +{ + float clutch =car->getDriveLine()->GetClutchApplication(); + + float torque = car->getDifferential(0)->GetTorqueOut(w->differentialSide); + endRatio = car->getEngine()->GetCumulativeRatio(); + + + + + //car->getDriveLine()-> + + + + + + //qdbg("clutch=%f, T=%f, ratio=%f\n",clutch,torque,gearRatio[curGear]*endRatio); + return clutch*torque*gearRatio[curGear]*endRatio; +} + + +void pGearBox::SetGear(int gear) +{ + curGear=gear; + float cRatio = gearRatio[curGear]; + float cInertia = gearInertia[curGear]; + SetRatio(gearRatio[curGear]); + SetInertia(gearInertia[curGear]); + car->PreCalcDriveLine(); +} +void pGearBox::CalcForces() +{ + +} +void pGearBox::Integrate() +// Based on current input values, adjust the engine +{ + int t; + bool ac=true;// RMGR->IsEnabled(RManager::ASSIST_AUTOCLUTCH); + + pDriveLineComp::Integrate(); + + // The shifting process + if(autoShiftStart) + { + + + t=GetPMan()->GetContext()->GetTimeManager()->GetAbsoluteTime()-autoShiftStart; + + if(ac){ + car->getDriveLine()->EnableAutoClutch(); + } + + // We are in a shifting operation + if(curGear!=futureGear) + { + + // We are in the pre-shift phase + if(t>=timeToDeclutch) + { + // Declutch is ready, change gear + SetGear(futureGear); + // Trigger gear shift sample + if(ac && (car->_currentStatus & VS_IsAccelerated) ) + car->getDriveLine()->SetClutchApplication(1.0f); + } else + { + // Change clutch + if(ac && (car->_currentStatus & VS_IsAccelerated) ) + car->getDriveLine()->SetClutchApplication((t*1000/timeToDeclutch)/1000.0f); + } + + } else + { + // We are in the post-shift phase + if(t>=timeToClutch+timeToDeclutch) + { + // Clutch is ready, end shifting process + + // Conclude the shifting process + autoShiftStart=0; + if(ac) + { + + car->getDriveLine()->SetClutchApplication(0.0f); + car->getDriveLine()->DisableAutoClutch(); + } + } else + { + // Change clutch + + if(ac && (car->_currentStatus & VS_IsAccelerated)) + car->getDriveLine()->SetClutchApplication(((t-timeToClutch)*1000/timeToDeclutch)/1000.0f); + + } + } + } +} + +void pGearBox::processFutureGear() +{ + + //qdbg("pGearBox:OnGfxFrame()\n"); + + if(autoShiftStart==0) + { + // No shift in progress; check shift commands from the controllers + if(car->_cShiftStateUp) + { + //qdbg("Shift Up!\n"); + if(curGearGetContext()->GetTimeManager()->GetAbsoluteTime(); + switch(curGear) + { + case 0: futureGear=2; break; // From neutral to 1st + case 1: futureGear=0; break; // From reverse to neutral + default: futureGear=curGear+1; break; + } + } + }else if(car->_cShiftStateDown) + { + autoShiftStart=GetPMan()->GetContext()->GetTimeManager()->GetAbsoluteTime(); + if(curGear!=1) // Not in reverse? + { + switch(curGear) + { + case 0: futureGear=1; break; // From neutral to reverse + case 2: futureGear=0; break; // From 1st to neutral + default: futureGear=curGear-1; break; + } + } + //qdbg("Switch back to futureGear=%d\n",futureGear); + } + } +} + +void pGearBox::setToDefault() +{ + + gears = 6; + + gearRatio[0]=1.0f; + gearInertia[0]=0.0f; + + gearRatio[1]=-3.59f; + gearInertia[1]=0.9f; + + gearRatio[2]=3.61f; + gearInertia[2]=0.13f; + + gearRatio[3]=4.36f; + gearInertia[3]=0.4f; + + gearRatio[4]=1.69f; + gearInertia[4]=0.07f; + + gearRatio[5]=1.29f; + gearInertia[5]=0.05f; + + gearRatio[6]=1.03f; + gearInertia[6]=0.04f; + + gearRatios.insert(0,-3.61f); + gearTensors.insert(0,0.13f); + + gearRatios.insert(1,3.61f); + gearTensors.insert(1,0.13f); + + gearRatios.insert(2,2.36f); + gearTensors.insert(2,0.09f); + + gearRatios.insert(3,1.69f); + gearTensors.insert(3,0.07f); + + + gearRatios.insert(4,1.29f); + gearTensors.insert(4,0.05f); + + gearRatios.insert(5,1.03f); + gearTensors.insert(5,0.04f); + + + autoShiftStart = 0; + timeToClutch=300; + timeToDeclutch=300.0f; + shiftDownRPM= 1110.0f; + shiftUpRPM=5500.0f; + futureGear = 0; + + + + + +} + +pGearBox::pGearBox(pVehicle *_car) +: pDriveLineComp() +{ + SetName("gearbox"); + car=_car; + Reset(); +} +pGearBox::~pGearBox() +{ +} + +void pGearBox::Reset() +// Reset all variables +{ + int i; + + flags=0; + timeToDeclutch=timeToClutch=0; + autoShiftStart=0; + futureGear=0; + for(i=0;i +#include "vtPhysXAll.h" + +#include +#include "pVehicleAll.h" + + +pPacejka::pPacejka() +{ + // Initial vars + a0=a1=a2=a3=a4=a5=a6=a7=a8=a9=a10=a111=a112=a12=a13=0; + b0=b1=b2=b3=b4=b5=b6=b7=b8=b9=b10=0; + c0=c1=c2=c3=c4=c5=c6=c7=c8=c9=c10=c11=c12=c13=c14=c15=c16=c17=0; + + camber=0; + sideSlip=0; + slipPercentage=0; + Fz=0; + + // Output + Fx=Fy=Mz=0; + longStiffness=latStiffness=0; + maxForce.Set(0,0,0); +} +void pPacejka::setToDefault() +{ + //; Pacejka constants + //Lateral coefficients + + a0=1.30000f; + a1=-49.00f; + a2=1216.00f; + a3=1632.00f; + a4=11.00f; + a5=0.00600f; + a6=-0.04000f; + a7=-0.40000f; + a8=0.00300f; + a9=-0.00200f; + + //;a10=0.16000 + + a10=0.f; + a111=-11.00f; + a112=0.04500; + a12=0.00f; + a13=0.0f; + + //;a13=-23.50000 + + //; Longitudinal coefficients + b0=1.57000f; + b1=-48.00f; + b2=1338.00f; + b3=6.80000; + b4=444.00f; + b5=0.00f; + b6=0.00340f; + b7=-0.00800f; + b8=0.66000f; + b9=0.00f; + b10=0.00f; + + //; Aligning moment coefficients + c0=2.46000f; + c1=-2.77000f; + c2=-2.90000f; + c3=0.00f; + c4=-3.60000f; + c5=-0.10000f; + c6=0.00040f; + c7=0.22000f; + c8=-2.31000f; + c9=3.87000f; + c10=0.00070f; + c11=-0.05000f; + c12=-0.00600f; + c13=0.33000f; + c14=-0.04000f; + c15=-0.40000f; + c16=0.09200f; + c17=0.01140f; + + //Statistical data (SR, SA in radians) + /*optimal_slipratio=0.09655 + optimal_slipangle=0.18296 + */ + +} +pPacejka::~pPacejka() +{ +} + + + +/********** +* Physics * +**********/ +void pPacejka::Calculate() +{ + // Calculate long. force (and long. stiffness plus max long. force) + Fx=CalcFx(); + // Calculate lateral force, cornering stiffness and max lateral force + Fy=CalcFy(); + // Aligning moment (force feedback) + Mz=CalcMz(); +} + +float pPacejka::CalcFx() +// Calculates longitudinal force +// From G. Genta's book, page 63 +// Note that the units are inconsistent: +// Fz is in kN +// slipRatio is in percentage (=slipRatio*100=slipPercentage) +// camber and slipAngle are in degrees +// Resulting forces are better defined: +// Fx, Fy are in N +// Mz is in Nm +{ + float B,C,D,E; + float Fx; + float Sh,Sv; + float uP; + float FzSquared; + + // Calculate derived coefficients + FzSquared=Fz*Fz; + C=b0; + uP=b1*Fz+b2; + D=uP*Fz; + + // Avoid div by 0 + if((C>-D3_EPSILON&&C-D3_EPSILON&&D-D3_EPSILON&&C-D3_EPSILON&&D-D3_EPSILON&&a4-D3_EPSILON&&C-D3_EPSILON&&DGetFloat(buf); + sprintf(buf,"%s.a1",path); a1=info->GetFloat(buf); + sprintf(buf,"%s.a2",path); a2=info->GetFloat(buf); + sprintf(buf,"%s.a3",path); a3=info->GetFloat(buf); + sprintf(buf,"%s.a4",path); a4=info->GetFloat(buf); + sprintf(buf,"%s.a5",path); a5=info->GetFloat(buf); + sprintf(buf,"%s.a6",path); a6=info->GetFloat(buf); + sprintf(buf,"%s.a7",path); a7=info->GetFloat(buf); + sprintf(buf,"%s.a8",path); a8=info->GetFloat(buf); + sprintf(buf,"%s.a9",path); a9=info->GetFloat(buf); + sprintf(buf,"%s.a10",path); a10=info->GetFloat(buf); + sprintf(buf,"%s.a111",path); a111=info->GetFloat(buf); + sprintf(buf,"%s.a112",path); a112=info->GetFloat(buf); + sprintf(buf,"%s.a13",path); a13=info->GetFloat(buf); + + // Fy + sprintf(buf,"%s.b0",path); b0=info->GetFloat(buf); + sprintf(buf,"%s.b1",path); b1=info->GetFloat(buf); + sprintf(buf,"%s.b2",path); b2=info->GetFloat(buf); + sprintf(buf,"%s.b3",path); b3=info->GetFloat(buf); + sprintf(buf,"%s.b4",path); b4=info->GetFloat(buf); + sprintf(buf,"%s.b5",path); b5=info->GetFloat(buf); + sprintf(buf,"%s.b6",path); b6=info->GetFloat(buf); + sprintf(buf,"%s.b7",path); b7=info->GetFloat(buf); + sprintf(buf,"%s.b8",path); b8=info->GetFloat(buf); + sprintf(buf,"%s.b9",path); b9=info->GetFloat(buf); + sprintf(buf,"%s.b10",path); b10=info->GetFloat(buf); + + // Mz + sprintf(buf,"%s.c0",path); c0=info->GetFloat(buf); + sprintf(buf,"%s.c1",path); c1=info->GetFloat(buf); + sprintf(buf,"%s.c2",path); c2=info->GetFloat(buf); + sprintf(buf,"%s.c3",path); c3=info->GetFloat(buf); + sprintf(buf,"%s.c4",path); c4=info->GetFloat(buf); + sprintf(buf,"%s.c5",path); c5=info->GetFloat(buf); + sprintf(buf,"%s.c6",path); c6=info->GetFloat(buf); + sprintf(buf,"%s.c7",path); c7=info->GetFloat(buf); + sprintf(buf,"%s.c8",path); c8=info->GetFloat(buf); + sprintf(buf,"%s.c9",path); c9=info->GetFloat(buf); + sprintf(buf,"%s.c10",path); c10=info->GetFloat(buf); + sprintf(buf,"%s.c11",path); c11=info->GetFloat(buf); + sprintf(buf,"%s.c12",path); c12=info->GetFloat(buf); + sprintf(buf,"%s.c13",path); c13=info->GetFloat(buf); + sprintf(buf,"%s.c14",path); c14=info->GetFloat(buf); + sprintf(buf,"%s.c15",path); c15=info->GetFloat(buf); + sprintf(buf,"%s.c16",path); c16=info->GetFloat(buf); + sprintf(buf,"%s.c17",path); c17=info->GetFloat(buf); + + return TRUE; +} +*/ + +/********** +* Physics * +**********/ +/* +bool pPacejka::Load(QInfo *info,cstring path) +// Get parameters from a file +{ + char buf[128]; + + // Fx + sprintf(buf,"%s.a0",path); a0=info->GetFloat(buf); + sprintf(buf,"%s.a1",path); a1=info->GetFloat(buf); + sprintf(buf,"%s.a2",path); a2=info->GetFloat(buf); + sprintf(buf,"%s.a3",path); a3=info->GetFloat(buf); + sprintf(buf,"%s.a4",path); a4=info->GetFloat(buf); + sprintf(buf,"%s.a5",path); a5=info->GetFloat(buf); + sprintf(buf,"%s.a6",path); a6=info->GetFloat(buf); + sprintf(buf,"%s.a7",path); a7=info->GetFloat(buf); + sprintf(buf,"%s.a8",path); a8=info->GetFloat(buf); + sprintf(buf,"%s.a9",path); a9=info->GetFloat(buf); + sprintf(buf,"%s.a10",path); a10=info->GetFloat(buf); + sprintf(buf,"%s.a111",path); a111=info->GetFloat(buf); + sprintf(buf,"%s.a112",path); a112=info->GetFloat(buf); + sprintf(buf,"%s.a13",path); a13=info->GetFloat(buf); + + // Fy + sprintf(buf,"%s.b0",path); b0=info->GetFloat(buf); + sprintf(buf,"%s.b1",path); b1=info->GetFloat(buf); + sprintf(buf,"%s.b2",path); b2=info->GetFloat(buf); + sprintf(buf,"%s.b3",path); b3=info->GetFloat(buf); + sprintf(buf,"%s.b4",path); b4=info->GetFloat(buf); + sprintf(buf,"%s.b5",path); b5=info->GetFloat(buf); + sprintf(buf,"%s.b6",path); b6=info->GetFloat(buf); + sprintf(buf,"%s.b7",path); b7=info->GetFloat(buf); + sprintf(buf,"%s.b8",path); b8=info->GetFloat(buf); + sprintf(buf,"%s.b9",path); b9=info->GetFloat(buf); + sprintf(buf,"%s.b10",path); b10=info->GetFloat(buf); + + // Mz + sprintf(buf,"%s.c0",path); c0=info->GetFloat(buf); + sprintf(buf,"%s.c1",path); c1=info->GetFloat(buf); + sprintf(buf,"%s.c2",path); c2=info->GetFloat(buf); + sprintf(buf,"%s.c3",path); c3=info->GetFloat(buf); + sprintf(buf,"%s.c4",path); c4=info->GetFloat(buf); + sprintf(buf,"%s.c5",path); c5=info->GetFloat(buf); + sprintf(buf,"%s.c6",path); c6=info->GetFloat(buf); + sprintf(buf,"%s.c7",path); c7=info->GetFloat(buf); + sprintf(buf,"%s.c8",path); c8=info->GetFloat(buf); + sprintf(buf,"%s.c9",path); c9=info->GetFloat(buf); + sprintf(buf,"%s.c10",path); c10=info->GetFloat(buf); + sprintf(buf,"%s.c11",path); c11=info->GetFloat(buf); + sprintf(buf,"%s.c12",path); c12=info->GetFloat(buf); + sprintf(buf,"%s.c13",path); c13=info->GetFloat(buf); + sprintf(buf,"%s.c14",path); c14=info->GetFloat(buf); + sprintf(buf,"%s.c15",path); c15=info->GetFloat(buf); + sprintf(buf,"%s.c16",path); c16=info->GetFloat(buf); + sprintf(buf,"%s.c17",path); c17=info->GetFloat(buf); + + return TRUE; +} +*/ \ No newline at end of file diff --git a/usr/Src/Core/pVehicle/pSteer.cpp b/usr/Src/Core/pVehicle/pSteer.cpp new file mode 100644 index 0000000..e309ca2 --- /dev/null +++ b/usr/Src/Core/pVehicle/pSteer.cpp @@ -0,0 +1,128 @@ +#include "StdAfx.h" +#include "pVehicleAll.h" + +// Paint the stub wheel? +//#define DO_PAINT_STUB + +#define DEF_LOCK 2 +#define DEF_RADIUS .20 +#define DEF_XA 20 + +// Input scaling +//#define MAX_INPUT 1000 + +void pVehicleSteer::setToDefault() +{ + + radius = 10.0; + xa = 0.0f; + lock = 80.0f; +} + +pVehicleSteer::pVehicleSteer(pVehicle *_car) +{ + car=_car; + angle=0; + lock=5; + xa=0; + position.Set(0,0,0); + radius=DEF_RADIUS; + axisInput=0; +} +pVehicleSteer::~pVehicleSteer() +{ + +} + +/* +bool pVehicleSteer::Load(QInfo *info,cstring path) +// 'path' may be 0, in which case the default "steer" is used +{ + char buf[128]; + + if(!path)path="steer"; + + // Location + sprintf(buf,"%s.x",path); + position.x=info->GetFloat(buf); + sprintf(buf,"%s.y",path); + position.y=info->GetFloat(buf); + sprintf(buf,"%s.z",path); + position.z=info->GetFloat(buf); + sprintf(buf,"%s.radius",path); + radius=info->GetFloat(buf,DEF_RADIUS); + sprintf(buf,"%s.xa",path); + xa=info->GetFloat(buf,DEF_XA); + + // Physical attribs + sprintf(buf,"%s.lock",path); + lock=info->GetFloat(buf,DEF_LOCK)/RR_RAD_DEG_FACTOR; + + // Model (was new'ed in the ctor) + model->Load(info,path); + if(!model->IsLoaded()) + { + // Stub gfx + quad=gluNewQuadric(); + } +//qdbg("RSteer: r=%f, xa=%f\n",radius,xa); + return TRUE; +} +*/ +/******* +* Dump * +*******/ +/* +bool RSteer::LoadState(QFile *f) +{ + f->Read(&angle,sizeof(angle)); + // 'axisInput'? + return TRUE; +} +bool RSteer::SaveState(QFile *f) +{ + f->Write(&angle,sizeof(angle)); + return TRUE; +} +*/ +/********** +* Attribs * +**********/ + +/******** +* Paint * +********/ + +/********** +* Animate * +**********/ +void pVehicleSteer::Integrate() +{ +//qdbg("RSteer: steerPos=%d => angle=%f deg\n",axisInput,angle*RR_RAD_DEG_FACTOR); +} + +/******** +* Input * +********/ +void pVehicleSteer::SetInput(int steerPos) +// 'steerPos' is the angle of the input steering wheel +// ranging from -1000..+1000 +{ + float a; + + // Clip + if(steerPos<-1000) + steerPos=-1000; + else if(steerPos>1000) + steerPos=1000; + + axisInput=steerPos; + + // Take controller position + a=((float)axisInput)*lock/1000.0; +//qdbg("RSteer: axisInput=%d, a=%f,lock=%f\n",axisInput,a,lock); + // Set this directly as the steering wheel's angles + // But notice that because of counterclockwise angles being >0, + // the sign is reversed + angle=a; +} diff --git a/usr/Src/Core/pVehicle/pVTireFunction.cpp b/usr/Src/Core/pVehicle/pVTireFunction.cpp new file mode 100644 index 0000000..b0143b6 --- /dev/null +++ b/usr/Src/Core/pVehicle/pVTireFunction.cpp @@ -0,0 +1,88 @@ +#include +#include "vtPhysXAll.h" + +#include "pVTireFunction.h" + + pTireFunction::pTireFunction() +{ + setToDefault(); +} + + void pTireFunction::setToDefault() +{ + extremumSlip = 1.0f; + extremumValue = 0.02f; + asymptoteSlip = 2.0f; + asymptoteValue = 0.01f; + stiffnessFactor = 1000000.0f; //quite stiff by default. + xmlLink =0; + +} + + bool pTireFunction::isValid() const +{ + if(!(0.0f < extremumSlip)) return false; + if(!(extremumSlip < asymptoteSlip)) return false; + if(!(0.0f < extremumValue)) return false; + if(!(0.0f < asymptoteValue)) return false; + if(!(0.0f <= stiffnessFactor)) return false; + + return true; +} + + + float pTireFunction::hermiteEval(float t) const +{ + + // This fix for TTP 3429 & 3675 is from Sega. + // Assume blending functions (look these up in a graph): + // H0(t) = 2ttt - 3tt + 1 + // H1(t) = -2ttt + 3tt + // H2(t) = ttt - 2tt + t + // H3(t) = ttt - tt + + float v = NxMath::abs(t); + float s = (t>=0) ? 1.0f : -1.0f; + + float F; + + if(v +#include "vtPhysXAll.h" + +#include "pVehicleMotor.h" +#include "pVehicleGears.h" + + +#include "pGearbox.h" + + +#include +#include "NxArray.h" + +#include "virtools/vtTools.h" + + + + +int pVehicle::_calculateCurrentStatus() +{ + + int result = 0; + + //---------------------------------------------------------------- + // + // is moving ? + // + { + + _computeLocalVelocity(); + if ( NxMath::abs(_localVelocity.z) > 0.01f) + result |=VS_IsMoving; + + if (result & VS_IsMoving) + { + + if(_localVelocity.z > 0.0f) + result|=VS_IsRollingForward; + + if(_localVelocity.z < 0.0f) + result|=VS_IsRollingBackward; + } + } + NxVec3 _loc = _localVelocity; + //---------------------------------------------------------------- + // + // is accelerated ? + // + + if ( _cAcceleration > 0.1f ) + result |=VS_IsAcceleratedForward; + + if ( _cAcceleration < 0.0f ) + result |=VS_IsAcceleratedBackward; + + if ( (result & VS_IsAcceleratedForward) || (result & VS_IsAcceleratedBackward) ) + result |=VS_IsAccelerated; + + //---------------------------------------------------------------- + // + // is Braking ? + // + if ( (result & VS_IsMoving ) ) + { + if ( _localVelocity.z > 0.0f && ( result & VS_IsAcceleratedBackward ) ) + { + result |=VS_IsBraking; + } + + if ( _localVelocity.z < 0.0f && (result & VS_IsAcceleratedForward ) ) + { + result |=VS_IsBraking; + } + } + + //---------------------------------------------------------------- + // + // is steering + // + if( XAbs(_cSteering) > 0.01f ) + result|=VS_IsSteering; + + //---------------------------------------------------------------- + // + // is falling + handbrake + // + + _nbNotTouching =0; + _nbTouching =0; + _nbHandbrakeOn =0; + + int nbWheels = _wheels.size(); + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if (!wheel->hasGroundContact()) + { + _nbNotTouching++; + } else { + _nbTouching++; + } + + if(_cHandbrake && wheel->getWheelFlag(WF_AffectedByHandbrake)) + { + _nbHandbrakeOn++; + } + } + if (_nbNotTouching == _wheels.size()) + result |= VS_IsFalling; + + if (_cHandbrake && _nbHandbrakeOn ) + { + result|=VS_Handbrake; + } + + + /* + if ( !(result & VS_IsBraking) ) + { + mBreakLastFrame = false; + mTimeBreaking = 0.0f; + } + */ + + _accelerationPedal = _cAcceleration; + return result; +} + + + + +void pVehicle::updateControl(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) +{ + setControlState(E_VCS_ACCELERATION,acceleration); + setControlState(E_VCS_HANDBRAKE,handBrake); + setControlState(E_VCS_STEERING,steering); + setControlMode(E_VCS_ACCELERATION,analogAcceleration ? E_VCSM_ANALOG : E_VCSM_DIGITAL); + setControlMode(E_VCS_STEERING, analogSteering ? E_VCSM_ANALOG : E_VCSM_DIGITAL); + + +} +void pVehicle::control(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) +{ + + if (steering != 0 || acceleration != 0 || handBrake) + getActor()->wakeUp(0.05); + + return; + + _controlSteering(steering, analogSteering); + _computeLocalVelocity(); + + NxVec3 locVel = _localVelocity; + float lcx = locVel.x; + float lcz = locVel.z; + + + float test = _localVelocity.z * acceleration < ( NxMath::sign(-acceleration) ); + float test2 = _localVelocity.z * acceleration < ( -0.1f ); + float test3 = XAbs(_localVelocity.z) * acceleration < ( -0.1f ); + + + if (!_braking || _releaseBraking) + { + //_braking = _localVelocity.x * acceleration < (-0.1f /** NxMath::sign(-acceleration) */); + _braking = _localVelocity.z * acceleration < ( -0.1 /*NxMath::sign(acceleration) */ ); + + //_braking = _localVelocity.z * acceleration < ( NxMath::sign(acceleration)); + _releaseBraking = false; + } + + if(_handBrake != handBrake) + { + _handBrake = handBrake; + _brakePedalChanged; + } + //printf("Braking: %s, Handbrake: %s\n", _braking?"true":"false", handBrake?"true":"false"); + _controlAcceleration(acceleration, analogAcceleration); +} + + + + +pWheel*pVehicle::getWheel(CK3dEntity *wheelReference) +{ + + if (!wheelReference) + { + return NULL; + } + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if (wheel->getEntID() == wheelReference->GetID()) + { + return wheel; + } + } + return NULL; +} +void pVehicle::handleContactPair(NxContactPair* pair, int carIndex) +{ + NxContactStreamIterator i(pair->stream); + + while(i.goNextPair()) + { + NxShape * s = i.getShape(carIndex); + + while(i.goNextPatch()) + { + const NxVec3& contactNormal = i.getPatchNormal(); + + while(i.goNextPoint()) + { + //user can also call getPoint() and getSeparation() here + + const NxVec3& contactPoint = i.getPoint(); + + //add forces: + + //assuming front wheel drive we need to apply a force at the wheels. + if (s->is(NX_SHAPE_CAPSULE) && s->userData != NULL) { + //assuming only the wheels of the car are capsules, otherwise we need more checks. + //this branch can't be pulled out of loops because we have to do a full iteration through the stream + + + NxQuat local2global = s->getActor().getGlobalOrientationQuat(); + /* + NxWheel* w = (NxWheel*)s->userData; + if (!w->getWheelFlag(E_WF_USE_WHEELSHAPE)) + { + NxWheel1 * wheel = static_cast(w); + wheel->contactInfo.otherActor = pair.actors[1-carIndex]; + wheel->contactInfo.contactPosition = contactPoint; + + wheel->contactInfo.contactPositionLocal = contactPoint; + wheel->contactInfo.contactPositionLocal -= _bodyActor->getGlobalPosition(); + local2global.inverseRotate(wheel->contactInfo.contactPositionLocal); + + wheel->contactInfo.contactNormal = contactNormal; + if (wheel->contactInfo.otherActor->isDynamic()) + { + NxVec3 globalV = s->getActor().getLocalPointVelocity(wheel->getWheelPos()); + globalV -= wheel->contactInfo.otherActor->getLinearVelocity(); + local2global.inverseRotate(globalV); + wheel->contactInfo.relativeVelocity = globalV.x; + //printf("%2.3f (%2.3f %2.3f %2.3f)\n", wheel->contactInfo.relativeVelocity, + // globalV.x, globalV.y, globalV.z); + } + else + { + NxVec3 vel = s->getActor().getLocalPointVelocity(wheel->getWheelPos()); + local2global.inverseRotate(vel); + wheel->contactInfo.relativeVelocity = vel.x; + wheel->contactInfo.relativeVelocitySide = vel.z; + } + NX_ASSERT(wheel->hasGroundContact()); + //printf(" Wheel %x is touching\n", wheel); + } + */ + } + } + } + } + //printf("----\n"); +} +float pVehicle::_computeAxisTorqueV2() +{ + if(_vehicleMotor != NULL) + { + NxReal rpm = _computeRpmFromWheels(); + NxReal motorRpm = _computeMotorRpm(rpm); + _vehicleMotor->setRpm(motorRpm); + float acc = _accelerationPedal; + NxReal torque = _accelerationPedal * _vehicleMotor->getTorque(); + NxReal v = getActor()->getLinearVelocity().magnitude(); + + /* + printf("v: %2.3f m/s (%2.3f km/h)\n", v, v*3.6f); + printf("rpm %2.3f, motorrpm %2.3f, torque %2.3f, realtorque %2.3f\n", + rpm, motorRpm, torque, torque*_getGearRatio()*_differentialRatio*_transmissionEfficiency); + */ + return torque * _getGearRatio() * _differentialRatio * _transmissionEfficiency; + } else { + _computeRpmFromWheels(); + return _cAcceleration * _motorForce; + } +} +float pVehicle::_computeRpmFromWheels() +{ + NxReal wheelRpms = 0; + NxI32 nbWheels = 0; + int nbAcc=0; + int nbNotAcc=0; + + int s = _wheels.size(); + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if (wheel->getWheelFlag(WF_Accelerated)) + { + nbWheels++; + wheelRpms += wheel->getRpm(); + } + + + } + return wheelRpms / (NxReal)nbWheels; +} + + +float pVehicle::_getGearRatio() +{ + if(_vehicleGears == NULL) + { + return 1; + } else { + return _vehicleGears->getCurrentRatio(); + } +} +void pVehicle::gearUp() +{ + if (_vehicleGears) + { + printf("Changing gear from %d to", _vehicleGears->getGear()); + _vehicleGears->gearUp(); + printf(" %d\n", _vehicleGears->getGear()); + } else { + printf("gearUp not supported if no gears available\n"); + } +} +void pVehicle::gearDown() +{ + if(_vehicleGears) + { + printf("Changing gear from %d to", _vehicleGears->getGear()); + _vehicleGears->gearDown(); + printf(" %d\n", _vehicleGears->getGear()); + } else { + printf("gearDown not supported if no gears available\n"); + } +} + +void pVehicle::setAutomaticMode(bool autoMode) +{ + mAutomaticMode=autoMode; + +} +float pVehicle::_computeMotorRpm(float rpm) +{ + NxReal temp = _getGearRatio() * _differentialRatio; + NxReal motorRpm = rpm * temp; + NxI32 change = -1; + if(_vehicleMotor) + { + NxI32 change; + if(_vehicleGears && (change = _vehicleMotor->changeGears(_vehicleGears, 0.2f))) + { + change = _vehicleMotor->changeGears(_vehicleGears, 0.2f); + if(change == 1 && mAutomaticMode ) + { + gearUp(); + } else { + NX_ASSERT(change == -1); + gearDown(); + } + } + temp = _getGearRatio() * _differentialRatio; + motorRpm = NxMath::max(rpm * temp, _vehicleMotor->getMinRpm()); + } + return motorRpm; +} +void pVehicle::_updateRpms() +{ + NxReal rpm = _computeRpmFromWheels(); + if(_vehicleMotor != NULL) + { + NxReal motorRpm = _computeMotorRpm(rpm); + _vehicleMotor->setRpm(motorRpm); + } +} +NxActor* pVehicle::getActor(){ return mActor; } + + + +float pVehicle::getDriveVelocity() +{ + return NxMath::abs(_localVelocity.x); +} + +const pWheel*pVehicle::getWheel(int i) +{ + NX_ASSERT(i < _wheels.size()); + return _wheels[i]; + +} + + + + + + +void pVehicle::_computeLocalVelocity() +{ + _computeMostTouchedActor(); + NxVec3 relativeVelocity; + if (_mostTouchedActor == NULL || !_mostTouchedActor->isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - _mostTouchedActor->getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + NxQuat global2Local; + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + char master[512]; + + //sprintf(master,"Velocity: %2.3f %2.3f %2.3f\n", _localVelocity.x, _localVelocity.y, _localVelocity.z); + //OutputDebugString(master); +} +void pVehicle::_controlSteering(float steering, bool analogSteering) +{ + + if(analogSteering) + { + _steeringWheelState = steering; + } else if (NxMath::abs(steering) > 0.0001f) { + _steeringWheelState += NxMath::sign(steering) * getDigitalSteeringDelta(); + } else if (NxMath::abs(_steeringWheelState) > 0.0001f) { + _steeringWheelState -= NxMath::sign(_steeringWheelState) * getDigitalSteeringDelta(); + } + _steeringWheelState = NxMath::clamp(_steeringWheelState, 1.f, -1.f); +} + +void pVehicle::_computeMostTouchedActor() +{ + std::map actors; + typedef std::map Map; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + NxActor* curActor = _wheels[i]->getTouchedActor(); + Map::iterator it = actors.find(curActor); + if (it == actors.end()) + { + actors[curActor] = 1; + } else { + it->second++; + } + } + + NxU32 count = 0; + _mostTouchedActor = NULL; + for(Map::iterator it = actors.begin(); it != actors.end(); ++it) + { + if(it->second > count) + { + count = it->second; + _mostTouchedActor = it->first; + } + } +} + + +int pVehicle::initWheels(int flags) +{ + getWheels().clear(); + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + pWheel *wheel = sinfo->wheel; + pWheel2* wheel2 = (pWheel2*)wheel; + NxWheelShape *wShape = wheel2->getWheelShape(); + wheel2->setEntity(static_cast(GetPMan()->GetContext()->GetObject(wheel2->getEntID()))); + if (!wShape) continue; + if (wheel2->getWheelFlag(WF_VehicleControlled) ) + { + int& pOptions = getProcessOptions(); + wheel2->setProcessOptions(pOptions); + + if ( wShape->getWheelFlags() & NX_WF_AXLE_SPEED_OVERRIDE ) + wheel2->_createInternalContactModifyCallback(); + + getWheels().push_back(wheel); + wheel2->setVehicle(this); + + + } + } + } + } + + return getWheels().size(); + + + /* + int result = 0 ; + + if (!getBody() || !getBody()->isValid() ) + { + return result; + } + + getWheels().clear(); + + + CK3dEntity* subEntity = NULL; + while (subEntity= getBody()->GetVT3DObject()->HierarchyParser(subEntity) ) + { + if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) + { + pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + if (subDescr->flags & BF_SubShape) + { + if (subDescr->hullType == HT_Wheel) + { + + if (subEntity->HasAttribute(GetPMan()->att_wheelDescr )) + { + CKParameter *par = subEntity->GetAttributeParameter(GetPMan()->att_wheelDescr ); + if (par) + { + pWheelDescr *wDescr = pFactory::Instance()->createWheelDescrFromParameter(par); + if (wDescr) + { + pWheel *wheel = pFactory::Instance()->createWheel(getBody(),*wDescr); + if (wheel) + { + NxWheelShape *wShape = static_cast(getBody()->_getSubShapeByEntityID(subEntity->GetID())); + + if(wDescr->wheelFlags & E_WF_USE_WHEELSHAPE) + { + pWheel2 *wheel2 = static_cast(wheel); + if (wheel2) + { + if(wShape) + wheel2->setWheelShape(wShape); + + } + } + wheel->setEntID(subEntity->GetID()); + getWheels().push_back(wheel); +// subEntity->SetParent(NULL); + + } + } + } + } + } + } + } + } + + + + return getWheels().size(); + */ +} + +void pVehicle::findDifferentialWheels(int& wheel1Index,int& wheel2Index) +{ + pWheel *wheel1 = NULL; + pWheel* wheel2 = NULL; + wheel1 = wheel2 = 0; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + + + pWheel *cW = _wheels[i]; + + if (cW->getWheelFlag(WF_AffectedByDifferential)) + { + if (!wheel1){ + wheel1 = cW; wheel1Index=i; } + else{ + wheel2 = cW;wheel2Index=i; } + } + } + if (!wheel1) + { + xWarning("couldn't find first differential wheel"); + wheel1Index = -1; + } + + if (!wheel2) + { + xWarning("couldn't find second differential wheel"); + wheel2Index = -1; + } +} + +pVehicle::pVehicle() +{ + + flags = 0; + + motorTorque = breakTorque = 0.0f; + + +} +void pVehicle::setControlState(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) +{ + _cAcceleration = acceleration; + _cSteering = steering; + + _cAnalogAcceleration = analogAcceleration; + _cAnalogSteering = analogSteering; + _cHandbrake = handBrake; + +} +pVehicle::pVehicle(pVehicleDesc descr,CK3dEntity *referenceObject) : xEngineObjectAssociation(referenceObject,referenceObject->GetID()) +{ + _digitalSteeringDelta = descr.digitalSteeringDelta; + _steeringSteerPoint = descr.steeringSteerPoint; + _steeringTurnPoint = descr.steeringTurnPoint; + _steeringMaxAngleRad = NxMath::degToRad(descr.steeringMaxAngle); + _transmissionEfficiency = descr.transmissionEfficiency; + _differentialRatio = descr.differentialRatio; + _maxVelocity = descr.maxVelocity; + _motorForce = descr.motorForce; + + _cSteering = 0.0f; + _cAcceleration = 0.0f; + _cAnalogAcceleration = false; + _cAnalogSteering = false; + _cHandbrake = false; + mAutomaticMode = true; + + setBody(descr.body); + + _vehicleMotor = NULL; + _vehicleGears = NULL; + steer = NULL; + + //---------------------------------------------------------------- + // + // Break settings + // + + mBreakLastFrame = false; + mTimeBreaking = 0.0f; + mBrakeMediumThresold = 1.5f; + mBrakeHighThresold = 3.0f; + + mBreakPressures[BL_Small] = 0.1f; + mBreakPressures[BL_Medium] = 0.3f; + mBreakPressures[BL_High] = 1.0f; + + useBreakTable = false; + + mSmallBrakeTable.brakeEntries[0] = 10.0f; + mSmallBrakeTable.brakeEntries[1] = 20.0f; + mSmallBrakeTable.brakeEntries[2] = 30.0f; + mSmallBrakeTable.brakeEntries[3] = 40.0f; + mSmallBrakeTable.brakeEntries[4] = 50.0f; + mSmallBrakeTable.brakeEntries[5] = 100.0f; + mSmallBrakeTable.brakeEntries[6] = 200.0f; + mSmallBrakeTable.brakeEntries[7] = 400.0f; + mSmallBrakeTable.brakeEntries[8] = 1000.0f; + mSmallBrakeTable.brakeEntries[9] = 1000.0f; + + mMediumBrakeTable.brakeEntries[0] = 400.0f; + mMediumBrakeTable.brakeEntries[1] = 450.0f; + mMediumBrakeTable.brakeEntries[2] = 550.0f; + mMediumBrakeTable.brakeEntries[3] = 650.0f; + mMediumBrakeTable.brakeEntries[4] = 725.0f; + mMediumBrakeTable.brakeEntries[5] = 900.0f; + mMediumBrakeTable.brakeEntries[6] = 1050.0f; + mMediumBrakeTable.brakeEntries[7] = 1000.0f; + mMediumBrakeTable.brakeEntries[8] = 1000.0f; + + mHighBrakeTable.brakeEntries[0] = 700.0f; + mHighBrakeTable.brakeEntries[1] = 775.0f; + mHighBrakeTable.brakeEntries[2] = 950.0f; + mHighBrakeTable.brakeEntries[3] = 1100.0f; + mHighBrakeTable.brakeEntries[4] = 1200.0f; + mHighBrakeTable.brakeEntries[5] = 1250.0f; + mHighBrakeTable.brakeEntries[6] = 1500.0f; + mHighBrakeTable.brakeEntries[7] = 2000.0f; + mHighBrakeTable.brakeEntries[8] = 1000.0f; + mHighBrakeTable.brakeEntries[9] = 1000.0f; + + breakConditionLevels[BC_NoUserInput]=BL_Small; + breakConditionLevels[BC_DirectionChange]=BL_High; + breakConditionLevels[BC_Handbrake]=BL_Medium; + breakConditionLevels[BC_UserBreak]=BL_Medium; + + + motorTorque = breakTorque = 0.0F; + + overrideMask = 0; + callMask.set( CB_OnPreProcess , true); + callMask.set( CB_OnPostProcess, true); + + preScript = postScript = 0; + + processOptions = 0; + + //setProcessOptions(GetPMan()->getProcessOptions()); + +} + + +pVehicleDesc::pVehicleDesc() //constructor sets to default +{ + setToDefault(); +} + +void pVehicleDesc::setToDefault() +{ + userData = NULL; + transmissionEfficiency = 1.0f; + differentialRatio = 1.0f; + maxVelocity = 80; + motorForce = 100.0f; + + body = NULL; + gearDescription = NULL;//new pVehicleGearDesc(); + motorDescr = NULL;//new pVehicleMotorDesc(); + steeringMaxAngle = 30; + steeringSteerPoint = VxVector(0,0,0); + steeringTurnPoint = VxVector(0,0,0); + digitalSteeringDelta = 0.04f; + processFlags = 0; + +} + + +bool pVehicleDesc::isValid() const +{ + /*for (NxU32 i = 0; i < carWheels.size(); i++) { + if (!carWheels[i]->isValid()) + return false; + } + */ + if (mass < 0) + return false; + + return true; +} + + +void pVehicle::setControlState(int parameter,float value) +{ + + + switch (parameter) + { + + case E_VCS_GUP: + _cShiftStateUp = (int)value; + break; + + case E_VCS_GDOWN: + _cShiftStateDown = (int)value; + break; + case E_VCS_ACCELERATION: + if (_cAnalogSteering == 0.0f) + { + xWarning("no Acc"); + } + _cAcceleration = value; + break; + + case E_VCS_STEERING: + _cSteering = value; + break; + + case E_VCS_HANDBRAKE: + _cHandbrake= (int)value; + break; + } +} + +void pVehicle::setControlMode(int parameter,int mode) +{ + switch (parameter) + { + case E_VCS_ACCELERATION: + _cAnalogAcceleration = (mode == E_VCSM_ANALOG) ? true : false; + break; + + case E_VCS_STEERING: + _cAnalogSteering = (mode == E_VCSM_ANALOG) ? true : false; + break; + } +} + +float pVehicle::_computeAxisTorque() +{ + if(_vehicleMotor != NULL) + { + NxReal rpm = _computeRpmFromWheels(); + NxReal motorRpm = _computeMotorRpm(rpm); + _vehicleMotor->setRpm(motorRpm); + NxReal torque = _accelerationPedal * _vehicleMotor->getTorque(); + NxReal v = getActor()->getLinearVelocity().magnitude(); + //printf("v: %2.3f m/s (%2.3f km/h)\n", v, v*3.6f); + //printf("rpm %2.3f, motorrpm %2.3f, torque %2.3f, realtorque %2.3f\n", + // rpm, motorRpm, torque, torque*_getGearRatio()*_differentialRatio*_transmissionEfficiency); + return torque * _getGearRatio() * _differentialRatio * _transmissionEfficiency; + } else { + _computeRpmFromWheels(); + return _accelerationPedal * _motorForce; + } +} +void pVehicle::getControlState(int parameter,float &value,int &mode) +{ + switch (parameter) + { + case E_VCS_ACCELERATION: + value = _cAcceleration; + mode = _cAnalogAcceleration; + break; + + case E_VCS_STEERING: + value = _cSteering; + mode = _cAnalogSteering; + break; + + case E_VCS_HANDBRAKE: + value = ((float)_cHandbrake); + mode = _cHandbrake; + break; + + } + +} \ No newline at end of file diff --git a/usr/Src/Core/pVehicle/pVehicleEngine.cpp b/usr/Src/Core/pVehicle/pVehicleEngine.cpp new file mode 100644 index 0000000..889b216 --- /dev/null +++ b/usr/Src/Core/pVehicle/pVehicleEngine.cpp @@ -0,0 +1,242 @@ +#include +#include "vtPhysXAll.h" + +#include "pVehicleMotor.h" +#include "pVehicleGears.h" + +#include +#include "NxArray.h" + +#include "pEngine.h" +#include "pGearbox.h" +#include "pDifferential.h" +#include "pSteer.h" + + +float pVehicle::getClutch() +{ + if (isValidEngine()) + { + return getDriveLine()->GetClutchApplication(); + } + return 0.0f; +} + +void pVehicle::setClutch(float clutch) +{ + if (isValidEngine()) + { + getDriveLine()->SetClutchApplication(clutch); + } +} + +void pVehicle::preAnimate() +{ + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel *cW = _wheels[i]; + pWheel2* wheel2 = (pWheel2*)cW; + if ( wheel2->isAxleSpeedFromVehicle() || wheel2->isTorqueFromVehicle() ) + wheel2->preAnimate(); + } +} + + + +void pVehicle::preCalculate() +{ + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel *cW = _wheels[i]; + pWheel2* wheel2 = (pWheel2*)cW; + + if ( wheel2->isAxleSpeedFromVehicle() || wheel2->isTorqueFromVehicle() ) + { + //wheel2->preAnimate(); + } + } +} + +void pVehicle::addDifferential(pDifferential *diff) +{ + if(differentials==MAX_DIFFERENTIAL) + { + xWarning("RCar::addDifferential(); maximum (%d) exceeded"); + return; + } + differential[differentials]=diff; + differentials++; +} + + +int pVehicle::doEngine(int flags,float dt) +{ + + if (engine && gearbox && driveLine ) + { + engine->updateUserControl(_cAcceleration); + engine->CalcForces(); + + driveLine->CalcForces(); + driveLine->CalcAccelerations(); + + driveLine->Integrate(); + + for(int i=0;iIntegrate(); + } + + + gearbox->processFutureGear(); + + } + return 0; +} + +int pVehicle::initEngine(int flags) +{ + + driveLine=new pDriveLine(this); + //driveLine->EnableAutoClutch(); + + engine=new pEngine(this); + engine->setToDefault(); + + gearbox=new pGearBox(this); + gearbox->setToDefault(); + + driveLine->SetRoot(engine); + engine->AddChild(gearbox); + + driveLine->SetGearBox(gearbox); + + steer = new pVehicleSteer(this); + steer->setToDefault(); + + steer->setLock(getMaxSteering()); + + + + //---------------------------------------------------------------- + // + // control values + // + _cShiftStateDown = _cShiftStateUp = 0; + + + //---------------------------------------------------------------- + // + // setup differential , a single one for the first + // + + differentials = 0 ; + + + + pDifferential *d = new pDifferential(this); + d->setToDefault(); + d->engine = engine; + addDifferential(d); + + + + pWheel2 *w1 = NULL;int w1Index = -1; + pWheel2 *w2 = NULL;int w2Index = -1; + + findDifferentialWheels(w1Index,w2Index); + + + + w1 = (w1Index !=-1) ? (pWheel2*)_wheels[w1Index] : NULL; + w2 = (w2Index !=-1) ? (pWheel2*)_wheels[w2Index] : NULL; + if ( !w1||!w2 || ( !w1&&!w2 ) ) + { + xError("Couldn't find differential wheels"); + return -1; + } + + + d->wheel[0]=w1; w1->setDifferential(d,0); + d->wheel[1]=w2; w2->setDifferential(d,1); + + + CK3dEntity *w1E = (CK3dEntity*)GetPMan()->GetContext()->GetObject(w1->mEntID); + CK3dEntity *w2E = (CK3dEntity*)GetPMan()->GetContext()->GetObject(w2->mEntID); + + + // Add differentials and wheels to the driveline + // Note this code does NOT work for 3 diffs, need more work for that. + driveLine->SetDifferentials(differentials); + if(differentials>0) + { + // Hook first diff to the gearbox + gearbox->AddChild(differential[0]); + } + // Make the wheels children of the differentials + // A diff with 2 diffs as children is not yet supported. + for(int i=0;iAddChild(differential[i]->wheel[0]); + differential[i]->AddChild(differential[i]->wheel[1]); + } + + + driveLine->CalcPreClutchInertia(); +// gearbox->SetGear(2); + gearbox->SetGear(0); + + driveLine->SetInput(1000.0f,_cHandbrake); + + return 0; +} + +void pVehicle::PreCalcDriveLine() +{ + driveLine->CalcCumulativeRatios(); + driveLine->CalcEffectiveInertiae(); + driveLine->CalcPostClutchInertia(); + +} +float pVehicle::getTorque(int component) +{ + if (isValidEngine()) + { + return getEngine()->getTorque(); + } + return -1.0f; +} + +bool pVehicle::isStalled() +{ + if (isValidEngine()) + { + return getEngine()->IsStalled(); + } + return false; +} +float pVehicle::getRPM() +{ + if (isValidEngine()) + { + return getEngine()->getRPM(); + } + return -1.0f; +} +int pVehicle::getGear() +{ + if (isValidEngine()) + { + return getGearBox()->GetGear(); + } +} + +bool pVehicle::hasDifferential() +{ + return differentials; +} + +bool pVehicle::isValidEngine() +{ + return engine && gearbox && driveLine && differentials && steer; +} diff --git a/usr/Src/Core/pVehicle/pVehicleGears.cpp b/usr/Src/Core/pVehicle/pVehicleGears.cpp new file mode 100644 index 0000000..17aa873 --- /dev/null +++ b/usr/Src/Core/pVehicle/pVehicleGears.cpp @@ -0,0 +1,63 @@ +#include +#include "vtPhysXAll.h" + +void pVehicleGearDesc::setToCorvette() { + + forwardGearRatios[0] = 1.66f; + forwardGearRatios[1] = 1.78f; + forwardGearRatios[2] = 1.30f; + forwardGearRatios[3] = 1; + forwardGearRatios[4] = 0.74f; + forwardGearRatios[5] = 0.50f; + nbForwardGears = 6; + + backwardGearRatio = -2.90f; + +} + + +void pVehicleGearDesc::setToDefault() +{ + //forwardGears.clear(); +} + +bool pVehicleGearDesc::isValid() const +{ + if (nbForwardGears > getMaxNumOfGears()) { + fprintf(stderr, "NxVehicleGearDesc::isValid(): nbForwardGears(%d) is bigger than max (%d)\n", + nbForwardGears, getMaxNumOfGears()); + return false; + } + if (nbForwardGears <= 0) { + fprintf(stderr, "NxVehicleGearDesc::isValid(): nbForwardGears(%d) smaller or equal 0\n", nbForwardGears); + return false; + } + if (backwardGearRatio > 0) { + fprintf(stderr, "NxVehilceGearDesc::isValid(): backwardGearRatio(%2.3f) is bigger than 0, make it negative\n", backwardGearRatio); + return false; + } + for (int i = 0; i < nbForwardGears; i++) + { + if (forwardGearRatios[i] < 0) + { + fprintf(stderr, "NxVehilceGearDesc::isValid(): forwardGearRatios[%d] (%2.3f) has value smaller 0\n", i, forwardGearRatios[i]); + return false; + } + } + return true; +} + + +float pVehicleGears::getCurrentRatio() const { + return getRatio(_curGear); +} + +float pVehicleGears::getRatio(NxI32 gear) const { + if (gear > 0) + return _forwardGearRatios[gear-1]; + //return _forwardGears[gear-1]; + if (gear == -1) + return _backwardGearRatio; + return 0; +} + diff --git a/usr/Src/Core/pVehicle/pVehicleMotor.cpp b/usr/Src/Core/pVehicle/pVehicleMotor.cpp new file mode 100644 index 0000000..a7750b7 --- /dev/null +++ b/usr/Src/Core/pVehicle/pVehicleMotor.cpp @@ -0,0 +1,105 @@ +#include +#include "vtPhysXAll.h" + + +int pVehicleMotor::loadNewTorqueCurve(pLinearInterpolation newTCurve) +{ + + _torqueCurve.clear(); + _torqueCurve = newTCurve; + + NxReal maxTorque = 0; + NxI32 maxTorquePos = -1; + for (NxU32 i = 0; i < _torqueCurve.getSize(); i++) + { + NxReal v = _torqueCurve.getValueAtIndex(i); + if (v > maxTorque) { + maxTorque = v; + maxTorquePos = i; + } + } + + _maxTorque = maxTorque; + _maxTorquePos = (float)maxTorquePos; + + + return 1; +} + +void pVehicleMotorDesc::setToDefault() +{ + torqueCurve.clear(); + minRpmToGearDown = 1000.0f; + maxRpmToGearUp = 4000.f; + maxRpm = 5000.f; + minRpm = 1000.f; + + + + setToCorvette(); + +} + +void pVehicleMotorDesc::setToCorvette() { + + // Default should be values for a corvette! + // These are corresponding numbers for rotations and torque (in rpm and Nm) + + /* torqueCurve.insert(1000.f, 193.f); + torqueCurve.insert(2000.f, 234.f); + torqueCurve.insert(4000.f, 275.f); + torqueCurve.insert(5000.f, 275.f); + torqueCurve.insert(6000.f, 166.f);*/ + torqueCurve.insert(1000, 400); + torqueCurve.insert(3000, 500); + torqueCurve.insert(5000, 300); + minRpmToGearDown = 1500.f; + maxRpmToGearUp = 4000.f; + minRpm = 1000.f; + maxRpm = 5000.f; +} + +bool pVehicleMotorDesc::isValid() const +{ + + if (torqueCurve.getSize() == 0) { + fprintf(stderr, "pVehicleMotorDesc::isValid(): Empty TorqueCurve\n"); + return false; + } + if (maxRpmToGearUp < minRpmToGearDown) { + fprintf(stderr, "pVehicleMotorDesc::isValid(): maxRpmToGearUp (%2.3f) is smaller than minRpmToGearDown (%2.3f)\n", + maxRpmToGearUp, minRpmToGearDown); + return false; + } + return true; + +} + + +int pVehicleMotor::changeGears(const pVehicleGears* gears, float threshold) const +{ + NxI32 gear = gears->getGear(); + if (_rpm > _maxRpmToGearUp && gear < gears->getMaxGear()) + return 1; + else if (_rpm < _minRpmToGearDown && gear > 1) + return -1; + /* + NxReal normalTorque = _torqueCurve.getValue(_rpm); + + NxReal lowerGearRatio = gears->getRatio(gear-1); + NxReal normalGearRatio = gears->getCurrentRatio(); + NxReal upperGearRatio = gears->getRatio(gear+1); + NxReal lowerGearRpm = _rpm / normalGearRatio * lowerGearRatio; + NxReal upperGearRpm = _rpm / normalGearRatio * upperGearRatio; + NxReal lowerTorque = _torqueCurve.getValue(lowerGearRpm); + NxReal upperTorque = _torqueCurve.getValue(upperGearRpm); + NxReal lowerWheelTorque = lowerTorque * lowerGearRatio; + NxReal normalWheelTorque = normalTorque * normalGearRatio; + NxReal upperWheelTorque = upperTorque * upperGearRatio; + //printf("%2.3f %2.3f %2.3f\n", lowerWheelTorque, normalWheelTorque, upperWheelTorque); + */ + + return 0; +} + + diff --git a/usr/Src/Core/pVehicle/pVehicleMovement.cpp b/usr/Src/Core/pVehicle/pVehicleMovement.cpp new file mode 100644 index 0000000..bd99142 --- /dev/null +++ b/usr/Src/Core/pVehicle/pVehicleMovement.cpp @@ -0,0 +1,428 @@ +#include +#include "vtPhysXAll.h" + +#include "pVehicleMotor.h" +#include "pVehicleGears.h" +#include "pSteer.h" + +#include +#include "NxArray.h" + + +float pVehicle::getBrakeAmountFromTable(pVehicleBreakLevel brakeLevel) +{ + + int value = abs((int(getMPH()) / 10)); + if(value > BREAK_TABLE_ENTRIES - 1) + value = BREAK_TABLE_ENTRIES - 1; + if(value < 0 || value == BREAK_TABLE_ENTRIES) + { + return 1.0f; + } + + switch(brakeLevel) + { + case BL_Small: + return mSmallBrakeTable.brakeEntries[brakeLevel]; + case BL_Medium: + return mMediumBrakeTable.brakeEntries[brakeLevel]; + case BL_High: + return mHighBrakeTable.brakeEntries[brakeLevel]; + } + + return 1.0f; + +} + +pVehicleBreakCase pVehicle::calculateBreakCase(int currentAccelerationStatus) +{ + + //---------------------------------------------------------------- + // + // is rolling or no user input ? + // + if( !(currentAccelerationStatus & VS_Handbrake ) && + (currentAccelerationStatus & VS_IsMoving ) && + !(currentAccelerationStatus & VS_IsAccelerated) + ) + return BC_NoUserInput; + + //---------------------------------------------------------------- + // + // direction change ? + // + if( !(currentAccelerationStatus & VS_Handbrake ) && + (currentAccelerationStatus & VS_IsBraking ) && + (currentAccelerationStatus & VS_IsMoving ) && + (currentAccelerationStatus & VS_IsAccelerated) + ) + return BC_DirectionChange; + + //---------------------------------------------------------------- + // + // handbrake + // + if( (currentAccelerationStatus & VS_Handbrake ) ) + return BC_Handbrake; + + return BC_NoUserInput; + +} + + +void pVehicle::doSteering() +{ + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel2* wheel = (pWheel2*)_wheels[i]; + if(wheel->getWheelFlag(WF_SteerableInput)) + { + int i; + // Send steering angle through to steering wheels + float factor=steer->GetLock()/wheel->GetLock()*2.0f; + float angle = steer->GetAngle(); + float rAngle = wheel->getWheelShape()->getSteerAngle(); + wheel->setSteering(steer->GetAngle()/factor); + + } + } +} +int pVehicle::_performSteering(float dt) +{ + _controlSteering(_cSteering, _cAnalogSteering); + + NxReal distanceSteeringAxisCarTurnAxis = _steeringSteerPoint.x - _steeringTurnPoint.x; + //NX_ASSERT(_steeringSteerPoint.z == _steeringTurnPoint.z); + NxReal distance2 = 0; + if (NxMath::abs(_steeringWheelState) > 0.01f) + distance2 = distanceSteeringAxisCarTurnAxis / NxMath::tan(_steeringWheelState * getMaxSteering()); + + float tanS = NxMath::tan(_steeringWheelState * getMaxSteering()); + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_SteerableInput)) + { + if(distance2 != 0) + { + + //NxReal xPos = wheel->getWheelPos().x; + NxReal xPos = ((pWheel2*)wheel)->getWheelShape()->getLocalPosition().x; + //NxReal xPos2 = _steeringSteerPoint.x- wheel->getWheelPos().x; + //NxReal xPos2 = _steeringSteerPoint.x- ((pWheel2*)wheel)->getWheelShape()->getLocalPosition().z; + NxReal zPos = ((pWheel2*)wheel)->getWheelShape()->getLocalPosition().z; + //NxReal zPos = wheel->getWheelPos().z; + + NxReal dz = -zPos + distance2; + NxReal dx = xPos - _steeringTurnPoint.x; + float angle =(NxMath::atan(dx/dz)); + if (dx < 0.0f) + { + angle*=-1.0f; + } + wheel->setAngle(angle); + } else { + wheel->setAngle(0.0f); + } + + } else if(wheel->getWheelFlag(WF_SteerableAuto)) + { + NxVec3 localVelocity = getActor()->getLocalPointVelocity(getFrom(wheel->getWheelPos())); + NxQuat local2Global = getActor()->getGlobalOrientationQuat(); + local2Global.inverseRotate(localVelocity); + // printf("%2.3f %2.3f %2.3f\n", wheel->getWheelPos().x,wheel->getWheelPos().y,wheel->getWheelPos().z); + localVelocity.y = 0; + if(localVelocity.magnitudeSquared() < 0.1f) + { + wheel->setAngle(0.0f); + } else { + localVelocity.normalize(); + // printf("localVelocity: %2.3f %2.3f\n", localVelocity.x, localVelocity.z); + if(localVelocity.x < 0) + localVelocity = -localVelocity; + NxReal angle = NxMath::clamp((NxReal)atan(localVelocity.z / localVelocity.x), 0.3f, -0.3f); + wheel->setAngle(angle); + } + } + } + + + + return 0; +} +float pVehicle::calculateBraking(float dt) +{ + + float breakTorque = 0.0f; + + + pVehicleBreakCase currentBreakCase = calculateBreakCase(_currentStatus); + + /* + int currentBreakLevel = getBreaklevelForCase(currentBreakCase); + */ + bool calculateBreaking = false; + XString errMessage; + + + if( + ((_currentStatus & VS_IsBraking ) && (_currentStatus & VS_IsMoving)) + ) calculateBreaking = true; + + + if ( (_currentStatus & VS_IsMoving ) && + (getBreakFlags() & VBF_Autobreak) && + (currentBreakCase == BC_NoUserInput)&& + (_currentStatus & VS_IsMoving ) && + !(_currentStatus & VS_IsAccelerated ) + ) + { + calculateBreaking = true; + /* errMessage.Format("autobreak");*/ + //xInfo(errMessage.Str()); + } + + + if (_currentStatus & VS_Handbrake) + { + /*errMessage.Format("handbrake"); + xInfo(errMessage.Str());*/ + goto performAcceleration; + } + + //---------------------------------------------------------------- + // + // calculate break torque + // + if ( calculateBreaking ) + { + + + //---------------------------------------------------------------- + // + // increase break time counter + // + if(mBreakLastFrame) + mTimeBreaking+=dt; + + //---------------------------------------------------------------- + // + // determine break amount by table + // + if ( (getBreakFlags() & VBF_UseTable) ) + { + + if(mTimeBreaking < mBrakeMediumThresold) + { + breakTorque = getBrakeAmountFromTable(BL_Small); + errMessage.Format("breaking at small : bt : %f at %f",breakTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + + }else if(mTimeBreaking >= mBrakeMediumThresold && mTimeBreaking < mBrakeHighThresold ) + { + breakTorque = getBrakeAmountFromTable(BL_Medium); + errMessage.Format("breaking at medium : bt : %f at %f",breakTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + }else + { + breakTorque = getBrakeAmountFromTable(BL_High); + errMessage.Format("breaking at high : bt : %f at %f",breakTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + } + }else + { + + //---------------------------------------------------------------- + // + // use break pressures + // + float mCurrentBrakeTorque = getBrakeTorque()*0.01f; + float AmountToBrakeFinal = 0.0f; + if(mTimeBreaking < mBrakeMediumThresold) + { + breakTorque = mCurrentBrakeTorque * mBreakPressures[BL_Small]; + errMessage.Format("breaking at small : bt : %f at %f",breakTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + + } + else if(mTimeBreaking >= mBrakeMediumThresold && mTimeBreaking < mBrakeHighThresold ) + { + breakTorque = mCurrentBrakeTorque * mBreakPressures[BL_Medium]; + errMessage.Format("breaking at medium : bt : %f at %f",breakTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + } + else + { + breakTorque = mCurrentBrakeTorque * mBreakPressures[BL_High]; + errMessage.Format("breaking at high : bt : %f at %f",breakTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + } + + + if (breakTorque > 1000.f) + { + breakTorque= 1000.0f; + } + + } + + }else + { + mBreakLastFrame = false; + mTimeBreaking = 0.0f; + } + + + performAcceleration: + + if (breakTorque > 0.0f) + { + mBreakLastFrame = true; + } + + return breakTorque; +} +int pVehicle::_performAcceleration(float dt) +{ + + motorTorque = 0.0f; + + if ( _nbTouching && _currentStatus & VS_IsAccelerated ) + { + NxReal axisTorque = _computeAxisTorqueV2(); + NxReal wheelTorque = axisTorque / (NxReal)(_wheels.size() - _nbHandbrakeOn ); + NxReal wheelTorqueNotTouching = _nbNotTouching > 0 ? wheelTorque * ( NxMath::pow(0.5f, (NxReal) _nbNotTouching )):0; + NxReal wheelTorqueTouching = wheelTorque - wheelTorqueNotTouching; + motorTorque = wheelTorqueTouching / (NxReal)_nbTouching; + }else + { + _updateRpms(); + } + + + return 1; +} + +void pVehicle::postStep() +{ + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + //---------------------------------------------------------------- + // + // determine break torque : + // + + // is moving in the opposite direction than its accelerated + pWheel* wheel = _wheels[i]; + wheel->tick( ( _currentStatus & VS_Handbrake) , motorTorque, breakTorque , _lastDT ); + + } + +} + +void pVehicle::setBreakPressure(int breakLevel,float pressure) +{ + mBreakPressures[breakLevel]=pressure; +} +void pVehicle::setBreakCaseLevel(pVehicleBreakCase breakCase,pVehicleBreakLevel level) +{ + breakConditionLevels[breakCase]=level; +} + +// ( X * 10 * 60) / (5280* 12) * 100 = X * 0.9469696 +//return (-((10 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed() * 60) / (5280 * 12)) * 100); +//return -0.9469696 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed(); + +float pVehicle::getBrakeTorque() +{ + int nbAWheels =0; + float radius = 0.0; + float axleSpeed = 0.0; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_Accelerated)) + { + nbAWheels++; + if (wheel->getRadius() > radius) + radius = wheel->getRadius(); + + pWheel2* w2 = (pWheel2*)wheel; + if (w2->getWheelShape()->getAxleSpeed() > axleSpeed) + { + axleSpeed = w2->getWheelShape()->getAxleSpeed(); + } + } + } + + if(fabs(axleSpeed) != 0) + { + return ((5252 * getMotorForce()) / (fabs(axleSpeed) * 10)); + } + + return 0.0f; +} + +float pVehicle::getMPH(int type) +{ + + int nbAWheels =0; + float radius = 0.0; + float axleSpeed = 0.0; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_Accelerated)) + { + nbAWheels++; + if (wheel->getRadius() > radius) + radius = wheel->getRadius(); + + pWheel2* w2 = (pWheel2*)wheel; + if (w2->getWheelShape()->getAxleSpeed() > axleSpeed) + { + axleSpeed = w2->getWheelShape()->getAxleSpeed(); + } + } + } + + + // ( X * 10 * 60) / (5280* 12) * 100 = X * 0.9469696 + //return (-((10 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed() * 60) / (5280 * 12)) * 100); + return 0.9469696 * radius * NxPi * axleSpeed; + +} +void pVehicle::_controlAcceleration(float acceleration, bool analogAcceleration) +{ + if(NxMath::abs(acceleration) < 0.001f) + { + _releaseBraking = true; + //xInfo("set release breaking = true"); + } + + if(!_braking) + { + _accelerationPedal = NxMath::clamp(acceleration, 1.f, -1.f); + _brakePedalChanged = _brakePedal == 0; + _brakePedal = 0; + //xInfo("breaking = false : clamp accPedal 1|-1"); + } else { + //xInfo("breaking = true : accPeal = 0"); + _accelerationPedal = 0; + NxReal newv = NxMath::clamp(NxMath::abs(acceleration), 1.f, 0.f); + _brakePedalChanged = _brakePedal == newv; + _brakePedal = newv; + } + char master[512]; + sprintf(master,"Acceleration: %2.3f, Braking %2.3f\n", _accelerationPedal, _brakePedal); + xInfo(master); + //OutputDebugString(master); + + +} + + + + diff --git a/usr/Src/Core/pVehicle/pVehicleRun.cpp b/usr/Src/Core/pVehicle/pVehicleRun.cpp new file mode 100644 index 0000000..7bb1006 --- /dev/null +++ b/usr/Src/Core/pVehicle/pVehicleRun.cpp @@ -0,0 +1,405 @@ +#include +#include "vtPhysXAll.h" + +#include "pVehicleMotor.h" +#include "pVehicleGears.h" +#include "pSteer.h" +#include "pGearbox.h" +#include +#include "NxArray.h" + +#include "pVehicleAll.h" + + +#include "virtools/vtTools.h" + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; +using namespace vtTools::BehaviorTools; + +void pVehicle::step(float dt) +{ + + + if (isValidEngine()) + { + //---------------------------------------------------------------- + // + // update user controls + // + steer->SetInput(_cSteering);doSteering(); + + engine->updateUserControl(_cAcceleration); + + if ( (_currentStatus & VS_IsAcceleratedForward ) || + (_currentStatus & VS_IsAcceleratedBackward) + ) + { + driveLine->SetInput(1000.0f,_cHandbrake); + } + if (!(_currentStatus & VS_IsAccelerated) ) + { + driveLine->SetInput(0.0f,_cHandbrake); + } + + //---------------------------------------------------------------- + // + // + // + + preAnimate(); + + + engine->CalcForces(); + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel2 *cW = (pWheel2*)_wheels[i]; + if (cW->isAxleSpeedFromVehicle() || cW->isTorqueFromVehicle() ) + cW->calcForces(); + } + + driveLine->CalcForces(); + + + ////////////////////////////////////////////////////////////////////////// + + // Now that engine and wheel forces are unknown, check the diffs + for(int i=0;iCalcForces(); + + ////////////////////////////////////////////////////////////////////////// + + driveLine->CalcAccelerations(); + + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel2 *cW = (pWheel2*)_wheels[i]; + if (cW->isAxleSpeedFromVehicle() || cW->isTorqueFromVehicle() ) + cW->CalcAccelerations(); + } + ////////////////////////////////////////////////////////////////////////// + #ifdef OBS_RPM_IS_NEW + // Engine RPM is related to the rotation of the powered wheels, + // since they are physically connected, somewhat + // Take the minimal rotation + float minV=99999.0f,maxV=0; + for(int i=0;i<_wheels.size();i++) + { + pWheel2 *cW = (pWheel2*)_wheels[i]; + if (cW && (cW->getWheelFlag(WF_Accelerated) && ( cW->getWheelShape()->getWheelFlags() & WSF_AxleSpeedOverride)) ) + { + if(cW->GetRotationV()>maxV) + maxV=cW->GetRotationV(); + + #ifdef OBS_HMM + if(cW[i]->GetRotationV()GetRotationV(); + #endif + + } + } + /*engine-> + engine->ApplyWheelRotation(maxV);*/ + + #endif + ////////////////////////////////////////////////////////////////////////// + steer->Integrate(); + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel2 *cW = (pWheel2*)_wheels[i]; + if (cW->isAxleSpeedFromVehicle() || cW->isTorqueFromVehicle() ) + cW->Integrate(); + } + + + driveLine->Integrate(); + + + for(int i=0;iIntegrate(); + } + + gearbox->processFutureGear(); + + } +} +void pVehicle::processPreScript() +{ + +} +void pVehicle::processPostScript() +{ + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(postScript); + if (beh) + { + SetInputParameterValue(beh,0,5); + beh->Execute(_lastDT); + GetOutputParameterValue(beh,0); + } +} +int pVehicle::onPostProcess() +{ + + /* + if (getBody()->isSleeping()) + getBody()->wakeUp(); + */ + + + + _lastDT = lastStepTimeMS; + + + _currentStatus = _calculateCurrentStatus(); + + VehicleStatus status = (VehicleStatus)_currentStatus; + float bTorque = calculateBraking(_lastDT); + + if (_cSteering != 0 || _cAcceleration != 0 || _cHandbrake) + getActor()->wakeUp(0.05); + + if (isValidEngine()) //new vehicle code + step(_lastDT); + else //old + _performSteering(_lastDT ); + + + if ( !(flags & VF_UseAdvance )) + { + _performAcceleration(_lastDT); + postStep(); + }else + { + for(NxU32 i = 0; i < _wheels.size(); i++) + { + + pWheel2* wheel = (pWheel2*)_wheels[i]; + + + if( wheel->isTorqueFromVehicle()) + wheel->applyTorqueToPhysics(); + + if( wheel->isAxleSpeedFromVehicle() ) + { +/* float v = wheel->rotationV.x; + v = v * getEngine()->getEndRotationalFactor() * getEngine()->getTimeScale(); + +*/ //wheel->getWheelShape()->setAxleSpeed(v); + +/* + pDifferential *diff = getDifferential(0); + float tOutOne = diff->GetTorqueOut(wheel[0]->differentialSide); + float tOutSeconf = diff->GetTorqueOut(wheel[1]->differentialSide); + + +*/ + + } + } + } + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel2* wheel = (pWheel2*)_wheels[i]; + wheel->updateSteeringPose( wheel->getWheelRollAngle(),wheel->getWheelShape()->getSteerAngle(),_lastDT); + wheel->updatePosition(); + } + + + setVSFlags(_currentStatus); + + processPostScript(); + + updateControl(0,false,0,false,false); + + + return 1; +} + +int pVehicle::onPreProcess() +{ + _lastDT = lastStepTimeMS; + + + return 1; +} + + + +void pVehicle::updateVehicle( float lastTimeStepSize ) +{ + + return; + + _lastDT = lastTimeStepSize; + + _currentStatus = _calculateCurrentStatus(); + + VehicleStatus status = (VehicleStatus)_currentStatus; + + + if (_cSteering != 0 || _cAcceleration != 0 || _cHandbrake) + getActor()->wakeUp(0.05); + + + float bTorque = calculateBraking(lastTimeStepSize); + + + + _performSteering(lastTimeStepSize); + if (engine && gearbox && driveLine ) + { + step(lastTimeStepSize); + } + + + if ( !(flags & VF_UseAdvance )) + { + _performAcceleration(lastTimeStepSize); + postStep(); + }else + { + for(NxU32 i = 0; i < _wheels.size(); i++) + { + + + pWheel2* wheel = (pWheel2*)_wheels[i]; +/* if( (wheel->getWheelFlag(WF_Accelerated)) && (wheel->getWheelShape()->getWheelFlags() & WSF_AxleSpeedOverride )) + { + + float v = wheel->rotationV.x *= 1.0f; + + wheel->getWheelShape()->setAxleSpeed( v ); + } + */ + } + } + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel2* wheel = (pWheel2*)_wheels[i]; + wheel->updateSteeringPose( wheel->getWheelRollAngle(),wheel->getWheelShape()->getSteerAngle(),lastTimeStepSize); + wheel->updatePosition(); + } + + if (getMotor()) + { + _currentStatus |= E_VSF_HAS_MOTOR; + } + + if (getGears()) + { + _currentStatus |= E_VSF_HAS_GEARS; + } + + setVSFlags(_currentStatus); + + + + return; + + //---------------------------------------------------------------- + // + // old code + // + + //control(_cSteering,_cAnalogSteering,_cAcceleration,_cAnalogAcceleration,_cHandbrake); + //printf("updating %x\n", this); + + NxReal distanceSteeringAxisCarTurnAxis = _steeringSteerPoint.x - _steeringTurnPoint.x; + NX_ASSERT(_steeringSteerPoint.z == _steeringTurnPoint.z); + NxReal distance2 = 0; + if (NxMath::abs(_steeringWheelState) > 0.01f) + distance2 = distanceSteeringAxisCarTurnAxis / NxMath::tan(_steeringWheelState * _steeringMaxAngleRad); + + NxU32 nbTouching = 0; + NxU32 nbNotTouching = 0; + NxU32 nbHandBrake = 0; + int wSize = _wheels.size(); + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_SteerableInput)) + { + if(distance2 != 0) + { + NxReal xPos = wheel->getWheelPos().x; + NxReal xPos2 = _steeringSteerPoint.x- wheel->getWheelPos().x; + NxReal zPos = wheel->getWheelPos().z; + NxReal dz = -zPos + distance2; + NxReal dx = xPos - _steeringTurnPoint.x; + float atan3 = NxMath::atan(dx/dz); + + float angle =(NxMath::atan(dx/dz)); + if (dx < 0.0f) + { + angle*=-1.0f; + } + wheel->setAngle(angle); + //errMessage.Format("w%d dz:%f dx:%f dx2%f distance:%f atan3:%f",i,dz,dx,xPos2,distance2,atan3); + //xInfo(errMessage.Str()); + + + } else { + wheel->setAngle(0.0f); + } + //printf("%2.3f\n", wheel->getAngle()); + + } else if(wheel->getWheelFlag(WF_SteerableAuto)) + { + NxVec3 localVelocity = getActor()->getLocalPointVelocity(getFrom(wheel->getWheelPos())); + NxQuat local2Global = getActor()->getGlobalOrientationQuat(); + local2Global.inverseRotate(localVelocity); + // printf("%2.3f %2.3f %2.3f\n", wheel->getWheelPos().x,wheel->getWheelPos().y,wheel->getWheelPos().z); + localVelocity.y = 0; + if(localVelocity.magnitudeSquared() < 0.1f) + { + wheel->setAngle(0.0f); + } else { + localVelocity.normalize(); + // printf("localVelocity: %2.3f %2.3f\n", localVelocity.x, localVelocity.z); + if(localVelocity.x < 0) + localVelocity = -localVelocity; + NxReal angle = NxMath::clamp((NxReal)atan(localVelocity.z / localVelocity.x), 0.3f, -0.3f); + wheel->setAngle(angle); + } + } + + // now the acceleration part + if(!wheel->getWheelFlag(WF_Accelerated)) + continue; + + if(_handBrake && wheel->getWheelFlag(WF_AffectedByHandbrake)) + { + nbHandBrake++; + } + else + { + if (!wheel->hasGroundContact()) + { + nbNotTouching++; + } else { + nbTouching++; + } + } + } + + NxReal motorTorque = 0.0; + float _acc = NxMath::abs(_accelerationPedal); + + XString errMessage; + if(nbTouching && NxMath::abs(_accelerationPedal) > 0.1f ) + { + NxReal axisTorque = _computeAxisTorque(); + NxReal wheelTorque = axisTorque / (NxReal)(_wheels.size() - nbHandBrake); + NxReal wheelTorqueNotTouching = nbNotTouching>0?wheelTorque*(NxMath::pow(0.5f, (NxReal)nbNotTouching)):0; + NxReal wheelTorqueTouching = wheelTorque - wheelTorqueNotTouching; + motorTorque = wheelTorqueTouching / (NxReal)nbTouching; + } else { + _updateRpms(); + } + + +} + diff --git a/usr/Src/Core/pVehicle/pVehicleXML.cpp b/usr/Src/Core/pVehicle/pVehicleXML.cpp new file mode 100644 index 0000000..e61d52f --- /dev/null +++ b/usr/Src/Core/pVehicle/pVehicleXML.cpp @@ -0,0 +1,632 @@ +#include +#include "vtPhysXAll.h" + +#include "tinyxml.h" + +int pFactory::loadFrom(pTireFunction& dst,const char* nodeName,const TiXmlDocument * doc ) +{ + int result = 0 ; + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "tireFunction" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + + int res = sube->QueryDoubleAttribute("ExtremumSlip",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.extremumSlip = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("ExtremumValue",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.extremumValue = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("AsymptoteSlip",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.asymptoteSlip = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("AsymptoteValue",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.asymptoteValue = static_cast(v); + } + } + res = sube->QueryDoubleAttribute("StiffnessFactor",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.stiffnessFactor = static_cast(v); + } + } + } + } + } + } + } + } + } + return result; +} + +int pFactory::loadWheelDescrFromXML(pWheelDescr& dst,const char* nodeName,const TiXmlDocument * doc ) +{ + int result = 0 ; + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "wheel" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + + int res = sube->QueryDoubleAttribute("Suspension",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.wheelSuspension = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.springRestitution = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("Damping",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.springDamping = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("Bias",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.springBias= static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("MaxBreakForce",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.maxBrakeForce = static_cast(v); + continue; + } + } + + + res = sube->QueryDoubleAttribute("FrictionToSide",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.frictionToSide = static_cast(v); + continue; + } + } + + res = sube->QueryDoubleAttribute("FrictionToFront",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.frictionToFront = static_cast(v); + continue; + } + } + + res = sube->QueryDoubleAttribute("InverseWheelMass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.inverseWheelMass = static_cast(v); + continue; + } + } + + const char* flags = NULL; + flags = sube->Attribute("Flags"); + if (flags && strlen(flags)) + { + dst.wheelFlags = (WheelFlags)_str2WheelFlag(flags); + } + + const char* sflags = NULL; + sflags = sube->Attribute("ShapeFlags"); + if (sflags && strlen(sflags)) + { + dst.wheelShapeFlags = (WheelShapeFlags)_str2WheelShapeFlag(sflags); + } + + + const char* latFunc = NULL; + latFunc = sube->Attribute("LateralFunction"); + if (latFunc && strlen(latFunc)) + { + int index = getEnumIndex(getManager()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,latFunc); + if (index!=0) + { + loadFrom(dst.latFunc,latFunc,doc); + dst.latFunc.xmlLink = index; + if (!dst.latFunc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Lateral Tire Function from XML was incorrect, setting to default"); + dst.latFunc.setToDefault(); + } + } + } + + const char* longFunc = NULL; + longFunc = sube->Attribute("LongitudeFunction"); + if (longFunc && strlen(longFunc)) + { + int index = getEnumIndex(getManager()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,longFunc); + if (index!=0) + { + loadFrom(dst.longFunc,longFunc,doc); + dst.longFunc.xmlLink = index; + if (!dst.longFunc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Longitude Tire Function from XML was incorrect, setting to default"); + dst.longFunc.setToDefault(); + } + } + } + } + } + } + } + } + } + } + return result; +} +int pFactory::loadVehicleDescrFromXML(pVehicleDesc& dst,const char* nodeName,const TiXmlDocument * doc ) +{ + + + int result = 0 ; + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "vehicle" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + + int res = sube->QueryDoubleAttribute("Mass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.mass = static_cast(v); + continue; + } + } + + } + } + } + } + } + } + } + return result; +} + +int pFactory::_str2PhysicFlags(XString _in) +{ + + + short nb = 0 ; + int result = 0; + XStringTokenizer tokizer(_in.CStr(), "|"); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) ) + { + XString tokx(tok); + + if ( _stricmp(tokx.CStr(),"DisableHardware") == 0 ) + { + result |= PMF_DONT_USE_HARDWARE; + } + + if ( _stricmp(tokx.CStr(),"DoNotDeleteScenes") == 0 ) + { + result |= PMF_DONT_DELETE_SCENES; + } + nb++; + } + return result; +} + +int pFactory::_str2SceneFlags(XString _in) +{ + + + short nb = 0 ; + int result = 0; + XStringTokenizer tokizer(_in.CStr(), "|"); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) ) + { + XString tokx(tok); + + if ( _stricmp(tokx.CStr(),"DisableSSE") == 0 ) + { + result |= NX_SF_DISABLE_SSE; + } + + if ( _stricmp(tokx.CStr(),"DisableCollision") == 0 ) + { + result |= NX_SF_DISABLE_COLLISIONS; + } + if ( _stricmp(tokx.CStr(),"SimulateSeperateThread") == 0 ) + { + result |= NX_SF_SIMULATE_SEPARATE_THREAD; + } + if ( _stricmp(tokx.CStr(),"EnableMultiThread") == 0 ) + { + result |= NX_SF_ENABLE_MULTITHREAD; + } + + if ( _stricmp(tokx.CStr(),"EnableActiveTransforms") == 0 ) + { + result |= NX_SF_ENABLE_ACTIVETRANSFORMS; + } + + if ( _stricmp(tokx.CStr(),"RestrictedScene") == 0 ) + { + result |= NX_SF_RESTRICTED_SCENE; + } + if ( _stricmp(tokx.CStr(),"DisableSceneMutex") == 0 ) + { + result |= NX_SF_DISABLE_SCENE_MUTEX; + } + + if ( _stricmp(tokx.CStr(),"ForceConeFriction") == 0 ) + { + result |= NX_SF_FORCE_CONE_FRICTION; + } + + if ( _stricmp(tokx.CStr(),"DisableSceneMutex") == 0 ) + { + result |= NX_SF_SEQUENTIAL_PRIMARY; + } + + /* + if ( _stricmp(tokx.CStr(),"DisableHardware") == 0 ) + { + result |= NX_SF_SEQUENTIAL_PRIMARY; + }*/ + + nb++; + } + return result; +} + +int pFactory::_str2WheelFlag(XString _in) +{ + + + short nb = 0 ; + int result = 0; + XStringTokenizer tokizer(_in.CStr(), "|"); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) ) + { + XString tokx(tok); + + if ( _stricmp(tokx.CStr(),"Steerable") == 0 ) + { + result |= WF_SteerableInput; + } + + if ( _stricmp(tokx.CStr(),"VehicleControlled") == 0 ) + { + result |= WF_VehicleControlled; + } + if ( _stricmp(tokx.CStr(),"SteerableAuto") == 0 ) + { + result |= WF_SteerableAuto; + } + if ( _stricmp(tokx.CStr(),"Handbrake") == 0 ) + { + result |= WF_AffectedByHandbrake; + } + + if ( _stricmp(tokx.CStr(),"Accelerated") == 0 ) + { + result |= WF_Accelerated; + } + + if ( _stricmp(tokx.CStr(),"Differential") == 0 ) + { + result |= WF_AffectedByDifferential; + } + if ( _stricmp(tokx.CStr(),"IgnoreTireFunction") == 0 ) + { + result |= WF_IgnoreTireFunction; + } + + + + /*if ( _stricmp(tokx.CStr(),"Wheelshape") == 0 ) + { + result |= WF_UseWheelShape; + }*/ + + nb++; + } + return result; +} +int pFactory::_str2WheelShapeFlag(XString _in) +{ + + + short nb = 0 ; + int result = 0; + XStringTokenizer tokizer(_in.CStr(), "|"); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) ) + { + XString tokx(tok); + + if ( _stricmp(tokx.CStr(),"AxisContactNormal") == 0 ) + { + result |= WSF_AxleSpeedOverride; + } + + if ( _stricmp(tokx.CStr(),"InputLateralSlip") == 0 ) + { + result |= WSF_InputLatSlipVelocity; + } + if ( _stricmp(tokx.CStr(),"InputLongitudinal") == 0 ) + { + result |= WSF_InputLongSlipVelocity; + } + if ( _stricmp(tokx.CStr(),"UnscaledSpringBehavior") == 0 ) + { + result |= WSF_UnscaledSpringBehavior; + } + + if ( _stricmp(tokx.CStr(),"WheelAxisContactNormal") == 0 ) + { + result |= WSF_WheelAxisContactNormal; + } + + if ( _stricmp(tokx.CStr(),"AxleSpeedOverride") == 0 ) + { + result |= WSF_AxleSpeedOverride; + } + + if ( _stricmp(tokx.CStr(),"EmulateLegacyWheel") == 0 ) + { + result |= WSF_EmulateLegacyWheel; + } + if ( _stricmp(tokx.CStr(),"ClampedFriction") == 0 ) + { + result |= WSF_ClampedFriction; + } + nb++; + } + return result; +} + +/* + +int pVehicle::loadFromXML(const char* nodeName,const TiXmlDocument * doc ) +{ + NxMaterialDesc *result = new NxMaterialDesc(); + result->setToDefault(); + + int res = 0; + + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + + + if ( strlen(nodeName) && doc) + { + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "vehicle" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryDoubleAttribute("Mass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + //setMass() = + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFriction= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->restitution= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->dynamicFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + const char* dirOfAnisotropy = NULL; + dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); + if (dirOfAnisotropy && strlen(dirOfAnisotropy)) + { + VxVector vec = pFactory::Instance()->_str2Vec(dirOfAnisotropy); + if (vec.Magnitude() >0.1f) + { + result->flags = NX_MF_ANISOTROPIC; + result->dirOfAnisotropy = pMath::getFrom(vec); + continue; + }else + { + result->dirOfAnisotropy = pMath::getFrom(VxVector(0,0,0)); + } + + //result->setGravity(vec); + + } + + ////////////////////////////////////////////////////////////////////////// + const char* FrictionCombineMode = NULL; + FrictionCombineMode = sube->Attribute("FrictionCombineMode"); + if (FrictionCombineMode && strlen(FrictionCombineMode)) + { +// int fMode = _str2CombineMode(FrictionCombineMode); +// result->frictionCombineMode = (NxCombineMode)fMode; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + const char* RestitutionCombineMode = NULL; + RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); + if (RestitutionCombineMode && strlen(RestitutionCombineMode)) + { +// int fMode = _str2CombineMode(RestitutionCombineMode); +// result->restitutionCombineMode= (NxCombineMode)fMode; + continue; + } + } + } +// return result; + } + } + } + } + } + } + + + + return 0; +} +*/ + + + diff --git a/usr/Src/Core/pVehicle/pWheel.cpp b/usr/Src/Core/pVehicle/pWheel.cpp new file mode 100644 index 0000000..3654434 --- /dev/null +++ b/usr/Src/Core/pVehicle/pWheel.cpp @@ -0,0 +1,104 @@ +#include +#include "vtPhysXAll.h" +#include + + +NxActor*pWheel::getTouchedActor()const{ return NULL;} + +void pWheelDescr::setToDefault() +{ + + userData = NULL; + wheelFlags =(WheelFlags)0; + + //radius.setToDefault(); + springBias = 0; + springRestitution = 1.f; + springDamping = 0.f; + + wheelSuspension = 1.f; + maxBrakeForce = 0.0f; + frictionToSide = 1.0f; + frictionToFront = 1.0f; + latFuncXML_Id=0; + longFuncXML_Id=0; + inverseWheelMass = 0.1f; + wheelShapeFlags =(WheelShapeFlags)0; + + latFunc.setToDefault(); + longFunc.setToDefault(); + + + + + +} +bool pWheelDescr::isValid() const +{ + + /*if(!NxMath::isFinite(radius)) return false; + if(radius<=0.0f) return false;*/ + + bool result = true; + int a=X_NEGATE(NxMath::isFinite(wheelSuspension)); + //iAssertWR(X_NEGATE(NxMath::isFinite(wheelSuspension)),"",result ); + iAssertWR(inverseWheelMass > 0.0f,"",result ); + iAssertWR(X_NEGATE(inverseWheelMass<0.0f),"",result ); + //iAssertWR(X_NEGATE(brakeTorque<0.0f),"",result ); + //iAssertWR(X_NEGATE(NxMath::isFinite(steerAngle)),"",result ); + //iAssertWR(X_NEGATE(brakeTorque<0.0f),"",result ); + iAssertWR(longFunc.isValid(),"",result ); + iAssertWR(latFunc.isValid(),"",result ); + +/* if (!suspension.isValid()) return false; + if (!longitudalTireForceFunction.isValid()) return false; + if (!lateralTireForceFunction.isValid()) return false; +*/ + //if (NxMath::abs(1-wheelAxis.magnitudeSquared()) > 0.001f) + // return false; + if (wheelApproximation > 0 && wheelApproximation < 4) { + + return false; + } + if ((wheelFlags & WF_SteerableAuto) && (wheelFlags & WF_SteerableInput)) + { + return false; + } + return result; +} + +int pWheel::_constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + return 1; +} + +void pWheel::setFlags(int flags) +{ + mWheelFlags = flags; +} + +pWheel::pWheel(pRigidBody *body,pWheelDescr *descr) +{ + + mBody = body; + mWheelFlags = descr->wheelFlags; + _wheelRollAngle = 0.0f; + mActor= body->getActor(); + + + +} + +pWheel1*pWheel::castWheel1() +{ + return dynamic_cast(this); +} +pWheel2*pWheel::castWheel2() +{ + + return dynamic_cast(this); +} + + + + diff --git a/usr/Src/Core/pVehicle/pWheel1.cpp b/usr/Src/Core/pVehicle/pWheel1.cpp new file mode 100644 index 0000000..356f5f5 --- /dev/null +++ b/usr/Src/Core/pVehicle/pWheel1.cpp @@ -0,0 +1,262 @@ +#include +#include "vtPhysXAll.h" + +pWheelContactData* +pWheel1::getContact(){ + + return new pWheelContactData(); +} + +float pWheel1::getRpm()const{ return NxMath::abs(_turnVelocity * 60.f);} + +NxActor *pWheel1::getTouchedActor(){ return contactInfo->otherActor; } + +void pWheel1::_tick(float dt) +{ + + if(!hasGroundContact()) + updateContactPosition(); + + //################################################################ + // + // Calculate the wheel rotation around the roll axis + // + updateAngularVelocity(dt*0.001f, false); + + float motorTorque=0.0; + + if(getWheelFlag(WF_Accelerated)) + { + /*if (handBrake && getWheelFlag(NX_WF_AFFECTED_BY_HANDBRAKE)) + { + // Handbrake, blocking! + }*/ + + if (hasGroundContact()) + { + // Touching, force applies + NxVec3 steeringDirection; + getSteeringDirection(steeringDirection); + steeringDirection.normalize(); + NxReal localTorque = motorTorque; + NxReal wheelForce = localTorque / _radius; + steeringDirection *= wheelForce; + wheelCapsule->getActor().addForceAtPos(steeringDirection, contactInfo->contactPosition); + if(contactInfo->otherActor->isDynamic()) + contactInfo->otherActor->addForceAtPos(-steeringDirection, contactInfo->contactPosition); + } + } + + NxMat34& wheelPose = getWheelCapsule()->getGlobalPose(); + NxMat33 rot, axisRot, rollRot; + rot.rotY( _angle ); + axisRot.rotY(0); + rollRot.rotX(_turnAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + + float a = _angle; + float b = getWheelRollAngle(); + + + setWheelPose(wheelPose); + //setWheelOrientation(wheelPose.M); + + + contactInfo->reset(); +} + + +void pWheel1::_updateVirtoolsEntity(bool position,bool rotation) +{ + + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(getEntID())); + if (ent && position) + { + + /* + NxWheelShape *wShape = getWheelShape(); + NxMat34 pose = wShape->getGlobalPose(); + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + NxVec3 suspensionOffsetDirection; + pose.M.getColumn(1, suspensionOffsetDirection); + suspensionOffsetDirection =-suspensionOffsetDirection; + + if (contactShape && wcd.contactForce > -1000) + { + NxVec3 toContact = wcd.contactPoint - pose.t; + double alongLength = suspensionOffsetDirection.dot(toContact); + NxVec3 across = toContact - alongLength * suspensionOffsetDirection; + double r = wShape->getRadius(); + double pullBack = sqrt(r*r - across.dot(across)); + pose.t += (alongLength - pullBack) * suspensionOffsetDirection; + } else { + pose.t += wShape->getSuspensionTravel() * suspensionOffsetDirection; + } + + VxVector oPos = getFrom(pose.t); + ent->SetPosition(&oPos); + + if (hasGroundContact()) + { + + + }else + { + // VxVector gPos = getWheelPos(); + // ent->SetPosition(&gPos,getBody()->GetVT3DObject()); + } + + */ + } + if (ent && rotation) + { + //float rollAngle = getWheelRollAngle(); + //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + + VxQuaternion rot = pMath::getFrom( getWheelPose().M ); + ent->SetQuaternion(&rot,NULL); + } + +} + + + + +void pWheel1::updateContactPosition() +{ + contactInfo->contactPositionLocal = getFrom(_maxPosition) - NxVec3(0, _maxSuspension+_radius, 0); +} +void pWheel1::setAngle(float angle) +{ + _angle = angle; + + NxReal Cos, Sin; + NxMath::sinCos(_angle, Sin, Cos); + NxMat33 wheelOrientation = wheelCapsule->getLocalOrientation(); + wheelOrientation.setColumn(0, NxVec3( Cos, 0, Sin )); + wheelOrientation.setColumn(2, NxVec3( Sin, 0,-Cos )); + setWheelOrientation(wheelOrientation); + +} + +void pWheel1::updateAngularVelocity(float lastTimeStepSize, bool handbrake) +{ + if((mWheelFlags & WF_AffectedByHandbrake) && handbrake) + { + _turnVelocity = 0; + } + else if (contactInfo->isTouching()) + { + NxReal wheelPerimeter = NxTwoPi * _radius; + NxReal newTurnVelocity = contactInfo->relativeVelocity / wheelPerimeter; + _turnVelocity = newTurnVelocity; + _turnAngle += _turnVelocity * lastTimeStepSize * NxTwoPi; + } + else + { + _turnVelocity *= 0.99f; + _turnAngle += _turnVelocity; + } + + while(_turnAngle >= NxTwoPi) + _turnAngle -= NxTwoPi; + while (_turnAngle < 0) + _turnAngle += NxTwoPi; + + setWheelRollAngle(_turnAngle); + +} + +void pWheel1::getSteeringDirection(NxVec3& dir) +{ + if(mWheelFlags & (WF_SteerableInput | WF_SteerableAuto)) + { + wheelCapsule->getGlobalOrientation().getColumn(0, dir); + } + else + { + wheelCapsule->getActor().getGlobalOrientation().getColumn(0, dir); + } +} + +void pWheel1::tick(bool handbrake, float motorTorque, float brakeTorque, float dt) +{ + + if(getWheelFlag(WF_Accelerated)) + { + if (handbrake && getWheelFlag(WF_AffectedByHandbrake)) + { + // Handbrake, blocking! + } + else if (hasGroundContact()) + { + // Touching, force applies + NxVec3 steeringDirection; + getSteeringDirection(steeringDirection); + steeringDirection.normalize(); + NxReal localTorque = motorTorque; + NxReal wheelForce = localTorque / _radius; + steeringDirection *= wheelForce; + wheelCapsule->getActor().addForceAtPos(steeringDirection, contactInfo->contactPosition); + if(contactInfo->otherActor->isDynamic()) + contactInfo->otherActor->addForceAtPos(-steeringDirection, contactInfo->contactPosition); + } + } + + NxReal OneMinusBreakPedal = 1-brakeTorque; + + /* + if(handBrake && getWheelFlag(WF_AffectedByHandbrake)) + { + material->setDynamicFrictionV(1); + material->setStaticFrictionV(4); + material->setDynamicFriction(0.4f); + material->setStaticFriction(1.0f); + } + else + { + NxReal newv = OneMinusBreakPedal * _frictionToFront + brakeTorque; + NxReal newv4= OneMinusBreakPedal * _frictionToFront + brakeTorque*4; + material->setDynamicFrictionV(newv); + material->setDynamicFriction(_frictionToSide); + + material->setStaticFrictionV(newv*4); + material->setStaticFriction(2); + }*/ + + if(!hasGroundContact()) + updateContactPosition(); + updateAngularVelocity(dt, handbrake); + + contactInfo->reset(); +} +VxVector pWheel1::getWheelPos()const{ return getFrom(wheelCapsule->getLocalPosition()); } +void pWheel1::setWheelOrientation(const NxMat33& m) +{ + wheelCapsule->setLocalOrientation(m); + if (wheelConvex != NULL) + wheelConvex->setLocalOrientation(m); +} + +void pWheel1::_updateAgeiaShape(bool position,bool rotation) +{ + +} + +int pWheel1::_constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + return 1; +} +pWheel1::pWheel1(pRigidBody *body, pWheelDescr *descr) : pWheel(body,descr) +{ + wheelCapsule = NULL; + wheelConvex = NULL; + + contactInfo = new ContactInfo(); + + +} + + + diff --git a/usr/Src/Core/pVehicle/pWheel2.cpp b/usr/Src/Core/pVehicle/pWheel2.cpp new file mode 100644 index 0000000..ca77fe2 --- /dev/null +++ b/usr/Src/Core/pVehicle/pWheel2.cpp @@ -0,0 +1,595 @@ +#include +#include "vtPhysXAll.h" + +#include +#include "pVehicleAll.h" +#define RR_RAD_DEG_FACTOR 57.29578f // From radians to degrees" + + +float pWheel2::getSteerAngle() +{ + + return mWheelShape->getSteerAngle(); + +} +void pWheel2::setSteering(float angle) +{ + if(angle>lock)angle=lock; + else if(angle<-lock)angle=-lock; + rotation.y=angle+toe; + // Apply Ackerman effect + if((ackermanFactor<0&&angle<0)||(ackermanFactor>0&&angle>0)) + rotation.y*=fabs(ackermanFactor); + + float a = rotation.y; + + float steerangle= rotation.y * lastStepTimeSec; + + + while (steerangle > NxTwoPi) //normally just 1x + steerangle-= NxTwoPi; + while (steerangle< -NxTwoPi) //normally just 1x + steerangle+= NxTwoPi; + + getWheelShape()->setSteerAngle(steerangle); + + + + +} + + +bool pWheel2::getContact(pWheelContactData&dst) +{ + + NxWheelContactData wcd; + NxShape* contactShape = mWheelShape->getContact(wcd); + dst.contactEntity = NULL; + if (contactShape) + { + + dst.contactForce = wcd.contactForce; + dst.contactNormal = getFrom(wcd.contactNormal); + dst.contactPoint= getFrom(wcd.contactPoint); + dst.contactPosition= wcd.contactPosition; + + + dst.lateralDirection= getFrom(wcd.lateralDirection); + dst.lateralImpulse= wcd.lateralImpulse; + dst.lateralSlip = wcd.lateralSlip; + + dst.longitudalDirection = getFrom(wcd.longitudalDirection); + dst.longitudalImpulse = wcd.longitudalImpulse; + dst.longitudalSlip= wcd.longitudalSlip; + + pSubMeshInfo *sInfo = static_cast(contactShape->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + dst.contactEntity = (CK3dEntity*)obj; + }else + { + dst.contactEntity = NULL; + } + } + + dst.otherShapeMaterialIndex = contactShape->getMaterial(); + + NxMaterial* otherMaterial = contactShape->getActor().getScene().getMaterialFromIndex(contactShape->getMaterial()); + if (otherMaterial) + { + pFactory::Instance()->copyTo(dst.otherMaterial,otherMaterial); + } + + return true; + + } + + return false; +} +pWheelContactData* pWheel2::getContact() +{ + NxWheelShape *wShape = getWheelShape(); + if (!wShape) + { + return new pWheelContactData(); + } + + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + + pWheelContactData result; + result.contactEntity = NULL; + + + if (contactShape) + { + + result.contactForce = wcd.contactForce; + result.contactNormal = getFrom(wcd.contactNormal); + result.contactPoint= getFrom(wcd.contactPoint); + result.contactPosition= wcd.contactPosition; + + + result.lateralDirection= getFrom(wcd.lateralDirection); + result.lateralImpulse= wcd.lateralImpulse; + result.lateralSlip = wcd.lateralSlip; + + result.longitudalDirection = getFrom(wcd.longitudalDirection); + result.longitudalImpulse = wcd.longitudalImpulse; + result.longitudalSlip= wcd.longitudalSlip; + + pSubMeshInfo *sInfo = static_cast(contactShape->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + result.contactEntity = (CK3dEntity*)obj; + }else + { + result.contactEntity = NULL; + } + } + + result.otherShapeMaterialIndex = contactShape->getMaterial(); + + NxMaterial* otherMaterial = contactShape->getActor().getScene().getMaterialFromIndex(contactShape->getMaterial()); + if (otherMaterial) + { + pFactory::Instance()->copyTo(result.otherMaterial,otherMaterial); + } + } + return &result; +} + +void pWheel2::_updateVirtoolsEntity(bool position,bool rotation) +{ + + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(getEntID())); + if (ent && position) + { + + NxWheelShape *wShape = getWheelShape(); + NxMat34 pose = wShape->getGlobalPose(); + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + NxVec3 suspensionOffsetDirection; + pose.M.getColumn(1, suspensionOffsetDirection); + suspensionOffsetDirection =-suspensionOffsetDirection; + + if (contactShape && wcd.contactForce > -1000) + { + + NxVec3 toContact = wcd.contactPoint - pose.t; + double alongLength = suspensionOffsetDirection.dot(toContact); + NxVec3 across = toContact - alongLength * suspensionOffsetDirection; + double r = wShape->getRadius(); + double pullBack = sqrt(r*r - across.dot(across)); + pose.t += (alongLength - pullBack) * suspensionOffsetDirection; + } else { + pose.t += wShape->getSuspensionTravel() * suspensionOffsetDirection; + } + + VxVector oPos = getFrom(pose.t); + ent->SetPosition(&oPos); + + if (hasGroundContact()) + { + + NxWheelShape *wShape = getWheelShape(); + NxMat34& wheelPose = wShape->getGlobalPose(); + +/* NxWheelContactData wcd; + NxShape* cShape = wShape->getContact(wcd); + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + VxVector gPos = getFrom(getWheelPose().t); + + /* + if( cShape && wcd.contactPosition <= (stravel + radius) ) + { + }*/ + + ////////////////////////////////////////////////////////////////////////// + + /*VxVector gPos = getFrom(getWheelPose().t); + //gPos*=-1.0f; + gPos -=getWheelPos(); + V 3. + xVector gPos2 = getFrom(getWheelShape()->getLocalPose().t); + ent->SetPosition(&gPos2,getBody()->GetVT3DObject()); + */ + }else + { +// VxVector gPos = getWheelPos(); +// ent->SetPosition(&gPos,getBody()->GetVT3DObject()); + } + } + if (ent && rotation) + { + + + //float rollAngle = getWheelRollAngle(); + //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + + VxQuaternion rot = pMath::getFrom( getWheelPose().M ); + ent->SetQuaternion(&rot,NULL); + } + + + NxWheelShape *wShape = getWheelShape(); + + //NxWheelShape *wShape = getWheelShape(); +/* + float rollAngle = getWheelRollAngle(); + //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + rollAngle+=wShape->getAxleSpeed() * ((1/60) * 0.01f); +*/ + + + + + /* + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + + + NxMat34& wheelPose = wShape->getGlobalPose(); + + NxWheelContactData wcd; + NxShape* cShape = wShape->getContact(wcd); + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( cShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } + + float rAngle = rollAngle; + float steer = wShape->getSteerAngle(); + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rollAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + setWheelPose(wheelPose); + + +*/ + +} + +void pWheel2::_updateAgeiaShape(bool position,bool rotation) +{ + +} + +float pWheel2::getRadius()const +{ + return mWheelShape->getRadius(); +} + +float pWheel2::getRpm() const +{ + + float a = NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; + if (getVehicle()) + { + + float b = NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * getVehicle()->_lastDT; + return b; + } + + return NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; +} +VxVector pWheel2::getWheelPos() const +{ + return getFrom(mWheelShape->getLocalPosition()); +} + +void pWheel2::setAngle(float angle) +{ + mWheelShape->setSteerAngle(-angle); +} + +NxActor*pWheel2::getTouchedActor()const +{ + NxWheelContactData wcd; + NxShape * s = mWheelShape->getContact(wcd); + if (s) + { + if (&s->getActor()) + { + return &s->getActor(); + }else + { + return NULL; + } + + }else + { + return NULL; + } + + return NULL; + //return s ? &s->getActor() : NULL; +} +float pWheel2::getAxleSpeed()const +{ + if (mWheelShape) + { + return mWheelShape->getAxleSpeed(); + } + return -1.f; + +} +bool pWheel2::hasGroundContact() const +{ + return getTouchedActor() != NULL; +} +void pWheel2::tick(bool handBrake, float motorTorque, float brakeTorque, float dt) +{ + if(handBrake && getWheelFlag(WF_AffectedByHandbrake)) + brakeTorque = 1000.0f; + + if(getWheelFlag(WF_Accelerated)) + mWheelShape->setMotorTorque(motorTorque); + + mWheelShape->setBrakeTorque(brakeTorque); + + /* + NxWheelShape *wShape = getWheelShape(); + float rollAngle = getWheelRollAngle(); + rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + NxMat34& wheelPose = wShape->getGlobalPose(); + + NxWheelContactData wcd; + NxShape* cShape = wShape->getContact(wcd); + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( cShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } + + float rAngle = rollAngle; + float steer = wShape->getSteerAngle(); + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rollAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + setWheelPose(wheelPose); + */ +} +VxVector pWheel2::getGroundContactPos()const +{ + VxVector pos = getWheelPos()+VxVector(0, -mWheelShape->getRadius(), 0); + + if (pos.Magnitude()) + { + int op2 = 0 ; + op2++; + } + return pos; +} + +float pWheel2::getSuspensionTravel()const +{ + + if (mWheelShape) + { + return mWheelShape->getSuspensionTravel(); + } + return 0.0f; +} + + +bool pWheel2::setSuspensionSpring(const pSpring& spring) +{ + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + NxWheelShape *wShape = getWheelShape(); + if (!wShape) + { + return false; + } + wShape->setSuspension(sLimit); + return true; +} + +void pWheel2::setAxleSpeed(float speed) +{ + + getWheelShape()->setAxleSpeed(speed); +} + +void pWheel2::setMotorTorque(float torque) +{ + getWheelShape()->setMotorTorque(torque); +} +void pWheel2::setBreakTorque(float torque) +{ + getWheelShape()->setBrakeTorque(torque); +} + +void pWheel2::setSuspensionTravel(float travel) +{ + getWheelShape()->setSuspensionTravel(travel); +} +pWheel2::pWheel2(pRigidBody *body,pWheelDescr *descr,CK3dEntity *wheelShapeReference): pWheel(body,descr) ,xEngineObjectAssociation(wheelShapeReference,wheelShapeReference->GetID()) +{ + this->setBody(body); + this->setEntity(wheelShapeReference); + + + + + brakingFactor = 0.05f; + frictionCoeff = 1.0f; + rollingCoeff = 1.0f; + + mWheelShape = NULL; + mWheelFlags = descr->wheelFlags; + _wheelRollAngle = 0.0f; + mVehicle = NULL; + lastContactData = new pWheelContactData(); + differentialSide=0; + differential = NULL; + hadContact = false; + + + slip2FCVelFactor = 1.0f; + + + tanSlipAngle=0; + slipAngle=0; + slipRatio=0; + lastU=0; + signU=1; // u>=0 + differentialSlipRatio=0; + + maxBrakingTorque = 400.0; + + + + + + lock = 80.0f; + ackermanFactor=1.1f; + tireRate = 180000; + mass = 10.0f; + + + + radius = descr->radius.value; + radiusLoaded = descr->radius.value; + + SetInertia(5.3f); + + relaxationLengthLat=0.91f; + relaxationLengthLong=0.091f; + + dampingSpeed = 0.15f; + dampingCoefficientLong = 1.5f; + dampingFactorLat=0.75; + dampingFactorLong=1.5f; + dampingCoefficientLat = 1.066f; + + + toe =-(1.0f/RR_RAD_DEG_FACTOR); + + rotation.Set(0,0,0); + rotation.y = toe; + + //---------------------------------------------------------------- + // + // pacejka + // + pacejka.setToDefault(); + //Statistical data (SR, SA in radians) + optimalSR=0.09655f; + optimalSA=0.18296f; + + + + + + stateFlags = 0; + lowSpeedFactor = 0.0f; + slipAngle = 0.0f; + slipRatio = 0.0f; + + overrideMask = 0; + callMask.set(CB_OnPostProcess,1); + callMask.set(CB_OnPreProcess,1); + + + preScript = postScript = 0; + entity = NULL; + + wheelContactModifyCallback =NULL; + + differential = NULL; + differentialSide =-1; + + + + +} +void pWheel2::setDifferential(pDifferential *diff,int side) +{ + differential=diff; differentialSide=side; + +} +float pWheel2::getEndBrakingTorqueForWheel() +{ + if(differential) + { + return differential->GetBreakTorqueOut(differentialSide); + } + return 0.0f; +} +float pWheel2::getEndTorqueForWheel() +{ + if(differential) + { +//*2*PI/60.0f + return differential->GetTorqueOut(differentialSide); + } + return 0.0f; +} + +float pWheel2::getEndAccForWheel() +{ + if(differential) + { + return differential->GetAccOut(differentialSide); + } + return 0.0f; +} + +float pWheel2::getWheelBreakTorque() +{ + if(mWheelShape) + { + return mWheelShape->getBrakeTorque(); + } + return 0.0f; +} +float pWheel2::getWheelTorque() +{ + if(mWheelShape) + { + return mWheelShape->getMotorTorque(); + } + return 0.0f; +} diff --git a/usr/Src/Core/pVehicle/pWheel2Run.cpp b/usr/Src/Core/pVehicle/pWheel2Run.cpp new file mode 100644 index 0000000..d071ef2 --- /dev/null +++ b/usr/Src/Core/pVehicle/pWheel2Run.cpp @@ -0,0 +1,378 @@ +#include +#include "vtPhysXAll.h" + +#include +#include "pWorldCallbacks.h" +#include "pCallbackSignature.h" + + + + +#include "virtools/vtTools.h" +#include "pVehicleAll.h" + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; +using namespace vtTools::BehaviorTools; + +bool pWheel2::isTorqueFromVehicle() +{ + return getWheelFlag(WF_Accelerated) && + getVehicle() && getVehicle()->isValidEngine() && + getDifferential() ; +} +bool pWheel2::isAxleSpeedFromVehicle() +{ + return ( getWheelFlag(WF_Accelerated) ) && + ( getWheelShape()->getWheelFlags() & WSF_AxleSpeedOverride ) && + getVehicle() && getVehicle()->isValidEngine() && getDifferential() ; +} +void pWheel2::applyTorqueToPhysics() +{ + if (getDifferential()) + { + + pDifferential *diff = getDifferential(); + + float finalTorqueOut = diff->GetTorqueOut(differentialSide); + + mWheelShape->setMotorTorque(finalTorqueOut); + + + + + + + // Add torque to body because of the accelerating drivetrain + // This gives a bit of the GPL effect where your car rolls when + // you throttle with the clutch disengaged. + + float tr=getVehicle()->getEngine()->GetTorqueReaction(); + if(tr>0) + { +// VxVector torque(0,0,diff->GetAccIn()*diff->inertiaIn*tr); +// getBody()->addTorque(torque); + } + + /* if( (wheel->getWheelShape()->getWheelFlags() & WSF_AxleSpeedOverride ) ) + { + float v = wheel->rotationV.x; + v = v * getEngine()->getEndRotationalFactor() * getEngine()->getTimeScale(); + } + */ + } +} + +void pWheel2::_createInternalContactModifyCallback() +{ + + if (mWheelShape) + { + if (!wheelContactModifyCallback) + { + wheelContactModifyCallback = new pWheelContactModify(); + wheelContactModifyCallback->setWheel(this); + mWheelShape->setUserWheelContactModify((NxUserWheelContactModify*)wheelContactModifyCallback); + + } + + //---------------------------------------------------------------- + //track information about callback + if (getBody()) + getBody()->getCallMask().set(CB_OnWheelContactModify,true); + } + + +} + +bool pWheelContactModify::onWheelContact(NxWheelShape* wheelShape, + NxVec3& contactPoint, + NxVec3& contactNormal, + NxReal& contactPosition, + NxReal& normalForce, + NxShape* otherShape, + NxMaterialIndex& otherShapeMaterialIndex, + NxU32 otherShapeFeatureIndex) +{ + pWheel2 *wheel = static_cast(getWheel()); + if (!getWheel()) + return true; + + + int contactModifyFlags = 0 ; + bool createContact=true; + + + //---------------------------------------------------------------- + // + // store compact : + // + if (wheel->getBody()->getCallMask().test(CB_OnWheelContactModify)) + { + pWheelContactModifyData &contactData = lastData; + contactData.object = getEntityFromShape(wheelShape); + contactData.contactNormal = getFrom(contactNormal); + contactData.contactPoint = getFrom(contactPoint); + contactData.contactPosition = contactPosition; + contactData.normalForce = normalForce; + contactData.otherMaterialIndex = otherShapeMaterialIndex; + + createContact = wheel->onWheelContactModify(contactModifyFlags,&contactData); + + + if (!createContact) + return false; + + if (contactModifyFlags==0) + return true; + + //---------------------------------------------------------------- + // + // copy result back to sdk + // + contactNormal = getFrom(contactData.contactNormal); + contactPoint = getFrom(contactData.contactPoint); + contactPosition = contactData.contactPosition; + normalForce = contactData.normalForce; + + + } + + //xWarning("whatever"); + return true; +} +bool pWheel2::onWheelContactModify(int& changeFlags,pWheelContactModifyData* contact) +{ + + + + bool result = true; + //---------------------------------------------------------------- + // + // sanity checks + // + if (!contact) + return true; + + //---------------------------------------------------------------- + // + // keep some informationens for our self + // + if( getProcessOptions() & pVPO_Wheel_UsePHYSX_Load && + getProcessOptions() & pVPO_Wheel_UsePHYSX_CONTACT_DATA && getVehicle() + ) + { + load = contact->contactNormal.y; + + if (load > 1500) + load = 1500; + + if (load <= 0) + load = 1000; + + + } + + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(getWheelContactScript()); + if (beh && CKGetObject(ctx(),getEntID())) + { + + SetInputParameterValue(beh,bbIWC_SrcObject,getEntID()); + + SetInputParameterValue(beh,bbIWC_Point,contact->contactPoint); + SetInputParameterValue(beh,bbIWC_Normal,contact->contactNormal); + SetInputParameterValue(beh,bbIWC_Position,contact->contactPosition); + SetInputParameterValue(beh,bbIWC_NormalForce,contact->normalForce); + SetInputParameterValue(beh,bbIWC_OtherMaterialIndex,contact->otherMaterialIndex); + //---------------------------------------------------------------- + // + // execute: + // + beh->Execute(lastStepTimeSec); + + //---------------------------------------------------------------- + // + // refuse contact + // + result = GetOutputParameterValue(beh,bbOWC_CreateContact); + if (!result) + return false; + + //---------------------------------------------------------------- + // + // nothing changed, return true + // + changeFlags = GetOutputParameterValue(beh,bbOWC_ModificationFlags); + if (changeFlags == 0 ) + { + return true; + } + + //---------------------------------------------------------------- + // + // pickup data, according to change flags + // + if (changeFlags & CWCM_ContactPoint ) + contact->contactPoint = GetOutputParameterValue(beh,bbOWC_Point); + + if (changeFlags & CWCM_ContactNormal) + contact->contactNormal= GetOutputParameterValue(beh,bbOWC_Normal); + + if (changeFlags & CWCM_ContactPosition ) + contact->contactPosition= GetOutputParameterValue(beh,bbOWC_Position); + + if (changeFlags & CWCM_NormalForce ) + contact->normalForce = GetOutputParameterValue(beh,bbOWC_NormalForce); + } + + + + return true; + +} + +bool pWheel2::onWheelContact(CK3dEntity* wheelShapeReference, VxVector& contactPoint, VxVector& contactNormal, float& contactPosition, float& normalForce, CK3dEntity* otherShapeReference, int& otherShapeMaterialIndex) +{ + //NxUserAllocator + return true; +} + +void pWheel2::setWheelContactScript(int val) +{ + + CKBehavior * beh = (CKBehavior*)GetPMan()->GetContext()->GetObject(val); + if (!beh) + return; + + XString errMessage; + if (!GetPMan()->checkCallbackSignature(beh,CB_OnWheelContactModify,errMessage)) + { + xError(errMessage.Str()); + return; + } + + pCallbackObject::setWheelContactScript(val); + + wheelContactModifyCallback = new pWheelContactModify(); + wheelContactModifyCallback->setWheel(this); + + getWheelShape()->setUserWheelContactModify((NxUserWheelContactModify*)wheelContactModifyCallback); + + + //---------------------------------------------------------------- + //track information about callback + getBody()->getCallMask().set(CB_OnWheelContactModify,true); + + +} +void pWheel2::processPreScript() +{ + +} +void pWheel2::processPostScript() +{ + +} +int pWheel2::onPostProcess() +{ + + return 1; +} +int pWheel2::onPreProcess() +{ + + return 1; +} + +void pWheel2::_tick(float dt) +{ + + + + float dt2 = dt; + + + NxWheelShape *wShape = getWheelShape(); + if (!wShape) return; + + + NxVec3 _localVelocity; + bool _breaking=false; + + NxWheelContactData wcd; + + NxShape* contactShape = wShape->getContact(wcd); + + if (contactShape) + { + + NxVec3 relativeVelocity; + if ( !contactShape->getActor().isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - contactShape->getActor().getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + _breaking = false; //NxMath::abs(_localVelocity.z) < ( 0.1 ); + // wShape->setAxleSpeed() + } + + + float rollAngle = getWheelRollAngle(); + + rollAngle+=wShape->getAxleSpeed() * (dt); + //rollAngle+=wShape->getAxleSpeed() * (1.0f/60.0f /*dt* 0.01f*/); + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + + NxMat34& wheelPose = wShape->getGlobalPose(); + + + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( contactShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } + + + float rAngle = getWheelRollAngle(); + float steer = wShape->getSteerAngle(); + + NxVec3 p0; + NxVec3 dir; + /* + getWorldSegmentFast(seg); + seg.computeDirection(dir); + dir.normalize(); + */ + NxReal r = wShape->getRadius(); + NxReal st = wShape->getSuspensionTravel(); + NxReal steerAngle = wShape->getSteerAngle(); + p0 = wheelPose.t; //cast from shape origin + wheelPose.M.getColumn(1, dir); + dir = -dir; //cast along -Y. + NxReal castLength = r + st; //cast ray this long + + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + setWheelPose(wheelPose); +} diff --git a/usr/Src/Core/pVehicle/pWheelCalc.cpp b/usr/Src/Core/pVehicle/pWheelCalc.cpp new file mode 100644 index 0000000..b604465 --- /dev/null +++ b/usr/Src/Core/pVehicle/pWheelCalc.cpp @@ -0,0 +1,1275 @@ +#include +#include "vtPhysXAll.h" + +#include + +#include "pDifferential.h" + +#include "pVehicleAll.h" + +//+ velWheelCC {x=66.735077 y=0.097698294 z=-215.35669 ...} VxVector +//+ velWheelTC {x=66.735077 y=0.097698294 z=-215.35669 ...} VxVector + + +enum StateFlags +{ + ON_SURFACE=1, // Wheel is touching surface? + ATTACHED=2, // Attached to suspension? + LOW_SPEED=4 // Wheel is turning slow +}; + + +#define FRICTION_COEFF 100.0f +#define MASS 12 +#define TIRE_RATE 50000.0f +#define WHEEL_PENETRATION_DEPTH -0.0258f +#define WHEEL_SUSPENSION_FORCE VxVector(0,-1025.0f,0) +#define RR_EPSILON_VELOCITY 0.001 // Wheel velocity +#define OPT_SLIPVECTOR_USES_TANSA + + + +// Use full 3D patch for surface detection? +#define USE_3D_PATCH + +#define ENV_INI "env.ini" + +// For method #3, slipVector (Gregor Veble), use tan(SA) or SA? +#define OPT_SLIPVECTOR_USES_TANSA + +// Skid methods +//#define SKID_METHOD_SEPARATE_LON_LAT +//#define SKID_METHOD_SLIP_RA_VECTOR +#define SKID_METHOD_Z_GREGOR + +// Point at which skidmarks appear +#define SKIDMARK_SLIPRATIO 0.2 + +// Apply damping to slipRatio/slipAngle differential eq's at low speed? +//#define DO_DAMPING_LAT +//#define DO_DAMPING_LONG + + +// Apply low-speed enhancements? (obsolete since 18-5-01) +#define DO_LOW_SPEED + +// Distance (in m) to start with wheel ray-track intersection; this is +// the height at which the ray is started to avoid getting a ray +// that starts BENEATH the track surface and therefore not hitting it. +#define DIST_INTERSECT 1.0 + +// Define the next symbol to check for wheel velocity reversal (vertically), +// and if so, the wheel is stopped momentarily. Is used to rule out +// incredibly high damper forces from pushing the wheel to full up or down. +// Should perhaps not be needed anymore combined with the implicit integrator. +// Note that this acts at the outermost positions of the wheel. +//#define DAMP_VERTICAL_VELOCITY_REVERSAL + +// Damp the wheel when crossing the equilibrium position? +// As the wheel passes its center position, the spring force reverses. To +// avoid adding energy into the system, when passing this position, damping +// is used to avoid overaccelerating the tire to the other side. +// Note that this acts when the wheel is near its center (rest) position, +// contrast this with DAMP_VERTICAL_VELOCITY_REVERSAL. +#define DAMP_VERTICAL_EQUILIBRIUM_REVERSAL + +// Use implicit integration? This should be more stable with +// high damper rates. +#define INTEGRATE_IMPLICIT_VERTICAL + +// Gregor Veble combined slip algorithm? (instead of Pacejka) +//#define DO_GREGOR +#ifdef DO_GREGOR + #undef DO_DAMPING_LAT + #undef DO_DAMPING_LONG +#endif + +// Delayed slip angle? +//#define USE_SAE950311_LAT + +// If not using SAE950311, damp SA at low speed? (to avoid jittering) +#define USE_SA_DAMPING_AT_LOW_SPEED + +// Wheel locking results in force going the direction of -slipVector? +#define USE_WHEEL_LOCK_ADJUST + +#define USE_NXWHEEL_CONTACT_DATA + +#define USE_NXWHEEL_NORMALFORCE_LOAD + + + + +static int getFrictionMethod(){ return FC_SLIPVECTOR; } + + + + + + +void pWheel2::CalcPacejka() +{ + + float normalForce; + + + if (hadContact) + { + normalForce=forceRoadTC.y; + }else{ + normalForce = 0.0f; + } + +/* + if (hadContact) + { + normalForce=500.0f; + }else{ + normalForce = 0.0f; + } +*/ + + + pacejka.SetCamber(0); + + bool FC_SLIPVECTOR =true; + // Note our positive slipAngle is the reverse of SAE's definition + if(FC_SLIPVECTOR) + { + // Gregor Veble's and also Brian Beckman's idea of mixing Pacejka + // Note that Gregor's Veble 'z' is 'csSlipLen' here. + // The load isn't touched + pacejka.SetNormalForce(normalForce); + // Lateral + //qdbg(" csSlipLen=%f, oSA=%f,oSR=%f\n",csSlipLen,optimalSA,optimalSR); + if(csSlipLenfrictionFactor!=1.0f) + { + + float frictionFactor = 0.1f; + pacejka.SetFx(pacejka.GetFx()*frictionFactor); + pacejka.SetFy(pacejka.GetFy()*frictionFactor); + // Do the same to the aligning moment, although not scientifically + // based (does aligning torque scale linearly with surface friction?) + pacejka.SetMz(pacejka.GetMz()*frictionFactor); + pacejka.SetMaxLongForce(pacejka.GetMaxLongForce()*frictionFactor); + pacejka.SetMaxLatForce(pacejka.GetMaxLatForce()*frictionFactor); + } +*/ + + //forceRoadTC.z=pacejka.GetFx(); + + //---------------------------------------------------------------- + // + // old + // + + /* + float factor = getVehicle()->getEngine()->getForceFeedbackScale(); + float longitudalImpulse = xCheckFloat(lastContactData->longitudalImpulse); + if (lastContactData) + { + forceRoadTC.z= longitudalImpulse * factor; + }*/ + + // Put some results in appropriate variables + #ifdef LTRACE + qdbg(" pacejka.Fx=%f\n",pacejka.GetFx()); + #endif + + float fx = pacejka.GetFx();; + forceRoadTC.z=pacejka.GetFx(); + +} + + + + +void ConvertTireToCarOrientation(pWheel2 * wheel , VxVector *from,VxVector *to) +// Convert vector 'from' from tire coordinates +// to car coordinates (into 'to') +// Assumes: from!=to +{ + if (!wheel) + return; + + float angle,sinAngle,cosAngle; + + // Note that the tire is constrained in 5 dimensions, so only + // 1 rotation needs to be done + + // Heading + angle=wheel->GetHeading(); + sinAngle=sin(angle); + cosAngle=cos(angle); + + // Rotate around Y axis to get heading of car right + to->x=from->z*sinAngle+from->x*cosAngle; + to->y=from->y; + to->z=from->z*cosAngle-from->x*sinAngle; +} + +void ConvertCarToTireOrientation (pWheel2*wheel, VxVector *from,VxVector*to) +// Convert vector 'from' from car coordinates +// to tire coordinates (into 'to') +// Assumes: from!=to +{ + if (!wheel) + return; + + float angle,sinAngle,cosAngle; + + // Heading + angle=-wheel->GetHeading(); + + if(fabs(angle)x=from->z*sinAngle+from->x*cosAngle; + to->y=from->y; + to->z=from->z*cosAngle-from->x*sinAngle; + //to->DbgPrint("C2T to"); +} + + +void pWheel2::calcVerticalForces() +{ + VxVector downGravity; + //float mass = getVehicle()->getBody()->getMass(); + + NxVec3 grav; + getVehicle()->getBody()->getActor()->getScene().getGravity(grav); + + + downGravity.y = -mass * -grav.y ; + if (getEntity()) + { + getEntity()->TransformVector(&forceGravityCC,&downGravity); + } + + forceVerticalCC=forceGravityCC+forceRoadTC+WHEEL_SUSPENSION_FORCE; + + float inverseWheelMass = mWheelShape->getInverseWheelMass(); + + +} +void pWheel2::calcLongForces() +{ + if (lastContactData) + { + + // + // LONGITUDINAL FORCES + // + + // Differential will do resulting long. torques for the engine + + // Calculate longitudinal road reaction force using Pacejka's magic formula + float pf; + + // Pacejka + float factor = getVehicle()->getEngine()->getForceFeedbackScale(); + float longitudalImpulse = xCheckFloat(lastContactData->longitudalImpulse); + + //qdbg("Pacejka Fx=%f, signU=%f\n",pf,signU); + forceRoadTC.z= factor * longitudalImpulse * signU ; + } + + + + + +} + +void pWheel2::calcBreakForces() +{ + + +} + + +void pWheel2::preAnimate() +{ + + //---------------------------------------------------------------- + // + // store last contact + // + hadContact = getContact(*lastContactData); + //---------------------------------------------------------------- + // + // reset + // + forceRoadTC.Set(0,0,0); + torqueTC.Set(0,0,0); + torqueFeedbackTC.Set(0,0,0); + dampingFactorLong=dampingFactorLat=0; + forceVerticalCC.Set(0,0,0); + forceDampingTC.Set(0,0,0); + torqueTC.Set(0,0,0); + torqueFeedbackTC.Set(0,0,0); + velWheelTC.Set(0,0,0); + velWheelCC.Set(0,0,0); + + + + + + //signU = ( getVehicle()->_currentStatus & VS_IsRollingForward ) ? 1.0f : - 1.0f; + + CalcLoad(); + CalcSlipAngle(); + CalcSlipRatio(&velWheelTC); + + + float tanOptimalSA=tan(0.18296f); + float optimalSR=0.0965f; + bool make =true; + + if(getFrictionMethod() == FC_SLIPVECTOR) + { + // Calculate SA/SR vector length (>1 = wanting more than tire supports) + + float lat,lon; + if (getVehicle()->getProcessOptions() & pVPO_SV_Tansa ) + lat=tanSlipAngle/tanOptimalSA; + else + lat=slipAngle/optimalSA; + + + lon=slipRatio/optimalSR; + csSlipLen=sqrtf(lat*lat+lon*lon); + + //qdbg(" latNrm=%f, lonNrm=%f, csSlipLen=%f\n",lat,lon,csSlipLen); + } + + + + CalcSlipVelocity(); + + // Low speed detection + + + if (getVehicle()->getProcessOptions() & pVPO_CheckLowSpeed) + { + float lowSpeed = 0.03f; + if(rotationV.x>-lowSpeed&&rotationV.xGetValue(coeff); + else*/ + this->frictionCoeff=1.0f; + + + +} +void pWheel2::CalcLoad() +{ + if (hadContact) + { + //forceRoadTC.y=-50*0.057598811f;// float; lastContactData->contactForce; + + if ( (getVehicle()->getProcessOptions() & pVPO_Wheel_UsePHYSX_Load) && + (getVehicle()->getProcessOptions() & pVPO_Wheel_UsePHYSX_CONTACT_DATA) + ) + { + forceRoadTC.y = load; + } + else{ + + forceRoadTC.y=-tireRate * WHEEL_PENETRATION_DEPTH;// float; lastContactData->contactForce; + } + + stateFlags|=ON_SURFACE; + }else + { + stateFlags&=~ON_SURFACE; + forceRoadTC.y = 0.0f; + } + + //load=forceRoadTC.y; + + radiusLoaded=getWheelShape()->getRadius(); +} +void pWheel2::calcForces() +{ + + if (hadContact) + { + + + float len; + + + float pf=0.0f; + float radiusLoaded = getRadius(); + + //---------------------------------------------------------------- + // + // vertical forces + // + + NxVec3 grav;getBody()->getActor()->getScene().getGravity(grav); + + VxVector forceGravityWC; + forceGravityWC.y = getMass() * grav.y; + + if (getEntity()) + getEntity()->TransformVector(&forceGravityCC,&forceGravityWC); + + VxVector suspension; + suspension.y = -load; + forceVerticalCC=forceGravityCC+forceRoadTC+suspension; + + + + //---------------------------------------------------------------- + // + // long forces + // + + // + // LONGITUDINAL FORCES + // + + // Differential will do resulting long. torques for the engine + + // Calculate longitudinal road reaction force using Pacejka's magic formula + // Pacejka + //float factor = getVehicle()->getEngine()->getForceFeedbackScale(); + //float longitudalImpulse = xCheckFloat(lastContactData->longitudalImpulse); + //qdbg("Pacejka Fx=%f, signU=%f\n",pf,signU); + //forceRoadTC.z= factor * longitudalImpulse * signU ; + + //---------------------------------------------------------------- + // + // + // + + + #ifdef DO_GREGOR + pf=Fx; + #else + // Pacejka + pf=pacejka.GetFx()*this->frictionCoeff; + #endif + + //qdbg("Pacejka Fx=%f, signU=%f\n",pf,signU); + forceRoadTC.z=signU*pf; + + + if ( getVehicle()->getProcessOptions() & pVPO_Lat_Damping ) + { + // Add damping force because of slipRatio vibrations + // at low speed (SAE950311) + forceRoadTC.z+=forceDampingTC.z; + //qdbg("FroadTC.z=%f, Fdamp=%f\n",forceRoadTC.z,forceDampingTC.z); + } + + + //---------------------------------------------------------------- + // + // Calculate braking forces & torques (brakes & rolling resistance) + // + float curBrakingTorque; + // Calculate braking torque more directly + + float bTorqueV = getVehicle()->calculateBraking( getVehicle()->_lastDT ); + + curBrakingTorque= bTorqueV * maxBrakingTorque/1000.0f; + curBrakingTorque*=brakingFactor; + // Apply braking torque in the reverse direction of the wheel's rotation + if(rotationV.x>0) + { + torqueBrakingTC.x=curBrakingTorque; + } + else + { + torqueBrakingTC.x=-curBrakingTorque; + } + forceBrakingTC.z=torqueBrakingTC.x/radiusLoaded; + + // Calculate feedback torque (goes back to differential) + // This doesn't include braking and rolling resistance, which are + // potential braking forces (which may not be fully used if the + // wheel is not rotating), but only the forces which are always + // there, like road reaction. + torqueFeedbackTC.x=-forceRoadTC.z*radiusLoaded; + + //---------------------------------------------------------------- + // + // + // + // Calculate rolling resistance (from John Dixon, Fr=u*Fv + // where Fv is the normal force, and 'u' the rolling coefficient) + // Rolling coefficient may need to go up with speed though + //forceRoadTC.y = pf; + + + if(rotationV.x>0) + torqueRollingTC.x=-rollingCoeff*forceRoadTC.y*radiusLoaded; + else + torqueRollingTC.x=rollingCoeff*forceRoadTC.y*radiusLoaded; + + // Calculate total braking torque (this is POTENTIAL, not always acted upon!) + torqueBrakingTC.x=-forceBrakingTC.z*radiusLoaded; + torqueBrakingTC.x+=torqueRollingTC.x; + + // + // lateral forces : + // + /*float lateralForce = xCheckFloat(lastContactData->lateralImpulse); + factor = getVehicle()->getEngine()->getForceFeedbackScale(); + forceRoadTC.x= signU*lateralForce * factor ; + */ + + #ifdef DO_GREGOR + pf=Fy; + #else + pf=pacejka.GetFy()*frictionCoeff; + #endif + //pf=forceRoadTC.x; + + #ifdef OBS + qdbg("Pacejka Fy(lat)=%f, SR=%f, SA=%f, load=%f\n",pf,slipRatio,slipAngle,load); + #endif + + forceRoadTC.x=pf; + + + if(getProcessOptions() & pVPO_Forces_No_Lateral) + { + // Cancel lateral forces + pacejka.SetFy(0); + forceRoadTC.x=0; + } + + if (getProcessOptions() & pVPO_Lat_Damping ) + { + + // Add damping force because of slipAngle vibrations + // at low speed (SAE950311) + // Note the mix of 2 coordinate systems here + forceRoadTC.x+=forceDampingTC.x; + //qdbg("Damping fRoad.x=%f, Fdamp=%f\n",forceRoadTC.x,forceDampingTC.x); + } + + // WHEEL LOCKING + + if(getVehicle()->getProcessOptions() & pVPO_Wheel_LockAdjust ) + goto skip_wla; + + + + if(slipRatio<0) + { + + VxVector forceLockedCC,forceLockedTC; + float slideFactor,oneMinusSlideFactor,lenSlip,lenNormal,y; + + // As the wheel is braked, more and more sliding kicks in. + // At the moment of 100% slide, the braking force points + // in the reverse direction of the slip velocity. Inbetween + // SR=0 and SR=-1 (and beyond), there is more and more sliding, + // so the force begins to point more and more like the slip vel. + + + // Calculate sliding factor (0..1) + if(slipRatio<-1.0f) + slideFactor=1.0f; + else + slideFactor=-slipRatio; + + //slideFactor*=.75f; + oneMinusSlideFactor=1.0f-slideFactor; + // Calculate 100% wheel lock direction + forceLockedCC.x=slipVectorCC.x; + forceLockedCC.y=0; + forceLockedCC.z=slipVectorCC.z; + // Make it match forceRoadTC's coordinate system + + ConvertCarToTireOrientation(this,&forceLockedCC,&forceLockedTC); + + + // Calc magnitude of normal and locked forces + lenSlip=forceLockedTC.Magnitude(); + + y=forceRoadTC.y; forceRoadTC.y=0; + lenNormal=forceRoadTC.Magnitude(); + forceRoadTC.y=y; + if(lenSlipgetGearBox()->GetTorqueForWheel(this); + + // + // ROTATIONAL acceleration + // + oldVX=rotationV.x; + + + //---------------------------------------------------------------- + // + // + // + // + // ROTATIONAL acceleration + // + //#define OBS + #ifdef OBS + // Check for locked wheel braking + //float netForce= getVehicle()->getEngine()->forEngin .z+forceRoadTC.z; + //qdbg("Fe=%f, Fr=%f, Fb=%f\n",forceEngineTC.z,forceRoadTC.z,forceBrakingTC.z); + if(rotationV.x>-RR_EPSILON_VELOCITY&&rotationV.x-netForce)|| + (netForce>0&&forceBrakingTC.z<-netForce)) + //if(forceBrakingTC.z<-netForce||forceBrakingTC.z>netForce) + { + //qdbg("RWh:Int; braking force keeps wheel still\n"); + rotationV.x=0; + goto skip_rot; + } + } + #endif + + + + + float timeStep= lastStepTimeSec; + + + + float a = rotationA.x*timeStep ; + rotationV.x+=rotationA.x*timeStep; + //skip_rot: + + // Check for wheel velocity reversal; in this case, damp the + // velocity to a minimum to get rid of jittering wheels at low + // speed and/or high braking. + if(differential) + { + if(oldVX>0&&rotationV.x<0) + { + // Lock the side + //qdbg("RWh%d; vel reversal, lock\n",wheelIndex); + differential->Lock(differentialSide); + rotationV.x=0; + differentialSlipRatio=0; + } else if(oldVX<0&&rotationV.x>0) + { + //qdbg("RWh%d; vel reversal, lock\n",wheelIndex); + // Lock the side + differential->Lock(differentialSide); + rotationV.x=0; + differentialSlipRatio=0; + } + } else + { + // No differential, use controlled jittering + if(oldVX>=0&&rotationV.x<0) + { + // Just lift the rotation over the 0 barrier; this will induce + // jittering near 0, but it's so small that it's unnoticeable. + // If we keep it at 0, you get larger jitters either way (+/-) + // until the wheel rotates again and starts the reversal again. + rotationV.x=-0.0001; + } else if(oldVX<=0&&rotationV.x>0) + { + rotationV.x=0.0001; + } + } + //qdbg(" rotV after velocity reversal=%f\n",rotationV.x); + + // Wheel rotation (spinning) + // + + float rotVx =rotation.x; + rotation.x+=rotationV.x*timeStep; + //rotation.x+=(rotationV.x+0.5f*rotationA.x*timeStep)*timeStep; + //rotation.x+=rotationV.x*timeStep; + // Keep rotation in limits + while(rotation.x>=2*PI) + rotation.x-=2*PI; + while(rotation.x<0) + rotation.x+=2*PI; + + // Friction reversal measures + if( (oldVX<0&&rotationV.x>0) || (oldVX>0&&rotationV.x<0) ) + { + rotationV.x=0; + + //qdbg("RWh:Int; friction reversal halt; %f -> %f\n",oldVX,rotationV.x); + } +} + +void pWheel2::CalcWheelAngAcc() +{ + if(differential) + { + // Use differential to determine acceleration + if(differential->IsLocked(differentialSide)) + { + // Wheel is held still by braking torques + rotationA.x=0; + } else + { + // Wheel is allowed to roll + rotationA.x=differential->GetAccOut(differentialSide); + } + //qdbg("diff=%p, diffSide=%d\n",differential,differentialSide); + } else + { + // Uses torque directly (no engine/differential forces) + rotationA.x=(torqueFeedbackTC.x+torqueBrakingTC.x)/GetInertia(); + } +} + +void pWheel2::CalcAccelerations() +{ + + rotationA.Set(0,0,0); + + CalcWheelAngAcc(); + //CalcBodyForce(); + + // Vertical forces; suspension, gravity, ground, tire rate + //acceleration=forceVerticalCC/GetMass(); + acceleration.x=acceleration.z=0.0f; + acceleration.y=forceVerticalCC.y/mass; + + + +#ifdef OBS + qdbg("RWh:AF; forceVerticalCC.y=%f, mass=%f\n",forceVerticalCC.y,MASS); +#endif + +} + + + +void pWheel2::CalcSlipRatio(VxVector *velWheelCC) +{ + + //rfloat vGround,vFreeRolling; + + float lastTime =lastStepTimeSec; + + /* + lastTime*=0.1f; +*/ + + //velWheelTC->DbgPrint("velWheelTC in CalcSR"); + if(!hadContact) + { + //qdbg("CalcSR; not on surface\n"); + // Not touching the surface, no slip ratio + slipRatio=0; + // Tire vibrations stop + differentialSlipRatio=0; + return; + } + + // SAE950311 algorithm + float u,delta,B; + u=velWheelTC.z; + B=relaxationLengthLong; + + // Switch to normal slip ratio calculations when there is + // speed (in the case when the velocities catch up on the timestep) + // Notice this test can be optimized, because the timestep and B + // are constants, so a 'turningPointU' can be defined. + //qdbg("Threshold: %f\n",u*RR_TIMESTEP/B); + + float t0 = u*lastTime; + bool tc = B>0.5 ? true : false; + + + + if(u*lastTime/B>0.5) + { + //---------------------------------------------------------------- + // + // changed : + // + //float wheelSlipRatio + + slipRatio=rotationV.x*radiusLoaded/u-1; + //slipRatio = lastContactData->longitudalSlip; + + return; + // Use straightforward slip ratio + slipRatio=rotationV.x*radiusLoaded/u-1; + //qdbg("'u' big enough; straight SR %f\n",slipRatio); + return; + } + + if((lastU<0&&u>=0)||(lastU>=0&&u<0)) + { + // 'u' changed sign, reverse slip + //qdbg("'u' changed sign from %f to %f; SR=-SR\n",u,lastU); + //differentialSlipRatio=-differentialSlipRatio; + // Damp while reversing slip; we're close to a standstill. + float dampSRreversal = 0.2f; + differentialSlipRatio=-dampSRreversal*differentialSlipRatio; + } + lastU=u; + // Detect sign of 'u' (real velocity of wheel) + if(u<0)signU=-1.0f; else signU=1.0f; + + // Eq. 26 + //delta=(fabs(u)-rotationV.x*radius*signU)/B-(fabs(u)/B)*differentialSlipRatio; + if(u<0) + { + // Eq. 25 + delta=(-u+rotationV.x*radius)/B+(u/B)*differentialSlipRatio; + } else + { + // Eq. 20 + delta=(u-rotationV.x*radius)/B-(u/B)*differentialSlipRatio; + } + + + // Integrate + differentialSlipRatio+=delta*lastTime; + if(differentialSlipRatio>10)differentialSlipRatio=10; + else if(differentialSlipRatio<-10)differentialSlipRatio=-10; + // Set slip ratio for the rest of the sim. Note that + // we use a different slip ratio definition from that of SAE950311 + //qdbg(" old SR=%f => new SR=%f\n",slipRatio,-differentialSlipRatio); + slipRatio=-differentialSlipRatio; + + +} + +void pWheel2::updatePosition() +{ + NxMat34 &wheelPose = getWheelPose(); + NxWheelContactData wcd; + NxShape* contactShape = mWheelShape->getContact(wcd); + NxReal stravel = mWheelShape->getSuspensionTravel(); + NxReal radius = mWheelShape->getRadius(); + //have ground contact? + if( contactShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } +} + +void pWheel2::updateSteeringPose(float rollangle,float steerAngle,float dt) +{ + + float rollAngle = getWheelRollAngle(); + + rollAngle+=getWheelShape()->getAxleSpeed() * (dt * 0.01f); + + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + + NxMat34& wheelPose = mWheelShape->getGlobalPose(); + + + NxReal stravel = mWheelShape->getSuspensionTravel(); + NxReal radius = mWheelShape->getRadius(); + + + + float rAngle = getWheelRollAngle(); + float steer = mWheelShape->getSteerAngle(); + + + NxVec3 dir; + + NxReal r = mWheelShape->getRadius(); + NxReal st = mWheelShape->getSuspensionTravel(); + + + wheelPose.M.getColumn(1, dir); + dir = -dir; //cast along -Y. + NxReal castLength = r + st; //cast ray this long + + + NxMat33 rot, axisRot, rollRot; + rot.rotY( mWheelShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + + setWheelPose(wheelPose); + +} + + + + + + + + + +void pWheel2::CalcSlipAngle() +// Based on the wheel world velocity and heading, calculate +// the angle from the wheel heading to the wheel's actual velocity +// Contrary to SAE, our Y-axis points up, and slipAngle>0 means +// in our case that the you're in a right turn (basically) +// 31-03-01: SAE950311 implementation (using relaxation lengths +// and a differential equation for the slip angle) for low-speed etc. +{ + + + VxVector velWheelWC; + + if(!hadContact) + { + //qdbg("CalcSA; not on surface\n"); + // Not touching the surface, no need to do slip angle + slipAngle=0; + // Tire springs back to 0 instantly (should be slowly actually) + tanSlipAngle=0; + velWheelTC.Set(0,0,0); + velWheelCC.Set(0,0,0); + return; + } + + + int options = getProcessOptions(); + + if (options & pVPO_Wheel_UsePHYSX_CONTACT_DATA ) + { + + /* + VxVector dir,up,right; + getEntity()->GetOrientation(&dir,&up,&right); + */ + + VxVector point= lastContactData->contactPoint; + if( lastContactData->contactPosition <= ( getWheelShape()->getSuspensionTravel() + radius) ) + point.y+=getRadius(); + else + point.y = getWheelPose().t.y - getSuspensionTravel(); + + //getEntity()->TransformVector(&point,&point); +/* + getBody()->GetVT3DObject()->InverseTransformVector(&point,&point); + + /* + + getEntity()->InverseTransformVector(&contactLocal,&point); + + VxVector contactLocal2; + getEntity()->InverseTransform(&contactLocal,&point); +*/ + + getBody()->GetVT3DObject()->InverseTransform(&point,&point); + + velWheelCC = getBody()->getLocalPointVelocity(point); + //getEntity()->TransformVector(&velWheelCC,&velWheelCC); + ConvertCarToTireOrientation(this,&velWheelCC,&velWheelTC); + + + } + + if ( options & pVPO_SA_Delay ) + { + // Derive change in tan(slipAngle) using SAE950311 + // u=longitudinal velocity, v=lateral velocity + float u,b,v,delta; + u=velWheelTC.z; + v=velWheelTC.x; + b=relaxationLengthLat; + + if ( options & pVPO_SA_DownSettle) + { + // Make sure SA settles down at low speeds + float min=5.0f; + if(u=0.0f)u=min; + else if(u>-min&&u<=0)u=-min; + } + + + // Calculate change in tan(SA) + delta=(v/b)-(fabs(u)/b)*tanSlipAngle; + if( getWheelFlag(WF_Accelerated) && getVehicle() ) + { + //qdbg("CSA; u=%f, v=%f, delta=%f, tanSA=%f, SA=%f\n",u,v,delta,tanSlipAngle,slipAngle); + // qdbg("delta=%f, tanSA=%f, SA=%f\n",delta,tanSlipAngle,atan(tanSlipAngle)); + // Integrate + tanSlipAngle+=delta*lastStepTimeMS; + // Derive new slip angle from state variable 'tanSlipAngle' + slipAngle=atanf(tanSlipAngle); + + } + }else + { + + // Calculate wheel velocity because of rotation around yaw (Y) axis + + /*velWheelCC.x+=car->GetBody()->GetRotVel()->y*cos(-angleCGM)*distCGM; + velWheelCC.z+=car->GetBody()->GetRotVel()->y*sin(-angleCGM)*distCGM; + ConvertCarToTireOrientation(&velWheelCC,&velWheelTC); + */ + + /* + // Get velocity of contact patch wrt the track (=world) + DVector3 cpPos,*p; + p=susp->GetPosition(); + // Taking the tire movement from really the contact patch location + // seems to overrate the lateral movement the tire goes through. + // This is due because the body rolls, but normally the suspension + // won't roll the tire in exactly the same way, but instead, + // the tire rotates with respect to the body, so the lateral + // movements are actually quite small. + // To simulate this, I approximate the movement with respect + // to the suspension attachment point, which moves far less + // laterally. This became apparent when dealing with much stiffer + // tire and suspension spring rates, which made the car wobbly. + // Taking a less laterally sensitive position solved this. + cpPos.x=p->x; + //cpPos.y=p->y+susp->GetLength()+radius; + cpPos.y=p->y; + cpPos.z=p->z; // Kingpin effects are ignored + car->GetBody()->CalcBodyVelForBodyPos(&cpPos,&velWheelCC); + car->ConvertCarToWorldOrientation(&velWheelCC,&velWheelWC); + ConvertCarToTireOrientation(&velWheelCC,&velWheelTC); + */ + + //qdbg("velWheelTC.z=%f, rotZ=%f\n",velWheelTC.z,rotationV.x*radius); + + // Non-SAE950311 method (no lag in slip angle buildup) + // Calculate slip angle as the angle between the wheel velocity vector + // and the wheel direction vector + + if(velWheelCC.x>-RR_EPSILON_VELOCITY&&velWheelCC.x-RR_EPSILON_VELOCITY&&velWheelCC.z slipAngle=0\n"); + } + else + { + // Enough velocity, calculate real angle + float h = GetHeading(); + + float realSteer = mWheelShape->getSteerAngle(); + + slipAngle=atan2(velWheelCC.x,velWheelCC.z)-GetHeading(); + + if (getProcessOptions() & pVPO_SA_Damping ) + { + // Damp down at low velocity + if(fabs(velWheelCC.x)<0.3f&&fabs(velWheelCC.z)<0.3f) + { + float max=fabs(velWheelCC.x); + if(fabs(velWheelCC.z) %f\n",slipAngle*RR_RAD2DEG,max,slipAngle*max); + slipAngle*=max*0.5f; + } + } + // Keep slipAngle between -180..180 degrees + if(slipAngle<-PI) + slipAngle+=2*PI; + else if(slipAngle>PI) + slipAngle-=2*PI; + + } + if ( options & pVPO_SV_Tansa) + { + bool make = true ; + if(make) + { + // We need tan(SA) when combining Pacejka Fx/Fy later + tanSlipAngle=tan(slipAngle); + //qdbg("FCSV: tanSA=%f\n",tanSlipAngle); + } + } + } +} \ No newline at end of file diff --git a/usr/Src/Core/pVehicle/pWheelCalc2.cpp b/usr/Src/Core/pVehicle/pWheelCalc2.cpp new file mode 100644 index 0000000..9e773a3 --- /dev/null +++ b/usr/Src/Core/pVehicle/pWheelCalc2.cpp @@ -0,0 +1,207 @@ +#include +#include "vtPhysXAll.h" + +#include + +#include "pDifferential.h" + +#include "pVehicleAll.h" + +#include "pWorldCallbacks.h" + + + +#define FRICTION_COEFF 100.0f +#define MASS 12 +#define TIRE_RATE 50000.0f +#define WHEEL_PENETRATION_DEPTH -0.0258f +#define WHEEL_SUSPENSION_FORCE VxVector(0,-1025.0f,0) +#define RR_EPSILON_VELOCITY 0.001 // Wheel velocity +#define OPT_SLIPVECTOR_USES_TANSA + + + +// Use full 3D patch for surface detection? +#define USE_3D_PATCH + +#define ENV_INI "env.ini" + +// For method #3, slipVector (Gregor Veble), use tan(SA) or SA? +#define OPT_SLIPVECTOR_USES_TANSA + +// Skid methods +//#define SKID_METHOD_SEPARATE_LON_LAT +//#define SKID_METHOD_SLIP_RA_VECTOR +#define SKID_METHOD_Z_GREGOR + +// Point at which skidmarks appear +#define SKIDMARK_SLIPRATIO 0.2 + +// Apply damping to slipRatio/slipAngle differential eq's at low speed? +//#define DO_DAMPING_LAT +//#define DO_DAMPING_LONG + + +// Apply low-speed enhancements? (obsolete since 18-5-01) +#define DO_LOW_SPEED + +// Distance (in m) to start with wheel ray-track intersection; this is +// the height at which the ray is started to avoid getting a ray +// that starts BENEATH the track surface and therefore not hitting it. +#define DIST_INTERSECT 1.0 + +// Define the next symbol to check for wheel velocity reversal (vertically), +// and if so, the wheel is stopped momentarily. Is used to rule out +// incredibly high damper forces from pushing the wheel to full up or down. +// Should perhaps not be needed anymore combined with the implicit integrator. +// Note that this acts at the outermost positions of the wheel. +#define DAMP_VERTICAL_VELOCITY_REVERSAL + +// Damp the wheel when crossing the equilibrium position? +// As the wheel passes its center position, the spring force reverses. To +// avoid adding energy into the system, when passing this position, damping +// is used to avoid overaccelerating the tire to the other side. +// Note that this acts when the wheel is near its center (rest) position, +// contrast this with DAMP_VERTICAL_VELOCITY_REVERSAL. +//#define DAMP_VERTICAL_EQUILIBRIUM_REVERSAL + +// Use implicit integration? This should be more stable with +// high damper rates. +#define INTEGRATE_IMPLICIT_VERTICAL + +// Gregor Veble combined slip algorithm? (instead of Pacejka) +//#define DO_GREGOR +#ifdef DO_GREGOR +#undef DO_DAMPING_LAT +#undef DO_DAMPING_LONG +#endif + +// Delayed slip angle? +//#define USE_SAE950311_LAT + +// If not using SAE950311, damp SA at low speed? (to avoid jittering) +//#define USE_SA_DAMPING_AT_LOW_SPEED + +// Wheel locking results in force going the direction of -slipVector? +//#define USE_WHEEL_LOCK_ADJUST + + +void pWheel2::CalcDamping() +{ + + // Calculate damping of the tire at low speed, to avoid + // oscillations. + float u,v,b,B; + + if ( getVehicle()->getProcessOptions() & pVPO_Lat_Damping || getVehicle()->getProcessOptions() & pVPO_Long_Damping ) + { + + + if(!hadContact) + return; + + u=velWheelTC.z; + v=velWheelTC.x; + + if (getVehicle()->getProcessOptions() & pVPO_Lat_Damping) + b=relaxationLengthLat; + + + if (getVehicle()->getProcessOptions() & pVPO_Long_Damping) + B=relaxationLengthLong; + } + + + + + + if ( getVehicle()->getProcessOptions() & pVPO_Lat_Damping ) + { + + + + // Calculate damping force, to be added later + // Assumes CalcLoad() has already been called (for 'load' to be valid) + //qdbg("u=%f, v=%f\n",u,v); + //if(velWheelTC.LengthSquared()0) + if(fabs(v)GetBody()->GetLinVel()->Length()GetBody()->GetRotVel()->y0) + //if(load>0) + //if(IsLowSpeed()==TRUE&&load>0) + { + + NxVec3 grav;getBody()->getActor()->getScene().getGravity(grav); + + forceDampingTC.x=2.0f*dampingCoefficientLat*v* + sqrt((load*(pacejka.GetCorneringStiffness()) /-grav.y*b)); + forceDampingTC.x*=rollingCoeff; + + #ifdef OBS + dampingFactorLat=(fabs(car->GetBody()->GetRotVel()->y))*1.0f; + #endif + //if(dampingFactorLat<0.1f)dampingFactorLat=0.1f; + //(dampingSpeed-fabs(car->GetBody()->GetRotVel()->y))*1.0f; + #ifdef OBS + // Factor damping + dampingCoefficient=1.0f; + dampingFactorLat=dampingCoefficient*(dampingSpeed-fabs(v)); + if(dampingFactorLat>1)dampingFactorLat=1; + + //slipAngle*=dampingFactorLat; + dampingFactorLat=0; + #endif + + //dampingFactorLat=fabs(v)*3; + } + + NxVec3 grav;getBody()->getActor()->getScene().getGravity(grav); + + // Natural frequency (debug) + float natFreq; + natFreq=sqrtf(-grav.y*pacejka.GetCorneringStiffness()/load*b); + +// #ifdef OBS qdbg("W%d; natFreq=%f ~ %f Hz\n",wheelIndex,natFreq,natFreq/6.28f); car->GetBody()->GetLinVel()->DbgPrint("body linVel");#endif + + forceRoadTC.x=pacejka.GetFy(); + //qdbg("Flat=%.2f, dampFlat=%.2f, cornStiffness=%.f, load %.f, v=%f\n", + // forceRoadTC.x,forceDampingTC.x,pacejka.GetCorneringStiffness(),load,v); + } + + if (getVehicle()->getProcessOptions() & pVPO_Long_Damping) + { + + // Calculate damping force, to be added later + // Assumes CalcLoad() has already been called (for 'load' to be valid) + if(fabs(u)LengthSquared()0) + { + + //---------------------------------------------------------------- + // + // get wheel load + // + + + + NxVec3 grav;getBody()->getActor()->getScene().getGravity(grav); + forceDampingTC.z=2.0f*dampingCoefficientLong*u*sqrt((load*pacejka.GetLongitudinalStiffness())/(-grav.y*B)); + forceDampingTC.z*=rollingCoeff; + #ifdef OBS + qdbg("Fz=%f, dampFlon=%f, longStiffness=%.f, load %.f, u=%f, v=%f,\n", + pacejka.GetFx(),forceDampingTC.z,pacejka.GetLongitudinalStiffness(),load,u,v); + #endif + + } + //qdbg("dampFactorLong=%f\n",dampingFactorLong); + } +} + + +float pWheel2::getMass() +{ + return mass; + +} diff --git a/usr/Src/Core/pWorld/pWorld.cpp b/usr/Src/Core/pWorld/pWorld.cpp new file mode 100644 index 0000000..e14d78f --- /dev/null +++ b/usr/Src/Core/pWorld/pWorld.cpp @@ -0,0 +1,614 @@ +#include + +#include "vtPhysXAll.h" +#include "pVehicleAll.h" +#include "pWorldSettings.h" + + +#include +#include + + +using namespace vtTools::AttributeTools; + +void pWorld::_construct() +{ + //mAllocator = new UserAllocator; + //mCManager = NxCreateControllerManager(mAllocator); + compartment = NULL; + +} + +void pWorld::destroyCloth(CK_ID id) +{ + + pCloth*cloth = getCloth(id); + if (cloth) + { + delete cloth; + } +} + +pCloth *pWorld::getCloth(CK_ID id) +{ + + int nbClothes = getScene()->getNbCloths(); + NxCloth** clothes = getScene()->getCloths(); + while(nbClothes--) + { + NxCloth* cloth = *clothes++; + if(cloth->userData != NULL) + { + pCloth *vCloth = static_cast(cloth->userData); + if (vCloth) + { + if (id == vCloth->getEntityID() ) + { + return vCloth; + } + } + } + } + + return NULL; +} + +pCloth *pWorld::getCloth(CK3dEntity*reference) +{ + if (!reference) + { + return NULL; + } + + int nbClothes = getScene()->getNbCloths(); + NxCloth** clothes = getScene()->getCloths(); + while(nbClothes--) + { + NxCloth* cloth = *clothes++; + if(cloth->userData != NULL) + { + pCloth *vCloth = static_cast(cloth->userData); + if (vCloth) + { + if (reference->GetID() == vCloth->getEntityID() ) + { + return vCloth; + } + } + } + } + return NULL; +} + +void pWorld::updateClothes() +{ + int nbClothes = getScene()->getNbCloths(); + NxCloth** clothes = getScene()->getCloths(); + while(nbClothes--) + { + NxCloth* cloth = *clothes++; + if(cloth->userData != NULL) + { + pCloth *vCloth = static_cast(cloth->userData); + if (vCloth) + { + vCloth->updateVirtoolsMesh(); + } + } + } + +} + + + +int pWorld::getNbBodies() +{ + int result = 0; + if (!getScene()) + { + return result; + } + result+= getScene()->getNbActors(); + return result; +} +int pWorld::getNbJoints() +{ + int result = 0; + if (!getScene()) + { + return result; + } + result+= getScene()->getNbJoints(); + return result; +} + + + +NxShape *pWorld::getShapeByEntityID(CK_ID id) +{ + + if (!getScene() ) + { + return NULL; + } + + CK3dEntity *entA = static_cast(GetPMan()->GetContext()->GetObject(id)); + if (!entA) + { + return NULL; + } + + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return NULL; + } + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body =static_cast(actor->userData); + if (body) + { + NxU32 nbShapes = body->getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)body->getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (info) + { + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(info->entID)); + if (ent == entA ) + { + return s; + } + } + } + } + } + } + } + } + return NULL; +} + +pRigidBody* pWorld::getBodyFromSubEntity(CK3dEntity *sub) +{ + + if (!getScene() ) + { + return NULL; + } + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return NULL; + } + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body =static_cast(actor->userData); + if (body) + { + NxU32 nbShapes = body->getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)body->getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (info) + { + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(info->entID)); + if (ent) + { + if (sub == ent) + { + return body; + } + } + } + } + } + } + } + } + } + return NULL; +} +void pWorld::checkList() +{ + if (!getScene() ) + { + return; + } + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return; + } + + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body = (pRigidBody*)actor->userData; + if (body) + { + CK3dEntity * ent = static_cast(GetPMan()->GetContext()->GetObject(body->getEntID())); + if (!ent) + { + deleteBody(body); + } + } + } + } + + + int nbClothes = getScene()->getNbCloths(); + NxCloth** clothes = getScene()->getCloths(); + while(nbClothes--) + { + NxCloth* cloth = *clothes++; + if(cloth->userData != NULL) + { + pCloth *vCloth = static_cast(cloth->userData); + if (vCloth) + { + + CK3dEntity * ent = static_cast(GetPMan()->GetContext()->GetObject(vCloth->getEntityID())); + if (!ent) + { + destroyCloth(vCloth->getEntityID()); + } + } + } + } +} +void pWorld::deleteBody(pRigidBody*body) +{ + + if(!body) + return; + + CK_ID id = body->getEntID(); + CK3dEntity *ent = (CK3dEntity*)GetPMan()->GetContext()->GetObject(id); + + if(!ent) + return; + + GetPMan()->getRemovalList().PushBack(id); + return; + + if (body) + { + body->destroy(); + if (body->getWorld() && body->getWorld()->getScene() ) + { + + for (int i = 0 ; i < body->getWorld()->getJointFeedbackList().Size(); i++ ) + { + pBrokenJointEntry *entry = *body->getWorld()->getJointFeedbackList().At(i); + if (entry && entry->joint) + { + } + } + } + SAFE_DELETE(body); + } + checkList(); +} + +void pWorld::deleteJoint(pJoint*joint) +{ + + if (!joint) + { + return; + } + + pWorld *world = joint->getWorld(); + if (world && world->getScene() ) + { + + + for (int i = 0 ; i < GetPMan()->getJointFeedbackList().Size(); i++ ) + { + pBrokenJointEntry *entry = *world->getJointFeedbackList().At(i); + if (entry && entry->joint == joint) + { + GetPMan()->getJointFeedbackList().EraseAt(i); + break; + } + } + + joint->getJoint()->userData = NULL; + world->getScene()->releaseJoint(*joint->getJoint()); + delete joint; + + } +} + +pJoint* pWorld::getJoint(CK3dEntity *_a, CK3dEntity *_b, JType type) +{ + + if (!getScene()) + { + return NULL; + } + + pRigidBody *a = GetPMan()->getBody(_a); + pRigidBody *b = GetPMan()->getBody(_b); + + + //bodies have already a joint together ? + if ( !a && !b) + { + return NULL; + } + + if ( a == b) + { + return NULL; + } + + if (a && !a->isValid() ) + { + return NULL; + } + + if (a && !GetPMan()->getWorldByBody(_a)) + { + return NULL; + } + + if (b && !GetPMan()->getWorldByBody(_b) ) + { + return NULL; + } + + if (b && !b->isValid()) + { + return NULL; + } + + if ( a && b ) + { + pWorld*worldA = GetPMan()->getWorldByBody(_a); + pWorld*worldB = GetPMan()->getWorldByBody(_b); + if (!worldA || !worldB || (worldA!=worldB) || !worldA->isValid() || !worldB->isValid() ) + { + return NULL; + } + } + + NxU32 jointCount = getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + getScene()->resetJointIterator(); + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = getScene()->getNextJoint(); + + if (type == JT_Any) + { + + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == _a && mJoint->GetVTEntB() == _b ) + { + return mJoint; + } + + CK3dEntity *inA = _b; + CK3dEntity *inB = _a; + if (mJoint->GetVTEntA() == inA && mJoint->GetVTEntB() == inB ) + { + return mJoint; + } + } + } + + + if ( j->getType() == type) + { + + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == _a && mJoint->GetVTEntB() == _b ) + { + return mJoint; + } + + CK3dEntity *inA = _b; + CK3dEntity *inB = _a; + if (mJoint->GetVTEntA() == inA && mJoint->GetVTEntB() == inB ) + { + return mJoint; + } + } + } + } + } + + return NULL; +} + +bool pWorld::isValid() +{ + return getScene() ? true : false; +} + + + + + + + + + +pRigidBody*pWorld::getBody(CK3dEntity*ent) +{ + pRigidBody *result = NULL; + + if (!ent || !getScene() ) + { + return NULL; + } + + int nbActors = getScene()->getNbActors(); + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body = (pRigidBody*)actor->userData; + if (body && body->getEntID() == ent->GetID() ) + { + return body; + } + + if (body && body->isSubShape(ent) ) + { + return body; + } + } + } + + return NULL; +} + +pWorld::pWorld(CK3dEntity* _o) +{ + + m_bCompletedLastFrame =true; + m_fTimeSinceLastCallToSimulate = 0.0f; + + m_SleepingSettings = NULL; + m_worldSettings =NULL; + m_vtReference = _o; + mScene = NULL; + contactReport = NULL; + triggerReport = NULL; + contactModify = NULL; + + callMask = XCM_PreProcess | XCM_PostProcess; + overrideMask = 0 ; + compartment = NULL; +} +pWorld::~pWorld() +{ + //m_worldSettings = NULL; + //m_SleepingSettings =NULL; + mScene = NULL; + //m_vtReference =NULL; +} +void pWorld::destroy() +{ + if (getScene()) + { + getScene()->setClothUserNotify(NULL); + getScene()->setUserTriggerReport(NULL); + getScene()->setUserContactModify(NULL); + getScene()->setUserActorPairFiltering(NULL); + getScene()->setUserContactReport(NULL); + getScene()->setUserNotify(NULL); + + SAFE_DELETE(contactReport); + SAFE_DELETE(triggerReport); + SAFE_DELETE(raycastReport); + SAFE_DELETE(contactModify); + + if(mDefaultMaterial) + getScene()->releaseMaterial(*mDefaultMaterial); + + + if(compartment) + { + //getScene()->re + } + //SAFE_DELETE() + + + int nbActors = getScene()->getNbActors(); + if (!nbActors)return; + + + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body = (pRigidBody*)actor->userData; + if (body) + { + //body->getActor()->getCompartment()-> + body->destroy(); + if (body->GetVT3DObject()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Body destroyed :"); + } + SAFE_DELETE(body); + } + } + } + } + + if (GetPMan()->getPhysicsSDK()) + { + GetPMan()->getPhysicsSDK()->releaseScene(*mScene); + mScene = NULL; + } + + if (m_SleepingSettings) + { + delete m_SleepingSettings; + m_SleepingSettings = NULL; + } + + if (m_worldSettings) + { + delete m_worldSettings; + m_worldSettings = NULL; + } + +} +int pWorld::UpdateProperties(DWORD mode,DWORD flags){ return 0;} +VxVector pWorld::getGravity() +{ + NxVec3 grav; + getScene()->getGravity(grav); + return getFrom(grav); + +} + +void pWorld::setGravity(VxVector gravity) +{ + getScene()->setGravity(getFrom(gravity)); +} diff --git a/usr/Src/Core/pWorld/pWorldCollision.cpp b/usr/Src/Core/pWorld/pWorldCollision.cpp new file mode 100644 index 0000000..3677c8d --- /dev/null +++ b/usr/Src/Core/pWorld/pWorldCollision.cpp @@ -0,0 +1,717 @@ +#include +#include "vtPhysXAll.h" +#include "pWorldCallbacks.h" + +bool pContactModify::onContactConstraint(NxU32& changeFlags, const NxShape* shape0, const NxShape* shape1, const NxU32 featureIndex0, const NxU32 featureIndex1, NxContactCallbackData& data) +{ + + bool result = true; + + NxActor *actor0 = &shape0->getActor(); + NxActor *actor1 = &shape1->getActor(); + + pRigidBody *body0 = NULL; + pRigidBody *body1 = NULL; + + if (actor0) + { + body0 = static_cast(actor0->userData); + + } + if (actor1) + { + body1 = static_cast(actor1->userData); + } + + pContactModifyData cData; + cData.dynamicFriction0 = data.dynamicFriction0; + cData.dynamicFriction1 = data.dynamicFriction1; + cData.staticFriction0 = data.staticFriction0; + cData.staticFriction1 = data.staticFriction1; + cData.localorientation0 = getFrom(data.localorientation0); + cData.localorientation1 = getFrom(data.localorientation1); + cData.localpos0 = getFrom(data.localpos0); + cData.localpos1 = getFrom(data.localpos1); + cData.restitution = data.restitution; + cData.minImpulse = data.minImpulse; + cData.maxImpulse = data.maxImpulse; + cData.target = getFrom(data.target); + cData.error = getFrom(data.error); + + + //---------------------------------------------------------------- + // + // execute callback scripts + // + if (body0 ) + { + if (body0->getFlags() & BF_ContactModify ) + { + result = body0->onContactConstraint((int&)changeFlags,body0->GetVT3DObject(),body1->GetVT3DObject(),&cData); + if (!result) + return false; + + if (changeFlags == CMM_None ) + { + return true; + } + } + } + if (body1) + { + if (body1->getFlags() & BF_ContactModify) + { + result = body1->onContactConstraint((int&)changeFlags,body1->GetVT3DObject(),body0->GetVT3DObject(),&cData); + if (!result) + return false; + + if (changeFlags == CMM_None ) + { + return true; + } + } + } + + //---------------------------------------------------------------- + // + // copy result back to sdk + // + if (changeFlags!=CMM_None) + { + data.dynamicFriction0 = cData.dynamicFriction0; + data.dynamicFriction1 = cData.dynamicFriction1; + data.staticFriction0 = cData.staticFriction0; + data.staticFriction1 = cData.staticFriction1; + data.localorientation0 = getFrom(cData.localorientation0); + data.localorientation1 = getFrom(cData.localorientation1); + data.localpos0 = getFrom(cData.localpos0); + data.localpos1 = getFrom(cData.localpos1); + data.restitution = cData.restitution; + data.minImpulse = cData.minImpulse; + data.maxImpulse = cData.maxImpulse; + data.target = getFrom(cData.target); + data.error = getFrom(cData.error); + } + return true; +} + +void pContactReport::onContactNotify(NxContactPair& pair, NxU32 events) +{ + + pRigidBody *bodyA = NULL; + pRigidBody *bodyB = NULL; + + if (pair.actors[0]) + { + bodyA = static_cast(pair.actors[0]->userData); + } + if (pair.actors[1]) + { + bodyB = static_cast(pair.actors[1]->userData); + } + + if (bodyA) + { + /* + if (bodyA->hasWheels()) + { + bodyA->handleContactPair(&pair,0); + return ; + } + */ + + /* + if (bodyA->getVehicle()) + { + pVehicle* v = bodyA->getVehicle(); + v->handleContactPair(&pair, 0); + return ; + } + */ + } + if ( bodyB ) + { + /* + if (bodyB->hasWheels()) + { + bodyB->handleContactPair(&pair,1); + return ; + } + + if (bodyB->getVehicle()) + { + pVehicle* v = bodyB->getVehicle(); + v->handleContactPair(&pair, 1); + return ; + } + */ + + + } + + // Iterate through contact points + NxContactStreamIterator i(pair.stream); + //user can call getNumPairs() here + while(i.goNextPair()) + { + //user can also call getShape() and getNumPatches() here + while(i.goNextPatch()) + { + //user can also call getPatchNormal() and getNumPoints() here + const NxVec3& contactNormal = i.getPatchNormal(); + while(i.goNextPoint()) + { + //user can also call getPoint() and getSeparation() here + const NxVec3& contactPoint = i.getPoint(); + + pCollisionsEntry entry; + entry.point = pMath::getFrom(contactPoint); + NxU32 faceIndex = i.getFeatureIndex0(); + if(faceIndex==0xffffffff)faceIndex = i.getFeatureIndex1(); + if(faceIndex!=0xffffffff)entry.faceIndex = faceIndex; + + entry.actors[0] = pair.actors[0]; + entry.actors[1] = pair.actors[1]; + entry.faceIndex = faceIndex; + entry.sumNormalForce = pMath::getFrom(pair.sumNormalForce); + entry.sumFrictionForce = pMath::getFrom(pair.sumFrictionForce); + entry.faceNormal = pMath::getFrom(contactNormal); + entry.eventType = events; + entry.pointNormalForce=i.getPointNormalForce(); + entry.distance = i.getSeparation(); + + + //////////////////////////////////////////////////////////////////////////// + //store shapes + + + NxShape *shapeA = i.getShape(0); + if (shapeA) + { + pSubMeshInfo *shapeInfo= static_cast(shapeA->userData); + if (shapeInfo) + { + entry.shapeEntityA = shapeInfo->entID; + } + } + + shapeA = i.getShape(1); + if (shapeA) + { + pSubMeshInfo *shapeInfo= static_cast(shapeA->userData); + if (shapeInfo) + { + entry.shapeEntityB = shapeInfo->entID; + } + } + + + pRigidBody *bodyA = NULL; + pRigidBody *bodyB = NULL; + if (pair.actors[0]) + { + bodyA = static_cast(pair.actors[0]->userData); + } + if (pair.actors[1]) + { + bodyB = static_cast(pair.actors[1]->userData); + } + + + if (bodyA && bodyA->getActor() /*&& (bodyA->getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) */) + { + entry.bodyA = bodyA; + entry.bodyB = bodyB; + bodyA->getCollisions().Clear(); + bodyA->getCollisions().PushBack(entry); + bodyA->onContactNotify(&entry); + } + + if (bodyB && bodyB->getActor()/* && (bodyB->getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) */) + { + entry.bodyA = bodyA; + entry.bodyB = bodyB; + bodyB->getCollisions().Clear(); + bodyB->getCollisions().PushBack(entry); + bodyB->onContactNotify(&entry); + } + + // result->getActor()->setContactReportFlags(NX_NOTIFY_ON_TOUCH); + /* + { + entry.bodyA = body; + body->getCollisions().Clear(); + body->getCollisions().PushBack(entry); + } + + if (pair.actors[1]) + { + pRigidBody *body = static_cast(pair.actors[1]->userData); + if (body) + { + entry.bodyB = body; + body->getCollisions().Clear(); + body->getCollisions().PushBack(entry); + + } + }*/ + /*getWorld()->getCollisions().PushBack(entry);*/ + } + } + } +} + +int pWorld::overlapOBBShapes(const VxBbox& worldBounds, CK3dEntity*shapeReference, pShapesType shapeType,CKGroup *shapes,int activeGroups/* =0xffffffff */, const pGroupsMask* groupsMask/* =NULL */, bool accurateCollision/* =false */) +{ + + int result=0; + + NxBox box; + + if (shapeReference) + { + + NxShape *shape = getShapeByEntityID(shapeReference->GetID()); + if (shape) + { + //shape->checkOverlapAABB() + + NxBoxShape*boxShape = static_cast(shape->isBox()); + if (boxShape) + { + boxShape->getWorldOBB(box); + } + } + + }else{ + + box.center = getFrom(worldBounds.GetCenter()); + box.extents = getFrom(worldBounds.GetSize()); + } + + int total = 0; + if (shapeType & ST_Dynamic ) + { + total+=getScene()->getNbDynamicShapes(); + } + + if (shapeType & ST_Static) + { + total+=getScene()->getNbStaticShapes(); + } + + NxShape** _shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); + for (NxU32 i = 0; i < total; i++) _shapes[i] = NULL; + + + + NxGroupsMask mask; + if (groupsMask) + { + mask.bits0 = groupsMask->bits0; + mask.bits1 = groupsMask->bits1; + mask.bits2 = groupsMask->bits2; + mask.bits3 = groupsMask->bits3; + }else{ + + mask.bits0 = 0; + mask.bits1 = 0; + mask.bits2 = 0; + mask.bits3 = 0; + + } + result = getScene()->overlapOBBShapes(box,(NxShapesType)shapeType,total,_shapes,NULL,activeGroups,&mask,accurateCollision); + + if (_shapes && shapes ) + { + for (int i = 0 ; i < result ; i++) + { + NxShape *s = _shapes[i]; + if (s) + { + const char* name =s->getName(); + pSubMeshInfo *sInfo = static_cast(s->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + + shapes->AddObject((CKBeObject*)obj); + } + } + } + } + } + + int op=2; + + + + + return result; + +} + +int pWorld::overlapSphereShapes(const VxSphere& worldSphere,CK3dEntity*shapeReference,pShapesType shapeType,CKGroup*shapes,int activeGroups/* =0xffffffff */, const pGroupsMask* groupsMask/* =NULL */, bool accurateCollision/* =false */) +{ + + int result=0; + + NxSphere sphere; + + if (shapeReference) + { + + NxShape *shape = getShapeByEntityID(shapeReference->GetID()); + if (shape) + { + //shape->checkOverlapAABB() + + NxSphereShape *sphereShape = static_cast(shape->isSphere()); + if (sphereShape) + { + sphere.radius = sphereShape->getRadius() + worldSphere.Radius(); + + //ori : + VxVector ori = worldSphere.Center(); + VxVector oriOut = ori; + if (shapeReference) + { + shapeReference->Transform(&oriOut,&ori); + } + + sphere.center = getFrom(oriOut); + + } + } + + }else{ + + sphere.center = getFrom(worldSphere.Center()); + sphere.radius = worldSphere.Radius(); + + } + + int total = 0; + if (shapeType & ST_Dynamic ) + { + total+=getScene()->getNbDynamicShapes(); + } + + if (shapeType & ST_Static) + { + total+=getScene()->getNbStaticShapes(); + } + + NxShape** _shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); + for (NxU32 i = 0; i < total; i++) _shapes[i] = NULL; + + + + NxGroupsMask mask; + if (groupsMask) + { + mask.bits0 = groupsMask->bits0; + mask.bits1 = groupsMask->bits1; + mask.bits2 = groupsMask->bits2; + mask.bits3 = groupsMask->bits3; + }else{ + + mask.bits0 = 0; + mask.bits1 = 0; + mask.bits2 = 0; + mask.bits3 = 0; + + } + + + + + result = getScene()->overlapSphereShapes(sphere,(NxShapesType)shapeType,total,_shapes,NULL,activeGroups,&mask,accurateCollision); + + if (_shapes && shapes ) + { + for (int i = 0 ; i < result ; i++) + { + NxShape *s = _shapes[i]; + if (s) + { + const char* name =s->getName(); + pSubMeshInfo *sInfo = static_cast(s->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + + shapes->AddObject((CKBeObject*)obj); + } + } + } + } + } + + int op=2; + + + + + return result; + +} + +int pWorld::raycastAllShapes(const VxRay& worldRay, pShapesType shapesType, int groups, float maxDist, pRaycastBit hintFlags, const pGroupsMask* groupsMask) +{ + + int result = 0; + + NxRay rayx; + rayx.dir = getFrom(worldRay.m_Direction); + rayx.orig = getFrom(worldRay.m_Origin); + + pRayCastReport &report = *getRaycastReport(); + + NxGroupsMask *mask = NULL; + if (groupsMask) + { + mask = new NxGroupsMask(); + mask->bits0 = groupsMask->bits0; + mask->bits1 = groupsMask->bits1; + mask->bits2 = groupsMask->bits2; + mask->bits3 = groupsMask->bits3; + + } + + result = getScene()->raycastAllShapes(rayx,report,(NxShapesType)shapesType,groups,maxDist,hintFlags,mask); + return result; + + +} +bool pWorld::raycastAnyBounds(const VxRay& worldRay, pShapesType shapesType, pGroupsMask *groupsMask/* =NULL */,int groups/* =0xffffffff */, float maxDist/* =NX_MAX_F32 */) +{ + + if (!getScene()) + { + return false; + } + + NxRay _worldRay; + _worldRay.dir = getFrom(worldRay.m_Direction); + _worldRay.orig = getFrom(worldRay.m_Origin); + + NxShapesType _shapesType = (NxShapesType)shapesType; + + NxReal _maxDist=maxDist; + + NxGroupsMask *mask = NULL; + if (groupsMask) + { + mask = new NxGroupsMask(); + mask->bits0 = groupsMask->bits0; + mask->bits1 = groupsMask->bits1; + mask->bits2 = groupsMask->bits2; + mask->bits3 = groupsMask->bits3; + + } + bool result = getScene()->raycastAnyBounds(_worldRay,_shapesType,groups,_maxDist,mask); + return result; + +} + +void pWorld::cIgnorePair(CK3dEntity *_a, CK3dEntity *_b, int ignore) +{ + + pRigidBody *a = GetPMan()->getBody(_a); + pRigidBody *b = GetPMan()->getBody(_b); + if (a&&b && a->getActor() && b->getActor() ) + { + if (getScene()) + { + getScene()->setActorPairFlags(*a->getActor(),*b->getActor(),ignore ? NX_IGNORE_PAIR : NX_NOTIFY_ALL ); + } + } +} + +void pWorld::cSetGroupCollisionFlag(int g1 , int g2,int enabled) +{ + + if (getScene()) + { + if (g1 >=0 && g1 <= 31 && g2 >=0 && g2 <= 31) + { + if (enabled==0 || enabled ==1) + { + getScene()->setGroupCollisionFlag(g1,g2,enabled); + } + } + } +} + +void pTriggerReport::onTrigger(NxShape& triggerShape, NxShape& otherShape, NxTriggerFlag status) +{ + + NxActor *triggerActor = &triggerShape.getActor(); + NxActor *otherActor = &otherShape.getActor(); + pRigidBody *triggerBody = NULL; + pRigidBody *otherBody = NULL; + + if (triggerActor) + { + triggerBody = static_cast(triggerActor->userData); + //triggerBody->getTriggers().Clear(); + } + + if (otherActor) + { + otherBody = static_cast(otherActor->userData); + //otherBody->getTriggers().Clear(); + } + + + pTriggerEntry entry; + entry.shapeA = &triggerShape; + entry.shapeB = &otherShape; + entry.triggerEvent = status; + + entry.triggerBodyB = triggerBody; + entry.otherBodyB = otherBody; + + + entry.triggerBody = triggerBody->GetVT3DObject(); + pSubMeshInfo *sInfo = (pSubMeshInfo*)otherShape.userData; + if (sInfo) + { + entry.otherObject = (CK3dEntity*)GetPMan()->GetContext()->GetObject(sInfo->entID); + } + + pSubMeshInfo *sInfoOri = (pSubMeshInfo*)triggerShape.userData; + if (sInfo) + { + entry.triggerShapeEnt = (CK3dEntity*)GetPMan()->GetContext()->GetObject(sInfoOri->entID); + } + + if (triggerBody) + { + //triggerBody->getTriggers().PushBack(entry); + triggerBody->onTrigger(&entry); + GetPMan()->getTriggers().PushBack(entry); + } +} + + +void pWorld::initUserReports() +{ + + contactReport = new pContactReport(); + contactReport->setWorld(this); + + triggerReport = new pTriggerReport(); + triggerReport->setWorld(this); + + raycastReport = new pRayCastReport(); + raycastReport->setWorld(this); + + contactModify = new pContactModify(); + contactModify->setWorld(this); + + + //getScene()->raycastAllShapes() +} +bool pRayCastReport::onHit(const NxRaycastHit& hit) +{ + + CKBehavior *beh =(CKBehavior*)GetPMan()->m_Context->GetObject(mCurrentBehavior); + if ( beh ) + { + pRayCastHits *carray = NULL; + beh->GetLocalParameterValue(0,&carray); + if (carray) + { + //carray->clear(); + }else + { + carray = new pRayCastHits(); + } + + //carray->push_back(const_cast(&hit)); + + NxRaycastHit *_hit = new NxRaycastHit(); + + _hit->distance = hit.distance; + _hit->faceID = hit.faceID; + _hit->flags = hit.flags; + _hit->internalFaceID = hit.internalFaceID; + _hit->materialIndex = hit.materialIndex; + _hit->shape = hit.shape; + _hit->u = hit.u; + _hit->v = hit.v; + _hit->worldImpact = hit.worldImpact; + _hit->worldNormal = hit.worldNormal; + + const char *name = hit.shape->getName(); + + carray->push_back(_hit); + beh->SetLocalParameterValue(0,&carray); + + + } + return true; +} + +void pWorld::setFilterOps(pFilterOp op0,pFilterOp op1, pFilterOp op2) +{ + getScene()->setFilterOps((NxFilterOp)op0,(NxFilterOp)op1,(NxFilterOp)op2); +} + +void pWorld::setFilterBool(bool flag){ getScene()->setFilterBool(flag);} +void pWorld::setFilterConstant0(const pGroupsMask& mask) +{ + NxGroupsMask _mask; + _mask.bits0=mask.bits0; + _mask.bits1=mask.bits1; + _mask.bits2=mask.bits2; + _mask.bits3=mask.bits3; + + getScene()->setFilterConstant0(_mask); +} + +void pWorld::setFilterConstant1(const pGroupsMask& mask) +{ + NxGroupsMask _mask; + _mask.bits0=mask.bits0; + _mask.bits1=mask.bits1; + _mask.bits2=mask.bits2; + _mask.bits3=mask.bits3; + + getScene()->setFilterConstant1(_mask); +} + +bool pWorld::getFilterBool()const{ return getScene()->getFilterBool();} +pGroupsMask pWorld::getFilterConstant0()const +{ + NxGroupsMask mask = getScene()->getFilterConstant0(); + pGroupsMask _mask; + + _mask.bits0=mask.bits0; + _mask.bits1=mask.bits1; + _mask.bits2=mask.bits2; + _mask.bits3=mask.bits3; + + return _mask; + +} + +pGroupsMask pWorld::getFilterConstant1()const +{ + NxGroupsMask mask = getScene()->getFilterConstant1(); + pGroupsMask _mask; + _mask.bits0=mask.bits0; + _mask.bits1=mask.bits1; + _mask.bits2=mask.bits2; + _mask.bits3=mask.bits3; + return _mask; +} + + + diff --git a/usr/Src/Core/pWorld/pWorldFluids.cpp b/usr/Src/Core/pWorld/pWorldFluids.cpp new file mode 100644 index 0000000..d45e379 --- /dev/null +++ b/usr/Src/Core/pWorld/pWorldFluids.cpp @@ -0,0 +1,65 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + + + +pFluid *pWorld::getFluid(CK_ID id) +{ + + int nbFluids= getScene()->getNbFluids(); + NxFluid** fluids = getScene()->getFluids(); + while(nbFluids--) + { + NxFluid* fluid = *fluids++; + if(fluid->userData != NULL) + { + pFluid *vFluid = static_cast(fluid->userData); + if (vFluid) + { + + if (vFluid->getEntityID() == id) + { + return vFluid; + + } + } + } + } + + return NULL; +} + +pFluid*pWorld::getFluid(CK3dEntity* entity) +{ + if (!entity) + { + return NULL; + } + + return getFluid(entity->GetID()); + +} +void pWorld::updateFluids() +{ + + + int nbFluids= getScene()->getNbFluids(); + NxFluid** fluids = getScene()->getFluids(); + while(nbFluids--) + { + NxFluid* fluid = *fluids++; + if(fluid->userData != NULL) + { + pFluid *vFluid = static_cast(fluid->userData); + if (vFluid) + { + vFluid->updateVirtoolsMesh(); + + } + } + } + +} +#endif \ No newline at end of file diff --git a/usr/Src/Core/pWorld/pWorldRun.cpp b/usr/Src/Core/pWorld/pWorldRun.cpp new file mode 100644 index 0000000..f6f7543 --- /dev/null +++ b/usr/Src/Core/pWorld/pWorldRun.cpp @@ -0,0 +1,412 @@ +#include + +#include "vtPhysXAll.h" +#include "pVehicleAll.h" +#include "pWorldSettings.h" + + +#include +#include + + +using namespace vtTools::AttributeTools; + + + +int pWorld::hadBrokenJoint() +{ + + int nbActors = getScene()->getNbActors(); + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor && actor->userData != NULL) + { + pRigidBody* body = (pRigidBody*)actor->userData; + if (body && body->hasBrokenJoint) + { + return 1; + } + } + } + + return 0; +} + +void pWorld::cleanBrokenJoints() +{ + + int nbActors = getScene()->getNbActors(); + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor && actor->userData != NULL) + { + pRigidBody* body = (pRigidBody*)actor->userData; + if (body ) + { + body->hasBrokenJoint = false; + } + } + } +} + +void pWorld::step(float stepsize) +{ + if (getScene()) + { + + CKVariableManager* vm = GetPMan()->GetContext()->GetVariableManager(); + if( !vm ) + return; + + int disable = 0 ; + vm->GetValue("Physic/Disable Physics",&disable); + if (disable) + { + return; + } + + + //int hasBroken = hadBrokenJoint(); + + + + NxU32 nbTransforms = 0; + NxActiveTransform *activeTransforms = getScene()->getActiveTransforms(nbTransforms); + + updateVehicles(stepsize); + + updateClothes(); + +#ifdef HAS_FLUIDS + updateFluids(); +#endif + + + vtAgeia::pWorldSettings *wSettings = GetPMan()->getDefaultWorldSettings(); + + if (wSettings->isFixedTime()) + getScene()->setTiming(wSettings->getFixedTimeStep() * 10.0f, wSettings->getNumIterations() , NX_TIMESTEP_FIXED); + /*else getScene()->setTiming( (stepsize * 100 ) / wSettings->getNumIterations() , wSettings->getNumIterations() , NX_TIMESTEP_VARIABLE); */ + /* + NxU32 nbIter = 0 ; + int op =2; + NxTimeStepMethod mode = NX_TIMESTEP_FIXED;*/ + /*float stepSz;getScene()->getTiming(stepSz,nbIter,op);*/ + + int nbDeleted = GetPMan()->_checkRemovalList(); + if (nbDeleted) + { + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"objects to delete"); + //return; + } + + + int nbReset = GetPMan()->_getRestoreMap()->Size(); + if(nbReset) + { + GetPMan()->_checkResetList(); + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"objects to reset"); + GetPMan()->_getResetList().Clear(); + return; + } + + int nbCheck = GetPMan()->getCheckList().Size(); + if(nbCheck) + { + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"objects to check"); + GetPMan()->_checkObjectsByAttribute(GetPMan()->GetContext()->GetCurrentLevel()->GetCurrentScene()); + GetPMan()->_checkListCheck(); + if(nbCheck) + { + if(nbCheck && GetPMan()->sceneWasChanged ) + { + + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"objects to check & and scene change, aborting"); + } + //GetPMan()->checkWorlds();drdrdr + //return; + } + } + + + + + if(!getScene()->checkResults(NX_RIGID_BODY_FINISHED,false)) + { + getScene()->simulate(stepsize * GetPMan()->GetContext()->GetTimeManager()->GetTimeScaleFactor() ); + } + + + if(getScene()->checkResults(NX_RIGID_BODY_FINISHED,false) /*&& hasBroken==0*/) + { + //if(nbDeleted) return; + int nbNewPostObjects = GetPMan()->getAttributePostObjects().Size(); + /* + if(m_bCompletedLastFrame) + { + //getScene()->simulate(stepsize * GetPMan()->GetContext()->GetTimeManager()->GetTimeScaleFactor() ); + getScene()->simulate( m_fTimeSinceLastCallToSimulate ); + m_bCompletedLastFrame = false; + m_fTimeSinceLastCallToSimulate = 0.0; + } + + m_fTimeSinceLastCallToSimulate +=(stepsize * GetPMan()->GetContext()->GetTimeManager()->GetTimeScaleFactor()); + + if(getScene()->checkResults(NX_ALL_FINISHED,false)) + {*/ + m_bCompletedLastFrame = true; + if(nbTransforms && activeTransforms && !nbDeleted && !nbReset && !nbCheck && !nbNewPostObjects /*&& hasBroken== 0*/) + { + for(NxU32 i = 0; i < nbTransforms; ++i) + { + // the user data of the actor holds the game object pointer + NxActor *actor = activeTransforms[i].actor; + //XString name = actor->getName(); + if (actor !=NULL) + { + pRigidBody *body = static_cast(actor->userData); + + // update the game object's transform to match the NxActor + if(body !=NULL) + { + assert(body && body->getEntID()); + NxMat34 transformation = activeTransforms[i].actor2World; + VxQuaternion rot = pMath::getFrom(transformation.M); + VxVector pos = pMath::getFrom(transformation.t); + VxVector pos2 = pMath::getFrom(transformation.t); + + + + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(body->getEntID())); + if (ent !=NULL && ent->GetClassID() != CKCID_3DOBJECT) + { + continue; + } + //assert(ent && ent->GetID()); + + /* + XString errMessage= "update body"; + errMessage+=ent->GetName(); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMessage.Str()); + */ + + //NxShape *mainShape=body->getMainShape(); + if (ent !=NULL) + { + int hier = (body->getFlags() & BF_Hierarchy ); + ent->SetPosition(&pos,NULL); + ent->SetQuaternion(&rot,NULL); + body->updateSubShapes(); + body->onMove(true,true,pos,rot); + + if (body->hasWheels()) + { + body->wakeUp(); + } + }else{ + //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Invalid entity due simulation."); + } + + }else + { + //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Invalid Body due simulation."); + } + } + } + } + + NxU32 error=0; + getScene()->flushStream(); + getScene()->fetchResults(NX_ALL_FINISHED,true,&error); + if(error !=0) + { + XString err="error fetching results : "; + err << error; + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,err.Str()); + } + + + }else + { + //cleanBrokenJoints(); + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"world has broken joints !"); + return; + } + + } + + + ////////////////////////////////////////////////////////////////////////// + // + // + // update Virtools from hardware objects + + + + int nbActors = getScene()->getNbActors(); + NxActor** actors = getScene()->getActors(); + if(getCompartment()) + { + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor && actor->userData != NULL) + { + pRigidBody* body = (pRigidBody*)actor->userData; + if (body && body->getActor()->getCompartment()) + { + NxMat34 transformation = actor->getGlobalPose(); + VxQuaternion rot = pMath::getFrom(transformation.M); + VxVector pos = pMath::getFrom(transformation.t); + VxVector pos2 = pMath::getFrom(transformation.t); + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(body->getEntID())); + //NxShape *mainShape=body->getMainShape(); + if (ent) + { + + //int hier = (body->getFlags() & BF_Hierarchy ); + ent->SetPosition(&pos,NULL); + ent->SetQuaternion(&rot,NULL); + body->updateSubShapes(); + body->onMove(true,true,pos,rot); + if (body->hasWheels()) + { + // body->wakeUp(); + } + }else{ + //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Invalid Body due simulation."); + } + } + } + } + } + + /* + if(getScene()->checkResults(NX_RIGID_BODY_FINISHED)) + { + NxU32 error; + getScene()->flushStream(); + getScene()->fetchResults(NX_RIGID_BODY_FINISHED,true,&error); + } + */ + + /* + + int err = error; + + NxReal maxTimestep; + NxTimeStepMethod method; + NxU32 maxIter; + NxU32 numSubSteps; + //getScene()->getTiming(maxTimestep, maxIter, method, &numSubSteps); + + + int op2 = 3; + op2++; + */ + +} + + +int pWorld::onPreProcess() +{ + + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return 0; + } + + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + pRigidBody *body = static_cast(actor->userData); + if (body) + { + pVehicle *v = body->getVehicle(); + if (!v && body->hasWheels()) + { + int nbShapes = actor->getNbShapes(); + NxShape ** slist = (NxShape **)actor->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + pWheel *wheel = sinfo->wheel; + pWheel2* wheel2 = dynamic_cast(wheel); + + if ( wheel2 && (wheel2->getCallMask().test(CB_OnPreProcess)) ) + { + wheel2->onPreProcess(); + } + + } + } + } + } + + //if (v && (v->getCallMask().test(CB_OnPreProcess))) + // v->onPreProcess(); + } + } + + return 1; +} +int pWorld::onPostProcess() +{ + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return 0; + } + + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + pRigidBody *body = static_cast(actor->userData); + if (body) + { + pVehicle *v = body->getVehicle(); + if (!v && body->hasWheels()) + { + int nbShapes = actor->getNbShapes(); + NxShape ** slist = (NxShape **)actor->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + pWheel *wheel = sinfo->wheel; + pWheel2* wheel2 = dynamic_cast(wheel); + + if ( wheel2 && (wheel2->getCallMask().test(CB_OnPostProcess))) + { + wheel2->onPostProcess(); + } + + } + } + } + } + //if (v && (v->getCallMask().test(CB_OnPostProcess))) + //v->onPostProcess(); + } + } + + return 1; +} diff --git a/usr/Src/Core/pWorld/pWorldSettings.cpp b/usr/Src/Core/pWorld/pWorldSettings.cpp new file mode 100644 index 0000000..5455dec --- /dev/null +++ b/usr/Src/Core/pWorld/pWorldSettings.cpp @@ -0,0 +1,164 @@ +#include +#include "vtPhysXAll.h" +#include "pWorldSettings.h" + +#include + +std::vector&_getValidDominanceGroups(std::vector&_inputGroups,pDominanceSetupItem *testItem) +{ + std::vector result; + + if (!_inputGroups.size()) + return result; + + + /* + + g1A + g1A + g1A != g1B ! + + g2A + g2B + + 1 2 3 + + + 1 : 1 - 2 + 2 : 1 - 3 + + */ + + for (int i = 0 ; i < _inputGroups.size() ; i++) + { + pDominanceSetupItem* cItem =_inputGroups[i]; + + if ( cItem == testItem ) + { + result.push_back(cItem); + continue; + } + + if ( cItem->dominanceGroup0 != testItem->dominanceGroup0 ) + { + + } + + + } + +} + + +void pWorld::_checkForDominanceConstraints() +{ + +#ifndef _DEBUG + assert(getReference()); + assert(getScene()); +#endif + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS); + + if (!getReference()->HasAttribute(att)) + return; + + CKParameterOut *domPar = getReference()->GetAttributeParameter(att); + if(!domPar) + return; + + + using namespace vtTools::ParameterTools; + using namespace vtTools::AttributeTools; + + + CKParameterOut *d1 = GetParameterFromStruct(domPar,PS_WDS_ITEM1); + CKParameterOut *d2 = GetParameterFromStruct(domPar,PS_WDS_ITEM2); + CKParameterOut *d3 = GetParameterFromStruct(domPar,PS_WDS_ITEM3); + CKParameterOut *d4 = GetParameterFromStruct(domPar,PS_WDS_ITEM4); + CKParameterOut *d5 = GetParameterFromStruct(domPar,PS_WDS_ITEM5); + + pDominanceSetupItem item1; + pDominanceSetupItem item2; + pDominanceSetupItem item3; + pDominanceSetupItem item4; + pDominanceSetupItem item5; + + + + int error = pFactory::Instance()->copyTo(d1,item1); + + error = pFactory::Instance()->copyTo(d2,item2); + error = pFactory::Instance()->copyTo(d3,item3); + error = pFactory::Instance()->copyTo(d4,item4); + error = pFactory::Instance()->copyTo(d5,item5); + + std::vector allDominanceItems; + + //################################################################ + // + // gather all in an array + // + + + + int a = item1.dominanceGroup0; + int a1 = item1.dominanceGroup1; + + if (item1.dominanceGroup0 !=0 && item1.dominanceGroup1 !=0 && (item1.dominanceGroup0 != item1.dominanceGroup1 ) ) + allDominanceItems.push_back(&item1); + + if (item2.dominanceGroup0 !=0 && item2.dominanceGroup1 !=0 && (item2.dominanceGroup0 != item1.dominanceGroup1 ) ) + allDominanceItems.push_back(&item2); + + if (item3.dominanceGroup0 !=0 && item3.dominanceGroup1 !=0 && (item3.dominanceGroup0 != item3.dominanceGroup1 ) ) + allDominanceItems.push_back(&item3); + + if (item4.dominanceGroup0 !=0 && item4.dominanceGroup1 !=0 && (item4.dominanceGroup0 != item4.dominanceGroup1 ) ) + allDominanceItems.push_back(&item4); + + if (item5.dominanceGroup0 !=0 && item5.dominanceGroup1 !=0 && (item5.dominanceGroup0 != item5.dominanceGroup1 ) ) + allDominanceItems.push_back(&item5); + + + //std::vector_validDominanceItems1 = _getValidDominanceGroups(allDominanceItems,&item1); + //int s = _validDominanceItems1.size(); + + + + for (int i = 0 ; i < allDominanceItems.size() ; i++) + { + pDominanceSetupItem* cItem = allDominanceItems[i]; + NxConstraintDominance cD1( cItem->constraint.dominanceA , cItem->constraint.dominanceB ); + + getScene()->setDominanceGroupPair(cItem->dominanceGroup0, cItem->dominanceGroup1,cD1); + + + + + } + + + + +} + + + +namespace vtAgeia +{ + + +pWorldSettings::pWorldSettings() : + m_Gravity(VxVector(0.0f,-9.81f,0.0f)) , + m_SkinWith(0.1) +{ + + fixedTime = false; + fixedTimeStep = 1.0f/60.0f; + numIterations = 8; + sceneFlags = 0 ; + physicFlags = 0; + +} + + +} \ No newline at end of file diff --git a/usr/Src/Core/pWorld/pWorldVehicle.cpp b/usr/Src/Core/pWorld/pWorldVehicle.cpp new file mode 100644 index 0000000..704dc84 --- /dev/null +++ b/usr/Src/Core/pWorld/pWorldVehicle.cpp @@ -0,0 +1,62 @@ +#include +#include "vtPhysXAll.h" + + +void pWorld::updateVehicle(pVehicle *vehicle, float dt) +{ + if (vehicle) + { + vehicle->updateVehicle(dt); + } +} + + + +void pWorld::updateVehicles(float dt) +{ + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return; + } + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + pRigidBody *body = static_cast(actor->userData); + if (body) + { + if (!isVehicle(actor) && body->hasWheels()) + { + body->updateWheels(dt); + } + } + + if (body && isVehicle(actor)) + { + updateVehicle(body->getVehicle(),dt); + } + } +} +bool pWorld::isVehicle(NxActor* actor) +{ + + pRigidBody *body = static_cast(actor->userData); + if (body) + { + return body->getVehicle() ? true : false; + } + return false; +} + +pVehicle*pWorld::getVehicle(CK3dEntity* body) +{ + + pRigidBody *rbody = getBody(body); + if (body && rbody->getVehicle() ) + { + return rbody->getVehicle(); + } + return NULL; +} diff --git a/usr/Src/Core/path.cpp b/usr/Src/Core/path.cpp new file mode 100644 index 0000000..c16e01f --- /dev/null +++ b/usr/Src/Core/path.cpp @@ -0,0 +1,46 @@ +#include "Path.h" + +char* +XPath::GetFileName(){ + + char *pc = data_.Str(); + int LastBackSlash =-1; + int iChar = 0; + while(pc[iChar] != 0){ + if(pc[iChar] == '\\')LastBackSlash = iChar; + iChar++; + } + return pc + LastBackSlash +1; +} + +char* +XPath::GetPath(){ + + char* PathCopy = data_.Str(); + PathRemoveFileSpec(PathCopy); + return PathCopy; + +} + +#include +int +XPath::absolute_levels()const{ + + //count path_sep´s + /* + using namespace std; + + + string s = data_.CStr(); + string::iterator cit = find(s.begin(),s.end(),path_separator_); + int n = 0;//;-) or how do you make this? + while ( cit != s.end()){ + ++n; + cit = find(cit+1 ,s.end(),path_separator_); + }*/ + return 1; +} + + + + diff --git a/usr/Src/Core/qTimer.cpp b/usr/Src/Core/qTimer.cpp new file mode 100644 index 0000000..c77ccdd --- /dev/null +++ b/usr/Src/Core/qTimer.cpp @@ -0,0 +1,270 @@ +#include "StdAfx.h" +#include +#include +#include + +#ifdef linux + #include +#endif + +// Screen Hertz; for Quizes, PAL should do the trick +#define TRACES_PER_SECOND 50 + +QTimer::QTimer() +{ + Reset(); +} +QTimer::~QTimer() +{ +} + +void QTimer::ResetBase() +// Reset 0-base for time counting +{ +#ifdef USE_VTRACE + baseVCount=app->GetVTraceCount(); +#endif + +#ifdef USE_UST + dmGetUST(&baseUST); +#endif + +#ifdef USE_TIME + time(&base_secs); +#endif + +#ifdef USE_GETTIMEOFDAY + struct timezone tz; + gettimeofday(&tvBase,&tz); + // Calculate time in usecs + base_usecs=tvBase.tv_sec*1000000+tvBase.tv_usec; +#endif + +#ifdef USE_OS_TICK + //baseTicks=(int)GetTickCount(); + baseTicks=(int)timeGetTime(); +#endif +} + +/********************** +* STOPWATCH EMULATION * +**********************/ +void QTimer::UpdateTicks() +// Updates 'ticks' to the last available time instant (NOW) +{ + if(!isRunning) + { + return; + } + +#ifdef USE_VTRACE + int vc; + vc=app->GetVTraceCount(); + ticks+=vc-baseVCount; + baseVCount=vc; +#endif + +#ifdef USE_UST + uint64 vc; + dmGetUST(&vc); + ticks+=vc-baseUST; + baseUST=vc; +#endif + +#ifdef USE_OS_TICK + // Looks a lot like UST + int t; + //t=(int)GetTickCount(); + t=(int)timeGetTime(); + ticks+=t-baseTicks; + baseTicks=t; +#endif + +#ifdef USE_GETTIMEOFDAY + int t; + struct timezone tz; + gettimeofday(&tv,&tz); + t=tv.tv_sec*1000000+tv.tv_usec; + ticks+=t-base_usecs; + base_usecs=t; +#endif +} +void QTimer::Reset() +{ /** Starts timer at current time **/ + ResetBase(); + ticks=0; + isRunning=FALSE; +} +void QTimer::Start() +// Turn timer on +{ + if(isRunning)return; + ResetBase(); + isRunning=TRUE; +} +void QTimer::Stop() +// Stop time recording +{ + if(!isRunning)return; + UpdateTicks(); + isRunning=FALSE; +} + +/**************** +* RETRIEVE TIME * +****************/ +void QTimer::GetTime(ulong *secs,ulong *micros) +/** Get passed time since last reset **/ +{ + +} +ulong QTimer::GetSeconds() +/** Get passed seconds since last Start() **/ +{ +#ifdef USE_VTRACE + long s; + int vc; + //vc=app->GetVTraceCount(); + //return (ulong)((vc-baseVCount)/TRACES_PER_SECOND); + UpdateTicks(); + return ticks/TRACES_PER_SECOND; +#endif +#ifdef USE_UST + UpdateTicks(); + return ticks/1000000000; // 10^9 = nanoseconds +#endif +#ifdef USE_TIME + time_t t; + time(&t); + return (ulong)(t-base_secs); +#endif +#ifdef USE_OS_TICK + UpdateTicks(); + return ticks/1000; +#endif +#ifdef USE_GETTIMEOFDAY + UpdateTicks(); + return ticks/1000000; +#endif +} +#ifdef USE_UST +uint64 QTimer::GetTicks() +#else +int QTimer::GetTicks() +#endif +// Get #ticks, 1 tick is 1 vertical blank interval, or nanosecond, or WHATEVER! +// Don't use this function in application code; too many variant +{ + UpdateTicks(); + return ticks; + //int vc; + //vc=app->GetVTraceCount(); + //return (int)(vc-baseVCount); +} +int QTimer::GetMilliSeconds() +{ +#ifdef USE_UST + //uint64 div; + //div=1000000; + UpdateTicks(); +//qdbg("ticks=%lld\n",ticks); + return (int)(ticks/1000000); +#endif +#ifdef USE_TIME + UpdateTicks(); + return (int)(ticks*1000); +#endif +#ifdef USE_OS_TICK + UpdateTicks(); + return (int)ticks; +#endif +#ifdef USE_GETTIMEOFDAY + UpdateTicks(); + return ticks/1000; +#endif +} +int QTimer::GetMicroSeconds() +// Returns time in microseconds +{ +#ifdef USE_UST + UpdateTicks(); + return (int)(ticks/1000); +#endif +#ifdef USE_TIME + UpdateTicks(); + return (int)(ticks*1000000); +#endif +#ifdef USE_OS_TICK + // Not really microseconds! + UpdateTicks(); + return (int)ticks; +#endif +#ifdef USE_GETTIMEOFDAY + UpdateTicks(); + return ticks; +#endif +} + + +void QTimer::WaitForTime(int secs,int msecs) +// Reasonably multitasking-friendly wait for the timer to pass the given +// time and return. +// On O2's and most low level SGI's, the accurary is ~10ms (scheduler slice) +// Starts the timer if it is not running (instead of just returning) +// On Win32, we might just use Sleep() +{ int n; + secs=secs*1000+msecs; + // Make sure timer is running + if(!IsRunning())Start(); + while(1) + { n=GetMilliSeconds(); + if(n>=secs)break; + Sleep(10); + } +} + +/***************** +* TIME ADJUSTING * +*****************/ +void QTimer::AdjustMilliSeconds(int delta) +// Adjust time in milliseconds +// 'delta' may be negative or positive. Note that this may underflow the +// timer, meaning it will be negative. +{ +#ifdef USE_UST + uint64 delta64; + delta64=(uint64)delta; + // Get time in nanoseconds + delta64*=1000000; + ticks+=delta64; +#endif +#ifdef USE_OS_TICK + // Adjust msecs + ticks+=delta; +#endif +#ifdef USE_GETTIMEOFDAY + ticks+=delta*1000; +#endif +} + +/** TEST **/ + +//#define NOTDEF_TEST +#ifdef NOTDEF_TEST + +#include + +void main(void) +{ QTimer *qt; + ulong s,m; + QAppSetup(); + qt=new QTimer(); + while(!RMB()) + { qt->GetTime(&s,&m); + printf("S=%d, M=%4d\n",s,m); + } + //delete qt; + QAppQuit(); +} + +#endif diff --git a/usr/Src/Core/xSystem3D.cpp b/usr/Src/Core/xSystem3D.cpp new file mode 100644 index 0000000..8b27a9e --- /dev/null +++ b/usr/Src/Core/xSystem3D.cpp @@ -0,0 +1,108 @@ +/******************************************************************** + created: 2007/10/29 + created: 29:10:2007 15:19 + filename: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src\xSystem3D.cpp + file path: f:\ProjectRoot\current\vt_plugins\vt_toolkit\src + file base: xSystem3D + file ext: cpp + author: mc007 + + purpose: +*********************************************************************/ + +/*#ifndef USEDIRECTX9 + #define USEDIRECTX9 +#endif*/ + +#include "pch.h" +#include "xSystem3D.h" +#include "d3d9.h" +#include "CKAll.h" +#include "3d/DXDiagNVUtil.h" +#include "../Manager/InitMan.h" + + +extern InitMan *_im2; +////////////////////////////////////////////////////////////////////// +// +// DirectX-Helpers +// +// + +namespace xSystem3DHelper +{ + /************************************************************************/ + /* */ + /************************************************************************/ + + void xSSaveAllDxPropsToFile(char*file) + { + + DXDiagNVUtil nvutil; + nvutil.InitIDxDiagContainer(); + + FILE *fp = fopen("x:\\dx.out","a"); + //nvutil.ListAllDXDiagPropertyNames(); + nvutil.ListAllDXDiagPropertyNamesToTxtFile(fp,true,NULL,NULL); + + + + } + //int xSGetAvailableTextureMem(); + + int xSGetAvailableTextureMem(CKContext *ctx) + + { + + ////////////////////////////////////////////////////////////////////////// + if (GetIManager() && GetIManager()->m_Context) + { + + CKContext * ctx1 = GetIManager()->m_Context; + CKRenderManager* rm = ctx1->GetRenderManager(); + CKRenderContext* rc = rm->GetRenderContext(0); + VxDirectXData* dx = rc->GetDirectXInfo(); + + int z_ = 0; + IDirect3DDevice9 *d_ptr = ((IDirect3DDevice9*)dx->D3DDevice); + + if(dx) { return d_ptr->GetAvailableTextureMem(); } + } + + ////////////////////////////////////////////////////////////////////////// + return -1; + + } + +/************************************************************************/ +/* */ +/************************************************************************/ + + + float xSGetPhysicalMemoryInMB() + { + DXDiagNVUtil nvutil; + nvutil.InitIDxDiagContainer(); + + + float ret = -1; + nvutil.GetPhysicalMemoryInMB(&ret); + nvutil.FreeIDxDiagContainer(); + + return ret; + } + + +///////////////////////////////////////////////////////////////////////// + int xSGetPhysicalGPUMemoryInMB(int device) + { + + DXDiagNVUtil nvutil; + nvutil.InitIDxDiagContainer(); + + int ret = -1; + nvutil.GetDisplayDeviceMemoryInMB(device, &ret); + nvutil.FreeIDxDiagContainer(); + return ret; + } +} \ No newline at end of file diff --git a/usr/Src/Core/xTime.cpp b/usr/Src/Core/xTime.cpp new file mode 100644 index 0000000..d71454b --- /dev/null +++ b/usr/Src/Core/xTime.cpp @@ -0,0 +1,74 @@ +#include + + +#include "xTime.h" +#include +xTime::xTime() +{ + // Default time span + span=0.01; + spanMS=10; + tmr=new QTimer(); + Reset(); +} +xTime::~xTime() +{ + SAFE_DELETE(tmr); +} + +/********** +* Attribs * +**********/ +void xTime::AddSimTime(int msecs) +// Another 'msecs' of time was simulated +{ + curSimTime+=msecs; +} +#ifdef OBS_INLINED +void xTime::SetLastSimTime(int t) +// 't' is the time to which the sim has been simulated +// This is set after a number of integrations to remember the last +// time for the next graphics frame (calculating the distance in time to 'now') +{ + lastSimTime=t; +} +#endif +void xTime::SetSpan(int ms) +// Set integration step time in milliseconds +{ + spanMS=ms; + span=((float)ms)/1000.0f; +} + + + +/************* +* Start/stop * +*************/ +void xTime::Start() +// Start the real timer +{ + tmr->Start(); +} +void xTime::Stop() +// Stop the real timer +{ + tmr->Stop(); +} +void xTime::Reset() +// Reset the real timer (to 0) +{ + tmr->Reset(); + curRealTime=0; + curSimTime=0; + lastSimTime=0; +} + +/********* +* Update * +*********/ +void xTime::Update() +// Update the real timing +{ + curRealTime=tmr->GetMilliSeconds(); +} diff --git a/usr/Src/Interface/BodyShort.cpp b/usr/Src/Interface/BodyShort.cpp new file mode 100644 index 0000000..e69de29 diff --git a/usr/Src/Interface/BodyShort.h b/usr/Src/Interface/BodyShort.h new file mode 100644 index 0000000..e69de29 diff --git a/usr/Src/Interface/Interface.rar b/usr/Src/Interface/Interface.rar new file mode 100644 index 0000000..49f7460 Binary files /dev/null and b/usr/Src/Interface/Interface.rar differ diff --git a/usr/Src/Interface/PBDodyTab.cpp b/usr/Src/Interface/PBDodyTab.cpp new file mode 100644 index 0000000..5c6a39d --- /dev/null +++ b/usr/Src/Interface/PBDodyTab.cpp @@ -0,0 +1,55 @@ +// PBDodyTab.cpp : implementation file +// + +#include "stdafx.h" +#include "PBDodyTab.h" + + +// PBDodyTab + +IMPLEMENT_DYNAMIC(PBDodyTab, CTabCtrl) + +PBDodyTab::PBDodyTab() +{ + + EnableAutomation(); +} + +PBDodyTab::~PBDodyTab() +{ +} + +void PBDodyTab::OnFinalRelease() +{ + // When the last reference for an automation object is released + // OnFinalRelease is called. The base class will automatically + // deletes the object. Add additional cleanup required for your + // object before calling the base class. + + CTabCtrl::OnFinalRelease(); +} + + +BEGIN_MESSAGE_MAP(PBDodyTab, CTabCtrl) +END_MESSAGE_MAP() + + +BEGIN_DISPATCH_MAP(PBDodyTab, CTabCtrl) +END_DISPATCH_MAP() + +// Note: we add support for IID_IPBDodyTab to support typesafe binding +// from VBA. This IID must match the GUID that is attached to the +// dispinterface in the .IDL file. + +// {35C830F1-59A2-40B2-971F-2BEEC5930188} +static const IID IID_IPBDodyTab = +{ 0x35C830F1, 0x59A2, 0x40B2, { 0x97, 0x1F, 0x2B, 0xEE, 0xC5, 0x93, 0x1, 0x88 } }; + +BEGIN_INTERFACE_MAP(PBDodyTab, CTabCtrl) + INTERFACE_PART(PBDodyTab, IID_IPBDodyTab, Dispatch) +END_INTERFACE_MAP() + + +// PBDodyTab message handlers + + diff --git a/usr/Src/Interface/PBDodyTab.h b/usr/Src/Interface/PBDodyTab.h new file mode 100644 index 0000000..f2482cb --- /dev/null +++ b/usr/Src/Interface/PBDodyTab.h @@ -0,0 +1,22 @@ +#pragma once + + +// PBDodyTab + +class PBDodyTab : public CTabCtrl +{ + DECLARE_DYNAMIC(PBDodyTab) + +public: + PBDodyTab(); + virtual ~PBDodyTab(); + + virtual void OnFinalRelease(); + +protected: + DECLARE_MESSAGE_MAP() + DECLARE_DISPATCH_MAP() + DECLARE_INTERFACE_MAP() +}; + + diff --git a/usr/Src/Interface/PBRootForm.cpp b/usr/Src/Interface/PBRootForm.cpp new file mode 100644 index 0000000..cfbe65b --- /dev/null +++ b/usr/Src/Interface/PBRootForm.cpp @@ -0,0 +1,49 @@ +// PBRootForm.cpp : implementation file +// + +#include "stdafx2.h" + +#include "PBRootForm.h" + + +// PBRootForm + +IMPLEMENT_DYNCREATE(PBRootForm, CFormView) + +PBRootForm::PBRootForm() + : CFormView(PBRootForm::IDD) +{ + +} + +PBRootForm::~PBRootForm() +{ +} + +void PBRootForm::DoDataExchange(CDataExchange* pDX) +{ + CFormView::DoDataExchange(pDX); +} + +BEGIN_MESSAGE_MAP(PBRootForm, CFormView) +END_MESSAGE_MAP() + + +// PBRootForm diagnostics + +#ifdef _DEBUG +void PBRootForm::AssertValid() const +{ + CFormView::AssertValid(); +} + +#ifndef _WIN32_WCE +void PBRootForm::Dump(CDumpContext& dc) const +{ + CFormView::Dump(dc); +} +#endif +#endif //_DEBUG + + +// PBRootForm message handlers diff --git a/usr/Src/Interface/PBRootForm.h b/usr/Src/Interface/PBRootForm.h new file mode 100644 index 0000000..c1e0e69 --- /dev/null +++ b/usr/Src/Interface/PBRootForm.h @@ -0,0 +1,30 @@ +#pragma once + + + +// PBRootForm form view + +class PBRootForm : public CFormView +{ + DECLARE_DYNCREATE(PBRootForm) + +protected: + PBRootForm(); // protected constructor used by dynamic creation + virtual ~PBRootForm(); + +public: + enum { IDD = PBRootMDI }; +#ifdef _DEBUG + virtual void AssertValid() const; +#ifndef _WIN32_WCE + virtual void Dump(CDumpContext& dc) const; +#endif +#endif + +protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + + DECLARE_MESSAGE_MAP() +}; + + diff --git a/usr/Src/Interface/PBShared.cpp b/usr/Src/Interface/PBShared.cpp new file mode 100644 index 0000000..a8b1383 --- /dev/null +++ b/usr/Src/Interface/PBShared.cpp @@ -0,0 +1,448 @@ +#include "StdAfx2.h" +#include "PCommonDialog.h" +#include "PBodySetup.h" +#include "PBodyTabCtrl.h" +#include "PBXMLSetup.h" +#include "resource.h" +#include "VITabCtrl.h" + + +#include "resource.h" +#include "VITabCtrl.h" +#include "VIControl.h" +#include "..\..\include\interface\pcommondialog.h" + + + +/************************************************************************/ +/* Global vars */ +/************************************************************************/ + +static CPSharedBase *gXML=NULL; +static CPSharedBase *gCOMMON=NULL; +static CPSharedBase *gCOLLISION=NULL; +static CPSharedBase *gOPTIMIZATION=NULL; + + +static CPSharedBase* gSharedBase=NULL; + +static CPSharedBase *gDialogs[DLGCOUNT] = +{ + gXML, + gCOMMON, +}; + +CPBParentDialog::CPBParentDialog(CKParameter* Parameter,CWnd*parent,CK_CLASSID Cid) : + CParameterDialog(Parameter,Cid) , CPSharedBase(Parameter,this,Cid) , m_TabControl(parent) +{ + + + if (_cleanUpIfNew(Parameter)) + { + _emptyTabs(); + } + + if (gSharedBase) + gSharedBase=NULL; + + gSharedBase =this; + setRootDialog(this); + setRootParameter(Parameter); + getInstance(); + //loadTabPane(); +} +CPBParentDialog::CPBParentDialog(CKParameter* Parameter,CK_CLASSID Cid) : + CParameterDialog(Parameter,Cid) , CPSharedBase(Parameter,this,Cid) , m_TabControl(NULL) +{ + + if (_cleanUpIfNew(Parameter)) + { + _emptyTabs(); + } + + gSharedBase = this; + setRootDialog(this); + setRootParameter(Parameter); + //loadTabPane(); + + +} + + +void CPBParentDialog::_destroy() +{ + if (getTabs().GetTabCount()) + { + _emptyTabs(); + } + + gSharedBase=NULL; +} + +/* + +CPBParentDialog::CPBParentDialog(CWnd* pParent = NULL) : +CParameterDialog(Parameter,Cid) , CPSharedBase(Parameter,this,Cid) +{ + + if (_cleanUpIfNew(Parameter)) + { + _emptyTabs(); + } + + gSharedBase = this; + setRootDialog(this); + setRootParameter(Parameter); + +}*/ + + + +/************************************************************************/ +/* */ +/************************************************************************/ + + + + + + + +/************************************************************************/ +/* */ +/************************************************************************/ + +BOOL CPSharedBase::initChildWin(CDialog* pDlg, UINT dialogID,UINT dialogPlaceHolderID) +{ + + ASSERT( pDlg ); + + if (!pDlg) + { + return false; + } + + + // wind handle of the target bed : + HWND dstWindow = NULL; + CPBParentDialog* parent = (CPBParentDialog*)getInstance()->getRootDlg(); + if (parent) + { + dstWindow = parent->getDlgWindowHandle(dialogPlaceHolderID); + + }else + return false; + + + + CWnd *cDstWindow = CWnd::FromHandle(dstWindow); + if (cDstWindow) + { + int p = getNbDialogs(); + }else + { + return false; + } + + + + //CWnd* pWnd = pDlg->GetDlgItem( dialogPlaceHolderID ); + CRect rcValue; + + if (pDlg) + { + cDstWindow->GetWindowRect( &rcValue ); // Use picture box position. + parent->ScreenToClient( &rcValue ); + + if (pDlg->Create( dialogID, cDstWindow )) + { + pDlg->SetWindowPos( cDstWindow, rcValue.left, rcValue.top,rcValue.Width(), rcValue.Height(), SWP_HIDEWINDOW); + return true; + } + //pWnd->ShowWindow(SWP_SHOWWINDOW); + } + + return false; +} + + + +void CPSharedBase::_dtrBodyCommonDlg(){} + + + +CPSharedBase* CPSharedBase::getDialog(int identifier) +{ + ASSERT( identifier >= 0 && identifier < DLGCOUNT ); + if (gDialogs[identifier]) + return gDialogs[identifier]; + + return NULL; +} + +void CPSharedBase::setDialog(int identifier,CPSharedBase*src) +{ + ASSERT( identifier >= 0 && identifier < DLGCOUNT ); + //if (gDialogs[identifier] != src ) + gDialogs[identifier] = src; +} +void CPSharedBase::destroyDialog(int identifier,CPSharedBase*src) +{ + ASSERT( identifier >= 0 && identifier < DLGCOUNT ); + if (src) + { + + } + src = gDialogs[identifier] = NULL; + +} +CParameterDialog *CPSharedBase::getRootDlg() +{ + return getInstance() ? getInstance()->dlgRoot : NULL; +} +CKParameter *CPSharedBase::getRootParameter() +{ + return getInstance() ? getInstance()->parameter : NULL; +} +void CPSharedBase::setRootParameter(CKParameter * val) +{ + if (getInstance()) + getInstance()->parameter = val; +} +void CPSharedBase::setRootDialog(CParameterDialog * val) +{ + if (getInstance()) + getInstance()->dlgRoot = val; +} +ParDialogArrayType& CPSharedBase::getDialogs() +{ + return getInstance() ? getInstance()->mDialogs : ParDialogArrayType() ; +} + + +CPSharedBase::~CPSharedBase() +{ + _reset(); +} +void CPSharedBase::_destroy() +{ + +} +void CPSharedBase::_reset() +{ + parameter = NULL; + dlgRoot = NULL; + mDialogs.Clear(); + mTab = NULL; + +} + +void CPSharedBase::_construct() +{ + +} + +CPSharedBase::CPSharedBase( + CKParameter* Parameter, + CParameterDialog *rootDialog, + CK_CLASSID Cid) : + dlgRoot(rootDialog) , parameter(Parameter) +{ + mDialogs.Clear(); + mTab = NULL; +} + +CPSharedBase::CPSharedBase(CKParameter* Parameter,CK_CLASSID Cid) +{ + dlgRoot=NULL; + mDialogs.Clear(); + mTab = NULL; + + +} +CPSharedBase*CPSharedBase::getInstance() +{ + return gSharedBase; +} +CPSharedBase::CPSharedBase(CParameterDialog *consumer,CKParameter* parameter) +{ + addDialog(consumer,parameter); +} +void CPSharedBase::addDialog(CParameterDialog *dlg,CKParameter*parameter) +{ + /*if(getInstance() && (*getDialogs().FindPtr(parameter))) + getDialogs().InsertUnique(parameter,dlg); */ +} +CPSharedBase** CPSharedBase::getStaticDialogs() +{ + return gDialogs; +} +int CPSharedBase::getNbDialogs() +{ + int result = 0; + for ( int i = 0 ; i < DLGCOUNT ; i++ ) + { + if (getStaticDialogs()[i] != NULL ) + { + result++; + } + } + return result; + +} + +/* +LRESULT CPBParentDialog::OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam) +{ + + WORD keyState = 0; + keyState |= (::GetKeyState(VK_CONTROL) < 0) ? MK_CONTROL : 0; + keyState |= (::GetKeyState(VK_SHIFT) < 0) ? MK_SHIFT : 0; + + LRESULT lResult; + HWND hwFocus = ::GetFocus(); + const HWND hwDesktop = ::GetDesktopWindow(); + + if (hwFocus == NULL) + lResult = SendMessage(WM_MOUSEWHEEL, (wParam << 16) | keyState, lParam); + else + { + do { + lResult = ::SendMessage(hwFocus, WM_MOUSEWHEEL,(wParam << 16) | keyState, lParam); + hwFocus = ::GetParent(hwFocus); + } + while (lResult == 0 && hwFocus != NULL && hwFocus != hwDesktop); + } + return lResult; + +} +*/ +/* +void CPBParentDialog::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) +{ + + //int cStates = GET_KEYSTATE_WPARAM(wParam); + int wheelDirection = zDelta; + + if (wheelDirection>0) + { + if ( mTestViControl.GetActiveTabIndex() +1 < mTestViControl.GetTabCount() ) + { + mTestViControl.SetActiveTab(mTestViControl.GetActiveTabIndex() +1 ); + }else{ + mTestViControl.SetActiveTab( 0 ); + } + }else + { + if ( mTestViControl.GetActiveTabIndex() -1 >=0 ) + { + mTestViControl.SetActiveTab(mTestViControl.GetActiveTabIndex() - 1 ); + }else{ + mTestViControl.SetActiveTab(mTestViControl.GetTabCount()); + } + } +} +*/ + + +void CPBParentDialog::InitAllControls() +{ + CRect rect; + EnableWindow(true); + + + PBodyTabContrl* viCtrl = getTabControl(); + if (!viCtrl)return; + + + + GetClientRect(&rect); + HRESULT res = ((VITabCtrl*)getTabControl())->Create("NoName",VITabCtrl::VITAB_UP|VITabCtrl::VITAB_DOWN,rect,((CWnd*)(getTabControl())),IDC_PBODY_TAB_PANE); + getTabControl()->GetClientRect(&rect); + + getTabControl()->_construct(); + + getTabControl()->GetClientRect(&rect); + + /************************************************************************/ + /* */ + /************************************************************************/ + + // wind handle of the target bed : + HWND dstWindow = NULL; + CWnd *cDstWindow = NULL; + CPBParentDialog* parent = (CPBParentDialog*)getInstance()->getRootDlg(); + + + + + if (parent) + { + dstWindow = parent->getDlgWindowHandle(IDC_SPACER); + if (dstWindow) + { + cDstWindow= CWnd::FromHandle(dstWindow); + + CRect rcValue; + cDstWindow->GetWindowRect( &rcValue ); // Use picture box position. + parent->ScreenToClient( &rcValue ); + + CWnd * target = parent->GetDlgItem(IDC_PBODY_TAB_PANE); + if (target) + { + + //target->SetWindowPos( cDstWindow, rcValue.left, rcValue.top,rcValue.Width(), rcValue.Height(), SWP_SHOWWINDOW); + //pWnd->ShowWindow(SWP_SHOWWINDOW); + } + } + } + + + + + + + + /************************************************************************/ + /* */ + /************************************************************************/ + + + + + //CPBParentDialog* parent = (CPBParentDialog*)getInstance()->getRootDlg(); + + + + int err = getTabControl()->InsertTab(-1,"XML",parent,true); + err = getTabControl()->InsertTab(-1,"XMLasas",parent,true ); + + + VITabCtrl::VITab *bTab= new VITabCtrl::VITab(); + bTab->m_Flags=VITabCtrl::VITAB_BORDER; + bTab->m_Name = "XML"; + bTab->m_Width = 30; + bTab->m_Wnd = NULL; + + + err = getTabControl()->GetTabCount(); + err = getTabControl()->InsertTab(-1,bTab,true); + + + + + + // parent->ScreenToClient( &rect ); + // getTabControl()->ScreenToClient(&rect); + //*/ + + +} + +int CPBParentDialog::OnCreate(LPCREATESTRUCT lpCreateStruct) +{ + if (__super::OnCreate(lpCreateStruct) == -1) + return -1; + + return 1; +} diff --git a/usr/Src/Interface/PBodyMainMDIEx.cpp b/usr/Src/Interface/PBodyMainMDIEx.cpp new file mode 100644 index 0000000..e69de29 diff --git a/usr/Src/Interface/PBodyMainMDIEx.h b/usr/Src/Interface/PBodyMainMDIEx.h new file mode 100644 index 0000000..edf3f84 --- /dev/null +++ b/usr/Src/Interface/PBodyMainMDIEx.h @@ -0,0 +1,26 @@ +#pragma once + + +// PBodyMainMDIEx frame with splitter + +class PBodyMainMDIEx : public CMDIChildWndEx +{ + DECLARE_DYNCREATE(PBodyMainMDIEx) +protected: + PBodyMainMDIEx(); // protected constructor used by dynamic creation + virtual ~PBodyMainMDIEx(); + + CSplitterWnd m_wndSplitter; + +public: + virtual void OnFinalRelease(); + +protected: + virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); + + DECLARE_MESSAGE_MAP() + DECLARE_DISPATCH_MAP() + DECLARE_INTERFACE_MAP() +}; + + diff --git a/usr/Src/Interface/PBodyQuickPage.cpp b/usr/Src/Interface/PBodyQuickPage.cpp new file mode 100644 index 0000000..01bd650 --- /dev/null +++ b/usr/Src/Interface/PBodyQuickPage.cpp @@ -0,0 +1,41 @@ +#include "stdafx2.h" +#include "PBodyTabCtrl.h" +#include "PBodyQuickPage.h" + + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// PBodyQuickPage dialog + + +PBodyQuickPage::PBodyQuickPage(CWnd* pParent /*=NULL*/) + : CDialog(PBodyQuickPage::IDD, pParent) +{ + //{{AFX_DATA_INIT(PBodyQuickPage) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void PBodyQuickPage::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(PBodyQuickPage) + // NOTE: the ClassWizard will add DDX and DDV calls here + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(PBodyQuickPage, CDialog) + //{{AFX_MSG_MAP(PBodyQuickPage) + // NOTE: the ClassWizard will add message map macros here + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// PBodyQuickPage message handlers diff --git a/usr/Src/Interface/PBodyQuickPage.h b/usr/Src/Interface/PBodyQuickPage.h new file mode 100644 index 0000000..435e745 --- /dev/null +++ b/usr/Src/Interface/PBodyQuickPage.h @@ -0,0 +1,46 @@ +#if !defined(AFX_TABONE_H__4F1DD92C_C67D_48AE_A73F_02D7EDA0580E__INCLUDED_) +#define AFX_TABONE_H__4F1DD92C_C67D_48AE_A73F_02D7EDA0580E__INCLUDED_ + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 +// TabOne.h : header file +// + +///////////////////////////////////////////////////////////////////////////// +// PBodyQuickPage dialog + +class PBodyQuickPage : public CDialog +{ +// Construction +public: + PBodyQuickPage(CWnd* pParent = NULL); // standard constructor + +// Dialog Data + //{{AFX_DATA(PBodyQuickPage) + enum { IDD = IDD_PBCOMMON }; + // NOTE: the ClassWizard will add data members here + //}}AFX_DATA + + +// Overrides + // ClassWizard generated virtual function overrides + //{{AFX_VIRTUAL(PBodyQuickPage) + protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + +// Implementation +protected: + + // Generated message map functions + //{{AFX_MSG(PBodyQuickPage) + // NOTE: the ClassWizard will add member functions here + //}}AFX_MSG + DECLARE_MESSAGE_MAP() +}; + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // !defined(AFX_TABONE_H__4F1DD92C_C67D_48AE_A73F_02D7EDA0580E__INCLUDED_) diff --git a/usr/Src/Interface/PBodySetup.cpp b/usr/Src/Interface/PBodySetup.cpp new file mode 100644 index 0000000..ad99f15 --- /dev/null +++ b/usr/Src/Interface/PBodySetup.cpp @@ -0,0 +1,292 @@ +#include "StdAfx2.h" + +#include "PCommonDialog.h" +#include "PBodySetup.h" +#include "..\..\include\interface\pbodysetup.h" + + +#define LAYOUT_STYLE (WS_CHILD|WS_VISIBLE) +#define LAYOUT_ShaderREE 130 + + + +int CPBodyCfg::OnSelect(int before/* =-1 */) +{ + + return -1; +} + +CParameterDialog* CPBodyCfg::refresh(CKParameter*src) +{ return this; } + +void CPBodyCfg::fillFlags() +{ + + BF_Move.SetCheck(true); +} + + +void CPBodyCfg::fillHullType() +{ + + + + HType.AddString("Sphere"); + HType.AddString("Box"); + HType.AddString("Capsule"); + HType.AddString("Plane"); + HType.AddString("Convex Mesh"); + HType.AddString("Height Field"); + HType.AddString("Wheel"); + HType.AddString("Cloth"); + HType.SetCurSel(0); + +} + + +void CPBodyCfg::initSplitter() +{ + + + + + //[...] //optional pre initialization steps + //int opt = mTestViControl.Create(WS_CHILD|WS_VISIBLE,r,pWnd,IDC_TRACKTEST); + /*if (opt) + {*/ + + // mTestViControl.SetColors(CZC_176,CZC_BLACK,CZC_176,CZC_WHITE,CZC_128,CZC_200); + /* + mTestViControl.SetFont(GetVIFont(VIFONT_NORMAL),FALSE); + mTestViControl.SetItemHeight(18);*/ + //mTestViControl.SetWindowText("Shader Tree"); + // mTestViControl.SetStyle(NTVS_DRAWHSEPARATOR); + // mTestViControl.SetPreAllocSize(2); + + // Create columns + // mTestViControl.SetColumnCount(1); + //mTestViControl.SetColumn(0, "Shader", 0, 10); + + //HTREEITEM newItem = mTestViControl.InsertItem("asddad", 0,0, mTestViControl.GetFirstVisibleItem() ); + + + + + // newItem->Flags = NTVI_EDITABLE; + // newItem->Data = NULL; + + /*HNTVITEM newItem; + newItem = mTestViControl.InsertItem("asddad", (HNTVITEM)NULL, TRUE); + newItem->Flags = NTVI_EDITABLE; + newItem->Data = NULL;*/ + + //} + +} +void CPBodyCfg::Init(CParameterDialog *parent) +{ + mParent = parent; + +} + + +CPBodyCfg::~CPBodyCfg() +{ + _destroy(); +} + +void CPBodyCfg::_destroy() +{ + //::CPSharedBase::_destroy(); + +} +//CPSharedBase(this,Parameter) +CPBodyCfg::CPBodyCfg(CKParameter* Parameter,CK_CLASSID Cid) :CParameterDialog(Parameter,Cid) +{ + setEditedParameter(Parameter); + //int snow = getNbDialogs(); + + +} + + +LRESULT CPBodyCfg::OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam) +{ + + WORD keyState = 0; + keyState |= (::GetKeyState(VK_CONTROL) < 0) ? MK_CONTROL : 0; + keyState |= (::GetKeyState(VK_SHIFT) < 0) ? MK_SHIFT : 0; + + LRESULT lResult; + HWND hwFocus = ::GetFocus(); + const HWND hwDesktop = ::GetDesktopWindow(); + + if (hwFocus == NULL) + lResult = SendMessage(WM_MOUSEWHEEL, (wParam << 16) | keyState, lParam); + else + { + do { + lResult = ::SendMessage(hwFocus, WM_MOUSEWHEEL,(wParam << 16) | keyState, lParam); + hwFocus = ::GetParent(hwFocus); + } + while (lResult == 0 && hwFocus != NULL && hwFocus != hwDesktop); + } + return lResult; + +} + +LRESULT CPBodyCfg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) +{ + switch (message) + { + + /* + case WM_MOUSEWHEEL: + { + int cStates = GET_KEYSTATE_WPARAM(wParam); + int wheelDirection = GET_WHEEL_DELTA_WPARAM(wParam); + + if (wheelDirection>0) + { + if ( mTestViControl.GetActiveTabIndex() +1 < mTestViControl.GetTabCount() ) + { + mTestViControl.SetActiveTab(mTestViControl.GetActiveTabIndex() +1 ); + }else{ + mTestViControl.SetActiveTab( 0 ); + } + }else + { + if ( mTestViControl.GetActiveTabIndex() -1 >=0 ) + { + mTestViControl.SetActiveTab(mTestViControl.GetActiveTabIndex() - 1 ); + }else{ + mTestViControl.SetActiveTab(mTestViControl.GetTabCount()); + } + } + + break; + return NULL; + } + */ + case WM_LBUTTONDOWN: + case WM_LBUTTONDBLCLK: + { + + + int indexTabUnderMouse = 0; + indexTabUnderMouse = mTestViControl.GetTabUnderMouse(); + if (indexTabUnderMouse >=0 ) + { + mTestViControl.SetActiveTab(indexTabUnderMouse); + } + //HTREEITEM newItem = mTestViControl.InsertItem("asddad2323",mTestViControl.GetFirstVisibleItem(), mTestViControl.GetFirstVisibleItem() ); + + /*HTREEITEM newItem; + newItem = mTestViControl.InsertItem("asddad", (HTREEITEM)NULL, NULL); + */ + /* + HNTVITEM newItem; + newItem = mTestViControl.InsertItem("asddad", (HNTVITEM)NULL, TRUE); + newItem->Flags = NTVI_EDITABLE; + newItem->Data = NULL; + + */ + /* + mTestViControl.UpdateWindow(); + mTestViControl.ShowWindow(1); + */ + + /* + mTestViControl.AddItem("asdasd",NULL); + int a = mTestViControl.GetSubItemCount(0);*/ + + /* + RECT r; + GetClientRect(&r); + + CDC* pDC=CDC::FromHandle((HDC)wParam); + pDC->FillSolidRect(&r,RGB(100,200,200));*/ + + break; + + } + case WM_ERASEBKGND: + { + /*RECT r; + GetClientRect(&r); + CDC* pDC=CDC::FromHandle((HDC)wParam); + pDC->FillSolidRect(&r,RGB(200,200,200)); + return 1;*/ + }break; + case CKWM_OK: + { + //CEdit *valueText = (CEdit*)GetDlgItem(IDC_EDIT); + /*CString l_strValue; + valueText->GetWindowText(l_strValue); + + double d; + if (sscanf(l_strValue,"%Lf",&d)) { + parameter->SetValue(&d); + }*/ + } break; + + case CKWM_INIT: + { + + RECT r; + GetClientRect(&r); + /* + CDC* pDC=CDC::FromHandle((HDC)wParam);*/ + //initSplitter(); + + fillHullType(); + char temp[64]; + double d; + } break; + } + return CDialog::WindowProc(message, wParam, lParam); +} + +void CPBodyCfg::DoDataExchange(CDataExchange* pDX) +{ + + //CDialog::DoDataExchange(pDX); + CParameterDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CPBodyCfg) + + DDX_Control(pDX, IDC_HULLTYPE, HType); + DDX_Control(pDX, IDC_LBL_HTYPE, LBL_HType); + + DDX_Control(pDX, IDC_BFLAGS_MOVING,BF_Move); + DDX_Control(pDX, IDC_BFLAGS_GRAV,BF_Grav); + DDX_Control(pDX, IDC_BFLAGS_COLL,BF_Collision); + DDX_Control(pDX, IDC_BFLAGS_COLL_NOTIFY,BF_CollisionNotify); + + DDX_Control(pDX, IDC_BFLAGS_KINEMATIC,BF_Kinematic); + DDX_Control(pDX, IDC_BFLAGS_TRIGGER,BF_TriggerShape); + DDX_Control(pDX, IDC_BFLAGS_SLEEP,BF_Sleep); + DDX_Control(pDX, IDC_BFLAGS_SSHAPE,BF_SubShape); + DDX_Control(pDX, IDC_BFLAGS_HIERARCHY,BF_Hierarchy); + DDX_Control(pDX, IDC_BFLAGS_DEFORMABLE,BF_Deformable); + DDX_Control(pDX, IDC_FLAGS_BG,BF_BG_Rect); + DDX_Control(pDX, IDC_LBL_FLAGS,LBL_Flags); + //}}AFX_DATA_MAP + +} + +BEGIN_MESSAGE_MAP(CPBodyCfg, CParameterDialog) + ON_WM_MOUSEMOVE() + ON_STN_CLICKED(IDC_LBL_FLAGS, OnStnClickedLblFlags) + ON_STN_CLICKED(IDC_DYNA_FLAGS_RECT, OnStnClickedDynaFlagsRect) +END_MESSAGE_MAP() + + +void CPBodyCfg::OnStnClickedLblFlags() +{ + // TODO: Add your control notification handler code here +} + +void CPBodyCfg::OnStnClickedDynaFlagsRect() +{ + // TODO: Add your control notification handler code here +} diff --git a/usr/Src/Interface/PBodyTabCtrl.cpp b/usr/Src/Interface/PBodyTabCtrl.cpp new file mode 100644 index 0000000..d485cb5 --- /dev/null +++ b/usr/Src/Interface/PBodyTabCtrl.cpp @@ -0,0 +1,153 @@ +#include "stdafx2.h" +#include "resource.h" +#include "PBodyTabCtrl.h" +#include "PBodyQuickPage.h" + + + + +/*#include "TabOne.h" +#include "TabTwo.h" +#include "TabThree.h" +*/ +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// PBodyTabContrl + +IMPLEMENT_DYNCREATE(PBodyTabContrl,VITabCtrl) + +PBodyTabContrl::PBodyTabContrl(CWnd*win) +{ + + + //PBodyTabContrl + m_tabPages[0]=new PBodyQuickPage(); + if (m_tabPages[0]) + { + m_nNumberOfPages=1; + + } + /*m_tabPages[1]=new CTabTwo; + m_tabPages[2]=new CTabThree; + */ + + m_nNumberOfPages=1; +} + +PBodyTabContrl::PBodyTabContrl() : VITabCtrl() +{ + + //PBodyTabContrl + m_tabPages[0]=new PBodyQuickPage(); + if (m_tabPages[0]) + { + m_nNumberOfPages=1; + + } + /*m_tabPages[1]=new CTabTwo; + m_tabPages[2]=new CTabThree; +*/ + + m_nNumberOfPages=1; +} + +PBodyTabContrl::~PBodyTabContrl() +{ + for(int nCount=0; nCount < m_nNumberOfPages; nCount++){ + delete m_tabPages[nCount]; + } +} + + + +void PBodyTabContrl::_construct() +{ + + VITabCtrl::EnableWindow(true); + VITabCtrl::EnableAutomation(); + VITabCtrl::ShowWindow(SW_SHOW); + + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + + + + m_tabCurrent=0; + //m_tabPages[0]->Create(IDD_PBCOMMON, this); + //m_tabPages[1]->Create(IDD_PBCOMMON, this); + + //m_tabPages[0]->ShowWindow(SW_SHOW); + //m_tabPages[1]->ShowWindow(SW_SHOW); + //m_tabPages[1]->ShowWindow(SW_SHOW); + + //m_tabPages[2]->ShowWindow(SW_HIDE); + + m_nNumberOfPages = 1; + + SetRectangle(); +} +void PBodyTabContrl::Init() +{ +//VITabCtrl::UpdateWindow(); + +} + +void PBodyTabContrl::SetRectangle() +{ + + CRect tabRect, itemRect; + int nX, nY, nXc, nYc; + + GetClientRect(&tabRect); + CRect r; + + + ((CTabCtrl *)(this))->GetItemRect(0, &itemRect); + + + + //TabCtrl_GetItemRect(0, &itemRect); + //GetItemRect + + nX=itemRect.left; + nY=itemRect.bottom+1; + nXc=tabRect.right-itemRect.left-1; + nYc=tabRect.bottom-nY-1; +/* + m_tabPages[0]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_SHOWWINDOW); + for(int nCount=1; nCount < m_nNumberOfPages; nCount++){ + m_tabPages[nCount]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_HIDEWINDOW); + }*/ + +} + +BEGIN_MESSAGE_MAP(PBodyTabContrl, VITabCtrl) + //{{AFX_MSG_MAP(PBodyTabContrl) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// PBodyTabContrl message handlers + +/* +void PBodyTabContrl::OnLButtonDown(UINT nFlags, CPoint point) +{ + + + CTabCtrl &tabContr = ((CTabCtrl*)(this)); + tabContr::OnLButtonDown(nFlags, point); + + if(m_tabCurrent != (CTabCtrl*)GetCurFocus()){ + m_tabPages[m_tabCurrent]->ShowWindow(SW_HIDE); + m_tabCurrent=GetCurFocus(); + m_tabPages[m_tabCurrent]->ShowWindow(SW_SHOW); + m_tabPages[m_tabCurrent]->SetFocus(); + } + + +} +*/ \ No newline at end of file diff --git a/usr/Src/Interface/PBodyTabCtrl.h b/usr/Src/Interface/PBodyTabCtrl.h new file mode 100644 index 0000000..5b604c4 --- /dev/null +++ b/usr/Src/Interface/PBodyTabCtrl.h @@ -0,0 +1,42 @@ +#ifndef __PBODY_TAB_CONTRL_H__ +#define __PBODY_TAB_CONTRL_H__ + +#include "VIControls.h" + + +///////////////////////////////////////////////////////////////////////////// +// PBodyTabContrl window + +class PBodyTabContrl : public VITabCtrl +{ + DECLARE_DYNCREATE(PBodyTabContrl) + +public: + PBodyTabContrl(); +public: + enum { IDD = IDC_PBODY_TAB_PANE }; + + PBodyTabContrl(CWnd*win); + virtual ~PBodyTabContrl(); + CDialog *m_tabPages[1]; + int m_tabCurrent; + int m_nNumberOfPages; + void _construct(); + +// Attributes +public: + +// Operations +public: + void Init(); + void SetRectangle(); + +protected: + DECLARE_MESSAGE_MAP() +}; + +///////////////////////////////////////////////////////////////////////////// + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. +#endif diff --git a/usr/Src/Interface/PCommonDialog.cpp b/usr/Src/Interface/PCommonDialog.cpp new file mode 100644 index 0000000..6e2a1fc --- /dev/null +++ b/usr/Src/Interface/PCommonDialog.cpp @@ -0,0 +1,203 @@ +#include "PCommonDialog.h" +#include "resource.h" +#include "VITabCtrl.h" + +#include "VIControl.h" + + +#define LAYOUT_STYLE (WS_CHILD|WS_VISIBLE) +#define LAYOUT_ShaderREE 130 + +RECT _GetNullRect() { + return RECT(); +} + + +LRESULT CPBCommonDialog::OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam) +{ + LRESULT lResult; + return lResult; + +} + +void CPBCommonDialog::fillFlags() +{ + + BF_Move.SetCheck(true); +} + + +void CPBCommonDialog::fillHullType() +{ + + HType.AddString("Sphere"); + HType.AddString("Box"); + HType.AddString("Capsule"); + HType.AddString("Plane"); + HType.AddString("Convex Mesh"); + HType.AddString("Height Field"); + HType.AddString("Wheel"); + HType.AddString("Cloth"); + HType.SetCurSel(0); +} + + +namespace vtAgeia +{ + +} + + +CKBOOL CPBCommonDialog::On_Init() +{ + + fillHullType(); + + + return true; + + +} + +LRESULT CPBCommonDialog::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) +{ + switch (message) + { + + + case WM_MOUSEWHEEL: + { + + + break; + + } + case WM_ERASEBKGND: + { + /*RECT r; + GetClientRect(&r); + CDC* pDC=CDC::FromHandle((HDC)wParam); + pDC->FillSolidRect(&r,RGB(100,8,100)); + */ + + }break; + case CKWM_OK: + { + + } break; + + case CKWM_INIT: + { + fillHullType(); + } break; + } + return CDialog::WindowProc(message, wParam, lParam); +} + + +void CPBCommonDialog::DoDataExchange(CDataExchange* pDX) +{ + + //CDialog::DoDataExchange(pDX); + + CParameterDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CPBCommonDialog) + //DDX_Control(pDX, IDC_DYNA_FLAGS_RECT,mDynaFlagsRect); + DDX_Control(pDX, IDC_HULLTYPE, HType); + DDX_Control(pDX, IDC_LBL_HTYPE, LBL_HType); + + + DDX_Control(pDX, IDC_BFLAGS_MOVING,BF_Move); + DDX_Control(pDX, IDC_BFLAGS_GRAV,BF_Grav); + DDX_Control(pDX, IDC_BFLAGS_HIERARCHY,BF_Hierarchy); + + DDX_Control(pDX, IDC_BFLAGS_COLL,BF_Collision); + DDX_Control(pDX, IDC_BFLAGS_COLL_NOTIFY,BF_CollisionNotify); + + DDX_Control(pDX, IDC_BFLAGS_KINEMATIC,BF_Kinematic); + DDX_Control(pDX, IDC_BFLAGS_TRIGGER,BF_TriggerShape); + DDX_Control(pDX, IDC_BFLAGS_SLEEP,BF_Sleep); + DDX_Control(pDX, IDC_BFLAGS_SSHAPE,BF_SubShape); + + DDX_Control(pDX, IDC_BFLAGS_DEFORMABLE,BF_Deformable); + DDX_Control(pDX, IDC_LBL_LFLAGS,LBL_Flags); + DDX_Control(pDX, IDC_LBL_FLAGS,LBL_Flags); + DDX_Control(pDX, IDC_LBL_DYNAFLAGS,LBL_DFlags); + + + DDX_Control(pDX, IDC_TLFLAGS_POS,TF_POS); + DDX_Control(pDX, IDC_TLFLAGS_ROT,TF_ROT); + + DDX_Control(pDX, IDC_TLFLAGS_POS_X,TF_PX); + DDX_Control(pDX, IDC_TLFLAGS_POS_Y,TF_PY); + DDX_Control(pDX, IDC_TLFLAGS_POS_Z,TF_PZ); + + + DDX_Control(pDX, IDC_TLFLAGS_ROT_X,TF_RX); + DDX_Control(pDX, IDC_TLFLAGS_ROT_Y,TF_RY); + DDX_Control(pDX, IDC_TLFLAGS_ROT_Z,TF_RZ); + + //}}AFX_DATA_MAP + +} +// DoubleParamDialog dialog + +BEGIN_MESSAGE_MAP(CPBCommonDialog, CParameterDialog) + ON_STN_CLICKED(IDC_DYNA_FLAGS_RECT, OnStnClickedDynaFlagsRect) +END_MESSAGE_MAP() + + +#include "xEnumerations.h" +#include "..\..\include\interface\pcommondialog.h" + + +/*IMPLEMENT_DYNAMIC(CPBCommonDialog, CDialog) +CPBCommonDialog::CPBCommonDialog(CKParameter *param, CWnd* pParent) +: CDialog(CPBCommonDialog::IDD, pParent) +{ + parameter = param; +}*/ + + + + +BOOL CPBCommonDialog::OnInitDialog() +{ + CParameterDialog::OnInitDialog(); + m_tt = new CToolTipCtrl(); + m_tt->Create(this); + // Add tool tips to the controls, either by hard coded string + // or using the string table resource + m_tt->AddTool( &BF_Move, _T("This is a tool tip!")); + /*m_tt->AddTool( &mDynaFlagsRect, _T("This is a tool tip!")); + //m_ToolTip.AddTool( &m_myEdit, IDS_MY_EDIT); + m_tt->Activate(TRUE); +*/ + // TODO: Add extra initialization here + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +BOOL CPBCommonDialog::PreTranslateMessage(MSG* pMsg) +{ + if(pMsg->message >= WM_MOUSEFIRST && pMsg->message <= WM_MOUSELAST) + m_tt->RelayEvent(pMsg); + + + // TODO: Add your specialized code here and/or call the base class + + return CParameterDialog::PreTranslateMessage(pMsg); +} + +void CPBCommonDialog::OnStnClickedDynaFlagsRect() +{ + + m_tt->Activate(TRUE); + + LPRECT rect; + m_tt->GetWindowRect(rect); + m_tt->GetWindowRect(rect); + + +} diff --git a/usr/Src/Interface/PropertiesViewBar.cpp b/usr/Src/Interface/PropertiesViewBar.cpp new file mode 100644 index 0000000..a587ed4 --- /dev/null +++ b/usr/Src/Interface/PropertiesViewBar.cpp @@ -0,0 +1,287 @@ +// This is a part of the Microsoft Foundation Classes C++ library. +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// This source code is only intended as a supplement to the +// Microsoft Foundation Classes Reference and related +// electronic documentation provided with the library. +// See these sources for detailed information regarding the +// Microsoft Foundation Classes product. + +#include "stdafx2.h" +//#include "VisualStudioDemo.h" +//#include "MainFrm.h" +#include "PropertiesViewBar.h" +#include "resource.h" + +#include + +#ifdef _DEBUG +#undef THIS_FILE +static char THIS_FILE[]=__FILE__; +#define new DEBUG_NEW +#endif + +///////////////////////////////////////////////////////////////////////////// +// CResourceViewBar + +CPropertiesViewBar::CPropertiesViewBar() +{ +} + +CPropertiesViewBar::~CPropertiesViewBar() +{ +} + +BEGIN_MESSAGE_MAP(CPropertiesViewBar, CDockablePane) + ON_WM_CREATE() + ON_WM_SIZE() + ON_COMMAND(ID_SORTINGPROP, OnSortingprop) + ON_UPDATE_COMMAND_UI(ID_SORTINGPROP, OnUpdateSortingprop) + ON_COMMAND(ID_PROPERIES1, OnProperies1) + ON_UPDATE_COMMAND_UI(ID_PROPERIES1, OnUpdateProperies1) + ON_COMMAND(ID_PROPERIES2, OnProperies2) + ON_UPDATE_COMMAND_UI(ID_PROPERIES2, OnUpdateProperies2) + ON_COMMAND(ID_EXPAND, OnExpand) + ON_UPDATE_COMMAND_UI(ID_EXPAND, OnUpdateExpand) + ON_WM_SETFOCUS() + ON_WM_SETTINGCHANGE() +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CResourceViewBar message handlers + +void CPropertiesViewBar::AdjustLayout() +{ + if (GetSafeHwnd() == NULL) + { + return; + } + + CRect rectClient,rectCombo; + GetClientRect(rectClient); + + m_wndObjectCombo.GetWindowRect(&rectCombo); + + int cyCmb = rectCombo.Size().cy; + int cyTlb = m_wndToolBar.CalcFixedLayout(FALSE, TRUE).cy; + + m_wndObjectCombo.SetWindowPos(NULL, rectClient.left, rectClient.top, rectClient.Width(), 200, SWP_NOACTIVATE | SWP_NOZORDER); + m_wndToolBar.SetWindowPos(NULL, rectClient.left, rectClient.top + cyCmb, rectClient.Width(), cyTlb, SWP_NOACTIVATE | SWP_NOZORDER); + m_wndPropList.SetWindowPos(NULL, rectClient.left, rectClient.top + cyCmb + cyTlb, rectClient.Width(), rectClient.Height() -(cyCmb+cyTlb), SWP_NOACTIVATE | SWP_NOZORDER); +} + +int CPropertiesViewBar::OnCreate(LPCREATESTRUCT lpCreateStruct) +{ + if (CDockablePane::OnCreate(lpCreateStruct) == -1) + return -1; + + CRect rectDummy; + rectDummy.SetRectEmpty(); + + // Create combo: + const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST + | WS_BORDER | CBS_SORT | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; + + if (!m_wndObjectCombo.Create(dwViewStyle, rectDummy, this, 1)) + { + TRACE0("Failed to create Properies Combo \n"); + return -1; // fail to create + } + + m_wndObjectCombo.AddString(_T("IDD_ABOUTBOX(Dialog)")); + m_wndObjectCombo.SetFont(CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT))); + m_wndObjectCombo.SetCurSel(0); + + if (!m_wndPropList.Create(WS_VISIBLE | WS_CHILD, rectDummy, this, 2)) + { + TRACE0("Failed to create Properies Grid \n"); + return -1; // fail to create + } + + InitPropList(); + + m_wndToolBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_PROPERTIES); + m_wndToolBar.LoadToolBar(IDR_PROPERTIES, 0, 0, TRUE /* Is locked */); + + OnChangeVisualStyle(); + + m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() | CBRS_TOOLTIPS | CBRS_FLYBY); + m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT)); + m_wndToolBar.SetOwner(this); + + // All commands will be routed via this control , not via the parent frame: + m_wndToolBar.SetRouteCommandsViaFrame(FALSE); + + AdjustLayout(); + return 0; +} + +void CPropertiesViewBar::OnSize(UINT nType, int cx, int cy) +{ + CDockablePane::OnSize(nType, cx, cy); + AdjustLayout(); +} + +void CPropertiesViewBar::OnSortingprop() +{ + m_wndPropList.SetAlphabeticMode(); +} + +void CPropertiesViewBar::OnUpdateSortingprop(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(m_wndPropList.IsAlphabeticMode()); +} + +void CPropertiesViewBar::OnExpand() +{ + m_wndPropList.SetAlphabeticMode(FALSE); +} + +void CPropertiesViewBar::OnUpdateExpand(CCmdUI* pCmdUI) +{ + pCmdUI->SetCheck(!m_wndPropList.IsAlphabeticMode()); +} + +void CPropertiesViewBar::OnProperies1() +{ + // TODO: Add your command handler code here +} + +void CPropertiesViewBar::OnUpdateProperies1(CCmdUI* /*pCmdUI*/) +{ + // TODO: Add your command update UI handler code here +} + +void CPropertiesViewBar::OnProperies2() +{ + // TODO: Add your command handler code here +} + +void CPropertiesViewBar::OnUpdateProperies2(CCmdUI* /*pCmdUI*/) +{ + // TODO: Add your command update UI handler code here +} + +void CPropertiesViewBar::InitPropList() +{ + SetPropListFont(); + + m_wndPropList.EnableHeaderCtrl(FALSE); + m_wndPropList.EnableDescriptionArea(); + m_wndPropList.SetVSDotNetLook(); + m_wndPropList.MarkModifiedProperties(); + + std::auto_ptr apGroup1(new CMFCPropertyGridProperty(_T("Appearance"))); + + apGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("3D Look"), (_variant_t) false, _T("Specifies the dialog's font will be nonbold and controls will have a 3D border"))); + + CMFCPropertyGridProperty* pProp = new CMFCPropertyGridProperty(_T("Border"), _T("Dialog Frame"), _T("One of: None, Thin, Resizable, or Dialog Frame")); + pProp->AddOption(_T("None")); + pProp->AddOption(_T("Thin")); + pProp->AddOption(_T("Resizable")); + pProp->AddOption(_T("Dialog Frame")); + pProp->AllowEdit(FALSE); + + apGroup1->AddSubItem(pProp); + apGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("Caption"), (_variant_t) _T("About"), _T("Specifies the text that will be displayed in the dialog's title bar"))); + + m_wndPropList.AddProperty(apGroup1.release()); + + std::auto_ptr apSize(new CMFCPropertyGridProperty(_T("Window Size"), 0, TRUE)); + + pProp = new CMFCPropertyGridProperty(_T("Height"), (_variant_t) 250l, _T("Specifies the dialog's height")); + pProp->EnableSpinControl(TRUE, 0, 1000); + apSize->AddSubItem(pProp); + + pProp = new CMFCPropertyGridProperty( _T("Width"), (_variant_t) 150l, _T("Specifies the dialog's width")); + pProp->EnableSpinControl(TRUE, 1, 500); + apSize->AddSubItem(pProp); + + m_wndPropList.AddProperty(apSize.release()); + + std::auto_ptr apGroup2(new CMFCPropertyGridProperty(_T("Font"))); + + LOGFONT lf; + CFont* font = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); + font->GetLogFont(&lf); + + lstrcpy(lf.lfFaceName, _T("Arial")); + + apGroup2->AddSubItem(new CMFCPropertyGridFontProperty(_T("Font"), lf, CF_EFFECTS | CF_SCREENFONTS, _T("Specifies the default font for the dialog"))); + apGroup2->AddSubItem(new CMFCPropertyGridProperty(_T("Use System Font"), (_variant_t) true, _T("Specifies that the dialog uses MS Shell Dlg font"))); + + m_wndPropList.AddProperty(apGroup2.release()); + + std::auto_ptr apGroup3(new CMFCPropertyGridProperty(_T("Misc"))); + pProp = new CMFCPropertyGridProperty(_T("(Name)"), _T("IDD_ABOUT_BOX(dialog)")); + pProp->Enable(FALSE); + apGroup3->AddSubItem(pProp); + + CMFCPropertyGridColorProperty* pColorProp = new CMFCPropertyGridColorProperty(_T("Window Color"), RGB(210, 192, 254), NULL, _T("Specifies the default dialog color")); + pColorProp->EnableOtherButton(_T("Other...")); + pColorProp->EnableAutomaticButton(_T("Default"), ::GetSysColor(COLOR_3DFACE)); + apGroup3->AddSubItem(pColorProp); + + static TCHAR BASED_CODE szFilter[] = _T("Icon Files(*.ico)|*.ico|All Files(*.*)|*.*||"); + apGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("Icon"), TRUE, _T(""), _T("ico"), 0, szFilter, _T("Specifies the dialog icon"))); + + apGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("Folder"), _T("c:\\"))); + + m_wndPropList.AddProperty(apGroup3.release()); + + std::auto_ptr apGroup4(new CMFCPropertyGridProperty(_T("Hierarchy"))); + + CMFCPropertyGridProperty* pGroup41 = new CMFCPropertyGridProperty(_T("First sub-level")); + apGroup4->AddSubItem(pGroup41); + + CMFCPropertyGridProperty* pGroup411 = new CMFCPropertyGridProperty(_T("Second sub-level")); + pGroup41->AddSubItem(pGroup411); + + pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 1"), (_variant_t) _T("Value 1"), _T("This is a description"))); + pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 2"), (_variant_t) _T("Value 2"), _T("This is a description"))); + pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 3"), (_variant_t) _T("Value 3"), _T("This is a description"))); + + apGroup4->Expand(FALSE); + m_wndPropList.AddProperty(apGroup4.release()); +} + +void CPropertiesViewBar::OnSetFocus(CWnd* pOldWnd) +{ + CDockablePane::OnSetFocus(pOldWnd); + + m_wndPropList.SetFocus(); + +} + +void CPropertiesViewBar::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) +{ + CDockablePane::OnSettingChange(uFlags, lpszSection); + SetPropListFont(); +} + +void CPropertiesViewBar::SetPropListFont() +{ + ::DeleteObject (m_fntPropList.Detach ()); + + LOGFONT lf; + afxGlobalData.fontRegular.GetLogFont (&lf); + + NONCLIENTMETRICS info; + info.cbSize = sizeof(info); + + afxGlobalData.GetNonClientMetrics (info); + + lf.lfHeight = info.lfMenuFont.lfHeight; + lf.lfWeight = info.lfMenuFont.lfWeight; + lf.lfItalic = info.lfMenuFont.lfItalic; + + m_fntPropList.CreateFontIndirect (&lf); + + m_wndPropList.SetFont(&m_fntPropList); +} + +void CPropertiesViewBar::OnChangeVisualStyle() +{ + m_wndToolBar.CleanUpLockedImages(); + //m_wndToolBar.LoadBitmap(theApp.m_bHiColorIcons ? IDB_PROP24 : IDR_PROPERTIES, 0, 0, TRUE /* Locked */); +} diff --git a/usr/Src/Interface/PropertiesViewBar.h b/usr/Src/Interface/PropertiesViewBar.h new file mode 100644 index 0000000..1e7cf2f --- /dev/null +++ b/usr/Src/Interface/PropertiesViewBar.h @@ -0,0 +1,71 @@ +// This is a part of the Microsoft Foundation Classes C++ library. +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// This source code is only intended as a supplement to the +// Microsoft Foundation Classes Reference and related +// electronic documentation provided with the library. +// See these sources for detailed information regarding the +// Microsoft Foundation Classes product. + +#pragma once +#include "StdAfx2.h" + +class CPropertiesToolBar : public CMFCToolBar +{ +public: + virtual void OnUpdateCmdUI(CFrameWnd* /*pTarget*/, BOOL bDisableIfNoHndler) + { + CMFCToolBar::OnUpdateCmdUI((CFrameWnd*) GetOwner(), bDisableIfNoHndler); + } + + virtual BOOL AllowShowOnList() const { return FALSE; } +}; + +class CPropertiesViewBar : public CDockablePane +{ +// Construction +public: + CPropertiesViewBar(); + + void AdjustLayout(); + +// Attributes +public: + void SetVSDotNetLook(BOOL bSet) + { + m_wndPropList.SetVSDotNetLook(bSet); + m_wndPropList.SetGroupNameFullWidth(bSet); + } + + void OnChangeVisualStyle(); + +protected: + CComboBox m_wndObjectCombo; + CPropertiesToolBar m_wndToolBar; + CMFCPropertyGridCtrl m_wndPropList; + CFont m_fntPropList; + +// Implementation +public: + virtual ~CPropertiesViewBar(); + +protected: + afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); + afx_msg void OnSize(UINT nType, int cx, int cy); + afx_msg void OnSortingprop(); + afx_msg void OnUpdateSortingprop(CCmdUI* pCmdUI); + afx_msg void OnProperies1(); + afx_msg void OnUpdateProperies1(CCmdUI* pCmdUI); + afx_msg void OnProperies2(); + afx_msg void OnUpdateProperies2(CCmdUI* pCmdUI); + afx_msg void OnExpand(); + afx_msg void OnUpdateExpand(CCmdUI* pCmdUI); + afx_msg void OnSetFocus(CWnd* pOldWnd); + afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection); + + DECLARE_MESSAGE_MAP() + + void InitPropList(); + void SetPropListFont(); +}; + diff --git a/usr/Src/Interface/StdAfx.cpp b/usr/Src/Interface/StdAfx.cpp new file mode 100644 index 0000000..bcb79c1 --- /dev/null +++ b/usr/Src/Interface/StdAfx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// Editor.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx2.h" + + + diff --git a/usr/Src/Interface/icon1.ico b/usr/Src/Interface/icon1.ico new file mode 100644 index 0000000..e9bade5 Binary files /dev/null and b/usr/Src/Interface/icon1.ico differ diff --git a/usr/Src/Interface/old.txt b/usr/Src/Interface/old.txt new file mode 100644 index 0000000..75f2dfa --- /dev/null +++ b/usr/Src/Interface/old.txt @@ -0,0 +1,483 @@ +DoubleParamDialog::~DoubleParamDialog(){} +LRESULT DoubleParamDialog::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { + switch (message) + { + case WM_ERASEBKGND: + { + RECT r; + GetClientRect(&r); + CDC* pDC=CDC::FromHandle((HDC)wParam); + pDC->FillSolidRect(&r,RGB(200,200,200)); + return 1; + }break; + case CKWM_OK: + { + CEdit *valueText = (CEdit*)GetDlgItem(IDC_EDIT); + /*CString l_strValue; + valueText->GetWindowText(l_strValue); + + double d; + if (sscanf(l_strValue,"%Lf",&d)) { + parameter->SetValue(&d); + }*/ + } break; + + case CKWM_INIT: + { + /*char temp[64]; + double d; + parameter->GetValue((void*)&d,FALSE); + sprintf(temp,"%Lf",d); + + CEdit *valueText = (CEdit*)GetDlgItem(IDC_EDIT);*/ +// valueText->SetWindowText(temp); + } break; + } + return CDialog::WindowProc(message, wParam, lParam); +} + +BOOL DoubleParamDialog::OnInitDialog() +{ + CDialog::OnInitDialog(); + + + //do your initialization stuff here + + editValue.SetEditStyle(VI_CTRL_EDIT_FLOAT); + + editValue.Create(ES_CENTER|WS_VISIBLE|WS_CHILD|ES_AUTOHSCROLL, CRect(140,10,240,25), this, IDC_EDIT); + textValue.Create("Parameter (double) :", WS_VISIBLE|WS_CHILD, CRect(20,10,120,30), this, IDC_PARAM_NAME); + + //end initialization stuff + + return FALSE; //false don't set the focus on the value +} + +void DoubleParamDialog::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); +} + + +BEGIN_MESSAGE_MAP(DoubleParamDialog, CDialog) +END_MESSAGE_MAP() + + +/*IMPLEMENT_DYNAMIC(CPBCommonDialog, CDialog) +CPBCommonDialog::CPBCommonDialog(CKParameter *param, CWnd* pParent) +: CDialog(CPBCommonDialog::IDD, pParent) +{ + parameter = param; +}*/ + +WIN_HANDLE CKDoubleUIFunc (CKParameter *param,WIN_HANDLE ParentWindow,CKRECT *rect) { + + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + DoubleParamDialog* dlg_modeless=new DoubleParamDialog(param); + dlg_modeless->Create(IDD_DIALOG1,CWnd::FromHandle((HWND)ParentWindow)); + return dlg_modeless->GetSafeHwnd(); +} + + + +IMPLEMENT_DYNAMIC(DoubleParamDialog, CDialog) +DoubleParamDialog::DoubleParamDialog(CKParameter *param, CWnd* pParent /*=NULL*/) +: CDialog(DoubleParamDialog::IDD, pParent) +{ + parameter = param; +} + + + +/*void CPBParentDialog::OnMouseMove(UINT nFlags, CPoint point) +{ + if (!m_bOverControl) // Cursor has just moved over control + { + TRACE0("Entering control\n"); + + m_bOverControl = TRUE; // Set flag telling us the mouse is in + Invalidate(); // Force a redraw + + SetTimer(m_nTimerID, 100, NULL); // Keep checking back every 1/10 sec + } + + CParameterDialog::OnMouseMove(nFlags, point); +} + +*/ +/* +void CPBParentDialog::OnTimer(UINT nIDEvent) +{ + // Where is the mouse? + CPoint p(GetMessagePos()); + ScreenToClient(&p); + + // Get the bounds of the control (just the client area) + CRect rect; + GetClientRect(rect); + + // Check the mouse is inside the control + if (!rect.PtInRect(p)) + { + TRACE0("Leaving control\n"); + + // if not then stop looking... + m_bOverControl = FALSE; + KillTimer(m_nTimerID); + + // ...and redraw the control + Invalidate(); + } + + CParameterDialog::OnTimer(nIDEvent); +} + +*/ +// +/*void CPBParentDialog::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) +{ + +} +*/ + + + + +/*void CPBodyCfg::PreSubclassWindow() +{ +CParameterDialog::PreSubclassWindow(); +ModifyStyle(0, SS_OWNERDRAW); // make the button owner drawn +}*/ + +/DDX_Control(pDX, IDC_TRACKTEST, mTestViControl); + DDX_Control(pDX, IDC_MAINTAB, mTestViControl);*/ + + + //DDX_Control(pDX, IDC_HULLTYPE, HType); + //BS_OWNERDRAW | WS_TABSTOP + + + + + + +//bodyXMLSetup->Init(src,IDD_PB_MAINTAB_DST,NULL); +/* + CWnd* pWnd = this->GetDlgItem( IDC_MAIN_VIEW_XML); + + MultiParamEditDlg* mF = new MultiParamEditDlg(src->GetCKContext(),pWnd); + + mF->AddParameter(testVector); + CRect rcValue; + pWnd->GetWindowRect( &rcValue ); // Use picture box position. + + pWnd->ScreenToClient( &rcValue ); + + mF->SetMode(MultiParamEditDlg::MODELESSEDIT|MultiParamEditDlg::USER_CUSTOM_BUTTONS|MultiParamEditDlg::AUTOCLOSE_WHEN_MODELESS|MultiParamEditDlg::CENTERMOUSESTYLE); + //err = bodyXMLSetup->ModelessCreate(pWnd); + + mF->UpdateData(); + mF->UpdateWindow(); + mF->ShowWindow(SW_NORMAL); + mF->DoModal(); +*/ + + + + + //err = bodyXMLSetup->GetMode(); + //bodyXMLSetup->SetMode(MultiParamEditDlg::MODELESSEDIT|MultiParamEditDlg::LIVE_UPDATE|MultiParamEditDlg::USER_CUSTOM_BUTTONS|MultiParamEditDlg::CREATEPARAM); + //bodyXMLSetup->SetMode(MultiParamEditDlg::MODELESSEDIT|MultiParamEditDlg::LIVE_UPDATE|MultiParamEditDlg::USER_CUSTOM_BUTTONS|MultiParamEditDlg::CREATEPARAM); + + //err = bodyXMLSetup->GetMode(); + + //bodyXMLSetup->AddParameter(testVector); + //err = bodyXMLSetup->ModelessCreate(pWnd); + //bodyXMLSetup->AttachControlSite(pWnd,IDC_MAIN_VIEW_XML); + //bodyXMLSetup->SetParent(pWnd); +// bodyXMLSetup-> +/* + + RECT r; + bodyXMLSetup->GetClientRect(&r);*/ + + /* + RECT r; + pWnd->GetClientRect(&r); + bodyXMLSetup->SetTitle("adsfasdf"); + //the call to AdjustWindows is needed in order for all child windows to be correctly placed + //pWnd->AdjustWindows(&r,TRUE); + + //err = DoModal(); + //bodyXMLSetup->GetStyle(); + + + + CRect rcValue; + pWnd->GetWindowRect( &rcValue ); // Use picture box position. + pWnd->ScreenToClient( &rcValue ); + bodyXMLSetup->SetWindowPos( pWnd, rcValue.left, rcValue.top,rcValue.Width(), rcValue.Height(), SWP_HIDEWINDOW); + */ + + /*bodyXMLSetup->UpdateData(); + bodyXMLSetup->UpdateWindow(); + bodyXMLSetup->ShowWindow(SW_NORMAL); + */ + + + + //err = bodyXMLSetup->SetStyle(0); + + + + + + //HTREEITEM newItem = mTestViControl.InsertItem("asddad2323",mTestViControl.GetFirstVisibleItem(), mTestViControl.GetFirstVisibleItem() ); + + /*HTREEITEM newItem; + newItem = mTestViControl.InsertItem("asddad", (HTREEITEM)NULL, NULL); + */ + /* + HNTVITEM newItem; + newItem = mTestViControl.InsertItem("asddad", (HNTVITEM)NULL, TRUE); + newItem->Flags = NTVI_EDITABLE; + newItem->Data = NULL; + +*/ +/* + mTestViControl.UpdateWindow(); + mTestViControl.ShowWindow(1); +*/ + + + + +/* + mTestViControl.AddItem("asdasd",NULL); + int a = mTestViControl.GetSubItemCount(0);*/ + + /* + RECT r; + GetClientRect(&r); + + CDC* pDC=CDC::FromHandle((HDC)wParam); + pDC->FillSolidRect(&r,RGB(100,200,200));*/ + + + + + + + + + + + CKBOOL CPBCommonDialog::On_Init() +{ + + + //fillHullType(); + + + //CParameterDialog::On_Init(); + //HType.set .SetEditStyle(VI_CTRL_EDIT_FLOAT); + + //HType.Create() + + //editValue.Create(ES_CENTER|WS_VISIBLE|WS_CHILD|ES_AUTOHSCROLL, CRect(0,0,100,25), this, IDC_EDIT); + + //textValue.Create("Parameter (double) :", WS_VISIBLE|WS_CHILD, CRect(20,10,120,30), this, IDC_PARAM_NAME); + + return true; + + +} + + + + LRESULT CPBCommonDialog::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { + switch (message) + { + + + case WM_MOUSEWHEEL: + { + + /*LRESULT lResult; + WORD keyState = 0; + keyState |= (::GetKeyState(VK_CONTROL) < 0) ? MK_CONTROL : 0; + keyState |= (::GetKeyState(VK_SHIFT) < 0) ? MK_SHIFT : 0;*/ + if(mDlgDeformable) + { + + int cStates = GET_KEYSTATE_WPARAM(wParam); + int wheelDirection = GET_WHEEL_DELTA_WPARAM(wParam); + //mDlgDeformable->OnMouseWheel(cStates,wheelDirection,CPoint()); + +// CWnd* pWnd = GetDlgItem( IDD_PBCOMMON_DEFORMABLE ); +// if (pWnd) +// { +// lResult = ::SendMessage(mDlgDeformable->GetSafeHwnd(), WM_MOUSEWHEEL,(wParam << 16) | keyState, lParam); +// } + + + } + + //RECT r; + //GetClientRect(&r); + //CDC* pDC=CDC::FromHandle((HDC)wParam); + //pDC->FillSolidRect(&r,RGB(200,200,200)); + break; + + } + case WM_ERASEBKGND: + { + RECT r; + GetClientRect(&r); + CDC* pDC=CDC::FromHandle((HDC)wParam); + pDC->FillSolidRect(&r,RGB(200,200,200)); + + }break; + case CKWM_OK: + { + //CEdit *valueText = (CEdit*)GetDlgItem(IDC_EDIT); + /*CString l_strValue; + valueText->GetWindowText(l_strValue); + + double d; + if (sscanf(l_strValue,"%Lf",&d)) { + parameter->SetValue(&d); + }*/ + } break; + + case CKWM_INIT: + { + char temp[64]; + double d; + + } break; + } + return CDialog::WindowProc(message, wParam, lParam); +} + + +void CPBCommonDialog::DoDataExchange(CDataExchange* pDX) +{ + //DDX_Control(pDX, IDC_FLEX_FRAME,BF_FLEX_Rect); + + //CDialog::DoDataExchange(pDX); + + CParameterDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CPBCommonDialog) + + //}}AFX_DATA_MAP + +} + +BEGIN_MESSAGE_MAP(CPBCommonDialog, CParameterDialog) + ON_WM_MOUSEMOVE() + ON_WM_MOUSEWHEEL() + ON_WM_HSCROLL() + ON_WM_VSCROLL() +END_MESSAGE_MAP() + +// Sets up dialog as a child/control of this dialog. +// "iWinID" is the resource ID of the dialog. +bool CPBCommonDialog::InitChildWin( CDialog* pDlg, UINT iWinID,int otherID ) +{ + CWnd* pWnd = GetDlgItem( otherID ); + CRect rcValue; + + if (pWnd && pDlg) { + pWnd->GetWindowRect( &rcValue ); // Use picture box position. + ScreenToClient( &rcValue ); + + if (pDlg->Create( iWinID, pWnd )) + { + pDlg->SetWindowPos( pWnd, rcValue.left, rcValue.top,rcValue.Width(), rcValue.Height(), SWP_HIDEWINDOW); + return true; + } + //pWnd->ShowWindow(SWP_SHOWWINDOW); + } + + return false; +} + + + + + + + + + /* +MultiParamEditDlg* CPBXMLSetup::refresh(CKParameter*src) +{ return this; } +*/ + +/* +BOOL CPBXMLSetup::Init(CKParameter* Parameter,UINT nIDTemplate,CParameterDialog *parent) +{ + + //int err = getXMLSetup().ModelessCreate(GetDlgItem( IDC_MAIN_VIEW_XML)); + //id2= getXMLSetup().ModelessCreate(GetDlgItem( IDC_MAIN_VIEW_XML)); + //id2 = getXMLSetup().ModelessCreate(GetDlgItem( IDD_PB_MAINTAB_DST)); + //id2 = getXMLSetup().GetDlgCtrlID(); + //getXMLSetup().SetDlgCtrlID() + + + + //GetWindowRect( &rcValue ); // Use picture box position. + +// getXMLSetup().SetMode(MultiParamEditDlg::MODELESSEDIT|MultiParamEditDlg::USER_CUSTOM_BUTTONS|MultiParamEditDlg::AUTOCLOSE_WHEN_MODELESS|MultiParamEditDlg::CREATEPARAM); + //getXMLSetup().AttachControlSite(this,IDC_MAIN_VIEW_XML); + + + bodyXMLSetup->getXMLSetup().UpdateData(); + bodyXMLSetup->getXMLSetup().UpdateWindow(); + bodyXMLSetup->getXMLSetup().ShowWindow(SW_NORMAL); + //bodyXMLSetup->getXMLSetup().FlashWindow(1); + + return true; +} +*/ + +/* +CPBXMLSetup::CPBXMLSetup(CKParameter* Parameter,CK_CLASSID Cid) : + CParameterDialog(Parameter,Cid) , CPSharedBase(this,Parameter) , + mXMLSetup(Parameter->GetCKContext(),NULL) +{ + setEditedParameter(Parameter); +} + +CPBXMLSetup::CPBXMLSetup(CKParameter* Parameter,CWnd *parent,CK_CLASSID Cid) : + CParameterDialog(Parameter,Cid) , CPSharedBase(this,Parameter) , + mXMLSetup(Parameter->GetCKContext(),parent) +{ + setEditedParameter(Parameter); +} +*/ +/* +BOOL CPBXMLSetup::Create(CKParameter* Parameter,UINT nIDTemplate, CWnd* pParentWnd ) +{ + + //CParameterDialog::Create(nIDTemplate,pParentWnd); + return TRUE; + +} +*/ + + +/* +CPBXMLSetup::CPBXMLSetup(CKParameter* Parameter,CWnd* parent) : + MultiParamEditDlg(Parameter->GetCKContext(),parent) , + CPSharedBase(Parameter), + CParameterDialog(Parameter,Cid) +{ + mXMLSetup = NULL; +} +*/ + +//DDX_Control(pDX, IDC_MAIN_VIEW_XML, mXMLSetup); +//DDX_Control(pDX, IDC_XINTERN_LINK_LBL2, XMLInternLinkLbl);//DDX_Control(pDX, IDC_XEXTERN_LINK_LBL, XMLExternLinkLbl); +//DDX_Control(pDX, IDC_XEXTERN_LINK, XMLExternLink); \ No newline at end of file diff --git a/usr/Src/Interface/old/resource.h b/usr/Src/Interface/old/resource.h new file mode 100644 index 0000000..f2d686c --- /dev/null +++ b/usr/Src/Interface/old/resource.h @@ -0,0 +1,45 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by vtAgeiaInterface.rc +// +#define IDD_DIALOG1 2000 +#define IDC_EDIT 2001 +#define IDC_PARAM_NAME 2006 +#define IDC_LBL_HTYPE 10000 +#define IDC_BFLAGS_MOVING 10001 +#define IDC_LBL_FLAGS 10002 +#define IDC_BFLAGS_DEFORMABLE 10003 +#define IDC_BFLAGS_GRAV 10004 +#define IDC_BFLAGS_KINEMATIC 10005 +#define IDC_BFLAGS_COLL 10006 +#define IDC_BFLAGS_COLL_NOTIFY 10007 +#define IDC_BFLAGS_TRIGGER 10008 +#define IDC_BFLAGS_SSHAPE 10009 +#define IDC_BFLAGS_HIERARCHY 10010 +#define IDD_EDITOR 10011 +#define IDC_FLAGS_BG 10012 +#define IDI_EDITORICON 10013 +#define IDC_FLEX_FRAME 10014 +#define IDC_HULLTYPE 10015 +#define IDC_BFLAGS_TRIGGEREX 10018 +#define IDC_TRACKTEST 10019 +#define IDC_TRACKTEST_TREE 10019 +#define IDC_BFLAGS_TEST 10020 +#define IDC_BFLAGS_SLEEP 10021 +#define IDC_TREE1 10021 +#define IDD_PBCOMMON 10022 +#define IDC_TAB1 10022 +#define IDD_TOOLBAR 10023 +#define IDD_PBCOMMON_DEFORMABLE 10024 +#define IDC_MAINTAB 10025 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 10006 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 10023 +#define _APS_NEXT_SYMED_VALUE 10000 +#endif +#endif diff --git a/usr/Src/Interface/old/vtAgeiaInterface.rc b/usr/Src/Interface/old/vtAgeiaInterface.rc new file mode 100644 index 0000000..cb5f1b4 --- /dev/null +++ b/usr/Src/Interface/old/vtAgeiaInterface.rc @@ -0,0 +1,233 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_PBCOMMON DIALOGEX 0, 0, 365, 141 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS +EXSTYLE WS_EX_CONTROLPARENT +FONT 7, "Tahoma", 400, 0, 0x0 +BEGIN + COMBOBOX IDC_HULLTYPE,43,1,67,70,CBS_DROPDOWNLIST | + CBS_OWNERDRAWVARIABLE | CBS_HASSTRINGS | WS_VSCROLL | + WS_TABSTOP + LTEXT "Hull Type",IDC_LBL_HTYPE,3,3,38,11 + CONTROL "Moving",IDC_BFLAGS_MOVING,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,170,15,40,10,WS_EX_TRANSPARENT + CONTROL "Deformable",IDC_BFLAGS_DEFORMABLE,"Button", + BS_AUTOCHECKBOX,288,15,58,9,WS_EX_TRANSPARENT + CONTROL "Gravity",IDC_BFLAGS_GRAV,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,170,27,42,13,WS_EX_TRANSPARENT + CONTROL "Kinematic",IDC_BFLAGS_KINEMATIC,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,170,40,48,13, + WS_EX_TRANSPARENT + CONTROL "Collision",IDC_BFLAGS_COLL,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,218,15,44,10,WS_EX_TRANSPARENT + CONTROL "Collision Notify",IDC_BFLAGS_COLL_NOTIFY,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,218,27,65,13, + WS_EX_TRANSPARENT + CONTROL "Trigger Shape",IDC_BFLAGS_TRIGGER,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,218,40,61,13, + WS_EX_TRANSPARENT + CONTROL "Sub Shape",IDC_BFLAGS_SSHAPE,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,218,55,52,13,WS_EX_TRANSPARENT + CONTROL "Hierarchy",IDC_BFLAGS_HIERARCHY,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,170,55,50,13, + WS_EX_TRANSPARENT + CONTROL "Sleep",IDC_BFLAGS_SLEEP,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,288,52,44,13,WS_EX_TRANSPARENT + CONTROL "",IDC_FLAGS_BG,"Static",SS_BLACKFRAME | WS_TABSTOP,170, + 71,182,66 + LTEXT "Flags",IDC_LBL_FLAGS,120,7,42,11,0,WS_EX_TRANSPARENT + LTEXT "StaticPlaceHolder",IDC_FLEX_FRAME,2,23,161,109 +END + +IDD_PBCOMMON_DEFORMABLE DIALOGEX 0, 0, 160, 83 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_VISIBLE +EXSTYLE WS_EX_NOPARENTNOTIFY | WS_EX_CONTROLPARENT +FONT 7, "Tahoma", 400, 0, 0x0 +BEGIN + CONTROL "",IDC_MAINTAB,"SysTabControl32",TCS_RAGGEDRIGHT,3,2,150, + 22 +END + +IDD_EDITOR DIALOG 0, 0, 186, 97 +STYLE DS_SETFONT | WS_CHILD +FONT 8, "MS Sans Serif" +BEGIN +END + +IDD_TOOLBAR DIALOG 0, 0, 186, 97 +STYLE DS_SETFONT | WS_CHILD +FONT 8, "MS Sans Serif" +BEGIN +END + +IDD_DIALOG1 DIALOGEX 0, 0, 177, 19 +STYLE DS_SETFONT | WS_CHILD | WS_CLIPCHILDREN +FONT 8, "Microsoft Sans Serif", 400, 0, 0x0 +BEGIN +END + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 9, 1\r\n" + "#pragma code_page(1252)\r\n" + "#endif //_WIN32\r\n" + "#include ""afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 4,0,0,90 + PRODUCTVERSION 4,0,0,90 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "CompanyName", "Virtools SA" + VALUE "FileDescription", "Editor DLL" + VALUE "FileVersion", "4.0.0.90" + VALUE "InternalName", "Editor" + VALUE "LegalCopyright", "© 1998-2007 Virtools SA" + VALUE "LegalTrademarks", "© 1998-2007 Virtools" + VALUE "OriginalFilename", "Editor.DLL" + VALUE "ProductName", "Virtools" + VALUE "ProductVersion", "4.0.0.90" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_EDITORICON ICON "icon1.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_PBCOMMON, DIALOG + BEGIN + RIGHTMARGIN, 335 + VERTGUIDE, 170 + VERTGUIDE, 218 + VERTGUIDE, 288 + HORZGUIDE, 15 + HORZGUIDE, 40 + HORZGUIDE, 65 + END + + IDD_PBCOMMON_DEFORMABLE, DIALOG + BEGIN + RIGHTMARGIN, 159 + END +END +#endif // APSTUDIO_INVOKED + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE 9, 1 +#pragma code_page(1252) +#endif //_WIN32 +#include "afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/usr/Src/Interface/pBXMLSetup.cpp b/usr/Src/Interface/pBXMLSetup.cpp new file mode 100644 index 0000000..59b827f --- /dev/null +++ b/usr/Src/Interface/pBXMLSetup.cpp @@ -0,0 +1,143 @@ +#include +#include "PCommonDialog.h" +#include "PBodySetup.h" +#include "PBXMLSetup.h" + + +#include "resource.h" +#include "VITabCtrl.h" +#include "VIControl.h" +#include "..\..\include\interface\pbxmlsetup.h" + + +void CPBXMLSetup::fillXMLLinks() +{ + + XMLExternLink.AddString("None"); + XMLInternLink.AddString("None"); + + XMLExternLink.SetCurSel(0); + XMLInternLink.SetCurSel(0); + + +} + +int CPBXMLSetup::OnSelect(int before/* =-1 */) +{ + return -1; +} + + +BOOL CPBXMLSetup::OnInitDialog() +{ + + + fillXMLLinks(); + CDialog::OnInitDialog(); + /*getXMLSetup().SetMode(MultiParamEditDlg::MODELESSEDIT|MultiParamEditDlg::USER_CUSTOM_BUTTONS|MultiParamEditDlg::AUTOCLOSE_WHEN_MODELESS|MultiParamEditDlg::CREATEPARAM); + //getXMLSetup().AttachControlSite(this,IDC_MAIN_VIEW_XML); + + CRect rcValue; + GetWindowRect( &rcValue ); // Use picture box position. + ScreenToClient( &rcValue ); +*/ + return TRUE; +} + + + + + +CPBXMLSetup::~CPBXMLSetup(){ _destroy();} +void CPBXMLSetup::_destroy(){ ::CPSharedBase::_destroy();} + +CPBXMLSetup::CPBXMLSetup(CKParameter* Parameter,CK_CLASSID Cid) : +CParameterDialog(Parameter,Cid) , CPSharedBase(this,Parameter) +{ + setEditedParameter(Parameter); +} + +CPBXMLSetup::CPBXMLSetup(CKParameter* Parameter,CWnd *parent,CK_CLASSID Cid) : +CParameterDialog(Parameter,Cid) , CPSharedBase(this,Parameter) +{ + setEditedParameter(Parameter); +} + +void CPSharedBase::_dtrBodyXMLDlg(){} +CPBXMLSetup*CPBXMLSetup::refresh(CKParameter*src){ return this;} + + +HWND CPBXMLSetup::getDlgWindowHandle(UINT templateID) +{ + HWND result = NULL; + GetDlgItem(templateID,&result); + return result; +} +LRESULT CPBXMLSetup::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) +{ + switch (message) + { + + case WM_LBUTTONDOWN: + case WM_LBUTTONDBLCLK: + { + + break; + + } + case WM_ERASEBKGND: + { + /*RECT r; + GetClientRect(&r); + CDC* pDC=CDC::FromHandle((HDC)wParam); + pDC->FillSolidRect(&r,RGB(200,200,200)); + return 1;*/ + }break; + case CKWM_OK: + { + //CEdit *valueText = (CEdit*)GetDlgItem(IDC_EDIT); + /*CString l_strValue; + valueText->GetWindowText(l_strValue); + + double d; + if (sscanf(l_strValue,"%Lf",&d)) { + parameter->SetValue(&d); + }*/ + } break; + + case CKWM_INIT: + { + + RECT r; + GetClientRect(&r); + fillXMLLinks(); + + } break; + } + return CDialog::WindowProc(message, wParam, lParam); +} + + + +void CPBXMLSetup::DoDataExchange(CDataExchange* pDX) +{ + + //CDialog::DoDataExchange(pDX); + CParameterDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CPBXMLSetup) + DDX_Control(pDX, IDC_XINTERN_LINK2, XMLInternLink); + DDX_Control(pDX, IDC_XEXTERN_LINK, XMLExternLink); + //}}AFX_DATA_MAP + +} + +BEGIN_MESSAGE_MAP(CPBXMLSetup, CParameterDialog) + + ON_STN_CLICKED(IDC_XML_MAIN_VIEW, OnStnClickedXmlMainView) +END_MESSAGE_MAP() + + +void CPBXMLSetup::OnStnClickedXmlMainView() +{ + // TODO: Add your control notification handler code here +} diff --git a/usr/Src/Interface/pCommonMouseHandler.cpp b/usr/Src/Interface/pCommonMouseHandler.cpp new file mode 100644 index 0000000..f1d338f --- /dev/null +++ b/usr/Src/Interface/pCommonMouseHandler.cpp @@ -0,0 +1,81 @@ +//#include "StdAfx2.h" + +/* +#include + +#include "PCommonDialog.h" +#include "PBodySetup.h" +#include "PBXMLSetup.h" +*/ +/* + + + +void CPBParentDialog::OnTabChange(int last,int current) +{ + + //mTestViControl.SetActiveTab(current); + return; + CPSharedBase* lastDlg = (CPSharedBase*)getDialog(last); + if (lastDlg) + { + + switch(last) + { + case BTAB_XML: + { + CPBXMLSetup*xmlDlg=(CPBXMLSetup*)CPSharedBase::getInstance()->getDialog(BTAB_XML); + if (xmlDlg) + { + //xmlDlg->ShowWindow(SW_HIDE); + //xmlDlg->UpdateWindow(); + } + }break; + + case BTAB_COMMON: + { + CPBodyCfg*cfg=(CPBodyCfg*)CPSharedBase::getInstance()->getDialog(BTAB_COMMON); + if (cfg) + { + //cfg->ShowWindow(SW_HIDE); + //cfg->UpdateWindow(); + } + }break; + + } + } + + CPSharedBase* selectedDlg = (CPSharedBase*)getDialog(current); + if (selectedDlg) + { + + switch(current) + { + case BTAB_XML: + { + CPBXMLSetup*xmlDlg=(CPBXMLSetup*)CPSharedBase::getInstance()->getDialog(BTAB_XML); + if (xmlDlg) + { + //xmlDlg->ShowWindow(SW_SHOW); + //xmlDlg->UpdateWindow(); + //xmlDlg->OnSelect(last); + + } + }break; + + case BTAB_COMMON: + { + CPBodyCfg*cfg=(CPBodyCfg*)CPSharedBase::getInstance()->getDialog(BTAB_COMMON); + if (cfg) + { +// cfg->ShowWindow(SW_NORMAL); + //cfg->UpdateWindow(); + cfg->OnSelect(last); + } + }break; + } + + + } +} +*/ \ No newline at end of file diff --git a/usr/Src/Interface/res/Toolbar.bmp b/usr/Src/Interface/res/Toolbar.bmp new file mode 100644 index 0000000..bc42142 Binary files /dev/null and b/usr/Src/Interface/res/Toolbar.bmp differ diff --git a/usr/Src/Interface/res/Toolbar24.bmp b/usr/Src/Interface/res/Toolbar24.bmp new file mode 100644 index 0000000..25f4636 Binary files /dev/null and b/usr/Src/Interface/res/Toolbar24.bmp differ diff --git a/usr/Src/Interface/res/VisualStudioDemo.ico b/usr/Src/Interface/res/VisualStudioDemo.ico new file mode 100644 index 0000000..334f78c Binary files /dev/null and b/usr/Src/Interface/res/VisualStudioDemo.ico differ diff --git a/usr/Src/Interface/res/VisualStudioDemoDoc.ico b/usr/Src/Interface/res/VisualStudioDemoDoc.ico new file mode 100644 index 0000000..900968a Binary files /dev/null and b/usr/Src/Interface/res/VisualStudioDemoDoc.ico differ diff --git a/usr/Src/Interface/res/build.bmp b/usr/Src/Interface/res/build.bmp new file mode 100644 index 0000000..1505769 Binary files /dev/null and b/usr/Src/Interface/res/build.bmp differ diff --git a/usr/Src/Interface/res/build24.bmp b/usr/Src/Interface/res/build24.bmp new file mode 100644 index 0000000..ede06e0 Binary files /dev/null and b/usr/Src/Interface/res/build24.bmp differ diff --git a/usr/Src/Interface/res/check.bmp b/usr/Src/Interface/res/check.bmp new file mode 100644 index 0000000..33a3c58 Binary files /dev/null and b/usr/Src/Interface/res/check.bmp differ diff --git a/usr/Src/Interface/res/class_view.ico b/usr/Src/Interface/res/class_view.ico new file mode 100644 index 0000000..b356c43 Binary files /dev/null and b/usr/Src/Interface/res/class_view.ico differ diff --git a/usr/Src/Interface/res/class_view_hc.ico b/usr/Src/Interface/res/class_view_hc.ico new file mode 100644 index 0000000..1aca44e Binary files /dev/null and b/usr/Src/Interface/res/class_view_hc.ico differ diff --git a/usr/Src/Interface/res/classview.bmp b/usr/Src/Interface/res/classview.bmp new file mode 100644 index 0000000..1e02aa1 Binary files /dev/null and b/usr/Src/Interface/res/classview.bmp differ diff --git a/usr/Src/Interface/res/classview_hc.bmp b/usr/Src/Interface/res/classview_hc.bmp new file mode 100644 index 0000000..6b22e78 Binary files /dev/null and b/usr/Src/Interface/res/classview_hc.bmp differ diff --git a/usr/Src/Interface/res/cpp.ico b/usr/Src/Interface/res/cpp.ico new file mode 100644 index 0000000..e96760c Binary files /dev/null and b/usr/Src/Interface/res/cpp.ico differ diff --git a/usr/Src/Interface/res/current.bmp b/usr/Src/Interface/res/current.bmp new file mode 100644 index 0000000..77d744f Binary files /dev/null and b/usr/Src/Interface/res/current.bmp differ diff --git a/usr/Src/Interface/res/dynamich.bmp b/usr/Src/Interface/res/dynamich.bmp new file mode 100644 index 0000000..2d92010 Binary files /dev/null and b/usr/Src/Interface/res/dynamich.bmp differ diff --git a/usr/Src/Interface/res/dynamich24.bmp b/usr/Src/Interface/res/dynamich24.bmp new file mode 100644 index 0000000..39fad8c Binary files /dev/null and b/usr/Src/Interface/res/dynamich24.bmp differ diff --git a/usr/Src/Interface/res/dynamichelp.ico b/usr/Src/Interface/res/dynamichelp.ico new file mode 100644 index 0000000..ee14a37 Binary files /dev/null and b/usr/Src/Interface/res/dynamichelp.ico differ diff --git a/usr/Src/Interface/res/dynamichelp_hc.ico b/usr/Src/Interface/res/dynamichelp_hc.ico new file mode 100644 index 0000000..732ef39 Binary files /dev/null and b/usr/Src/Interface/res/dynamichelp_hc.ico differ diff --git a/usr/Src/Interface/res/edit.bmp b/usr/Src/Interface/res/edit.bmp new file mode 100644 index 0000000..69c17ec Binary files /dev/null and b/usr/Src/Interface/res/edit.bmp differ diff --git a/usr/Src/Interface/res/edit24.bmp b/usr/Src/Interface/res/edit24.bmp new file mode 100644 index 0000000..95b2067 Binary files /dev/null and b/usr/Src/Interface/res/edit24.bmp differ diff --git a/usr/Src/Interface/res/file_view.ico b/usr/Src/Interface/res/file_view.ico new file mode 100644 index 0000000..5b1e67d Binary files /dev/null and b/usr/Src/Interface/res/file_view.ico differ diff --git a/usr/Src/Interface/res/file_view_hc.ico b/usr/Src/Interface/res/file_view_hc.ico new file mode 100644 index 0000000..6bedaae Binary files /dev/null and b/usr/Src/Interface/res/file_view_hc.ico differ diff --git a/usr/Src/Interface/res/filevie24.bmp b/usr/Src/Interface/res/filevie24.bmp new file mode 100644 index 0000000..b60f483 Binary files /dev/null and b/usr/Src/Interface/res/filevie24.bmp differ diff --git a/usr/Src/Interface/res/fileview.bmp b/usr/Src/Interface/res/fileview.bmp new file mode 100644 index 0000000..a2d62d0 Binary files /dev/null and b/usr/Src/Interface/res/fileview.bmp differ diff --git a/usr/Src/Interface/res/help24.bmp b/usr/Src/Interface/res/help24.bmp new file mode 100644 index 0000000..a77a96f Binary files /dev/null and b/usr/Src/Interface/res/help24.bmp differ diff --git a/usr/Src/Interface/res/img_inte_hc.bmp b/usr/Src/Interface/res/img_inte_hc.bmp new file mode 100644 index 0000000..44a2544 Binary files /dev/null and b/usr/Src/Interface/res/img_inte_hc.bmp differ diff --git a/usr/Src/Interface/res/intellisense.bmp b/usr/Src/Interface/res/intellisense.bmp new file mode 100644 index 0000000..a071848 Binary files /dev/null and b/usr/Src/Interface/res/intellisense.bmp differ diff --git a/usr/Src/Interface/res/menuimages.bmp b/usr/Src/Interface/res/menuimages.bmp new file mode 100644 index 0000000..9d816cc Binary files /dev/null and b/usr/Src/Interface/res/menuimages.bmp differ diff --git a/usr/Src/Interface/res/menuimages24.bmp b/usr/Src/Interface/res/menuimages24.bmp new file mode 100644 index 0000000..04c3430 Binary files /dev/null and b/usr/Src/Interface/res/menuimages24.bmp differ diff --git a/usr/Src/Interface/res/optionsimages.bmp b/usr/Src/Interface/res/optionsimages.bmp new file mode 100644 index 0000000..1aa6b51 Binary files /dev/null and b/usr/Src/Interface/res/optionsimages.bmp differ diff --git a/usr/Src/Interface/res/output_bar.ico b/usr/Src/Interface/res/output_bar.ico new file mode 100644 index 0000000..93e437f Binary files /dev/null and b/usr/Src/Interface/res/output_bar.ico differ diff --git a/usr/Src/Interface/res/output_bar_hc.ico b/usr/Src/Interface/res/output_bar_hc.ico new file mode 100644 index 0000000..9c7b953 Binary files /dev/null and b/usr/Src/Interface/res/output_bar_hc.ico differ diff --git a/usr/Src/Interface/res/prop24.bmp b/usr/Src/Interface/res/prop24.bmp new file mode 100644 index 0000000..6e90ff4 Binary files /dev/null and b/usr/Src/Interface/res/prop24.bmp differ diff --git a/usr/Src/Interface/res/prop_bar_hc.ico b/usr/Src/Interface/res/prop_bar_hc.ico new file mode 100644 index 0000000..967463e Binary files /dev/null and b/usr/Src/Interface/res/prop_bar_hc.ico differ diff --git a/usr/Src/Interface/res/properti.bmp b/usr/Src/Interface/res/properti.bmp new file mode 100644 index 0000000..8bf6601 Binary files /dev/null and b/usr/Src/Interface/res/properti.bmp differ diff --git a/usr/Src/Interface/res/properti.ico b/usr/Src/Interface/res/properti.ico new file mode 100644 index 0000000..391b206 Binary files /dev/null and b/usr/Src/Interface/res/properti.ico differ diff --git a/usr/Src/Interface/res/res_view.ico b/usr/Src/Interface/res/res_view.ico new file mode 100644 index 0000000..c51369e Binary files /dev/null and b/usr/Src/Interface/res/res_view.ico differ diff --git a/usr/Src/Interface/res/res_view_hc.ico b/usr/Src/Interface/res/res_view_hc.ico new file mode 100644 index 0000000..d11fa5b Binary files /dev/null and b/usr/Src/Interface/res/res_view_hc.ico differ diff --git a/usr/Src/Interface/res/resource.bmp b/usr/Src/Interface/res/resource.bmp new file mode 100644 index 0000000..8b30401 Binary files /dev/null and b/usr/Src/Interface/res/resource.bmp differ diff --git a/usr/Src/Interface/res/resource24.bmp b/usr/Src/Interface/res/resource24.bmp new file mode 100644 index 0000000..251e14b Binary files /dev/null and b/usr/Src/Interface/res/resource24.bmp differ diff --git a/usr/Src/Interface/res/solution.bmp b/usr/Src/Interface/res/solution.bmp new file mode 100644 index 0000000..a4ef154 Binary files /dev/null and b/usr/Src/Interface/res/solution.bmp differ diff --git a/usr/Src/Interface/res/solution24.bmp b/usr/Src/Interface/res/solution24.bmp new file mode 100644 index 0000000..559214a Binary files /dev/null and b/usr/Src/Interface/res/solution24.bmp differ diff --git a/usr/Src/Interface/res/sort.bmp b/usr/Src/Interface/res/sort.bmp new file mode 100644 index 0000000..4e2155d Binary files /dev/null and b/usr/Src/Interface/res/sort.bmp differ diff --git a/usr/Src/Interface/res/sort24.bmp b/usr/Src/Interface/res/sort24.bmp new file mode 100644 index 0000000..5e1c377 Binary files /dev/null and b/usr/Src/Interface/res/sort24.bmp differ diff --git a/usr/Src/Interface/res/start.png b/usr/Src/Interface/res/start.png new file mode 100644 index 0000000..cb060ab Binary files /dev/null and b/usr/Src/Interface/res/start.png differ diff --git a/usr/Src/Interface/res/toolbar1.bmp b/usr/Src/Interface/res/toolbar1.bmp new file mode 100644 index 0000000..9327881 Binary files /dev/null and b/usr/Src/Interface/res/toolbar1.bmp differ diff --git a/usr/Src/Interface/res/toolbar_.bmp b/usr/Src/Interface/res/toolbar_.bmp new file mode 100644 index 0000000..d2e1d64 Binary files /dev/null and b/usr/Src/Interface/res/toolbar_.bmp differ diff --git a/usr/Src/Interface/res/watch_bar.ico b/usr/Src/Interface/res/watch_bar.ico new file mode 100644 index 0000000..df182a2 Binary files /dev/null and b/usr/Src/Interface/res/watch_bar.ico differ diff --git a/usr/Src/Interface/res/watch_bar_hc.ico b/usr/Src/Interface/res/watch_bar_hc.ico new file mode 100644 index 0000000..f8fe84e Binary files /dev/null and b/usr/Src/Interface/res/watch_bar_hc.ico differ diff --git a/usr/Src/Interface/res/workspc.bmp b/usr/Src/Interface/res/workspc.bmp new file mode 100644 index 0000000..9e9f456 Binary files /dev/null and b/usr/Src/Interface/res/workspc.bmp differ diff --git a/usr/Src/Interface/resource.h b/usr/Src/Interface/resource.h new file mode 100644 index 0000000..47cf2b7 --- /dev/null +++ b/usr/Src/Interface/resource.h @@ -0,0 +1,71 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by vtAgeiaInterface.rc +// +#define IDD_MYTABEXAMPLE_DIALOG 102 +#define IDR_MAINFRAME 128 +#define IDD_TAB_ONE 129 +#define IDD_TAB_TWO 130 +#define IDD_TAB_THREE 131 +#define IDC_PBODY_TAB_PANE 145 +#define IDC_TREE1 147 +#define IDC_MAIN_VIEW_XML 998 +#define IDC_PB_XML_TABS 9995 +#define IDD_PB_XML_PARENT 9999 +#define IDC_BFLAGS_MOVING 10001 +#define IDC_LBL_FLAGS 10002 +#define IDC_BFLAGS_DEFORMABLE 10003 +#define IDC_BFLAGS_GRAV 10004 +#define IDC_BFLAGS_KINEMATIC 10005 +#define IDC_LBL_DYNAFLAGS 10006 +#define IDC_BFLAGS_COLL_NOTIFY 10007 +#define IDD_BODYSHORTPANE 10007 +#define IDC_BFLAGS_TRIGGER 10008 +#define IDC_BFLAGS_SSHAPE 10009 +#define IDC_BFLAGS_HIERARCHY 10010 +#define IDD_EDITOR 10011 +#define IDC_LBL_LFLAGS 10011 +#define IDC_FLAGS_BG 10012 +#define IDI_EDITORICON 10013 +#define IDC_TLFLAGS_POS 10013 +#define IDC_TLFLAGS_ROT 10014 +#define IDC_HULLTYPE 10015 +#define IDC_HULLTYPE2 10016 +#define IDC_TLFLAGS_POS_X 10016 +#define IDC_TLFLAGS_POS_Y 10017 +#define IDC_TLFLAGS_POS_Z 10018 +#define IDC_TLFLAGS_ROT_Y 10019 +#define IDC_TLFLAGS_ROT_Z 10020 +#define IDC_BFLAGS_SLEEP 10021 +#define IDD_PBCOMMON 10022 +#define IDC_TLFLAGS_ROT_Y2 10022 +#define IDC_TLFLAGS_ROT_X 10022 +#define IDD_TOOLBAR 10023 +#define IDC_XML_MAIN_VIEW 10027 +#define IDC_EDIT1 10028 +#define IDC_DYNA_FLAGS_RECT 10029 +#define IDC_SPACER 10031 +#define IDC_BFLAGS_COLL 10306 +#define IDC_LBL_HTYPE 10890 +#define IDC_LBL_HTYPE2 10891 +#define IDD_PB_PARENT_DIALOG 30000 +#define IDC_PB_MAINTAB 30001 +#define IDD_PB_MAINTAB_DST 30002 +#define IDC_MAIN_VIEW 30004 +#define IDD_PB_COLLISION_PARENT 30008 +#define IDC_XEXTERN_LINK 30022 +#define IDC_XEXTERN_LINK_LBL 30030 +#define IDC_XINTERN_LINK2 30031 +#define IDC_XINTERN_LINK_LBL2 30032 +#define IDD_PBODY_TAB_PANE 30033 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 10008 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 10030 +#define _APS_NEXT_SYMED_VALUE 10000 +#endif +#endif diff --git a/usr/Src/Interface/resource.h2 b/usr/Src/Interface/resource.h2 new file mode 100644 index 0000000..880a612 --- /dev/null +++ b/usr/Src/Interface/resource.h2 @@ -0,0 +1,215 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by vtAgeiaInterface.rc +// +#define VS_VERSION_INFO1 2 +#define IDS_MAIN_TOOLBAR 101 +#define IDD_MYTABEXAMPLE_DIALOG 102 +#define IDS_STRING_NOT_FOUND_FMT 102 +#define IDS_BUILD_TOOLBAR 103 +#define IDS_RESOURCE_TOOLBAR 104 +#define IDS_EDIT_TOOLBAR 106 +#define IDS_EDITFAILED 121 +#define IDS_PGUPFAILED 122 +#define IDR_MAINFRAME 128 +#define IDD_TAB_ONE 129 +#define IDR_DEVTYPE0 129 +#define IDD_TAB_TWO 130 +#define IDR_DEVTYPE_CPP 130 +#define IDD_TAB_THREE 131 +#define IDC_PBODY_TAB_PANE 145 +#define IDC_TREE1 147 +#define IDD_PB_QUICK_OAGE 247 +#define IDC_MAIN_VIEW_XML 998 +#define IDC_PB_XML_TABS 9995 +#define IDD_PB_XML_PARENT 9999 +#define IDC_BFLAGS_MOVING 10001 +#define IDC_LBL_FLAGS 10002 +#define IDC_BFLAGS_DEFORMABLE 10003 +#define IDC_BFLAGS_GRAV 10004 +#define IDC_BFLAGS_KINEMATIC 10005 +#define IDC_BFLAGS_COLL_NOTIFY 10007 +#define IDC_BFLAGS_TRIGGER 10008 +#define IDC_BFLAGS_SSHAPE 10009 +#define IDD_BodyShortPane 10009 +#define IDC_BFLAGS_HIERARCHY 10010 +#define IDC_FLAGS_BG 10012 +#define IDC_HULLTYPE 10015 +#define IDC_HULLTYPE2 10016 +#define IDC_BFLAGS_SLEEP 10021 +#define IDD_PBCOMMON 10022 +#define IDC_XML_MAIN_VIEW 10027 +#define IDC_MAIN_TAB 10028 +#define IDC_SPACER 10031 +#define IDC_BFLAGS_COLL 10306 +#define IDC_LBL_HTYPE 10890 +#define IDC_LBL_HTYPE2 10891 +#define IDD_PB_PARENT_DIALOG 30000 +#define IDC_PB_MAINTAB 30001 +#define IDD_PB_MAINTAB_DST 30002 +#define IDC_MAIN_VIEW 30004 +#define IDD_PB_COLLISION_PARENT 30008 +#define IDC_XEXTERN_LINK 30022 +#define IDC_XEXTERN_LINK_LBL 30030 +#define IDC_XINTERN_LINK2 30031 +#define IDC_XINTERN_LINK_LBL2 30032 +#define IDD_PBODY_TAB_PANE 30033 +#define IDD_EDITOR 30035 +#define IDD_TOOLBAR 30036 +#define ID_VIEW_CUSTOMIZE 32770 +#define ID_VIEW_USER_TOOLBAR1 32771 +#define ID_VIEW_USER_TOOLBAR2 32772 +#define ID_VIEW_USER_TOOLBAR3 32773 +#define ID_VIEW_USER_TOOLBAR4 32774 +#define ID_VIEW_USER_TOOLBAR5 32775 +#define ID_VIEW_USER_TOOLBAR6 32776 +#define ID_VIEW_USER_TOOLBAR7 32777 +#define ID_VIEW_USER_TOOLBAR8 32778 +#define ID_VIEW_USER_TOOLBAR9 32779 +#define ID_VIEW_USER_TOOLBAR10 32780 +#define ID_VIEW_TOOLBARS 32781 +#define ID_VIEW_WORKSPACE 32782 +#define ID_VIEW_OUTPUT 32783 +#define ID_WINDOW_MANAGER 32784 +#define ID_VIEW_DYNAMICHELP 32785 +#define ID_DUMMY_COMPILE 32787 +#define ID_DUMMY_BUILD 32788 +#define ID_SORT_MENU 32789 +#define ID_DUMMY_STOP_BUILD 32789 +#define ID_DUMMY_EXECUTE 32790 +#define ID_DUMMY_GO 32791 +#define ID_DUMMY_SELECT_ACTIVE_CONFIGURATION 32794 +#define ID_DUMMY_REMOVE_ALL_BREAKPOINTS 32796 +#define ID_VIEW_BUILD_TOOLBAR 32797 +#define ID_DUMMY_REBUILD_ALL 32798 +#define ID_DUMMY_CLEAN 32799 +#define IDS_DUMMY_UNDO_ACTION 32800 +#define ID_VIEW_CB_CAPTION 32804 +#define ID_VIEW_FORCE_GRADIENT 32805 +#define ID_USER_TOOL1 32806 +#define ID_USER_TOOL2 32807 +#define ID_USER_TOOL3 32808 +#define ID_USER_TOOL4 32809 +#define ID_USER_TOOL5 32810 +#define ID_USER_TOOL6 32811 +#define ID_USER_TOOL7 32812 +#define ID_USER_TOOL8 32813 +#define ID_USER_TOOL9 32814 +#define ID_USER_TOOL10 32815 +#define ID_TOOLS_MACRO 32816 +#define ID_TOOLS_ENTRY 32819 +#define ID_NEW_DIALOG 32823 +#define ID_NEW_MENU 32824 +#define ID_NEW_CURSOR 32825 +#define ID_NEW_ICON 32826 +#define ID_NEW_BITMAP 32827 +#define ID_NEW_TOOLBAR 32828 +#define ID_NEW_ACCELERATOR 32829 +#define ID_NEW_STRING_TABLE 32830 +#define ID_NEW_VERSION 32831 +#define ID_OUTPUT_GOTO_ERROR 32833 +#define ID_CLASS_DEFINITION 32836 +#define ID_CLASS_ADD_MEMEBER_FUNCTION 32837 +#define ID_CLASS_ADD_MEMEBER_VARIABLE 32838 +#define ID_CLASS_PROPERTIES 32839 +#define ID_RESOURCE_OPEN 32840 +#define ID_RESOURCE_OPEN_BINARY 32841 +#define ID_DUMMY_INSERT_RESOURCE 32842 +#define ID_VIEW_TAB_FLAT_BORDERS 32844 +#define ID_HELP_KEYBOARDMAP 32845 +#define ID_MENU_DIR1 32847 +#define ID_MENU_DIR2 32848 +#define ID_MENU_DIR3 32849 +#define ID_MDITABS_ICONS 32850 +#define ID_MDITABS_TOP 32851 +#define ID_MDITABS_BOTTOM 32852 +#define ID_VIEW_MDI_TABS 32853 +#define ID_MDITABS_CLOSE 32855 +#define ID_VIEW_CLASS 32856 +#define ID_VIEW_RESOURCE 32857 +#define ID_VIEW_FILE 32858 +#define ID_MENU_ITEM1 32866 +#define ID_MENU_ITEM2 32867 +#define ID_MENU_ITEM3 32868 +#define ID_SORTING_GROUPBYTYPE 32869 +#define ID_SORTING_SORTALF 32870 +#define ID_SORTING_SORTBYTYPE 32871 +#define ID_SORTING_SORTBYACCESS 32872 +#define ID_DHELP1 32873 +#define ID_DHELP2 32874 +#define ID_DHELP3 32875 +#define ID_EXPAND 32878 +#define ID_SORTINGPROP 32879 +#define ID_PROPERIES1 32880 +#define ID_PROPERIES2 32881 +#define ID_NEW_FOLDER 32882 +#define ID_PROPERTIES 32883 +#define ID_SOLUTION_OPEN 32884 +#define ID_SOLUTION_OPEN_WITH 32885 +#define ID_FILE_NEW_PROJECT 32886 +#define ID_FILE_NEW_BLANK_SOLUTION 32887 +#define ID_FILE_OPEN_SOLUTION 32888 +#define ID_FILE_CLOSE_SOLUTION 32889 +#define ID_FILE_SAVE_ALL 32892 +#define ID_TOOLS_DEBUG_PROCESSES 32893 +#define ID_TOOLS_CONNECT_TO_DATABASE 32894 +#define ID_WINDOW_CLOSE_ALL 32895 +#define ID_HELP_SHOW_START 32896 +#define ID_VIEW_REFRESH 32897 +#define ID_VIEW_PROPERTIES 32900 +#define ID_VIEW_WATCH 32901 +#define ID_VIEW_FULLSCREEN 32902 +#define ID_EDIT_TOGGLEBOOKMARK 32925 +#define ID_EDIT_NEXTBOOKMARK 32926 +#define ID_EDIT_PREVIOUSBOOKMARK 32927 +#define ID_EDIT_TOGGLEBREAKPOINT 32928 +#define ID_EDIT_CLEAR_ALLBOOKMARKS 32930 +#define ID_EDIT_INCREASE_IDENT 32931 +#define ID_EDIT_DECREASE_IDENT 32932 +#define ID_VIEW_EDIT_TOOLBAR 32933 +#define ID_EDIT_LISTMEMBERS 32935 +#define IDS_UAT_UNDEFINED 32936 +#define IDS_UAT_TYPING 32937 +#define IDS_UAT_DELETE 32938 +#define IDS_UAT_INDENT 32939 +#define IDS_UAT_UNKNOWN 32940 +#define IDS_UAT_CUT 32941 +#define IDS_UAT_PASTE 32942 +#define IDS_UAT_BACKSPACE 32943 +#define IDS_UAT_UNINDENT 32944 +#define IDS_UAT_DRAGDROP 32945 +#define IDS_UAT_TAB 32946 +#define IDS_UAT_ENTER 32947 +#define ID_EDIT_FIND_COMBO 32948 +#define ID_TOOLS_OPTIONS 32949 +#define ID_VIEW_APP_LOOK 32950 +#define ID_HELP_WEB 32951 +#define ID_EDIT_HIDESELECTION 32952 +#define ID_EDIT_TOGGLEOUTLINING 32953 +#define ID_EDIT_STOPHIDINGCURRENT 32954 +#define ID_EDIT_TOGGLEALLOUTLINING 32955 +#define ID_EDIT_COLLAPSETODEFINITIONS 32956 +#define ID_EDIT_STOPOUTLINING 32957 +#define ID_EDIT_AUTOOUTLINING 32958 +#define ID_EDIT_ENABLEOUTLINING 32959 +#define ID_EDIT_NEXT_WORD 32960 +#define ID_EDIT_LINENUMBERS 32961 +#define IDS_UAT_REPLACE 32962 +#define ID_EDIT_GOTO_LINE 32963 +#define ID_MDI_NEW_VERT_GROUP 32965 +#define ID_MDI_NEW_HORZ_TAB_GROUP 32966 +#define ID_MDI_MOVE_TO_PREV_GROUP 32967 +#define ID_MDI_CANCEL 32968 +#define ID_MDI_MOVE_TO_NEXT_GROUP 32969 +#define ID_MDI_TABBED_DOCUMENT 32974 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 10010 +#define _APS_NEXT_COMMAND_VALUE 32771 +#define _APS_NEXT_CONTROL_VALUE 10035 +#define _APS_NEXT_SYMED_VALUE 10000 +#endif +#endif diff --git a/usr/Src/Interface/targetver.h b/usr/Src/Interface/targetver.h new file mode 100644 index 0000000..27867ba --- /dev/null +++ b/usr/Src/Interface/targetver.h @@ -0,0 +1,26 @@ + +#pragma once + +// The following macros define the minimum required platform. The minimum required platform +// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run +// your application. The macros work by enabling all features available on platform versions up to and +// including the version specified. + +// Modify the following defines if you have to target a platform prior to the ones specified below. +// Refer to MSDN for the latest info on corresponding values for different platforms. +#ifndef WINVER // Specifies that the minimum required platform is Windows Vista. +#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. +#endif + +#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. +#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. +#endif + +#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98. +#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. +#endif + +#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. +#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE. +#endif + diff --git a/usr/Src/Interface/template/PBXMLSetup.h b/usr/Src/Interface/template/PBXMLSetup.h new file mode 100644 index 0000000..8b69553 --- /dev/null +++ b/usr/Src/Interface/template/PBXMLSetup.h @@ -0,0 +1,133 @@ +#pragma once + +#include "StdAfx2.h" +#include "VIControls.h" +#include "ParameterDialog.h" +#include "CKShader.h" +#include "ParameterDialog.h" +#include "MultiParamEditDlg.h" + +//#include "CUIKNotificationReceiver.h" + +//--- Include "GenericObjectParameterDialog.h" from CK2UI define IDDs to mak it compile +#define IDD_GENOBJECTDIALOG 2011 +#define IDD_BASEPARAMDIALOG 2000 +#include "Parameters\GenericObjectParameterDialog.h" + +#include "resource.h" + + + +#include "PCommonDialog.h" + + +//--- Some constants +#define MFC_NAME_OF_DIALOG "#32770" +#define CHECK_MATERIAL_TIMER 57 + +class CPBXMLSetup : public MultiParamEditDlg , public CPSharedBase +{ + +public: + + // virtual void PreSubclassWindow(); + + int m_paramType; + + CPBXMLSetup(CKContext* context,CWnd* parent = NULL); + CPBXMLSetup(CKParameter* Parameter,CK_CLASSID Cid=CKCID_OBJECT); + virtual ~CPBXMLSetup(); + void _destroy(); + + //virtual BOOL Create(UINT nIDTemplate, CWnd* pParentWnd); + virtual void Init(CParameterDialog *parent); + + CParameterDialog* refresh(CKParameter*src); + /************************************************************************/ + /* Overrides + */ + /************************************************************************/ + void OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); + LRESULT OnRegisteredMouseWheel(WPARAM wParam, LPARAM lParam); + + + /************************************************************************/ + /* Accessors */ + /************************************************************************/ + CKParameter * getEditedParameter() const { return mParameter; } + void setEditedParameter(CKParameter * val) { mParameter= val; } + + + + /************************************************************************/ + /* Virtools mParameter transfer callbacks : */ + /************************************************************************/ + virtual BOOL On_UpdateFromParameter(CKParameter* p){ + + // if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); + // if(!p) return FALSE; + + return TRUE; + } + + virtual BOOL On_UpdateToParameter(CKParameter* p) + { + + /* + if(!p) p = (CKParameterOut *)CKGetObject(m_EditedParameter); + if(!p) return FALSE; + CString cstr;*/ + return TRUE; + + } + + + + // associated resource id : + enum { IDD = IDD_PBCOMMON_DEFORMABLE }; + + + + /************************************************************************/ + /* MFC */ + /************************************************************************/ + //{{AFX_VIRTUAL(CPBXMLSetup) +protected: + virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support + //}}AFX_VIRTUAL + + + //{{AFX_MSG(CPBXMLSetup) + //ON_REGISTERED_MESSAGE(_afxMsgMouseWheel, OnRegisteredMouseWheel); + //afx_msg void OnMouseMove(UINT nFlags, CPoint point); + //afx_msg void OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); + + //}}AFX_MSG + +public: + + + /************************************************************************/ + /* Low Level passes */ + /************************************************************************/ + LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); + + + + /************************************************************************/ + /* Members */ + /************************************************************************/ + + +public: + + + CKParameter *mParameter; + VIEdit editValue; + VIStaticText textValue; + VIComboBox type; + + DECLARE_MESSAGE_MAP() + + +}; diff --git a/usr/Src/Interface/template/pBXMLSetup.cpp b/usr/Src/Interface/template/pBXMLSetup.cpp new file mode 100644 index 0000000..f8db485 --- /dev/null +++ b/usr/Src/Interface/template/pBXMLSetup.cpp @@ -0,0 +1,96 @@ +#include "PCommonDialog.h" +#include "PBodySetup.h" +#include "PBXMLSetup.h" +#include "resource.h" +#include "VITabCtrl.h" + +#include "VIControl.h" + + +#define LAYOUT_STYLE (WS_CHILD|WS_VISIBLE) +#define LAYOUT_ShaderREE 130 + +/* +MultiParamEditDlg* CPBXMLSetup::refresh(CKParameter*src) +{ return this; } +*/ +void CPBXMLSetup::Init(CParameterDialog *parent){} +CPBXMLSetup::~CPBXMLSetup(){ _destroy();} +void CPBXMLSetup::_destroy(){ ::CPSharedBase::_destroy();} + +/* +CPBXMLSetup::CPBXMLSetup( + CKParameter* Parameter, + CK_CLASSID Cid) : +CParameterDialog(Parameter,Cid) , +CPSharedBase(this,Parameter) +{ + + setEditedParameter(Parameter); +} +*/ + + +LRESULT CPBXMLSetup::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) +{ + switch (message) + { + + case WM_LBUTTONDOWN: + case WM_LBUTTONDBLCLK: + { + + break; + + } + case WM_ERASEBKGND: + { + /*RECT r; + GetClientRect(&r); + CDC* pDC=CDC::FromHandle((HDC)wParam); + pDC->FillSolidRect(&r,RGB(200,200,200)); + return 1;*/ + }break; + case CKWM_OK: + { + //CEdit *valueText = (CEdit*)GetDlgItem(IDC_EDIT); + /*CString l_strValue; + valueText->GetWindowText(l_strValue); + + double d; + if (sscanf(l_strValue,"%Lf",&d)) { + parameter->SetValue(&d); + }*/ + } break; + + case CKWM_INIT: + { + + RECT r; + GetClientRect(&r); + /* + CDC* pDC=CDC::FromHandle((HDC)wParam);*/ + //initSplitter(); + char temp[64]; + double d; + } break; + } + return CDialog::WindowProc(message, wParam, lParam); +} + +void CPBXMLSetup::DoDataExchange(CDataExchange* pDX) +{ + + //CDialog::DoDataExchange(pDX); + CParameterDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CPBXMLSetup) + + //}}AFX_DATA_MAP + +} + + + +BEGIN_MESSAGE_MAP(CPBXMLSetup, CParameterDialog) +END_MESSAGE_MAP() + diff --git a/usr/Src/Interface/vtAgeiaInterface.aps b/usr/Src/Interface/vtAgeiaInterface.aps new file mode 100644 index 0000000..d8adcb3 Binary files /dev/null and b/usr/Src/Interface/vtAgeiaInterface.aps differ diff --git a/usr/Src/Interface/vtAgeiaInterface.def b/usr/Src/Interface/vtAgeiaInterface.def new file mode 100644 index 0000000..09ecd91 --- /dev/null +++ b/usr/Src/Interface/vtAgeiaInterface.def @@ -0,0 +1,8 @@ +; Editor.def : Declares the module parameters for the DLL. + +LIBRARY "vtAgeiaInterface" +; DESCRIPTION 'vtAgeiaInterface Windows Dynamic Link Library' + +EXPORTS + GetVirtoolsPluginInfoCount + GetVirtoolsPluginInfo diff --git a/usr/Src/Interface/vtAgeiaInterface.rc b/usr/Src/Interface/vtAgeiaInterface.rc new file mode 100644 index 0000000..59a627e --- /dev/null +++ b/usr/Src/Interface/vtAgeiaInterface.rc @@ -0,0 +1,304 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_BODYSHORTPANE DIALOGEX 0, 0, 316, 185 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +EXSTYLE WS_EX_CONTROLPARENT +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LTEXT "Static",IDC_STATIC,33,31,238,131,WS_BORDER +END + +IDD_PBODY_TAB_PANE DIALOGEX 0, 0, 266, 198 +STYLE DS_SETFONT | WS_CHILD | WS_VISIBLE +FONT 8, "MS Sans Serif", 0, 0, 0x1 +BEGIN + CONTROL "MainTab",IDC_PBODY_TAB_PANE,"SysTabControl32",0x0,7,7, + 252,163 + PUSHBUTTON "OK",IDOK,74,178,50,14 + PUSHBUTTON "Cancel",IDCANCEL,142,178,50,14 +END + +IDD_PB_MAINTAB_DST DIALOGEX 0, 0, 432, 338 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS +FONT 7, "Tahoma", 400, 0, 0x0 +BEGIN +END + +IDD_PBCOMMON DIALOGEX 0, 0, 342, 70 +STYLE DS_SETFONT | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS +FONT 7, "Tahoma", 400, 0, 0x0 +BEGIN + COMBOBOX IDC_HULLTYPE,40,3,67,70,CBS_DROPDOWNLIST | + CBS_OWNERDRAWVARIABLE | CBS_HASSTRINGS | WS_VSCROLL | + WS_TABSTOP + LTEXT "Hull Type",IDC_LBL_HTYPE,7,5,32,9 + CONTROL "Moving",IDC_BFLAGS_MOVING,"Button",BS_AUTOCHECKBOX,7,29, + 36,10,WS_EX_TRANSPARENT + CONTROL "Deformable",IDC_BFLAGS_DEFORMABLE,"Button", + BS_AUTOCHECKBOX,7,48,47,9,WS_EX_TRANSPARENT + CONTROL "Gravity",IDC_BFLAGS_GRAV,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,60,47,35,10,WS_EX_TRANSPARENT + CONTROL "Kinematic",IDC_BFLAGS_KINEMATIC,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,122,57,48,10, + WS_EX_TRANSPARENT + CONTROL "Collision",IDC_BFLAGS_COLL,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,60,29,37,10,WS_EX_TRANSPARENT + CONTROL "Collision Notify",IDC_BFLAGS_COLL_NOTIFY,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,60,38,57,11, + WS_EX_TRANSPARENT + CONTROL "Trigger Shape",IDC_BFLAGS_TRIGGER,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,122,29,55,9, + WS_EX_TRANSPARENT + CONTROL "Sub Shape",IDC_BFLAGS_SSHAPE,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,122,38,46,10,WS_EX_TRANSPARENT + CONTROL "Hierarchy",IDC_BFLAGS_HIERARCHY,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,7,38,45,11, + WS_EX_TRANSPARENT + CONTROL "Sleep",IDC_BFLAGS_SLEEP,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,122,46,44,13,WS_EX_TRANSPARENT + LTEXT "Static Flags",IDC_LBL_FLAGS,7,19,45,10,0, + WS_EX_TRANSPARENT + LTEXT "",IDC_DYNA_FLAGS_RECT,138,3,94,11,WS_BORDER, + WS_EX_TRANSPARENT + LTEXT "Dynamic Flags",IDC_LBL_DYNAFLAGS,60,19,45,10,0, + WS_EX_TRANSPARENT + LTEXT "Lock Transformation",IDC_LBL_LFLAGS,187,19,93,10,0, + WS_EX_TRANSPARENT + CONTROL "Position",IDC_TLFLAGS_POS,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,188,29,60,10,WS_EX_TRANSPARENT + CONTROL "Rotation",IDC_TLFLAGS_ROT,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,188,50,38,9,WS_EX_TRANSPARENT + CONTROL "X",IDC_TLFLAGS_POS_X,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,197,39,18,10,WS_EX_TRANSPARENT + CONTROL "Y",IDC_TLFLAGS_POS_Y,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,215,39,18,10,WS_EX_TRANSPARENT + CONTROL "Z",IDC_TLFLAGS_POS_Z,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,234,39,18,10,WS_EX_TRANSPARENT + CONTROL "Y",IDC_TLFLAGS_ROT_Y,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,215,59,18,9,WS_EX_TRANSPARENT + CONTROL "Z",IDC_TLFLAGS_ROT_Z,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,234,59,18,9,WS_EX_TRANSPARENT + CONTROL "X",IDC_TLFLAGS_ROT_X,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,198,59,18,9,WS_EX_TRANSPARENT +END + +IDD_PB_COLLISION_PARENT DIALOGEX 0, 0, 448, 359 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS +EXSTYLE WS_EX_CONTROLPARENT +FONT 7, "Tahoma", 400, 0, 0x0 +BEGIN +END + +IDD_PB_XML_PARENT DIALOGEX 0, 0, 360, 199 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_BORDER +EXSTYLE WS_EX_CONTROLPARENT +FONT 8, "Tahoma", 400, 0, 0x0 +BEGIN + COMBOBOX IDC_XEXTERN_LINK,95,4,90,70,CBS_DROPDOWNLIST | + CBS_OWNERDRAWVARIABLE | CBS_HASSTRINGS | WS_VSCROLL | + WS_GROUP | WS_TABSTOP + LTEXT "XML Link Extern Format",IDC_XEXTERN_LINK_LBL,6,7,88,11 + COMBOBOX IDC_XINTERN_LINK2,95,22,90,70,CBS_DROPDOWNLIST | + CBS_OWNERDRAWVARIABLE | CBS_HASSTRINGS | WS_VSCROLL | + WS_GROUP | WS_TABSTOP + LTEXT "XML Link Intern Format",IDC_XINTERN_LINK_LBL2,7,26,85, + 11 + CONTROL "Moving",IDC_BFLAGS_MOVING,"Button",BS_AUTOCHECKBOX | + WS_GROUP | WS_TABSTOP,198,4,80,10,WS_EX_TRANSPARENT + CONTROL "Gravity",IDC_BFLAGS_GRAV,"Button",BS_AUTOCHECKBOX | + WS_GROUP | WS_TABSTOP,198,17,80,10,WS_EX_TRANSPARENT + CONTROL "Kinematic",IDC_BFLAGS_KINEMATIC,"Button", + BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,198,30,80,10, + WS_EX_TRANSPARENT + CONTROL "Hierarchy",IDC_BFLAGS_HIERARCHY,"Button",BS_AUTO3STATE | + WS_GROUP | WS_TABSTOP,198,43,80,10,WS_EX_TRANSPARENT +END + +IDC_MAIN_VIEW DIALOGEX 0, 0, 355, 192 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS +EXSTYLE WS_EX_TRANSPARENT | WS_EX_CONTROLPARENT | WS_EX_NOINHERITLAYOUT +FONT 8, "MS Sans Serif", 0, 0, 0x1 +BEGIN + CONTROL "MainTab",IDC_PBODY_TAB_PANE,"SysTabControl32", + TCS_MULTILINE | TCS_RAGGEDRIGHT,30,15,286,30 + CONTROL "",IDC_SPACER,"Static",SS_BLACKRECT | SS_REALSIZEIMAGE, + 30,48,286,108 +END + +IDD_PB_PARENT_DIALOG DIALOGEX 0, 0, 524, 371 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD +FONT 7, "Tahoma", 400, 0, 0x0 +BEGIN + CONTROL "MainTab",IDC_PB_MAINTAB,"SysTabControl32", + TCS_FOCUSNEVER,7,3,424,16 + LTEXT "StaticPlaceHolder",IDC_MAIN_VIEW,62,34,297,94,NOT + WS_VISIBLE | WS_TABSTOP + LTEXT "XML",IDC_MAIN_VIEW_XML,64,202,319,124,NOT WS_VISIBLE | + WS_TABSTOP +END + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 9, 1\r\n" + "#pragma code_page(1252)\r\n" + "#endif //_WIN32\r\n" + "#include ""afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 4,0,0,90 + PRODUCTVERSION 4,0,0,90 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "CompanyName", "Virtools SA" + VALUE "FileDescription", "Editor DLL" + VALUE "FileVersion", "4.0.0.90" + VALUE "InternalName", "Editor" + VALUE "LegalCopyright", "© 1998-2007 Virtools SA" + VALUE "LegalTrademarks", "© 1998-2007 Virtools" + VALUE "OriginalFilename", "Editor.DLL" + VALUE "ProductName", "Virtools" + VALUE "ProductVersion", "4.0.0.90" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_EDITORICON ICON "icon1.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_PBCOMMON, DIALOG + BEGIN + VERTGUIDE, 7 + VERTGUIDE, 60 + VERTGUIDE, 138 + BOTTOMMARGIN, 68 + HORZGUIDE, 14 + HORZGUIDE, 29 + END + + IDD_PB_XML_PARENT, DIALOG + BEGIN + VERTGUIDE, 198 + VERTGUIDE, 278 + END +END +#endif // APSTUDIO_INVOKED + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE 9, 1 +#pragma code_page(1252) +#endif //_WIN32 +#include "afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/usr/Src/Interface/vtAgeiaInterface.rc2_ b/usr/Src/Interface/vtAgeiaInterface.rc2_ new file mode 100644 index 0000000..5f74c76 --- /dev/null +++ b/usr/Src/Interface/vtAgeiaInterface.rc2_ @@ -0,0 +1,679 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// German (Germany) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) +#ifdef _WIN32 +LANGUAGE LANG_GERMAN, SUBLANG_GERMAN +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_BodyShortPane DIALOGEX 0, 0, 316, 185 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +EXSTYLE WS_EX_CONTROLPARENT +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LTEXT "Static",IDC_STATIC,6,7,303,171 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_BodyShortPane, DIALOG + BEGIN + LEFTMARGIN, 6 + RIGHTMARGIN, 309 + TOPMARGIN, 7 + BOTTOMMARGIN, 178 + END +END +#endif // APSTUDIO_INVOKED + +#endif // German (Germany) resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDC_MAIN_VIEW DIALOGEX 0, 0, 355, 192 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS +EXSTYLE WS_EX_TRANSPARENT | WS_EX_CONTROLPARENT | WS_EX_NOINHERITLAYOUT +FONT 8, "MS Sans Serif", 0, 0, 0x1 +BEGIN + CONTROL "MainTab",IDC_PBODY_TAB_PANE,"SysTabControl32", + TCS_BOTTOM | TCS_RAGGEDRIGHT | WS_TABSTOP,33,39,226,30 + CONTROL "",IDC_SPACER,"Static",SS_BLACKRECT | SS_NOTIFY | + SS_REALSIZEIMAGE | WS_BORDER,32,116,189,62, + WS_EX_DLGMODALFRAME | WS_EX_TRANSPARENT +END + +IDD_PB_MAINTAB_DST DIALOGEX 0, 0, 432, 338 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS +FONT 7, "Tahoma", 400, 0, 0x0 +BEGIN +END + +IDD_PBCOMMON DIALOGEX 0, 0, 276, 123 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | DS_CENTER | WS_CHILD | + WS_VISIBLE +EXSTYLE WS_EX_TRANSPARENT +FONT 7, "MS Shell Dlg", 400, 0, 0x0 +BEGIN + COMBOBOX IDC_HULLTYPE,5,65,67,70,CBS_DROPDOWNLIST | + CBS_OWNERDRAWVARIABLE | CBS_HASSTRINGS | WS_VSCROLL | + WS_TABSTOP + LTEXT "UserLevel",IDC_LBL_HTYPE,14,38,38,11 + CONTROL "Moving",IDC_BFLAGS_MOVING,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,86,14,40,10,WS_EX_TRANSPARENT + CONTROL "Deformable",IDC_BFLAGS_DEFORMABLE,"Button", + BS_AUTOCHECKBOX,204,14,58,9,WS_EX_TRANSPARENT + CONTROL "Gravity",IDC_BFLAGS_GRAV,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,86,26,42,13,WS_EX_TRANSPARENT + CONTROL "Kinematic",IDC_BFLAGS_KINEMATIC,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,86,39,48,13, + WS_EX_TRANSPARENT + CONTROL "Collision",IDC_BFLAGS_COLL,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,134,14,44,10,WS_EX_TRANSPARENT + CONTROL "Collision Notify",IDC_BFLAGS_COLL_NOTIFY,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,134,26,65,13, + WS_EX_TRANSPARENT + CONTROL "Trigger Shape",IDC_BFLAGS_TRIGGER,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,134,39,61,13, + WS_EX_TRANSPARENT + CONTROL "Sub Shape",IDC_BFLAGS_SSHAPE,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,134,54,52,13,WS_EX_TRANSPARENT + CONTROL "Hierarchy",IDC_BFLAGS_HIERARCHY,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,86,54,50,13, + WS_EX_TRANSPARENT + CONTROL "Sleep",IDC_BFLAGS_SLEEP,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,204,51,44,13,WS_EX_TRANSPARENT + CONTROL "",IDC_FLAGS_BG,"Static",SS_BLACKFRAME | WS_TABSTOP,88, + 73,175,42 + LTEXT "Flags",IDC_LBL_FLAGS,79,0,42,11,0,WS_EX_TRANSPARENT + COMBOBOX IDC_HULLTYPE2,5,95,67,70,CBS_DROPDOWNLIST | + CBS_OWNERDRAWVARIABLE | CBS_HASSTRINGS | WS_VSCROLL | + WS_TABSTOP + LTEXT "Hull Type",IDC_LBL_HTYPE2,10,12,38,11 +END + +IDD_PB_COLLISION_PARENT DIALOGEX 0, 0, 448, 359 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS +EXSTYLE WS_EX_CONTROLPARENT +FONT 7, "Tahoma", 400, 0, 0x0 +BEGIN +END + +IDD_PB_XML_PARENT DIALOGEX 0, 0, 360, 199 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_BORDER +EXSTYLE WS_EX_CONTROLPARENT +FONT 8, "Tahoma", 400, 0, 0x0 +BEGIN + COMBOBOX IDC_XEXTERN_LINK,95,4,90,70,CBS_DROPDOWNLIST | + CBS_OWNERDRAWVARIABLE | CBS_HASSTRINGS | WS_VSCROLL | + WS_GROUP | WS_TABSTOP + LTEXT "XML Link Extern Format",IDC_XEXTERN_LINK_LBL,6,7,88,11 + COMBOBOX IDC_XINTERN_LINK2,95,22,90,70,CBS_DROPDOWNLIST | + CBS_OWNERDRAWVARIABLE | CBS_HASSTRINGS | WS_VSCROLL | + WS_GROUP | WS_TABSTOP + LTEXT "XML Link Intern Format",IDC_XINTERN_LINK_LBL2,7,26,85, + 11 + CONTROL "Moving",IDC_BFLAGS_MOVING,"Button",BS_AUTOCHECKBOX | + WS_GROUP | WS_TABSTOP,198,4,80,10,WS_EX_TRANSPARENT + CONTROL "Gravity",IDC_BFLAGS_GRAV,"Button",BS_AUTOCHECKBOX | + WS_GROUP | WS_TABSTOP,198,17,80,10,WS_EX_TRANSPARENT + CONTROL "Kinematic",IDC_BFLAGS_KINEMATIC,"Button", + BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,198,30,80,10, + WS_EX_TRANSPARENT + CONTROL "Hierarchy",IDC_BFLAGS_HIERARCHY,"Button",BS_AUTO3STATE | + WS_GROUP | WS_TABSTOP,198,43,80,10,WS_EX_TRANSPARENT +END + +IDD_PB_PARENT_DIALOG DIALOGEX 0, 0, 477, 269 +STYLE DS_SETFONT | DS_CONTROL | WS_CHILD +EXSTYLE WS_EX_CONTROLPARENT +FONT 7, "Tahoma", 400, 0, 0x0 +BEGIN + CONTROL "MainTab",IDC_PB_MAINTAB,"SysTabControl32", + TCS_FOCUSNEVER,13,9,424,16 + LTEXT "StaticPlaceHolder",IDC_MAIN_VIEW,140,84,297,94, + WS_TABSTOP + LTEXT "XML",IDC_MAIN_VIEW_XML,16,127,319,124,WS_TABSTOP +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDC_MAIN_VIEW, DIALOG + BEGIN + RIGHTMARGIN, 329 + END + + IDD_PB_XML_PARENT, DIALOG + BEGIN + VERTGUIDE, 198 + VERTGUIDE, 278 + END +END +#endif // APSTUDIO_INVOKED + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#define _AFX_NO_SPLITTER_RESOURCES\r\n" + "#define _AFX_NO_OLE_RESOURCES\r\n" + "#define _AFX_NO_TRACKER_RESOURCES\r\n" + "#define _AFX_NO_PROPERTY_RESOURCES\r\n" + "\r\n" + "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" + "#ifdef _WIN32\r\n" + "LANGUAGE 9, 1\r\n" + "#pragma code_page(1252)\r\n" + "#endif //_WIN32\r\n" + "#include ""afxres.rc"" // Standard components\r\n" + "#endif\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 4,0,0,90 + PRODUCTVERSION 4,0,0,90 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "CompanyName", "Virtools SA" + VALUE "FileDescription", "Editor DLL" + VALUE "FileVersion", "4.0.0.90" + VALUE "InternalName", "Editor" + VALUE "LegalCopyright", "© 1998-2007 Virtools SA" + VALUE "LegalTrademarks", "© 1998-2007 Virtools" + VALUE "OriginalFilename", "Editor.DLL" + VALUE "ProductName", "Virtools" + VALUE "ProductVersion", "4.0.0.90" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +VS_VERSION_INFO1 VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "FileDescription", "VisualStudioDemo MFC Application" + VALUE "FileVersion", "1, 0, 0, 1" + VALUE "InternalName", "VisualStudioDemo" + VALUE "LegalCopyright", "Copyright (C) 2001" + VALUE "OriginalFilename", "VisualStudioDemo.EXE" + VALUE "ProductName", "VisualStudioDemo Application" + VALUE "ProductVersion", "1, 0, 0, 1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDR_MAINFRAME "VisualStudioDemo" + IDR_DEVTYPE0 "\n\n\n\n\nVisualStudioDemo.Document\nVisualStudioDemo Document" + IDR_DEVTYPE_CPP "\nC++ example - \nC++ File\nC++ Files (.cpp)\n.cpp\nVisualStudioDemo.Document\nVisualStudioDemo Document" +END + +STRINGTABLE +BEGIN + IDS_MAIN_TOOLBAR "Standard" + IDS_STRING_NOT_FOUND_FMT "Cannot find the string ""%s""" + IDS_BUILD_TOOLBAR "Build" + IDS_RESOURCE_TOOLBAR "Resource" + IDS_EDIT_TOOLBAR "Edit" +END + +STRINGTABLE +BEGIN + AFX_IDS_APP_TITLE "VisualStudioDemo" + AFX_IDS_IDLEMESSAGE "Ready" +END + +STRINGTABLE +BEGIN + ID_INDICATOR_EXT "EXT" + ID_INDICATOR_CAPS "CAP" + ID_INDICATOR_NUM "NUM" + ID_INDICATOR_SCRL "SCRL" + ID_INDICATOR_OVR "OVR" + ID_INDICATOR_REC "REC" +END + +STRINGTABLE +BEGIN + ID_FILE_NEW "Creates a new document\nNew" + ID_FILE_OPEN "Opens an existing document\nOpen" + ID_FILE_CLOSE "Closes the active document\nClose" + ID_FILE_SAVE "Saves the active document\nSave" + ID_FILE_SAVE_AS "Saves the active document with a new name\nSave As" + ID_FILE_PAGE_SETUP "Changes the printing options\nPage Setup" + ID_FILE_PRINT_SETUP "Changes the printer and printing options\nPrint Setup" + ID_FILE_PRINT "Prints the active document\nPrint" + ID_FILE_PRINT_PREVIEW "Displays full pages\nPrint Preview" +END + +STRINGTABLE +BEGIN + ID_APP_ABOUT "Displays program information, version number and copyright\nAbout" + ID_APP_EXIT "Quits the application; prompts to save documents\nExit" +END + +STRINGTABLE +BEGIN + ID_FILE_MRU_FILE1 "Opens this document" + ID_FILE_MRU_FILE2 "Opens this document" + ID_FILE_MRU_FILE3 "Opens this document" + ID_FILE_MRU_FILE4 "Opens this document" + ID_FILE_MRU_FILE5 "Opens this document" + ID_FILE_MRU_FILE6 "Opens this document" + ID_FILE_MRU_FILE7 "Opens this document" + ID_FILE_MRU_FILE8 "Opens this document" + ID_FILE_MRU_FILE9 "Opens this document" + ID_FILE_MRU_FILE10 "Opens this document" + ID_FILE_MRU_FILE11 "Opens this document" + ID_FILE_MRU_FILE12 "Opens this document" + ID_FILE_MRU_FILE13 "Opens this document" + ID_FILE_MRU_FILE14 "Opens this document" + ID_FILE_MRU_FILE15 "Opens this document" + ID_FILE_MRU_FILE16 "Opens this document" +END + +STRINGTABLE +BEGIN + ID_NEXT_PANE "Switches to the next window pane\nNext Pane" + ID_PREV_PANE "Switches back to the previous window pane\nPrevious Pane" +END + +STRINGTABLE +BEGIN + ID_WINDOW_NEW "Opens another window for the active document\nNew Window" + ID_WINDOW_ARRANGE "Arranges icons at the bottom of the window\nArrange Icons" + ID_WINDOW_CASCADE "Arranges windows so they overlap\nCascade Windows" + ID_WINDOW_TILE_HORZ "Arranges windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_TILE_VERT "Arranges windows as non-overlapping tiles\nTile Windows" + ID_WINDOW_SPLIT "Splits the active window into panes\nSplit" +END + +STRINGTABLE +BEGIN + ID_EDIT_CLEAR "Erases the selection\nErase" + ID_EDIT_CLEAR_ALL "Erases everything\nErase All" + ID_EDIT_COPY "Copies the selection and puts it on the Clipboard\nCopy" + ID_EDIT_CUT "Cuts the selection and puts it on the Clipboard\nCut" + ID_EDIT_FIND "Finds the specified text\nFind" + ID_EDIT_PASTE "Inserts Clipboard contents\nPaste" + ID_EDIT_REPEAT "Repeats the last action\nRepeat" + ID_EDIT_REPLACE "Replaces specific text with different text\nReplace" + ID_EDIT_SELECT_ALL "Selects the entire document\nSelect All" + ID_EDIT_UNDO "Undoes the last action\nUndo" + ID_EDIT_REDO "Redoes the previously undone action\nRedo" +END + +STRINGTABLE +BEGIN + IDS_UAT_UNINDENT "Unindent" + IDS_UAT_DRAGDROP "Drag/drop" + IDS_UAT_TAB "Tab" + IDS_UAT_ENTER "Enter" + ID_EDIT_FIND_COMBO "Finds the specified text\nFind" + ID_TOOLS_OPTIONS "Changes options\nOptions" + ID_VIEW_APP_LOOK "Modifies the application general look\nApplication Look" + ID_HELP_WEB "Opens the Microsoft Home page\nMicrosoft on the Web" + ID_EDIT_HIDESELECTION "Adds the user-defined collapsible node for the currently selected text\nHide Selection" + ID_EDIT_TOGGLEOUTLINING "Toggles outlining inside selection\nToggle Outlining" + ID_EDIT_STOPHIDINGCURRENT + "Deletes the user-defined collapsible node(s) inside selection\nStop Hiding Current" + ID_EDIT_TOGGLEALLOUTLINING + "Toggles outlinings for the whole text\nToggle All Outlining" + ID_EDIT_COLLAPSETODEFINITIONS + "Collapses the members of all outlining types\nCollapse to Definitions" + ID_EDIT_STOPOUTLINING "Cancels auto-outlining mode\nStop Outlining" + ID_EDIT_AUTOOUTLINING "Enables/disables auto-outlining mode\nEnable Auto-Outlining" + ID_EDIT_ENABLEOUTLINING "Enables/disables outlining mode\nEnable Outlining" +END + +STRINGTABLE +BEGIN + ID_VIEW_TOOLBAR "Shows or hides the toolbar\nToggle ToolBar" + ID_VIEW_STATUS_BAR "Shows or hides the status bar\nToggle StatusBar" +END + +STRINGTABLE +BEGIN + AFX_IDS_SCSIZE "Changes the window size" + AFX_IDS_SCMOVE "Changes the window position" + AFX_IDS_SCMINIMIZE "Reduces the window to an icon" + AFX_IDS_SCMAXIMIZE "Enlarges the window to full size" + AFX_IDS_SCNEXTWINDOW "Switches to the next document window" + AFX_IDS_SCPREVWINDOW "Switches to the previous document window" + AFX_IDS_SCCLOSE "Closes the active window and prompts to save the documents" +END + +STRINGTABLE +BEGIN + AFX_IDS_SCRESTORE "Restores the window to normal size" + AFX_IDS_SCTASKLIST "Activates Task List" + AFX_IDS_MDICHILD "Activates this window" +END + +STRINGTABLE +BEGIN + AFX_IDS_PREVIEW_CLOSE "Closes print preview mode\nCancel Preview" +END + +STRINGTABLE +BEGIN + IDS_EDITFAILED "You cannot edit the document!" + IDS_PGUPFAILED "PgUp is failed!" +END + +STRINGTABLE +BEGIN + ID_VIEW_CUSTOMIZE "Customizes toolbars and menus\nCustomize" + ID_VIEW_USER_TOOLBAR1 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_USER_TOOLBAR2 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_USER_TOOLBAR3 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_USER_TOOLBAR4 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_USER_TOOLBAR5 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_USER_TOOLBAR6 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_USER_TOOLBAR7 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_USER_TOOLBAR8 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_USER_TOOLBAR9 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_USER_TOOLBAR10 "Shows or hides the user toolbar\nToggle User ToolBar" + ID_VIEW_WORKSPACE "Shows or hides the workspace\nWorkSpace" + ID_VIEW_OUTPUT "Shows or hides the output\nOutput" +END + +STRINGTABLE +BEGIN + ID_EDIT_NEXT_WORD "Find next word\nFind Next word" + ID_EDIT_LINENUMBERS "Shows/hides the line numbers\nLine Numbers" + IDS_UAT_REPLACE "Replace" + ID_EDIT_GOTO_LINE "Moves to a specified location\nGo to line" + ID_MDI_NEW_VERT_GROUP "Creates a new vertical tab group" + ID_MDI_NEW_HORZ_TAB_GROUP "Creates a new horizontal tab group" + ID_MDI_MOVE_TO_PREV_GROUP + "Moves the current view to the previous tab group" + ID_MDI_MOVE_TO_NEXT_GROUP "Moves the current view to the next tab group" + ID_MDI_TABBED_DOCUMENT "Tabbed Document\nTabbed Document" +END + +STRINGTABLE +BEGIN + ID_WINDOW_MANAGER "Manages the currently open windows\nWindow List" + ID_VIEW_DYNAMICHELP "Shows or hides the Dynamic Help\nDynamicHelp" + ID_DUMMY_COMPILE "Compiles the file\nCompile" + ID_DUMMY_BUILD "Builds the project\nBuild" + ID_DUMMY_STOP_BUILD "Stops the build\nStop Build" + ID_DUMMY_EXECUTE "Executes the program\nExecute Program" + ID_DUMMY_GO "Starts or continues the program\nGo" + ID_DUMMY_SELECT_ACTIVE_CONFIGURATION + "Selects the active configuration\nSelect Active Configuration" + ID_DUMMY_REMOVE_ALL_BREAKPOINTS + "Removes all breakpoints\nRemove All Breakpoints" + ID_VIEW_BUILD_TOOLBAR "Shows or hides the build toolbar\nToggle Build ToolBar" + ID_DUMMY_REBUILD_ALL "Rebuilds the active project\nRebuild All" + ID_DUMMY_CLEAN "Cleans the project\nClean" +END + +STRINGTABLE +BEGIN + ID_EDIT_TOGGLEBREAKPOINT + "Inserts or removes a breakpoint\nInsert/Remove Breakpoint" + ID_EDIT_CLEAR_ALLBOOKMARKS + "Clears all bookmarks in the window\nClear All Bookmarks" + ID_EDIT_INCREASE_IDENT "Indents the selection text right one tab stop\nIncrease Ident" + ID_EDIT_DECREASE_IDENT "Indents the selection text left one tab stop\nDecrease Ident" + ID_VIEW_EDIT_TOOLBAR "Shows or hides the edit toolbar\nToggle Build ToolBar" + ID_EDIT_LISTMEMBERS "Brings up the completion list box\nList Members" + IDS_UAT_UNDEFINED "" + IDS_UAT_TYPING "Typing" + IDS_UAT_DELETE "Delete" + IDS_UAT_INDENT "Indent" + IDS_UAT_UNKNOWN "" + IDS_UAT_CUT "Cut" + IDS_UAT_PASTE "Paste" + IDS_UAT_BACKSPACE "Backspace" +END + +STRINGTABLE +BEGIN + IDS_DUMMY_UNDO_ACTION "Undoes this action\nUndo" + ID_VIEW_CB_CAPTION "Toggle control bar captions\nControl Bar Captions" + ID_VIEW_FORCE_GRADIENT "Force Gradiend Captions\nGradiend Captions" + ID_USER_TOOL1 "Activates user-defined tool" + ID_USER_TOOL2 "Activates user-defined tool" + ID_USER_TOOL3 "Activates user-defined tool" + ID_USER_TOOL4 "Activates user-defined tool" + ID_USER_TOOL5 "Activates user-defined tool" + ID_USER_TOOL6 "Activates user-defined tool" + ID_USER_TOOL7 "Activates user-defined tool" + ID_USER_TOOL8 "Activates user-defined tool" + ID_USER_TOOL9 "Activates user-defined tool" + ID_USER_TOOL10 "Activates user-defined tool" +END + +STRINGTABLE +BEGIN + ID_HELP_SHOW_START "Shows the Start Page\nShow Start Page" + ID_VIEW_REFRESH "Refreshes the current view\nRefresh" + ID_VIEW_PROPERTIES "Shows or hides the Properties View\nProperties View" + ID_VIEW_WATCH "Shows or hides the watch\nToggle Watch" + ID_VIEW_FULLSCREEN "Toggles full screen mode On and Off\nToggles Full Screen" +END + +STRINGTABLE +BEGIN + ID_TOOLS_MACRO "Creates and edits macros\nMacro" + ID_TOOLS_ENTRY "\n" + ID_NEW_DIALOG "Creates a new dialog resource\nNew Dialog" + ID_NEW_MENU "Creates a new menu resource\nNew Menu" + ID_NEW_CURSOR "Creates a new cursor resource\nNew Cursor" + ID_NEW_ICON "Creates a new icon resource\nNew Icon" + ID_NEW_BITMAP "Creates a new bitmap resource\nNew Bitmap" + ID_NEW_TOOLBAR "Creates a new toolbar resource\nNew Toolbar" + ID_NEW_ACCELERATOR "Creates a new accelerator resource\nNew Accelerator" + ID_NEW_STRING_TABLE "Creates a new string table resource\nNew String Table" + ID_NEW_VERSION "Creates a new version resource\nNew Version" +END + +STRINGTABLE +BEGIN + ID_OUTPUT_GOTO_ERROR "Moves to the line containing current error or tag\nGo to Error" + ID_CLASS_DEFINITION "Displays the definition of the selected item\nDefinition" + ID_CLASS_ADD_MEMEBER_FUNCTION + "Adds a member function to the selected class\nAdd Member Function" + ID_CLASS_ADD_MEMEBER_VARIABLE + "Adds a member variable to the selected class\nAdd Member Variable" + ID_CLASS_PROPERTIES "Edits the current selection properties" + ID_RESOURCE_OPEN "Opens the selected resource for editing\nOpen" + ID_RESOURCE_OPEN_BINARY "Opens the selected resource for binary editing\nOpen Binary" + ID_VIEW_TAB_FLAT_BORDERS "Toggles Tab Flat Borders\nTab &Flat Borders" + ID_HELP_KEYBOARDMAP "Displays all keyboard commands\nKeyboard Map" + ID_MENU_DIR1 "$(ItemDirectory)" +END + +STRINGTABLE +BEGIN + ID_MENU_ITEM1 "$(ItemPath)" + ID_MENU_ITEM2 "$(ItemFilename)" + ID_MENU_ITEM3 "$(ItemExtension)" + ID_DHELP1 "Help Content\nHelp Content" + ID_DHELP2 "Help Index\nIndex" + ID_DHELP3 "Help Search\nSearch" + ID_EXPAND "Categorized\nCategorized" + ID_SORTINGPROP "Alphabetic\nAlphabetic" +END + +STRINGTABLE +BEGIN + ID_MENU_DIR2 "$(WindowsDirectory)" + ID_MENU_DIR3 "$(SystemDirectory)" + ID_MDITABS_ICONS "Toggles MDI Tab Icons\nMDI Icons" + ID_MDITABS_TOP "Shows MDI Tabs on top\nTop" + ID_MDITABS_BOTTOM "Shows MDI Tabs at bottom\nBottom" + ID_VIEW_MDI_TABS "Toggles MDI Tabs\nShow/Hide Tabs" + ID_MDITABS_CLOSE "Closes clicked document\nClose Document" + ID_VIEW_CLASS "Shows or hides the Class View\nClassView" + ID_VIEW_RESOURCE "Shows or hides the Resource View\nResourceView" + ID_VIEW_FILE "Shows or hides the Solution Explorer\nSolutionExplorer" +END + +STRINGTABLE +BEGIN + ID_PROPERIES1 "Properties\nProperties" + ID_PROPERIES2 "Events\nEvents" + ID_NEW_FOLDER "New Folder\nNew Folder" + ID_PROPERTIES "Show Properties\nProperties" + ID_SOLUTION_OPEN "Opens a file\nOpen" + ID_SOLUTION_OPEN_WITH "Opens a solution\nOpen With...." + ID_FILE_NEW_PROJECT "Creates a new project\nNew Project" + ID_FILE_NEW_BLANK_SOLUTION "Creates a new blank solution\nBlank Solution" + ID_FILE_OPEN_SOLUTION "Opens a solution\nOpen Solution" + ID_FILE_CLOSE_SOLUTION "Closes the solution\nClose Solution" + ID_FILE_SAVE_ALL "Saves all open documents\nSave All" + ID_TOOLS_DEBUG_PROCESSES "Shows debug processes\nDebug Processes" + ID_TOOLS_CONNECT_TO_DATABASE "Connects to a database\nConnect to Database" + ID_WINDOW_CLOSE_ALL "Closes all documents\nClose All Documents" +END + +STRINGTABLE +BEGIN + ID_EDIT_TOGGLEBOOKMARK "Inserts or removes a Bookmark\nToggle Bookmark" + ID_EDIT_NEXTBOOKMARK "Goes to the next temporary bookmark\nNext Bookmark" + ID_EDIT_PREVIOUSBOOKMARK + "Goes to the previous temporary bookmark\nPrevious Bookmark" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#define _AFX_NO_SPLITTER_RESOURCES +#define _AFX_NO_OLE_RESOURCES +#define _AFX_NO_TRACKER_RESOURCES +#define _AFX_NO_PROPERTY_RESOURCES + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE 9, 1 +#pragma code_page(1252) +#endif //_WIN32 +#include "afxres.rc" // Standard components +#endif + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/usr/Src/Interface/vtAgeiaInterfaceCallback.cpp b/usr/Src/Interface/vtAgeiaInterfaceCallback.cpp new file mode 100644 index 0000000..84658a4 --- /dev/null +++ b/usr/Src/Interface/vtAgeiaInterfaceCallback.cpp @@ -0,0 +1,122 @@ +#include "stdafx2.h" +#include "vtAgeiaInterfaceCallback.h" + + +#include "vtAgeiaInterfaceKeyboardShortcuts.h" +#include "vtAgeiaInterfaceMenu.h" + +#include "PCommonDialog.h" +#include "vtBodyStructs.h" +#include "PBodySetup.h" + + + + +//static plugin interface that allow direct communication with Virtools Dev +PluginInterface* s_Plugininterface = NULL; + +WIN_HANDLE CKActorUIFunc(CKParameter* param,WIN_HANDLE parent,CKRECT *rect); +WIN_HANDLE CKDoubleUIFunc (CKParameter *param,WIN_HANDLE ParentWindow,CKRECT *rect); + +/* +AFX_STATIC UINT _afxMsgMouseWheel = +(((::GetVersion() & 0x80000000) && LOBYTE(LOWORD(::GetVersion()) == 4)) || + (!(::GetVersion() & 0x80000000) && LOBYTE(LOWORD(::GetVersion()) == 3))) + ? ::RegisterWindowMessage(MSH_MOUSEWHEEL) : 0; +*/ + +//ON_REGISTERED_MESSAGE(_afxMsgMouseWheel, OnRegisteredMouseWheel)*/ +//ON_BN_CLICKED(IDC_BFLAGS_DEFORMABLE, OnBnClickedBflagsDeformable) + + + +WIN_HANDLE CKActorUIFunc (CKParameter *param,WIN_HANDLE ParentWindow,CKRECT *rect) +{ + + + AFX_MANAGE_STATE(AfxGetStaticModuleState()); +/* + // Initialize OLE libraries + if (!AfxOleInit()) + { + //AfxMessageBox(IDP_OLE_INIT_FAILED); + return FALSE; + } +*/ +// CMultiDocTemplate* pDocTemplate; + +/* pDocTemplate = new CMultiDocTemplate(IDR_DRAWCLTYPE, RUNTIME_CLASS(CDrawDoc), RUNTIME_CLASS(CSplitFrame), RUNTIME_CLASS(CDrawView)); + pDocTemplate->SetContainerInfo(IDR_DRAWCLTYPE_CNTR_IP); + AddDocTemplate(pDocTemplate); +*/ + + + CPBCommonDialog *Dlg = new CPBCommonDialog(param); + Dlg->m_Context = param->GetCKContext(); + HWND win = (HWND)ParentWindow; + //Dlg->HType.SetCurSel(0); + CKRECT &rect2= *rect; + HWND result = NULL; + + //CPBParentDialog *Dlg = new CPBParentDialog(param,CWnd::FromHandle(win)); + //CPBodyCfg *Dlg = new CPBodyCfg(param); + + if (param && win && Dlg ) + { + Dlg->Create( IDD_PBCOMMON, CWnd::FromHandle(win)); + result = CreateParameterDialog( win, Dlg, 0, PARAMETER_PICKALL, 0, PARAMETER_NORESIZE); + } + + if (result) + { + return result; + } + + return NULL; + +} + +//main plugin callback for Virtools Dev +void PluginCallback(PluginInfo::CALLBACK_REASON reason,PluginInterface* plugininterface) +{ + CKContext* ctx = GetCKContext(0); + + CKParameterManager *pm = ctx->GetParameterManager(); + + + { //--- Set UI Function of Shader Param + CKParameterTypeDesc *param_desc = pm->GetParameterTypeDescription(VTF_PHYSIC_BODY_COMMON_SETTINGS); + if( !param_desc ) return; + + param_desc->UICreatorFunction = CKActorUIFunc; + //param_desc->UICreatorFunction = CKDoubleUIFunc; + } + + switch(reason) + { + case PluginInfo::CR_LOAD: + { + s_Plugininterface = plugininterface; + //InitParameters(reason,plugininterface); + /*InitMenu(); + UpdateMenu(); + RegisterKeyboardShortcutCategory(); + RegisterKeyboardShortcuts();*/ + + }break; + case PluginInfo::CR_UNLOAD: + { + //RemoveMenu(); + //UnregisterKeyboardShortcutCategory(); + s_Plugininterface = NULL; + }break; + case PluginInfo::CR_NEWCOMPOSITIONNAME: + { + // InitMenu(); + + }break; + case PluginInfo::CR_NOTIFICATION: + { + }break; + } +} diff --git a/usr/Src/Interface/vtAgeiaInterfaceEditor.cpp b/usr/Src/Interface/vtAgeiaInterfaceEditor.cpp new file mode 100644 index 0000000..046aaa1 --- /dev/null +++ b/usr/Src/Interface/vtAgeiaInterfaceEditor.cpp @@ -0,0 +1,266 @@ +// Editor.cpp : Defines the initialization routines for the DLL. +// + +#include "stdafx2.h" +#include "vtAgeiaInterfaceEditor.h" +#include "vtAgeiaInterfaceEditorDlg.h" +#include "vtAgeiaInterfaceToolbarDlg.h" +#include "vtAgeiaInterfaceCallback.h" + +#include "resource.h" +#ifdef _MFCDEBUGNEW +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif +#endif + +vtAgeiaInterfaceEditorDlg* g_Editor = NULL; +vtAgeiaInterfaceToolbarDlg* g_Toolbar = NULL; + +//---------------------------------------- +//The Plugin Info structure that must be filled for Virtools Dev to load effectively the plugin +PluginInfo g_PluginInfo0; + +//Returns the number of plugin contained in this dll +//this function must be exported (have a .def file with its name or use __declspec( dllexport ) +int GetVirtoolsPluginInfoCount() +{ + return 1; +} + +//returns the ptr of the (index)th plugininfo structure of this dll +//this function must be exported (have a .def file with its name or use __declspec( dllexport ) +PluginInfo* GetVirtoolsPluginInfo(int index) +{ + switch(index) + { + case 0: + return &g_PluginInfo0; + } + return NULL; +} + +// +// Note! +// +// If this DLL is dynamically linked against the MFC +// DLLs, any functions exported from this DLL which +// call into MFC must have the AFX_MANAGE_STATE macro +// added at the very beginning of the function. +// +// For example: +// +// extern "C" BOOL PASCAL EXPORT ExportedFunction() +// { +// AFX_MANAGE_STATE(AfxGetStaticModuleState()); +// // normal function body here +// } +// +// It is very important that this macro appear in each +// function, prior to any calls into MFC. This means that +// it must appear as the first statement within the +// function, even before any object variable declarations +// as their constructors may generate calls into the MFC +// DLL. +// +// Please see MFC Technical Notes 33 and 58 for additional +// details. +// + +///////////////////////////////////////////////////////////////////////////// +// vtAgeiaInterfaceEditorApp + +BEGIN_MESSAGE_MAP(vtAgeiaInterfaceEditorApp, CWinApp) + //{{AFX_MSG_MAP(vtAgeiaInterfaceEditorApp) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// vtAgeiaInterfaceEditorApp construction + +vtAgeiaInterfaceEditorApp::vtAgeiaInterfaceEditorApp() +{ + mContext = NULL; + pMan =NULL; +} + +///////////////////////////////////////////////////////////////////////////// +// The one and only vtAgeiaInterfaceEditorApp object + +vtAgeiaInterfaceEditorApp theApp; + + + + + + +BOOL vtAgeiaInterfaceEditorApp::InitInstance() +{ + AfxOleInit(); + // TODO: Add your specialized code here and/or call the base class + if (GetCKContext(0)) + { + /*theApp.mContext = GetCKContext(0); + PhysicManager *im = (PhysicManager*)getContext()->GetManagerByGuid(PhysicManager_GUID); + if (im) + { + pMan = im; + }*/ + } + + strcpy(g_PluginInfo0.m_Name,"vtAgeiaInterface"); + g_PluginInfo0.m_PluginType = PluginInfo::PT_EDITOR; + //g_PluginInfo0.m_PluginType = (PluginInfo::PLUGIN_TYPE)(g_PluginInfo0.m_PluginType | PluginInfo::PTF_RECEIVENOTIFICATION); + + + //EDITOR + { + g_PluginInfo0.m_EditorInfo.m_Guid[1] = 0xd07cc06a; + g_PluginInfo0.m_EditorInfo.m_Guid[2] = 0x7ca4fc86; + strcpy(g_PluginInfo0.m_EditorInfo.m_EditorName,"vtAgeiaEditor"); + + g_PluginInfo0.m_EditorInfo.m_CreateEditorDlgFunc = fCreateEditorDlg; + g_PluginInfo0.m_EditorInfo.m_CreateToolbarDlgFunc = fCreateToolbarDlg; + + g_PluginInfo0.m_EditorInfo.m_bUnique = 1; + g_PluginInfo0.m_EditorInfo.m_bIndestructible = 0; + g_PluginInfo0.m_EditorInfo.m_bManageScrollbar = 0; + + g_PluginInfo0.m_EditorInfo.m_Width = 400; + g_PluginInfo0.m_EditorInfo.m_Height = 200; + + g_PluginInfo0.m_EditorInfo.m_ToolbarHeight = 21; + //InitImageList(); + g_PluginInfo0.m_EditorInfo.m_IconList = &m_ImageList; + g_PluginInfo0.m_EditorInfo.m_IconIndex = 0; + + g_PluginInfo0.m_PluginCallback = PluginCallback; + } + + + return CWinApp::InitInstance(); +} + +int vtAgeiaInterfaceEditorApp::ExitInstance() +{ + // TODO: Add your specialized code here and/or call the base class + + DeleteImageList(); + + return CWinApp::ExitInstance(); +} + +void vtAgeiaInterfaceEditorApp::InitImageList() +{ + AFX_MANAGE_STATE(AfxGetStaticModuleState()); + + m_ImageList.Create(16, 16, ILC_COLOR8|ILC_MASK, 0, 2); + +// m_ImageList.Add(AfxGetApp()->LoadIcon(IDI_EDITORICON)); +} + +void vtAgeiaInterfaceEditorApp::DeleteImageList() +{ + m_ImageList.DeleteImageList(); +} + + +/* + +CWnd* thisSubParentWindow = CWnd::FromHandle((HWND)ParentWindow); +MultiParamEditDlg pedit(GetCKContext(0), thisSubParentWindow); +int s = pedit.GetMode(); +pedit.SetMode(MultiParamEditDlg::AUTOCLOSE_WHEN_MODELESS|MultiParamEditDlg::MODELESSEDIT); + +CKParameterOut *commonParameter= GetParameterFromStruct(param,PS_COMMON_SETTINGS); +pedit.AddParameter(commonParameter); +//for (int i = 0; i < mfx->m_Params.Size(); ++i) +// pedit.AddParameter(mfx->m_Params[i]); +pedit.SetTitle("Material Shader Fx Params"); +pedit.DoModal(); + +return pedit.GetSafeHwnd(); + +char name[256]; +if (oriUIFunc && param) +{ + + //CWnd* thisSubParentWindow = CWnd::FromHandle((HWND)ParentWindow); + CWnd* thisSubParentWindow = CWnd::FromHandle((HWND)ParentWindow); + CString strMain; + thisSubParentWindow->GetWindowText(strMain); + + + + if (thisSubParentWindow !=NULL ) + { + CWnd* bigParentWindow = thisSubParentWindow; + for( CWnd* subParentWindow = bigParentWindow->GetWindow(GW_CHILD); subParentWindow ; subParentWindow = subParentWindow->GetWindow(GW_HWNDNEXT) ) + { + + + CString str; + subParentWindow->GetWindowText(str); + + GetClassName( subParentWindow->m_hWnd, name, sizeof(name) ); + + XString _name(name); + //if( strcmp(name,MFC_NAME_OF_DIALOG) ) continue; + for( CWnd* child = subParentWindow->GetWindow(GW_CHILD) ; child ; child = child->GetWindow(GW_HWNDNEXT) ) + { + + + CString str2; + child->GetWindowText(str); + + + //GetClassName( child->m_hWnd, name, sizeof(name) ); + //XString _name2(name); + + //if( strcmp(name,MFC_NAME_OF_DIALOG) ) continue; + + //CParameterDialog* otherParamDialog = (CParameterDialog*)(child->SendMessage( CKWM_GETPARAMDIALOG, 0, 0 )); + //if( !otherParamDialog ) continue; + + CKParameterOut *commonParameter= GetParameterFromStruct(param,PS_COMMON_SETTINGS); + if (commonParameter) + { + int p2=2; + p2++; + //SetParameterStructureValue(commonParameter,PS_HULL_TYPE,HT_Mesh,false); + } + + + //--- From this point it should be a CParameterDialog... + //CParameterDialog* otherParamDialog = (CParameterDialog*)(child->SendMessage( CKWM_GETPARAMDIALOG, 0, 0 )); + //if( !otherParamDialog ) continue; + + } + + + + + + } + } + + + //MultiParamEditDlg test(param->GetCKContext(),ParentWindow); + + + CKParameterOut *commonParameter= GetParameterFromStruct(param,PS_COMMON_SETTINGS); + if (commonParameter) + { + //SetParameterStructureValue(commonParameter,PS_HULL_TYPE,HT_Mesh,false); + + } + //return (*oriUIFunc)(param,ParentWindow,rect); + return ParentWindow; + double d = 0.0; +} + +*/ \ No newline at end of file diff --git a/usr/Src/Interface/vtAgeiaInterfaceEditorDlg.cpp b/usr/Src/Interface/vtAgeiaInterfaceEditorDlg.cpp new file mode 100644 index 0000000..7b9ba6f --- /dev/null +++ b/usr/Src/Interface/vtAgeiaInterfaceEditorDlg.cpp @@ -0,0 +1,316 @@ +// vtAgeiaInterfaceEditorDlg.cpp : implementation file +// + +#include "stdafx2.h" +#include "vtAgeiaInterfaceEditor.h" +#include "vtAgeiaInterfaceEditorDlg.h" +#include "vtAgeiaInterfaceKeyboardShortcuts.h" +#include "vtAgeiaInterfaceCallback.h" + + + +#ifdef _MFCDEBUGNEW +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif +#endif + +extern vtAgeiaInterfaceEditorApp theApp; + + +DllEditorDlg* fCreateEditorDlg(HWND parent) +{ + HRESULT r = CreateDllDialog(parent,IDD_EDITOR,&g_Editor); + return (DllEditorDlg*)g_Editor; +} + +///////////////////////////////////////////////////////////////////////////// +// vtAgeiaInterfaceEditorDlg dialog + + +vtAgeiaInterfaceEditorDlg::vtAgeiaInterfaceEditorDlg(CWnd* pParent /*=NULL*/) + : DllEditorDlg(vtAgeiaInterfaceEditorDlg::IDD, pParent) +{ + mContext = NULL; + pMan = NULL; + + //{{AFX_DATA_INIT(vtAgeiaInterfaceEditorDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void vtAgeiaInterfaceEditorDlg::DoDataExchange(CDataExchange* pDX) +{ + DllEditorDlg::DoDataExchange(pDX); + //{{AFX_DATA_MAP(vtAgeiaInterfaceEditorDlg) + // NOTE: the ClassWizard will add DDX and DDV calls here + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(vtAgeiaInterfaceEditorDlg, DllEditorDlg) + //{{AFX_MSG_MAP(vtAgeiaInterfaceEditorDlg) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// vtAgeiaInterfaceEditorDlg message handlers + +LRESULT vtAgeiaInterfaceEditorDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) +{ + // TODO: Add your specialized code here and/or call the base class + + switch (message) + { + case WM_KEYDOWN: + { + KeyboardShortcutManager* ksm = GetInterface()->GetKeyboardShortcutManager(); + /*int commandID = ksm->TestKS(STR_CATEGORY,wParam); + if (commandID) + OnGlobalKeyboardShortcut(commandID); + */ + }break; + } + + return DllEditorDlg::WindowProc(message, wParam, lParam); +} + +BOOL vtAgeiaInterfaceEditorDlg::SaveData(CKInterfaceObjectManager* iom) +{ + + if( !iom ) return FALSE; + + const int chunkCount = iom->GetChunkCount(); + + CKStateChunk* chunk = iom->GetChunk( 0 ); + if( !chunk ) return FALSE; + + + int a = 0 ; + return TRUE; +} + +BOOL vtAgeiaInterfaceEditorDlg::LoadData(CKInterfaceObjectManager* iom) +{ + + + if( !iom ) return FALSE; + + const int chunkCount = iom->GetChunkCount(); + + CKStateChunk* chunk = iom->GetChunk( 0 ); + if( !chunk ) return FALSE; + + chunk->StartRead(); + + chunk->CloseChunk(); + return TRUE; + + +} +BOOL vtAgeiaInterfaceEditorDlg::PreTranslateMessage(MSG* pMsg) +{ + // TODO: Add your specialized code here and/or call the base class + + /*if ( + pMsg->message >= WM_MOUSEFIRST && + pMsg->message <= WM_MOUSELAST) + { + MSG msg; + ::CopyMemory(&msg, pMsg, sizeof(MSG)); + m_wndToolTip.RelayEvent(pMsg); + } + */ + /*switch(pMsg->message) + { + case WM_MOUSEMOVE: + { + break; + } + case WM_SYSKEYDOWN: + case WM_KEYDOWN: + { + + }break; + }*/ + + return DllEditorDlg::PreTranslateMessage(pMsg); +} + +BOOL vtAgeiaInterfaceEditorDlg::OnInitDialog() +{ + DllEditorDlg::OnInitDialog(); + + // TODO: Add extra initialization here + + //EnableToolTips(TRUE); + //CreateTooltip(); + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +//this is the almost equivalent of OnInitDialog you should use if you want to +//use the PluginInterface with GetInterface or if you want to be sure the toolbar is present +void vtAgeiaInterfaceEditorDlg::OnInterfaceInit() +{ + if (theApp.mContext && theApp.pMan) + { + init(theApp.mContext,theApp.pMan); + } + //sample code : here we ask to listen to the _CKFILELOADED notification + //which is send when a file is loaded from Virtools Dev's user interface + ObserveNotification(CUIK_NOTIFICATION_CKFILELOADED); + + ObserveNotification(CUIK_NOTIFICATION_LEVEL_LOADED); + ObserveNotification(CUIK_NOTIFICATION_CKFILELOADED); + ObserveNotification(CUIK_NOTIFICATION_PRECKFILELOADED); + + ObserveNotification(CUIK_NOTIFICATION_OBJECTROTCHANGED); + ObserveNotification(CUIK_NOTIFICATION_OBJECTPOSCHANGED); + ObserveNotification(CUIK_NOTIFICATION_SELECTIONCHANGED); + ObserveNotification(CUIK_NOTIFICATION_UPDATESETUP); + ObserveNotification(CUIK_NOTIFICATION_OBJECTPARAMSCHANGED); + + + + +} + +void vtAgeiaInterfaceEditorDlg::objectSelChanged(DWORD par1,DWORD par2) +{ + + /* + if (getContext()) + { + + getContext()->OutputToConsoleEx("sel changed :"); + return ; + CKBeObject *object = (CKBeObject*)mContext->GetObject(par1); + if (object) + { + CKSTRING name = object->GetName(); + getContext()->OutputToConsoleEx("sel changed : %s",name); + + } + }*/ +} +void vtAgeiaInterfaceEditorDlg::objectPosChanged(CK_ID objID) +{ + int id = objID; + ///MessageBox("asdasd","asdasd",1); +/* + + if (mContext) + { + CKBeObject *object = (CKBeObject*)mContext->GetObject(objID); + if (objID) + { + int a = 0 ; + CKSTRING name = object->GetName(); + CKSTRING name2 = object->GetName(); + + + } + } + + */ +} +void vtAgeiaInterfaceEditorDlg::init(CKContext *ctx,PhysicManager *pm) +{ + pMan = pm; + mContext = ctx; + +} + +//called on WM_DESTROY +void vtAgeiaInterfaceEditorDlg::OnInterfaceEnd() +{ +} + +HRESULT vtAgeiaInterfaceEditorDlg::ReceiveNotification(UINT MsgID,DWORD Param1,DWORD Param2,CKScene* Context) +{ + switch(MsgID) + { + //sample code : + case CUIK_NOTIFICATION_CKFILELOADED: + { + }break; + case CUIK_NOTIFICATION_OBJECTPOSCHANGED: + { + //objectPosChanged(Param1); + } + case CUIK_NOTIFICATION_SELECTIONCHANGED: + { + + //objectSelChanged(Param1,Param2); + break; + } + case CUIK_NOTIFICATION_UPDATESETUP: + { + //objectSelChanged(Param1,Param2); + break; + } + case CUIK_NOTIFICATION_OBJECTPARAMSCHANGED: + { + //objectSelChanged(Param1,Param2); + break; + } + break; + } + return 0; +} + +void vtAgeiaInterfaceEditorDlg::CreateTooltip() +{ + m_wndToolTip.Create(this); + m_wndToolTip.Activate(TRUE); + + //delay after which the tooltip apppear, value of 1 is immediate, 0 is default (that is 500 for windows) + m_wndToolTip.SetDelayTime(500); + + //change tooltip back color + //m_wndToolTip.SetTipBkColor(CZC_176); + //change tooltip text color + //m_wndToolTip.SetTipTextColor(CZC_BLACK); + + //for each control you want to add a tooltip on, add the following line + //m_wndToolTip.AddTool(CWnd* target,const char* tooltip_string); + + //delay after which the tooltip will auto close itself + m_wndToolTip.SetDelayTime(TTDT_AUTOPOP,5000); + + m_wndToolTip.SetWindowPos(&(CWnd::wndTopMost),0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); + + //if you want multiline tooltip, you must add the following line (note that this represent the max tooltip width in pixel) + m_wndToolTip.SendMessage(TTM_SETMAXTIPWIDTH, 0, 500); +} +int vtAgeiaInterfaceEditorDlg::OnGlobalKeyboardShortcut(int commandID) +{ + return 0; //return 1 if successfull/keyboard shortcut has been processed +} + +int vtAgeiaInterfaceEditorDlg::OnLocalKeyboardShortcut(int commandID) +{ + return 0; //return 1 if successfull/keyboard shortcut has been processed +} +void vtAgeiaInterfaceEditorDlg::OnCustomMenu(CMenu* menu,int startingCommandID,int endingCommandID) +{ + menu->AppendMenu(0,0 /*base ID*/ + startingCommandID,"Sample Command 1"); + menu->AppendMenu(0,1 /*base ID*/ + startingCommandID,"Sample Command 2"); +} + +void vtAgeiaInterfaceEditorDlg::OnCustomMenu(int commandID) +{ + switch(commandID) { + case 0: + AfxMessageBox("sample command 1 called"); + break; + case 1: + AfxMessageBox("sample command 2 called"); + break; + } +} diff --git a/usr/Src/Interface/vtAgeiaInterfaceKeyboardShortcuts.cpp b/usr/Src/Interface/vtAgeiaInterfaceKeyboardShortcuts.cpp new file mode 100644 index 0000000..737b1a3 --- /dev/null +++ b/usr/Src/Interface/vtAgeiaInterfaceKeyboardShortcuts.cpp @@ -0,0 +1,92 @@ +#include "stdafx2.h" +#include "vtAgeiaInterfaceEditor.h" +#include "vtAgeiaInterfaceEditorDlg.h" +#include "vtAgeiaInterfaceKeyboardShortcuts.h" + +void GlobalKSCallback(int commandID) +{ + if (g_Editor) + g_Editor->OnGlobalKeyboardShortcut(commandID); +} + +int RegisterKeyboardShortcutCategory() +{ + KeyboardShortcutManager* ksm = s_Plugininterface->GetKeyboardShortcutManager(); + if (ksm) + { + //remove the comments delimiters to register global keyboard shortcut category + //that will be detected by the application whatever the focused window is. + int index = ksm->RegisterCategory(STR_CATEGORY,NULL,ACTIVE/*+GLOBAL*/,NULL,NULL/*GlobalKSCallback*/,GetCommandName); + if (index>=0) + return 1; + } + return 0; +} + +int UnregisterKeyboardShortcutCategory() +{ + KeyboardShortcutManager* ksm = s_Plugininterface->GetKeyboardShortcutManager(); + if (ksm) + { + return ksm->UnregisterCategory(STR_CATEGORY); + } + return 0; +} + +int RegisterKeyboardShortcuts() +{ + KeyboardShortcutManager* ksm = s_Plugininterface->GetKeyboardShortcutManager(); + KeyboardShortcutManager::KS ks; + + int index = ksm->GetCategoryIndex(STR_CATEGORY); + +//sample code to register Ctrl+shift+alt+A with commandid_a and B with commandid_b + ks.key = 'A'; + ks.flags = ks.KS_CONTROL|ks.KS_SHIFT|ks.KS_ALT; + ks.commandID = CID_A; + ksm->RegisterKS(index,ks); + + ks.key = 'B'; + ks.flags = 0; + ks.commandID = CID_B; + ksm->RegisterKS(index,ks); +//end sample code + + return 1; +} + +const char* GetCommandName(int commandID) +{ +//sample code + switch(commandID) + { + case CID_A: + return STR_A; + case CID_B: + return STR_B; + } +//sample code + return NULL; +} + +const char* GetCommandMenuName(int commandID,XString &name) +{ + name=""; + const char* cstr = GetCommandName(commandID); + if (!cstr) + return NULL; + + name = cstr; + + KeyboardShortcutManager* ksm = s_Plugininterface->GetKeyboardShortcutManager(); + if (ksm) + { + ksm->GetKSName( STR_CATEGORY, + commandID, + name, + FALSE/*do not clear string*/, + TRUE/*add tab to string if string not empty*/); + } + + return name.CStr(); +} diff --git a/usr/Src/Interface/vtAgeiaInterfaceMenu.cpp b/usr/Src/Interface/vtAgeiaInterfaceMenu.cpp new file mode 100644 index 0000000..7724200 --- /dev/null +++ b/usr/Src/Interface/vtAgeiaInterfaceMenu.cpp @@ -0,0 +1,63 @@ +#include "stdafx2.h" +#include "vtAgeiaInterfaceeditor.h" +#include "vtAgeiaInterfaceMenu.h" + +//declaration of menu callback (for InitMenu function) +void PluginMenuCallback(int commandID); + +//static main menu +CMenu* s_MainMenu = NULL; + +#define PLUGINMENU_MAXENTRIES 20 //put there the max entries your menu may use + + + + + +//adds the menu to Virtools Dev main menu +void InitMenu() +{ + if (!s_Plugininterface) + return; + + s_MainMenu = s_Plugininterface->AddPluginMenu(STR_MAINMENUNAME,PLUGINMENU_MAXENTRIES,NULL,(VoidFunc1Param)PluginMenuCallback); +} + +//removes the menu from Virtools Dev main menu +void RemoveMenu() +{ + if (!s_Plugininterface || !s_MainMenu) + return; + + s_Plugininterface->RemovePluginMenu(s_MainMenu); +} + +//up to user. +//(May be called on new composition notification for instance) +//Note that first commandID can be 0 +//but last command ID must be lesser thanPLUGINMENU_MAXENTRIES +void UpdateMenu() +{ + s_Plugininterface->ClearPluginMenu(s_MainMenu); //clear menu + + s_Plugininterface->AddPluginMenuItem(s_MainMenu,0,"item0"); //add simple item sample + s_Plugininterface->AddPluginMenuItem(s_MainMenu,1,"item1"); //add simple item sample + s_Plugininterface->AddPluginMenuItem(s_MainMenu,-1,NULL,TRUE); //add separator sample + CMenu* sub0 = s_Plugininterface->AddPluginMenuItem(s_MainMenu,2,"SubMenu0",FALSE,TRUE); //sub menu sample + CMenu* sub1 = s_Plugininterface->AddPluginMenuItem(s_MainMenu,3,"SubMenu1",FALSE,TRUE); //sub menu sample + s_Plugininterface->AddPluginMenuItem(sub0,4,"item2"); //add simple item to sub menu sample + s_Plugininterface->AddPluginMenuItem(sub0,5,"item3"); //add simple item to sub menu sample + s_Plugininterface->AddPluginMenuItem(sub1,6,"item4"); //add simple item to sub menu sample + s_Plugininterface->AddPluginMenuItem(sub1,7,"item5"); //add simple item to sub menu sample + + s_Plugininterface->UpdatePluginMenu(s_MainMenu); //update menu,always needed when you finished to update the menu + //unless you want the menu not to have Virtools Dev main menu color scheme. +} + +//fill with your command IDs and your actions +void PluginMenuCallback(int commandID) +{ + /*switch(commandID) + { + }*/ +} diff --git a/usr/Src/Interface/vtAgeiaInterfaceToolbarDlg.cpp b/usr/Src/Interface/vtAgeiaInterfaceToolbarDlg.cpp new file mode 100644 index 0000000..e5a77c9 --- /dev/null +++ b/usr/Src/Interface/vtAgeiaInterfaceToolbarDlg.cpp @@ -0,0 +1,123 @@ +// vtAgeiaInterfaceToolbarDlg.cpp : implementation file +// + +#include "stdafx2.h" +#include "vtAgeiaInterfaceEditor.h" +#include "vtAgeiaInterfaceToolbarDlg.h" + +#ifdef _MFCDEBUGNEW +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif +#endif + +DllToolbarDlg* fCreateToolbarDlg(HWND parent) +{ + HRESULT r = CreateDllDialog(parent,IDD_TOOLBAR,&g_Toolbar); + return (DllToolbarDlg*)g_Toolbar; +} + +///////////////////////////////////////////////////////////////////////////// +// vtAgeiaInterfaceToolbarDlg dialog + + +vtAgeiaInterfaceToolbarDlg::vtAgeiaInterfaceToolbarDlg(CWnd* pParent /*=NULL*/) + : DllToolbarDlg(vtAgeiaInterfaceToolbarDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(vtAgeiaInterfaceToolbarDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void vtAgeiaInterfaceToolbarDlg::DoDataExchange(CDataExchange* pDX) +{ + DllToolbarDlg::DoDataExchange(pDX); + //{{AFX_DATA_MAP(vtAgeiaInterfaceToolbarDlg) + // NOTE: the ClassWizard will add DDX and DDV calls here + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(vtAgeiaInterfaceToolbarDlg, DllToolbarDlg) + //{{AFX_MSG_MAP(vtAgeiaInterfaceToolbarDlg) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// vtAgeiaInterfaceToolbarDlg message handlers + +BOOL vtAgeiaInterfaceToolbarDlg::PreTranslateMessage(MSG* pMsg) +{ + // TODO: Add your specialized code here and/or call the base class + + if ( + pMsg->message >= WM_MOUSEFIRST && + pMsg->message <= WM_MOUSELAST) + { + MSG msg; + ::CopyMemory(&msg, pMsg, sizeof(MSG)); + m_wndToolTip.RelayEvent(pMsg); + } + + return DllToolbarDlg::PreTranslateMessage(pMsg); +} + +BOOL vtAgeiaInterfaceToolbarDlg::OnInitDialog() +{ + DllToolbarDlg::OnInitDialog(); + + // TODO: Add extra initialization here + +// EnableToolTips(TRUE); +// CreateTooltip(); + + ActivateClosebutton(); + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + +//this is the almost equivalent of OnInitDialog you should use if you want to +//use the PluginInterface with GetInterface or if you want to be sure the editor is present +void vtAgeiaInterfaceToolbarDlg::OnInterfaceInit() +{ +} + +//called on WM_DESTROY +void vtAgeiaInterfaceToolbarDlg::OnInterfaceEnd() +{ +} + +HRESULT vtAgeiaInterfaceToolbarDlg::ReceiveNotification(UINT MsgID,DWORD Param1,DWORD Param2,CKScene* Context) +{ + return 0; +} + +void vtAgeiaInterfaceToolbarDlg::CreateTooltip() +{ + //m_wndToolTip.Create(this); +// m_wndToolTip.Activate(TRUE); + + //delay after which the tooltip apppear, value of 1 is immediate, 0 is default (that is 500 for windows) + //m_wndToolTip.SetDelayTime(500); + + //change tooltip back color + //m_wndToolTip.SetTipBkColor(CZC_176); + //change tooltip text color + //m_wndToolTip.SetTipTextColor(CZC_BLACK); + + //for each control you want to add a tooltip on, add the following line + //m_wndToolTip.AddTool(CWnd* target,const char* tooltip_string); + + //delay after which the tooltip will auto close itself + /* + m_wndToolTip.SetDelayTime(TTDT_AUTOPOP,5000); + + m_wndToolTip.SetWindowPos(&(CWnd::wndTopMost),0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); + + //if you want multiline tooltip, you must add the following line (note that this represent the max tooltip width in pixel) + m_wndToolTip.SendMessage(TTM_SETMAXTIPWIDTH, 0, 500); + */ +} diff --git a/usr/Src/old/Core/IParameter.cpp b/usr/Src/old/Core/IParameter.cpp new file mode 100644 index 0000000..2e81cc1 --- /dev/null +++ b/usr/Src/old/Core/IParameter.cpp @@ -0,0 +1,796 @@ +#include "StdAfx.h" +#include "vtPhysXAll.h" + +#include "IParameter.h" + +#include "vtStructHelper.h" + + +static IParameter* gIPar = NULL; + +#include "pMisc.h" + +int IParameter::copyTo(pVehicleBrakeTable& dst,CKParameter*src) +{ + if (!src)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + for (int i = 0 ; i < BREAK_TABLE_ENTRIES ; i ++) + dst.brakeEntries[i] = GetValueFromParameterStruct(src,i); + + return true; + + +} +int IParameter::copyTo(CKParameter*dst,pWheelDescr src) +{ + + if (!dst)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,E_WD_SPRING_BIAS,src.springBias,false); + SetParameterStructureValue(dst,E_WD_SPRING_RES,src.springRestitution,false); + SetParameterStructureValue(dst,E_WD_DAMP,src.springDamping,false); + SetParameterStructureValue(dst,E_WD_MAX_BFORCE,src.maxBrakeForce,false); + SetParameterStructureValue(dst,E_WD_FFRONT,src.frictionToFront,false); + SetParameterStructureValue(dst,E_WD_FSIDE,src.frictionToSide,false); + SetParameterStructureValue(dst,E_WD_FLAGS,src.wheelFlags,false); + SetParameterStructureValue(dst,E_WD_INVERSE_WHEEL_MASS,src.inverseWheelMass,false); + SetParameterStructureValue(dst,E_WD_SFLAGS,src.wheelShapeFlags,false); + SetParameterStructureValue(dst,E_WD_SUSPENSION,src.wheelSuspension,false); + + + + +} + +int IParameter::copyTo(pWheelDescr& dst,CKParameter*src) +{ + int result = 1; + if (!src) + { + return NULL; + } + using namespace vtTools::ParameterTools; + + dst.wheelSuspension = GetValueFromParameterStruct(src,E_WD_SUSPENSION); + dst.springRestitution= GetValueFromParameterStruct(src,E_WD_SPRING_RES); + dst.springBias = GetValueFromParameterStruct(src,E_WD_SPRING_BIAS); + dst.springDamping= GetValueFromParameterStruct(src,E_WD_DAMP); + + dst.maxBrakeForce= GetValueFromParameterStruct(src,E_WD_MAX_BFORCE); + dst.frictionToSide= GetValueFromParameterStruct(src,E_WD_FSIDE); + dst.frictionToFront= GetValueFromParameterStruct(src,E_WD_FFRONT); + + CKParameterOut *pOld = GetParameterFromStruct(src,E_WD_INVERSE_WHEEL_MASS); + if (pOld) + { + if (pOld->GetGUID() == CKPGUID_FLOAT) + { + dst.inverseWheelMass= GetValueFromParameterStruct(src,E_WD_INVERSE_WHEEL_MASS); + } + + if (pOld->GetGUID() == CKPGUID_INT) + { + dst.wheelApproximation= GetValueFromParameterStruct(src,E_WD_INVERSE_WHEEL_MASS); + } + } + + + + dst.wheelFlags= (WheelFlags)GetValueFromParameterStruct(src,E_WD_FLAGS); + dst.wheelShapeFlags=(WheelShapeFlags) GetValueFromParameterStruct(src,E_WD_SFLAGS); + + + CKParameterOut *parLatFunc = GetParameterFromStruct(src,E_WD_LAT_FUNC); + CKParameterOut *parLongFunc = GetParameterFromStruct(src,E_WD_LONG_FUNC); + + + + /************************************************************************/ + /* XML Setup ? */ + /************************************************************************/ + int xmlLinkId= GetValueFromParameterStruct(src,E_WD_XML); + bool wIsXML=false; + bool latIsXML= false; + bool longIsXML=false; + + XString nodeName; + if ( xmlLinkId !=0 ) + { + nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_WHEEL_SETTINGS,xmlLinkId); + pFactory::Instance()->loadWheelDescrFromXML(dst,nodeName.CStr(),pFactory::Instance()->getDefaultDocument()); + wIsXML =true; + if (!dst.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Wheel Description was invalid"); + } + if (dst.latFunc.xmlLink!=0) + { + latIsXML=true; + } + + if (dst.longFunc.xmlLink!=0) + { + longIsXML=true; + } + } + + if (!latIsXML) + { + dst.latFunc = pFactory::Instance()->createTireFuncFromParameter(parLatFunc); + } + + if (!longIsXML) + { + dst.longFunc= pFactory::Instance()->createTireFuncFromParameter(parLongFunc); + } + + if (wIsXML) + { + IParameter::Instance()->copyTo((CKParameterOut*)src,dst); + + } + if (longIsXML) + { + pFactory::Instance()->copyTo(GetParameterFromStruct(src,E_WD_LONG_FUNC),dst.longFunc); + } + + if (latIsXML) + { + pFactory::Instance()->copyTo(GetParameterFromStruct(src,E_WD_LAT_FUNC),dst.latFunc); + } + + return result; +} +int IParameter::copyTo(pConvexCylinderSettings& dst,CKParameter*src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + pFactory::Instance()->copyTo(dst.radius, GetParameterFromStruct(src,PS_CC_RADIUS_REFERENCED_VALUE),true); + pFactory::Instance()->copyTo(dst.height, GetParameterFromStruct(src,PS_CC_HEIGHT_REFERENCED_VALUE),true); + + dst.approximation = GetValueFromParameterStruct(src,PS_CC_APPROXIMATION); + dst.buildLowerHalfOnly = GetValueFromParameterStruct(src,PS_CC_BUILD_LOWER_HALF_ONLY); + dst.convexFlags = (pConvexFlags)GetValueFromParameterStruct(src,PS_CC_EXTRA_SHAPE_FLAGS); + + + //---------------------------------------------------------------- + // + // Calculate Forward Axis, optionally referenced by an entity + // + dst.forwardAxis = GetValueFromParameterStruct(src,PS_CC_FORWARD_AXIS); + dst.forwardAxisRef = (CK3dEntity*)GetPMan()->m_Context->GetObject(GetValueFromParameterStruct(src,PS_CC_FORWARD_AXIS_REF)); + if (dst.forwardAxisRef) + { + VxVector dir,up,right; + dst.forwardAxisRef->GetOrientation(&dir,&up,&right); + dst.forwardAxisRef->TransformVector(&dst.forwardAxis,&dir); + dst.forwardAxis.Normalize(); + } + + + + //---------------------------------------------------------------- + // + // Calculate Down Axis, optionally referenced by an entity + // + dst.downAxis = GetValueFromParameterStruct(src,PS_CC_DOWN_AXIS); + dst.downAxisRef = (CK3dEntity*)GetPMan()->m_Context->GetObject(GetValueFromParameterStruct(src,PS_CC_DOWN_AXIS_REF)); + if (dst.downAxisRef) + { + VxVector dir,up,right; + dst.downAxisRef->GetOrientation(&dir,&up,&right); + dst.downAxisRef->TransformVector(&dst.downAxis,&up); + dst.downAxis.Normalize(); + } + + + //---------------------------------------------------------------- + // + // Calculate Right Axis, optionally referenced by an entity + // + dst.rightAxis = GetValueFromParameterStruct(src,PS_CC_RIGHT_AXIS); + dst.rightAxisRef = (CK3dEntity*)GetPMan()->m_Context->GetObject(GetValueFromParameterStruct(src,PS_CC_RIGHT_AXIS_REF)); + if (dst.rightAxisRef) + { + VxVector dir,up,right; + dst.rightAxisRef->GetOrientation(&dir,&up,&right); + dst.rightAxisRef->TransformVector(&dst.rightAxis,&right); + dst.rightAxis.Normalize(); + } + + + + + + return 1; +} + +int IParameter::copyTo(pMassSettings& dst,CKParameter*src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + dst.newDensity= GetValueFromParameterStruct(src,PS_BM_DENSITY,false); + dst.totalMass= GetValueFromParameterStruct(src,PS_BM_TOTAL_MASS,false); + dst.localPosition = GetValueFromParameterStruct(src,PS_BM_PIVOT_POS,false); + dst.localOrientation = GetValueFromParameterStruct(src,PS_BM_PIVOT_ROTATION,false); + dst.massReference= GetValueFromParameterStruct(src,PS_BM_PIVOT_REFERENCE,false); + return 1; +} + +int IParameter::copyTo(pPivotSettings& dst,CKParameter*src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + dst.localPosition = GetValueFromParameterStruct(src,PS_BP_LINEAR,false); + dst.localOrientation = GetValueFromParameterStruct(src,PS_BP_ANGULAR,false); + dst.pivotReference = GetValueFromParameterStruct(src,PS_BP_REFERENCE,false); + + + return 1; + +} + +int IParameter::copyTo(pObjectDescr&dst,CK3dEntity*src,int copyFlags) +{ + + pRigidBody *srcBody = GetPMan()->getBody(src); + NxActor *actor = NULL; + pObjectDescr*initDescr = NULL; + NxShape *mainShape= NULL; + + //---------------------------------------------------------------- + // + // sanity checks + // + if (!src || !srcBody || !srcBody->getMainShape()) + return 0; + + + initDescr = srcBody->getInitialDescription(); + actor = srcBody->getActor(); + mainShape = srcBody->getMainShape(); + + + + if (!initDescr || !actor ) + return 0; + + + //---------------------------------------------------------------- + // + // general settings + // + dst.hullType = (HullType)vtAgeia::getHullTypeFromShape(srcBody->getMainShape()); + + + srcBody->recalculateFlags(0); + dst.flags = (BodyFlags)srcBody->getFlags(); + dst.worlReference = srcBody->getWorld()->getReference()->GetID(); + dst.density = initDescr->density; + dst.mask = initDescr->mask; + + + //---------------------------------------------------------------- + // + // specific override : optimization + // + if ( (copyFlags & PB_CF_OPTIMIZATION) ) + { + + //---------------------------------------------------------------- + // + // damping + sleeping + // + dst.optimization.angDamping = actor->getAngularDamping(); + dst.optimization.linDamping = actor->getLinearDamping(); + dst.optimization.linSleepVelocity = actor->getSleepLinearVelocity(); + dst.optimization.angSleepVelocity = actor->getSleepAngularVelocity(); + dst.optimization.sleepEnergyThreshold = actor->getSleepEnergyThreshold(); + + //---------------------------------------------------------------- + // + // transformation flags + // + + dst.optimization.transformationFlags = (BodyLockFlags)srcBody->getTransformationsLockFlags(); + + + dst.optimization.solverIterations = actor->getSolverIterationCount(); + dst.optimization.dominanceGroup = actor->getDominanceGroup(); + dst.optimization.compartmentGroup = initDescr->optimization.compartmentGroup; + } + + //---------------------------------------------------------------- + // + // specific override : collision + // + //if ( (dst.mask & OD_Optimization ) ) + if ( (copyFlags & PB_CF_COLLISION ) ) + { + dst.collisionGroup = mainShape->getGroup(); + + NxGroupsMask nxMask = mainShape->getGroupsMask(); + dst.groupsMask.bits0 = nxMask.bits0; + dst.groupsMask.bits1 = nxMask.bits1; + dst.groupsMask.bits2 = nxMask.bits2; + dst.groupsMask.bits3 = nxMask.bits3; + dst.skinWidth = mainShape->getSkinWidth(); + } + + //---------------------------------------------------------------- + // + // specific override : ccd + // + //if ( (dst.mask & OD_CCD) ) + if ( (copyFlags & OD_CCD ) && (dst.mask & OD_CCD) ) + { + + dst.ccd.flags = initDescr->ccd.flags; + dst.ccd.meshReference = initDescr->ccd.meshReference; + dst.ccd.motionThresold = initDescr->ccd.motionThresold; + dst.ccd.scale = initDescr->ccd.scale; + } + + //---------------------------------------------------------------- + // + // specific override : capsule + // + if ( (copyFlags && OD_Capsule) && (dst.mask & OD_Capsule) ) + dst.capsule = initDescr->capsule; + + //---------------------------------------------------------------- + // + // specific override : convex cylinder + // + if ( (copyFlags && OD_ConvexCylinder) && (dst.mask & OD_ConvexCylinder) ) + dst.convexCylinder = initDescr->convexCylinder; + + //---------------------------------------------------------------- + // + // specific override : material + // + if ( (copyFlags && OD_Material) && (dst.mask & OD_Material) ) + dst.material = initDescr->material; + + //---------------------------------------------------------------- + // + // specific override : pivot + // + if ( (copyFlags && OD_Pivot) ) + { + //dst.pivotOffsetAngular = getFrom(mainShape->getLocalOrientation() ); + dst.pivotOffsetLinear = getFrom( mainShape->getLocalPosition() ); + //dst.pivotOffsetReference= initDescr->pivotOffsetReference; + } + + if ( (copyFlags && PB_CF_MASS_SETTINGS) ) + { + //dst.pivotOffsetAngular = getFrom(mainShape->getLocalOrientation() ); + dst.massOffsetLinear = getFrom(actor->getCMassLocalPosition()); + //dst.pivotOffsetReference= initDescr->pivotOffsetReference; + } + + //---------------------------------------------------------------- + // + // correct data mask : + // + + DWORD mask = (DWORD)(dst.mask); + mask &=~((OD_Pivot)); + + + + if ( !(copyFlags & PB_CF_PIVOT_SETTINGS) ) + mask &=~((OD_Pivot)); + + if ( !(copyFlags & PB_CF_MASS_SETTINGS) ) + mask &=~(OD_Mass); + + if ( !(copyFlags & PB_CF_OPTIMIZATION) ) + mask &=~(OD_Optimization); + + if ( !(copyFlags & PB_CF_COLLISION) ) + mask &=~(OD_Collision); + + if ( !(copyFlags & PB_CF_CCD) ) + mask &=~(OD_CCD); + + if ( !(copyFlags & PB_CF_CAPSULE) ) + mask &=~(OD_Capsule); + + + if ( !(copyFlags & PB_CF_CONVEX_CYLINDER) ) + mask&=~(OD_ConvexCylinder); + + if ( !(copyFlags & PB_CF_MATERIAL) ) + mask &=~(OD_Material); + + return 1; + +} + +int IParameter::copyTo(pCapsuleSettingsEx& dst,CKParameter*src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(src); + #endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + pFactory::Instance()->copyTo(dst.radius, GetParameterFromStruct(src,PS_BCAPSULE_RADIUS_REFERENCED_VALUE),false); + pFactory::Instance()->copyTo(dst.height, GetParameterFromStruct(src,PS_PCAPSULE_HEIGHT_REFERENCED_VALUE),false); + + return 1; +} + +int IParameter::copyTo(pCCDSettings& dst,CKParameter*src) +{ + //---------------------------------------------------------------- + // + // Sanity checks + // +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + //---------------------------------------------------------------- + + // + // general + // + + dst.flags = GetValueFromParameterStruct(src,PS_B_CCD_FLAGS,false); + dst.motionThresold = GetValueFromParameterStruct(src,PS_B_CCD_MOTION_THRESHOLD,false); + dst.scale= GetValueFromParameterStruct(src,PS_B_CCD_SCALE,false); + dst.meshReference= GetValueFromParameterStruct(src,PS_B_CCD_MESH_REFERENCE,false); + + + return 1; +} + +int IParameter::copyTo(pOptimization& dst,CKParameter*src) +{ + + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(src); + #endif + + using namespace vtTools; + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + //---------------------------------------------------------------- + // + // Retrieve all sub parameters : + // + CKParameterOut *parSleeping = GetParameterFromStruct(src,PS_BO_SLEEPING); + CKParameterOut *parDamping = GetParameterFromStruct(src,PS_BO_DAMPING); + + //---------------------------------------------------------------- + // + // general + // + + dst.transformationFlags = (BodyLockFlags) GetValueFromParameterStruct(src,PS_BO_LOCKS,false); + + dst.solverIterations = GetValueFromParameterStruct(src,PS_BO_SOLVER_ITERATIONS,false); + dst.compartmentGroup = GetValueFromParameterStruct(src,PS_BO_COMPARTMENT_ID,false); + dst.dominanceGroup = GetValueFromParameterStruct(src,PS_BO_DOMINANCE_GROUP,false); + + //---------------------------------------------------------------- + // + // Sleeping + // + dst.angSleepVelocity = GetValueFromParameterStruct(parSleeping,PS_BS_ANGULAR_SLEEP,false); + dst.linSleepVelocity = GetValueFromParameterStruct(parSleeping,PS_BS_LINEAR_SLEEP,false); + dst.sleepEnergyThreshold = GetValueFromParameterStruct(parSleeping,PS_BS_THRESHOLD,false); + + //---------------------------------------------------------------- + // + // Damping + // + dst.angDamping = GetValueFromParameterStruct(parDamping,PS_BD_ANGULAR,false); + dst.linDamping= GetValueFromParameterStruct(parDamping,PS_BD_LINEAR,false); + + return 1; + +} + +int IParameter::copyTo(CKParameter*dst,pObjectDescr*src) +{ + + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(dst); + assert(src); + #endif + + + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + //---------------------------------------------------------------- + // + // Retrieve all sub parameters : + // + CKParameterOut *parBCommon = GetParameterFromStruct(dst,PS_COMMON_SETTINGS); + CKParameterOut *parBCollision = GetParameterFromStruct(dst,PS_COLLISION_SETTINGS); + //CKParameterOut *parBCCD = GetParameterFromStruct(parBCollision,PS_BC_CCD_SETUP); + CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); + + #ifdef _DEBUG + assert(parBCommon); + //assert(parBPivot); + //assert(parBCCD); + assert(parBCollision); + #endif + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // transfer + // + + + //---------------------------------------------------------------- + // + // common + // + SetParameterStructureValue(parBCommon,PS_BC_HULL_TYPE,src->hullType); + SetParameterStructureValue(parBCommon,PS_BC_DENSITY,src->density); + SetParameterStructureValue(parBCommon,PS_BC_FLAGS,src->flags); + SetParameterStructureValue(parBCommon,PS_BC_WORLD,src->worlReference); + + //---------------------------------------------------------------- + // + // XML + // + + //---------------------------------------------------------------- + // + // Collision + // + SetParameterStructureValue(parBCollision,PS_BC_GROUP,src->collisionGroup); + SetParameterStructureValue(parBCollision,PS_BC_SKINWITDH,src->skinWidth); + + + SetParameterStructureValue(parGroupsMask,0,src->groupsMask.bits0); + SetParameterStructureValue(parGroupsMask,1,src->groupsMask.bits1); + SetParameterStructureValue(parGroupsMask,2,src->groupsMask.bits2); + SetParameterStructureValue(parGroupsMask,3,src->groupsMask.bits3); + + //---------------------------------------------------------------- + // + // CCD + // + + /* + SetParameterStructureValue(parBCCD,PS_B_CCD_MOTION_THRESHOLD,src->ccdMotionThresold); + SetParameterStructureValue(parBCCD,PS_B_CCD_FLAGS,src->ccdFlags); + SetParameterStructureValue(parBCCD,PS_B_CCD_MESH_REFERENCE,src->ccdMeshReference); + SetParameterStructureValue(parBCCD,PS_B_CCD_SCALE,src->ccdScale); + + */ + return 1; + +} + + +int IParameter::copyTo(pCollisionSettings &dst,CKParameter*src) +{ + + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(src); + #endif + + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + CKParameterOut *parGroupsMask = GetParameterFromStruct(src,PS_BC_GROUPSMASK); + + // Sanity checks + #ifdef _DEBUG + assert(parGroupsMask); + #endif + //---------------------------------------------------------------- + // + // Collision Setup + // + dst.collisionGroup = GetValueFromParameterStruct(src,PS_BC_GROUP,false); + + // + dst.groupsMask.bits0 = GetValueFromParameterStruct(parGroupsMask,0); + dst.groupsMask.bits1 = GetValueFromParameterStruct(parGroupsMask,1); + dst.groupsMask.bits2 = GetValueFromParameterStruct(parGroupsMask,2); + dst.groupsMask.bits3 = GetValueFromParameterStruct(parGroupsMask,3); + + dst.skinWidth = GetValueFromParameterStruct(src,PS_BC_SKINWITDH,false); + return 1; +} + +int IParameter::copyTo(pObjectDescr*dst,CKParameter*src) +{ + + //---------------------------------------------------------------- + // + // Sanity checks + // + #ifdef _DEBUG + assert(dst); + assert(src); + #endif + + //---------------------------------------------------------------- + // + // Possible this function is invoked due the loading of a cmo file whilst core is not started yet : + // + CKStructHelper sHelper(src); + if(sHelper.GetMemberCount() == 0) + return 0; + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + //---------------------------------------------------------------- + // + // Retrieve all sub parameters : + // + CKParameterOut *parBCommon = GetParameterFromStruct(src,PS_COMMON_SETTINGS); + //CKParameterOut *parBPivot = GetParameterFromStruct(src,PS_PIVOT); + //CKParameterOut *parBMass = GetParameterFromStruct(src,PS_MASS); + CKParameterOut *parBCollision = GetParameterFromStruct(src,PS_COLLISION_SETTINGS); + //CKParameterOut *parBCCD = GetParameterFromStruct(parBCollision,PS_BC_CCD_SETUP); + CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); + + #ifdef _DEBUG + assert(parBCommon); + //assert(parBPivot); + //assert(parBMass); + assert(parBCollision); + #endif + + + //---------------------------------------------------------------- + // + // Common settings as hull type, body flags, ... + // + + dst->hullType =(HullType)GetValueFromParameterStruct(parBCommon,PS_BC_HULL_TYPE,false); + dst->flags = (BodyFlags)GetValueFromParameterStruct(parBCommon,PS_BC_FLAGS,false); + /*dst->transformationFlags = GetValueFromParameterStruct(parBCommon,PS_BC_TFLAGS,false);*/ + dst->worlReference = GetValueFromParameterStruct(parBCommon,PS_BC_WORLD,false); + dst->density = GetValueFromParameterStruct(parBCommon,PS_BC_DENSITY,false); + + + //---------------------------------------------------------------- + // + // Pivot Offset + // + + /* + dst->pivotOffsetLinear = GetValueFromParameterStruct(parBPivot,PS_BP_LINEAR,false); + dst->pivotOffsetAngular = GetValueFromParameterStruct(parBPivot,PS_BP_ANGULAR,false); + + //---------------------------------------------------------------- + // + // Mass Offset + // + + dst->density = GetValueFromParameterStruct(parBMass,PS_BM_DENSITY,false); + dst->totalMass = GetValueFromParameterStruct(parBMass,PS_BM_TOTAL_MASS,false); + dst->massOffsetLinear = GetValueFromParameterStruct(parBMass,PS_BM_PIVOT_POS,false); + */ + //dst->massOffsetAngular = GetValueFromParameterStruct(parBMass,PS_BM_PIVOT_ROTATION,false); + + + + //---------------------------------------------------------------- + // + // Collision Setup + // + dst->collisionGroup = GetValueFromParameterStruct(parBCollision,PS_BC_GROUP,false); + + // + dst->groupsMask.bits0 = GetValueFromParameterStruct(parGroupsMask,0); + dst->groupsMask.bits1 = GetValueFromParameterStruct(parGroupsMask,1); + dst->groupsMask.bits2 = GetValueFromParameterStruct(parGroupsMask,2); + dst->groupsMask.bits3 = GetValueFromParameterStruct(parGroupsMask,3); + + dst->skinWidth = GetValueFromParameterStruct(parBCollision,PS_BC_SKINWITDH,false); + + dst->mask << OD_Collision; + + //---------------------------------------------------------------- + // + // CCD Settings + // + /*dst->ccdFlags = GetValueFromParameterStruct(parBCCD,PS_B_CCD_FLAGS,false); + dst->ccdMotionThresold= GetValueFromParameterStruct(parBCCD,PS_B_CCD_MOTION_THRESHOLD,false); + dst->ccdScale = GetValueFromParameterStruct(parBCCD,PS_B_CCD_SCALE,false); + dst->ccdMeshReference = GetValueFromParameterStruct(parBCCD,PS_B_CCD_MESH_REFERENCE,false); + */ + + + //---------------------------------------------------------------- + // + // Misc + // + dst->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + + return 1; +} +IParameter* IParameter::Instance() +{ + if (!gIPar) + { + gIPar = new IParameter(GetPMan()); + } + return gIPar; +} + + + +IParameter::IParameter(PhysicManager*_pManager) : mManager(_pManager) +{ + gIPar = this; + +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/CKPhysicManager.cpp b/usr/Src/old/Core/Manager/CKPhysicManager.cpp new file mode 100644 index 0000000..a702db9 --- /dev/null +++ b/usr/Src/old/Core/Manager/CKPhysicManager.cpp @@ -0,0 +1,9 @@ +#include +#include "vtPhysXAll.h" + + + +CKPhysicManager::CKPhysicManager(CKContext *Context,CKGUID guid,char* name):CKBaseManager(Context,GUID_MODULE_MANAGER,"PhysicManager") +{ + +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManagerAttributeRegistry.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManagerAttributeRegistry.cpp new file mode 100644 index 0000000..817fcc7 --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManagerAttributeRegistry.cpp @@ -0,0 +1,117 @@ +#include +#include "vtPhysXAll.h" + +#include "vtAttributeHelper.h" + +void PhysicManager::_checkObjectsByAttribute() +{ + + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;//(sizeof(*getRegistrationTable()) / sizeof((getRegistrationTable())[0])); + for (int fIndex = 0 ; fIndex < sizeJFuncMap ; fIndex ++) + { + + std::vectorattributeIdList; + pFactory::Instance()->findAttributeIdentifiersByGuid(getRegistrationTable()[fIndex].guid,attributeIdList); + int attCount = attributeIdList.size(); + + for (int i = 0 ; i < attCount ; i++ ) + { + int currentAttType = attributeIdList.at(i); + const XObjectPointerArray& Array = attman->GetAttributeListPtr( attributeIdList.at(i) ); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + CK3dEntity *target = static_cast(*it); + if (target) + { + XString error; + error.Format("Registering :%s with %s",target->GetName(),attman->GetAttributeNameByType(currentAttType)); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.CStr() ); + (*getRegistrationTable()[fIndex].rFunc)(target,currentAttType,true,false); + } + } + } + } +} + +void PhysicManager::_RegisterAttributeCallbacks() +{ + if (!getAttributeFunctions().Size()) + { + return; + } + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + AttributeFunctionArrayIteratorType it = getAttributeFunctions().Begin(); + + while(it != getAttributeFunctions().End()) + { + ObjectRegisterFunction myFn = (ObjectRegisterFunction)*it; + if (myFn) + { + attman->SetAttributeCallbackFunction(it.GetKey(),PObjectAttributeCallbackFunc,myFn); + } + it++; + } +} + +void PhysicManager::cleanAttributePostObjects() +{ + using namespace vtTools::ParameterTools; + + if (!getAttributePostObjects().Size()) + return; + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + PostRegistrationArrayIteratorType it = getAttributePostObjects().Begin(); + while(it != getAttributePostObjects().End()) + { + pAttributePostObject& post = *it; + CK3dEntity *refObject = static_cast(GetPMan()->m_Context->GetObject(post.objectId)); + if (refObject) + { + + ObjectRegisterFunction regFn = (ObjectRegisterFunction)post.func; + if (regFn) + { + (*regFn)(refObject,post.attributeID,true,false); + } + } + it++; + } + int s = getAttributePostObjects().Size(); + + getAttributePostObjects().Clear(); +} + +void PhysicManager::populateAttributeFunctions() +{ + + getAttributeFunctions().Clear(); + + int sizeJFuncMap = ATT_FUNC_TABLE_SIZE;// (sizeof(*getRegistrationTable()) / sizeof(ObjectRegistration)); + for (int fIndex = 0 ; fIndex < sizeJFuncMap ; fIndex ++) + { + #ifdef _DEBUG + + //XString _errorStr; + //getRegistrationTable()[fIndex].rFunc. + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.Str()); + + #endif + + std::vectorattributeIdList; + pFactory::Instance()->findAttributeIdentifiersByGuid(getRegistrationTable()[fIndex].guid,attributeIdList); + int attCount = attributeIdList.size(); + for (int i = 0 ; i < attCount ; i++ ) + { + int currentAttType = attributeIdList.at(i); + getAttributeFunctions().Insert(currentAttType,getRegistrationTable()[fIndex].rFunc); + } + } +} +ObjectRegistration*PhysicManager::getRegistrationTable() +{ + return attributeFunctionMap; +} diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManagerRegisterParameterOps.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManagerRegisterParameterOps.cpp new file mode 100644 index 0000000..c91a319 --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManagerRegisterParameterOps.cpp @@ -0,0 +1,962 @@ +#include +#include "vtPhysXAll.h" + + + + +#define PARAMETER_OP_TYPE_STRING_TO_ATT CKGUID(0x3678447e,0x30362a74) + +#define PARAM_OP_TYPE_CIS_INI_COLLISION CKGUID(0x4ec2349b,0x5edf7dd8) +#define PARAM_OP_TYPE_CHAS_CONTACT CKGUID(0x3ed57b83,0x47ad145f) +#define PARAM_OP_TYPE_CRAY_COLLISION CKGUID(0x53425880,0x1b540c2b) + +#define PARAM_OP_TYPE_CGROUP_COLLISION CKGUID(0x7b762a1a,0x702e471c) + +#define PARAM_OP_RC_ANY_BOUNDS CKGUID(0x31e415e2,0x61e42210) +#define PARAM_OP_RC_ANY_SHAPE CKGUID(0x62943427,0x31877a8f) + + + +void ParamOpRayCastAnyShape(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + using namespace vtTools::ParameterTools; + using namespace vtTools::BehaviorTools; + + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CK_ID targetID = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_WORLD,false); + CK_ID oriRef = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_ORI_REF,false); + CK_ID dirRef = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_DIR_REF,false); + + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(targetID); + if (!world) + { + int result = false; + res->SetValue(&result); + return; + } + + CK3dEntity *rayOriRef= (CK3dEntity *)GetPMan()->m_Context->GetObject(oriRef); + CK3dEntity *rayDirRef= (CK3dEntity *) GetPMan()->m_Context->GetObject(dirRef); + + VxVector ori = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_ORI,false); + VxVector dir = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_DIR,false); + + VxVector oriOut = ori; + if (rayOriRef) + { + rayOriRef->Transform(&oriOut,&ori); + } + + //dir : + VxVector dirOut = dir; + if (rayDirRef) + { + VxVector dir,up,right; + rayDirRef->GetOrientation(&dir,&up,&right); + rayDirRef->TransformVector(&dirOut,&up); + } + + int groups = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_GROUPS,false); + float length = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_LENGTH,false); + int types = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_SHAPES_TYPES,false); + + + CK_ID* paramids = static_cast(p1->GetReadDataPtr()); + CKParameterOut* maskP = static_cast(p1->GetCKContext()->GetObject(paramids[E_RC_GROUPS_MASK])); + + NxGroupsMask mask; + mask.bits0 = GetValueFromParameterStruct(maskP,0); + mask.bits1 = GetValueFromParameterStruct(maskP,1); + mask.bits2 = GetValueFromParameterStruct(maskP,2); + mask.bits3 = GetValueFromParameterStruct(maskP,3); + + NxRay ray; + ray.orig = getFrom(oriOut); + ray.dir = getFrom(dirOut); + + + //NxShape **shapes = new NxShape*[2]; + + NxU32 total = world->getScene()->getTotalNbShapes();//world->getScene()->getNbDynamicShapes() + world->getScene()->getNbStaticShapes(); + //NxShape** shapes = NULL ;//(NxShape**)NxAlloca(nbShapes*sizeof(NxShape*)); + + NxShape** shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); + for (NxU32 i = 0; i < total; i++) shapes[i] = NULL; + + //NxShape **shapes = NULL; + int result = world->getScene()->raycastAnyShape(ray,(NxShapesType)types,groups,length,&mask,shapes); + + NxShape *s = shapes[0]; + if (s) + { + pSubMeshInfo *sInfo = static_cast(s->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + CK_ID id = obj->GetID(); + res->SetValue(&id); + //beh->SetOutputParameterObject(bbO_Shape,obj); + } + + } + + } + + + //res->SetValue(&result); + return; + } + + +} + + +void ParamOpRayCastAnyBounds(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + using namespace vtTools::ParameterTools; + using namespace vtTools::BehaviorTools; + + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CK_ID targetID = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_WORLD,false); + CK_ID oriRef = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_ORI_REF,false); + CK_ID dirRef = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_DIR_REF,false); + + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + + ////////////////////////////////////////////////////////////////////////// + // the world : + pWorld *world=GetPMan()->getWorld(targetID); + if (!world) + { + int result = false; + res->SetValue(&result); + return; + } + + CK3dEntity *rayOriRef= (CK3dEntity *)GetPMan()->m_Context->GetObject(oriRef); + CK3dEntity *rayDirRef= (CK3dEntity *) GetPMan()->m_Context->GetObject(dirRef); + + VxVector ori = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_ORI,false); + VxVector dir = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_DIR,false); + + VxVector oriOut = ori; + if (rayOriRef) + { + rayOriRef->Transform(&oriOut,&ori); + } + + //dir : + VxVector dirOut = dir; + if (rayDirRef) + { + VxVector dir,up,right; + rayDirRef->GetOrientation(&dir,&up,&right); + rayDirRef->TransformVector(&dirOut,&up); + } + + int groups = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_GROUPS,false); + float length = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_LENGTH,false); + int types = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_RC_SHAPES_TYPES,false); + + + CK_ID* paramids = static_cast(p1->GetReadDataPtr()); + CKParameterOut* maskP = static_cast(p1->GetCKContext()->GetObject(paramids[E_RC_GROUPS_MASK])); + + NxGroupsMask mask; + mask.bits0 = GetValueFromParameterStruct(maskP,0); + mask.bits1 = GetValueFromParameterStruct(maskP,1); + mask.bits2 = GetValueFromParameterStruct(maskP,2); + mask.bits3 = GetValueFromParameterStruct(maskP,3); + + NxRay ray; + ray.orig = getFrom(oriOut); + ray.dir = getFrom(dirOut); + + int result = world->getScene()->raycastAnyBounds(ray,(NxShapesType)types,groups,length,&mask); + + res->SetValue(&result); + return; + + + + + } + + +} + + + + + + + +#define PARAM_OP_TYPE_MGET_SFRICTION CKGUID(0x58566e7b,0x494f208a) +#define PARAM_OP_TYPE_MGET_SFRICTIONV CKGUID(0x7af723af,0x7e222884) +#define PARAM_OP_TYPE_MGET_SDFRICTION CKGUID(0x10733925,0x77c37dba) +#define PARAM_OP_TYPE_MGET_SDFRICTIONV CKGUID(0x29131ba,0x3b2a6f07) +#define PARAM_OP_TYPE_MGET_ANIS CKGUID(0x255256df,0x61fe2f77) +#define PARAM_OP_TYPE_MGET_FMODE CKGUID(0x321f0335,0x589576df) +#define PARAM_OP_TYPE_MGET_RMODE CKGUID(0x1cb07645,0x79ff1329) +#define PARAM_OP_TYPE_MGET_XML_TYPE CKGUID(0x6fea2100,0x6667545b) +#define PARAM_OP_TYPE_MGET_RES CKGUID(0x41702512,0x78c48ca) + + +#define PARAM_OP_TYPE_MSET_SFRICTION CKGUID(0x2f2e1071,0x2d4623ec) +#define PARAM_OP_TYPE_MSET_SFRICTIONV CKGUID(0x31940b2a,0x67f43440) +#define PARAM_OP_TYPE_MSET_SDFRICTION CKGUID(0x205b0164,0x39d626d0) +#define PARAM_OP_TYPE_MSET_SDFRICTIONV CKGUID(0x11f36b7a,0x7877377b) +#define PARAM_OP_TYPE_MSET_ANIS CKGUID(0x36565c47,0x46002830) +#define PARAM_OP_TYPE_MSET_FMODE CKGUID(0x4ddb7828,0x4d111b71) +#define PARAM_OP_TYPE_MSET_RMODE CKGUID(0x5d2315b7,0x2cb834f3) + + +void ParamOpMGetF(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->staticFriction; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetDF(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->dynamicFriction; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetR(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->restitution; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),3,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetDFV(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->dynamicFrictionV; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),4,false); + } + } + res->SetValue(&value); +} + +void ParamOpMGetFV(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + float value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->staticFrictionV; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),5,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetA(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + VxVector value(0.0f); + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = getFrom(mDesrc->dirOfAnisotropy); + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),6,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetFMode(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + int value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->frictionCombineMode; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),7,false); + } + } + res->SetValue(&value); +} +////////////////////////////////////////////////////////////////////////// +void ParamOpMGetRMode(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + int index = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + int value = 0; + if (index !=0 && GetPMan()->getCurrentFactory()) + { + if (GetPMan()->getDefaultConfig()) + { + XString mName = vtAgeia::getEnumDescription(pm,VTE_XML_MATERIAL_TYPE,index); + NxMaterialDesc *mDesrc = pFactory::Instance()->createMaterialFromXML(mName.Str(),GetPMan()->getDefaultConfig()); + if (mDesrc) + { + value = mDesrc->restitutionCombineMode; + res->SetValue(&value); + delete mDesrc; + mDesrc = NULL; + return; + } + } + } + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),8,false); + } + } + res->SetValue(&value); +} +void ParamOpMGetXMat(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int value = 0; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} + + +#define PARAM_OP_TYPE_BGET_RESTITUTION CKGUID(0x58566e7b,0x494f208a) + + +void ParamOpStringToAdd(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CKAttributeManager *am = (CKAttributeManager*)context->GetAttributeManager(); + + //CKSTRING test = + CKParameter *p = p1->GetRealSource(); + + if (!p) { return; } + + CKSTRING test = vtTools::ParameterTools::GetParameterAsString(p); + if (!strlen(test))return; + + + XString aName; + XString aCat; + XString aType; + + XStringTokenizer tokizer(test, "|"); + const char*tok = NULL; + int nb = 0; + while ((tok=tokizer.NextToken(tok)) && nb < 3) + { + XString tokx(tok); + + switch (nb) + { + case 0: + aName = tokx.Str(); + break; + + case 1: + aCat= tokx.Str(); + break; + + case 2: + aType = tokx.Str(); + break; + } + nb++; + } + + CKAttributeType aIType = am->GetAttributeTypeByName(aName.Str()); + if (aIType!=-1) + { + res->SetValue(&aIType); + return; + } + + + CKGUID pType = pm->ParameterNameToGuid(aType.Str()); + CKParameterType pt = pm->ParameterGuidToType(pType); + if (pt==-1) + { + pType = CKPGUID_NONE; + } + + aIType = am->RegisterNewAttributeType(aName.Str(),pType,CKCID_OBJECT); + + if (aCat.Length()) + { + am->AddCategory(aCat.Str()); + am->SetAttributeCategory(aIType,aCat.Str()); + } + + + res->SetValue(&aIType); + +} + +void PhysicManager::_RegisterParameterOperations() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + + _RegisterParameterOperationsBody(); + _RegisterParameterOperationsJoint(); + _RegisterParameterOperationsVehicle(); + + + pm->RegisterOperationType(PARAMETER_OP_TYPE_STRING_TO_ATT, "convert"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_STRING_TO_ATT,CKPGUID_ATTRIBUTE,CKPGUID_STRING,CKPGUID_NONE,ParamOpStringToAdd); + + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_RMODE, "pMgRMode"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_RMODE,VTE_MATERIAL_COMBINE_MODE,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetRMode); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_FMODE, "pMgFMode"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_FMODE,VTE_MATERIAL_COMBINE_MODE,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetFMode); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_RES, "pMgRestitution"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_RES,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetR); + + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SFRICTION, "pMgSFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SFRICTION,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetF); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SFRICTIONV, "pMgSVFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SFRICTIONV,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetFV); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SDFRICTION, "pMgDFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SDFRICTION,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetDF); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_SDFRICTIONV, "pMgDVFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_SDFRICTIONV,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetDFV); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_ANIS, "pMgAnis"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_ANIS,CKPGUID_VECTOR,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetA); + + pm->RegisterOperationType(PARAM_OP_TYPE_MGET_XML_TYPE, "pMgType"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_MGET_XML_TYPE,VTE_XML_MATERIAL_TYPE,VTS_MATERIAL,CKPGUID_NONE,ParamOpMGetXMat); + + + + /************************************************************************/ + /* */ + /************************************************************************/ + + + + + +/* + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FRICTION, "GetFriction"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FRICTION,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetFriction); + + + + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_LDAMP, "GetLinDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_LDAMP,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetLDamp); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_LDAMPT, "GetLinDampingT"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_LDAMPT,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetLDampT); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_ADAMP, "GetAngDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_ADAMP,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetADamp); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_ADAMPT, "GetAngDampingT"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_ADAMPT,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetADampT); + + pm->RegisterOperationType(PARAM_OP_TYPE_CIS_INI_COLLISION, "IsInCollision"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_CIS_INI_COLLISION,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpCIsInCollision); + + pm->RegisterOperationType(PARAM_OP_TYPE_CHAS_CONTACT, "HasContact"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_CHAS_CONTACT,CKPGUID_3DENTITY,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpCHasContact); + + pm->RegisterOperationType(PARAM_OP_TYPE_CRAY_COLLISION, "RayCollision"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_CRAY_COLLISION,CKPGUID_3DENTITY,CKPGUID_3DENTITY,CKPGUID_VECTOR4,ParamOpCRayCollision); + + pm->RegisterOperationType(PARAM_OP_TYPE_CGROUP_COLLISION, "IsCollision"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_CGROUP_COLLISION,CKPGUID_3DENTITY,CKPGUID_3DENTITY,CKPGUID_GROUP,ParamOpCIsInCollisionWithGroup); +*/ + + + + + + + + + + + pm->RegisterOperationType(PARAM_OP_RC_ANY_BOUNDS, "raycastAnyBounds"); + pm->RegisterOperationFunction(PARAM_OP_RC_ANY_BOUNDS,CKPGUID_BOOL,VTS_RAYCAST,CKPGUID_NONE,ParamOpRayCastAnyBounds); + + pm->RegisterOperationType(PARAM_OP_RC_ANY_SHAPE, "raycastAnyShape"); + pm->RegisterOperationFunction(PARAM_OP_RC_ANY_SHAPE,CKPGUID_3DENTITY,VTS_RAYCAST,CKPGUID_NONE,ParamOpRayCastAnyShape); + + + + + + + + + + +} + +/* +void ParamOpBGetLVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetAVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetTorque(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetFriction(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBisFixed(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetHType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpBGetLDamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetLDampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpBGetADamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpBGetADampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpCIsInCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpCHasContact(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpCRayCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpCIsInCollisionWithGroup(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +*/ + + +/* +void ParamOpCIsInCollisionWithGroup(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + ////////////////////////////////////////////////////////////////////////// + //retrieve the position ori : + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + ////////////////////////////////////////////////////////////////////////// + //retrieve the group + CK_ID targetIDG; + p2->GetValue(&targetIDG); + CKGroup *group = static_cast(context->GetObject(targetIDG)); + + + ////////////////////////////////////////////////////////////////////////// + //our result object : + CK3dEntity* result = NULL; + CK_ID id = 0; + + ////////////////////////////////////////////////////////////////////////// + //check our input object : + if (!ent) + { + res->SetValue(&id); + return; + } + + if (ent ) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + + if (world) + { + VxVector pos,normal; + float depth; + result = world->CIsInCollision(ent,group,pos,normal,depth); + if (result) + { + id = result->GetID(); + } + + } + } + res->SetValue(&id); +} + + +////////////////////////////////////////////////////////////////////////// +void ParamOpCRayCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + ////////////////////////////////////////////////////////////////////////// + //retrieve the position ori : + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + ////////////////////////////////////////////////////////////////////////// + //our result object : + CK3dEntity* result = NULL; + CK_ID id = 0; + + ////////////////////////////////////////////////////////////////////////// + //check our input object : + if (!ent) + { + res->SetValue(&id); + return; + } + + + ////////////////////////////////////////////////////////////////////////// + //we retrieve ori of the ray by a box : + VxVector4 inVec(0,0,0,0); + p2->GetValue(&inVec); + + VxVector oriOut(0,0,0); + + ////////////////////////////////////////////////////////////////////////// + //direction of the ray : + VxVector dirIn (inVec.x,inVec.y,inVec.z); + + pWorld *world=GetPMan()->getWorldByBody(ent); + + if (world) + { + VxVector pos,normal; + float depth; + result = world->CRayCollision(oriOut,ent,dirIn,ent,inVec.w,true,pos,normal); + if (result) + { + id = result->GetID(); + } + + } + res->SetValue(&id); +} +////////////////////////////////////////////////////////////////////////// +void ParamOpCHasContact(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + CK3dEntity* result = NULL; + CK_ID id = 0; + + if (ent ) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + + if (world) + { + VxVector pos,normal; + float depth; + result = world->CIsInCollision(ent,pos,normal,depth); + if (result) + { + id = result->GetID(); + } + + } + } + res->SetValue(&id); +} +////////////////////////////////////////////////////////////////////////// +void ParamOpCIsInCollision(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + CK_ID targetID2; + p2->GetValue(&targetID2); + CK3dEntity *ent2 = static_cast(context->GetObject(targetID2)); + + int result = 0; + + if (ent && ent2) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + pWorld *world2=GetPMan()->getWorldByBody(ent2); + if (world && world2 && world == world2) + { + VxVector pos,normal; + float depth; + result = world->CIsInCollision(ent,ent2,pos,normal,depth); + } + } + res->SetValue(&result); +} +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetFriction(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetFriction(); + res->SetValue(&vec); + } + } + } +} + + +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetLDamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetLinearDamping(); + res->SetValue(&vec); + } + } + } +} +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetLDampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetLinearDampingThreshold(); + res->SetValue(&vec); + } + } + } +} +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetADamp(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetLinearDamping(); + res->SetValue(&vec); + } + } + } +} +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetADampT(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->GetLinearDampingThreshold(); + res->SetValue(&vec); + } + } + } +} +*/ +////////////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterBodyParameters.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterBodyParameters.cpp new file mode 100644 index 0000000..0b43123 --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterBodyParameters.cpp @@ -0,0 +1,365 @@ +#include +#include "vtPhysXAll.h" +#include "vtStructHelper.h" +#include "vtAttributeHelper.h" + +#include "gConfig.h" + + +#define PHYSIC_JOINT_CAT "Physic Constraints" + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; + + +StructurMember bodyDamping[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Linear Damping","0.1"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Angular Damping","0.1"), +}; + +StructurMember bodySleeping[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Linear Sleep Velocity","0.1"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Angular Sleep Velocity","0.1"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Sleep Energy Threshold","0.1"), +}; + +StructurMember bodyXMLSetup[] = +{ + STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_SETTINGS_INTERN,"Internal","None"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_SETTINGS_EXTERN,"External","None"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS,"Import Flags","Stub"), +}; + +StructurMember bodyCCDSettings[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Motion Threshold","None"), + STRUCT_ATTRIBUTE(VTF_PHYSIC_CCD_FLAGS,"Flags","Stub"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Mesh Scale","1.0f"), + STRUCT_ATTRIBUTE(CKPGUID_BEOBJECT,"Shape Reference","None"), +}; + +StructurMember bodyCollisionsSettings[] = +{ + STRUCT_ATTRIBUTE(VTE_PHYSIC_BODY_COLL_GROUP,"Collisions Group","All"), + STRUCT_ATTRIBUTE(VTS_FILTER_GROUPS,"Group Mask","None"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Skin Width","-1.0"), + //STRUCT_ATTRIBUTE(VTS_PHYSIC_CCD_SETTINGS,"CCD Settings","None"), +}; + +StructurMember bodyCollisionsSetup[] = +{ + STRUCT_ATTRIBUTE(VTS_PHYSIC_COLLISIONS_SETTINGS,"Collisions Settings","None"), + //STRUCT_ATTRIBUTE(VTS_PHYSIC_CCD_SETTINGS,"CCD Settings","0"), +}; + + + +StructurMember bodyOptimistationSettings[] = +{ + STRUCT_ATTRIBUTE(VTF_BODY_TRANS_FLAGS,"Transformation Locks","None"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DAMPING_PARAMETER,"Damping Settings","None"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_SLEEP_SETTINGS,"Sleeping Settings","None"), + STRUCT_ATTRIBUTE(CKPGUID_INT,"Solver Iterations",""), + STRUCT_ATTRIBUTE(VTE_PHYSIC_DOMINANCE_GROUP,"Dominance Group",""), + STRUCT_ATTRIBUTE(CKPGUID_INT,"Compartment Id",""), +}; + +StructurMember bodyCommonSettings[] = +{ + STRUCT_ATTRIBUTE(VTE_COLLIDER_TYPE,"Hull Type","1"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Density","1"), + STRUCT_ATTRIBUTE(VTF_BODY_FLAGS,"Flags","Moving Object,World Gravity,Enabled,Collision"), +/* STRUCT_ATTRIBUTE(VTF_BODY_TRANS_FLAGS,"Transformation Locks",""),*/ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"World","pWorldDefault"), +}; + +StructurMember bodyGeomtryOverride[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Offset Linear","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_EULERANGLES,"Offset Angular","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Offset Reference",""), +}; + +StructurMember bodyMassSetup[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"New Density","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Total Mass","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Offset Linear","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_EULERANGLES,"Offset Angular","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Mass Offset Reference","0.0"), +}; + +StructurMember bodySetup[] = +{ + STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_XML_SETUP,"XML Links","0"), + STRUCT_ATTRIBUTE(VTF_PHYSIC_BODY_COMMON_SETTINGS,"Common Settings","0"), + /*STRUCT_ATTRIBUTE(VTS_PHYSIC_PIVOT_OFFSET,"Pivot","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_MASS_SETUP,"Mass Setup","0"),*/ + STRUCT_ATTRIBUTE(VTS_PHYSIC_COLLISIONS_SETTINGS,"Collisions Setup","0"), + /*STRUCT_ATTRIBUTE(VTS_PHYSIC_ACTOR_OPTIMIZATION,"Optimization","0"),*/ +}; + +StructurMember axisReferencedLength[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Value","0"), + STRUCT_ATTRIBUTE(CKPGUID_BEOBJECT,"Reference Object","0"), + STRUCT_ATTRIBUTE(CKPGUID_AXIS,"Local Axis","0"), +}; + + + +StructurMember customCapsule[] = +{ + STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Radius",""), + STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Width","0"), +}; +StructurMember customConvexCylinder[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_INT,"Approximation","10"), + STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Radius",""), + STRUCT_ATTRIBUTE(VTS_AXIS_REFERENCED_LENGTH,"Width","0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Forward Axis","0.0,0.0,-1.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Forward Axis Reference","0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Down Axis","0.0,-1.0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Down Axis Reference","0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Right Axis","1.0,0.0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Right Axis Reference","0"), + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Build Lower Half Only","0"), + STRUCT_ATTRIBUTE(VTF_CONVEX_FLAGS,"Convex Flags","0"), +}; + +//#define gSMapJDistance myStructJDistance +extern void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); + +typedef CKERROR (*bodyParameterDefaultFunction)(CKParameter*); + +bodyParameterDefaultFunction bodyCreateFuncOld = NULL; + + +void bodyDefaultFunctionMerged(CKParameter*in) +{ + + CKStructHelper sHelper(in); + //if ( ==0 ) //happens when dev is being opened and loads a cmo with physic objects. + + + XString msg; + + msg.Format("parameter members : %d",sHelper.GetMemberCount()); + if(bodyCreateFuncOld!=0 ) + { + bodyCreateFuncOld(in); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,msg.Str()); + } + + return; + +// CKParameter + //CKAttributeManager::SetAttributeDefaultValue() + + +} +void PhysicManager::_RegisterBodyParameterFunctions() +{ + return; + + CKContext* ctx = GetContext(); + + CKParameterManager *pm = ctx->GetParameterManager(); + CKParameterTypeDesc *param_desc = pm->GetParameterTypeDescription(VTF_PHYSIC_BODY_COMMON_SETTINGS); + if( !param_desc ) return; + if (param_desc->CreateDefaultFunction!=0) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"has function"); + bodyCreateFuncOld = param_desc->CreateDefaultFunction; + param_desc->CreateDefaultFunction = (CK_PARAMETERCREATEDEFAULTFUNCTION)bodyDefaultFunctionMerged; + } + + //param_desc->UICreatorFunction = CKActorUIFunc; + //param_desc->UICreatorFunction = CKDoubleUIFunc; + + +} +void PhysicManager::_RegisterBodyParameters() +{ + + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + + int attRef=0; + //################################################################ + // + // Geometry Related + // + + // Object and Axis Related Length : + REGISTER_CUSTOM_STRUCT("pAxisReferencedLength",PS_AXIS_REFERENCED_LENGTH,VTS_AXIS_REFERENCED_LENGTH,axisReferencedLength,false); + REGISTER_CUSTOM_STRUCT("pCustomConvexCylinder",PS_CUSTOM_CONVEX_CYLINDER_DESCR,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,customConvexCylinder,false); + REGISTER_STRUCT_AS_ATTRIBUTE("pCustomConvexCylinder",PS_CUSTOM_CONVEX_CYLINDER_DESCR,PHYSIC_BODY_CAT,VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR,CKCID_3DOBJECT,customConvexCylinder,true); + + + REGISTER_CUSTOM_STRUCT("pCapsule",PS_CAPSULE,VTS_CAPSULE_SETTINGS_EX,customCapsule,false); + REGISTER_STRUCT_AS_ATTRIBUTE("pCapsule",PS_CAPSULE,PHYSIC_BODY_CAT,VTS_CAPSULE_SETTINGS_EX,CKCID_3DOBJECT,customCapsule,true); + + + ////////////////////////////////////////////////////////////////////////// + // + // Collision Common Structs : + // + pm->RegisterNewFlags(VTF_CONVEX_FLAGS,"pConvexFlags","Flip Normals=1,16 Bit Indices=2,Compute Convex=4,Inflate Convex=8,Uncompressed Normals=64"); + pm->RegisterNewFlags(VTF_TRIGGER,"pTriggerFlags","Disable=0,OnEnter=1,OnLeave=2,OnStay=4"); + pm->RegisterNewEnum(VTE_FILTER_OPS,"pFilterOp","And=0,Or=1,Xor=2,Nand=3,Nor=4,NXor=5"); + pm->RegisterNewFlags(VTE_FILTER_MASK,"pFilterMask","0,1,2,3"); + pm->RegisterNewStructure(VTS_FILTER_GROUPS,"pFilterGroups","bits0,bits1,bits2,bits3",VTE_FILTER_MASK,VTE_FILTER_MASK,VTE_FILTER_MASK,VTE_FILTER_MASK); + pm->RegisterNewFlags(VTF_SHAPES_TYPE,"pShapesTypes","Static=1,Dynamic=2"); + + ////////////////////////////////////////////////////////////////////////// + // + // Body Sub Structs : + // + + pm->RegisterNewFlags(VTF_BODY_FLAGS,"pBFlags","Moving Object=1,World Gravity=2,Collision=4,Kinematic Object=8,Sub Shape=16,Hierarchy=32,Add Attributes=64,Trigger Shape=128,Deformable=256,Collision Notify=512,Sleep=1024"); + pm->RegisterNewFlags(VTF_BODY_TRANS_FLAGS,"pBTFlags","FrozenPositionX=2,FrozenPositionY=4,FrozenPositionZ=8,FrozenRotationX=16,FrozenRotationY=32,FrozenRotationZ=64"); + pm->RegisterNewEnum(VTE_COLLIDER_TYPE,"pBHullType","Sphere=0,Box=1,Capsule=2,Plane=3,Mesh=4,Convex Mesh=5,Height Field=6,Wheel=7,Cloth=8,Convex Cylinder"); + + pm->RegisterNewStructure(VTS_PHYSIC_PARAMETER,"pObject", "Geometry,Physic Flags,Density,Skin Width,Mass Offset,Pivot Offset,Hierarchy,World,New Density,Total Mass,Collision Group",VTE_COLLIDER_TYPE,VTF_BODY_FLAGS,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_INT); + + int currentAttributeType = -1; + + att_physic_object= attman->RegisterNewAttributeType("Object",VTS_PHYSIC_PARAMETER,CKCID_3DOBJECT); + attman->SetAttributeDefaultValue(att_physic_object,"1;Moving Object,World Gravity,Enabled,Collision;1;-1;0,0,0;0,0,0;FALSE,pDefaultWorld"); + + attman->SetAttributeCategory(att_physic_object,"Physic"); + + + pm->RegisterNewEnum(VTE_BODY_FORCE_MODE,"pBForceMode","Force=0,Impulse=1,Velocity Change=2,Smooth Impulse=3,Smooth Velocity Change=4,Acceleration=5"); + attman->SetAttributeCategory(att_physic_limit,"Physic"); + + ////////////////////////////////////////////////////////////////////////// + // + // Capsule : + // + pm->RegisterNewStructure(VTS_CAPSULE_SETTINGS,"Capsule", "Local Length Axis,Local Radius Axis,Length,Radius",CKPGUID_AXIS,CKPGUID_AXIS,CKPGUID_FLOAT,CKPGUID_FLOAT); + + CKParameterTypeDesc* param_type=pm->GetParameterTypeDescription(VTS_CAPSULE_SETTINGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + + att_capsule = attman->RegisterNewAttributeType("Capsule",VTS_CAPSULE_SETTINGS,CKCID_BEOBJECT); + attman->SetAttributeDefaultValue(att_capsule,"1;0;-1.0;-1.0f"); + attman->SetAttributeCategory(att_capsule,"Physic"); + + //---------------------------------------------------------------- + // + // copy flags + // + pm->RegisterNewFlags(VTF_PHYSIC_ACTOR_COPY_FLAGS,"pBCopyFlags","Physics=1,Shared=2,Pivot=4,Mass=8,Collision=16,CCD=32,Material=64,Optimization=128,Capsule=256,Convex Cylinder=512,Force=1024,Velocities=2048,Joints=4096,Limit Planes=8192,Swap Joint References=16384,Override Body Flags=32768,Copy IC=65536,Restore IC=131072"); + /* + param_type=pm->GetParameterTypeDescription(VTF_PHYSIC_ACTOR_COPY_FLAGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; + */ + + + ////////////////////////////////////////////////////////////////////////// + // + // Body Collision Setup + // + + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // CCD Settings : + // + // Custom Enumeration to setup ccd flags + pm->RegisterNewFlags(VTF_PHYSIC_CCD_FLAGS,"pBCCDFlags","None=1,Shared=2,DynamicDynamic=4"); + REGISTER_CUSTOM_STRUCT("pBCCDSettings",PS_B_CCD,VTS_PHYSIC_CCD_SETTINGS,bodyCCDSettings,GC_SHOWPARAMETER); + REGISTER_STRUCT_AS_ATTRIBUTE("pBCCDSettings",PS_B_CCD,PHYSIC_BODY_CAT,VTS_PHYSIC_CCD_SETTINGS,CKCID_3DOBJECT,bodyCCDSettings,true,attRef); + + + //////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // Collisions Settings + // + pm->RegisterNewEnum(VTE_PHYSIC_BODY_COLL_GROUP,"pBCollisionsGroup","All=0,MyObstacles=1,MyWheels=2"); + param_type=pm->GetParameterTypeDescription(VTE_PHYSIC_BODY_COLL_GROUP); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; + + + REGISTER_CUSTOM_STRUCT("pBCollisionSettings",PS_B_COLLISON,VTS_PHYSIC_COLLISIONS_SETTINGS,bodyCollisionsSettings,GC_SHOWPARAMETER); + REGISTER_STRUCT_AS_ATTRIBUTE("pBCollisionSettings",PS_B_COLLISON,PHYSIC_BODY_CAT,VTS_PHYSIC_COLLISIONS_SETTINGS,CKCID_3DOBJECT,bodyCollisionsSettings,true,attRef); + + + /* Merged */ + REGISTER_CUSTOM_STRUCT("pBCSetup",PS_B_COLLISION_SETUP,VTS_PHYSIC_COLLISIONS_SETUP,bodyCollisionsSetup,GC_SHOWPARAMETER ); + + ////////////////////////////////////////////////////////////////////////// + // + // XML Setup + pm->RegisterNewFlags(VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS,"pBXMLFlags","None=0,Stub=1"); + param_type=pm->GetParameterTypeDescription(VTS_PHYSIC_ACTOR_XML_IMPORT_FLAGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + REGISTER_CUSTOM_STRUCT("pBXMLSetup",PS_BODY_XML_SETUP,VTS_PHYSIC_ACTOR_XML_SETUP,bodyXMLSetup,false); + + ////////////////////////////////////////////////////////////////////////// + // + // Common + REGISTER_CUSTOM_STRUCT("pBCommon",PS_BODY_COMMON,VTF_PHYSIC_BODY_COMMON_SETTINGS,bodyCommonSettings,false); + + ////////////////////////////////////////////////////////////////////////// + // + // Sleep + REGISTER_CUSTOM_STRUCT("pBSleepSettings",PS_B_SLEEPING,VTS_PHYSIC_SLEEP_SETTINGS,bodySleeping,GC_SHOWPARAMETER); + + + ////////////////////////////////////////////////////////////////////////// + // + // Damping + REGISTER_CUSTOM_STRUCT("pBDamping",PS_B_DAMPING,VTS_PHYSIC_DAMPING_PARAMETER,bodyDamping,GC_SHOWPARAMETER); + + ////////////////////////////////////////////////////////////////////////// + // + // Optimization + REGISTER_CUSTOM_STRUCT("pBOptimisation",PS_B_OPTIMISATION,VTS_PHYSIC_ACTOR_OPTIMIZATION,bodyOptimistationSettings,GC_SHOWPARAMETER); + REGISTER_STRUCT_AS_ATTRIBUTE("pBOptimisation",PS_B_OPTIMISATION,PHYSIC_BODY_CAT,VTS_PHYSIC_ACTOR_OPTIMIZATION,CKCID_3DOBJECT,bodyOptimistationSettings,true,attRef); + + + + ////////////////////////////////////////////////////////////////////////// + // + // Geometry + REGISTER_CUSTOM_STRUCT("pBPivotSettings",PS_B_PIVOT,VTS_PHYSIC_PIVOT_OFFSET,bodyGeomtryOverride,GC_SHOWPARAMETER); + REGISTER_STRUCT_AS_ATTRIBUTE("pBPivotSettings",PS_B_PIVOT,PHYSIC_BODY_CAT,VTS_PHYSIC_PIVOT_OFFSET,CKCID_3DOBJECT,bodyGeomtryOverride,true,attRef); + + + ////////////////////////////////////////////////////////////////////////// + // + // Mass Override + REGISTER_CUSTOM_STRUCT("pBMassSettings",PS_B_MASS,VTS_PHYSIC_MASS_SETUP,bodyMassSetup,false); + param_type=pm->GetParameterTypeDescription(VTS_PHYSIC_MASS_SETUP); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + REGISTER_STRUCT_AS_ATTRIBUTE("pBMassSettings",PS_B_MASS,PHYSIC_BODY_CAT,VTS_PHYSIC_MASS_SETUP,CKCID_3DOBJECT,bodyMassSetup,true,attRef); + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // this is the new replacement for the "Object" attribute. + // + REGISTER_CUSTOM_STRUCT("pBSetup",PS_BODY_SETUP,VTS_PHYSIC_ACTOR,bodySetup,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pBSetup",PS_BODY_SETUP,PHYSIC_BODY_CAT,VTS_PHYSIC_ACTOR,CKCID_3DOBJECT,bodySetup,attRef); + + +} diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterJointParameters.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterJointParameters.cpp new file mode 100644 index 0000000..55a6bc4 --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterJointParameters.cpp @@ -0,0 +1,296 @@ +#include +#include "vtPhysXAll.h" +#include "vtStructHelper.h" + +#define PHYSIC_JOINT_CAT "Physic Constraints" + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; + + + + +StructurMember myStructJBall[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Limit Swing Axis","0,0,0"), + + STRUCT_ATTRIBUTE(VTE_JOINT_PROJECTION_MODE,"Projection Mode","None"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Projection Distance","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision","TRUE"), + + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Swing Limit","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Twist High Limit ","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Twist Low Limit ","0.0,0.0,0.0"), + + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Swing Spring","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Twist Spring","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Joint Spring","0.0,0.0,0.0"), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + +}; + + +StructurMember myStructJDistance[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Local 0 Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Local 0 Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Local 1 Anchor","0,0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Local 1 Reference","pDefaultWorld"), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision","TRUE"), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Minimum Distance","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Distance","0.0"), + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Spring","0.0f,0.0f,0.0f"), + + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + +}; + + +StructurMember myStructJFixed[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + +}; + +StructurMember JPrismaticMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + +}; + +StructurMember JCylindricalMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), +}; + +StructurMember JPointInPlaneMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), +}; + +StructurMember JPointOnLineMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision",""), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), +}; + +StructurMember JRevoluteMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Collision","TRUE"), + + STRUCT_ATTRIBUTE(VTE_JOINT_PROJECTION_MODE,"Projection Mode","None"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Projection Distance","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Projection Angle","0.3"), + + STRUCT_ATTRIBUTE(VTS_JOINT_SPRING,"Spring","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Limit High","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JLIMIT,"Limit Low","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(VTS_JOINT_MOTOR,"Motor","0.0,0.0,0.0"), + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Force","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Maximum Torque","0.0"), + + +}; + + + +StructurMember JLimitPlaneMemberTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + STRUCT_ATTRIBUTE(VTE_JOINT_TYPE,"Target Joint Type","JT_Any"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Restitution","0.0f"), + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Point is on Body","False"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Limit Point",""), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Limit Point Reference",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Normal",""), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Normal Up Reference",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Point in Plane",""), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Point in Plane Reference",""), + +}; + +StructurMember JD6Members[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Body B","BodyB"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Anchor","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Anchor Reference",""), + + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Axis","0,0,0"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Axis Reference",""), + STRUCT_ATTRIBUTE(VTF_JOINT_D6_AXIS_MASK,"Axis Mask",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"X",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Y",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Z",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Swing 1",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Swing 2",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Twist Low",""), + STRUCT_ATTRIBUTE(VTS_JOINT_D6_AXIS_ITEM,"Twist High",""), +}; + +StructurMember JD6AxisItem[] = +{ + STRUCT_ATTRIBUTE(VTE_JOINT_MOTION_MODE_AXIS,"Axis","X"), + STRUCT_ATTRIBUTE(VTS_JOINT_SLIMIT,"Limit",""), +}; + +#define gSMapJDistance myStructJDistance +#define gSMapJFixed myStructJFixed +#define gSMapJBall myStructJBall +#define gSMapJPrismatic JPrismaticMemberTable +#define gSMapJRevolute JRevoluteMemberTable +#define gSMapJCylindrical JCylindricalMemberTable +#define gSMapJPointInPlane JPointInPlaneMemberTable +#define gSMapJPointOnLine JPointOnLineMemberTable +#define gSMapJLimitPlane JLimitPlaneMemberTable + +extern void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg); +void PhysicManager::_RegisterJointParameters() +{ + + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + + //---------------------------------------------------------------- + // + // D6 Help Structures + // + + pm->RegisterNewEnum(VTE_JOINT_MOTION_MODE,"pJMotionMode","Locked=0,Limited=1,Free=2"); + pm->RegisterNewStructure(VTS_JOINT_SLIMIT,"pJD6SLimit","Damping,Spring,Value,Restitution",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_ANGLE,CKPGUID_FLOAT); + + //---------------------------------------------------------------- + // + // Types for D6 - Joint - Attribute only : + // + + + //SetWindowLong(m_hWnd,GWL_USERDATA,(LONG)this_mod); // set our user data to a "this" pointer + /* + pm->RegisterNewEnum(VTF_JOINT_D6_AXIS_MASK,"pD6AxisMask","X=1,Y=2,Z=4,Swing1=8,Swing2=16,Twist Low=32,Twist High=64"); + REGISTER_CUSTOM_STRUCT("pJD6AxisItem",PS_D6_AXIS_ITEM,VTS_JOINT_D6_AXIS_ITEM,JD6AxisItem,TRUE); + REGISTER_CUSTOM_STRUCT("pJD6",PS_D6,VTS_JOINT_D6,JD6Members,TRUE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJD6",PS_D6,PHYSIC_JOINT_CAT,VTS_JOINT_D6,CKCID_BEOBJECT,JD6Members,true,attRef); + + */ + + int attRef=0; + pm->RegisterNewEnum(VTE_JOINT_TYPE,"pJointType","None=-1,Prismatic=0,Revolute=1,Cylindrical=2,Spherical=3,Point On Line=4,Point In Plane=5,Distance=6,Pulley=7,Fixed=8,D6=9"); + + pm->RegisterNewEnum(VTE_PHYSIC_JDRIVE_TYPE,"pJD6DriveType","Disabled=0,Position=1,Velocity=2"); + pm->RegisterNewStructure(VTS_JOINT_DRIVE,"pJD6Drive","Damping,Spring,Force Limit,Drive Type",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,VTE_PHYSIC_JDRIVE_TYPE); + + pm->RegisterNewStructure(VTS_JOINT_SPRING,"pJSpring","Damper,Spring,Target Value",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT); + pm->RegisterNewStructure(VTS_JLIMIT,"pJLimit","Value,Restitution,Hardness",CKPGUID_ANGLE,CKPGUID_FLOAT,CKPGUID_FLOAT); + + + pm->RegisterNewEnum(VTE_JOINT_MOTION_MODE_AXIS,"pJD6Axis","Twist=0,Swing1=1,Swing2=2,X=3,Y=4,Z=5"); + pm->RegisterNewEnum(VTE_JOINT_DRIVE_AXIS,"pJD6DriveAxis","Twist=0,Swing=1,Slerp=2,X=3,Y=4,Z=5"); + pm->RegisterNewEnum(VTE_JOINT_LIMIT_AXIS,"pJD6LimitAxis","Linear=0,Swing1=1,Swing2,Twist High,Twist Low"); + + pm->RegisterNewEnum(VTE_JOINT_PROJECTION_MODE,"pJProjectionMode","None=0,Point MinDist=1,Linear MindDist"); + pm->RegisterNewStructure(VTS_JOINT_MOTOR,"pJMotor","Target Velocity,Maximum Force,Free Spin",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_BOOL); + + REGISTER_CUSTOM_STRUCT("pJDistance",PS_JDISTANCE_MEMBERS,VTS_JOINT_DISTANCE,gSMapJDistance,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJDistance",PS_JDISTANCE_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_DISTANCE,CKCID_3DOBJECT,gSMapJDistance,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJFixed",PS_JFIXED_MEMBERS,VTS_JOINT_FIXED,gSMapJFixed,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJFixed",PS_JFIXED_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_FIXED,CKCID_3DOBJECT,gSMapJFixed,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJBall",PS_JBALL_MEMBERS,VTS_JOINT_BALL,gSMapJBall,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJBall",PS_JBALL_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_BALL,CKCID_3DOBJECT,gSMapJBall,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJPrismatic",PS_JPRISMATIC_MEMBERS,VTS_JOINT_PRISMATIC ,gSMapJPrismatic,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJPrismatic",PS_JPRISMATIC_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_PRISMATIC ,CKCID_BEOBJECT,gSMapJPrismatic,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJCylindrical",PS_JCYLINDRICAL_MEMBERS,VTS_JOINT_CYLINDRICAL,gSMapJCylindrical,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJCylindrical",PS_JCYLINDRICAL_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_CYLINDRICAL,CKCID_BEOBJECT,gSMapJCylindrical,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJRevolute",PS_JREVOLUTE,VTS_JOINT_REVOLUTE,gSMapJRevolute,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJRevolute",PS_JREVOLUTE,PHYSIC_JOINT_CAT,VTS_JOINT_REVOLUTE ,CKCID_BEOBJECT,gSMapJRevolute,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJPointInPlane",PS_JPOINT_IN_PLANE_MEMBERS,VTS_JOINT_POINT_IN_PLANE,gSMapJPointInPlane,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJPointInPlane",PS_JPOINT_IN_PLANE_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_POINT_IN_PLANE,CKCID_BEOBJECT,gSMapJPointInPlane,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJPointOnLine",PS_JPOINT_ON_LINE_MEMBERS,VTS_JOINT_POINT_ON_LINE,gSMapJPointOnLine,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJPointOnLine",PS_JPOINT_ON_LINE_MEMBERS,PHYSIC_JOINT_CAT,VTS_JOINT_POINT_ON_LINE,CKCID_BEOBJECT,gSMapJPointOnLine,true,attRef); + + REGISTER_CUSTOM_STRUCT("pJLimitPlane",PS_JLIMIT_PLANE_MEMBERS,VTS_PHYSIC_JLIMIT_PLANE,gSMapJLimitPlane,FALSE); + REGISTER_STRUCT_AS_ATTRIBUTE("pJLimitPlane",PS_JLIMIT_PLANE_MEMBERS,PHYSIC_JOINT_CAT,VTS_PHYSIC_JLIMIT_PLANE,CKCID_BEOBJECT,gSMapJLimitPlane,true,attRef); + + + + + + populateAttributeFunctions(); + _RegisterAttributeCallbacks(); + +} diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterParameters.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterParameters.cpp new file mode 100644 index 0000000..6ebe50b --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterParameters.cpp @@ -0,0 +1,377 @@ +#include +#include "vtPhysXAll.h" + +#include "vtStructHelper.h" +#include "vtAttributeHelper.h" + +using namespace vtTools::AttributeTools; + +int PhysicManager::getAttributeTypeByGuid(CKGUID guid) +{ + + + CKContext *ctx = GetPMan()->GetContext(); + + CKAttributeManager *attMan = ctx->GetAttributeManager(); + CKParameterManager *parMan = ctx->GetParameterManager(); + + int cCount = attMan->GetAttributeCount(); + for(int i = 0 ; i < cCount ; i++) + { + CKSTRING name = attMan->GetAttributeNameByType(i); + if ( parMan->ParameterTypeToGuid(attMan->GetAttributeParameterType(i)) == guid ) + { + return i; + } + } + + return -1; +} + +void PhysicManager::_RegisterDynamicEnumeration(XString file,XString enumerationName,CKGUID enumerationGuid,PFEnumStringFunction enumFunc,BOOL hidden) +{ + + + TiXmlDocument * defaultDoc = loadDefaults(file.Str()); + if (!defaultDoc) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config :PhysicDefaults.xml: failed"); + } + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + if (!getCurrentFactory()) + { + pFactory *factory = new pFactory(this,getDefaultConfig()); + setCurrentFactory(factory); + } + + pFactory *factory = pFactory::Instance(); + + XString outList; + if (defaultDoc) + outList = (factory->*enumFunc)(getDefaultConfig()); + + if (!outList.Length()) + outList<< "None=0"; + + CKParameterType pType = pm->ParameterGuidToType(enumerationGuid); + if (pType==-1) + pm->RegisterNewEnum(enumerationGuid,enumerationName.Str(),outList.Str()); + else{ + pm->ChangeEnumDeclaration(enumerationGuid,outList.Str()); + } + + CKParameterTypeDesc* param_type = pm->GetParameterTypeDescription(enumerationGuid); + if (param_type && hidden) + param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"%s settings from xml detected : %s",enumerationName.Str(),outList.Str()); + + + +} + +void PhysicManager::_RegisterDynamicParameters() +{ + + + TiXmlDocument * defaultDoc = loadDefaults("PhysicDefaults.xml"); + if (!defaultDoc) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config :PhysicDefaults.xml: failed"); + } + + //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Default xml configuration loaded"); + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + if (!getCurrentFactory()) + { + pFactory *factory = new pFactory(this,getDefaultConfig()); + setCurrentFactory(factory); + } + + + int pType = 0; + + ////////////////////////////////////////////////////////////////////////// + // + // Material ! + // +/* + XString materialList; + if (defaultDoc) + { + materialList = pFactory::Instance()->_getMaterialsAsEnumeration(getDefaultConfig()); + }else{ + + materialList << "None=0"; + } + + int pType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); + + if (pType==-1) + pm->RegisterNewEnum(VTE_XML_MATERIAL_TYPE,"pMaterialType",materialList.Str()); + else{ + pm->ChangeEnumDeclaration(VTE_XML_MATERIAL_TYPE,materialList.Str()); + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"materials : %s",materialList.Str()); +*/ + + _RegisterDynamicEnumeration("PhysicDefaults.xml","pMaterialType",VTE_XML_MATERIAL_TYPE,&pFactory::_getMaterialsAsEnumeration,true); + _RegisterDynamicEnumeration("PhysicDefaults.xml","pBodyXMLInternalLink",VTS_PHYSIC_ACTOR_XML_SETTINGS_INTERN,&pFactory::_getBodyXMLInternalEnumeration,false); + _RegisterDynamicEnumeration("PhysicDefaults.xml","pBodyXMLExternalLink",VTS_PHYSIC_ACTOR_XML_SETTINGS_EXTERN,&pFactory::_getBodyXMLExternalEnumeration,false); + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Vehicle Settings + // + XString vSListStr; + if (defaultDoc) + vSListStr= pFactory::Instance()->_getVehicleSettingsAsEnumeration(getDefaultConfig()); + + if (!vSListStr.Length()) + vSListStr << "None=0"; + + pType = pm->ParameterGuidToType(VTE_XML_VEHICLE_SETTINGS); + if (pType==-1) + pm->RegisterNewEnum(VTE_XML_VEHICLE_SETTINGS,"pVehicleSettingsLink",vSListStr.Str()); + else{ + pm->ChangeEnumDeclaration(VTE_XML_VEHICLE_SETTINGS,vSListStr.Str()); + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"vehicle settings : %s",vSListStr.Str()); + + + ////////////////////////////////////////////////////////////////////////// + // + // Wheel Settings + // + XString wSListStr; + if (defaultDoc) + wSListStr = pFactory::Instance()->_getVehicleWheelAsEnumeration(getDefaultConfig()); + + if (!wSListStr.Length()) + wSListStr << "None=0"; + + + pType = pm->ParameterGuidToType(VTE_XML_WHEEL_SETTINGS); + if (pType==-1) + pm->RegisterNewEnum(VTE_XML_WHEEL_SETTINGS,"pWheelSettingsLink",wSListStr.Str()); + else{ + pm->ChangeEnumDeclaration(VTE_XML_WHEEL_SETTINGS,wSListStr.Str()); + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"wheel vehicle settings : %s",wSListStr.Str()); + + + CKParameterTypeDesc* param_type; + param_type=pm->GetParameterTypeDescription(VTE_XML_WHEEL_SETTINGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + + ////////////////////////////////////////////////////////////////////////// + // + // Wheel Tire Function + // + XString wTListStr; + if (defaultDoc) + wTListStr = pFactory::Instance()->_getVehicleTireFunctionAsEnumeration(getDefaultConfig()); + + if (!wTListStr.Length()) + wTListStr << "None=0"; + + pType = pm->ParameterGuidToType(VTE_XML_TIRE_SETTINGS); + if (pType==-1) + pm->RegisterNewEnum(VTE_XML_TIRE_SETTINGS,"pWheelSettingsLink",wTListStr.Str()); + else{ + pm->ChangeEnumDeclaration(VTE_XML_TIRE_SETTINGS,wTListStr.Str()); + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"wheel tire force settings : %s",wTListStr.Str()); + + param_type=pm->GetParameterTypeDescription(VTE_XML_TIRE_SETTINGS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + + + + //_getVehicleTireFunctionAsEnumeration + /*param_type=pm->GetParameterTypeDescription(CKPGUID_EVOLUTIONS); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; +*/ + + + _RegisterDynamicEnumeration("PhysicDefaults.xml","pMaterialType",VTE_XML_MATERIAL_TYPE,&pFactory::_getMaterialsAsEnumeration,true); + + +} + + +void recheckWorldsFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg) +{ + + int s = GetPMan()->getNbObjects(); + if (AttribType == GetPMan()->GetPAttribute()) + { + pRigidBody *body = body = GetPMan()->getBody(pFactory::Instance()->getMostTopParent((CK3dEntity*)obj)); + if (body) + { + if (Set) + if (!body->isSubShape(obj)) + body->_checkForNewSubShapes(); + else + body->_checkForRemovedSubShapes(); + } + } + //CKParameterOut *pout = obj->GetAttributeParameter(GetPMan()->att_physic_object); + +} + +using namespace vtTools::ParameterTools; + + +vtTools::ParameterTools::StructurMember PBRigidBodyMemberMap[] = +{ + + STRUCT_ATTRIBUTE(VTE_COLLIDER_TYPE,"Geometry","Sphere"), + STRUCT_ATTRIBUTE(VTF_BODY_FLAGS,"Physic Flags","Moving Object,World Gravity,Enabled,Collision"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Density","1.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Skin Width","-1.0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Mass Offset","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Pivot Offset","0.0,0.0,0.0"), + STRUCT_ATTRIBUTE(CKPGUID_BOOL,"Hierarchy","FALSE"), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"World","pDefaultWorld"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Total Mass","-1.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"New Density","-1.0"), + STRUCT_ATTRIBUTE(CKPGUID_INT,"Collision Group","0"), +}; + +//pm->RegisterNewStructure(VTS_PHYSIC_PARAMETER,"pObject", ",Mass Offset,Pivot Offset,Hierarchy,World,New Density,Total Mass,Collision Group", +//VTE_COLLIDER_TYPE,VTF_BODY_FLAGS,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_INT); + + +void PhysicManager::_RegisterParameters() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + + + attman->AddCategory("Physic"); + + _RegisterWorldParameters(); + _RegisterBodyParameters(); + _RegisterBodyParameterFunctions(); + + + /************************************************************************/ + /* clothes : */ + /************************************************************************/ + pm->RegisterNewFlags(VTE_CLOTH_FLAGS,"pClothFlags","Pressure=1,Static=2,DisableCollision=4,SelfCollision=8,Gravity=32,Bending=64,BendingOrtho=128,Damping=256,CollisionTwoway=512,TriangleCollision=2048,Tearable=4096,Hardware=8192,ComDamping=16384,ValidBounds=32768,FluidCollision=65536,DisableCCD=131072,AddHere=262144,AttachToParentMainShape=524288,AttachToCollidingShapes=1048576,AttachToCore=2097152,AttachAttributes=4194304"); + pm->RegisterNewFlags(VTE_CLOTH_ATTACH_FLAGS,"pClothAttachFlags","Twoway=1,Tearable=2"); + + pm->RegisterNewStructure(VTS_CLOTH_DESCR,"pClothDesc","Thickness,Density,Bending Stiffness,Stretching Stiffness,Damping Coefficient,Friction,Pressure,Tear Factor,Collision Response Coefficient,Attachment Response Coefficient,Attachment Tear Factor,To Fluid Response Coefficient,From Fluid Response Coefficient,Min Adhere Velocity,Solver Iterations,External Acceleration,Wind Acceleration,Wake Up Counter,Sleep Linear Velocity,Collision Group,Valid Bounds,Relative Grid Spacing,Flags,Tear Vertex Color,World Reference,Attachment Flags",CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_INT, CKPGUID_VECTOR, CKPGUID_VECTOR, CKPGUID_FLOAT, CKPGUID_FLOAT, CKPGUID_INT, CKPGUID_BOX, CKPGUID_FLOAT, VTE_CLOTH_FLAGS, CKPGUID_COLOR, CKPGUID_3DENTITY, VTE_CLOTH_ATTACH_FLAGS); + att_clothDescr= attman->RegisterNewAttributeType("Cloth",VTS_CLOTH_DESCR,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_clothDescr,"Physic"); + attman->SetAttributeDefaultValue(att_clothDescr,"0.01f;1.0f;1.0f;1.0f;0.5f;0.5f;1.0f;1.5f;0.2f; 0.2f;1.5f;1.0f;1.0f;1.0f;5;0.0f,0.0f,0.0f;0.0f,0.0f,0.0f;0.4f;-1.0f;0;0.0f,0.0f,0.0f,0.0f,0.0f,0.0f;0.25;Gravity;255,255,255,255;pDefaultWorld;Twoway"); + + pm->RegisterNewStructure(VTS_CLOTH_METAL_DESCR,"pDeformableSettings","Impulse Threshold,Penetration Depth,Maximal Deformation Distance",CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT); + + CKParameterTypeDesc* param_type=pm->GetParameterTypeDescription(VTS_CLOTH_METAL_DESCR); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + att_deformable = attman->RegisterNewAttributeType("Deformable Settings",VTS_CLOTH_METAL_DESCR,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_deformable,"Physic"); + + //attman->SetAttributeCallbackFunction(att_clothDescr,recheckWorldsFunc,NULL); + + + /************************************************************************/ + /* material */ + /************************************************************************/ + pm->RegisterNewFlags(VTF_MATERIAL_FLAGS,"pMaterialFlags","Anisotropic=1,Disable Friction=16,Disable Strong Friction=32"); + pm->RegisterNewEnum(VTE_MATERIAL_COMBINE_MODE,"pFrictionCombineMode","Average=0,Min=1,Multiply=2,Max=3"); + pm->RegisterNewStructure(VTS_MATERIAL,"pMaterial","XML Link,DynamicFriction,Static Friction,Restitution,Dynamic Friction V,Static Friction V,Direction of Anisotropy,Friction Combine Mode,Restitution Combine Mode,Flags",VTE_XML_MATERIAL_TYPE,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_VECTOR,VTE_MATERIAL_COMBINE_MODE,VTE_MATERIAL_COMBINE_MODE,VTF_MATERIAL_FLAGS); + + att_surface_props= attman->RegisterNewAttributeType("Material",VTS_MATERIAL,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_surface_props,"Physic"); + + attman->SetAttributeCallbackFunction(att_surface_props,recheckWorldsFunc,NULL); + + + /************************************************************************/ + /* Collision */ + /************************************************************************/ + + + att_trigger= attman->RegisterNewAttributeType("Trigger",VTF_TRIGGER,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_trigger,"Physic"); + + pm->RegisterNewFlags(VTF_RAY_HINTS,"pRayCastHints","Shape=1,Impact=2,Normal=4,Face Index=8,Distance=16,UV=32,Face Normal=64,Material=128"); + pm->RegisterNewStructure(VTS_RAYCAST,"pRayCast","World Reference,Ray Origin,Ray Origin Reference,Ray Direction,Ray Direction Reference,Length,Groups,Groups Mask,Shape Types",CKPGUID_3DENTITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_FLOAT,CKPGUID_INT,VTS_FILTER_GROUPS,VTF_SHAPES_TYPE); + + + + /************************************************************************/ + /* Vehicle : */ + /************************************************************************/ + // + + //pm->RegisterNewStructure(VTS_WHEEL_CONTACT,"pWheelContactData","Contact Point,Contact Normal,Longitudes Direction,Lateral Direction,Contact Force,Longitudes Slip,Lateral Slip, Longitudes Impulse,Lateral Impulse,Other Material,Contact Position, Contact Entity",CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_VECTOR,CKPGUID_VECTOR, CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,VTS_MATERIAL,CKPGUID_FLOAT,CKPGUID_3DENTITY); + //REGISTER_CUSTOM_STRUCT("pJDistance",PS_JDISTANCE_MEMBERS,VTS_JOINT_DISTANCE,gSMapJDistance,FALSE); + + _RegisterVehicleParameters(); + _RegisterJointParameters(); + + + //registerWatchers(); +} + +XString getEnumDescription(CKParameterManager* pm,CKBeObject *object,int index) +{ + + XString result="None"; + int pType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + if(i == index) + { + result = enumStruct->GetEnumDescription(i); + } + } + } + return result; +} + +int getEnumIndexByDescription(CKParameterManager* pm,XString descr) +{ + + int result =0; + int pType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + + if (!strcmp(enumStruct->GetEnumDescription(i),descr.CStr())) + { + return i; + } + } + } + return result; +} diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterVehicleParameters.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterVehicleParameters.cpp new file mode 100644 index 0000000..165d5a3 --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterVehicleParameters.cpp @@ -0,0 +1,117 @@ +#include +#include "vtPhysXAll.h" +#include "vtAttributeHelper.h" +#include + + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; + +vtTools::ParameterTools::StructurMember breakTable[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"0","250"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"1","250"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"2","300"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"3","350"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"4","450"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"5","575"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"6","625"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"7","700"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"8","1000"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"9","1000"), +}; + +vtTools::ParameterTools::StructurMember myStructWheelContactData[] = +{ + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Contact Point",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Contact Normal",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Longitudes Direction",""), + STRUCT_ATTRIBUTE(CKPGUID_VECTOR,"Lateral Direction",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Contact Force",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Longitudes Slip",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Lateral Slip",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Longitudes Impulse",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Lateral Impulse",""), + STRUCT_ATTRIBUTE(VTS_MATERIAL,"Other Material",""), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Contact Pos",""), + STRUCT_ATTRIBUTE(CKPGUID_3DENTITY,"Colliding Entity",""), +}; + +void PhysicManager::_RegisterVehicleParameters() +{ + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + CKParameterTypeDesc* param_type = NULL; + + //################################################################ + // + // Tire Function + // + pm->RegisterNewStructure(VTF_VWTIRE_SETTINGS,"pTireFunction", + "XML Link,Extremum Slip,Extremum Value,Asymptote Slip,Asymptote Value,Stiffness Factor", + VTE_XML_TIRE_SETTINGS,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT,CKPGUID_FLOAT); + + + //################################################################ + // + // Motor related + // + pm->RegisterNewStructure(VTS_VMOTOR_ENTRY,"RPM / Newton Meter","RPM,Newton Meter",CKPGUID_FLOAT,CKPGUID_FLOAT); + param_type=pm->GetParameterTypeDescription(VTS_VMOTOR_ENTRY); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + pm->RegisterNewStructure(VTS_VMOTOR_TVALUES,"pVehicleMotor Torques","1,2,3,4,5,6,7", VTS_VMOTOR_ENTRY,VTS_VMOTOR_ENTRY, VTS_VMOTOR_ENTRY,VTS_VMOTOR_ENTRY, VTS_VMOTOR_ENTRY,VTS_VMOTOR_ENTRY, VTS_VMOTOR_ENTRY); + + + pm->RegisterNewStructure(VTS_VGEAR_RATIO_ENTRY,"Gear / Ratio","Gear,Ratio",CKPGUID_INT,CKPGUID_FLOAT); + param_type=pm->GetParameterTypeDescription(VTS_VGEAR_RATIO_ENTRY); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + pm->RegisterNewStructure(VTS_VGEAR_RATIOS,"pVehicleGear List","1,2,3,4,5,6,7", VTS_VGEAR_RATIO_ENTRY,VTS_VGEAR_RATIO_ENTRY, VTS_VGEAR_RATIO_ENTRY,VTS_VGEAR_RATIO_ENTRY, VTS_VGEAR_RATIO_ENTRY,VTS_VGEAR_RATIO_ENTRY, VTS_VGEAR_RATIO_ENTRY); + + //################################################################ + // + // Vehicle Common + // + pm->RegisterNewFlags(VTF_VSTATE_FLAGS,"pVehicleStateFlags","Is Moving=1,Is Accelerated=2,Is Accelerated Forward=4,Is Accelerated Backward=8,All Wheels On Ground=16,Is Falling=32,Handbrake=64,Is Braking=128,Is Steering=256,Has Gearbox=512,Has Motor=1024"); + pm->RegisterNewEnum(VTE_BRAKE_LEVEL,"pVehicleBreakLevel","No Break=-1,Small=0,Medium=1,High=2"); + pm->RegisterNewEnum(VTE_BRAKE_XML_LINK,"pVehicleXMLBrakeSettings","Stub=1"); + pm->RegisterNewEnum(VTE_VEHICLE_XML_LINK,"pVehicleXMLLink","Stub=1"); + + pm->RegisterNewFlags(VTF_BRAKE_FLAGS,"pVehicleBreakFlags","Use Table=1,Auto Break=2"); + + REGISTER_CUSTOM_STRUCT("pVehicleBreakTable",E_VBT_STRUCT,VTS_BRAKE_TABLE,breakTable,FALSE); + + + + //################################################################ + // + // Wheel + // + + REGISTER_CUSTOM_STRUCT("pWheelContactData",E_WCD_STRUCT,VTS_WHEEL_CONTACT,myStructWheelContactData,FALSE); + + pm->RegisterNewFlags(VTS_PHYSIC_WHEEL_FLAGS,"pWheelFlags","Steerable Input=1,Steerable Auto=2,Affected By Handbrake=4,Accelerated=8,Controlled by Vehicle=16,Affected by Differential=32,Ignore Tire Function=64"); + //pm->RegisterNewFlags(VTS_PHYSIC_WHEEL_FLAGS,"pWheelFlags","Steerable Input=1,Steerable Auto=2,Affected By Handbrake=4,Accelerated=8,Build Lower Half=256,Use Wheel Shape=512,Controlled by Vehicle"); + pm->RegisterNewFlags(VTF_VWSHAPE_FLAGS,"pWheelShapeFlags","AxisContactNormal=1,InputLateralSlip=2,InputLongitudinal=4,UnscaledSpringBehavior=8,EmulateLegacyWheel=32,ClampedFriction=64"); + + pm->RegisterNewStructure(VTS_PHYSIC_WHEEL_DESCR,"pWheelDescr", + "XML Link,Suspension,Spring Restitution,Spring Bias,Spring Damping,Maximum Brake Force,Friction To Side,Friction To Front,Inverse Wheel Mass,Wheel Flags,Wheel Shape Flags,Lateral Force Settings,Longitudinal Force Settings", + VTE_XML_WHEEL_SETTINGS, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + CKPGUID_FLOAT, + VTS_PHYSIC_WHEEL_FLAGS, + VTF_VWSHAPE_FLAGS, + VTF_VWTIRE_SETTINGS, + VTF_VWTIRE_SETTINGS); + + att_wheelDescr = attman->RegisterNewAttributeType("pWheel",VTS_PHYSIC_WHEEL_DESCR,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_wheelDescr ,"Physic"); + +} diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterWorldParameters.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterWorldParameters.cpp new file mode 100644 index 0000000..a3cd01c --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManagerVTRegisterWorldParameters.cpp @@ -0,0 +1,108 @@ +#include + +#include "pCrossTypes.h" +#include +#include "vtPhysXAll.h" + +#include "vtStructHelper.h" +#include "vtAttributeHelper.h" + + +using namespace vtTools::AttributeTools; +using namespace vtTools::ParameterTools; + + + +/************************************************************************/ +/* Dominance Setup */ +/************************************************************************/ + + +////////////////////////////////////////////////////////////////////////// +// +// Dominance help member : +// +StructurMember dominanceConstraint[] = +{ + + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Dominance 0","0.0"), + STRUCT_ATTRIBUTE(CKPGUID_FLOAT,"Dominance 1","1.0"), +}; + +////////////////////////////////////////////////////////////////////////// +// +// Dominance help member : +// +StructurMember dominanceItem[] = +{ + + STRUCT_ATTRIBUTE(VTE_PHYSIC_DOMINANCE_GROUP,"Dominance Group A","1"), + STRUCT_ATTRIBUTE(VTE_PHYSIC_DOMINANCE_GROUP,"Dominance Group B","2"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_CONSTRAINT,"Dominance Constraint","1.0,0.0"), + +}; + +StructurMember dominanceSetup[] = +{ + + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 1","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 2","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 3","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 4","0"), + STRUCT_ATTRIBUTE(VTS_PHYSIC_DOMINANCE_ITEM,"Settings 5","0"), +}; +//STRUCT_ATTRIBUTE(CKPGUID_2DCURVE,"Settings 5","0"), + +void PhysicManager::_RegisterWorldParameters() +{ + CKParameterManager *pm = m_Context->GetParameterManager(); + CKAttributeManager* attman = m_Context->GetAttributeManager(); + + CKParameterTypeDesc* param_type = NULL; + + + + /************************************************************************/ + /* Dominance Structs */ + /************************************************************************/ + + REGISTER_CUSTOM_STRUCT("pWDominanceConstraint",PS_W_DOMINANCE_CONSTRAINT,VTS_PHYSIC_DOMINANCE_CONSTRAINT,dominanceConstraint,true); + + // Dominance group as user friendly enumeration + pm->RegisterNewEnum(VTE_PHYSIC_DOMINANCE_GROUP,"pDominanceGroup","None=0,First=1,Second=2"); + param_type=pm->GetParameterTypeDescription(VTE_PHYSIC_DOMINANCE_GROUP); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_TOSAVE; + + + //if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + + + REGISTER_CUSTOM_STRUCT("pDominanceItem",PS_W_DOIMINANCE,VTS_PHYSIC_DOMINANCE_ITEM,dominanceItem,true); + + REGISTER_CUSTOM_STRUCT("pDominanceSetup",PS_W_DOIMINANCE_SETUP,VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS,dominanceSetup,true); + + REGISTER_STRUCT_AS_ATTRIBUTE("Dominance Group Setup",PS_W_DOIMINANCE_SETUP,PHYSIC_BODY_CAT,VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS,CKCID_3DENTITY,dominanceSetup,true); + + + /************************************************************************/ + /* world */ + /************************************************************************/ + + /*pm->RegisterNewEnum(VTE_PHYSIC_BODY_COLL_GROUP,"pBCollisionsGroup","All=0,MyObstacles=1,MyWheels=2"); + param_type=pm->GetParameterTypeDescription(VTE_PHYSIC_BODY_COLL_GROUP); + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_USER; + if (param_type) param_type->dwFlags|=CKPARAMETERTYPE_HIDDEN; + */ + + + pm->RegisterNewStructure(VTS_PHYSIC_WORLD_PARAMETER, "pWorldSettings", "Gravity,SkinWith", CKPGUID_VECTOR, CKPGUID_FLOAT ); + + att_world_object = attman->RegisterNewAttributeType("World",VTS_PHYSIC_WORLD_PARAMETER,CKCID_BEOBJECT); + attman->SetAttributeCategory(att_world_object,"Physic"); + + + + + +} diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsBody.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsBody.cpp new file mode 100644 index 0000000..95a6fe9 --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsBody.cpp @@ -0,0 +1,561 @@ +#include +#include "vtPhysXAll.h" + + +#define PARAM_OP_TYPE_BGET_VELOCITY CKGUID(0x3b2a778c,0x293b206d) +#define PARAM_OP_TYPE_BGET_AVELOCITY CKGUID(0x67ee7c4e,0x1e3b4d15) +#define PARAM_OP_TYPE_BGET_TORQUE CKGUID(0x1ecd7ee4,0x4f0b7eda) +#define PARAM_OP_TYPE_BGET_FORCE CKGUID(0x7dd13e61,0x40af4f99) +#define PARAM_OP_TYPE_BGET_FRICTION CKGUID(0x482b3611,0x4b0a168c) +#define PARAM_OP_TYPE_BGET_HTYPE CKGUID(0x68eb059e,0x26bb745a) +#define PARAM_OP_TYPE_BGET_FIXED CKGUID(0x7bcd7379,0x5c950897) +#define PARAM_OP_TYPE_BGET_KINEMATIC CKGUID(0x6cf414e6,0xf0a35ec) + +#define PARAM_OP_TYPE_BGET_GRAVITY CKGUID(0x63f81d10,0xd532a5a) +#define PARAM_OP_TYPE_BGET_COLLISION CKGUID(0x57f61ee3,0xef1252a) +#define PARAM_OP_TYPE_BGET_COLLISION_GROUP CKGUID(0xeea6d63,0x2d8a032d) +#define PARAM_OP_TYPE_BGET_SLEEPING CKGUID(0x7ca42afe,0x2665435) + +#define PARAM_OP_TYPE_BIS_SUB_SHAPE_OF CKGUID(0x7ed952ce,0x5160083) + + +#define PARAM_OP_TYPE_BGET_FLAGS CKGUID(0x19263740,0x5dd248a2) +#define PARAM_OP_TYPE_BGET_MATERIAL CKGUID(0x1306375d,0x2bcc3cab) +#define PARAM_OP_TYPE_BGET_ISPOBJECT CKGUID(0xa0d7467,0x76692667) + + +#define PARAM_OP_TYPE_BGET_PVEL CKGUID(0x46bc47fc,0x1a4e6a83) +#define PARAM_OP_TYPE_BGET_LPVEL CKGUID(0x1c7e07fa,0x430a084b) +#define PARAM_OP_TYPE_BGET_MASS CKGUID(0x257d5234,0x362841d4) + +#define PARAM_OP_TYPE_BJ_ISCONNECTED CKGUID(0x51db16ef,0xfb772d0) +#define PARAM_OP_TYPE_BJ_NBJOINTS CKGUID(0x29e20d6c,0x6ebc03d2) + + + +#define PARAM_OP_TYPE_BGET_LDAMP CKGUID(0x532052cd,0x97d4334) +#define PARAM_OP_TYPE_BGET_LDAMPT CKGUID(0x7e6623dd,0x3beb16d1) +#define PARAM_OP_TYPE_BGET_ADAMP CKGUID(0x6c620e3b,0x4c2344d8) +#define PARAM_OP_TYPE_BGET_ADAMPT CKGUID(0x148b07eb,0x563c4ff7) + + +void ParamOpBIsSubShape(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + + CK_ID targetID_Sub; + p2->GetValue(&targetID_Sub); + + int result=0; + + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + + if (target->isSubShape(static_cast(context->GetObject(targetID_Sub)))) + { + result = 1; + } + } + } + } + + res->SetValue(&result); + +} + +////////////////////////////////////////////////////////////////////////// +void ParamOpBGetLVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector vec = target->getLinearVelocity(); + res->SetValue(&vec); + } + } + } +} + +void ParamOpBGetAVelocity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector vec = target->getAngularVelocity(); + res->SetValue(&vec); + } + } + } +} + +void ParamOpBGetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector vec = target->getLinearMomentum(); + res->SetValue(&vec); + } + } + } +} +void ParamOpBGetTorque(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector vec = target->getAngularMomentum(); + res->SetValue(&vec); + } + } + } +} + +void ParamOpBisFixed(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->getActor()->isDynamic(); + res->SetValue(&value); + } + } + } +} +void ParamOpBGetHType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->getHullType(); + res->SetValue(&value); + } + } + } +} + +void ParamOpBisKinematic(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->isKinematic(); + res->SetValue(&value); + } + } + } +} +void ParamOpBisCollider(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->isCollisionEnabled(ent); + res->SetValue(&value); + } + } + } +} +void ParamOpBisGravity(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->isAffectedByGravity(); + res->SetValue(&value); + } + } + } +} + +void ParamOpBGetCollGroup(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->getCollisionsGroup(); + res->SetValue(&value); + } + } + } +} +void ParamOpBIsSleeping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int value = target->isSleeping(); + res->SetValue(&value); + } + } + } +} +void ParamOpBGetFlags(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + target->recalculateFlags(0); + int value = target->getFlags(); + res->SetValue(&value); + } + } + } +} +void ParamOpBIsPObject(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + int result = 0; + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + result = 1; + } + } + } + res->SetValue(&result); +} + +void ParamOpBGetPVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector point; + p2->GetValue(&point); + VxVector vec = target->getPointVelocity(point); + res->SetValue(&vec); + } + } + } +} +void ParamOpBGetLPVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + VxVector point; + p2->GetValue(&point); + VxVector vec = target->getLocalPointVelocity(point); + res->SetValue(&vec); + } + } + } +} + + + + +void ParamOpBGetMass(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + float vec = target->getMass(); + res->SetValue(&vec); + } + } + } +} +void ParamOpBJIsConnected(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + + CK_ID targetIDB; + p2->GetValue(&targetIDB); + + int result = - 1; + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + CK3dEntity *entB = static_cast(context->GetObject(targetIDB)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + pJoint *joint = target->isConnected(entB); + if (joint) + { + result = joint->getType(); + } + } + } + } + res->SetValue(&result); +} +void ParamOpBGetMaterial(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + CK_ID targetID2; + p2->GetValue(&targetID2); + CK3dEntity *ent2 = static_cast(context->GetObject(targetID2)); + + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + pMaterial mat = target->getShapeMaterial(ent2); + pFactory::Instance()->copyTo(res,mat); + } + } + } +} + + +void ParamOpBGetNbJoints(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + if (ent) + { + pWorld *world=GetPMan()->getWorldByBody(ent); + if (world) + { + pRigidBody*target= world->getBody(ent); + if (target) + { + int nbJoints = target->getNbJoints(); + res->SetValue(&nbJoints); + + } + } + } +} + +void PhysicManager::_RegisterParameterOperationsBody() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + + pm->RegisterOperationType(PARAM_OP_TYPE_BJ_NBJOINTS, "bNbJoints"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BJ_NBJOINTS,CKPGUID_INT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetNbJoints); + + + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_MATERIAL, "bMat"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_MATERIAL,VTS_MATERIAL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBGetMaterial); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_VELOCITY, "bVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_VELOCITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetLVelocity); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_AVELOCITY, "bAVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_AVELOCITY,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetAVelocity); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FORCE, "bForce"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FORCE,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetForce); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_TORQUE, "bTorque"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_TORQUE,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetTorque); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_HTYPE, "bHullType"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_HTYPE,VTE_COLLIDER_TYPE,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetHType); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FIXED, "bDynamic"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FIXED,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisFixed); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_KINEMATIC, "bKinematic"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_KINEMATIC,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisKinematic); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_GRAVITY, "bGravity"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_GRAVITY,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisGravity); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_COLLISION, "bCollider"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_COLLISION,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBisCollider); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_COLLISION_GROUP, "bCollGroup"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_COLLISION_GROUP,CKPGUID_INT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetCollGroup); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_SLEEPING, "bSleeping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_SLEEPING,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBIsSleeping); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_FLAGS, "bFlags"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_FLAGS,VTF_BODY_FLAGS,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetFlags); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_ISPOBJECT, "bRegistered"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_ISPOBJECT,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBIsPObject); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_PVEL, "bPointVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_PVEL,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_VECTOR,ParamOpBGetPVel); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_LPVEL, "bLPointVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_LPVEL,CKPGUID_VECTOR,CKPGUID_3DENTITY,CKPGUID_VECTOR,ParamOpBGetLPVel); + + pm->RegisterOperationType(PARAM_OP_TYPE_BGET_MASS, "bMass"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_MASS,CKPGUID_FLOAT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpBGetMass); + + pm->RegisterOperationType(PARAM_OP_TYPE_BJ_ISCONNECTED, "bConnected"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BJ_ISCONNECTED,VTE_JOINT_TYPE,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBJIsConnected); + + pm->RegisterOperationType(PARAM_OP_TYPE_BIS_SUB_SHAPE_OF, "IsSubShape"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_BIS_SUB_SHAPE_OF,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBIsSubShape); + +} + + + diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsJoints.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsJoints.cpp new file mode 100644 index 0000000..10b2ed3 --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsJoints.cpp @@ -0,0 +1,760 @@ +#include +#include "vtPhysXAll.h" + +#define PARAMETER_OP_TYPE_IS_CONNECTED CKGUID(0x2fe947dd,0x783224e9) + +#define PARAM_OP_TYPE_JGET_LIMIT1 CKGUID(0x3678447e,0x30362a74) +#define PARAM_OP_TYPE_JGET_LIMIT2 CKGUID(0xc21ab2,0x465f7f69) +#define PARAM_OP_TYPE_JGET_LIMIT3 CKGUID(0x3ed57b83,0x47ad145f) + +//pMotor : +#define PARAM_OP_TYPE_JMOTOR_SET_TVEL CKGUID(0xa872a4,0x4e8921a4) +#define PARAM_OP_TYPE_JMOTOR_SET_MAXF CKGUID(0x2026057d,0x372684a) +#define PARAM_OP_TYPE_JMOTOR_SET_SPIN_FREE CKGUID(0x4aa2636b,0x734a6d4c) + +#define PARAM_OP_TYPE_JMOTOR_GET_TVEL CKGUID(0x6f91728a,0x29d13cda) +#define PARAM_OP_TYPE_JMOTOR_GET_MAXF CKGUID(0x1e583ea9,0x4305055) +#define PARAM_OP_TYPE_JMOTOR_GET_SPIN_FREE CKGUID(0x50f145b,0x45df2205) + +/************************************************************************/ +/* joint structures : */ +/************************************************************************/ + +void ParamOpJMotorSetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpJMotorSetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpJMotorSetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + +void ParamOpJMotorGetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpJMotorGetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); +void ParamOpJMotorGetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2); + + +void ParamOpJMotorSetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJMotorGetTVel(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJMotorSetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJMotorGetFMAX(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJMotorSetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + int value = 0; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJMotorGetSpinFree(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int value = 0; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + +/************************************************************************/ +/* */ +/************************************************************************/ +#define PARAM_OP_TYPE_JLIMIT_SET_VALUE CKGUID(0x38a829f0,0x47851486) +#define PARAM_OP_TYPE_JLIMIT_SET_RES CKGUID(0x3ce77eb1,0x2e921a87) +#define PARAM_OP_TYPE_JLIMIT_SET_HARD CKGUID(0x111a4a9f,0x54094430) + +#define PARAM_OP_TYPE_JLIMIT_GET_VALUE CKGUID(0xc203321,0x4ca77bd) +#define PARAM_OP_TYPE_JLIMIT_GET_RES CKGUID(0x19f812e7,0x5fb3cfc) +#define PARAM_OP_TYPE_JLIMIT_GET_HARD CKGUID(0x6b1b44cd,0x5efc7f51) + +void ParamOpJLimitSetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJLimitGetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJLimitSetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJLimitGetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJLimitSetHard(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJLimitGetHard(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + +/************************************************************************/ +/* spring : */ +/************************************************************************/ +#define PARAM_OP_TYPE_JSPRING_SET_SPRING CKGUID(0x2e0f1602,0x7f9d30fe) +#define PARAM_OP_TYPE_JSPRING_SET_DAMPER CKGUID(0x7392369,0x168f33a1) +#define PARAM_OP_TYPE_JSPRING_SET_VALUE CKGUID(0x70026320,0x35b41a38) + +#define PARAM_OP_TYPE_JSPRING_GET_SPRING CKGUID(0x3dde73ff,0x550c16ff) +#define PARAM_OP_TYPE_JSPRING_GET_DAMPER CKGUID(0x1f793582,0x11f96df9) +#define PARAM_OP_TYPE_JSPRING_GET_VALUE CKGUID(0x76226303,0x67ba262f) + +void ParamOpJSpringSetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJSpringGetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJSpringSetDamper(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJSpringGetDamper(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJSpringSetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJSpringGetVAlue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + + + + +/************************************************************************/ +/* spring : */ +/************************************************************************/ +#define PARAM_OP_TYPE_JSLIMIT_SET_DAMPING CKGUID(0x24e53be6,0x43bf6178) +#define PARAM_OP_TYPE_JSLIMIT_SET_SPRING CKGUID(0x19ea18da,0x4a8f7902) +#define PARAM_OP_TYPE_JSLIMIT_SET_VALUE CKGUID(0x7abb085e,0x464b16b4) +#define PARAM_OP_TYPE_JSLIMIT_SET_RES CKGUID(0x8eb56f2,0x44a40a2) + +#define PARAM_OP_TYPE_JSLIMIT_GET_DAMPING CKGUID(0x74b33ddd,0x6faa11f1) +#define PARAM_OP_TYPE_JSLIMIT_GET_SPRING CKGUID(0x4440614,0x134514de) +#define PARAM_OP_TYPE_JSLIMIT_GET_VALUE CKGUID(0x455a525d,0x77e17e01) +#define PARAM_OP_TYPE_JSLIMIT_GET_RES CKGUID(0x7d1554b4,0x32a72cd3) + + +void ParamOpJSLimitSetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJSLimitGetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJSLimitSetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJSLimitGetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJSLimitSetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJSLimitGetValue(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + + + + + + + +void ParamOpJSLimitSetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,3,value,false); +} +void ParamOpJSLimitGetRes(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),3,false); + } + } + res->SetValue(&value); +} + + + + + + +/************************************************************************/ +/* spring : */ +/************************************************************************/ +#define PARAM_OP_TYPE_JDRIVE_SET_DAMPING CKGUID(0x2ef2554b,0x50681945) +#define PARAM_OP_TYPE_JDRIVE_SET_SPRING CKGUID(0x657274d7,0x5c23079c) +#define PARAM_OP_TYPE_JDRIVE_SET_FORCE CKGUID(0x54d75463,0x2e343c56) +#define PARAM_OP_TYPE_JDRIVE_SET_TYPE CKGUID(0x37ff7a9d,0x1f1c3013) + +#define PARAM_OP_TYPE_JDRIVE_GET_DAMPING CKGUID(0x3d4b76b7,0xf059e8) +#define PARAM_OP_TYPE_JDRIVE_GET_SPRING CKGUID(0x4abe6b69,0x56615834) +#define PARAM_OP_TYPE_JDRIVE_GET_FORCE CKGUID(0x4ff912df,0x40d1429) +#define PARAM_OP_TYPE_JDRIVE_GET_TYPE CKGUID(0x54a63237,0x1f8a3347) + +void ParamOpJDriveSetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,0,value,false); +} + +void ParamOpJDriveGetDamping(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),0,false); + } + } + res->SetValue(&value); +} +void ParamOpJDriveSetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,1,value,false); +} + + +void ParamOpJDriveGetSpring(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),1,false); + } + } + res->SetValue(&value); +} +void ParamOpJDriveSetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + float value = 0.0f; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,2,value,false); +} + +void ParamOpJDriveGetForce(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + float value = 0.0f; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),2,false); + } + } + res->SetValue(&value); +} + +void ParamOpJDriveSetType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + + if (!GetPMan()->getCurrentFactory()) + { + return; + } + int value = 0; + p2->GetValue(&value); + res->CopyValue(p1->GetRealSource(),false); + vtTools::ParameterTools::SetParameterStructureValue(res,3,value,false); +} +void ParamOpJDriveGetType(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + int value = 0; + if (p1) + { + if (p1->GetRealSource()) + { + value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),3,false); + } + } + res->SetValue(&value); +} + + + + + + + +void ParamOpJIsConnected(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + + CK_ID targetID2; + p2->GetValue(&targetID2); + CK3dEntity *ent2 = static_cast(context->GetObject(targetID2)); + + + if (!pFactory::Instance()->jointCheckPreRequisites(ent,ent2,JT_Distance)) + { + int result = 0; + res->SetValue(&result); + return; + } + + + // the world : + pWorld *worldA=GetPMan()->getWorldByBody(ent); + pWorld *worldB=GetPMan()->getWorldByBody(ent2); + if (!worldA) + { + worldA = worldB; + } + if (!worldA) + { + int result = 0; + + res->SetValue(&result); + return; + + } + + pJoint*joint = static_cast(worldA->getJoint(ent,ent2,JT_Any)); + int result = joint ? 1 : 0; + res->SetValue(&result); + return; + +} + + +void PhysicManager::_RegisterParameterOperationsJoint() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + + pm->RegisterOperationType(PARAMETER_OP_TYPE_IS_CONNECTED, "connected"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_IS_CONNECTED,CKPGUID_BOOL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpJIsConnected); + + + /************************************************************************/ + /* Drive */ + /************************************************************************/ + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_DAMPING, "jDsDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_DAMPING,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,CKPGUID_FLOAT,ParamOpJDriveSetDamping); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_DAMPING, "jDgDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_DAMPING,CKPGUID_FLOAT,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetDamping); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_SPRING, "jDsSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_SPRING,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,CKPGUID_FLOAT,ParamOpJDriveSetSpring); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_SPRING, "jDgSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_SPRING,CKPGUID_FLOAT,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetSpring); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_FORCE, "jDsForce"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_FORCE,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,CKPGUID_FLOAT,ParamOpJDriveSetForce); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_FORCE, "jDgForce"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_FORCE,CKPGUID_FLOAT,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetForce); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_SET_TYPE, "jDsType"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_SET_TYPE,VTS_JOINT_DRIVE,VTS_JOINT_DRIVE,VTE_PHYSIC_JDRIVE_TYPE,ParamOpJDriveSetType); + + pm->RegisterOperationType(PARAM_OP_TYPE_JDRIVE_GET_TYPE, "jDgType"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JDRIVE_GET_TYPE,VTE_PHYSIC_JDRIVE_TYPE,VTS_JOINT_DRIVE,CKPGUID_NONE,ParamOpJDriveGetType); + + /************************************************************************/ + /* Soft Limit */ + /************************************************************************/ + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_DAMPING, "jSLsDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_DAMPING,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetDamping); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_DAMPING, "jSLgDamping"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_DAMPING,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetDamping); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_SPRING, "jSLsSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_SPRING,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetSpring); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_SPRING, "jSLgSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_SPRING,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetSpring); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_VALUE, "jSLsValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_VALUE,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_VALUE, "jSLgValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_VALUE,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_SET_RES, "jSLsRes"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_SET_RES,VTS_JOINT_SLIMIT,VTS_JOINT_SLIMIT,CKPGUID_FLOAT,ParamOpJSLimitSetRes); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSLIMIT_GET_RES, "jSLgRes"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSLIMIT_GET_RES,CKPGUID_FLOAT,VTS_JOINT_SLIMIT,CKPGUID_NONE,ParamOpJSLimitGetRes); + + /************************************************************************/ + /* spring : */ + /************************************************************************/ + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_SET_SPRING, "jSsSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_SET_SPRING,VTS_JOINT_SPRING,VTS_JOINT_SPRING,CKPGUID_FLOAT,ParamOpJSpringSetSpring); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_GET_SPRING, "jSgSpring"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_GET_SPRING,CKPGUID_FLOAT,VTS_JOINT_SPRING,CKPGUID_NONE,ParamOpJSpringGetSpring); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_SET_DAMPER, "jSsDamper"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_SET_DAMPER,VTS_JOINT_SPRING,VTS_JOINT_SPRING,CKPGUID_FLOAT,ParamOpJSpringSetDamper); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_GET_DAMPER, "jSgDamper"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_GET_DAMPER,CKPGUID_FLOAT,VTS_JOINT_SPRING,CKPGUID_NONE,ParamOpJSpringGetDamper); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_SET_VALUE, "jSsValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_SET_VALUE,VTS_JOINT_SPRING,VTS_JOINT_SPRING,CKPGUID_FLOAT,ParamOpJSpringSetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JSPRING_GET_VALUE, "jSgValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JSPRING_GET_VALUE,CKPGUID_FLOAT,VTS_JOINT_SPRING,CKPGUID_NONE,ParamOpJSpringGetVAlue); + + + /************************************************************************/ + /* pJLimit Structure Access : */ + /************************************************************************/ + + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_SET_VALUE, "jLsValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_SET_VALUE,VTS_JLIMIT,VTS_JLIMIT,CKPGUID_FLOAT,ParamOpJLimitSetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_GET_VALUE, "jLgValue"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_GET_VALUE,CKPGUID_FLOAT,VTS_JLIMIT,CKPGUID_NONE,ParamOpJLimitGetValue); + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_SET_RES, "jLsRestitution"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_SET_RES,VTS_JLIMIT,VTS_JLIMIT,CKPGUID_FLOAT,ParamOpJLimitSetRes); + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_GET_RES, "jLgRestitution"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_GET_RES,CKPGUID_FLOAT,VTS_JLIMIT,CKPGUID_NONE,ParamOpJLimitGetRes); + + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_SET_HARD, "jLsHardness"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_SET_HARD,VTS_JLIMIT,VTS_JLIMIT,CKPGUID_FLOAT,ParamOpJLimitSetHard); + + pm->RegisterOperationType(PARAM_OP_TYPE_JLIMIT_GET_RES, "jLgHardness"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JLIMIT_GET_HARD,CKPGUID_FLOAT,VTS_JLIMIT,CKPGUID_NONE,ParamOpJLimitGetHard); + + + /************************************************************************/ + /* pMotor Structure Acess : */ + /************************************************************************/ + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_SET_TVEL, "jMsVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_SET_TVEL,VTS_JOINT_MOTOR,VTS_JOINT_MOTOR,CKPGUID_FLOAT,ParamOpJMotorSetTVel); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_GET_TVEL, "jMgVel"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_GET_TVEL,CKPGUID_FLOAT,VTS_JOINT_MOTOR,CKPGUID_NONE,ParamOpJMotorGetTVel); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_SET_MAXF, "jMsFMax"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_SET_MAXF,VTS_JOINT_MOTOR,VTS_JOINT_MOTOR,CKPGUID_FLOAT,ParamOpJMotorSetFMAX); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_GET_MAXF, "jMgFMax"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_GET_MAXF,CKPGUID_FLOAT,VTS_JOINT_MOTOR,CKPGUID_NONE,ParamOpJMotorGetFMAX); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_SET_SPIN_FREE, "jMsSpinFree"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_SET_SPIN_FREE,VTS_JOINT_MOTOR,VTS_JOINT_MOTOR,CKPGUID_BOOL,ParamOpJMotorSetSpinFree); + + pm->RegisterOperationType(PARAM_OP_TYPE_JMOTOR_GET_SPIN_FREE, "jMgSpingFree"); + pm->RegisterOperationFunction(PARAM_OP_TYPE_JMOTOR_GET_SPIN_FREE,CKPGUID_BOOL,VTS_JOINT_MOTOR,CKPGUID_NONE,ParamOpJMotorGetSpinFree); + + + + + + +} + diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsMisc.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsMisc.cpp new file mode 100644 index 0000000..edb7d22 --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsMisc.cpp @@ -0,0 +1,10 @@ +#include +#include "vtPhysXAll.h" + + +void PhysicManager::_RegisterParameterOperationsMisc() +{ + CKParameterManager *pm = m_Context->GetParameterManager(); + //pm->RegisterOperationType(PARAM_OP_TYPE_BGET_MATERIAL, "bMat"); + //pm->RegisterOperationFunction(PARAM_OP_TYPE_BGET_MATERIAL,VTS_MATERIAL,CKPGUID_3DENTITY,CKPGUID_3DENTITY,ParamOpBGetMaterial); +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsVehicle.cpp b/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsVehicle.cpp new file mode 100644 index 0000000..4fabd4a --- /dev/null +++ b/usr/Src/old/Core/Manager/Parameter/PhysicManager_ParameterOperationsVehicle.cpp @@ -0,0 +1,87 @@ +#include +#include "vtPhysXAll.h" + +#define PARAMETER_OP_TYPE_WHEEL_GETCONTACT CKGUID(0x74654a40,0x74ba3b5b) +#define PARAMETER_OP_TYPE_WDATA_GET_COLLIDER CKGUID(0x4dae6732,0x37740a24) +#define PARAMETER_OP_TYPE_WDATA_GET_MATERIAL CKGUID(0xa45301e,0x73e41d8f) +#define PARAMETER_OP_TYPE_WDATA_GET_CPOINT CKGUID(0x2f731ff8,0xa792311) + + +void ParamOpWheelContactGetCollider(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + if (p1) + { + if (p1->GetRealSource()) + { + CK_ID value = vtTools::ParameterTools::GetValueFromParameterStruct(p1->GetRealSource(),E_WCD_CONTACT_ENTITY,false); + res->SetValue(&value); + } + } +} + +void ParamOpWheelContactGetMaterial(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + CKParameterManager *pm = static_cast(context->GetParameterManager()); + if (p1) + { + if (p1->GetRealSource()) + { + CKParameterOut *materialParameter = vtTools::ParameterTools::GetParameterFromStruct(p1->GetRealSource(),E_WCD_OTHER_MATERIAL_INDEX,false); + if (materialParameter) + { + res->CopyValue(materialParameter); + } + } + } +} + +void ParamOpWheelGetContact(CKContext* context, CKParameterOut* res, CKParameterIn* p1, CKParameterIn* p2) +{ + + CKParameterManager *pm = static_cast(context->GetParameterManager()); + CK_ID targetID; + p1->GetValue(&targetID); + CK3dEntity *ent = static_cast(context->GetObject(targetID)); + pRigidBody *body = NULL; + + //user comes usually with entity which is associated with the wheel and not with the body reference : + body = GetPMan()->getBody(pFactory::Instance()->getMostTopParent(ent)); + if (!body) + return; + + pWheel2 *wheel =(pWheel2*)body->getWheel(ent); + if (!wheel)return; + + pWheelContactData cData = *wheel->getContact(); + + //copy result in the parameter operations result parameter : + pFactory::Instance()->copyTo(res,cData); + +} + + + +void PhysicManager::_RegisterParameterOperationsVehicle() +{ + + CKParameterManager *pm = m_Context->GetParameterManager(); + + + pm->RegisterOperationType(PARAMETER_OP_TYPE_WHEEL_GETCONTACT, "pwGContact"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_WHEEL_GETCONTACT,VTS_WHEEL_CONTACT,CKPGUID_3DENTITY,CKPGUID_NONE,ParamOpWheelGetContact); + + ////////////////////////////////////////////////////////////////////////// + // member retrieve of the type pWheelContactData : + + //other entity : + pm->RegisterOperationType(PARAMETER_OP_TYPE_WDATA_GET_COLLIDER, "wcdGEntity"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_WDATA_GET_COLLIDER,CKPGUID_3DENTITY,VTS_WHEEL_CONTACT,CKPGUID_NONE,ParamOpWheelContactGetCollider); + + //material + pm->RegisterOperationType(PARAMETER_OP_TYPE_WDATA_GET_MATERIAL, "wcdGMaterial"); + pm->RegisterOperationFunction(PARAMETER_OP_TYPE_WDATA_GET_MATERIAL,VTS_MATERIAL,VTS_WHEEL_CONTACT,CKPGUID_NONE,ParamOpWheelContactGetMaterial); + + + +} diff --git a/usr/Src/old/Core/Manager/PhysicManager.cpp b/usr/Src/old/Core/Manager/PhysicManager.cpp new file mode 100644 index 0000000..47bdff9 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManager.cpp @@ -0,0 +1,327 @@ +#include + +#include "vtPhysXAll.h" + +#include +#include + + + +#include "IParameter.h" + + +PhysicManager *manager = NULL; +using namespace xUtils; +using namespace vtAgeia; + +void +PhysicManager::_destruct(xBitSet flags /* = 0 */) +{ + + //################################################################ + // + // some sanity checks + // + assert(mIParameter); + assert(m_Worlds); + assert(manager); + + //################################################################ + // + // Clean instances : + // + SAFE_DELETE(mIParameter); +} +////////////////////////////////////////////////////////////////////////// +PhysicManager::PhysicManager(CKContext* context):CKPhysicManager(context,GUID_MODULE_MANAGER,VTCX_API_ENTRY("PhysicManager")) //Name as used in profiler +{ + + + m_Context->RegisterNewManager(this); + m_Worlds = new pWorldMap(); + manager = this; + + + _Hook3DBBs(); + _HookGenericBBs(); + + _construct(); + + int ss = xLogger::GetInstance()->getItemDescriptions().size(); + int ss2= xLogger::GetInstance()->getLogItems().size(); + xLogger::xLog(ELOGERROR,E_BB,"No Reference Object specified"); + + timer = 0.0f; + mPhysicsSDK = NULL; + DongleHasBasicVersion=0; + DongleHasAdvancedVersion=0; + + _LogErrors = _LogInfo = _LogTrace = _LogWarnings = _LogToConsole = 0; + + + mIParameter = new IParameter(this); + + +} +////////////////////////////////////////////////////////////////////////// +void PhysicManager::cleanAll() +{ + + ////////////////////////////////////////////////////////////////////////// + //destroy all worlds : + if (getWorlds()->Size()) + { + destroyWorlds(); + m_DefaultWorld = NULL; + + } + + ////////////////////////////////////////////////////////////////////////// + //destroy default objects : + + + + ////////////////////////////////////////////////////////////////////////// + //world settings : + if (getDefaultWorldSettings()) + { + SAFE_DELETE(mDefaultWorldSettings); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted default world settings"); + } + + + ////////////////////////////////////////////////////////////////////////// + //default configuration : + if (m_DefaultDocument) + { + SAFE_DELETE(m_DefaultDocument); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted default configuration"); + } + + if (pFactory::Instance()) + { + pFactory::Instance()->reloadConfig("PhysicDefaults.xml"); + } + + if (getPhysicsSDK()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Physic SDK released "); + NxReleasePhysicsSDK(getPhysicsSDK()); + mPhysicsSDK = NULL; + } + + + + _getManagerFlags() = 0 ; + +} + +void PhysicManager::doInit() +{ + //CreateWorlds(0); +} +CKERROR PhysicManager::OnCKPause() +{ + return CK_OK; +} +CKERROR PhysicManager::OnCKPlay() +{ + int a = _LogErrors; + int b = 0; + + + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGERROR,_LogErrors); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGERROR,_LogErrors); + + + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGTRACE,_LogTrace); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGWARNING,_LogWarnings); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGINFO,_LogInfo); + + + try { + populateAttributeFunctions(); + _RegisterAttributeCallbacks(); + } catch(std::exception ex) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Error during Attribute List Populations"); + } catch(...) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Error during Attribute List Populations"); + //systemMessage("System Error"); + } + if (getNbObjects()) + { + _migrateOldCustomStructures(GetContext()->GetCurrentScene()); + + if ( + isFlagOff(_getManagerFlags(),E_MF_PSDK_LOADED) && + isFlagOff(_getManagerFlags(),E_MF_DEFAULT_WORLD_CREATED) && + isFlagOff(_getManagerFlags(),E_MF_FACTORY_CREATED) + ) + { + performInitialization(); + checkWorlds(); + } + } + return CK_OK; +} +CKERROR PhysicManager::PostClearAll() +{ + return CK_OK; +} +CKERROR PhysicManager::OnCKInit() +{ + bindVariables(); + return CK_OK; +} + + +CKERROR PhysicManager::PreSave() +{ + return CK_OK; +} +CKContext* PhysicManager::GetContext() +{ + return manager->m_Context; +} +PhysicManager* PhysicManager::GetInstance() +{ + if (manager) + { + return manager; + } + return NULL; +} +PhysicManager::~PhysicManager(){} + +CKERROR PhysicManager::OnPostCopy(CKDependenciesContext& context) +{ + CKDependenciesContext dependencies_ctx(m_Context); +// dependencies_ctx.SetOperationMode(CK_DEPENDENCIES_SAVE); +/* + dependencies_ctx.StartDependencies(iDep); + + //We scan the group and fill the dependencies context + for (int i=0;iGetObjectCount();i++) + { + CKBeObject* object = iGrp->GetObject(i); + object->PrepareDependencies(dependencies_ctx); + } +*/ + // Build a list of id to save + return CK_OK; + XObjectArray dependencies_list = context.FillDependencies(); + int s = dependencies_list.Size(); + + + + //dependencies_list.PushBack(iGrp->GetID());//add group at the end + + //copy list of objects in ckobjectarray + CKObjectArray* listToSave = CreateCKObjectArray(); + XObjectArray::Iterator it1 = dependencies_list.Begin(); + XObjectArray::Iterator it2 = dependencies_list.End(); + while (it1!=it2) + { + CKObject* object = m_Context->GetObject(*it1); + /*CK_ID cID = object->GetID(); + listToSave->InsertRear(*it1++); + CKSTRING name = object->GetName(); + + CK_ID id2 = context.RemapID(cID); + CK_ID id3 = context.RemapID(cID);*/ + + + + } + + return CK_OK; + + +} +CKERROR PhysicManager::SequenceDeleted(CK_ID *objids,int count) +{ + + + + if (getNbObjects()) + { + if(GetContext()->IsPlaying()) + checkWorlds(); + } + return CK_OK; +} + +CKERROR PhysicManager::SequenceAddedToScene(CKScene *scn,CK_ID *objids,int count) +{ + int isInLoad=GetContext()->IsInLoad(); + int nbOfObjects = 0 ; + if (!GetContext()->IsPlaying()) + { + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(GetPAttribute()); + nbOfObjects = Array.Size(); + if (nbOfObjects) + { + _migrateOldCustomStructures(scn); + } + + + } + + if (getNbObjects()) + { + if(GetContext()->IsPlaying()){ + + + /* + for (int i = 0 ; i < count ; i++ ) + { + CK_ID dstId = objids[i]; + CKBeObject * obj = GetContext()->GetObject() + } + */ + checkWorlds(); + } + } + return CK_OK; +} +CKERROR PhysicManager::SequenceToBeDeleted(CK_ID *objids,int count) +{ + return CK_OK; +} + +CKERROR PhysicManager::SequenceRemovedFromScene(CKScene *scn,CK_ID *objids,int count) +{ + + if (getNbObjects()) + { + if(GetContext()->IsPlaying()) + checkWorlds(); + } + return CK_OK; +} + + +CKERROR PhysicManager::PreClearAll() +{ + + return CK_OK; +} + +CKERROR PhysicManager::OnCKReset() +{ + + + cleanAll(); + _RegisterDynamicParameters(); + + return CK_OK; +} +CKERROR PhysicManager::OnCKEnd() +{ + + unBindVariables(); + + return 0; +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerBody.cpp b/usr/Src/old/Core/Manager/PhysicManagerBody.cpp new file mode 100644 index 0000000..00ba14a --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerBody.cpp @@ -0,0 +1,106 @@ +#include + +#include "vtPhysXAll.h" + +#include "vtStructHelper.h" + +//################################################################ +// +// Prototype +// +XString getDefaultValue(CKParameter *inputParameter) +{ + CustomParametersArrayType& inputArray = GetPMan()->_getCustomStructures(); + XString result; + + int s = inputArray.Size(); + + + + CustomParametersArrayIteratorType it = inputArray.Find(inputParameter->GetGUID()); + if (it == inputArray.End()) + return result; + + using namespace vtTools::ParameterTools; + + int x = 0; + CustomStructure *cStruct = *it; + if (cStruct) + { + cStruct->getArray().size(); + } + + CKParameterTypeDesc *tdescr = GetPMan()->GetContext()->GetParameterManager()->GetParameterTypeDescription( inputParameter->GetType() ); + if( (tdescr->dwFlags & CKPARAMETERTYPE_STRUCT) == 0x00000010 ) + { + int y = cStruct->getArray().size(); + int y2 = cStruct->getArray().size(); + }else{ + } + + return result; +} + +//################################################################ +// +// Not being used +// +void rigidBodyAttributeCallback(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg) +{ + + // recheckWorldsFunc(AttribType,Set,obj,arg); + +} + +//################################################################ +// +// Body functions +// +pRigidBody*PhysicManager::getBody(const char*name,int flags/* =0 */) +{ + + for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) + { + pWorld *w = *it; + if(w) + { + int nbActors = w->getScene()->getNbActors(); + NxActor** actors = w->getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + if (!strcmp(actor->getName(),name) ) + { + + pRigidBody* body =static_cast(actor->userData); + if (body) + { + return body; + } + } + } + } + } + } + return 0; +} +pRigidBody*PhysicManager::getBody(CK3dEntity *ent) +{ + + pWorld* w = getWorldByBody(ent); + if (w) + { + + pRigidBody *body = w->getBody(ent); + if (body) + { + return body; + } + } + + return NULL; +} + + diff --git a/usr/Src/old/Core/Manager/PhysicManagerBodyAttributeFunctions.cpp b/usr/Src/old/Core/Manager/PhysicManagerBodyAttributeFunctions.cpp new file mode 100644 index 0000000..1f72a89 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerBodyAttributeFunctions.cpp @@ -0,0 +1,144 @@ +#include +#include "vtPhysXAll.h" + + +using namespace xUtils; +using namespace vtAgeia; + + +#include "vtAttributeHelper.h" + + +// [3/31/2009 master] Temp ! +#include "IParameter.h" + + + +//################################################################ +// +// Declaration of rigid body related attribute callback function +// +int registerRigidBody(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + + using namespace vtTools::ParameterTools; + int error = 0 ; + + + //---------------------------------------------------------------- + // + // Sanity checks : + // + assert(target); + + CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); + + CKParameterOut *bodyParameter = target->GetAttributeParameter(attributeType); + + assert(bodyParameter); + CKStructHelper sHelper(bodyParameter); + if (sHelper.GetMemberCount() ==0 ) + { //happens when dev is being opened and loads a cmo with physic objects. + return -1; + } + + + + if (set) + { + + pRigidBody* body = GetPMan()->getBody(target); + if (body) + { + return true; + } + //---------------------------------------------------------------- + // + // attribute has been added at run-time, post pone the registration to the next frame. + // + if ( isPostJob && GetPMan()->GetContext()->IsPlaying() ) + { + pAttributePostObject postAttObject(target->GetID(),registerRigidBody,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + } + if(!GetPMan()->GetContext()->IsPlaying()) + return true; + + + pObjectDescr *objDecr = new pObjectDescr(); + IParameter::Instance()->copyTo(objDecr,bodyParameter); + + //---------------------------------------------------------------- + // + // Pivot override ? + // + int attPivot = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); + if (target->HasAttribute(attPivot)){ + IParameter::Instance()->copyTo(objDecr->pivot,target->GetAttributeParameter(attPivot)); + objDecr->mask << OD_Pivot; + } + + //---------------------------------------------------------------- + // + // Pivot override ? + // + int attMass = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); + if (target->HasAttribute(attMass)){ + IParameter::Instance()->copyTo(objDecr->mass,target->GetAttributeParameter(attMass)); + objDecr->mask << OD_Mass; + } + + //---------------------------------------------------------------- + // + // register the body + // + if(!body && !(objDecr->flags & BF_SubShape) ) + { + body = pFactory::Instance()->createRigidBody(target,*objDecr); + if (body) + { + body->setInitialDescription(objDecr); + } + } + + //SAFE_DELETE(objDecr); + + + } + + + //xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"register object"); + + + error++; + + return error; +} + + +/* +//################################################################ +// +// Not being used +// +int registerRigidBody(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + +if (!GetPMan()->GetContext()->IsPlaying() && set) +{ + +using namespace vtTools::ParameterTools; +CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + +XString errString; +errString.Format("attr added"); +xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.Str()); + +XString value = getDefaultValue(distanceParameter); +} + +return 0; +} + +*/ diff --git a/usr/Src/old/Core/Manager/PhysicManagerBuildingBlockOverides3DTransforms.cpp b/usr/Src/old/Core/Manager/PhysicManagerBuildingBlockOverides3DTransforms.cpp new file mode 100644 index 0000000..a5c4fc8 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerBuildingBlockOverides3DTransforms.cpp @@ -0,0 +1,468 @@ +#include +#include "vtPhysXAll.h" + + +#define BB_SET_POSITION_GUID CKGUID(0xe456e78a, 0x456789aa) +#define BB_SET_ORIENTATION_GUID CKGUID(0x625874aa, 0xaa694132) +#define BB_ROTATE_GUID CKGUID(0xffffffee, 0xeeffffff) +#define BB_TRANSLATE_GUID CKGUID(0x000d000d, 0x000d000d) + +#define BB_SET_EORIENTATION_GUID CKGUID(0xc4966d8,0x6c0c6d14) + + +CKBEHAVIORFCT BBSetEOri; + +int BB_SetEOrientationNew(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBSetEOri(context); + + int pUpdate=0; + behaviour->GetLocalParameterValue(1,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setRotation(quat); + + VxVector vectorN(0,0,0); + + int pResetF=0; + behaviour->GetLocalParameterValue(2,&pResetF); + int pResetT=0; + behaviour->GetLocalParameterValue(3,&pResetT); + + int pResetLV=0; + behaviour->GetLocalParameterValue(4,&pResetLV); + int pResetAV=0; + behaviour->GetLocalParameterValue(5,&pResetAV); + + if (pResetF) + { + solid->setLinearMomentum(vectorN); + } + + if (pResetT) + { + solid->setAngularMomentum(vectorN); + } + + if (pResetLV) + { + solid->setLinearVelocity(vectorN); + } + + if (pResetAV) + { + solid->setAngularVelocity(vectorN); + } + + }else + { + pWorld *world = GetPMan()->getWorldByBody(ent); + if (world) + { + solid = world->getBodyFromSubEntity(ent); + if (solid) + { + solid->updateSubShapes(false,false,true); + } + } + } + } + return CK_OK; +} +/************************************************************************/ +/* Set Position : */ +/************************************************************************/ +CKBEHAVIORFCT BBSetPos; +int BB_SetPosNew(const CKBehaviorContext& context) +{ + + + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBSetPos(context); + + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + + + + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + + pWorld *world = GetPMan()->getWorldByBody(ent); + if (!world) + { + return 0; + } + + pRigidBody *solid = world->getBody(ent); + if (solid) + { + VxVector vector(0,0,0); + //behaviour->GetInputParameterValue(0,&vector); + ent->GetPosition(&vector); + solid->setPosition(vector,ent); + + VxVector vectorN(0,0,0); + + int pResetF=0; + behaviour->GetLocalParameterValue(1,&pResetF); + int pResetT=0; + behaviour->GetLocalParameterValue(2,&pResetT); + + int pResetLV=0; + behaviour->GetLocalParameterValue(3,&pResetLV); + int pResetAV=0; + behaviour->GetLocalParameterValue(4,&pResetAV); + + if (pResetF) + { + solid->setLinearMomentum(vectorN); + } + + if (pResetT) + { + solid->setAngularMomentum(vectorN); + } + + if (pResetLV) + { + solid->setLinearVelocity(vectorN); + } + + if (pResetAV) + { + solid->setAngularVelocity(vectorN); + } + }else + { + pWorld *world = GetPMan()->getWorldByBody(ent); + if (world) + { + solid = world->getBodyFromSubEntity(ent); + if (solid) + { + solid->updateSubShapes(false,true,false); + } + } + } + + } + return CK_OK; + +} + +/************************************************************************/ +/* Set Orientation : */ +/************************************************************************/ +CKBEHAVIORFCT BBSetOri; +int BB_SetOrientationNew(const CKBehaviorContext& context) +{ + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBSetOri(context); + + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setRotation(quat); + + VxVector vectorN(0,0,0); + + int pResetF=0; + behaviour->GetLocalParameterValue(1,&pResetF); + int pResetT=0; + behaviour->GetLocalParameterValue(2,&pResetT); + + int pResetLV=0; + behaviour->GetLocalParameterValue(3,&pResetLV); + int pResetAV=0; + behaviour->GetLocalParameterValue(4,&pResetAV); + + if (pResetF) + { + solid->setLinearMomentum(vectorN); + } + + if (pResetT) + { + solid->setAngularMomentum(vectorN); + } + + if (pResetLV) + { + solid->setLinearVelocity(vectorN); + } + + if (pResetAV) + { + solid->setAngularVelocity(vectorN); + } + + }else + { + pWorld *world = GetPMan()->getWorldByBody(ent); + if (world) + { + solid = world->getBodyFromSubEntity(ent); + if (solid) + { + solid->updateSubShapes(false,false,true); + } + } + } + } + return CK_OK; +} +/************************************************************************/ +/* */ +/************************************************************************/ +CKBEHAVIORFCT BBRotate; +int BB_RotateNew(const CKBehaviorContext& context) +{ + + + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBRotate(context); + + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setRotation(quat); + + VxVector vectorN(0,0,0); + + int pResetF=0; + behaviour->GetLocalParameterValue(1,&pResetF); + int pResetT=0; + behaviour->GetLocalParameterValue(2,&pResetT); + + int pResetLV=0; + behaviour->GetLocalParameterValue(3,&pResetLV); + int pResetAV=0; + behaviour->GetLocalParameterValue(4,&pResetAV); + + if (pResetF) + { + solid->setLinearMomentum(vectorN); + } + + if (pResetT) + { + solid->setAngularMomentum(vectorN); + } + + if (pResetLV) + { + solid->setLinearVelocity(vectorN); + } + + if (pResetAV) + { + solid->setAngularVelocity(vectorN); + } + + }else + { + pWorld *world = GetPMan()->getWorldByBody(ent); + if (world) + { + solid = world->getBodyFromSubEntity(ent); + if (solid) + { + solid->updateSubShapes(false,false,true); + } + } + } + + } + return CK_OK; +} +/************************************************************************/ +/* */ +/************************************************************************/ +CKBEHAVIORFCT BBTranslate; +int BB_TranslateNew(const CKBehaviorContext& context) +{ + + + CKBehavior *behaviour = context.Behavior; + CKContext *ctx = context.Context; + + BBTranslate(context); + + int pUpdate=0; + behaviour->GetLocalParameterValue(0,&pUpdate); + if (pUpdate) + { + CK3dEntity *ent = (CK3dEntity *) behaviour->GetTarget(); + if( !ent ) + return CKBR_OWNERERROR; + pRigidBody *solid = GetPMan()->getBody(ent); + if (solid) + { + VxVector pos,scale; + VxQuaternion quat; + Vx3DDecomposeMatrix(ent->GetWorldMatrix(),quat,pos,scale); + solid->setPosition(pos,ent); + + VxVector vectorN(0,0,0); + + int pResetF=0; + behaviour->GetLocalParameterValue(1,&pResetF); + int pResetT=0; + behaviour->GetLocalParameterValue(2,&pResetT); + + int pResetLV=0; + behaviour->GetLocalParameterValue(3,&pResetLV); + int pResetAV=0; + behaviour->GetLocalParameterValue(4,&pResetAV); + + if (pResetF) + { + solid->setLinearMomentum(vectorN); + } + + if (pResetT) + { + solid->setAngularMomentum(vectorN); + } + + if (pResetLV) + { + solid->setLinearVelocity(vectorN); + } + + if (pResetAV) + { + solid->setAngularVelocity(vectorN); + } + }else + { + pWorld *world = GetPMan()->getWorldByBody(ent); + if (world) + { + solid = world->getBodyFromSubEntity(ent); + if (solid) + { + solid->updateSubShapes(false,true,false); + } + } + } + + } + return CK_OK; +} + +/************************************************************************/ +/* */ +/************************************************************************/ +CKERROR PhysicManager::_Hook3DBBs() +{ + + CKBehaviorManager *bm = m_Context->GetBehaviorManager(); + + CKBehaviorPrototype *bproto = CKGetPrototypeFromGuid(BB_SET_EORIENTATION_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBSetEOri = bproto->GetFunction(); + bproto->SetFunction(BB_SetEOrientationNew); + + } + + bproto = CKGetPrototypeFromGuid(BB_SET_POSITION_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBSetPos = bproto->GetFunction(); + bproto->SetFunction(BB_SetPosNew); + + } + + bproto = CKGetPrototypeFromGuid(BB_SET_ORIENTATION_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBSetOri = bproto->GetFunction(); + bproto->SetFunction(BB_SetOrientationNew); + } + + bproto = CKGetPrototypeFromGuid(BB_ROTATE_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBRotate = bproto->GetFunction(); + bproto->SetFunction(BB_RotateNew); + } + bproto = CKGetPrototypeFromGuid(BB_TRANSLATE_GUID); + if(bproto) + { + bproto->DeclareSetting("Update Physics",CKPGUID_BOOL,"true"); + bproto->DeclareSetting("Reset Force",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Torque",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Linear Velocity",CKPGUID_BOOL,"false"); + bproto->DeclareSetting("Reset Angular Velocity",CKPGUID_BOOL,"false"); + BBTranslate = bproto->GetFunction(); + bproto->SetFunction(BB_TranslateNew); + } + return CK_OK; +} diff --git a/usr/Src/old/Core/Manager/PhysicManagerCheckDemo.cpp b/usr/Src/old/Core/Manager/PhysicManagerCheckDemo.cpp new file mode 100644 index 0000000..f5e8afa --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerCheckDemo.cpp @@ -0,0 +1,37 @@ +#include +#include "vtPhysXAll.h" + + +BOOL PhysicManager::checkDemo(CK3dEntity* a) +{ + return true; + + /* + if (!a) + { + return false; + } + //VxVector scale = vtODE::math::BoxGetZero(a); + /*if ( scale.x > 400 || scale.y > 100 || scale.z > 400 ) + { + return false; + } + + if (GetPMan()->DefaultWorld() && GetPMan()->DefaultWorld()->NumBodies() > 30 ) + { + return false; + } + //return true; + CKMesh *mesh = (CKMesh *)a->GetCurrentMesh(); + + if (mesh) + { + int vcount = mesh->GetVertexCount(); + if (vcount ==960 ||vcount ==559 || vcount ==4096 ||vcount ==106 ||vcount ==256 || vcount ==17 || vcount ==24 || vcount == 266 || vcount == 841 ) + { + return true; + } + } + return false; + */ +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerCollision.cpp b/usr/Src/old/Core/Manager/PhysicManagerCollision.cpp new file mode 100644 index 0000000..cd08ced --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerCollision.cpp @@ -0,0 +1,17 @@ +#include +#include "vtPhysXAll.h" + +////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// +struct clist2 +{ + + CK3dEntity *part; + CK3dEntity *obstacle; + CK3dEntity *sub_obstacle; + VxVector pos; + VxVector normal; + float depth; + clist2(CK3dEntity* p , CK3dEntity *o,CK3dEntity*so, VxVector po, VxVector n , float d ) : + part(p) , obstacle(o), sub_obstacle(so), pos(po) , normal (n) , depth (d){} + +}; diff --git a/usr/Src/old/Core/Manager/PhysicManagerData.cpp b/usr/Src/old/Core/Manager/PhysicManagerData.cpp new file mode 100644 index 0000000..f3d2e30 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerData.cpp @@ -0,0 +1,1055 @@ +#include +#include "vtPhysXAll.h" +#include "IParameter.h" + + +XString PhysicManager::_getConfigPath() +{ + + XString result; + + + CKPathManager *pm = (CKPathManager*)this->m_Context->GetPathManager(); + + //pm->OpenSubFile() + + XString configFile("DonglePaths.ini"); + XString section("Paths"); + + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,configFile); + + + int errorLine; + XString errorText; + VxConfiguration config; + VxConfigurationSection *tsection = NULL; + VxConfigurationEntry *entry = NULL; + + if (!config.BuildFromFile(Ini, errorLine, errorText)) + { + MessageBox(NULL,"Cannot open DonglePath.Ini in Virtools directory",0,MB_OK|MB_ICONERROR); + return XString("none"); + } + + if ((tsection = config.GetSubSection((char*)section.Str(), FALSE)) != NULL) + { + + ConstEntryIt it = tsection->BeginChildEntry(); + VxConfigurationEntry *sEntry = NULL; + + + char newPath[MAX_PATH]; + while (sEntry=tsection->GetNextChildEntry(it)) + { + if (sEntry!=NULL) + { + const char * value = sEntry->GetValue(); + XString path(value); + + FILE *file = fopen(path.CStr(),"r"); + if (file) + { + fclose(file); + return path; + } + } + } + MessageBox(NULL,"Couldnt find any valid license file in the DonglePaths.Ini",0,MB_OK|MB_ICONERROR); + } + return result; +} + + +void PhysicManager::bindVariables() +{ + + CKVariableManager* vm = m_Context->GetVariableManager(); + if( !vm ) + return; + + pSDKParameters& p = getSDKParameters(); + + vm->Bind( + "Physic/Skin Width", &p.SkinWidth, 0.025f, VxVar::COMPOSITIONBOUND, + "Default value for pShape::skinWidth."); + + vm->Bind( + "Physic/Default Sleep Linear Velocity Squared", &p.DefaultSleepLinVelSquared, 0.15f*0.15f, VxVar::COMPOSITIONBOUND, + "The default linear velocity, squared, below which objects start going to sleep. Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set."); + + vm->Bind( + "Physic/Default Sleep Angular Velocity Squared", &p.DefaultSleepAngVel_squared, 0.14f * 0.14f, VxVar::COMPOSITIONBOUND, + "The default angular velocity, squared, below which objects start going to sleep. Note: Only makes sense when the pSDKP_BF_ENERGY_SLEEP_TEST is not set."); + + vm->Bind( + "Physic/Bounce Threshold", &p.BounceThreshold , -2.0f , VxVar::COMPOSITIONBOUND, + "A contact with a relative velocity below this will not bounce."); + + vm->Bind( + "Physic/Dynamic Friction Scaling", &p.DynFrictScaling,1.0f , VxVar::COMPOSITIONBOUND, + "This lets the user scale the magnitude of the dynamic friction applied to all objects. "); + + + vm->Bind( + "Physic/Static Friction Scaling", &p.StaFrictionScaling,1.0f,VxVar::COMPOSITIONBOUND, + "This lets the user scale the magnitude of the static friction applied to all objects."); + + + + vm->Bind( + "Physic/Maximum Angular Velocity", &p.MaxAngularVelocity , 7.0f, VxVar::COMPOSITIONBOUND, + "See the comment for pRigidBody::setMaxAngularVelocity() for details."); + + + vm->Bind( + "Physic/Continuous Collision Detection", &p.ContinuousCD ,0.0f, VxVar::COMPOSITIONBOUND, + "Enable/disable continuous collision detection (0.0f to disable)."); + + vm->Bind( + "Physic/Adaptive Force", &p.AdaptiveForce ,1.0f , VxVar::COMPOSITIONBOUND, + "Used to enable adaptive forces to accelerate convergence of the solver. "); + + + vm->Bind( + "Physic/Collision Veto Jointed", &p.CollVetoJointed , 1.0f , VxVar::COMPOSITIONBOUND, + "Controls default filtering for jointed bodies. True means collision is disabled."); + + vm->Bind( + "Physic/Trigger Trigger Callback", &p.TriggerTriggerCallback, 1.0f , VxVar::COMPOSITIONBOUND, + "Controls whether two touching triggers generate a callback or not."); + + + + vm->Bind( + "Physic/CCD Epsilon", &p.CCDEpsilon,0.01f, VxVar::COMPOSITIONBOUND, + "Distance epsilon for the CCD algorithm."); + + vm->Bind( + "Physic/Solver Convergence Threshold", &p.SolverConvergenceThreshold, 0.0f , VxVar::COMPOSITIONBOUND, + "Used to accelerate solver."); + + + + vm->Bind( + "Physic/BBox Noise Level", &p.BBoxNoiseLevel, 0.001f, VxVar::COMPOSITIONBOUND, + "Used to accelerate HW Broad Phase. "); + + vm->Bind( + "Physic/Implicit Sweep Cache Size", &p.ImplicitSweepCacheSize, 5.0f , VxVar::COMPOSITIONBOUND, + "Used to set the sweep cache size. "); + + vm->Bind( + "Physic/Default Sleep Energy", &p.DefaultSleepEnergy, 0.005f, VxVar::COMPOSITIONBOUND, + "The default sleep energy threshold. Objects with an energy below this threshold are allowed to go to sleep. Note: Only used when the pSDKP_BF_ENERGY_SLEEP_TEST flag is set."); + + vm->Bind( + "Physic/Constant Fluid Max Packets", &p.ConstantFluidMaxPackets, 925, VxVar::COMPOSITIONBOUND, + " Constant for the maximum number of packets per fluid. Used to compute the fluid packet buffer size in NxFluidPacketData."); + + vm->Bind( + "Physic/Constant Fluid Maximum Particles Per Step", &p.ConstantFluidMaxParticlesPerStep, 4096, VxVar::COMPOSITIONBOUND, + "Constant for the maximum number of new fluid particles per frame."); + + vm->Bind( + "Physic/Improved Spring Solver", &p.ImprovedSpringSolver,1.0f , VxVar::COMPOSITIONBOUND, + "Enable/disable improved spring solver for joints and wheel shapes."); + + ////////////////////////////////////////////////////////////////////////// + pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); + + + vm->Bind( + "Physic Debugger/Host", &dbgSetup.mHost,XString("localhost"), VxVar::COMPOSITIONBOUND, + "Specifies the host running a debugger"); + + vm->Bind( + "Physic Debugger/Port", &dbgSetup.port,5425, VxVar::COMPOSITIONBOUND, + "Specifies the port of the remote debugger"); + + vm->Bind( + "Physic Debugger/Enabled", &dbgSetup.enabled,0, VxVar::COMPOSITIONBOUND, + "Enables/Disables the remote debugger"); + + vm->Bind( + "Physic Console Logger/Errors", &_LogErrors,0, VxVar::COMPOSITIONBOUND, + "Log Errors"); + + vm->Bind( + "Physic Console Logger/Infos", &_LogInfo,0, VxVar::COMPOSITIONBOUND, + "Log Infos"); + + vm->Bind( + "Physic Console Logger/Trace", &_LogTrace,0, VxVar::COMPOSITIONBOUND, + "Log Trace"); + + vm->Bind( + "Physic Console Logger/Warnings", &_LogWarnings,0, VxVar::COMPOSITIONBOUND, + "Log Warnings"); + + vm->Bind( + "Physic Console Logger/Console", &_LogWarnings,0, VxVar::COMPOSITIONBOUND, + "Console"); + + +} + +void PhysicManager::unBindVariables() +{ + + + CKVariableManager* vm = m_Context->GetVariableManager(); + if( !vm ) + return; + + pSDKParameters& p = getSDKParameters(); + + + vm->UnBind( "Physic Console Logger/Errors" ); + vm->UnBind( "Physic Console Logger/Infos" ); + vm->UnBind( "Physic Console Logger/Trace" ); + vm->UnBind( "Physic Console Logger/Warnings" ); + vm->UnBind( "Physic Console Logger/Console" ); + + + + vm->UnBind("Physic/Skin Width"); + vm->UnBind("Physic/Default Sleep Linear Velocity Squared"); + vm->UnBind( "Physic/Default Sleep Angular Velocity Squared "); + vm->UnBind( "Physic/Bounce Threshold"); + vm->UnBind( "Physic/Dynamic Friction Scaling"); + vm->UnBind( "Physic/Static Friction Scaling"); + vm->UnBind( "Physic/Maximum Angular Velocity"); + vm->UnBind( "Physic/Continuous Collision Detection"); + vm->UnBind( "Physic/Adaptive Force "); + vm->UnBind( "Physic/Collision Veto Jointed "); + vm->UnBind( "Physic/Trigger Trigger Callback"); + vm->UnBind( "Physic/CCD Epsilon"); + vm->UnBind( "Physic/Solver Convergence Threshold"); + vm->UnBind( "Physic/BBox Noise Level"); + vm->UnBind( "Physic/Implicit Sweep Cache Size"); + vm->UnBind( "Physic/Default Sleep Energy"); + vm->UnBind( "Physic/Constant Fluid Max Packets"); + vm->UnBind( "Physic/Constant Fluid Maximum Particles Per Step"); + vm->UnBind( "Physic/Improved Spring Solver" ); + + + + vm->UnBind( "Physic Debugger/Host" ); + vm->UnBind( "Physic Debugger/Port" ); + vm->UnBind( "Physic Debugger/Enabled" ); + +} + + + +#define PMANAGER_CHUNKID 1005 +#define PMANAGER_SAVE_VERSION 3 +#define PMANAGER_FLAGS 0 +#define PMANAGER_USER_ENUM_IDENTIFIER 11005 + +int PhysicManager::_migrateOldCustomStructures(CKScene *scnene) +{ + + bool bIsLoading = ctx()->IsInLoad(); + //CKObject* o = ctx->GetObject(ol[CKCID_MESH]); + int count = ctx()->GetObjectsCountByClassID(CKCID_3DOBJECT); + if (!count) + return 0; + + +// CK_ID* ol = ctx->GetObjectsListByClassID(i); + + XString errMessage; + int nbOfObjects = 0 ; + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(GetPAttribute()); + nbOfObjects = Array.Size(); + + if (nbOfObjects==0) + return 0; + + + + if (!scnene) + return 0; + + int attOld = GetPAttribute(); + int attNew = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + + int nbRecovered=0; + + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + int cCount = attman->GetAttributeListPtr(GetPAttribute()).Size(); + if (!cCount) + break; + + CK3dEntity*target = static_cast(*it); + if (!target)//shit happens + break; + + CKParameterOut * pOld =target->GetAttributeParameter(attOld); + if (!pOld)//shit happens + break; + + pObjectDescr * oDescr = pFactory::Instance()->createPObjectDescrFromParameter(pOld); + if (!oDescr)//shit happens + continue; + + + //---------------------------------------------------------------- + // + // fix up : + // + + //hierarchy + bool hierarchy =false; + if( (oDescr->flags & BF_Hierarchy) || oDescr->hirarchy ) + hierarchy = true; + + if (hierarchy) + oDescr->flags << BF_Hierarchy; + + + oDescr->massOffsetLinear = oDescr->massOffset; + oDescr->pivotOffsetLinear = oDescr->shapeOffset; + + //---------------------------------------------------------------- + // + // attach new attribute parameter + // + target->SetAttribute(attNew); + CKParameterOut *newPar = target->GetAttributeParameter(attNew); + if (newPar) + { + IParameter::Instance()->copyTo(newPar,oDescr); + } + + //---------------------------------------------------------------- + // + // clean old attribute + // + target->RemoveAttribute(attOld); + //---------------------------------------------------------------- + // + // set IC + // + + + //----- Restore the IC + if(target->IsInScene(scnene)) + { + CKStateChunk *chunk = scnene->GetObjectInitialValue(target); + if(chunk) + { + CKStateChunk *chunk = CKSaveObjectState(target); + scnene->SetObjectInitialValue(target,chunk); + } + } + + it = Array.Begin(); + + SAFE_DELETE(oDescr); + + nbRecovered++; + + //---------------------------------------------------------------- + // + // cleanup + // + + } + if (attman->GetAttributeListPtr(GetPAttribute()).Size() >0) + { + _migrateOldCustomStructures(GetContext()->GetCurrentScene()); + } + + /* + errMessage.Format("nub of old objects recovered: %d",nbRecovered); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMessage.Str()); + + */ + return nbOfObjects; + + +} + +CKERROR PhysicManager::PostLoad() +{ + CKScene *scene = GetContext()->GetCurrentScene(); + _migrateOldCustomStructures(scene); + + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Post Load"); + return true; +} + + +void PhysicManager::setPSDKParameters(pSDKParameters¶m) +{ + + if (!getPhysicsSDK()) + return ; + + getPhysicsSDK()->setParameter((NxParameter)pSDKP_SkinWidth,param.SkinWidth); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_DefaultSleepLinVelSquared,param.DefaultSleepLinVelSquared); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_DefaultSleepAngVelSquared,param.DefaultSleepAngVel_squared); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_BounceThreshold,param.BounceThreshold); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_DynFrictScaling,param.DynFrictScaling); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_StaFrictionScaling,param.StaFrictionScaling); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_MaxAngularVelocity,param.MaxAngularVelocity); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ContinuousCD,param.ContinuousCD); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_AdaptiveForce,param.AdaptiveForce); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_CollVetoJointed,param.CollVetoJointed); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_TriggerTriggerCallback,param.TriggerTriggerCallback); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_CCDEpsilon,param.CCDEpsilon); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_SolverConvergenceThreshold,param.SolverConvergenceThreshold); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_BBoxNoiseLevel,param.BBoxNoiseLevel); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ImplicitSweepCacheSize,param.ImplicitSweepCacheSize); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_DefaultSleepEnergy,param.DefaultSleepEnergy); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ConstantFluidMaxPackets,param.ConstantFluidMaxPackets); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ConstantFluidMaxParticlesPerStep,param.ConstantFluidMaxParticlesPerStep); + getPhysicsSDK()->setParameter((NxParameter)pSDKP_ImprovedSpringSolver,param.ImprovedSpringSolver); + + + + + +} + +CKStateChunk* PhysicManager::SaveData(CKFile* SavedFile) +{ + + if (!getNbObjects()) + { + return NULL; + } + + + CKStateChunk *chunk = CreateCKStateChunk(PMANAGER_CHUNKID, SavedFile); + if (!chunk) + return NULL; + chunk->StartWrite(); + chunk->WriteIdentifier(PMANAGER_CHUNKID); + chunk->WriteInt(PMANAGER_SAVE_VERSION); + chunk->WriteInt(PMANAGER_FLAGS); + + + CKVariableManager* vm = m_Context->GetVariableManager(); + if( !vm ) + return NULL; + + + pSDKParameters& p = getSDKParameters(); + + + CKVariableManager::Variable *var = vm->GetVariable("Physic/Skin Width"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.SkinWidth); + } + + var = vm->GetVariable("Physic/Default Sleep Linear Velocity Squared"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.DefaultSleepLinVelSquared); + } + + var = vm->GetVariable("Physic/Default Sleep Angular Velocity Squared"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.DefaultSleepAngVel_squared); + } + + + + var = vm->GetVariable("Physic/Bounce Threshold"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.BounceThreshold); + } + + + + var = vm->GetVariable("Physic/Dynamic Friction Scaling"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.DynFrictScaling); + } + + + + var = vm->GetVariable("Physic/Static Friction Scaling"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.StaFrictionScaling); + } + + var = vm->GetVariable("Physic/Maximum Angular Velocity"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.MaxAngularVelocity); + } + + var = vm->GetVariable("Physic/Continuous Collision Detection"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ContinuousCD); + } + + var = vm->GetVariable("Physic/Adaptive Force"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.AdaptiveForce); + } + + var = vm->GetVariable("Physic/Collision Veto Jointed"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.CollVetoJointed); + } + + var = vm->GetVariable("Physic/Trigger Trigger Callback"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.TriggerTriggerCallback); + } + + var = vm->GetVariable("Physic/CCD Epsilon"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.CCDEpsilon); + } + + var = vm->GetVariable("Physic/Solver Convergence Threshold"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.SolverConvergenceThreshold); + } + + var = vm->GetVariable("Physic/BBox Noise Level"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.BBoxNoiseLevel); + } + + var = vm->GetVariable("Physic/Implicit Sweep Cache Size"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ImplicitSweepCacheSize); + } + + + var = vm->GetVariable("Physic/Default Sleep Energy"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.DefaultSleepEnergy); + } + + + + + var = vm->GetVariable("Physic/Constant Fluid Max Packets"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ConstantFluidMaxPackets); + } + + + + var = vm->GetVariable("Physic/Constant Fluid Maximum Particles Per Step"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ConstantFluidMaxParticlesPerStep); + } + + + + var = vm->GetVariable("Physic/Improved Spring Solver"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteFloat(p.ImprovedSpringSolver); + } + + + + + ////////////////////////////////////////////////////////////////////////// + + pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); + + var = vm->GetVariable("Physic Debugger/Host"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteString(dbgSetup.mHost.CStr()); + } + + var = vm->GetVariable("Physic Debugger/Port"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(dbgSetup.port); + } + + var = vm->GetVariable("Physic Debugger/Enabled"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(dbgSetup.enabled); + } + + + + var = vm->GetVariable("Physic Console Logger/Errors"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogErrors); + } + + var = vm->GetVariable("Physic Console Logger/Infos"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogInfo); + } + + var = vm->GetVariable("Physic Console Logger/Trace"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogTrace); + } + + var = vm->GetVariable("Physic Console Logger/Warnings"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogWarnings); + } + + + _saveUserEnumeration(chunk,SavedFile); + + var = vm->GetVariable("Physic Console Logger/Console"); + if (var) + { + chunk->WriteInt(var->IsCompositionDepending()); + chunk->WriteInt(_LogToConsole); + } + + chunk->CloseChunk(); + return chunk; +} + +CKERROR PhysicManager::LoadData(CKStateChunk *chunk,CKFile* LoadedFile) +{ + + + assert(LoadedFile != 0); + if (!chunk) + return CKERR_INVALIDPARAMETER; + + + chunk->StartRead(); + + if (chunk->SeekIdentifier(PMANAGER_CHUNKID)) + { + + // Check the version + int version = chunk->ReadInt(); + + // Check the flags + int flags = chunk->ReadInt(); + + CKVariableManager* vm = m_Context->GetVariableManager(); + if( !vm ) + return NULL; + + + pSDKParameters& p = getSDKParameters(); + + + ////////////////////////////////////////////////////////////////////////// + int isInCMO = chunk->ReadInt(); + float v = chunk->ReadFloat(); + + if (isInCMO) + { + p.SkinWidth = v; + } + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.DefaultSleepLinVelSquared = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.DefaultSleepAngVel_squared = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.BounceThreshold = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.DynFrictScaling = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.StaFrictionScaling = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.MaxAngularVelocity = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ContinuousCD = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.AdaptiveForce = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.CollVetoJointed = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.TriggerTriggerCallback = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.CCDEpsilon = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.SolverConvergenceThreshold = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.BBoxNoiseLevel = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ImplicitSweepCacheSize = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.DefaultSleepEnergy = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ConstantFluidMaxPackets = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ConstantFluidMaxParticlesPerStep = v; + } + + + ////////////////////////////////////////////////////////////////////////// + isInCMO = chunk->ReadInt(); + v = chunk->ReadFloat(); + + if (isInCMO) + { + p.ImprovedSpringSolver = v; + } + + + ////////////////////////////////////////////////////////////////////////// + pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); + + isInCMO = chunk->ReadInt(); + XString host = chunk->ReadString(); + if (isInCMO) + { + dbgSetup.mHost = host; + } + + + isInCMO = chunk->ReadInt(); + int port = chunk->ReadInt(); + + if (isInCMO) + { + dbgSetup.port= port; + } + + isInCMO = chunk->ReadInt(); + int enabled = chunk->ReadInt(); + + if (isInCMO) + { + dbgSetup.enabled= enabled; + } + + + + ////////////////////////////////////////////////////////////////////////// + + isInCMO = chunk->ReadInt(); + int val = chunk->ReadInt(); + if (isInCMO==1 && val >=-1000 ) + { + _LogErrors=val; + } + if (isInCMO==0) + { + _LogErrors=1; + } + + isInCMO = chunk->ReadInt(); + val = chunk->ReadInt(); + if (isInCMO==1 && val >=-1000 ) + { + _LogInfo=val; + } + + isInCMO = chunk->ReadInt(); + val = chunk->ReadInt(); + if (isInCMO==1&& val >=-1000) + { + _LogTrace=val; + } + + isInCMO = chunk->ReadInt(); + val = chunk->ReadInt(); + if (isInCMO==1&& val >=-1000 ) + { + _LogWarnings=val; + } + + _loadUserEnumeration(chunk,LoadedFile); + + isInCMO = chunk->ReadInt(); + val = chunk->ReadInt(); + if (isInCMO==1&& val >=-1000 ) + { + _LogToConsole=val; + } + chunk->CloseChunk(); + + } + return CK_OK; +} + + + +void PhysicManager::_saveUserEnumeration(CKStateChunk *chunk,CKFile* SavedFile) +{ + ////////////////////////////////////////////////////////////////////////// + //write a identifier, just to ensure due the load we are at right seek point ! + + chunk->WriteInt(PMANAGER_USER_ENUM_IDENTIFIER); + + /////////////////////////////////////////////////////////////////////////// + //write out the the user enumeration for pWDominanceGroups + XString enumDescription = getEnumDescription(m_Context->GetParameterManager(),VTE_PHYSIC_DOMINANCE_GROUP); + XString enumDescriptionCollGroup = getEnumDescription(m_Context->GetParameterManager(),VTE_PHYSIC_BODY_COLL_GROUP); + + XString errString; + errString.Format("Writing dominance enum :%s",enumDescription.Str()); + + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errString.CStr()); + + chunk->WriteString(enumDescription.CStr()); + chunk->WriteString(enumDescriptionCollGroup.CStr()); + +} + +void PhysicManager::_loadUserEnumeration(CKStateChunk *chunk,CKFile* LoadedFile) +{ + + int enumIdentfier = chunk->ReadInt(); + + if (enumIdentfier!=PMANAGER_USER_ENUM_IDENTIFIER) return; + + CKParameterManager *pm = m_Context->GetParameterManager(); + ////////////////////////////////////////////////////////////////////////// + //we read our dominance group enumeration back : + + XString dominanceGroupEnumerationString; + int strEnumDescSizeDG = chunk->ReadString(dominanceGroupEnumerationString); + + XString collisionGroupEnumerationString; + int strEnumDescSizeCG = chunk->ReadString(collisionGroupEnumerationString); + + XString errString; + errString.Format("Loading dominance enum :%s",dominanceGroupEnumerationString.Str()); + //xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,dominanceGroupEnumerationString.CStr()); + + CKParameterType pType = pm->ParameterGuidToType(VTE_PHYSIC_DOMINANCE_GROUP); + if (pType!=-1 && dominanceGroupEnumerationString.Length()) + { + pm->ChangeEnumDeclaration(VTE_PHYSIC_DOMINANCE_GROUP,dominanceGroupEnumerationString.Str()); + } + + //---------------------------------------------------------------- + // + // collision group + // + pType = pm->ParameterGuidToType(VTE_PHYSIC_BODY_COLL_GROUP); + if (pType!=-1 && collisionGroupEnumerationString.Length()) + { + XString enumDescriptionCollGroup = getEnumDescription(m_Context->GetParameterManager(),VTE_PHYSIC_BODY_COLL_GROUP); + + pm->ChangeEnumDeclaration(VTE_PHYSIC_BODY_COLL_GROUP,collisionGroupEnumerationString.Str()); + + //---------------------------------------------------------------- + // + // + // + CKEnumStruct *eStruct = pm->GetEnumDescByType(pType); + if (eStruct) + { + int a = eStruct->GetNumEnums(); + if (a) + { + XString enumString = eStruct->GetEnumDescription(0); + if (!enumString.Length()) + { + pm->ChangeEnumDeclaration(VTE_PHYSIC_BODY_COLL_GROUP,enumDescriptionCollGroup.Str()); + } + } + int ab = eStruct->GetNumEnums(); + + } + + } + + +} +CKERROR PhysicManager::PostSave() +{ + + return CK_OK; +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerDongle.cpp b/usr/Src/old/Core/Manager/PhysicManagerDongle.cpp new file mode 100644 index 0000000..88e8f88 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerDongle.cpp @@ -0,0 +1,328 @@ +#include +#include "vtPhysXAll.h" + +#include "pConfig.h" + +#ifdef DONGLE_VERSION + + #include "matrix32.h" + +#endif + + +long DataIn[256]; /* Buffer to read the Dongle data */ +long DataOut[256]; /* Buffer for data to be stored */ +long DataBlock[2]; /* Data buffer for Encrypt/Decrypt */ +short RetCode; /* Return value */ +long API_Version; /* Version number of the Matrix-API */ +long DNG_Version; /* Dongle version number */ +short DNG_LPTADR; /* Adress of LPT port */ +short DNG_Count; /* Number of Dongles connected */ +short DNG_Mem; /* Memory size of Dongle */ +short DNG_MaxVar; /* Maximum number of data fields */ +short AppSlot; /* Application-Slot for Network access */ +short i; + + + +int netMode = 0; +short DNG_Port = 1; +long UserCode = 4002529; + +int DONGLE_BASIC_VERSION_KEY_1 = 28071977; +int DONGLE_BASIC_VERSION_KEY_2 = 77917082; + +int DONGLE_BASIC_VERSION_KEY_1_ENC = 364898188; +int DONGLE_BASIC_VERSION_KEY_2_ENC = 930141357; + + + +int DONGLE_ADVANCED_VERSION_KEY1 = 56143954; +int DONGLE_ADVANCED_VERSION_KEY2 = 45934165; + + +extern PhysicManager*manager; + + +#ifdef DONGLE_VERSION + + +#pragma comment(lib,"matrix32.lib") + + + +void PhysicManager::_initResources(int flags){ + + + + // Init Matrix-API + RetCode = Init_MatrixAPI(); + if(RetCode < 0) + { + printf("Init_MatrixAPI failed %d \n", RetCode); + exit; + } + + API_Version = GetVersionAPI(); + if(API_Version == 0) + { + printf("Cannot read API-Version! \n"); + Release_MatrixAPI(); + return; + } + + // Search for number of Dongles at DNG_Port + DNG_Port = Dongle_Find(); + DNG_Count = Dongle_Count(DNG_Port); + + long test = 0 ; + if(DNG_Count > 0) + { + //manager->m_Context->OutputToConsoleEx("Matrix-Modules at Port %d: %d \n", DNG_Port, DNG_Count); + } + else + { + XString donglePath = _getConfigPath(); + + //manager->m_Context->OutputToConsoleEx("Cannot find Matrix-Modules at Port %d ! \n", DNG_Port); + + //return; + //goto NETWORK_CHECK; + + int ret = SetConfig_MatrixNet(1,donglePath.Str()); + int DNG_NR = 1; + AppSlot = 1; + ret = LogIn_MatrixNet(UserCode, AppSlot, DNG_NR); + if (ret<=0) + { + MessageBox(NULL,"Couldn't find Dongle!",0,MB_OK|MB_ICONERROR); + this->DongleHasBasicVersion=0; + this->DongleHasAdvancedVersion=0; + //Release_MatrixAPI(); + return; + } + + + netMode = 1; + DNG_Port = Dongle_Find(); + DNG_Count = Dongle_Count(DNG_Port); + + if(DNG_Count == 0) + { + manager->m_Context->OutputToConsoleEx("Couldn't find Dongle"); + } + + } + + + DNG_Mem = Dongle_MemSize(DNG_Count, DNG_Port); + if(DNG_Mem > 0) + { + //manager->m_Context->OutputToConsoleEx("MemSize of Matrix-Module %d at Port %d: %d Bytes \n", DNG_Count, DNG_Port, DNG_Mem); + + } + else + { + //manager->m_Context->OutputToConsoleEx("Cannot read MemSize! \n"); + Release_MatrixAPI(); + return; + } + + RetCode = Dongle_ReadData(UserCode, DataIn,6, DNG_Count, DNG_Port); + if(RetCode < 0) + { + m_Context->OutputToConsoleEx("Data Read-Error! \n"); + Release_MatrixAPI(); + return; + } + + + DataBlock[0] = 28071977; /* Clear Data */ + DataBlock[1] = 77917082; /* Clear Data */ + + + long DataBlockKeyBasic[2]; + DataBlockKeyBasic[0] = DataIn[2]; + DataBlockKeyBasic[1] = DataIn[3]; + + long DataBlockKeyAdvanced[2]; + DataBlockKeyAdvanced[0] = DataIn[4]; + DataBlockKeyAdvanced[1] = DataIn[5]; + + RetCode = Dongle_DecryptData(UserCode, DataBlockKeyBasic, DNG_Count, DNG_Port); + RetCode = Dongle_DecryptData(UserCode, DataBlockKeyAdvanced, DNG_Count, DNG_Port); + + + + + if (netMode) + { + + if (DataBlockKeyBasic[0]==DONGLE_BASIC_VERSION_KEY_1_ENC && DataBlockKeyBasic[1]==DONGLE_BASIC_VERSION_KEY_2_ENC ) + { + DongleHasBasicVersion= 1; + } + + }else + { + if (DataBlockKeyBasic[0]==DONGLE_BASIC_VERSION_KEY_1 && DataBlockKeyBasic[1]==DONGLE_BASIC_VERSION_KEY_2 ) + { + DongleHasBasicVersion= 1; + } + + if (DataBlockKeyAdvanced[0]==DONGLE_ADVANCED_VERSION_KEY1 && DataBlockKeyAdvanced[1]==DONGLE_ADVANCED_VERSION_KEY2) + { + DongleHasAdvancedVersion=1; + } + } + + Release_MatrixAPI(); + + +} + +#endif + + + +/* +#ifdef REDIST +#endif +*/ + +/* +#ifdef DEMO_ONLY + + void FindResourceX() + { + + } + +#endif +*/ + + + +/* +#if defined (DONGLE_VERSION) + + +void PhysicManager::makeDongleTest() +{ + //FindResourceX(); + +} +*/ + + + +/* + +void MODULE_API FindResourceX() +{ + + + RetCode = Init_MatrixAPI(); + if(RetCode < 0) + { + printf("Init_MatrixAPI failed %d \n", RetCode); + exit; + } + + + API_Version = GetVersionAPI(); + if(API_Version == 0) + { + printf("Cannot read API-Version! \n"); + Release_MatrixAPI(); + return; + } + else + { + // printf("Version of Matrix-API: %d.%d \n", HIWORD(API_Version), LOWORD(API_Version)); + // manager->m_Context->OutputToConsoleEx("Version of Matrix-API: %d.%d \n", HIWORD(API_Version), LOWORD(API_Version)); + } + + + int port = Dongle_Find(); + DNG_Count = Dongle_Count(port); + DNG_Port = port; + + if(DNG_Count > 0) + { + //manager->m_Context->OutputToConsoleEx("Matrix-Modules at Port %d: %d \n", DNG_Port, DNG_Count); + } + else + { + //goto NETWORK + //manager->m_Context->OutputToConsoleEx("Cannot find Matrix-Modules at Port %d ! \n", DNG_Port); + Release_MatrixAPI(); + return; + } + + DNG_Mem = Dongle_MemSize(DNG_Count, DNG_Port); + if(DNG_Mem > 0) + { + + //manager->m_Context->OutputToConsoleEx("MemSize of Matrix-Module %d at Port %d: %d Bytes \n", DNG_Count, DNG_Port, DNG_Mem); + + } + else + { + //manager->m_Context->OutputToConsoleEx("Cannot read MemSize! \n"); + Release_MatrixAPI(); + return; + } + + RetCode = Dongle_ReadData(UserCode, DataIn,6, DNG_Count, DNG_Port); + if(RetCode < 0) + { + manager->m_Context->OutputToConsoleEx("Data Read-Error! \n"); + Release_MatrixAPI(); + return; + } + + + + DataBlock[0] = 28071977; + DataBlock[1] = 77917082; + + + + long DataBlockKeyBasic[2]; + DataBlockKeyBasic[0] = DataIn[2]; + DataBlockKeyBasic[1] = DataIn[3]; + + long DataBlockKeyAdvanced[2]; + DataBlockKeyAdvanced[0] = DataIn[4]; + DataBlockKeyAdvanced[1] = DataIn[5]; + + RetCode = Dongle_DecryptData(UserCode, DataBlockKeyBasic, DNG_Count, DNG_Port); + RetCode = Dongle_DecryptData(UserCode, DataBlockKeyAdvanced, DNG_Count, DNG_Port); + + //manager->m_Context->OutputToConsoleEx("Decrypted Data: %lu %lu \n", DataBlockKeyBasic[0], DataBlockKeyBasic[1]); + //manager->m_Context->OutputToConsoleEx("Decrypted Data: %lu %lu \n", DataBlockKeyAdvanced[0], DataBlockKeyAdvanced[1]); + + + if (DataBlockKeyBasic[0]==DONGLE_BASIC_VERSION_KEY_1 && DataBlockKeyBasic[1]==DONGLE_BASIC_VERSION_KEY_2 ) + { +// DongleHasBasicVersion= 1; + } + + if (DataBlockKeyAdvanced[0]==DONGLE_ADVANCED_VERSION_KEY1 && DataBlockKeyAdvanced[1]==DONGLE_ADVANCED_VERSION_KEY2) + { +// DongleHasAdvancedVersion= 1; + } + + //manager->m_Context->OutputToConsoleEx("Clear Data: %lu %lu \n", DataBlock[0], DataBlock[1]); + //manager->m_Context->OutputToConsoleEx("Encrypted Data: %lu %lu \n", DataBlock[0], DataBlock[1]); + + + Release_MatrixAPI(); +} + + + +#endif + +*/ \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerFluids.cpp b/usr/Src/old/Core/Manager/PhysicManagerFluids.cpp new file mode 100644 index 0000000..7b6fa00 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerFluids.cpp @@ -0,0 +1,159 @@ +#include +#include "vtPhysXAll.h" + +#include "VSLManagerSDK.h" + + +#ifdef HAS_FLUID + +void __newpFluidDescr(BYTE *iAdd) +{ + new(iAdd)pFluidDesc(); +} + +void __newpFluidEmitterDesc(BYTE *iAdd) +{ + new(iAdd)pFluidEmitterDesc(); +} + +void PhysicManager::_RegisterFluid_VSL() +{ + + + STARTVSLBIND(m_Context) + + + + /************************************************************************/ + /* pFluidFlags */ + /************************************************************************/ + + DECLAREENUM("pFluidFlag") + DECLAREENUMVALUE("pFluidFlag", "PFF_DisableGravity" , 2) + DECLAREENUMVALUE("pFluidFlag", "PFF_CollisionTwoway" , 4) + DECLAREENUMVALUE("pFluidFlag", "PFF_Enabled" , 8) + DECLAREENUMVALUE("pFluidFlag", "PFF_Hardware" , 16) + DECLAREENUMVALUE("pFluidFlag", "PFF_PriorityMode" , 32) + DECLAREENUMVALUE("pFluidFlag", "PFF_ProjectToPlane" , 64) + + DECLAREENUM("pFluidSimulationMethod") + DECLAREENUMVALUE("pFluidSimulationMethod", "PFS_SPH" , 1) + DECLAREENUMVALUE("pFluidSimulationMethod", "PFS_NoParticleInteraction" , 2) + DECLAREENUMVALUE("pFluidSimulationMethod", "PFS_MixedMode" , 4) + + DECLAREENUM("pFluidCollisionMethod") + DECLAREENUMVALUE("pFluidCollisionMethod", "PFCM_Static" , 1) + DECLAREENUMVALUE("pFluidCollisionMethod", "PFCM_Dynamic" , 2) + + + + DECLAREOBJECTTYPE(pFluidDesc) + DECLARECTOR_0(__newpFluidDescr) + DECLAREMEMBER(pFluidDesc,int,maxParticles) + DECLAREMEMBER(pFluidDesc,float,attractionForDynamicShapes) + DECLAREMEMBER(pFluidDesc,float,attractionForStaticShapes) + DECLAREMEMBER(pFluidDesc,float,collisionDistanceMultiplier) + DECLAREMEMBER(pFluidDesc,int,collisionGroup) + DECLAREMEMBER(pFluidDesc,pFluidCollisionMethod,collisionMethod) + DECLAREMEMBER(pFluidDesc,float,collisionResponseCoefficient) + DECLAREMEMBER(pFluidDesc,float,damping) + DECLAREMEMBER(pFluidDesc,float,dynamicFrictionForDynamicShapes) + DECLAREMEMBER(pFluidDesc,float,dynamicFrictionForStaticShapes) + DECLAREMEMBER(pFluidDesc,VxVector,externalAcceleration) + DECLAREMEMBER(pFluidDesc,float,fadeInTime) + DECLAREMEMBER(pFluidDesc,float,kernelRadiusMultiplier) + DECLAREMEMBER(pFluidDesc,float,packetSizeMultiplier) + DECLAREMEMBER(pFluidDesc,int,maxParticles) + DECLAREMEMBER(pFluidDesc,float,motionLimitMultiplier) + DECLAREMEMBER(pFluidDesc,int,numReserveParticles) + DECLAREMEMBER(pFluidDesc,int,packetSizeMultiplier) + DECLAREMEMBER(pFluidDesc,float,restitutionForDynamicShapes) + DECLAREMEMBER(pFluidDesc,float,restitutionForStaticShapes) + DECLAREMEMBER(pFluidDesc,float,restParticlesPerMeter) + DECLAREMEMBER(pFluidDesc,float,restDensity) + DECLAREMEMBER(pFluidDesc,pFluidSimulationMethod,simulationMethod) + DECLAREMEMBER(pFluidDesc,float,staticFrictionForDynamicShapes) + DECLAREMEMBER(pFluidDesc,float,staticFrictionForStaticShapes) + DECLAREMEMBER(pFluidDesc,float,stiffness) + DECLAREMEMBER(pFluidDesc,float,surfaceTension) + DECLAREMEMBER(pFluidDesc,float,viscosity) + DECLAREMEMBER(pFluidDesc,pFluidFlag,flags) + DECLAREMEMBER(pFluidDesc,CK_ID,worldReference) + + + DECLAREMETHOD_0(pFluidDesc,void,setToDefault) + DECLAREMETHOD_0(pFluidDesc,bool,isValid) + + + /************************************************************************/ + /* emitter */ + /************************************************************************/ + + + ////////////////////////////////////////////////////////////////////////// + // + // emitter flags : + // + DECLAREENUM("pFluidEmitterFlag") + DECLAREENUMVALUE("pFluidEmitterFlag", "PFEF_ForceOnBody" , 4) + DECLAREENUMVALUE("pFluidEmitterFlag", "PFEF_AddBodyVelocity" , 8) + DECLAREENUMVALUE("pFluidEmitterFlag", "PFEF_Enabled" , 16) + + DECLAREENUM("pEmitterShape") + DECLAREENUMVALUE("pEmitterShape", "PFES_Rectangular" , 1) + DECLAREENUMVALUE("pEmitterShape", "PFES_Ellipse" , 2) + + DECLAREENUM("pEmitterType") + DECLAREENUMVALUE("pEmitterType", "PFET_ConstantPressure" , 1) + DECLAREENUMVALUE("pEmitterType", "PFET_ConstantFlowRate" , 2) + + + ////////////////////////////////////////////////////////////////////////// + // + // emitter descr : + // + + DECLAREOBJECTTYPE(pFluidEmitterDesc) + DECLARECTOR_0(__newpFluidEmitterDesc) + DECLAREMEMBER(pFluidEmitterDesc,CK3dEntity*,frameShape) + DECLAREMEMBER(pFluidEmitterDesc,pEmitterType,type) + DECLAREMEMBER(pFluidEmitterDesc,int,maxParticles) + DECLAREMEMBER(pFluidEmitterDesc,pEmitterShape,shape) + DECLAREMEMBER(pFluidEmitterDesc,float,dimensionX) + DECLAREMEMBER(pFluidEmitterDesc,float,dimensionY) + DECLAREMEMBER(pFluidEmitterDesc,VxVector,randomPos) + DECLAREMEMBER(pFluidEmitterDesc,float,randomAngle) + DECLAREMEMBER(pFluidEmitterDesc,float,fluidVelocityMagnitude) + DECLAREMEMBER(pFluidEmitterDesc,float,rate) + DECLAREMEMBER(pFluidEmitterDesc,float,randomAngle) + DECLAREMEMBER(pFluidEmitterDesc,float,particleLifetime) + DECLAREMEMBER(pFluidEmitterDesc,float,repulsionCoefficient) + DECLAREMEMBER(pFluidEmitterDesc,pFluidEmitterFlag,flags) + DECLAREMETHOD_0(pFluidEmitterDesc,void,setToDefault) + DECLAREMETHOD_0(pFluidEmitterDesc,bool,isValid) + DECLAREMEMBER(pFluidEmitterDesc,CK_ID,entityReference) + + + + DECLAREPOINTERTYPE(pFluidEmitter) + + /************************************************************************/ + /* fluid */ + /************************************************************************/ + + DECLAREPOINTERTYPE(pFluid) + DECLAREMETHOD_0(pFluid,CK3dEntity*,getParticleObject) + + DECLAREMETHOD_2(pFactory,pFluid*,createFluid,CK3dEntity*,pFluidDesc) + + DECLAREMETHOD_1(pFluid,pFluidEmitter*,createEmitter,const pFluidEmitterDesc&) + + + + STOPVSLBIND + + + +} + +#endif // HAS_FLUID \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerHookVirtoolsGenericBBs.cpp b/usr/Src/old/Core/Manager/PhysicManagerHookVirtoolsGenericBBs.cpp new file mode 100644 index 0000000..1fc72dc --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerHookVirtoolsGenericBBs.cpp @@ -0,0 +1,192 @@ +#include +#include "vtPhysXAll.h" +#include "IParameter.h" + + +#define BB_OBJECT_COPY CKGUID(0x3f6b0ac7,0x47d20f78) +#define BB_OBJECT_DELETE CKGUID(0x74120ded,0x76524673) + +enum BB_COPY_SETTINGS +{ + + bbS_Dynamic, + bbS_Awak, + bbs_Flags, + bbs_NewBodyFlags, + +}; + +CKBEHAVIORFCT BBCopy; +int BB_CopyNew(const CKBehaviorContext& context) +{ + + + CKBehavior *beh = context.Behavior; + CKContext *ctx = context.Context; + + BBCopy(context); + + // Copy Objects + int count = beh->GetInputParameterCount(); + + // Dynamic ? + BOOL dynamic = TRUE; + beh->GetLocalParameterValue(0,&dynamic); + + int flags = 0; + beh->GetLocalParameterValue(bbs_Flags,&flags); + + int newBodyFlags = 0; + beh->GetLocalParameterValue(bbs_NewBodyFlags,&newBodyFlags); + + CKDependencies* dep = *(CKDependencies**)beh->GetInputParameterReadDataPtr(0); + + + XArraySrcObjects; + + int i; + for(i=1;iGetInputParameterObject(i); + if (!srcObject) continue; + + // we do not want to to duplicate level + if (CKIsChildClassOf(srcObject,CKCID_LEVEL)) continue; + + if (CKIsChildClassOf(srcObject,CKCID_3DENTITY)) + { + + + CK3dEntity *src=(CK3dEntity*)srcObject; + CK3dEntity *dst=(CK3dEntity*)(beh->GetOutputParameterObject(i-1)); + + pObjectDescr oDescr; + IParameter::Instance()->copyTo(oDescr,src,flags); + + + //---------------------------------------------------------------- + // + // IC Data, we just save it out + // + if ( flags & PB_CF_COPY_IC ) + { + CKScene *scene = ctx()->GetCurrentScene(); + if(scene && src->IsInScene(scene)) + { + CKStateChunk *chunk = scene->GetObjectInitialValue(src); + if(chunk) + { + + CKStateChunk *chunkClone=CreateCKStateChunk(CKCID_OBJECT); + chunkClone->Clone(chunk); + + //---------------------------------------------------------------- + // + // copy and restore IC of parent object + // + if(chunkClone) + { + scene->SetObjectInitialValue(dst,chunkClone); + } + + CKERROR error = 0; + if ( flags & PB_CF_RESTORE_IC ) + { + error = CKReadObjectState(dst,chunkClone); + } + + //---------------------------------------------------------------- + // + // copy and restore IC for children : + // + int a = ((*dep->At(CKCID_3DENTITY)) & CK_DEPENDENCIES_COPY_3DENTITY_CHILDREN); + int a1 = (( flags & PB_CF_OVRRIDE_BODY_FLAGS ) && (newBodyFlags & BF_Hierarchy)); + int a2 = ( oDescr.flags & BF_Hierarchy); + + if ( ((*dep->At(CKCID_3DENTITY)) & CK_DEPENDENCIES_COPY_3DENTITY_CHILDREN) && + ( (( flags & PB_CF_OVRRIDE_BODY_FLAGS ) && (newBodyFlags & BF_Hierarchy)) || + ( oDescr.flags & BF_Hierarchy) ) + ) + { + CK3dEntity* subEntity = NULL; + SrcObjects.Clear(); + + while (subEntity= dst->HierarchyParser(subEntity) ) + { + SrcObjects.PushBack(subEntity); + } + int dCount = dst->GetChildrenCount(); + int dCount2 = SrcObjects.Size(); + + for(i = 0;iGetObjectInitialValue(orginalObject); + if (chunkSub) + { + CKStateChunk *chunkCloneSub=CreateCKStateChunk(CKCID_OBJECT); + chunkCloneSub->Clone(chunkSub); + scene->SetObjectInitialValue(subEntity,chunkCloneSub); + if ( flags & PB_CF_RESTORE_IC ) + { + CKReadObjectState(subEntity,chunkCloneSub); + subEntity->SetParent(dst); + } + } + } + + } + } + } + } + } + pRigidBody *srcBody = GetPMan()->getBody((CK3dEntity*)src); + NxShape *shape = NULL; + if (srcBody) + { + shape = srcBody->getSubShape((CK3dEntity*)src); + } + //---------------------------------------------------------------- + // + // copy sub shape ? + // + if (shape && shape!=srcBody->getMainShape()) + { + pFactory::Instance()->cloneShape((CK3dEntity*)src,(CK3dEntity*)(beh->GetOutputParameterObject(i-1)),srcBody->GetVT3DObject(),flags,newBodyFlags); + continue; + } + + //---------------------------------------------------------------- + // + // copy body ? + // + if (srcBody) + pFactory::Instance()->cloneRigidBody(src,dst,dep,flags,newBodyFlags); + } + } + return CK_OK; +} +/************************************************************************/ +/* */ +/************************************************************************/ +CKERROR +PhysicManager::_HookGenericBBs() +{ + CKBehaviorManager *bm = m_Context->GetBehaviorManager(); + + CKBehaviorPrototype *bproto = CKGetPrototypeFromGuid(BB_OBJECT_COPY); + if(bproto) + { + bproto->DeclareSetting("Copy Flags",VTF_PHYSIC_ACTOR_COPY_FLAGS,""); + bproto->DeclareSetting("New Body Flags",VTF_BODY_FLAGS,""); + + BBCopy = bproto->GetFunction(); + bproto->SetFunction(BB_CopyNew); + } + + return CK_OK; +} diff --git a/usr/Src/old/Core/Manager/PhysicManagerInit.cpp b/usr/Src/old/Core/Manager/PhysicManagerInit.cpp new file mode 100644 index 0000000..67858b6 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerInit.cpp @@ -0,0 +1,338 @@ +#include +#include "vtPhysXAll.h" +#include "pWorldSettings.h" +#include "pLogger.h" +#include "pConfig.h" + +/* +class myLogConsumer : public xLogConsumer +{ + +public: + myLogConsumer() : xLogConsumer() + { + + } + + void logString(const char *string); +}; + +void myLogConsumer::logString(const char *string) +{ + xLogConsumer::logString(string); + + int test = 2; + test++; + + +} + +myLogConsumer pLogConsumer; +*/ + +#include + +int PhysicManager::initManager(int flags/* =0 */) +{ + xBitSet inFlags = flags; + xBitSet resultFlags = 0; + + + xAssertionEx::Instance(); + customizeAsserts(); + + ////////////////////////////////////////Load our physic default xml document : + if (isFlagOn(inFlags,E_MFI_LOAD_CONFIG) && getDefaultConfig()) + { + delete m_DefaultDocument; + m_DefaultDocument = NULL; + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted old default config"); + } + + if (isFlagOn(inFlags,E_MFI_LOAD_CONFIG)) + { + TiXmlDocument * defaultDoc = loadDefaults("PhysicDefaults.xml"); + if (!defaultDoc) + { + //enableFlag(resultFlags,E_MF_LOADING_DEFAULT_CONFIG_FAILED); + enableFlag(_getManagerFlags(),E_MF_LOADING_DEFAULT_CONFIG_FAILED); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config :PhysicDefaults.xml: failed"); + setDefaultConfig(NULL); + }else + { + setDefaultConfig(defaultDoc); + } + + } + + ////////////////////////////////////////////////////////////////////////////factory : + if (isFlagOn(inFlags,E_MFI_CREATE_FACTORY)) + { + if (getCurrentFactory()) + { + + getCurrentFactory()->setPhysicSDK(getPhysicsSDK()); + enableFlag(_getManagerFlags(),E_MF_FACTORY_CREATED); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Old factory updated"); + } + if (!getCurrentFactory()) + { + + pFactory *factory = new pFactory(this,getDefaultConfig()); + factory->setPhysicSDK(getPhysicsSDK()); + enableFlag(_getManagerFlags(),E_MF_FACTORY_CREATED); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"New factory created"); + setCurrentFactory(factory); + } + } + + if (getDefaultWorldSettings()) + { + SAFE_DELETE(mDefaultWorldSettings); + } + + ////////////////////////////////////////////////////////////////////////// + //world settings : + pWorldSettings *wSettings = pFactory::Instance()->createWorldSettings(XString("Default"),getDefaultConfig()); + if (!wSettings) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Couldn't load default world settings!"); + wSettings = new pWorldSettings(); + } + + setDefaultWorldSettings(wSettings); + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Default world settings created"); + + + //////////////////////////////////////////default world : + if (isFlagOn(_getManagerFlags(),E_MF_FACTORY_CREATED) && + getDefaultWorldSettings() ) + { + if (pFactory::Instance()->createDefaultWorld("pDefaultWorld")) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Default world created"); + } + //else xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Creating default world failed"); + } + _RegisterDynamicParameters(); + + int mask = resultFlags.getMask(); + return mask; + + +} + +int PhysicManager::initPhysicEngine(int flags /* = 0 */) +{ + + if (getPhysicsSDK()) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Physic SDK already initiated! Releasing old SDK "); + NxReleasePhysicsSDK(getPhysicsSDK()); + setPhysicsSDK(NULL); + } + + NxPhysicsSDKDesc desc; + NxSDKCreateError errorCode = NXCE_NO_ERROR; + + pErrorStream* eStream = getLogger()->getErrorStream(); + mPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL,(NxUserOutputStream*)eStream, desc, &errorCode); + if(mPhysicsSDK == NULL) + { + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_AGEIA,"Physic SDK already initiated! Releasing old SDK "); + enableFlag(_getManagerFlags(),E_MF_PSDK_FAILED); + return E_PE_AGEIA_ERROR; + } + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Physic SDK initiated!"); + + if (getDefaultConfig()) + { + pRemoteDebuggerSettings rSettings = pFactory::Instance()->createDebuggerSettings(getDefaultConfig()); + + if (rSettings.enabled) + { + mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(rSettings.mHost.CStr(),rSettings.port); + + if (!mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"couldn't connect to remote debugger !"); + }else + { + + mRemoteDebugger = mPhysicsSDK->getFoundationSDK().getRemoteDebugger(); + + } + } + } + + + /*mPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1); + mPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); + mPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1); + mPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1); +*/ + + setPSDKParameters(getSDKParameters()); + + pRemoteDebuggerSettings &dbgSetup = getRemoteDebuggerSettings(); + if (dbgSetup.enabled) + { + + mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(dbgSetup.mHost.CStr(),dbgSetup.port); + if (!mPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"couldn't connect to remote debugger !"); + }else + { + + mRemoteDebugger = mPhysicsSDK->getFoundationSDK().getRemoteDebugger(); + } + } + + enableFlag(_getManagerFlags(),E_MF_PSDK_LOADED); + return E_PE_OK; +} +int PhysicManager::performInitialization() +{ + + XString buffer; + +#ifdef DEMO_ONLY + + SYSTEMTIME sys; + + GetSystemTime(&sys); + + int dayd = sys.wDay; + int monthd = sys.wMonth; + int yeard = sys.wYear; + + if (!GetContext()->IsInInterfaceMode()){ + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"sorry guy, just a demo !"); + MessageBox(NULL,"just a demo !!!","tzzzz...",0); + return E_PE_INVALID_OPERATION; + } + if ( yeard == 2009 ) + { + if (monthd <=END_MONTH && monthd >=START_MONTH ) + { + goto init; + }else goto expired; + }else goto expired; + + +expired : + + + buffer << "today is the " << dayd << " of " << monthd << "\n"; + buffer << "but this release only works until : " << END_MONTH; + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,buffer.CStr()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Demo expired!"); + return E_PE_INVALID_OPERATION; + +#endif + + +init: + + + + + xBitSet initFlags = 0 ; + enableFlag(initFlags,E_MFI_LOAD_CONFIG); + enableFlag(initFlags,E_MFI_CREATE_FACTORY); + int error = initManager( initFlags.getMask()); + if (error == E_PE_INVALID_OPERATION ) + { + return 0; + } + + + if (isFlagOff(_getManagerFlags(),E_MF_PSDK_LOADED)) + { + if (initPhysicEngine()!= E_PE_OK ) + { + return E_MF_PSDK_FAILED; + } + + enableFlag(initFlags,E_MFI_USE_XML_WORLD_SETTINGS); + enableFlag(initFlags,E_MFI_CREATE_DEFAULT_WORLD); + + + int error = initManager( initFlags.getMask()); + if (error != E_PE_OK ) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't init manager"); + return E_PE_INVALID_OPERATION; + } + } + return E_PE_OK; +} + +bool PhysicManager::isValid() +{ + return isFlagOn(_getManagerFlags(),E_MF_PSDK_LOADED) && + isFlagOn(_getManagerFlags(),E_MF_FACTORY_CREATED) && + getDefaultWorldSettings() && getDefaultWorld(); +} + +void PhysicManager::_construct(xBitSet flags /* = 0 */) +{ + mManagerFlags = 0 ; + mPhysicsSDK = NULL; + mLogger = NULL; + mDefaultWorldSettings = NULL; + m_DefaultDocument = NULL; + m_currentFactory = NULL; + m_DefaultDocument = NULL; + m_currentFactory = NULL; + m_DefaultWorld = NULL; + mRemoteDebugger = NULL; + mIParameter = NULL; + + + + + xLogger::GetInstance()->setVirtoolsContext(m_Context); + + xLogger::GetInstance()->addLogItem(E_LI_AGEIA); + xLogger::GetInstance()->addLogItem(E_LI_MANAGER); + xLogger::GetInstance()->addLogItem(E_VSL); + xLogger::GetInstance()->addLogItem(E_BB); + + xLogger::GetInstance()->addItemDescription("AGEIA"); + xLogger::GetInstance()->addItemDescription("MANAGER"); + xLogger::GetInstance()->addItemDescription("VSL"); + xLogger::GetInstance()->addItemDescription("BB"); + + + + + xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGERROR,1); + xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGTRACE,0); + xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGWARNING,0); + xLogger::GetInstance()->enableLoggingLevel(E_BB,ELOGINFO,0); + + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGERROR,1); + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGTRACE,0); + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGWARNING,0); + xLogger::GetInstance()->enableLoggingLevel(E_LI_AGEIA,ELOGINFO,0); + + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGERROR,1); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGTRACE,0); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGWARNING,0); + xLogger::GetInstance()->enableLoggingLevel(E_LI_MANAGER,ELOGINFO,0); +/* + #ifdef CONSOLE_OUTPUT + xLogger::GetInstance()->Init(); + #endif +*/ + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Initiated"); + + if (!getLogger()) + { + setLogger(new pLogger()); + } +} diff --git a/usr/Src/old/Core/Manager/PhysicManagerJointAttributeFunctions.cpp b/usr/Src/old/Core/Manager/PhysicManagerJointAttributeFunctions.cpp new file mode 100644 index 0000000..1731b87 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerJointAttributeFunctions.cpp @@ -0,0 +1,934 @@ +#include +#include "vtPhysXAll.h" +#include "vtAttributeHelper.h" + + +using namespace xUtils; +using namespace vtAgeia; +using namespace vtTools::ParameterTools; +using namespace vtTools::AttributeTools; + + +int registerJD6(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + return 0; +} +int registerJD6Drive(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + return 0; +} +int registerJLimitPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + + + //---------------------------------------------------------------- + // + // get and check objects + // + if (!target) + return -1; + + CKParameterOut *attParameter = target->GetAttributeParameter(attributeType); + if (!attParameter) + return -1; + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + + pRigidBody *body = GetPMan()->getBody(target); + if (!body) + return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(attParameter,PS_JLP_BODY_B_REF); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + + if (set) + { + //---------------------------------------------------------------- + // + // post pone i ck-start-up or loading + // + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJLimitPlane,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + } + + int jointType = GetValueFromParameterStruct(attParameter,PS_JLP_JOINT_TYPE); + + //try to get the joint + pJoint *joint = GetPMan()->getJoint(target,bodyBEnt,(JType)jointType); + if (!joint) + return -1; + + //---------------------------------------------------------------- + // + // we are on ck-play or SetAttribute-BB : Retrieve all parameters from the attribute : + // + + VxVector limitPoint = GetValueFromParameterStruct(attParameter,PS_JLP_LIMIT_POINT); + + CK_ID limitPointRefID = GetValueFromParameterStruct(attParameter,PS_JLP_LIMIT_POINT_REF); + CK3dEntity *limiPointRef = static_cast(GetPMan()->m_Context->GetObject(limitPointRefID)); + if (limiPointRef) + limiPointRef->Transform(&limitPoint,&limitPoint); + + + int isOnBodyB = GetValueFromParameterStruct(attParameter,PS_JLP_IS_ON_BODY_B); + float length = limitPoint.SquareMagnitude(); + if (XAbs(limitPoint.SquareMagnitude()) >=0.01f) + joint->setLimitPoint(limitPoint,isOnBodyB); + + + // - Limit Point Normal + VxVector limitPointNormal = GetValueFromParameterStruct(attParameter,PS_JLP_NORMAL); + + CK_ID limitPointNormalRefID = GetValueFromParameterStruct(attParameter,PS_JLP_NORMAL_REF); + CK3dEntity *limitPointNormalRef = static_cast(GetPMan()->m_Context->GetObject(limitPointNormalRefID)); + + if (limitPointNormalRef) + { + VxVector dir,up,right; + limitPointNormalRef->GetOrientation(&dir,&up,&right); + limitPointNormalRef->TransformVector(&limitPointNormal,&up); + } + + // - Point in Plane + VxVector PointInPlane = GetValueFromParameterStruct(attParameter,PS_JLP_PT_IN_PLANE); + + CK_ID PointInPlaneRefID = GetValueFromParameterStruct(attParameter,PS_JLP_PT_IN_PLANE_REF); + CK3dEntity *PointInPlaneRef = static_cast(GetPMan()->m_Context->GetObject(PointInPlaneRefID)); + if (PointInPlaneRef) + PointInPlaneRef->Transform(&PointInPlane,&PointInPlane); + + // - Restitution + float res = GetValueFromParameterStruct(attParameter,PS_JLP_RESTITUTION); + + // - Execute + + int result = joint->addLimitPlane(limitPointNormal,PointInPlane,res); + return result; + } + +} + + +int registerJPointOnLine(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + CKParameterOut *pointInPlaneParameter = target->GetAttributeParameter(attributeType); + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (pointInPlaneParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJPointOnLine,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_ANCHOR_REF); + + + + ////////////////////////////////////////////////////////////////////////// + //anchor : + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + int collision = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_COLLISION); + + + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + + pJointPointOnLine*joint = static_cast(pFactory::Instance()->createPointOnLineJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + joint->enableCollision(collision); + + float maxForce = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPOL_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + return 1; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_PointOnLine); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + + return 1; + } + } + + return 0; + +} + +int registerJPointInPlane(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + CKParameterOut *pointInPlaneParameter = target->GetAttributeParameter(attributeType); + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (pointInPlaneParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJPointInPlane,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_ANCHOR_REF); + + + + ////////////////////////////////////////////////////////////////////////// + //anchor : + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + int collision = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_COLLISION); + + + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + //pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) + pJointPointInPlane*joint = static_cast(pFactory::Instance()->createPointInPlaneJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + joint->enableCollision(collision); + + float maxForce = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(pointInPlaneParameter,PS_JPIP_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + return 1; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_PointInPlane); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + + return 1; + } + } + + return 0; + +} + + +int registerJRevolute(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + + int s = GetPMan()->getAttributePostObjects().Size(); + using namespace vtTools::ParameterTools; + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJRevolute,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_ANCHOR_REF); + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + + int collision = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_COLLISION); + + int projectionMode = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_PROJ_MODE); + float projectionDistance= GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_PROJ_DISTANCE); + float projectionAngle = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_PROJ_ANGLE); + + + + pJointLimit limitHigh = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_LIMIT_HIGH)); + pJointLimit limitLow= pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_LIMIT_LOW)); + pSpring spring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_SPRING)); + pMotor motor = pFactory::Instance()->createMotorFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JREVOLUTE_MOTOR)); + + pJointRevolute*joint = static_cast(pFactory::Instance()->createRevoluteJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + + joint->enableCollision(collision); + joint->setLowLimit(limitLow); + joint->setHighLimit(limitHigh); + joint->setSpring(spring); + + if (projectionMode!=0) + { + joint->setProjectionMode((ProjectionMode)projectionMode); + joint->setProjectionDistance(projectionDistance); + joint->setProjectionAngle(projectionAngle); + } + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JREVOLUTE_MAX_TORQUE); + if (maxTorque !=0.0f || maxForce!=0.0f) + { + joint->setBreakForces(maxForce,maxTorque); + } + + return true; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Revolute); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + return 0; + +} + + +int registerJCylindrical(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + + + using namespace vtTools::ParameterTools; + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJCylindrical,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_ANCHOR_REF); + + + + ////////////////////////////////////////////////////////////////////////// + //anchor : + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + int collision = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_COLLISION); + + + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + //pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) + pJointCylindrical*joint = static_cast(pFactory::Instance()->createCylindricalJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + joint->enableCollision(collision); + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_MAX_TORQUE); + //joint->setBreakForces(maxForce,maxTorque); + return true; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Cylindrical); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + + return 0; + +} + + +int registerJPrismatic(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJPrismatic,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_ANCHOR_REF); + + + + ////////////////////////////////////////////////////////////////////////// + //anchor : + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + int collision = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_COLLISION); + + + ////////////////////////////////////////////////////////////////////////// + //axis + VxVector axis = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_AXIS); + CK_ID axisRefID = GetValueFromParameterStruct(distanceParameter,PS_JPRISMATIC_AXIS_REF); + CK3dEntity *axisRef = static_cast(GetPMan()->m_Context->GetObject(axisRefID)); + if (axisRef) + { + VxVector dir,up,right; + axisRef->GetOrientation(&dir,&up,&right); + axisRef->TransformVector(&axis,&up); + } + //pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) + pJointCylindrical*joint = static_cast(pFactory::Instance()->createCylindricalJoint(target,bodyBEnt,anchor0,axis)); + if (joint) + { + joint->enableCollision(collision); + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JCYLINDRICAL_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + + return true; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Prismatic); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + return 0; +} + +int registerJBall(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JBALL_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJBall,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JBALL_ANCHOR); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JBALL_ANCHOR_REF); + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->Transform(&anchor0,&anchor0); + + VxVector swingAxis = GetValueFromParameterStruct(distanceParameter,PS_JBALL_LIMIT_SWING_AXIS); + + int collision = GetValueFromParameterStruct(distanceParameter,PS_JBALL_COLLISION); + + int projectionMode = GetValueFromParameterStruct(distanceParameter,PS_JBALL_PROJ_MODE); + float minDist = GetValueFromParameterStruct(distanceParameter,PS_JBALL_PROJ_DISTANCE); + + pJointLimit swingLimit = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_SWING_LIMIT)); + pJointLimit twistHighLimit = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_TWIST_HIGH)); + pJointLimit twistHighLow = pFactory::Instance()->createLimitFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_TWIST_LOW)); + + pSpring swingSpring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_SWING_SPRING)); + pSpring twistSpring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_TWIST_SPRING)); + pSpring jointSpring = pFactory::Instance()->createSpringFromParameter(vtTools::ParameterTools::GetParameterFromStruct(distanceParameter,PS_JBALL_JOINT_SPRING)); + + pJointBall *joint = static_cast(pFactory::Instance()->createBallJoint(target,bodyBEnt,anchor0,swingAxis)); + if (joint) + { + joint->setProjectionMode((ProjectionMode)projectionMode); + joint->setProjectionDistance(minDist); + joint->enableCollision(collision); + + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JBALL_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JBALL_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + + + + if (swingLimit.value !=-1.0f) + { + joint->setSwingLimit(swingLimit); + joint->enableFlag(NX_SJF_SWING_LIMIT_ENABLED,true); + } + + joint->setSwingLimit(swingLimit); + + + if (twistHighLimit.value != 0.0f || twistHighLow.value !=0.0f ) + { + + joint->setTwistHighLimit(twistHighLimit); + joint->setTwistLowLimit(twistHighLow); + joint->enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,true); + } + + if (swingSpring.spring !=0.0f) + { + joint->setSwingSpring(swingSpring); + joint->enableFlag(NX_SJF_SWING_SPRING_ENABLED,true); + } + + + if (twistSpring.spring =0.0f) + { + joint->setTwistSpring(twistSpring); + joint->enableFlag(NX_SJF_TWIST_SPRING_ENABLED,true); + } + + if (jointSpring.spring !=0.0f) + { + joint->setJointSpring(jointSpring); + joint->enableFlag(NX_SJF_JOINT_SPRING_ENABLED,true); + } + + return true; + } + + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Spherical); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + return 0; +} + +int registerJFixed(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JFIXED_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + if (set) + { + + if ( isPostJob && GetPMan()->GetContext()->IsPlaying() ) + { + pAttributePostObject postAttObject(target->GetID(),registerJFixed,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + + pJointFixed *joint = static_cast(pFactory::Instance()->createFixedJoint(target,bodyBEnt)); + if (joint) + { + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JFIXED_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JFIXED_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + + return true; + } + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Fixed); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + + return 0; + + +} + + + +int registerJDistance(CK3dEntity *target,int attributeType,bool set,bool isPostJob) +{ + using namespace vtTools::ParameterTools; + + + CKStructHelper sHelper(target->GetAttributeParameter(attributeType)); + if (sHelper.GetMemberCount() ==0 )//happens when dev is being opened and loads a cmo with physic objects. + return -1; + + CKParameterOut *distanceParameter = target->GetAttributeParameter(attributeType); + if (distanceParameter ) + { + + pRigidBody *body = GetPMan()->getBody(target); + if (!body)return -1; + + CK_ID bodyBId = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_BODY_B); + CK3dEntity *bodyBEnt = static_cast(GetPMan()->GetContext()->GetObject(bodyBId)); + pRigidBody *bodyB = GetPMan()->getBody(bodyBEnt); + if (bodyB && bodyB->getWorld() != body->getWorld() ) + return -1; + + if (set) + { + + if (isPostJob && GetPMan()->GetContext()->IsPlaying()) + { + pAttributePostObject postAttObject(target->GetID(),registerJDistance,attributeType); + GetPMan()->getAttributePostObjects().PushBack(postAttObject); + + int s = GetPMan()->getAttributePostObjects().Size(); + + return true; + + } + + if (bodyB && body->isConnected(bodyBEnt) ) + return -1; + + VxVector anchor0 = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_A_POS); + CK_ID anchor0RefID = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_A_REF); + CK3dEntity *a0Ref = static_cast(GetPMan()->m_Context->GetObject(anchor0RefID)); + if (a0Ref) a0Ref->TransformVector(&anchor0,&anchor0,a0Ref); + + VxVector anchor1 = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_B_POS); + CK_ID anchor1RefID = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_LOCAL_ANCHOR_B_REF); + CK3dEntity *a1Ref = static_cast(GetPMan()->m_Context->GetObject(anchor1RefID)); + if (a1Ref) a1Ref->TransformVector(&anchor1,&anchor1,a1Ref); + + float maxDist = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_MAX_DISTANCE); + float minDist = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_MIN_DISTANCE); + + pSpring spring = pFactory::Instance()->createSpringFromParameter( GetParameterFromStruct(distanceParameter,PS_JDISTANCE_SPRING) ); + + int collision = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_COLL); + + + pJointDistance *joint = static_cast(pFactory::Instance()->createDistanceJoint(target,bodyBEnt,anchor0,anchor1,minDist,maxDist,spring)); + if (joint) + { + + float maxForce = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_MAX_FORCE); + float maxTorque = GetValueFromParameterStruct(distanceParameter,PS_JDISTANCE_MAX_TORQUE); + joint->setBreakForces(maxForce,maxTorque); + joint->enableCollision(collision); + + + #ifdef _DEBUG + + XString _errorStr; + + XString attName = GetPMan()->GetContext()->GetAttributeManager()->GetAttributeNameByType(attributeType); + + _errorStr << "Distance joint created on " << target->GetName() << " for attribute type : " << attName.Str(); + + xLogger::xLog(XL_START,ELOGINFO,E_LI_MANAGER,_errorStr.Str()); + + #endif + + return true; + } + return 0; + }else + { + + + pJoint *joint = body->isConnected(bodyBEnt); + if ( joint) + { + body->getWorld()->deleteJoint(joint); + } + pJoint *joint2 = body->getWorld()->getJoint(target,bodyBEnt,(JType)JT_Distance); + if (joint2) + { + body->getWorld()->deleteJoint(joint); + } + } + } + return 0; + +} + + +void PObjectAttributeCallbackFunc(int AttribType,CKBOOL Set,CKBeObject *obj,void *arg) +{ + + CK3dEntity *ent = static_cast(obj); + if (!ent)return; + + ObjectRegisterFunction myFn = static_cast(arg); + if (ent , myFn) + { + bool isPlaying = GetPMan()->GetContext()->IsPlaying(); + int success = (*myFn)(ent,AttribType,Set,true); + + if (!success) + { + CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); + XString error; + error << "Registration Function failed for attribute" << attman->GetAttributeNameByType(AttribType) << " for Object : " << ent->GetName() ; + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,error.Str()); + }else{ + + CKAttributeManager* attman = GetPMan()->GetContext()->GetAttributeManager(); + XString error; + error << "Registration Function succeeded for attribute" << attman->GetAttributeNameByType(AttribType) << " for Object : " << ent->GetName() ; + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,error.Str()); + } + } +} diff --git a/usr/Src/old/Core/Manager/PhysicManagerJointVSL.cpp b/usr/Src/old/Core/Manager/PhysicManagerJointVSL.cpp new file mode 100644 index 0000000..3216bae --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerJointVSL.cpp @@ -0,0 +1,61 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + +//#include "pVehicle.h" + + + + + + + + +void PhysicManager::_RegisterVSLJoint() +{ + + + + STARTVSLBIND(m_Context) + + + + STOPVSLBIND + + +} + + + +/* +void __newvtWorldSettings(BYTE *iAdd) +{ +new (iAdd) pWorldSettings(); +} +void __newvtSleepingSettings(BYTE *iAdd) +{ +new (iAdd) pSleepingSettings(); +} +void __newvtJointSettings(BYTE *iAdd) +{ +new (iAdd) pJointSettings(); +} + + +int TestWS(pWorldSettings pWS) +{ +VxVector grav = pWS.Gravity(); +return 2; +} + +pFactory* GetPFactory(); + + +pFactory* GetPFactory() +{ +return pFactory::Instance(); +} + + +extern pRigidBody*getBody(CK3dEntity*ent); +*/ \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerJoints.cpp b/usr/Src/old/Core/Manager/PhysicManagerJoints.cpp new file mode 100644 index 0000000..2011fd9 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerJoints.cpp @@ -0,0 +1,170 @@ +#include +#include "vtPhysXAll.h" + +#include "vtAttributeHelper.h" + +pJoint*PhysicManager::getJoint(CK3dEntity*referenceA,CK3dEntity*referenceB/* =NULL */,JType type/* =JT_Any */) +{ + + pJoint *result = NULL; + + pRigidBody *a = GetPMan()->getBody(referenceA); + pRigidBody *b = GetPMan()->getBody(referenceB); + + pWorld *wA = a ? a->getWorld() : NULL; + pWorld *wB = b ? b->getWorld() : NULL; + pWorld *worldFinal = NULL; + + + bool oneBodyJoint = false;// body with world frame ? + CK3dEntity* oneBodyJointReference =NULL; + + + //---------------------------------------------------------------- + // + // Sanity Checks + // + XString errorString; + + // Reference A physicalized at all ? + if ( !referenceA && !referenceB ) + { + errorString.Format("No reference specified"); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // Reference A IS NOT Reference B ? + if ( (referenceA!=NULL && referenceB!=NULL) && (a==b) ) + { + errorString.Format("Reference A (%s) is the same as Reference B (%s)",referenceA->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // Reference A physicalized at all ? + if (referenceA && !a){ + + errorString.Format("Reference A (%s) valid but not physicalized",referenceA->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // Reference B physicalized at all ? + if (referenceB && !b){ + + errorString.Format("Reference B (%s) valid but not physicalized",referenceB->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + + // world of object a valid ? + if (a && !wA){ + errorString.Format("Reference A (%s) is physicalized but has no valid world object",referenceA->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // world of object b valid ? + if (b && !wB){ + errorString.Format("Reference B (%s) is physicalized but has no valid world object",referenceB->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + // rigid bodies are in the same world + if ( (wA!=NULL && wB!=NULL) && (wA!=wB) ) + { + errorString.Format("Reference A (%s) and B(%s) is physicalized but are not in the same world",referenceA->GetName(),referenceB->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorString.Str()); + return result; + } + + //---------------------------------------------------------------- + // + // Preparing lookup + // + if ( wA ) + worldFinal = wA; + if ( wB ) + worldFinal = wB; + + + // constraint is attached to world frame ? + if ( (a && !b) || (b && !a) ) + oneBodyJoint = true; + + // world frame constraint, track the reference + if (oneBodyJoint) + { + if ( a ) + oneBodyJointReference = referenceA; + if ( b ) + oneBodyJointReference = referenceB; + } + + + //---------------------------------------------------------------- + // + // Parse the scene joints + // + NxU32 jointCount = worldFinal->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + worldFinal->getScene()->resetJointIterator(); + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = worldFinal->getScene()->getNextJoint(); + + pJoint *_cJoint = static_cast( j->userData ); + if (!_cJoint) + continue; + + //---------------------------------------------------------------- + // + // Special case : has a joint at all, only for world frame constraints + // + if (type == JT_Any) + { + if ( oneBodyJoint && + _cJoint->GetVTEntA() == oneBodyJointReference || + _cJoint->GetVTEntB() == oneBodyJointReference + ) + return _cJoint; + } + + //---------------------------------------------------------------- + // + // Specific joint type + // + if ( j->getType() == type) + { + + //---------------------------------------------------------------- + // + // world constraint joint + // + if (oneBodyJoint && + _cJoint->GetVTEntA() == oneBodyJointReference || + _cJoint->GetVTEntB() == oneBodyJointReference + ) + return _cJoint; + + //---------------------------------------------------------------- + // + // Two references given + // + if ( _cJoint->GetVTEntA() == referenceA && _cJoint->GetVTEntB() == referenceB ) + return _cJoint; + + if ( _cJoint->GetVTEntA() == referenceB && _cJoint->GetVTEntB() == referenceA ) + return _cJoint; + + } + } + } + return NULL; +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerLoader.cpp b/usr/Src/old/Core/Manager/PhysicManagerLoader.cpp new file mode 100644 index 0000000..f156afc --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerLoader.cpp @@ -0,0 +1,68 @@ +#include +#include "vtPhysXAll.h" + +#include "tinyxml.h" + + + +static const TiXmlElement *getFirstOdeElement(const TiXmlElement *root); +static const TiXmlElement *getFirstOdeElement(const TiXmlElement *root) +{ + // should have some recursive algo + if (!strcmp(root->Value(), "vtPhysics")) + { + return root; + } + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling()) + { + if (child->Type() == TiXmlNode::ELEMENT) + { + const TiXmlElement *res = getFirstOdeElement(child->ToElement ()); + if (res) + return res; + } + } + + return 0; +} +TiXmlDocument* +PhysicManager::loadDefaults(XString filename) +{ + + + // load and check file + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,filename.CStr()); + XString name(Ini); + name << '\0'; + + m_DefaultDocument = new TiXmlDocument(filename.Str()); + m_DefaultDocument ->LoadFile(Ini); + m_DefaultDocument ->Parse(Ini); + + if (m_DefaultDocument->Error()) + { + //xLogger::xLog("couldn't load default document"); + + delete m_DefaultDocument; + m_DefaultDocument = NULL; + + return NULL; + } + + // get the ogreode element. + TiXmlNode* node = m_DefaultDocument->FirstChild( "vtPhysics" ); + if (!node) + { + //Ogre::LogManager::getSingleton().logMessage(" cannot find ogreode root in XML file!"); + return NULL; + } + return m_DefaultDocument; + +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerRun.cpp b/usr/Src/old/Core/Manager/PhysicManagerRun.cpp new file mode 100644 index 0000000..aa05b5e --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerRun.cpp @@ -0,0 +1,88 @@ +#include +#include "vtPhysXAll.h" +#include "pConfig.h" + +int demoTimerExpired=0; + + +void PhysicManager::advanceTime(float time) +{ + + timer +=time; + float timeNow = timer; + + mLastStepTime = time; + +} + +void PhysicManager::update(float stepsize) +{ + + advanceTime(stepsize); + +#ifdef SESSION_LIMIT + #ifndef REDIST + + if (timer >(SESSION_MAX)) + { + if (demoTimerExpired==0) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Demo expires after 15 mins"); + demoTimerExpired = 1; + } + return ; + } + #endif +#endif + + +#ifdef REDIST + + if (m_Context->IsInInterfaceMode()) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"This is a redist Dll"); + return; + } + #pragma message("-------------------------------PManager ::Update REDIST" ) +#endif + +#if PROFILER + //CKTimeProfiler(const char* iTitle, CKContext* iContext, int iStartingCount = 4): + //CKTimeProfiler MyProfiler("PhysX Step",GetContext(),8); +#endif + pWorldMapIt it = getWorlds()->Begin(); + while(it != getWorlds()->End()) + { + pWorld *w = *it; + w->step(stepsize); + it++; + } + + //float pTime = MyProfiler + //float a = pTime; +} + +CKERROR PhysicManager::PostProcess() +{ + + + pWorldMapIt it = getWorlds()->Begin(); + while(it != getWorlds()->End()) + { + pWorld *w = *it; + //w->getCollisions().Clear(); + it++; + } + + cleanAttributePostObjects(); + + return CK_OK; +} + +CKERROR PhysicManager::PreProcess() +{ + + float timeCtx = GetContext()->GetTimeManager()->GetLastDeltaTimeFree(); + update(timeCtx); + return CK_OK; +} diff --git a/usr/Src/old/Core/Manager/PhysicManagerVTRegisterCommon.cpp b/usr/Src/old/Core/Manager/PhysicManagerVTRegisterCommon.cpp new file mode 100644 index 0000000..ad59a06 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerVTRegisterCommon.cpp @@ -0,0 +1,557 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + + + + +PhysicManager*GetPhysicManager(); +pRigidBody *getBody(CK3dEntity*ent); +CKGUID GetPhysicManagerGUID() { return GUID_MODULE_MANAGER;} + +typedef ForceMode PForceMode; +typedef D6MotionMode PJMotion; +typedef D6DriveType PDriveType; + + +pFactory* getPFactory() +{ + return pFactory::Instance(); +} + + +void __newpObjectDescr(BYTE *iAdd) +{ + new (iAdd) pObjectDescr(); +} + + +void __newpRaycastHit(BYTE *iAdd) +{ + new(iAdd)pRaycastHit(); +} + +void __newpGroupsMask(BYTE *iAdd) +{ + new(iAdd)pGroupsMask(); +} + +void __newpOptimization(BYTE *iAdd) +{ + new(iAdd)pOptimization(); +} +void __newpMassSettings(BYTE *iAdd) +{ + new(iAdd)pMassSettings(); +} +void __newpCCD(BYTE *iAdd) +{ + new(iAdd)pCCDSettings(); +} +void __newpCollisionSettings(BYTE *iAdd) +{ + new(iAdd)pCollisionSettings(); +} + +void __newpPivotSettings(BYTE *iAdd) +{ + new(iAdd)pPivotSettings(); +} + +void __newpMaterial(BYTE *iAdd) +{ + new(iAdd)pMaterial(); +} +void __newpAxisReferenceLength(BYTE *iAdd) +{ + new(iAdd)pAxisReferencedLength(); +} + + +void __newpCapsuleSettingsEx(BYTE *iAdd) +{ + new(iAdd)pCapsuleSettingsEx(); +} +void __newpConvexCylinder(BYTE *iAdd) +{ + new(iAdd)pConvexCylinderSettings(); +} + +void __newpWheelDescr(BYTE *iAdd) +{ + new (iAdd)pWheelDescr(); +} + +void __newpTireFunction(BYTE *iAdd) +{ + new (iAdd)pTireFunction(); +} + +CKGUID getRigidBodyParameterType() +{ + return VTS_PHYSIC_ACTOR; +} + +////////////////////////////////////////////////////////////////////////// + +#define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) + +void logWarning(const char*errMessage) +{ + if (!errMessage || !strlen(errMessage)) + return; + + xLogger::xLog(XL_START,ELOGWARNING,E_VSL,errMessage); + + +} + +void PhysicManager::_RegisterVSLCommon() +{ + + STARTVSLBIND(m_Context) + + //---------------------------------------------------------------- + // + // manager related + // + + { + + DECLAREENUM("pSDKParameter") + DECLAREENUMVALUE("pSDKParameter", "pSDKP_SkinWidth" ,1 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_DefaultSleepLinVelSquared" ,2 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_DefaultSleepAngVelSquared" ,3 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_BounceThreshold" ,4 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_DynFrictScaling" , 5) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_StaFrictionScaling" ,6 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_MaxAngularVelocity" ,7 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ContinuousCD" ,8 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_AdaptiveForce" ,68 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_CollVetoJointed" ,69 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_TriggerTriggerCallback" ,70 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_SelectHW_Algo" ,71 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_CCDEpsilon" ,73 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_SolverConvergenceThreshold" ,74 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_BBoxNoiseLevel" ,75 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ImplicitSweepCacheSize" , 76) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_DefaultSleepEnergy" ,77 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ConstantFluidMaxPackets" ,78 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ConstantFluidMaxParticlesPerStep" ,79 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_AsynchronousMeshCreation" ,96 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ForceFieldCustomKernelEpsilon" ,97 ) + DECLAREENUMVALUE("pSDKParameter", "pSDKP_ImprovedSpringSolver" ,98 ) + + } + + + REGISTERCONST("FLT_MAX",BIND_FLOAT,FLT_MAX) + REGISTERCONST("PTYPE_RIGID_BODY",BIND_FLOAT,FLT_MAX) + + //---------------------------------------------------------------- + // + // common types + // + DECLAREPOINTERTYPE(pFactory) + DECLAREFUN_C_0(pFactory,getPFactory) + + + + DECLAREFUN_C_0(CKGUID, GetPhysicManagerGUID) + DECLAREOBJECTTYPE(PhysicManager) + DECLARESTATIC_1(PhysicManager,PhysicManager*,Cast,CKBaseManager* iM) + DECLAREFUN_C_0(PhysicManager*, GetPhysicManager) + + DECLAREPOINTERTYPE(pRigidBody) + DECLAREPOINTERTYPEALIAS(pRigidBody,"pBody") + + DECLAREFUN_C_0(CKGUID,getRigidBodyParameterType) + DECLAREFUN_C_1(void,logWarning,const char*) + + DECLAREPOINTERTYPE(pWorld) + DECLAREPOINTERTYPE(pCloth) + DECLAREPOINTERTYPE(pVehicle) + DECLAREPOINTERTYPE(pWheel) + DECLAREPOINTERTYPE(pVehicle) + DECLAREPOINTERTYPE(pVehicleMotor) + DECLAREPOINTERTYPE(pVehicleGears) + + DECLAREPOINTERTYPE(pWheel1) + DECLAREPOINTERTYPE(pWheel2) + + + DECLAREINHERITANCESIMPLE("pWheel","pWheel1") + DECLAREINHERITANCESIMPLE("pWheel","pWheel2") + + ////////////////////////////////////////////////////////////////////////// + // + // Joints : + // + + + DECLAREPOINTERTYPE(pJoint) + DECLAREPOINTERTYPE(pJointFixed) + DECLAREPOINTERTYPE(pJointDistance) + DECLAREPOINTERTYPE(pJointD6) + DECLAREPOINTERTYPE(pJointPulley) + DECLAREPOINTERTYPE(pJointBall) + DECLAREPOINTERTYPE(pJointRevolute) + DECLAREPOINTERTYPE(pJointPrismatic) + DECLAREPOINTERTYPE(pJointCylindrical) + DECLAREPOINTERTYPE(pJointPointInPlane) + DECLAREPOINTERTYPE(pJointPointOnLine) + + + DECLAREINHERITANCESIMPLE("pJoint","pJointDistance") + DECLAREINHERITANCESIMPLE("pJoint","pJointD6") + DECLAREINHERITANCESIMPLE("pJoint","pJointFixed") + DECLAREINHERITANCESIMPLE("pJoint","pJointPulley") + DECLAREINHERITANCESIMPLE("pJoint","pJointBall") + DECLAREINHERITANCESIMPLE("pJoint","pJointRevolute") + DECLAREINHERITANCESIMPLE("pJoint","pJointPrismatic") + DECLAREINHERITANCESIMPLE("pJoint","pJointCylindrical") + DECLAREINHERITANCESIMPLE("pJoint","pJointPointOnLine") + DECLAREINHERITANCESIMPLE("pJoint","pJointPointInPlane") + //---------------------------------------------------------------- + // + // help structures collision + // + + DECLAREOBJECTTYPE(pGroupsMask) + DECLARECTOR_0(__newpGroupsMask) + DECLAREMEMBER(pGroupsMask,int,bits0) + DECLAREMEMBER(pGroupsMask,int,bits1) + DECLAREMEMBER(pGroupsMask,int,bits2) + DECLAREMEMBER(pGroupsMask,int,bits3) + + + DECLAREOBJECTTYPE(pCollisionSettings) + DECLARECTOR_0(__newpCollisionSettings) + DECLAREMEMBER(pCollisionSettings,int,collisionGroup) + DECLAREMEMBER(pCollisionSettings,pGroupsMask,groupsMask) + DECLAREMEMBER(pCollisionSettings,float,skinWidth) + + + DECLAREOBJECTTYPE(pRaycastHit) + DECLARECTOR_0(__newpRaycastHit) + DECLAREMEMBER(pRaycastHit,float,distance) + DECLAREMEMBER(pRaycastHit,CK3dEntity*,shape) + DECLAREMEMBER(pRaycastHit,VxVector,worldImpact) + DECLAREMEMBER(pRaycastHit,VxVector,worldNormal) + DECLAREMEMBER(pRaycastHit,int,faceID) + DECLAREMEMBER(pRaycastHit,int,internalFaceID) + DECLAREMEMBER(pRaycastHit,float,u) + DECLAREMEMBER(pRaycastHit,float,v) + DECLAREMEMBER(pRaycastHit,int,materialIndex) + DECLAREMEMBER(pRaycastHit,int,flags) + + DECLAREENUM("pFilterOp") + DECLAREENUMVALUE("pFilterOp", "FO_And" , 0) + DECLAREENUMVALUE("pFilterOp", "FO_Or" , 1) + DECLAREENUMVALUE("pFilterOp", "FO_Xor" ,2) + DECLAREENUMVALUE("pFilterOp", "FO_Nand",3 ) + DECLAREENUMVALUE("pFilterOp", "FO_Nor" , 4) + DECLAREENUMVALUE("pFilterOp", "FO_NXor" ,5 ) + + DECLAREENUM("pShapesType") + DECLAREENUMVALUE("pShapesType", "ST_Static" , 1) + DECLAREENUMVALUE("pShapesType", "ST_Dynamic" , 2) + DECLAREENUMVALUE("pShapesType", "ST_All" , 3) + + //---------------------------------------------------------------- + // + // help structures Rigid body + // + + DECLAREENUM("BodyFlags") + DECLAREENUMVALUE("BodyFlags", "BF_Moving" , 1) + DECLAREENUMVALUE("BodyFlags", "BF_Gravity" , 2) + DECLAREENUMVALUE("BodyFlags", "BF_Collision" , 4) + DECLAREENUMVALUE("BodyFlags", "BF_Kinematic" , 8) + DECLAREENUMVALUE("BodyFlags", "BF_SubShape" , 16) + DECLAREENUMVALUE("BodyFlags", "BF_Hierarchy" , 32) + DECLAREENUMVALUE("BodyFlags", "BF_Attributes" , 64) + DECLAREENUMVALUE("BodyFlags", "BF_TriggerShape" , 128) + + + DECLAREENUM("BodyLockFlags") + DECLAREENUMVALUE("BodyLockFlags", "BF_LPX" , 2) + DECLAREENUMVALUE("BodyLockFlags", "BF_LPY" , 4) + DECLAREENUMVALUE("BodyLockFlags", "BF_LPZ" , 8) + DECLAREENUMVALUE("BodyLockFlags", "BF_LRX" , 16) + DECLAREENUMVALUE("BodyLockFlags", "BF_LRY" , 32) + DECLAREENUMVALUE("BodyLockFlags", "BF_LRZ" , 64) + + + + DECLAREENUM("HullType") + DECLAREENUMVALUE("HullType", "HT_Sphere" , 0) + DECLAREENUMVALUE("HullType", "HT_Box" , 1) + DECLAREENUMVALUE("HullType", "HT_Capsule" , 2) + DECLAREENUMVALUE("HullType", "HT_Plane" , 3) + DECLAREENUMVALUE("HullType", "HT_Mesh" , 4) + DECLAREENUMVALUE("HullType", "HT_ConvexMesh" , 5) + DECLAREENUMVALUE("HullType", "HT_HeightField" , 6) + DECLAREENUMVALUE("HullType", "HT_Wheel" , 7) + DECLAREENUMVALUE("HullType", "HT_ConvexCylinder" , 9) + + + + + DECLAREENUM("CombineMode") + DECLAREENUMVALUE("CombineMode", "CM_Average" , 0) + DECLAREENUMVALUE("CombineMode", "CM_Min" , 1) + DECLAREENUMVALUE("CombineMode", "CM_Multiply" , 2) + DECLAREENUMVALUE("CombineMode", "CM_Max" , 3) + + DECLAREENUM("pObjectDescrMask") + DECLAREENUMVALUE("pObjectDescrMask", "OD_XML" , 1) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Pivot" , 2) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Mass" , 4) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Collision" , 8) + DECLAREENUMVALUE("pObjectDescrMask", "OD_CCD" , 16) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Material" , 32) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Optimization" , 64) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Capsule" , 128) + DECLAREENUMVALUE("pObjectDescrMask", "OD_ConvexCylinder" , 256) + DECLAREENUMVALUE("pObjectDescrMask", "OD_Wheel" , 512) + + + DECLAREENUM("DIRECTION") + DECLAREENUMVALUE("DIRECTION", "DIR_X" , 0) + DECLAREENUMVALUE("DIRECTION", "DIR_Y" , 1) + DECLAREENUMVALUE("DIRECTION", "DIR_Z" , 2) + + + //---------------------------------------------------------------- + // + // Wheel related types + // + + + DECLAREOBJECTTYPE(pTireFunction) + DECLARECTOR_0(__newpTireFunction) + DECLAREMEMBER(pTireFunction,float,extremumSlip) + DECLAREMEMBER(pTireFunction,float,extremumValue) + DECLAREMEMBER(pTireFunction,float,asymptoteSlip) + DECLAREMEMBER(pTireFunction,float,stiffnessFactor) + DECLAREMEMBER(pTireFunction,int,xmlLink) + DECLAREMETHOD_0(pTireFunction,void,setToDefault) + + + + + + DECLAREENUM("WheelFlags") + DECLAREENUMVALUE("WheelFlags", "WF_SteerableInput" , 1) + DECLAREENUMVALUE("WheelFlags", "WF_SteerableAuto" , 2) + DECLAREENUMVALUE("WheelFlags", "WF_AffectedByHandbrake" , 4) + DECLAREENUMVALUE("WheelFlags", "WF_Accelerated" , 8) + DECLAREENUMVALUE("WheelFlags", "WF_BuildLowerHalf" , 256) + DECLAREENUMVALUE("WheelFlags", "WF_UseWheelShape" , 512) + DECLAREENUMVALUE("WheelFlags", "WF_VehicleControlled" , 1024) + + + DECLAREENUM("WheelShapeFlags") + DECLAREENUMVALUE("WheelShapeFlags", "WSF_WheelAxisContactNormal" , 1) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_InputLatSlipVelocity" , 1) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_InputLongSlipVelocity" , 2) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_UnscaledSpringBehavior" , 4) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_EmulateLegacyWheel" , 8) + DECLAREENUMVALUE("WheelShapeFlags", "WSF_ClampedFriction" , 16) + + + + DECLAREENUM("pConvexFlags") + DECLAREENUMVALUE("pConvexFlags", "CF_FlipNormals" , CF_FlipNormals) + DECLAREENUMVALUE("pConvexFlags", "CF_16BitIndices" , CF_16BitIndices) + DECLAREENUMVALUE("pConvexFlags", "CF_ComputeConvex" , CF_ComputeConvex) + DECLAREENUMVALUE("pConvexFlags", "CF_InflateConvex" , CF_InflateConvex) + DECLAREENUMVALUE("pConvexFlags", "CF_UncompressedNormals" , CF_UncompressedNormals) + + + + DECLAREOBJECTTYPE(pAxisReferencedLength) + DECLARECTOR_0(__newpAxisReferenceLength) + DECLAREMEMBER(pAxisReferencedLength,float,value) + DECLAREMEMBER(pAxisReferencedLength,CKBeObject*,reference) + DECLAREMEMBER(pAxisReferencedLength,int,referenceAxis) + DECLAREMETHOD_0(pAxisReferencedLength,bool,isValid) + DECLAREMETHOD_0(pAxisReferencedLength,void,setToDefault) + + DECLAREOBJECTTYPE(pWheelDescr) + DECLARECTOR_0(__newpWheelDescr) + DECLAREMEMBER(pWheelDescr,float,springRestitution) + DECLAREMEMBER(pWheelDescr,pAxisReferencedLength,radius) + DECLAREMEMBER(pWheelDescr,float,wheelSuspension) + DECLAREMEMBER(pWheelDescr,float,springDamping) + DECLAREMEMBER(pWheelDescr,float,springDamping) + DECLAREMEMBER(pWheelDescr,float,maxBrakeForce) + DECLAREMEMBER(pWheelDescr,float,frictionToFront) + DECLAREMEMBER(pWheelDescr,float,frictionToSide) + DECLAREMEMBER(pWheelDescr,float,inverseWheelMass) + DECLAREMEMBER(pWheelDescr,WheelFlags,wheelFlags) + DECLAREMEMBER(pWheelDescr,WheelShapeFlags,wheelShapeFlags) + DECLAREMEMBER(pWheelDescr,pTireFunction,latFunc) + DECLAREMEMBER(pWheelDescr,pTireFunction,longFunc) + DECLAREMETHOD_0(pWheelDescr,void,setToDefault) + DECLAREMETHOD_0(pWheelDescr,bool,isValid) + + + + + + + + + + + DECLAREOBJECTTYPE(pConvexCylinderSettings) + DECLARECTOR_0(__newpCollisionSettings) + DECLAREMEMBER(pConvexCylinderSettings,pAxisReferencedLength,radius) + DECLAREMEMBER(pConvexCylinderSettings,pAxisReferencedLength,height) + DECLAREMEMBER(pConvexCylinderSettings,int,approximation) + DECLAREMEMBER(pConvexCylinderSettings,VxVector,forwardAxis) + DECLAREMEMBER(pConvexCylinderSettings,CK3dEntity*,forwardAxisRef) + DECLAREMEMBER(pConvexCylinderSettings,VxVector,downAxis) + DECLAREMEMBER(pConvexCylinderSettings,CK3dEntity*,downAxisRef) + DECLAREMEMBER(pConvexCylinderSettings,VxVector,rightAxis) + DECLAREMEMBER(pConvexCylinderSettings,CK3dEntity*,rightAxisRef) + DECLAREMEMBER(pConvexCylinderSettings,bool,buildLowerHalfOnly) + DECLAREMEMBER(pConvexCylinderSettings,pConvexFlags,convexFlags) + DECLAREMETHOD_0(pConvexCylinderSettings,bool,isValid) + DECLAREMETHOD_0(pConvexCylinderSettings,void,setToDefault) + + DECLAREOBJECTTYPE(pCapsuleSettingsEx) + DECLARECTOR_0(__newpCapsuleSettingsEx) + DECLAREMEMBER(pCapsuleSettingsEx,pAxisReferencedLength,radius) + DECLAREMEMBER(pCapsuleSettingsEx,pAxisReferencedLength,height) + + + DECLAREOBJECTTYPE(pMaterial) + DECLARECTOR_0(__newpMaterial) + DECLAREMEMBER(pMaterial,int,flags) + DECLAREMEMBER(pMaterial,float,dynamicFriction) + DECLAREMEMBER(pMaterial,float,staticFriction) + DECLAREMEMBER(pMaterial,float,restitution) + DECLAREMEMBER(pMaterial,float,dynamicFrictionV) + DECLAREMEMBER(pMaterial,float,staticFrictionV) + DECLAREMEMBER(pMaterial,CombineMode,frictionCombineMode) + DECLAREMEMBER(pMaterial,CombineMode,restitutionCombineMode) + DECLAREMEMBER(pMaterial,VxVector,dirOfAnisotropy) + DECLAREMEMBER(pMaterial,int,xmlLinkID) + + + DECLAREOBJECTTYPE(pOptimization) + DECLARECTOR_0(__newpOptimization) + DECLAREMEMBER(pOptimization,BodyLockFlags,transformationFlags) + DECLAREMEMBER(pOptimization,float,linDamping) + DECLAREMEMBER(pOptimization,float,angDamping) + DECLAREMEMBER(pOptimization,float,linSleepVelocity) + DECLAREMEMBER(pOptimization,float,angSleepVelocity) + DECLAREMEMBER(pOptimization,float,sleepEnergyThreshold) + DECLAREMEMBER(pOptimization,int,dominanceGroup) + DECLAREMEMBER(pOptimization,int,solverIterations) + DECLAREMEMBER(pOptimization,int,compartmentGroup) + + DECLAREOBJECTTYPE(pMassSettings) + DECLARECTOR_0(__newpMassSettings) + DECLAREMEMBER(pMassSettings,float,newDensity) + DECLAREMEMBER(pMassSettings,float,totalMass) + DECLAREMEMBER(pMassSettings,VxVector,localPosition) + DECLAREMEMBER(pMassSettings,VxVector,localOrientation) + DECLAREMEMBER(pMassSettings,CK_ID,massReference) + + DECLAREOBJECTTYPE(pPivotSettings) + DECLARECTOR_0(__newpPivotSettings) + DECLAREMEMBER(pPivotSettings,VxVector,localPosition) + DECLAREMEMBER(pPivotSettings,VxVector,localOrientation) + DECLAREMEMBER(pPivotSettings,CK_ID,pivotReference) + + + DECLAREOBJECTTYPE(pCCDSettings) + DECLARECTOR_0(__newpCCD) + DECLAREMEMBER(pCCDSettings,float,motionThresold) + DECLAREMEMBER(pCCDSettings,int,flags) + DECLAREMEMBER(pCCDSettings,CK_ID,meshReference) + DECLAREMEMBER(pCCDSettings,float,scale) + + + + DECLAREOBJECTTYPE(pObjectDescr) + DECLARECTOR_0(__newpObjectDescr) + DECLAREMEMBER(pObjectDescr,HullType,hullType) + DECLAREMEMBER(pObjectDescr,float,density) + DECLAREMEMBER(pObjectDescr,BodyFlags,flags) + DECLAREMEMBER(pObjectDescr,VxVector,massOffset) + DECLAREMEMBER(pObjectDescr,VxVector,shapeOffset) + DECLAREMEMBER(pObjectDescr,float,skinWidth) + DECLAREMEMBER(pObjectDescr,float,newDensity) + DECLAREMEMBER(pObjectDescr,float,totalMass) + DECLAREMEMBER(pObjectDescr,int,collisionGroup) + DECLAREMEMBER(pObjectDescr,int,hirarchy) + + DECLAREMEMBER(pObjectDescr,int,mask) + + + + DECLAREMEMBER(pObjectDescr,pCollisionSettings,collision) + DECLAREMETHOD_0(pObjectDescr,pCollisionSettings&,getCollision) + DECLAREMETHOD_1(pObjectDescr,void,setCollision,pCollisionSettings) + + DECLAREMEMBER(pObjectDescr,pMaterial,material) + DECLAREMETHOD_0(pObjectDescr,pMaterial&,getMaterial) + DECLAREMETHOD_1(pObjectDescr,void,setMaterial,pMaterial) + + DECLAREMEMBER(pObjectDescr,pMassSettings,mass) + DECLAREMETHOD_0(pObjectDescr,pMassSettings&,getMass) + DECLAREMETHOD_1(pObjectDescr,void,setMass,pMassSettings) + + DECLAREMEMBER(pObjectDescr,pCCDSettings,ccd) + DECLAREMETHOD_0(pObjectDescr,pCCDSettings&,getCollision) + DECLAREMETHOD_1(pObjectDescr,void,setCollision,pCCDSettings) + + DECLAREMEMBER(pObjectDescr,pOptimization,optimization) + DECLAREMETHOD_0(pObjectDescr,pOptimization&,getOptimization) + DECLAREMETHOD_1(pObjectDescr,void,setOptimization,pOptimization) + + DECLAREMEMBER(pObjectDescr,pPivotSettings,pivot) + DECLAREMETHOD_0(pObjectDescr,pPivotSettings&,getPivot) + DECLAREMETHOD_1(pObjectDescr,void,setPivot,pPivotSettings) + + DECLAREMEMBER(pObjectDescr,pCapsuleSettingsEx,capsule) + DECLAREMETHOD_0(pObjectDescr,pCapsuleSettingsEx&,getCapsule) + DECLAREMETHOD_1(pObjectDescr,void,setCapsule,pCapsuleSettingsEx) + + DECLAREMEMBER(pObjectDescr,pConvexCylinderSettings,convexCylinder) + DECLAREMETHOD_0(pObjectDescr,pConvexCylinderSettings&,getConvexCylinder) + DECLAREMETHOD_1(pObjectDescr,void,setConvexCylinder,pConvexCylinderSettings) + + + DECLAREMETHOD_1(CK3dEntity,CKParameterOut*,GetAttributeParameter,int) + + + //#define REGISTERVSLGUID(iGUID, iClassName) VSLM->RegisterGUID(iGUID, iClassName); + + + + + + + + + + + + + + STOPVSLBIND + + +} + + +PhysicManager*GetPhysicManager() +{ + return GetPMan(); +} diff --git a/usr/Src/old/Core/Manager/PhysicManagerVTRegisterVSL.cpp b/usr/Src/old/Core/Manager/PhysicManagerVTRegisterVSL.cpp new file mode 100644 index 0000000..16608ba --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerVTRegisterVSL.cpp @@ -0,0 +1,746 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + +//#include "pVehicle.h" + + + + +PhysicManager *ourMan = NULL; + +typedef ForceMode PForceMode; +typedef D6MotionMode PJMotion; +typedef D6DriveType PDriveType; + + +pRigidBody *getBody(CK3dEntity*ent){ + pRigidBody *body = GetPMan()->getBody(ent); + if (body) + { + return body; + }else{ + return NULL; + } +} + +void __newpSpring(BYTE *iAdd) +{ + new (iAdd) pSpring(); +} +void __newpSoftLimit(BYTE *iAdd) +{ + new (iAdd) pJD6SoftLimit(); +} + +void __newpDrive(BYTE *iAdd) +{ + new (iAdd) pJD6Drive(); +} +void __newpJointLimit(BYTE *iAdd) +{ + new (iAdd) pJointLimit(); +} + +void __newpMotor(BYTE *iAdd) +{ + new (iAdd) pMotor(); +} + + +pSerializer *GetSerializer() +{ + return pSerializer::Instance(); +} + + + +void __newpClothDescr(BYTE *iAdd) +{ + new(iAdd)pClothDesc(); +} + +#define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) + + +void PhysicManager::_RegisterVSL() +{ + + _RegisterVSLCommon(); + + + ourMan = GetPMan(); + + + _RegisterVSLCommon(); + _RegisterVSLVehicle(); + + STARTVSLBIND(m_Context) + + + ////////////////////////////////////////////////////////////////////////// + // + // Bindings for pVehicle related classes : + // + // + + DECLAREENUM("pClothAttachmentFlag") + DECLAREENUMVALUE("pClothAttachmentFlag", "PCAF_ClothAttachmentTwoway" ,1 ) + DECLAREENUMVALUE("pClothAttachmentFlag", "PCAF_ClothAttachmentTearable" ,2 ) + + DECLAREENUM("pClothFlag") + DECLAREENUMVALUE("pClothFlag", "PCF_Pressure" ,1 ) + + DECLAREENUMVALUE("pClothFlag", "PCF_Static",2) + DECLAREENUMVALUE("pClothFlag", "PCF_DisableCollision",4) + DECLAREENUMVALUE("pClothFlag", "PCF_SelfCollision",8) + DECLAREENUMVALUE("pClothFlag", "PCF_Gravity",32) + DECLAREENUMVALUE("pClothFlag", "PCF_Bending",64) + DECLAREENUMVALUE("pClothFlag", "PCF_BendingOrtho",128) + DECLAREENUMVALUE("pClothFlag", "PCF_Damping",256) + DECLAREENUMVALUE("pClothFlag", "PCF_CollisionTwoway",512) + DECLAREENUMVALUE("pClothFlag", "PCF_TriangleCollision",2048) + DECLAREENUMVALUE("pClothFlag", "PCF_Tearable",4096) + DECLAREENUMVALUE("pClothFlag", "PCF_Hardware",8192) + DECLAREENUMVALUE("pClothFlag", "PCF_ComDamping",16384) + DECLAREENUMVALUE("pClothFlag", "PCF_ValidBounds",32768) + DECLAREENUMVALUE("pClothFlag", "PCF_FluidCollision",65536) + DECLAREENUMVALUE("pClothFlag", "PCF_DisableDynamicCCD",131072) + DECLAREENUMVALUE("pClothFlag", "PCF_AddHere",262144) + DECLAREENUMVALUE("pClothFlag", "PCF_AttachToParentMainShape",524288) + DECLAREENUMVALUE("pClothFlag", "PCF_AttachToCollidingShapes",1048576) + DECLAREENUMVALUE("pClothFlag", "PCF_AttachToCore",2097152) + DECLAREENUMVALUE("pClothFlag", "PCF_AttachAttributes",4194304) + + + + + + + DECLAREOBJECTTYPE(pClothDesc) + + DECLAREMEMBER(pClothDesc,float,thickness) + DECLAREMEMBER(pClothDesc,float,density) + DECLAREMEMBER(pClothDesc,float,bendingStiffness) + + DECLAREMEMBER(pClothDesc,float,stretchingStiffness) + DECLAREMEMBER(pClothDesc,float,dampingCoefficient) + DECLAREMEMBER(pClothDesc,float,friction) + DECLAREMEMBER(pClothDesc,float,pressure) + DECLAREMEMBER(pClothDesc,float,tearFactor) + DECLAREMEMBER(pClothDesc,float,collisionResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,attachmentResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,attachmentTearFactor) + DECLAREMEMBER(pClothDesc,float,toFluidResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,fromFluidResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,minAdhereVelocity) + DECLAREMEMBER(pClothDesc,int,solverIterations) + DECLAREMEMBER(pClothDesc,VxVector,externalAcceleration) + DECLAREMEMBER(pClothDesc,VxVector,windAcceleration) + DECLAREMEMBER(pClothDesc,float,wakeUpCounter) + DECLAREMEMBER(pClothDesc,float,sleepLinearVelocity) + DECLAREMEMBER(pClothDesc,int,collisionGroup) + DECLAREMEMBER(pClothDesc,VxBbox,validBounds) + DECLAREMEMBER(pClothDesc,float,relativeGridSpacing) + DECLAREMEMBER(pClothDesc,pClothFlag,flags) + DECLAREMEMBER(pClothDesc,pClothAttachmentFlag,attachmentFlags) + DECLAREMEMBER(pClothDesc,VxColor,tearVertexColor) + DECLAREMEMBER(pClothDesc,CK_ID,worldReference) + + + DECLAREMETHOD_0(pClothDesc,void,setToDefault) + DECLARECTOR_0(__newpClothDescr) + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Vehicle : + // + DECLAREMETHOD_1(pVehicle,void,updateVehicle,float) + DECLAREMETHOD_5(pVehicle,void,setControlState,float,bool,float,bool,bool) + + + DECLAREMETHOD_1(pVehicle,pWheel*,getWheel,CK3dEntity*) + DECLAREMETHOD_0(pVehicle,pVehicleMotor*,getMotor) + DECLAREMETHOD_0(pVehicle,pVehicleGears*,getGears) + + DECLAREMETHOD_0(pVehicle,void,gearUp) + DECLAREMETHOD_0(pVehicle,void,gearDown) + + + DECLAREMETHOD_0(pVehicleGears,int,getGear) + + + + ////////////////////////////////////////////////////////////////////////// + //motor : + DECLAREMETHOD_0(pVehicleMotor,float,getRpm) + DECLAREMETHOD_0(pVehicleMotor,float,getTorque) + + + DECLAREMETHOD_0(pWheel,pWheel1*,castWheel1) + DECLAREMETHOD_0(pWheel,pWheel2*,castWheel2) + + DECLAREMETHOD_0(pWheel,float,getWheelRollAngle) + DECLAREMETHOD_0(pWheel2,float,getRpm) + DECLAREMETHOD_0(pWheel2,float,getAxleSpeed) + DECLAREMETHOD_0(pWheel2,float,getSuspensionTravel) + DECLAREMETHOD_0(pWheel2,VxVector,getGroundContactPos) + + + ////////////////////////////////////////////////////////////////////////// + // + // Bindings for pVehicle related classes : + // + // + + + + + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Bindings for pVehicle related classes : + // + // + DECLAREOBJECTTYPE(pJointLimit) + DECLARECTOR_0(__newpJointLimit) + DECLAREMEMBER(pJointLimit,float,hardness) + DECLAREMEMBER(pJointLimit,float,restitution) + DECLAREMEMBER(pJointLimit,float,value) + + DECLAREOBJECTTYPE(pJD6Drive) + DECLARECTOR_0(__newpDrive) + DECLAREMEMBER(pJD6Drive,float,damping) + DECLAREMEMBER(pJD6Drive,float,spring) + DECLAREMEMBER(pJD6Drive,float,forceLimit) + DECLAREMEMBER(pJD6Drive,int,driveType) + + DECLAREOBJECTTYPE(pJD6SoftLimit) + DECLARECTOR_0(__newpSoftLimit) + DECLAREMEMBER(pJD6SoftLimit,float,damping) + DECLAREMEMBER(pJD6SoftLimit,float,spring) + DECLAREMEMBER(pJD6SoftLimit,float,value) + DECLAREMEMBER(pJD6SoftLimit,float,restitution) + + + DECLAREOBJECTTYPE(pSpring) + DECLARECTOR_0(__newpSpring) + //DECLARECTOR_3(__newpSpringSettings3,float,float,float) + DECLAREMEMBER(pSpring,float,damper) + DECLAREMEMBER(pSpring,float,spring) + DECLAREMEMBER(pSpring,float,targetValue) + + DECLAREOBJECTTYPE(pMotor) + DECLARECTOR_0(__newpMotor) + DECLAREMEMBER(pMotor,float,maximumForce) + DECLAREMEMBER(pMotor,float,targetVelocity) + DECLAREMEMBER(pMotor,float,freeSpin) + + ////////////////////////////////////////////////////////////////////////// + // + // Serializer : + // + DECLAREPOINTERTYPE(pSerializer) + DECLAREFUN_C_0(pSerializer*, GetSerializer) + DECLAREMETHOD_2(pSerializer,void,overrideBody,pRigidBody*,int) + DECLAREMETHOD_2(pSerializer,int,loadCollection,const char*,int) + DECLAREMETHOD_1(pSerializer,int,saveCollection,const char*) + DECLAREMETHOD_2(pSerializer,void,parseFile,const char*,int) + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Factory + // + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // ENUMERATION + // + + DECLAREENUM("D6DriveType") + + DECLAREENUMVALUE("D6DriveType", "D6DT_Position" ,1 ) + DECLAREENUMVALUE("D6DriveType", "D6DT_Velocity" ,2 ) + + + DECLAREENUM("PForceMode") + + DECLAREENUMVALUE("PForceMode", "PFM_Force" , 0) + DECLAREENUMVALUE("PForceMode", "PFM_Impulse" , 1) + DECLAREENUMVALUE("PForceMode", "PFM_VelocityChange" , 2) + DECLAREENUMVALUE("PForceMode", "PFM_SmoothImpulse" , 3) + DECLAREENUMVALUE("PForceMode", "PFM_SmoothVelocityChange" , 4) + DECLAREENUMVALUE("PForceMode", "PFM_Acceleration" , 5) + + DECLAREENUM("D6MotionMode") + + DECLAREENUMVALUE("D6MotionMode", "D6MM_Locked" , 0) + DECLAREENUMVALUE("D6MotionMode", "D6MM_Limited" , 1) + DECLAREENUMVALUE("D6MotionMode", "D6MM_Free" , 2) + + DECLAREENUM("JType") + DECLAREENUMVALUE("JType", "JT_Any" , -1) + DECLAREENUMVALUE("JType", "JT_Prismatic" , 0) + DECLAREENUMVALUE("JType", "JT_Revolute" , 1) + DECLAREENUMVALUE("JType", "JT_Cylindrical" , 2) + DECLAREENUMVALUE("JType", "JT_Spherical" , 3) + DECLAREENUMVALUE("JType", "JT_PointOnLine" , 4) + DECLAREENUMVALUE("JType", "JT_PointInPlane" , 5) + DECLAREENUMVALUE("JType", "JT_Distance" , 6) + DECLAREENUMVALUE("JType", "JT_Pulley" , 7) + DECLAREENUMVALUE("JType", "JT_Fixed" ,8 ) + DECLAREENUMVALUE("JType", "JT_D6" ,9 ) + + + ////////////////////////////////////////////////////////////////////////// + // + // Bindings for pVehicle related classes : + // + // + DECLAREMETHOD_2(pFactory,pVehicle*,createVehicle,CK3dEntity*,pVehicleDesc) + + + //DECLAREMETHOD_0(pVehicle,float,getWheelRollAngle) + //DECLAREMETHOD_0(pVehicle,float,getRpm) + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT CREATION + // + DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointDistance*,createDistanceJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,VxVector(),VxVector,VxVector(),float,0.0f,float,0.0f,pSpring,pSpring()) + DECLAREMETHOD_5(pFactory,pJointD6*,createD6Joint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,bool) + DECLAREMETHOD_2(pFactory,pJointFixed*,createFixedJoint,CK3dEntity*,CK3dEntity*) + DECLAREMETHOD_3_WITH_DEF_VALS(pFactory,pRigidBody*,createBody,CK3dEntity*,NODEFAULT,pObjectDescr,NODEFAULT,CK3dEntity*,NULL) + + DECLAREMETHOD_2(pFactory,pRigidBody*,createRigidBody,CK3dEntity*,pObjectDescr&) + + DECLAREMETHOD_2(pFactory,bool,loadMaterial,pMaterial&,const char*) + DECLAREMETHOD_2(pFactory,pMaterial,loadMaterial,const char*,int&) + + DECLAREMETHOD_2(pFactory,bool,loadFrom,pWheelDescr&,const char*) + DECLAREMETHOD_5(pFactory,pWheel*,createWheel,CK3dEntity *,CK3dEntity*,pWheelDescr,pConvexCylinderSettings,VxVector) + + + + + + DECLAREMETHOD_6(pFactory,pJointPulley*,createPulleyJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointBall*,createBallJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointRevolute*,createRevoluteJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointPrismatic*,createPrismaticJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointCylindrical*,createCylindricalJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointPointInPlane*,createPointInPlaneJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointPointOnLine*,createPointOnLineJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + + + + + DECLAREMETHOD_2(pFactory,pCloth*,createCloth,CK3dEntity*,pClothDesc) + + + + ////////////////////////////////////////////////////////////////////////// + // + // Cloth + // + DECLAREMETHOD_4(pCloth,void,attachToCore,CK3dEntity*,float,float,float) + DECLAREMETHOD_2(pCloth,void,attachToShape,CK3dEntity*,pClothAttachmentFlag) + + + ////////////////////////////////////////////////////////////////////////// + // + // MANAGER + // + + + DECLAREMETHOD_0(PhysicManager,pWorld*,getDefaultWorld) + DECLAREMETHOD_1(PhysicManager,pRigidBody*,getBody,CK3dEntity*) + DECLAREMETHOD_1(PhysicManager,pWorld*,getWorldByBody,CK3dEntity*) + DECLAREMETHOD_1(PhysicManager,pWorld*,getWorld,CK_ID) + DECLAREMETHOD_1(PhysicManager,int,getAttributeTypeByGuid,CKGUID) + + + DECLAREMETHOD_1(CK3dEntity,CKBOOL,HasAttribute,int) + + + + DECLAREMETHOD_3_WITH_DEF_VALS(PhysicManager,pJoint*,getJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NULL,JType,JT_Any) + +// DECLAREMETHOD_0(PhysicManager,void,makeDongleTest) + + + ////////////////////////////////////////////////////////////////////////// + // + // World + // + + DECLAREMETHOD_1(pWorld,pRigidBody*,getBody,CK3dEntity*) + DECLAREMETHOD_1(pWorld,pVehicle*,getVehicle,CK3dEntity*) + DECLAREMETHOD_3(pWorld,pJoint*,getJoint,CK3dEntity*,CK3dEntity*,JType) + + DECLAREMETHOD_3(pWorld,void,setFilterOps,pFilterOp,pFilterOp,pFilterOp) + DECLAREMETHOD_1(pWorld,void,setFilterBool,bool) + DECLAREMETHOD_1(pWorld,void,setFilterConstant0,const pGroupsMask&) + DECLAREMETHOD_1(pWorld,void,setFilterConstant1,const pGroupsMask&) + + + + + // + DECLAREMETHOD_5_WITH_DEF_VALS(pWorld,bool,raycastAnyBounds,const VxRay&,NODEFAULT,pShapesType,NODEFAULT,pGroupsMask,NODEFAULT,int,0xffffffff,float,NX_MAX_F32) + DECLAREMETHOD_8(pWorld,bool,overlapSphereShapes,CK3dEntity*,const VxSphere&,CK3dEntity*,pShapesType,CKGroup*,int,const pGroupsMask*,BOOL) + + //(const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,unsigned int groups=0xffffffff, float maxDist=NX_MAX_F32); + + + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT :: Revolute + // + DECLAREMETHOD_0(pJoint,pJointRevolute*,castRevolute) + DECLAREMETHOD_1(pJointRevolute,void,setGlobalAnchor,const VxVector&) + DECLAREMETHOD_1(pJointRevolute,void,setGlobalAxis,const VxVector&) + + + DECLAREMETHOD_1(pJointRevolute,void,setSpring,pSpring) + DECLAREMETHOD_1(pJointRevolute,void,setHighLimit,pJointLimit) + DECLAREMETHOD_1(pJointRevolute,void,setLowLimit,pJointLimit) + DECLAREMETHOD_1(pJointRevolute,void,setMotor,pMotor) + + DECLAREMETHOD_0(pJointRevolute,pSpring,getSpring) + DECLAREMETHOD_0(pJointRevolute,pJointLimit,getLowLimit) + DECLAREMETHOD_0(pJointRevolute,pJointLimit,getHighLimit) + DECLAREMETHOD_0(pJointRevolute,pMotor,getMotor) + DECLAREMETHOD_1(pJointRevolute,void,enableCollision,bool) + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT :: Ball + // + DECLAREMETHOD_0(pJoint,pJointBall*,castBall) + + DECLAREMETHOD_1(pJointBall,void,setAnchor,VxVector) + + DECLAREMETHOD_1(pJointBall,void,setSwingLimitAxis,VxVector) + DECLAREMETHOD_1(pJointBall,bool,setSwingLimit,pJointLimit) + DECLAREMETHOD_1(pJointBall,bool,setTwistHighLimit,pJointLimit) + DECLAREMETHOD_1(pJointBall,bool,setTwistLowLimit,pJointLimit) + + + DECLAREMETHOD_0(pJointBall,pJointLimit,getSwingLimit) + DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistHighLimit) + DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistLowLimit) + + DECLAREMETHOD_1(pJointBall,bool,setSwingSpring,pSpring) + DECLAREMETHOD_1(pJointBall,bool,setTwistSpring,pSpring) + DECLAREMETHOD_1(pJointBall,void,setJointSpring,pSpring) + + DECLAREMETHOD_0(pJointBall,pSpring,getSwingSpring) + DECLAREMETHOD_0(pJointBall,pSpring,getTwistSpring) + DECLAREMETHOD_0(pJointBall,pSpring,getJointSpring) + + DECLAREMETHOD_1(pJointBall,void,enableCollision,bool) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Prismatic + // + // + DECLAREMETHOD_0(pJoint,pJointPrismatic*,castPrismatic) + + DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointPrismatic,void,enableCollision,bool) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Cylindrical + // + // + DECLAREMETHOD_0(pJoint,pJointCylindrical*,castCylindrical) + + DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointCylindrical,void,enableCollision,int) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Point In Plane + // + // + DECLAREMETHOD_0(pJoint,pJointPointInPlane*,castPointInPlane) + + DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointPointInPlane,void,enableCollision,bool) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Point In Plane + // + // + DECLAREMETHOD_0(pJoint,pJointPointOnLine*,castPointOnLine) + + DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointPointOnLine,void,enableCollision,bool) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT BASE + // + // + DECLAREMETHOD_1(pJoint,void,setLocalAnchor0,VxVector) + + DECLAREMETHOD_2(pJoint,void,setBreakForces,float,float) + DECLAREMETHOD_2(pJoint,void,getBreakForces,float&,float&) + DECLAREMETHOD_3(pJoint,int,addLimitPlane,VxVector,VxVector,float) + DECLAREMETHOD_2_WITH_DEF_VALS(pJoint,void,setLimitPoint,VxVector,NODEFAULT,bool,true) + DECLAREMETHOD_0(pJoint,void,purgeLimitPlanes) + DECLAREMETHOD_0(pJoint,void,resetLimitPlaneIterator) + DECLAREMETHOD_0(pJoint,int,hasMoreLimitPlanes) + DECLAREMETHOD_3(pJoint,int,getNextLimitPlane,VxVector&,float&,float&) + DECLAREMETHOD_0(pJoint,int,getType) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT :: DISTANCE + // + DECLAREMETHOD_0(pJoint,pJointDistance*,castDistanceJoint) + + DECLAREMETHOD_1(pJointDistance,void,setMinDistance,float) + DECLAREMETHOD_1(pJointDistance,void,setMaxDistance,float) + DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor0,VxVector) + DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor1,VxVector) + DECLAREMETHOD_1(pJointDistance,void,setSpring,pSpring) + DECLAREMETHOD_0(pJointDistance,float,getMinDistance) + DECLAREMETHOD_0(pJointDistance,float,getMaxDistance) + DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor0) + DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor1) + DECLAREMETHOD_0(pJointDistance,pSpring,getSpring) + DECLAREMETHOD_1(pJointDistance,void,enableCollision,bool) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT PULLEY + // + + DECLAREMETHOD_0(pJoint,pJointPulley*,castPulley) + + DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorA,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorB,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setPulleyA,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setPulleyB,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setStiffness,float) + DECLAREMETHOD_1(pJointPulley,void,setRatio,float) + DECLAREMETHOD_1(pJointPulley,void,setRigid,int) + DECLAREMETHOD_1(pJointPulley,void,setDistance,float) + DECLAREMETHOD_1(pJointPulley,void,setMotor,pMotor) + DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorA) + DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorB) + DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyA) + DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyB) + DECLAREMETHOD_0(pJointPulley,float,getStiffness) + + DECLAREMETHOD_0(pJointPulley,float,getRatio) + DECLAREMETHOD_0(pJointPulley,float,getDistance) + DECLAREMETHOD_1(pJointPulley,void,enableCollision,bool) + DECLAREMETHOD_0(pJointPulley,pMotor,getMotor) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT D6 + // + + DECLAREMETHOD_0(pJoint,pJointD6*,castD6Joint) + + DECLAREMETHOD_1(pJointD6,void,setTwistMotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setSwing1MotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setSwing2MotionMode,D6MotionMode) + + DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) + + + DECLAREMETHOD_1(pJointD6,void,setXMotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setYMotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setZMotionMode,D6MotionMode) + + DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) + + ////////////////////////////////////////////////////////////////////////// + //softwLimits + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getLinearLimit) + DECLAREMETHOD_1(pJointD6,int,setLinearLimit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing1Limit) + DECLAREMETHOD_1(pJointD6,int,setSwing1Limit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing2Limit) + DECLAREMETHOD_1(pJointD6,int,setSwing2Limit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistHighLimit) + DECLAREMETHOD_1(pJointD6,int,setTwistHighLimit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistLowLimit) + DECLAREMETHOD_1(pJointD6,int,setTwistLowLimit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getXDrive) + DECLAREMETHOD_1(pJointD6,int,setXDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getYDrive) + DECLAREMETHOD_1(pJointD6,int,setYDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getZDrive) + DECLAREMETHOD_1(pJointD6,int,setZDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getSwingDrive) + DECLAREMETHOD_1(pJointD6,int,setSwingDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getTwistDrive) + DECLAREMETHOD_1(pJointD6,int,setTwistDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getSlerpDrive) + DECLAREMETHOD_1(pJointD6,int,setSlerpDrive,pJD6Drive) + + DECLAREMETHOD_1(pJointD6,void,setDrivePosition,VxVector) + DECLAREMETHOD_1(pJointD6,void,setDriveRotation,VxQuaternion) + + DECLAREMETHOD_1(pJointD6,void,setDriveLinearVelocity,VxVector) + DECLAREMETHOD_1(pJointD6,void,setDriveAngularVelocity,VxVector) + + DECLAREMETHOD_1(pJointD6,void,enableCollision,bool) + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Rigid Body Exports + // + // + + + /************************************************************************/ + /* Forces */ + /************************************************************************/ + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addForce,const VxVector&,NODEFAULT, PForceMode, 0,bool,true) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addTorque,const VxVector&,NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalForce,const VxVector&,NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalTorque,const VxVector&,NODEFAULT, PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtPos, const VxVector&,NODEFAULT,const VxVector&,NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtLocalPos,const VxVector,NODEFAULT, const VxVector&, NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtPos, const VxVector&, NODEFAULT,const VxVector&,NODEFAULT, PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtLocalPos, const VxVector&, NODEFAULT,const VxVector&, NODEFAULT,PForceMode,0,bool,true) + + + /************************************************************************/ + /* Momentum */ + /************************************************************************/ + DECLAREMETHOD_1(pRigidBody,void,setAngularMomentum,const VxVector&) + DECLAREMETHOD_1(pRigidBody,void,setLinearMomentum,const VxVector&) + DECLAREMETHOD_0(pRigidBody,VxVector,getAngularMomentum) + DECLAREMETHOD_0(pRigidBody,VxVector,getLinearMomentum) + + /************************************************************************/ + /* Pose : */ + /************************************************************************/ + DECLAREMETHOD_1(pRigidBody,void,setPosition,const VxVector&) + DECLAREMETHOD_1(pRigidBody,void,setRotation,const VxQuaternion&) + DECLAREMETHOD_1(pRigidBody,void,translateLocalShapePosition,VxVector) + + /************************************************************************/ + /* Velocity : */ + /************************************************************************/ + + DECLAREMETHOD_1(pRigidBody,void,setLinearVelocity,const VxVector&) + DECLAREMETHOD_1(pRigidBody,void,setAngularVelocity,const VxVector&) + DECLAREMETHOD_0(pRigidBody,float,getMaxAngularSpeed) + DECLAREMETHOD_0(pRigidBody,VxVector,getLinearVelocity) + DECLAREMETHOD_0(pRigidBody,VxVector,getAngularVelocity) + + /************************************************************************/ + /* Mass */ + /************************************************************************/ + + DECLAREMETHOD_1(pRigidBody,void,setMassOffset,VxVector) + DECLAREMETHOD_1(pRigidBody,void,setMaxAngularSpeed,float) + + /************************************************************************/ + /* Hull */ + /************************************************************************/ + DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) + + + DECLAREMETHOD_0(pRigidBody,pWorld*,getWorld) + DECLAREMETHOD_1(pRigidBody,pJoint*,isConnected,CK3dEntity*) + //DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) + DECLAREMETHOD_1_WITH_DEF_VALS(pRigidBody,float,getMass,CK3dEntity*,NULL) + DECLAREMETHOD_0(pRigidBody,int,getHullType) + + DECLAREMETHOD_2(pRigidBody,void,setGroupsMask,CK3dEntity*,const pGroupsMask&) + + DECLAREMETHOD_0(pRigidBody,int,getFlags) + DECLAREMETHOD_1(pRigidBody,VxVector,getPointVelocity,VxVector) + DECLAREMETHOD_1(pRigidBody,VxVector,getLocalPointVelocity,VxVector) + + + DECLAREMETHOD_0(pRigidBody,bool,isCollisionEnabled) + + DECLAREMETHOD_1(pRigidBody,void,setKinematic,int) + DECLAREMETHOD_0(pRigidBody,int,isKinematic) + + DECLAREMETHOD_1(pRigidBody,void,enableGravity,int) + DECLAREMETHOD_0(pRigidBody,bool,isAffectedByGravity) + + DECLAREMETHOD_1(pRigidBody,void,setSleeping,int) + DECLAREMETHOD_0(pRigidBody,int,isSleeping) + DECLAREMETHOD_1(pRigidBody,void,setLinearDamping,float) + DECLAREMETHOD_1(pRigidBody,void,setAngularDamping,float) + DECLAREMETHOD_1(pRigidBody,void,lockTransformation,BodyLockFlags) + DECLAREMETHOD_1(pRigidBody,int,isBodyFlagOn,int) + DECLAREMETHOD_1(pRigidBody,void,setSolverIterationCount,int) + + + + DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setCollisionsGroup,int,NODEFAULT,CK3dEntity*,) + DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,enableCollision,bool,NODEFAULT,CK3dEntity*,NULL) + + DECLAREMETHOD_0(pRigidBody,int,getCollisionsGroup) + DECLAREMETHOD_2(pRigidBody,int,updateMassFromShapes,float,float) + DECLAREMETHOD_5_WITH_DEF_VALS(pRigidBody,int,addSubShape,CKMesh*,NULL,pObjectDescr,NODEFAULT,CK3dEntity*,NULL,VxVector,VxVector(),VxQuaternion,VxQuaternion()) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,int,removeSubShape,CKMesh*,NODEFAULT,float,0.0,float,0.0) + + + + STOPVSLBIND + + +} diff --git a/usr/Src/old/Core/Manager/PhysicManagerVehcileVSL.cpp b/usr/Src/old/Core/Manager/PhysicManagerVehcileVSL.cpp new file mode 100644 index 0000000..710fb1b --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerVehcileVSL.cpp @@ -0,0 +1,66 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + +void __newpVehicleDescr(BYTE *iAdd) +{ + + new (iAdd)pVehicleDesc(); +} + +void __newpVehicleMotorDesc(BYTE *iAdd) +{ + new (iAdd)pVehicleMotorDesc(); +} + +void __newpVehicleGearDesc(BYTE *iAdd) +{ + new(iAdd)pVehicleGearDesc(); +} +void PhysicManager::_RegisterVSLVehicle() +{ + STARTVSLBIND(m_Context) + + //---------------------------------------------------------------- + // + // vehicle base types + // + + DECLAREPOINTERTYPE(pVehicleMotorDesc) + + DECLAREMEMBER(pVehicleMotorDesc,float,maxRpmToGearUp) + DECLAREMEMBER(pVehicleMotorDesc,float,minRpmToGearDown) + DECLAREMEMBER(pVehicleMotorDesc,float,maxRpm) + DECLAREMEMBER(pVehicleMotorDesc,float,minRpm) + DECLAREMETHOD_0(pVehicleMotorDesc,void,setToCorvette) + + DECLAREPOINTERTYPE(pVehicleGearDesc) + DECLAREMEMBER(pVehicleGearDesc,int,nbForwardGears) + DECLAREMETHOD_0(pVehicleGearDesc,void,setToDefault) + DECLAREMETHOD_0(pVehicleGearDesc,void,setToCorvette) + DECLAREMETHOD_0(pVehicleGearDesc,bool,isValid) + + + DECLAREOBJECTTYPE(pVehicleDesc) + DECLARECTOR_0(__newpVehicleDescr) + DECLAREMEMBER(pVehicleDesc,float,digitalSteeringDelta) + DECLAREMEMBER(pVehicleDesc,VxVector,steeringSteerPoint) + DECLAREMEMBER(pVehicleDesc,VxVector,steeringTurnPoint) + DECLAREMEMBER(pVehicleDesc,float,steeringMaxAngle) + DECLAREMEMBER(pVehicleDesc,float,transmissionEfficiency) + DECLAREMEMBER(pVehicleDesc,float,differentialRatio) + DECLAREMEMBER(pVehicleDesc,float,maxVelocity) + DECLAREMEMBER(pVehicleDesc,float,motorForce) + + DECLAREMETHOD_0(pVehicleDesc,pVehicleGearDesc*,getGearDescription) + DECLAREMETHOD_0(pVehicleDesc,pVehicleMotorDesc*,getMotorDescr) + DECLAREMETHOD_0(pVehicleDesc,void,setToDefault) + + + + + + STOPVSLBIND + + +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerWatchers.cpp b/usr/Src/old/Core/Manager/PhysicManagerWatchers.cpp new file mode 100644 index 0000000..5906628 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerWatchers.cpp @@ -0,0 +1,98 @@ +#include +#include "vtPhysXAll.h" +#include + + +class PhysicVariableWatcher : public CKVariableManager::Watcher +{ +public: + PhysicVariableWatcher(CKContext* context, XString variableName, XString currentValue); + + virtual void PostWrite(const char* iName); +private: + PhysicVariableWatcher(); + + CKContext* context; + CKBOOL manualSetInProgress; + XString variableName; + XString currentValue; +}; + +PhysicVariableWatcher::PhysicVariableWatcher(CKContext* context, XString variableName, XString currentValue) +{ + this->context = context; + this->manualSetInProgress = FALSE; + this->variableName = variableName; + this->currentValue = currentValue; +} + +static PhysicVariableWatcher *watcherConsole=NULL; + + +void PhysicVariableWatcher::PostWrite(const char* iName) +{ + + + XString newValue; + XString msg; + + // Check if we are currently manually setting the value + if (this->manualSetInProgress) + return; + + if( !context || !context->GetVariableManager()) + return; + + if(!GetPMan()) + return; + + // Get new value + int a=0; + context->GetVariableManager()->GetValue(iName, &GetPMan()->_LogToConsole); + xLogger::GetInstance()->enableConsoleOutput(GetPMan()->_LogToConsole); + + + return ; + + + // Validate value + + if (0 == newValue.Length()) + { + // This is valid, it means disable the GBL platform + } + else + { + + int LogConsole = newValue.ToInt(); + if ( LogConsole ==1 ) + { + // Restore back to previous value + // this->manualSetInProgress = TRUE; + // context->GetVariableManager()->SetValue(this->variableName.CStr(), this->currentValue.CStr()); + // this->manualSetInProgress = FALSE; + } + else + { + // Remember current value + //this->currentValue = newValue; + + // Write back in preferred format + //newValue.Format("(0x%08x,0x%08x)", laid.guid.d1, laid.guid.d2); + + //this->manualSetInProgress = TRUE; + //context->GetVariableManager()->SetValue(this->variableName.CStr(), newValue.CStr()); + //this->manualSetInProgress = FALSE; + } + } +} + + +void +PhysicManager::_registerWatchers(CKContext*context) +{ + const char* nameConsoleLogger = "Physic Console Logger/Console"; + watcherConsole = new PhysicVariableWatcher(context, nameConsoleLogger, "0"); + context->GetVariableManager()->RegisterWatcher(nameConsoleLogger, watcherConsole); + +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerWorldsAndBodies.cpp b/usr/Src/old/Core/Manager/PhysicManagerWorldsAndBodies.cpp new file mode 100644 index 0000000..953af43 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerWorldsAndBodies.cpp @@ -0,0 +1,494 @@ +#include +#include "vtPhysXAll.h" + +#include "vtAttributeHelper.h" + +NxShape *PhysicManager::getSubShape(CK3dEntity*referenceObject) +{ + if (!referenceObject) + return NULL; + + pRigidBody *body = getBody(referenceObject); + if (!body) + return NULL; + + + return body->getSubShape(referenceObject); + + +} +NxCCDSkeleton* PhysicManager::getCCDSkeleton(CKBeObject *shapeReference) +{ + + pWorldMapIt it = getWorlds()->Begin(); + int s = getWorlds()->Size(); + + + while(it != getWorlds()->End()) + { + pWorld *w = *it; + NxActor** actors = w->getScene()->getActors(); + int nbActors = w->getScene()->getNbActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + NxU32 nbShapes = actor->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)actor->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sInfo) + { + + } + + } + } + } + } + } + + return NULL; +} + +void PhysicManager::createWorlds(int flags) +{ + +#ifdef _DEBUG + //assert(m_DefaultSleepingSettings()); +// assert(getWorlds()); +#endif + + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_world_object); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + CK3dEntity*target = static_cast(*it); + pWorld *world = getWorld(target->GetID()); + + const char*name = target->GetName(); + if (world == getDefaultWorld() ) + { + continue; + } + ////////////////////////////////////////////////////////////////////////// + //world not registered : + if (!world) + { + + //at first we check for an attached sleeping settings attribute, when not, we use this->DefaultDefaultSleepingSettings +// pSleepingSettings *sleepSettings = target->HasAttribute(att_sleep_settings) ? +// pFactory::Instance()->GetSleepingSettingsFromEntity(target) : &this->DefaultSleepingSettings(); + + //we also retrieve objects world settings + //pWorldSettings * worldSettings = pFactory::Instance()->GetWorldSettingsFromEntity(target); + + //now we can create the final world,the function initiates the world and also it inserts the world + //in our m_pWorlds array ! + //world = pFactory::Instance()->createWorld(target,worldSettings,sleepSettings); + } + } +}; +int PhysicManager::getNbWorlds(){ return getWorlds()->Size();} +void PhysicManager::checkClothes() +{ + + if (!getNbObjects()) + return; + + if (!isValid()) performInitialization(); + if (!isValid()) + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't make manager valid"); + return; + } + + + ////////////////////////////////////////////////////////////////////////// + // we iterate through all entities tagged with the physic attribute + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_clothDescr); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + + CK3dEntity *target = static_cast(*it); + if (target) + { + const char *bName = target->GetName(); + // is the body registered in any world ? + + + CK_ID wID = vtTools::AttributeTools::GetValueFromAttribute(target,att_clothDescr,E_CS_WORLD_REFERENCE); + CK3dEntity *worldReference = (CK3dEntity*)m_Context->GetObject(wID); + pWorld *world = getWorld(wID); + + if (!worldReference) + { + continue; + } + + if (getBody(target)) + { + continue; + } + + if (world->getShapeByEntityID(target->GetID())) + { + continue; + } + + if (world && worldReference) + { + pCloth *cloth = world->getCloth(target); + if (!cloth) + { + pClothDesc *descr = pFactory::Instance()->createClothDescrFromParameter(target->GetAttributeParameter(att_clothDescr)); + cloth = pFactory::Instance()->createCloth(target,*descr); + if(cloth) + { + ////////////////////////////////////////////////////////////////////////// + if (descr->flags & PCF_AttachToParentMainShape ) + { + if (target->GetParent()) + { + CK3dEntity *bodyReference = pFactory::Instance()->getMostTopParent(target); + if (bodyReference) + { + pRigidBody *body = GetPMan()->getBody(bodyReference); + if (body) + { + cloth->attachToShape((CKBeObject*)bodyReference,descr->attachmentFlags); + } + } + } + } + ////////////////////////////////////////////////////////////////////////// + if (descr->flags & PCF_AttachToCollidingShapes) + { + cloth->attachToCollidingShapes(descr->attachmentFlags); + } + } + } + } + } + } + +} +void PhysicManager::checkWorlds() +{ + + if (!getNbObjects()) + return; + + if (!isValid()) performInitialization(); + if (!isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't make manager valid"); + return; + } + + + ////////////////////////////////////////////////////////////////////////// + // we iterate through all entities tagged with the physic attribute + CKAttributeManager* attman = m_Context->GetAttributeManager(); + const XObjectPointerArray& Array = attman->GetAttributeListPtr(att_physic_object); + for (CKObject** it = Array.Begin(); it != Array.End(); ++it) + { + + CK3dEntity *target = static_cast(*it); + if (target) + { + const char *bName = target->GetName(); + // is the body registered in any world ? + pRigidBody* body = getBody(target); + if(!body) + { + //we retrieve the bodies target world : + CK_ID wID = vtTools::AttributeTools::GetValueFromAttribute(target,GetPAttribute(),E_PPS_WORLD); + int flags = vtTools::AttributeTools::GetValueFromAttribute(target,GetPAttribute(),E_PPS_BODY_FLAGS); + if (flags & BF_SubShape) + { + continue; + } + pWorld *world = getWorld(wID) ? getWorld(wID) : getDefaultWorld(); + if(world) + { + + //now create the final rigid body : + body = pFactory::Instance()->createRigidBodyFull(target,world->getReference()); + } + } + } + } + + + checkClothes(); + _checkObjectsByAttribute(); + + + + ////////////////////////////////////////////////////////////////////////// + pWorldMapIt itx = getWorlds()->Begin(); + while(itx != getWorlds()->End()) + { + pWorld *w = *itx; + if (w) + { + w->checkList(); + } + itx++; + } +} +pWorld *PhysicManager::getWorld(CK3dEntity *_o, CK3dEntity *body) +{ + pWorld *result=NULL; + + + ////////////////////////////////////////////////////////////////////////// + // + // Priorities : + // 1. the given world by _o + // 2. DefaultWorld + // 3. body physic attribute + // 4. created default world + // + ////////////////////////////////////////////////////////////////////////// + // we try to get it over _o : + if (_o) + { + result = getWorld(_o->GetID()); + if (result && getWorld(_o->GetID())->getReference() ) + { + _o = result->getReference(); + return result; + } + } + ////////////////////////////////////////////////////////////////////////// + //still nothing, we try to get the default world : + result = getDefaultWorld(); + if (result && getDefaultWorld()->getReference() ) + { + CK_ID id = getDefaultWorld()->getReference()->GetID(); + _o = result->getReference(); + return result; + } + + ////////////////////////////////////////////////////////////////////////// + //we try to get it over the bodies attribute : + if (body) + { + if (body->HasAttribute(GetPAttribute())) + { + CK_ID id = vtTools::AttributeTools::GetValueFromAttribute(body,GetPMan()->GetPAttribute(),E_PPS_WORLD); + _o = static_cast(ctx()->GetObject(id)); + if (_o) + { + result = getWorld(_o->GetID()); + if (result && getWorld(_o->GetID())->getReference()) + { + _o = result->getReference(); + return result; + } + _o = NULL; + } + } + } + ////////////////////////////////////////////////////////////////////////// + //still nothing + if (!getDefaultWorld()) + { + return NULL; + //result = pFactory::Instance()->createDefaultWorld("pDefaultWorld"); + /* + if (result) + { + _o = getDefaultWorld()->getReference(); + }else{ + + GetPMan()->performInitialization(); + result = GetPMan()->getDefaultWorld(); + _o = result->getReference(); + } + + */ + } + return result; +} +void PhysicManager::destroyWorlds() +{ + + pWorldMapIt it = getWorlds()->Begin(); + int s = getWorlds()->Size(); + + + while(it != getWorlds()->End()) + { + pWorld *w = *it; + if (w) + { + w->destroy(); + + if (w->getReference()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"World destroyed :%s",w->getReference()->GetName()); + } + + getWorlds()->Remove(w->getReference()); + delete w; + w = NULL; + + if (getWorlds()->Size()) + { + destroyWorlds(); + } + } + } + getWorlds()->Clear(); +} +pWorld*PhysicManager::getWorld(CK_ID _o) +{ + + pWorld *result = NULL; + CK3dEntity *obj = static_cast(GetContext()->GetObject(_o)); + if (obj) + { + if (getWorlds()->FindPtr(obj)) + { + return *getWorlds()->FindPtr(obj); + } + } + return 0; +} +void PhysicManager::deleteWorld(CK_ID _o) +{ + + CK3dEntity *obj = static_cast(GetContext()->GetObject(_o)); + if (obj) + { + pWorld *w = getWorld(_o); + if (w) + { + w->destroy(); + getWorlds()->Remove(obj); + delete w; + } + } +} + + + +pWorld*PhysicManager::getWorldByShapeReference(CK3dEntity *shapeReference) +{ + + if (!shapeReference) + { + return NULL; + } + + for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) + { + pWorld *w = *it; + if(w) + { + pRigidBody *body = w->getBody(pFactory::Instance()->getMostTopParent(shapeReference)); + if (body) + { + if (body->isSubShape((CKBeObject*)shapeReference)) + { + return w; + } + } + } + } + return 0; +} +pWorld*PhysicManager::getWorldByBody(CK3dEntity*ent) +{ + + if (!ent) + { + return NULL; + } + + for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) + { + pWorld *w = *it; + if(w) + { + //pRigidBody *body = w->getBody(pFactory::Instance()->getMostTopParent(ent)); + pRigidBody *body = w->getBody(ent); + if (body) + { + return w; + } + } + } + return 0; +} + +pCloth *PhysicManager::getCloth(CK_ID entityID) +{ + + CK3dEntity *entity = (CK3dEntity*)m_Context->GetObject(entityID); + if (!entityID) + { + return NULL; + } + + + for (pWorldMapIt it = getWorlds()->Begin(); it!=getWorlds()->End(); it++) + { + pWorld *w = *it; + if(w) + { + pCloth *cloth = w->getCloth(entity); + if (cloth) + { + return cloth; + } + } + } + + return NULL; +} +int PhysicManager::getNbObjects(int flags /* =0 */) +{ + + CKAttributeManager* attman = ctx()->GetAttributeManager(); + + int testAtt = -1; + + if (flags == 0) testAtt = GetPMan()->GetPAttribute(); + + int newPhysicObjectAttributeType = getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + + + // [3/31/2009 master] + + const XObjectPointerArray& Array = attman->GetAttributeListPtr(testAtt); + int startSize = 0; + startSize +=Array.Size(); + + startSize+=attman->GetAttributeListPtr(newPhysicObjectAttributeType).Size(); + + + /* + pWorldMapIt it = getWorlds()->Begin(); + while(it != getWorlds()->End()) + { + pWorld *w = *it; + if (w) + { + w->checkList(); + } + it++; + } + */ + return startSize; +} \ No newline at end of file diff --git a/usr/Src/old/Core/Manager/PhysicManagerXML.cpp b/usr/Src/old/Core/Manager/PhysicManagerXML.cpp new file mode 100644 index 0000000..c7cede6 --- /dev/null +++ b/usr/Src/old/Core/Manager/PhysicManagerXML.cpp @@ -0,0 +1,35 @@ +#include +#include "vtPhysXAll.h" + + + + +void PhysicManager::reloadXMLDefaultFile(const char*fName) +{ + + + if (! fName || !strlen(fName))return; + + + + ////////////////////////////////////////Load our physic default xml document : + if (getDefaultConfig()) + { + delete m_DefaultDocument; + m_DefaultDocument = NULL; + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted old default config"); + + } + + TiXmlDocument * defaultDoc = loadDefaults(XString(fName)); + if (!defaultDoc) + { + enableFlag(_getManagerFlags(),E_MF_LOADING_DEFAULT_CONFIG_FAILED); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config : PhysicDefaults.xml: failed"); + setDefaultConfig(NULL); + }else + { + setDefaultConfig(defaultDoc); + } + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pCloth/pCloth.cpp b/usr/Src/old/Core/pCloth/pCloth.cpp new file mode 100644 index 0000000..bee43d0 --- /dev/null +++ b/usr/Src/old/Core/pCloth/pCloth.cpp @@ -0,0 +1,514 @@ +#include +#include "vtPhysXAll.h" +#include "Stream.h" +#include "cooking.h" + + + +pCloth::~pCloth() +{ + + + + if (!getCloth()) + { + return; + } + + getWorld()->getScene()->releaseCloth(*mCloth); + //getWorld()->getScene()-> + releaseReceiveBuffers(); + setEntityID(-1); + + +} +void pCloth::detachFromShape(CKBeObject *shape) +{ + if (!shape) + { + return; + } + NxShape *aShape = getWorld()->getShapeByEntityID(shape->GetID()); + if (aShape) + { + getCloth()->detachFromShape(aShape); + } + +} +void pCloth::dominateVertex(int vertexId, float expirationTime, float dominanceWeight) +{ + getCloth()->dominateVertex(vertexId,expirationTime,dominanceWeight); +} + +void pCloth::freeVertex(const int vertexId) +{ + getCloth()->freeVertex(vertexId); +} + +void pCloth::attachVertexToGlobalPosition(const int vertexId, const VxVector &pos) +{ + + getCloth()->attachVertexToGlobalPosition(vertexId,getFrom(pos)); + +} +void pCloth::attachVertexToShape(int vertexId, CKBeObject *shape, const VxVector &localPos, int attachmentFlags) +{ + + if (!shape) + { + return; + } + + if (!getWorld()) + return; + + NxShape *aShape = getWorld()->getShapeByEntityID(shape->GetID()); + if (aShape) + { + getCloth()->attachVertexToShape(vertexId,aShape,getFrom(localPos),attachmentFlags); + } +} + +void pCloth::attachToCore(CK3dEntity *body, float impulseThreshold, float penetrationDepth, float maxDeformationDistance) +{ + + pRigidBody *rbody = GetPMan()->getBody(body); + if (!body) + { + return ; + } + + if (rbody->getWorld() != getWorld() ) + { + return; + } + + getCloth()->attachToCore(rbody->getActor(),impulseThreshold,penetrationDepth,maxDeformationDistance); + + +} + +void pCloth::attachToCollidingShapes(int attachmentFlags) +{ + mCloth->attachToCollidingShapes(attachmentFlags); +} +void pCloth::attachToShape(CKBeObject *shape, int attachmentFlags) +{ + + if (!shape) + { + return; + } + + if (!getWorld()) + return; + + NxShape *aShape = getWorld()->getShapeByEntityID(shape->GetID()); + if (aShape) + { + getCloth()->attachToShape(aShape,attachmentFlags); + } + + +} + +void pCloth::setCollisionResponseCoefficient(float coefficient) +{ + mCloth->setCollisionResponseCoefficient(coefficient); +} +void pCloth::addDirectedForceAtPos(const VxVector& position, const VxVector& force, float radius, ForceMode mode /* = FM_Force */) +{ + mCloth->addDirectedForceAtPos(getFrom(position),getFrom(force),(NxForceMode)mode ); +} +void pCloth::addForceAtVertex(const VxVector& force, int vertexId, ForceMode mode /* = FM_Force */) +{ + mCloth->addForceAtVertex(getFrom(force),vertexId,(NxForceMode)mode); +} + +void pCloth::addForceAtPos(const VxVector& position, float magnitude, float radius, ForceMode mode /* = FM_Force */) +{ + mCloth->addForceAtPos(getFrom(position),magnitude,radius,(NxForceMode)mode); +} + +void pCloth::wakeUp(float wakeCounterValue /* = NX_SLEEP_INTERVAL */) +{ + mCloth->wakeUp(wakeCounterValue); +} + +void pCloth::putToSleep() +{ + mCloth->putToSleep(); +} + +void pCloth::setFlags(int flags) +{ + mCloth->setFlags(flags); +} +void pCloth::setSleepLinearVelocity(float threshold) +{ + mCloth->setSleepLinearVelocity(threshold); +} +void pCloth::setExternalAcceleration(VxVector acceleration) +{ + mCloth->setExternalAcceleration(getFrom(acceleration)); +} +void pCloth::setWindAcceleration(VxVector acceleration) +{ + mCloth->setWindAcceleration(getFrom(acceleration)); +} +void pCloth::setMinAdhereVelocity(float velocity) +{ + mCloth->setMinAdhereVelocity(velocity); +} +void pCloth::setToFluidResponseCoefficient(float coefficient) +{ + mCloth->setToFluidResponseCoefficient(coefficient); +} +void pCloth::setFromFluidResponseCoefficient(float coefficient) +{ + mCloth->setFromFluidResponseCoefficient(coefficient); +} +void pCloth::setAttachmentResponseCoefficient(float coefficient) +{ + mCloth->setAttachmentResponseCoefficient(coefficient); +} +void pCloth::setVelocity(const VxVector& velocity, int vertexId) +{ + mCloth->setVelocity(getFrom(velocity),vertexId); +} +void pCloth::setValidBounds(const VxBbox& validBounds) +{ + NxBounds3 box; + box.set( getFrom(validBounds.Min), getFrom(validBounds.Max)); + mCloth->setValidBounds(box); +} + +void pCloth::setGroup(int collisionGroup) +{ + mCloth->setGroup(collisionGroup); +} +void pCloth::setSolverIterations(int iterations) +{ + mCloth->setSolverIterations(iterations); +} +void pCloth::setThickness(float thickness) +{ + mCloth->setThickness(thickness); +} +void pCloth::setAttachmentTearFactor(float factor) +{ + mCloth->setAttachmentTearFactor(factor); +} +void pCloth::setTearFactor(float factor) +{ + mCloth->setTearFactor(factor); +} +void pCloth::setPressure(float pressure) +{ + mCloth->setPressure(pressure); +} +void pCloth::setFriction(float friction) +{ + mCloth->setFriction(friction); +} +void pCloth::setDampingCoefficient(float dampingCoefficient) +{ + mCloth->setDampingCoefficient(dampingCoefficient); +} + +void pCloth::setStretchingStiffness(float stiffness) +{ + mCloth->setStretchingStiffness(stiffness); +} +void pCloth::setBendingStiffness(float stiffness) +{ + mCloth->setBendingStiffness(stiffness); +} + +void pCloth::updateVirtoolsMesh() +{ + + NxMeshData *data = getReceiveBuffers(); + CK3dEntity *srcEntity =(CK3dEntity*) GetPMan()->GetContext()->GetObject(getEntityID()); + if (!srcEntity) + { + return; + } + + /* + if (getCloth()->isSleeping()) + { + return; + } + + */ + CKMesh *mesh = srcEntity->GetCurrentMesh(); + NxReal *vertices = (NxReal*)data->verticesPosBegin; + + + VxVector pos; + srcEntity->GetPosition(&pos); + for (int i = 0 ; i< mesh->GetVertexCount() ; i++ ) + { + VxVector v; + v.x = vertices[i * 3]; + v.y = vertices[i * 3 + 1]; + v.z = vertices[i * 3 + 2]; + VxVector outIV; + srcEntity->InverseTransform(&outIV,&v); + mesh->SetVertexPosition(i,&outIV); + } + int t = 3; + +} + +bool pCloth::cookMesh(NxClothMeshDesc* desc) +{ + + // we cook the mesh on the fly through a memory stream + // we could also use a file stream and pre-cook the mesh + MemoryWriteBuffer wb; + int dValid = desc->isValid(); + + + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return NULL; + } + + bool success = CookClothMesh(*desc, wb); + + if (!success) + return false; + + MemoryReadBuffer rb(wb.data); + + mClothMesh = GetPMan()->getPhysicsSDK()->createClothMesh(rb); + + CloseCooking(); + + return true; + +} + +bool pCloth::generateMeshDesc(pClothDesc cDesc,NxClothMeshDesc *desc, CKMesh*mesh) +{ + + if (!mesh) + { + return false; + } + + int numVerts = mesh->GetVertexCount(); + int numFaces = mesh->GetFaceCount(); + + // allocate flag buffer + if(desc->vertexFlags == 0) + desc->vertexFlags = malloc(sizeof(NxU32)*desc->numVertices); + + // create tear lines + NxU32* flags = (NxU32*)desc->vertexFlags; + + NxReal *vertices = new float[3 * numVerts]; + //NxVec3 *verts = new NxVec3[numVerts]; + + for (int i = 0 ; i< numVerts ; i++ ) + { + VxVector v; + mesh->GetVertexPosition(i,&v); + vertices[i * 3] = v.x; + vertices[i * 3 + 1] =v.y; + vertices[i * 3 + 2] = v.z; + + + + if (desc->flags & NX_CLOTH_MESH_TEARABLE) + { + DWORD vColor = mesh->GetVertexColor(i); + DWORD cColor = RGBAFTOCOLOR(&cDesc.tearVertexColor); + if (vColor == cColor ) + { + int op2 =0; + flags[i] = NX_CLOTH_VERTEX_TEARABLE; + int k = 0 ; + k++; + } + } + } + + NxU32 *indices2 = new NxU32[numFaces*3]; + + for(int j = 0 ; j < numFaces ; j++) + { + + int findicies[3]; + mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); + indices2[ j *3 ] = findicies[0]; + indices2[ j *3 + 1 ] = findicies[1]; + indices2[ j *3 + 2 ] = findicies[2]; + } + desc->numVertices = numVerts; + desc->pointStrideBytes = sizeof(NxReal)*3; + desc->points = vertices; + desc->numTriangles = numFaces; + desc->triangles = indices2; + desc->triangleStrideBytes = sizeof(NxU32)*3; + desc->flags = 0; + desc->vertexMasses = 0; + desc->vertexFlags = 0; + desc->flags = NX_CLOTH_MESH_WELD_VERTICES; + desc->weldingDistance = 0.0001f; + + return true; + + +} + + +void pCloth::allocateClothReceiveBuffers(int numVertices, int numTriangles) +{ + + // here we setup the buffers through which the SDK returns the dynamic cloth data + // we reserve more memory for vertices than the initial mesh takes + // because tearing creates new vertices + // the SDK only tears cloth as long as there is room in these buffers + + + mReceiveBuffers = new NxMeshData(); + + NxU32 maxVertices = 3 * numVertices; + mReceiveBuffers->verticesPosBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices); + mReceiveBuffers->verticesNormalBegin = (NxVec3*)malloc(sizeof(NxVec3)*maxVertices); + mReceiveBuffers->verticesPosByteStride = sizeof(NxVec3); + mReceiveBuffers->verticesNormalByteStride = sizeof(NxVec3); + mReceiveBuffers->maxVertices = maxVertices; + mReceiveBuffers->numVerticesPtr = (NxU32*)malloc(sizeof(NxU32)); + + // the number of triangles is constant, even if the cloth is torn + NxU32 maxIndices = 3*numTriangles; + mReceiveBuffers->indicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxIndices); + mReceiveBuffers->indicesByteStride = sizeof(NxU32); + mReceiveBuffers->maxIndices = maxIndices; + mReceiveBuffers->numIndicesPtr = (NxU32*)malloc(sizeof(NxU32)); + + // the parent index information would be needed if we used textured cloth + NxU32 maxParentIndices = maxVertices; + mReceiveBuffers->parentIndicesBegin = (NxU32*)malloc(sizeof(NxU32)*maxParentIndices); + mReceiveBuffers->parentIndicesByteStride = sizeof(NxU32); + mReceiveBuffers->maxParentIndices = maxParentIndices; + mReceiveBuffers->numParentIndicesPtr = (NxU32*)malloc(sizeof(NxU32)); + + // init the buffers in case we want to draw the mesh + // before the SDK as filled in the correct values + *mReceiveBuffers->numVerticesPtr = 0; + *mReceiveBuffers->numIndicesPtr = 0; +} + +void pCloth::releaseReceiveBuffers() +{ + + // Parent Indices is always allocated +/* free (mReceiveBuffers.parentIndicesBegin); + + mReceiveBuffers.setToDefault();*/ + +} + +void pCloth::releaseMeshDescBuffers(const NxClothMeshDesc* desc) +{ + + NxVec3* p = (NxVec3*)desc->points; + NxU32* t = (NxU32*)desc->triangles; + NxReal* m = (NxReal*)desc->vertexMasses; + NxU32* f = (NxU32*)desc->vertexFlags; + free(p); + free(t); + free(m); + free(f); +} + + +pCloth::pCloth() +{ + +} + +/*----------------------------------------------------------------------------*/ + +pClothDesc::pClothDesc() +{ + //setToDefault(); + +} + +/*----------------------------------------------------------------------------*/ + +void pClothDesc::setToDefault() +{ + thickness = 0.01f; + density = 1.0f; + bendingStiffness = 1.0f; + + stretchingStiffness = 1.0f; + dampingCoefficient = 0.5f; + friction = 0.5f; + + pressure = 1.0f; + tearFactor = 1.5f; + attachmentTearFactor = 1.5f; + + attachmentResponseCoefficient = 0.2f; + attachmentTearFactor = 1.5f; + collisionResponseCoefficient = 0.2f; + toFluidResponseCoefficient = 1.0f; + + fromFluidResponseCoefficient = 1.0f; + minAdhereVelocity = 1.0f; + flags = PCF_Gravity|PCF_CollisionTwoway; + + solverIterations = 5; + wakeUpCounter = NX_SLEEP_INTERVAL; + sleepLinearVelocity = -1.0f; + collisionGroup = 0; + forceFieldMaterial = 0; + externalAcceleration =VxVector(0.0f, 0.0f, 0.0f); + windAcceleration=VxVector(0.0f, 0.0f, 0.0f); + groupsMask.bits0 = 0; + groupsMask.bits1 = 0; + groupsMask.bits2 = 0; + groupsMask.bits3 = 0; + validBounds = VxBbox(); + relativeGridSpacing = 0.25f; + tearVertexColor.Set(1.0f); + + +} + +/*----------------------------------------------------------------------------*/ + +bool pClothDesc::isValid() const +{ + // if (flags & NX_CLF_SELFCOLLISION) return false; // not supported at the moment + + + if(thickness < 0.0f) return false; + if(density <= 0.0f) return false; + if(bendingStiffness < 0.0f || bendingStiffness > 1.0f) return false; + if(stretchingStiffness <= 0.0f || stretchingStiffness > 1.0f) return false; + if(pressure < 0.0f) return false; + if(tearFactor <= 1.0f) return false; + if(attachmentTearFactor <= 1.0f) return false; + if(solverIterations < 1) return false; + if(friction < 0.0f || friction > 1.0f) return false; + if(dampingCoefficient < 0.0f || dampingCoefficient > 1.0f) return false; + if(collisionResponseCoefficient < 0.0f) return false; + if(wakeUpCounter < 0.0f) return false; + if(attachmentResponseCoefficient < 0.0f || attachmentResponseCoefficient > 1.0f) return false; + if(toFluidResponseCoefficient < 0.0f) return false; + if(fromFluidResponseCoefficient < 0.0f) return false; + if(minAdhereVelocity < 0.0f) return false; + if(relativeGridSpacing < 0.01f) return false; + if(collisionGroup >= 32) return false; // We only support 32 different collision groups + return true; +} diff --git a/usr/Src/old/Core/pErrorStream.cpp b/usr/Src/old/Core/pErrorStream.cpp new file mode 100644 index 0000000..f5917a7 --- /dev/null +++ b/usr/Src/old/Core/pErrorStream.cpp @@ -0,0 +1,29 @@ +#include +#include "vtPhysXAll.h" + +#include "pErrorStream.h" + +namespace vtAgeia +{ + + + +void pErrorStream::reportError(NxErrorCode e, const char* message, const char* file, int line) +{ + + xLogger::xLog(ELOGERROR,E_LI_AGEIA,message); + +} +NxAssertResponse pErrorStream::reportAssertViolation(const char* message, const char* file, int line) +{ + return NX_AR_CONTINUE; + +} +void pErrorStream::print(const char* message) +{ + + xLogger::xLog(ELOGERROR,E_LI_AGEIA,message); + +} + +} diff --git a/usr/Src/old/Core/pFactory/pFactory.cpp b/usr/Src/old/Core/pFactory/pFactory.cpp new file mode 100644 index 0000000..892bead --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactory.cpp @@ -0,0 +1,279 @@ +#include +#include "vtPhysXAll.h" +//#include "tinyxml.h" +#include + + +static pFactory* pFact = NULL; + +void pFactory::findAttributeIdentifiersByGuid(CKGUID guid,std::vector&targetList) +{ + + CKContext *ctx = GetPMan()->GetContext(); + + CKAttributeManager *attMan = ctx->GetAttributeManager(); + CKParameterManager *parMan = ctx->GetParameterManager(); + + int cCount = attMan->GetAttributeCount(); + for(int i = 0 ; i < cCount ; i++) + { + CKSTRING name = attMan->GetAttributeNameByType(i); + if ( parMan->ParameterTypeToGuid(attMan->GetAttributeParameterType(i)) == guid ) + { + targetList.push_back(i); + } + + } +} + +//************************************ +// Method: Instance +// FullName: vtODE::pFactory::Instance +// Access: public +// Returns: pFactory* +// Qualifier: +//************************************ +pFactory* pFactory::Instance() +{ + + if (!pFact) + { + pFact = new pFactory(GetPMan(),GetPMan()->getDefaultConfig()); + } + return pFact; +} + + + + + +//************************************ +// Method: ~pFactory +// FullName: vtODE::pFactory::~pFactory +// Access: public +// Returns: +// Qualifier: +//************************************ +pFactory::~pFactory() +{ + + //Clean(); + delete pFact; + pFact = NULL; +} + +pFactory::pFactory() +{ + +} +//************************************ +// Method: pFactory +// FullName: vtODE::pFactory::pFactory +// Access: public +// Returns: // Qualifier: : m_PManager(prm1), m_DefaultDocument(prm2) +// Parameter: PhysicManager* prm1 +// Parameter: TiXmlDocument*prm2 +//************************************ +pFactory::pFactory(PhysicManager* prm1,TiXmlDocument*prm2) : + mManager(prm1), m_DefaultDocument(prm2) +{ + pFact = this; + mPhysicSDK = NULL; +} +//************************************ +// Method: ResolveFileName +// FullName: vtODE::pFactory::ResolveFileName +// Access: public +// Returns: XString +// Qualifier: +// Parameter: const char *input +//************************************ +XString pFactory::ResolveFileName(const char *input) +{ + CKPathManager *pm = GetPMan()->m_Context->GetPathManager(); + + FILE *file = fopen(input,"r"); + XString result; + if (file) + { + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,input); + + fclose(file); + + return XString(Ini); + } + + if (!file) + { + CKSTRING lastCmo = GetPMan()->m_Context->GetLastCmoLoaded(); + CKPathSplitter splitter(const_cast(lastCmo)); + CKPathSplitter splitter2(const_cast(input)); + CKPathMaker maker(splitter.GetDrive(),splitter.GetDir(),const_cast(input),""); + char* NewFilename = maker.GetFileName(); + file = fopen(NewFilename,"r"); + if (!file) + { + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,input); + file = fopen(Ini,"r"); + if(file) + { + fclose(file); + return XString(Ini); + } + + if(pm) + { + XString fname(const_cast(input)); + CKERROR error = GetPMan()->m_Context->GetPathManager()->ResolveFileName( fname , DATA_PATH_IDX); + if (error ==CK_OK) + { + file = fopen(fname.CStr(),"r"); + if (file) + { + fclose(file); + result = fname; + } + } + + } + } + } + return result; +} + +//************************************ +// Method: CreateFrame +// FullName: vtODE::pFactory::CreateFrame +// Access: public +// Returns: CK3dEntity* +// Qualifier: +// Parameter: XString name +//************************************ +CK3dEntity* +pFactory::createFrame(const char* name) +{ + if (!strlen(name)) + { + return NULL; + } + + int count = ctx()->GetObjectsCountByClassID(CKCID_3DENTITY); + CK_ID* ol = ctx()->GetObjectsListByClassID(CKCID_3DENTITY); + + for(int j=0;j(ctx()->GetObject(ol[j])); + if (!strcmp(o->GetName(),name ) ) + { + return static_cast(o); + } + } + + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_NONAMECHECK; + //if (dynamic) creaoptions = CK_OBJECTCREATION_DYNAMIC; + + // The Creation + + CKObject* object = ctx()->CreateObject(CKCID_3DENTITY,const_cast(name),creaoptions); + CK3dEntity* ent=(CK3dEntity*)object; + ent->SetFlags(ent->GetFlags()|CK_3DENTITY_FRAME); + + // we add it to the level + + CKLevel *level = ctx()->GetCurrentLevel(); + if (level) + { + level->AddObject(object); + } + + return ent; + +} + + + +//************************************ +// Method: _str2Vec +// FullName: vtODE::pFactory::_str2Vec +// Access: public +// Returns: VxVector +// Qualifier: +// Parameter: XString _in +//************************************ +VxVector +pFactory::_str2Vec(XString _in) +{ + short nb = 0 ; + VxVector out; + XStringTokenizer tokizer(_in.CStr(), ","); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) && nb < 3) + { + XString tokx(tok); + out.v[nb] = tokx.ToFloat(); + nb++; + } + return out; +} + +int pFactory::_str2MaterialFlag(XString _in) +{ + + short nb = 0 ; + int result = 0; + XStringTokenizer tokizer(_in.CStr(), "|"); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) && nb < 3) + { + XString tokx(tok); + + if ( _stricmp(tokx.CStr(),"Anisotropic") == 0 ) + { + result |= MF_Anisotropic; + } + if ( _stricmp(tokx.CStr(),"DisableFriction") == 0 ) + { + result |= MF_DisableFriction; + } + if ( _stricmp(tokx.CStr(),"DisableStrongFriction") == 0 ) + { + result |= MF_DisableStrongFriction; + } + nb++; + } + return result; +} + + +int pFactory::_getEnumIndex(XString enumerationFull,XString enumValue) +{ + + int result = 0; + XStringTokenizer tokizer(enumerationFull.CStr(), ","); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok))) + { + XString tokx(tok); + if ( !strcmp(tokx.CStr(),enumValue.CStr()) ) + { + return result; + } + // out.v[nb] = tokx.ToFloat(); + result++; + } + return 0; +} \ No newline at end of file diff --git a/usr/Src/old/Core/pFactory/pFactoryBody.cpp b/usr/Src/old/Core/pFactory/pFactoryBody.cpp new file mode 100644 index 0000000..7a01229 --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryBody.cpp @@ -0,0 +1,1956 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" + +#include "NXU_helper.h" // NxuStream helper functions. +#include "NXU_PhysicsInstantiator.h" + +#include "IParameter.h" + +#include "xDebugTools.h" + + +pRigidBody*pFactory::cloneRigidBody(CK3dEntity *src,CK3dEntity *dst,CKDependencies *deps,int copyFlags,int bodyFlags/* =0 */) +{ + //src->Rest + pRigidBody *result = GetPMan()->getBody(dst); + pRigidBody *srcBody = GetPMan()->getBody(src); + CK3dEntity *referenceObject = dst; + + XString errMsg; + pObjectDescr oDescr; + + //---------------------------------------------------------------- + // + // sanity checks + // + #ifdef _DEBUG + assert(src); + assert(dst); + #endif // _DEBUG + + if (!(copyFlags & PB_CF_PHYSICS)) + { + errMsg.Format("Nothing to copy, aborting"); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,errMsg.Str()); + return NULL; + } + + //iAssertW(!result,"","Object :%s already physicalized"); + + //---------------------------------------------------------------- + // + // fill object description + // + if (!result && IParameter::Instance()->copyTo(oDescr,src,copyFlags)) + { + pWorld *world = GetPMan()->getWorld(oDescr.worlReference) ? GetPMan()->getWorld(oDescr.worlReference) : GetPMan()->getDefaultWorld(); + if(world) + { + + if ( (copyFlags && PB_CF_OVRRIDE_BODY_FLAGS) ) + oDescr.flags = (BodyFlags)bodyFlags; + + //now create the final rigid body : + result = pFactory::Instance()->createRigidBody(dst,oDescr); + } + } + + if (!result){ + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"cloning failed"); + return NULL; + } + + //---------------------------------------------------------------- + // + // clone joints + // + if ( (copyFlags & PB_CF_JOINTS) ) + { + pFactory::cloneJoints(src,dst,copyFlags); + + } + + //---------------------------------------------------------------- + // + // copy velocities + // + if ( (copyFlags & PB_CF_VELOCITIES) ) + { + NxActor *actorSrc = srcBody->getActor(); + NxActor *actorDst = result->getActor(); + + actorDst->setLinearVelocity( actorSrc->getLinearVelocity() ); + actorDst->setAngularVelocity( actorSrc->getAngularVelocity() ); + } + + //---------------------------------------------------------------- + // + // copy forces + // + if ( (copyFlags & PB_CF_FORCE) ) + { + NxActor *actorSrc = srcBody->getActor(); + NxActor *actorDst = result->getActor(); + actorDst->setLinearMomentum( actorSrc->getLinearMomentum() ); + actorDst->setAngularMomentum( actorSrc->getAngularMomentum() ); + } + + //---------------------------------------------------------------- + // + // copy sub shapes if : + // + // "Copy Children In Dependencies" && + // ( copyFlags::OverrideBodyFlags & hierarchy && newBodyFlags & hierarchy ) || + // ( oldBodyFlags & hierarchy ) + if ( ((*deps->At(CKCID_3DENTITY)) & CK_DEPENDENCIES_COPY_3DENTITY_CHILDREN) && + ( (( copyFlags & PB_CF_OVRRIDE_BODY_FLAGS ) && (bodyFlags & BF_Hierarchy)) || + ( oDescr.flags & BF_Hierarchy) ) + ) + { + int dCount = dst->GetChildrenCount(); + CK3dEntity* subEntity = NULL; + while (subEntity= dst->HierarchyParser(subEntity) ) + { + if (subEntity==dst) + continue; + + CK3dEntity *orginalObject = findSimilarInSourceObject(src,dst,subEntity); + if (orginalObject) + { + iAssertW(cloneShape(orginalObject,subEntity,dst,copyFlags,bodyFlags),"","clone of sub shape failed"); + } + } + } + return NULL; +} + +pRigidBody*pFactory::createRigidBody(CK3dEntity *referenceObject,pObjectDescr& oDescr) +{ + CK3dEntity *worldReferenceObject = (CK3dEntity*)GetPMan()->GetContext()->GetObject(oDescr.worlReference); + + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + + if (!world) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"world object invalid, setting to default world"); + world = GetPMan()->getDefaultWorld(); + } + + pRigidBody*result = world->getBody(referenceObject); + + // create minimum object + result = createBody(referenceObject,worldReferenceObject); + + if (!result) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed"); + return NULL; + + } + result->setWorld(world); + result->setFlags(oDescr.flags); + result->setHullType(oDescr.hullType); + + if (oDescr.density <= 0.001f) + oDescr.density = 1.0f; + + if (oDescr.skinWidth <= 0.001f) + oDescr.skinWidth = 0.025f; + + + result->setDensity(oDescr.density); + + bool hierarchy = (oDescr.flags & BF_Hierarchy); + bool isDeformable = oDescr.flags & BF_Deformable; + bool trigger = oDescr.flags & BF_TriggerShape; + + + //################################################################ + // + // Deformable ? + // + + + pCloth *cloth = NULL; + pClothDesc cDescr; + + if (isDeformable) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"deformable feature disabled in this release"); + return NULL; + + cDescr.setToDefault(); + cDescr.worldReference = worldReferenceObject->GetID(); + + if ( result->getFlags() & BF_Gravity ) + { + cDescr.flags |= PCF_Gravity; + } + + if ( result->getFlags() & BF_Collision ) + { + + } + + if (!cloth) + { + cloth = pFactory::Instance()->createCloth(referenceObject,cDescr); + if (!cloth) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : factory object failed !"); + } + } + } + + + float density = oDescr.density; + VxVector box_s= BoxGetZero(referenceObject); + + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + v_matrix = referenceObject->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + + NxVec3 pos = pMath::getFrom(position); + NxQuat rot = pMath::getFrom(quat); + + + //---------------------------------------------------------------- + // + // Fill NxActorDescr + // + + + NxActorDesc actorDesc;actorDesc.setToDefault(); + NxBodyDesc bodyDesc;bodyDesc.setToDefault(); + + // + // Fix parameters to default values + + + actorDesc.density = oDescr.density; + + //skin width + if (oDescr.skinWidth<=0.0001f) + oDescr.skinWidth=0.025f; + + + float radius = result->GetVT3DObject()->GetRadius(); + + //---------------------------------------------------------------- + // + // Create the physic mesh. Externalizing this procedure will corrupt the + // actor description object. + // + + switch(oDescr.hullType) + { + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.dimensions = pMath::getFrom(box_s)*0.5f; + } + shape.density = density; + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + if (! (oDescr.flags & BF_Deformable) ) + { + shape.radius = radius; + } + shape.density = density; + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + + pFactory::Instance()->createMesh(result->getWorld()->getScene(),result->GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return false; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + shape.group = oDescr.collisionGroup; + + actorDesc.shapes.pushBack(&shape); + shape.skinWidth = oDescr.skinWidth; + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + + if (result->GetVT3DObject()->GetCurrentMesh()) + { + if (result->GetVT3DObject()->GetCurrentMesh()->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshes allowed, by Ageia!"); + return false; + } + }else + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); + return false; + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + pFactory::Instance()->createConvexMesh(result->getWorld()->getScene(),result->GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxConvexShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + return false; + + + } + shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + actorDesc.shapes.pushBack(&shape); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + int h = shape.isValid(); + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexCylinder: + { + NxConvexShapeDesc shape; + pConvexCylinderSettings &cSettings = oDescr.convexCylinder; + + iAssertW( (oDescr.mask & OD_ConvexCylinder),pFactory::Instance()->findSettings(cSettings,result->GetVT3DObject()), + "Hull type has been set to convex cylinder but there is no descriptions passed or activated in the pObjectDescr::mask.Trying object attributes...."); + + if (cSettings.radius.reference) + cSettings.radius.evaluate(cSettings.radius.reference); + + if (cSettings.height.reference) + cSettings.height.evaluate(cSettings.height.reference); + + + iAssertW( cSettings.isValid() , cSettings.setToDefault(),""); + + cSettings.radius.value = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); + cSettings.height.value = cSettings.height.value > 0.0f ? cSettings.height.value : (box_s.v[cSettings.height.referenceAxis] * 0.5f); + + + + bool resultAssert = true; + iAssertWR( pFactory::Instance()->_createConvexCylinderMesh(&shape,cSettings,result->GetVT3DObject()),"",resultAssert); + + shape.density = density; + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + + NxCapsuleShapeDesc shape; + pCapsuleSettingsEx &cSettings = oDescr.capsule; + if (!( oDescr.mask & OD_Capsule) ) + { + // try over attribute : + pFactory::Instance()->findSettings(cSettings,result->GetVT3DObject()); + } + + bool resultAssert = true; + + if (cSettings.radius.reference) + cSettings.radius.evaluate(cSettings.radius.reference); + + if (cSettings.height.reference) + cSettings.height.evaluate(cSettings.height.reference); + + iAssertWR(cSettings.isValid(),cSettings.setToDefault(),resultAssert); + + + + shape.radius = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); + shape.height = cSettings.height.value > 0.0f ? (cSettings.height.value-( 2*shape.radius)) : (box_s.v[cSettings.height.referenceAxis] - ( 2*shape.radius)) ; + + + shape.density = density; + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + break; + } + + case HT_Wheel: + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Wheel shape can be sub shape only!"); + return false; + } + } + + if ( !isDeformable) + { + actorDesc.globalPose.t = pos; + actorDesc.globalPose.M = rot; + } + + + + //---------------------------------------------------------------- + // + // Create the final NxActor + // + + if (oDescr.flags & BF_Moving) + actorDesc.body = &bodyDesc; + + NxActor *actor = world->getScene()->createActor(actorDesc); + if (!actor) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); + delete result; + return NULL; + + } + + //---------------------------------------------------------------- + // + // + // + result->setActor(actor); + actor->setName(referenceObject->GetName()); + result->SetVT3DObject(referenceObject); + actor->userData= result; + + + ////////////////////////////////////////////////////////////////////////// + //Deformable : + if (isDeformable && cloth) + { + + pDeformableSettings dSettings; + dSettings.ImpulsThresold = 50.0f; + dSettings.PenetrationDepth= 0.1f ; + dSettings.MaxDeform = 2.0f; + + CKParameterOut *poutDS = referenceObject->GetAttributeParameter(GetPMan()->att_deformable); + if (poutDS) + { + pFactory::Instance()->copyTo(dSettings,poutDS); + } + cloth->attachToCore(referenceObject,dSettings.ImpulsThresold,dSettings.PenetrationDepth,dSettings.MaxDeform); + result->setCloth(cloth); + } + + + ////////////////////////////////////////////////////////////////////////// + // + // Extra settings : + // + + if (result->getFlags() & BF_Moving) + { + VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&oDescr.massOffsetLinear); + actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); + } + + if (result->getFlags() & BF_Kinematic) + { + result->setKinematic(true); + } + + if (result->getFlags() & BF_Moving ) + { + result->enableGravity(result->getFlags() & BF_Gravity); + } + + if (result->getFlags() & BF_Sleep ) + { + result->setSleeping(true); + } + + if (oDescr.worlReference == 0) + { + if (GetPMan()->getDefaultWorld()) + { + oDescr.worlReference = GetPMan()->getDefaultWorld()->getReference()->GetID(); + } + } + + //---------------------------------------------------------------- + // + // store mesh meta info in the first main mesh + // + NxShape *shape = result->getShapeByIndex(); + if (shape) + { + pSubMeshInfo *sInfo = new pSubMeshInfo(); + sInfo->entID = referenceObject->GetID(); + sInfo->refObject = (CKBeObject*)referenceObject; + shape->userData = (void*)sInfo; + result->setMainShape(shape); + shape->setName(referenceObject->GetName()); + + } + + result->enableCollision( (result->getFlags() & BF_Collision), referenceObject ); + + //---------------------------------------------------------------- + // + // Adjust pivot + // + + if ( (oDescr.mask & OD_Pivot) ) + { + iAssertW1( oDescr.pivot.isValid(),oDescr.pivot.setToDefault()); + result->updatePivotSettings(oDescr.pivot,referenceObject); + }else if(pFactory::Instance()->findSettings(oDescr.collision,referenceObject)) + result->updatePivotSettings(oDescr.pivot,referenceObject); + + //---------------------------------------------------------------- + // + // Optimization + // + if ((oDescr.mask & OD_Optimization )) + { + iAssertW1( oDescr.optimization.isValid(),oDescr.optimization.setToDefault()); + result->updateOptimizationSettings(oDescr.optimization); + } + else{ + if(pFactory::Instance()->findSettings(oDescr.optimization,referenceObject)) + { + iAssertW1( oDescr.optimization.isValid(),oDescr.optimization.setToDefault()); + result->updateOptimizationSettings(oDescr.optimization); + } + } + + //---------------------------------------------------------------- + // + // Collision + // + if ((oDescr.mask & OD_Collision)) + result->updateCollisionSettings(oDescr.collision,referenceObject); + else if(pFactory::Instance()->findSettings(oDescr.collision,referenceObject)) + result->updateCollisionSettings(oDescr.collision,referenceObject); + + + //---------------------------------------------------------------- + // + // Material + // + + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + + pMaterial &bMaterial = oDescr.material; + + if (oDescr.mask & OD_Material) + { + result->updateMaterialSettings(bMaterial,referenceObject); + }else + { + bool hasMaterial = pFactory::Instance()->findSettings(bMaterial,referenceObject); + if (!hasMaterial) + { + if (world->getDefaultMaterial()) + { + int z = (int)world->getDefaultMaterial()->userData; + shape->setMaterial(world->getDefaultMaterial()->getMaterialIndex()); + } + }else{ + + iAssertW( bMaterial.isValid(),bMaterial.setToDefault(), + "Material settings were still invalid : "); + + NxMaterialDesc nxMatDescr; + pFactory::Instance()->copyTo(nxMatDescr,bMaterial); + NxMaterial *nxMaterial = world->getScene()->createMaterial(nxMatDescr); + if (nxMaterial) + { + shape->setMaterial(nxMaterial->getMaterialIndex()); + } + } + } + + + xLogger::xLog(ELOGINFO,E_LI_MANAGER,"Rigid body creation successful : %s",referenceObject->GetName()); + + result->setInitialDescription(&oDescr); + + //---------------------------------------------------------------- + // + // Hierarchy mode fix : + // + if ( (oDescr.flags & BF_Hierarchy) ) + oDescr.hirarchy = true; + + if ( oDescr.hirarchy ) + oDescr.flags << BF_Hierarchy; + + + if ( (!oDescr.hirarchy) || !(oDescr.flags & BF_Hierarchy) ) + return result; + + //---------------------------------------------------------------- + // + // Parse hirarchy + // + CK3dEntity* subEntity = NULL; + while (subEntity= referenceObject->HierarchyParser(subEntity) ) + { + pObjectDescr *subDescr = NULL; + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + if (subEntity->HasAttribute(attTypePBSetup)) + { + subDescr = new pObjectDescr(); + CKParameterOut *par = subEntity->GetAttributeParameter(attTypePBSetup); + IParameter::Instance()->copyTo(subDescr,par); + subDescr->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + } + + if (!subDescr) + continue; + + if (subDescr->flags & BF_SubShape) + { + ////////////////////////////////////////////////////////////////////////// + // + // Regular Mesh : + // + + if (subDescr->hullType != HT_Cloth) + { + //result->addSubShape(NULL,*subDescr,subEntity); + + VxQuaternion refQuad;subEntity->GetQuaternion(&refQuad,referenceObject); + VxVector relPos;subEntity->GetPosition(&relPos,referenceObject); + + shape = pFactory::Instance()->createShape(referenceObject,*subDescr,subEntity,subEntity->GetCurrentMesh(),relPos,refQuad); + + //NxShape *shape = result->getSubShape(subEntity); + if (shape) + { + //---------------------------------------------------------------- + // + // check for collision setup + // + + //try to get get from child attributes first + /* + if(pFactory::Instance()->findSettings(subDescr->collision,subEntity)) + { + result->updateCollisionSettings(subDescr->collision,subEntity); + continue; + } + if ( (subDescr->mask & OD_Optimization) ) + { + //if (pFactory::Instance()->findSettings(subDescr->collision,subEntity)) + result->updateCollisionSettings(subDescr->collision,subEntity); + } + else if ( (oDescr.mask & OD_Optimization) ) + { + result->updateCollisionSettings(oDescr.collision,subEntity); + }else if(pFactory::Instance()->findSettings(subDescr->collision,subEntity)) + { + result->updateCollisionSettings(subDescr->collision,subEntity); + } + */ + } + + } + ////////////////////////////////////////////////////////////////////////// + // + // Cloth Mesh : + // + if (subDescr->hullType == HT_Cloth) + { + //pClothDesc *cloth = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + } + } + + //---------------------------------------------------------------- + // + // Adjust mass + // + + //---------------------------------------------------------------- + // + // Collision + // + if ((oDescr.mask & OD_Mass)) + result->updateMassSettings(oDescr.mass); + else if(pFactory::Instance()->findSettings(oDescr.mass,referenceObject)) + result->updateMassSettings(oDescr.mass); + + + return result; + + nothing: + + return result; + +} + +pRigidBody*pFactory::createCapsule(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags) +{ + + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + pRigidBody*result = world->getBody(referenceObject); + if(result) + { + result->destroy(); + delete result; + result = NULL; + } + // we create our final body in the given world : + result = createBody(referenceObject,worldReferenceObject); + if (result) + { + result->setWorld(world); + + using namespace vtTools::AttributeTools; + + result->setFlags(descr->flags); + result->setHullType(descr->hullType); + result->setDataFlags(0x000); + result->checkDataFlags(); + + if (result->getSkinWidth()==-1.0f) + { + result->setSkinWidth(0.01f); + } + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + v_matrix = referenceObject->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + VxVector box_s= BoxGetZero(referenceObject); + + NxVec3 pos = pMath::getFrom(position); + NxQuat rot = pMath::getFrom(quat); + + float density = result->getDensity(); + float radius = referenceObject->GetRadius(); + if (referenceObject->GetRadius() < 0.001f ) + { + radius = 1.0f; + } + + + ////////////////////////////////////////////////////////////////////////// + //create actors description + NxActorDesc actorDesc;actorDesc.setToDefault(); + NxBodyDesc bodyDesc;bodyDesc.setToDefault(); + + ////////////////////////////////////////////////////////////////////////// + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + if (isFlagOn(result->getDataFlags(),EDF_MATERIAL_PARAMETER)) + { + NxMaterialDesc entMatNull;entMatNull.setToDefault(); + NxMaterialDesc *entMat = createMaterialFromEntity(referenceObject); + material = world->getScene()->createMaterial(entMatNull); + material->loadFromDesc(*entMat); + result->setMaterial(material); + }else{ + if (world->getDefaultMaterial()) + { + result->setMaterial(world->getDefaultMaterial()); + } + } + ////////////////////////////////////////////////////////////////////////// + + NxCapsuleShapeDesc capsuleShape; + + if ( creationFlags & E_OFC_DIMENSION ) + { + capsuleShape.height = box_s.y - ((box_s.x)); + capsuleShape.radius = box_s.x*0.5f; + } + + capsuleShape.density = descr->density; + + + capsuleShape.materialIndex = result->getMaterial()->getMaterialIndex(); + + //shape.localPose.t = pMath::getFrom(shapeOffset); + + if (result->getSkinWidth()!=-1.0f) + capsuleShape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&capsuleShape); + + + + + ////////////////////////////////////////////////////////////////////////// + //dynamic object ? + if (result->getFlags() & BF_Moving){ + actorDesc.body = &bodyDesc; + } + else + actorDesc.body = NULL; + + ////////////////////////////////////////////////////////////////////////// + //set transformations + actorDesc.density = descr->density; + + if (creationFlags & E_OFC_POSITION) + { + actorDesc.globalPose.t = pos; + } + + if (creationFlags & E_OFC_POSITION) + { + actorDesc.globalPose.M = rot; + } + + ////////////////////////////////////////////////////////////////////////// + //create the actor + + int v = actorDesc.isValid(); + NxActor *actor = world->getScene()->createActor(actorDesc); + if (!actor) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); + delete result; + return NULL; + + } + + + ////////////////////////////////////////////////////////////////////////// + //set additional settings : + result->setActor(actor); + actor->setName(referenceObject->GetName()); + actor->userData= result; + + if (result->getFlags() & BF_Moving) + { + VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&result->getMassOffset()); + actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); + } + + if (result->getFlags() & BF_Kinematic) + { + actor->raiseBodyFlag(NX_BF_KINEMATIC); + } + + result->enableCollision((result->getFlags() & BF_Collision)); + if (result->getFlags() & BF_Moving) + { + if (!(result->getFlags() & BF_Gravity)) + { + actor->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); + } + } + + NxShape *shape = result->getShapeByIndex(); + if (shape) + { + pSubMeshInfo *sInfo = new pSubMeshInfo(); + sInfo->entID = referenceObject->GetID(); + sInfo->refObject = (CKBeObject*)referenceObject; + shape->userData = (void*)sInfo; + result->setMainShape(shape); + shape->setName(referenceObject->GetName()); + } + } + + return result; +} + +pRigidBody*pFactory::createBox(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,pObjectDescr*descr,int creationFlags) +{ + + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + pRigidBody*result = world->getBody(referenceObject); + if(result) + { + result->destroy(); + delete result; + result = NULL; + } + // we create our final body in the given world : + result = createBody(referenceObject,worldReferenceObject); + if (result) + { + result->setWorld(world); + + using namespace vtTools::AttributeTools; + + result->setFlags(descr->flags); + result->setHullType(descr->hullType); + result->setDataFlags(0x000); + result->checkDataFlags(); + + if (result->getSkinWidth()==-1.0f) + { + result->setSkinWidth(0.01f); + } + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + v_matrix = referenceObject->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + VxVector box_s= BoxGetZero(referenceObject); + + NxVec3 pos = pMath::getFrom(position); + NxQuat rot = pMath::getFrom(quat); + + float density = result->getDensity(); + float radius = referenceObject->GetRadius(); + if (referenceObject->GetRadius() < 0.001f ) + { + radius = 1.0f; + } + + + ////////////////////////////////////////////////////////////////////////// + //create actors description + NxActorDesc actorDesc;actorDesc.setToDefault(); + NxBodyDesc bodyDesc;bodyDesc.setToDefault(); + + ////////////////////////////////////////////////////////////////////////// + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + if (isFlagOn(result->getDataFlags(),EDF_MATERIAL_PARAMETER)) + { + NxMaterialDesc entMatNull;entMatNull.setToDefault(); + NxMaterialDesc *entMat = createMaterialFromEntity(referenceObject); + material = world->getScene()->createMaterial(entMatNull); + material->loadFromDesc(*entMat); + result->setMaterial(material); + }else{ + if (world->getDefaultMaterial()) + { + result->setMaterial(world->getDefaultMaterial()); + } + } + ////////////////////////////////////////////////////////////////////////// + + NxBoxShapeDesc boxShape; + if (creationFlags & E_OFC_DIMENSION ) + { + boxShape.dimensions = pMath::getFrom(box_s)*0.5f; + } + boxShape.density = descr->density; + boxShape.materialIndex = result->getMaterial()->getMaterialIndex(); + if (result->getSkinWidth()!=-1.0f) + boxShape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&boxShape); + + ////////////////////////////////////////////////////////////////////////// + //dynamic object ? + if (result->getFlags() & BF_Moving){ + actorDesc.body = &bodyDesc; + } + else + actorDesc.body = NULL; + + ////////////////////////////////////////////////////////////////////////// + //set transformations + actorDesc.density = descr->density; + + if (creationFlags & E_OFC_POSITION) + { + actorDesc.globalPose.t = pos; + } + + if (creationFlags & E_OFC_POSITION) + { + actorDesc.globalPose.M = rot; + } + + ////////////////////////////////////////////////////////////////////////// + //create the actor + + int v = actorDesc.isValid(); + NxActor *actor = world->getScene()->createActor(actorDesc); + if (!actor) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); + delete result; + return NULL; + + } + + + ////////////////////////////////////////////////////////////////////////// + //set additional settings : + result->setActor(actor); + actor->setName(referenceObject->GetName()); + actor->userData= result; + + if (result->getFlags() & BF_Moving) + { + VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&result->getMassOffset()); + actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); + } + + if (result->getFlags() & BF_Kinematic) + { + actor->raiseBodyFlag(NX_BF_KINEMATIC); + } + + result->enableCollision((result->getFlags() & BF_Collision)); + if (result->getFlags() & BF_Moving) + { + if (!(result->getFlags() & BF_Gravity)) + { + actor->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); + } + } + + NxShape *shape = result->getShapeByIndex(); + if (shape) + { + pSubMeshInfo *sInfo = new pSubMeshInfo(); + sInfo->entID = referenceObject->GetID(); + sInfo->refObject = (CKBeObject*)referenceObject; + shape->userData = (void*)sInfo; + result->setMainShape(shape); + shape->setName(referenceObject->GetName()); + } + } + + return result; +} + +pRigidBody*pFactory::createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject,NXU::NxActorDesc *desc,int flags) +{ + +#ifdef _DEBUG + assert(referenceObject); + assert(desc); +#endif + + /************************************************************************/ + /* + + + + + */ + /************************************************************************/ + VxVector vpos; + referenceObject->GetPosition(&vpos); + + VxQuaternion vquat; + referenceObject->GetQuaternion(&vquat); + + NxQuat nrot = desc->globalPose.M; + NxVec3 npos = desc->globalPose.t; + + NxMat33 rotX; + rotX.rotX( PI / 2.0f ); + NxMat33 rotZ; + rotZ.rotZ( PI ); + + NxMat34 rotMat; + rotMat.M.multiply( rotZ, rotX ); + + NxMat34 posMat( true ); + +/* posMat.t.set( -mTerrain->getPosition().x, + mTerrain->getPosition().y, + mTerrain->getPosition().z ); +*/ + desc->globalPose.multiply( posMat, rotMat ); + + + NxQuat nrot2 = desc->globalPose.M; + NxVec3 npos2 = desc->globalPose.t; + + VxQuaternion nvm = getFromStream(nrot); + + VxVector nvpos = getFromStream(npos); + + + + for (NxU32 k=0; kmShapes.size(); k++) + { + NXU::NxShapeDesc *shape = desc->mShapes[k]; + NxVec3 locPos = shape->localPose.t; + NxQuat localQuad = shape->localPose.M; + } + + + int op = 2; + + + + return NULL; +} + + + +pRigidBody*pFactory::createRigidBodyFull(CK3dEntity *referenceObject, CK3dEntity *worldReferenceObject) +{ + + + //################################################################ + // + // Sanity checks + // + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + pRigidBody*result = world->getBody(referenceObject); + + + if(result) + { + result->destroy(); + delete result; + result = NULL; + } + + + //################################################################ + // + // Construct the result + // + result = createBody(referenceObject,worldReferenceObject); + if (result) + { + + + result->setWorld(world); + + + //---------------------------------------------------------------- + // + // Handle different attribute types (Object or pBSetup) + // + + int attTypeOld = GetPMan()->GetPAttribute(); + int attTypeNew = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + + pObjectDescr *oDescr = NULL; + + + //---------------------------------------------------------------- + // + // the old way : + // + + if (referenceObject->HasAttribute(attTypeOld)) + { + result->retrieveSettingsFromAttribute(); + oDescr = pFactory::Instance()->createPObjectDescrFromParameter(referenceObject->GetAttributeParameter(GetPMan()->GetPAttribute())); + + + + } + + bool hierarchy = result->getFlags() & BF_Hierarchy; + bool isDeformable = result->getFlags() & BF_Deformable; + bool trigger = (result->getFlags() & BF_TriggerShape); + + + //---------------------------------------------------------------- + // + // the new way + // + + if (referenceObject->HasAttribute(attTypeNew)) + { + oDescr = new pObjectDescr(); + + } + + + result->checkDataFlags(); + + + + + /* + pObjectDescr *oDescr = + if (!oDescr) + return result; + + */ + + //################################################################ + // + // Older versions have the hierarchy mode settings not the body flags + // We migrate it : + // + + if (oDescr->hirarchy) + { + result->setFlags( (result->getFlags() | BF_Hierarchy )); + } + if (hierarchy) + { + oDescr->hirarchy = hierarchy; + } + //################################################################ + // + // Deformable ? + // + + + pCloth *cloth = NULL; + pClothDesc cDescr; + + if (isDeformable) + { + cDescr.setToDefault(); + cDescr.worldReference = worldReferenceObject->GetID(); + + if ( result->getFlags() & BF_Gravity ) + { + cDescr.flags |= PCF_Gravity; + } + + if ( result->getFlags() & BF_Collision ) + { + + } + + if (!cloth) + { + cloth = pFactory::Instance()->createCloth(referenceObject,cDescr); + if (!cloth) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : factory object failed !"); + } + } + } + + + //################################################################ + // + // Some settings + // + if (result->getSkinWidth()==-1.0f) + { + result->setSkinWidth(0.01f); + } + + float radius = referenceObject->GetRadius(); + if (referenceObject->GetRadius() < 0.001f ) + { + radius = 1.0f; + } + + float density = result->getDensity(); + VxVector box_s= BoxGetZero(referenceObject); + + //################################################################ + // + // Calculate destination matrix + // + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + v_matrix = referenceObject->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + + NxVec3 pos = pMath::getFrom(position); + NxQuat rot = pMath::getFrom(quat); + + + ////////////////////////////////////////////////////////////////////////// + //create actors description + NxActorDesc actorDesc;actorDesc.setToDefault(); + NxBodyDesc bodyDesc;bodyDesc.setToDefault(); + + + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + + + + + switch(result->getHullType()) + { + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + + if (! isDeformable ) + { + shape.dimensions = pMath::getFrom(box_s)*0.5f; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&shape); + + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + + + if (! isDeformable ) + { + shape.radius = radius; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&shape); + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + + if (! (result->getFlags() & BF_Deformable) ) + { + + //xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Can not use a mesh as de"); + //return NULL; + + } + + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + + createMesh(world->getScene(),referenceObject->GetCurrentMesh(),myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return NULL; + } + shape.meshData = getManager()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + actorDesc.shapes.pushBack(&shape); + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + if (referenceObject->GetCurrentMesh()) + { + if (referenceObject->GetCurrentMesh()->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshs allowed, by Ageia!"); + goto nothing; + } + }else + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); + goto nothing; + + + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + createConvexMesh(world->getScene(),referenceObject->GetCurrentMesh(),myMesh); + + NxConvexShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + goto nothing; + + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + goto nothing; + } + shape.meshData = getManager()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + actorDesc.shapes.pushBack(&shape); + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + int h = shape.isValid(); + CloseCooking(); + + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexCylinder: + { + NxConvexShapeDesc shape; + if (!_createConvexCylinder(&shape,referenceObject)) + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + + shape.density = density; + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + + actorDesc.shapes.pushBack(&shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + + NxCapsuleShapeDesc shape; + + if ( !isDeformable ) + { + + pCapsuleSettings cSettings; + + pFactory::Instance()->findSettings(cSettings,referenceObject); + + shape.radius = cSettings.radius > 0.0f ? cSettings.radius : box_s.v[cSettings.localRadiusAxis] * 0.5f; + shape.height = cSettings.height > 0.0f ? cSettings.height : box_s.v[cSettings.localLengthAxis] - ( 2*shape.radius) ; + } + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + // shape.localPose.t = pMath::getFrom(shapeOffset); + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + actorDesc.shapes.pushBack(&shape); + break; + } + + case HT_Wheel: + { + // xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + + + /* + NxWheelShapeDesc shape; + shape.radius = box_s.z*0.5f; + shape.density = density; + if (result->getSkinWidth()!=-1.0f) + shape.skinWidth = result->getSkinWidth(); + + if (referenceObject && referenceObject->HasAttribute(GetPMan()->att_wheelDescr )) + { + CKParameter *par = referenceObject->GetAttributeParameter(GetPMan()->att_wheelDescr ); + if (par) + { + pWheelDescr *wheelDescr = pFactory::Instance()->copyTo(par); + if (wheelDescr) + { + + float heightModifier = (wheelDescr->wheelSuspension + radius ) / wheelDescr->wheelSuspension; + shape.suspension.damper = wheelDescr->springDamping * heightModifier; + shape.suspension.targetValue = wheelDescr->springBias * heightModifier; + shape.suspensionTravel = wheelDescr->wheelSuspension; + + shape.lateralTireForceFunction.stiffnessFactor *= wheelDescr->frictionToSide; + shape.longitudalTireForceFunction.stiffnessFactor*=wheelDescr->frictionToFront; + shape.inverseWheelMass = 0.1; + int isValid = shape.isValid(); + + + actorDesc.shapes.pushBack(&shape); + } + }else + { + XString name = result->GetVT3DObject()->GetName(); + name << " needs to have an additional wheel attribute attached ! "; + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,name.CStr()); + } + } + */ + break; + } + } + + + ////////////////////////////////////////////////////////////////////////// + //dynamic object ? + if (result->getFlags() & BF_Moving){ + actorDesc.body = &bodyDesc; + } + else + actorDesc.body = NULL; + + ////////////////////////////////////////////////////////////////////////// + //set transformations + actorDesc.density = result->getDensity(); + + + if ( !isDeformable) + { + actorDesc.globalPose.t = pos; + actorDesc.globalPose.M = rot; + } + + + ////////////////////////////////////////////////////////////////////////// + //create the actor + + int v = actorDesc.isValid(); + NxActor *actor = world->getScene()->createActor(actorDesc); + if (!actor) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't create actor"); + delete result; + return NULL; + + } + + ////////////////////////////////////////////////////////////////////////// + //set additional settings : + result->setActor(actor); + actor->setName(referenceObject->GetName()); + actor->userData= result; + + ////////////////////////////////////////////////////////////////////////// + //Deformable : + if (isDeformable && cloth) + { + + pDeformableSettings dSettings; + dSettings.ImpulsThresold = 50.0f; + dSettings.PenetrationDepth= 0.1f ; + dSettings.MaxDeform = 2.0f; + + CKParameterOut *poutDS = referenceObject->GetAttributeParameter(GetPMan()->att_deformable); + if (poutDS) + { + pFactory::Instance()->copyTo(dSettings,poutDS); + } + cloth->attachToCore(referenceObject,dSettings.ImpulsThresold,dSettings.PenetrationDepth,dSettings.MaxDeform); + result->setCloth(cloth); + } + + + ////////////////////////////////////////////////////////////////////////// + // + // Extra settings : + // + + if (result->getFlags() & BF_Moving) + { + VxVector massOffsetOut;referenceObject->Transform(&massOffsetOut,&result->getMassOffset()); + actor->setCMassOffsetGlobalPosition(pMath::getFrom(massOffsetOut)); + } + + + if (result->getFlags() & BF_Kinematic) + { + result->setKinematic(true); + } + + + + if (result->getFlags() & BF_Moving ) + { + result->enableGravity(result->getFlags() & BF_Gravity); + } + + //---------------------------------------------------------------- + // + // Special Parameters + // + + //- look for optimization attribute : + result->checkForOptimization(); + + + + + //---------------------------------------------------------------- + // + // store mesh meta info in the first main mesh + // + NxShape *shape = result->getShapeByIndex(); + if (shape) + { + pSubMeshInfo *sInfo = new pSubMeshInfo(); + sInfo->entID = referenceObject->GetID(); + sInfo->refObject = (CKBeObject*)referenceObject; + shape->userData = (void*)sInfo; + result->setMainShape(shape); + shape->setName(referenceObject->GetName()); + + pMaterial bMaterial; + bool hasMaterial = pFactory::Instance()->findSettings(bMaterial,referenceObject); + if (!hasMaterial) + { + if (world->getDefaultMaterial()) + { + int z = (int)world->getDefaultMaterial()->userData; + shape->setMaterial(world->getDefaultMaterial()->getMaterialIndex()); + //pFactory::Instance()->copyTo(bMaterial,world->getDefaultMaterial()); + } + }else{ + + NxMaterialDesc nxMatDescr; + pFactory::Instance()->copyTo(nxMatDescr,bMaterial); + NxMaterial *nxMaterial = world->getScene()->createMaterial(nxMatDescr); + if (nxMaterial) + { + shape->setMaterial(nxMaterial->getMaterialIndex()); + } + } + } + + result->enableCollision( (result->getFlags() & BF_Collision), referenceObject ); + + + //- handle collisions setup + if (oDescr->version == pObjectDescr::E_OD_VERSION::OD_DECR_V1) + result->updateCollisionSettings(*oDescr,referenceObject); + + + + + + xLogger::xLog(ELOGINFO,E_LI_MANAGER,"Rigid body creation successful : %s",referenceObject->GetName()); + + //---------------------------------------------------------------- + // + // Parse hierarchy + // + if (!oDescr->hirarchy) + return result; + + CK3dEntity* subEntity = NULL; + while (subEntity= referenceObject->HierarchyParser(subEntity) ) + { + if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) + { + pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + if (subDescr->flags & BF_SubShape) + { + + ////////////////////////////////////////////////////////////////////////// + // + // Regular Mesh : + // + + if (subDescr->hullType != HT_Cloth) + { + result->addSubShape(NULL,*oDescr,subEntity); + } + + ////////////////////////////////////////////////////////////////////////// + // + // Cloth Mesh : + // + if (subDescr->hullType == HT_Cloth) + { + //pClothDesc *cloth = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + } + } + } + + if (oDescr->hirarchy) + { + + + if (oDescr->newDensity!=0.0f || oDescr->totalMass!=0.0f ) + { + result->updateMassFromShapes(oDescr->newDensity,oDescr->totalMass); + } + } + + + return result; + + } + nothing: + + + + return result; +} +pRigidBody*pFactory::createBody(CK3dEntity *referenceObject,CK3dEntity *worldReferenceObject) +{ + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + // + // Pseudo code : + // + // 1. check the passed world, otherwise use+create the physic managers default world : + // 1. + ////////////////////////////////////////////////////////////////////////// + + if (!referenceObject) + { + return NULL; + } + + pWorld *world=GetPMan()->getWorld(worldReferenceObject,referenceObject); + if (world) + { + int p = 0; + } + + if (!world) + { + return NULL; + } + + pRigidBody *result = new pRigidBody(referenceObject,world); + + return result; + +} + + + + + + +pRigidBody*pFactory::createBody(CK3dEntity *referenceObject,pObjectDescr description,CK3dEntity *worldReferenceObject/* =NULL */) +{ + using namespace vtTools::BehaviorTools; + using namespace vtTools; + using namespace vtTools::AttributeTools; + + pRigidBody *result = NULL; + + if (!referenceObject) + return result; + + pWorld *world=getManager()->getWorld(worldReferenceObject,referenceObject); + if (!world) + { + return result; + } + + if (referenceObject->HasAttribute(GetPMan()->GetPAttribute())) + { + referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); + } + referenceObject->SetAttribute(GetPMan()->GetPAttribute()); + + + int htype = description.hullType; + int flags = description.flags; + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HIRARCHY,&description.hirarchy); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HULLTYPE,&htype); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_BODY_FLAGS,&flags); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_DENSITY,&description.density); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_NEW_DENSITY,&description.newDensity); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_TOTAL_MASS,&description.totalMass); + SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_MASS_OFFSET,&description.massOffset); + + CK_ID wid = world->getReference()->GetID(); + AttributeTools::SetAttributeValue(referenceObject,GetPMan()->GetPAttribute(),E_PPS_WORLD,&wid); + + result = pFactory::Instance()->createRigidBodyFull(referenceObject,world->getReference()); + if (result) + { + result->translateLocalShapePosition(description.shapeOffset); + result->setCMassOffsetLocalPosition(description.massOffset); + } + + if ( ! (description.flags & BF_AddAttributes) ) + { + referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); + } + + return result; + + +} + +CK3dEntity *pFactory::getMostTopParent(CK3dEntity*ent) +{ + + if (!ent) + { + return NULL; + } + + CK3dEntity *result = ent->GetParent(); + if (result) + { + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + //if ( (!result->HasAttribute(GetPMan()->GetPAttribute())) || !(result->HasAttribute(attTypePBSetup))) + if ( (result->HasAttribute(GetPMan()->GetPAttribute())) || (result->HasAttribute(attTypePBSetup))) + { + return ent; + } + if (result->GetParent()) + { + return getMostTopParent(result); + } + else + { + return result; + } + }else + { + return ent; + } +} + + + + +/* +templateclass MODULE_API xImplementationObject2 +{ +public: + +//xLinkedObjectStorage() : mInternalId(-1) , mClassId(-1) {}; +typedef void* xImplementationObject2::*StoragePtr; +xImplementationObject2(){} +xImplementationObject2(StoragePtr storage) +{ + +} +void setStorage(StoragePtr* stPtr) +{ +mStorage = stPtr; +} +T getImpl() { return mObject; } + + +protected: +private: +T mObject; +StoragePtr mStorage; +}; + + + +class ATest : public xImplementationObject2 +{ + +public: + +ATest(); +}; + +NxActor *actor = NULL; + +ATest::ATest() : xImplementationObject2(actor->userData) +{ + + +// setStorage(actor->userData); + +} +*/ \ No newline at end of file diff --git a/usr/Src/old/Core/pFactory/pFactoryClothes.cpp b/usr/Src/old/Core/pFactory/pFactoryClothes.cpp new file mode 100644 index 0000000..797c436 --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryClothes.cpp @@ -0,0 +1,270 @@ +#include +#include "vtPhysXAll.h" + +#include "cooking.h" +#include "Stream.h" + +#include "pConfig.h" + + +void pFactory::copyTo(pDeformableSettings &dst,CKParameter*par) +{ + + if (!par) + { + return; + } + + using namespace vtTools::ParameterTools; + dst.ImpulsThresold = GetValueFromParameterStruct(par,0); + dst.PenetrationDepth = GetValueFromParameterStruct(par,1); + dst.MaxDeform = GetValueFromParameterStruct(par,2); + +} + +pCloth* pFactory::createCloth(CK3dEntity *srcReference,pClothDesc descr) +{ + + +#ifdef DONLGE + if(!GetPMan()->DongleHasAdvancedVersion) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Cannot create cloth : no license !"); + return NULL; + } +#endif + + if (!srcReference) + { + return NULL; + } + + if (!srcReference->GetCurrentMesh()) + { + return NULL; + } + + if (!descr.isValid()) + { + return NULL; + } + + CK3dEntity*worldReference = (CK3dEntity*)GetPMan()->m_Context->GetObject(descr.worldReference); + + if (!worldReference) + { + if (GetPMan()->getDefaultWorld()) + { + worldReference = GetPMan()->getDefaultWorld()->getReference(); + }else + return NULL; + } + + pWorld*world = GetPMan()->getWorld(worldReference->GetID()); + if (!world) + { + return NULL; + + } + + + pRigidBody *body = GetPMan()->getBody(srcReference); +/* if (!body) + { + return NULL; + } +*/ + + NxClothMeshDesc meshDesc; + + // if we want tearing we must tell the cooker + // this way it will generate some space for particles that will be generated during tearing + if (descr.flags & PCF_Tearable) + meshDesc.flags |= NX_CLOTH_MESH_TEARABLE; + + pCloth *result = new pCloth(); + + result->generateMeshDesc(descr,&meshDesc,srcReference->GetCurrentMesh()); + int mValid = meshDesc.isValid(); + + if (!result->cookMesh(&meshDesc)) + { + delete result; + return NULL; + } + + result->releaseMeshDescBuffers(&meshDesc); + result->allocateClothReceiveBuffers(meshDesc.numVertices, meshDesc.numTriangles); + + NxClothDesc cDescr; + copyToClothDescr(&cDescr,descr); + cDescr.clothMesh = result->getClothMesh(); + cDescr.meshData = *result->getReceiveBuffers(); + + VxMatrix v_matrix ; + VxVector position,scale; + VxQuaternion quat; + + + + v_matrix = srcReference->GetWorldMatrix(); + Vx3DDecomposeMatrix(v_matrix,quat,position,scale); + + cDescr.globalPose.t = getFrom(position); + cDescr.globalPose.M = getFrom(quat); + + + + + NxCloth *cloth = world->getScene()->createCloth(cDescr); + if (cloth) + { + result->setCloth(cloth); + result->setEntityID(srcReference->GetID()); + result->setWorld(GetPMan()->getDefaultWorld()); + cloth->userData = result; + + if (meshDesc.points) + { +// delete []meshDesc.points; +// delete []meshDesc.triangles; + } + + + + if (descr.flags & PCF_AttachToParentMainShape ) + { + if (srcReference->GetParent()) + { + CK3dEntity *bodyReference = getMostTopParent(srcReference); + if (bodyReference) + { + pRigidBody *body = GetPMan()->getBody(bodyReference); + if (body) + { + result->attachToShape((CKBeObject*)bodyReference,descr.attachmentFlags); + } + } + } + } + + if (descr.flags & PCF_AttachToCollidingShapes) + { + result->attachToCollidingShapes(descr.attachmentFlags); + } + + if (descr.flags & PCF_AttachToCore) + { +/* + + NxBodyDesc coreBodyDesc; + coreBodyDesc.linearDamping = 0.2f; + coreBodyDesc.angularDamping = 0.2f; + + NxActorDesc coreActorDesc; + coreActorDesc.density = 0.1f; + coreActorDesc.body = &coreBodyDesc; + + coreActorDesc.shapes.pushBack(new NxBoxShapeDesc()); + + NxActor *coreActor = world->getScene()->createActor(coreActorDesc); + coreActor->userData =NULL; + + + NxReal impulseThreshold = 50.0f; + NxReal penetrationDepth = 0.5f; + NxReal maxDeformationDistance = 0.5f; + + cloth->attachToCore(coreActor, impulseThreshold, penetrationDepth, maxDeformationDistance); +*/ +// result->attachToCollidingShapes(descr.attachmentFlags); + } + + return result; + } + + if (meshDesc.points) + { +// delete []meshDesc.points; +// delete []meshDesc.triangles; + } + + return result; + +} +pClothDesc* pFactory::createClothDescrFromParameter(CKParameter *par) +{ + + if (!par) + return NULL; + + pClothDesc *descr = new pClothDesc(); + + using namespace vtTools::ParameterTools; + + descr->density = GetValueFromParameterStruct(par,E_CS_DENSITY,false); + descr->thickness = GetValueFromParameterStruct(par,E_CS_THICKNESS,false); + descr->bendingStiffness = GetValueFromParameterStruct(par,E_CS_BENDING_STIFFNESS,false); + descr->stretchingStiffness = GetValueFromParameterStruct(par,E_CS_STRETCHING_STIFFNESS,false); + descr->dampingCoefficient = GetValueFromParameterStruct(par,E_CS_DAMPING_COEFFICIENT,false); + descr->friction = GetValueFromParameterStruct(par,E_CS_FRICTION,false); + + descr->pressure = GetValueFromParameterStruct(par,E_CS_PRESSURE,false); + descr->tearFactor = GetValueFromParameterStruct(par,E_CS_TEAR_FACTOR,false); + descr->collisionResponseCoefficient = GetValueFromParameterStruct(par,E_CS_COLLISIONRESPONSE_COEFFICIENT,false); + + descr->attachmentResponseCoefficient = GetValueFromParameterStruct(par,E_CS_ATTACHMENTRESPONSE_COEFFICIENT,false); + descr->attachmentTearFactor = GetValueFromParameterStruct(par,E_CS_ATTACHMENT_TEAR_FACTOR,false); + descr->toFluidResponseCoefficient = GetValueFromParameterStruct(par,E_CS_TO_FLUID_RESPONSE_COEFFICIENT,false); + + descr->fromFluidResponseCoefficient = GetValueFromParameterStruct(par,E_CS_FROM_FLUIDRESPONSE_COEFFICIENT,false); + descr->minAdhereVelocity = GetValueFromParameterStruct(par,E_CS_MIN_ADHERE_VELOCITY,false); + descr->solverIterations = GetValueFromParameterStruct(par,E_CS_SOLVER_ITERATIONS,false); + + descr->externalAcceleration = GetValueFromParameterStruct(par,E_CS_EXTERN_ALACCELERATION,false); + descr->windAcceleration = GetValueFromParameterStruct(par,E_CS_WIND_ACCELERATION,false); + descr->wakeUpCounter = GetValueFromParameterStruct(par,E_CS_WAKE_UP_COUNTER,false); + + descr->sleepLinearVelocity = GetValueFromParameterStruct(par,E_CS_SLEEP_LINEAR_VELOCITY,false); + descr->collisionGroup = GetValueFromParameterStruct(par,E_CS_COLLISIONG_ROUP,false); + + descr->validBounds = GetValueFromParameterStruct(par,E_CS_VALID_BOUNDS,false); + descr->relativeGridSpacing = GetValueFromParameterStruct(par,E_CS_RELATIVE_GRID_SPACING,false); + descr->flags = GetValueFromParameterStruct(par,E_CS_FLAGS,false); + descr->tearVertexColor = GetValueFromParameterStruct(par,E_CS_TEAR_VERTEX_COLOR,false); + + descr->worldReference = GetValueFromParameterStruct(par,E_CS_WORLD_REFERENCE,false); + + return descr; + +} + +void pFactory::copyToClothDescr(NxClothDesc* dst,pClothDesc src ) +{ + + dst->density = src.density ; + dst->thickness = src.thickness ; + dst->bendingStiffness = src.bendingStiffness; + dst->stretchingStiffness = src.stretchingStiffness; + dst->dampingCoefficient = src.dampingCoefficient; + + dst->friction = src.friction; + dst->pressure = src.pressure; + dst->tearFactor = src.tearFactor ; + dst->collisionResponseCoefficient = src.collisionResponseCoefficient ; + dst->attachmentResponseCoefficient = src.attachmentResponseCoefficient ; + dst->attachmentTearFactor = src.attachmentTearFactor ; + dst->toFluidResponseCoefficient = src.toFluidResponseCoefficient ; + dst->fromFluidResponseCoefficient= src.fromFluidResponseCoefficient ; + dst->minAdhereVelocity = src.minAdhereVelocity ; + dst->solverIterations = src.solverIterations ; + dst->externalAcceleration = getFrom(src.externalAcceleration) ; + dst->windAcceleration = getFrom(src.windAcceleration); + dst->wakeUpCounter = src.wakeUpCounter ; + dst->sleepLinearVelocity = src.sleepLinearVelocity ; + dst->collisionGroup = src.collisionGroup; + dst->validBounds.set(getFrom(src.validBounds.Min) , getFrom(src.validBounds.Max)); + dst->relativeGridSpacing = src.relativeGridSpacing; + dst->flags =src.flags; + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pFactory/pFactoryFluids.c__ b/usr/Src/old/Core/pFactory/pFactoryFluids.c__ new file mode 100644 index 0000000..4817ae1 --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryFluids.c__ @@ -0,0 +1,336 @@ +#include +#include "pCommon.h" +#include "pFactory.h" + +#include "CK3dPointCloud.h" + +int RenderParticles_P(CKRenderContext *dev,CKRenderObject *obj,void *arg); + +void pFactory::copyToEmitterDesc(NxFluidEmitterDesc&dst,pFluidEmitterDesc src) +{ + + + + + dst.dimensionX = src.dimensionX; + dst.dimensionY = src.dimensionY; + dst.flags = (NxFluidEmitterFlag)src.flags; + dst.fluidVelocityMagnitude = src.fluidVelocityMagnitude; + dst.maxParticles = src.maxParticles; + dst.particleLifetime = src.particleLifetime; + dst.randomAngle = src.randomAngle; + dst.randomPos = getFrom( src.randomPos); + dst.rate = src.rate; + dst.type = (NxEmitterType)src.type; + dst.repulsionCoefficient = src.repulsionCoefficient; + if (src.frameShape) + { + pWorld *w = GetPMan()->getWorldByShapeReference(src.frameShape); + if (w) + { + NxShape *shape = w->getShapeByEntityID(src.frameShape->GetID()); + if (shape) + { + dst.frameShape = shape; + }else + { + dst.frameShape = NULL; + } + } + } + + + + +} + +void pFactory::initParticles(pFluidDesc &desc,NxParticleData&dst,CK3dEntity*srcReference,CK3dEntity*dstEntity) +{ + + + CKMesh *mesh = dstEntity->GetCurrentMesh(); + if (!mesh) + return; + + ////////////////////////////////////////////////////////////////////////// + mesh->SetVertexCount(desc.maxParticles); + CKDWORD stride; + void* ptr = mesh->GetPositionsPtr(&stride); + XPtrStrided vpos(ptr,stride); + + VxVector pos(0,0,0); + + for (int i = 0 ; i < mesh->GetVertexCount();i++ ) + { + pos.x +=(float)(i*0.0001f); + mesh->SetVertexPosition(i,&pos); + } + ////////////////////////////////////////////////////////////////////////// + + mesh->VertexMove(); + + char* bufferPos = reinterpret_cast(dst.bufferPos); + char* bufferVel = reinterpret_cast(dst.bufferVel); + char* bufferLife = reinterpret_cast(dst.bufferLife); + + +// if(bufferPos == NULL && bufferVel == NULL && bufferLife == NULL) +// return; +/* + NxVec3 aabbDim; + aabb.getExtents(aabbDim); + aabbDim *= 2.0f; +*/ + (*dst.numParticlesPtr) = 0; + + for (int j = 0 ; j < desc.maxParticles ; j ++ ) + { + VxVector mPos; + mesh->GetVertexPosition(j,&mPos); + + srcReference->Transform(&mPos,&mPos); + + NxVec3 p(mPos.x,mPos.y,mPos.z); + + + NxVec3& position = *reinterpret_cast(bufferPos); + position = p; + int stride = dst.bufferPosByteStride; + bufferPos += dst.bufferPosByteStride; + + + NxVec3& velocity = *reinterpret_cast(bufferVel); + NxVec3 vel; + velocity = vel; + bufferVel += dst.bufferVelByteStride; + + if (bufferLife) + { + NxReal& life = *reinterpret_cast(bufferLife); + life = 0.0f; + bufferLife += dst.bufferLifeByteStride; + } + + (*dst.numParticlesPtr)++; + } + +} + +pFluid* pFactory::createFluid(CK3dEntity *srcReference ,pFluidDesc desc) +{ + + //Create a set of initial particles + + pParticle* initParticle = new pParticle[desc.maxParticles]; + unsigned initParticlesNum = 0; + + //Setup structure to pass initial particles. + NxParticleData initParticleData; + initParticleData.numParticlesPtr = &initParticlesNum; + initParticleData.bufferPos = &initParticle[0].position.x; + initParticleData.bufferPosByteStride = sizeof(pParticle); + initParticleData.bufferVel = &initParticle[0].velocity.x; + initParticleData.bufferVelByteStride = sizeof(pParticle); + + CK3dEntity *particleEntity = createFluidEntity(); + + CKMesh *mesh = particleEntity->GetCurrentMesh(); + mesh->SetVertexCount(desc.maxParticles); + + VxVector pos; + + srcReference->GetPosition(&pos); + particleEntity->SetPosition(&pos); + + CK3dPointCloud *cloud = createPointCloud(desc); + if (cloud) + { + cloud->SetReferentialPosition(pos); + } + + //initParticles(desc,initParticleData,srcReference,particleEntity); + + + //Setup fluid descriptor + NxFluidDesc fluidDesc; + fluidDesc.setToDefault(); + + copyToFluidDescr(fluidDesc,desc); + + /*fluidDesc.maxParticles = desc.maxParticles; + fluidDesc.kernelRadiusMultiplier = 2.0f; + fluidDesc.restParticlesPerMeter = 10.0f; + fluidDesc.motionLimitMultiplier = 3.0f; + fluidDesc.packetSizeMultiplier = 8; + fluidDesc.collisionDistanceMultiplier = 0.1; + fluidDesc.stiffness = 50.0f; + fluidDesc.viscosity = 40.0f; + fluidDesc.restDensity = 1000.0f; + fluidDesc.damping = 0.0f; + fluidDesc.restitutionForStaticShapes = 0.2f; + fluidDesc.dynamicFrictionForStaticShapes= 0.05f; + fluidDesc.simulationMethod = NX_F_SPH;*/ + fluidDesc.flags &= ~NX_FF_HARDWARE; + + + //Add initial particles to fluid creation. + fluidDesc.initialParticleData = initParticleData; + + + //Create user fluid. + //- create NxFluid in NxScene + //- setup the buffers to read from data from the SDK + //- set NxFluid::userData field to MyFluid instance + bool trackUserData = false; + bool provideCollisionNormals = false; + + pFluid* fluid = new pFluid(fluidDesc, trackUserData, provideCollisionNormals, getFrom(NxVec3(0.4f,0.5f,0.9f)), 0.03f); + + + if (fluidDesc.flags & NX_FF_HARDWARE) + { + int op = 2; + } + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + CK3dEntity*worldReference = (CK3dEntity*)GetPMan()->m_Context->GetObject(desc.worldReference); + + if (!worldReference) + { + if (GetPMan()->getDefaultWorld()) + { + worldReference = GetPMan()->getDefaultWorld()->getReference(); + }else + return NULL; + } + + pWorld*world = GetPMan()->getWorld(worldReference->GetID()); + if (!world) + { + return NULL; + + } + + int s = fluidDesc.isValid(); + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + NxFluid* xfluid = world->getScene()->createFluid(fluidDesc); + if (xfluid) + { + xfluid->userData = fluid; + fluid->setFluid( xfluid ); + fluid->setEntityID( particleEntity->GetID() ); + + particleEntity->SetRenderCallBack(RenderParticles_P,fluid); + + return fluid; + } + + return NULL; +} + +void pFactory::copyToFluidDescr(NxFluidDesc &dst , pFluidDesc src ) +{ + + dst.attractionForDynamicShapes = src.attractionForDynamicShapes; + dst.attractionForStaticShapes = src.attractionForStaticShapes; + dst.collisionDistanceMultiplier = src.collisionDistanceMultiplier; + dst.collisionGroup = src.collisionGroup; + dst.collisionMethod = src.collisionMethod; + dst.collisionResponseCoefficient =src.collisionResponseCoefficient; + dst.damping = src.damping; + dst.dynamicFrictionForDynamicShapes = src.dynamicFrictionForDynamicShapes; + dst.dynamicFrictionForStaticShapes = src.dynamicFrictionForStaticShapes; + dst.externalAcceleration = getFrom(src.externalAcceleration); + dst.fadeInTime = src.fadeInTime; + dst.kernelRadiusMultiplier = src.kernelRadiusMultiplier; + dst.packetSizeMultiplier = src.packetSizeMultiplier; + dst.maxParticles = src.maxParticles; + dst.motionLimitMultiplier = src.motionLimitMultiplier; + dst.numReserveParticles = src.numReserveParticles; + dst.packetSizeMultiplier = src.packetSizeMultiplier; + dst.restitutionForDynamicShapes = src.restitutionForDynamicShapes; + dst.restitutionForStaticShapes =src.restitutionForStaticShapes; + dst.restParticlesPerMeter = src.restParticlesPerMeter; + dst.restDensity = src.restDensity; + dst.simulationMethod = src.simulationMethod; + dst.staticFrictionForDynamicShapes = src.staticFrictionForDynamicShapes; + dst.staticFrictionForStaticShapes = src.staticFrictionForStaticShapes; + dst.stiffness = src.stiffness; + dst.surfaceTension =src.surfaceTension; + dst.viscosity =src.viscosity; + dst.flags = src.flags; + +} + + + + + +CK3dEntity*pFactory::createFluidEntity() +{ + + CK3dEntity *result = NULL; + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; + + XString name; + name << "_Decal"; + + CK3dEntity* decal = (CK3dEntity*)ctx()->CreateObject(CKCID_3DOBJECT,name.Str(),creaoptions); + + name << "Mesh"; + CKMesh* decalmesh = (CKMesh*)ctx()->CreateObject(CKCID_MESH,name.Str(),creaoptions); + if (!decalmesh) return NULL; + + // Add to the level + CKLevel* level = ctx()->GetCurrentLevel(); + CKScene* scene = ctx()->GetCurrentScene(); + + level->AddObject(decal); + level->AddObject(decalmesh); + + // And to the current scene if any + if (scene != level->GetLevelScene()) { + scene->AddObject(decal); + scene->AddObject(decalmesh); + } + + // 3DEntity + decal->SetWorldMatrix(VxMatrix::Identity()); + decal->SetCurrentMesh(decalmesh); + + return decal; + +} + + +CK3dPointCloud*pFactory::createPointCloud(const pFluidDesc&descr) +{ + + CK3dPointCloud*result = NULL; + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; + + XString name; + name << "_FluidCloud"; + + result = (CK3dPointCloud*)ctx()->CreateObject(CKCID_3DPOINTCLOUD,name.Str(),creaoptions); + // Add to the level + CKLevel* level = ctx()->GetCurrentLevel(); + CKScene* scene = ctx()->GetCurrentScene(); + + level->AddObject((CKObject*)result); + + // And to the current scene if any + if (scene != level->GetLevelScene()) { + scene->AddObject((CKSceneObject*)result); + } + + // 3DEntity + result->SetWorldMatrix(VxMatrix::Identity()); + //decal->SetCurrentMesh(decalmesh); + + return result; + + + + +} diff --git a/usr/Src/old/Core/pFactory/pFactoryFluids.cpp b/usr/Src/old/Core/pFactory/pFactoryFluids.cpp new file mode 100644 index 0000000..93a9b23 --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryFluids.cpp @@ -0,0 +1,337 @@ +#include +#include "vtPhysXAll.h" + +#include "CK3dPointCloud.h" + +#ifdef HAS_FLUIDS + +int RenderParticles_P(CKRenderContext *dev,CKRenderObject *obj,void *arg); + +void pFactory::copyToEmitterDesc(NxFluidEmitterDesc&dst,pFluidEmitterDesc src) +{ + + + dst.dimensionX = src.dimensionX; + dst.dimensionY = src.dimensionY; + dst.flags = (NxFluidEmitterFlag)src.flags; + dst.fluidVelocityMagnitude = src.fluidVelocityMagnitude; + dst.maxParticles = src.maxParticles; + dst.particleLifetime = src.particleLifetime; + dst.randomAngle = src.randomAngle; + dst.randomPos = getFrom( src.randomPos); + dst.rate = src.rate; + dst.type = (NxEmitterType)src.type; + dst.repulsionCoefficient = src.repulsionCoefficient; + if (src.frameShape) + { + pWorld *w = GetPMan()->getWorldByShapeReference(src.frameShape); + if (w) + { + NxShape *shape = w->getShapeByEntityID(src.frameShape->GetID()); + if (shape) + { + dst.frameShape = shape; + }else + { + dst.frameShape = NULL; + } + } + } + + + + +} + +void pFactory::initParticles(pFluidDesc &desc,NxParticleData&dst,CK3dEntity*srcReference,CK3dEntity*dstEntity) +{ + + + CKMesh *mesh = dstEntity->GetCurrentMesh(); + if (!mesh) + return; + + ////////////////////////////////////////////////////////////////////////// + mesh->SetVertexCount(desc.maxParticles); + CKDWORD stride; + void* ptr = mesh->GetPositionsPtr(&stride); + XPtrStrided vpos(ptr,stride); + + VxVector pos(0,0,0); + + for (int i = 0 ; i < mesh->GetVertexCount();i++ ) + { + pos.x +=(float)(i*0.0001f); + mesh->SetVertexPosition(i,&pos); + } + ////////////////////////////////////////////////////////////////////////// + + mesh->VertexMove(); + + char* bufferPos = reinterpret_cast(dst.bufferPos); + char* bufferVel = reinterpret_cast(dst.bufferVel); + char* bufferLife = reinterpret_cast(dst.bufferLife); + + +// if(bufferPos == NULL && bufferVel == NULL && bufferLife == NULL) +// return; +/* + NxVec3 aabbDim; + aabb.getExtents(aabbDim); + aabbDim *= 2.0f; +*/ + (*dst.numParticlesPtr) = 0; + + for (int j = 0 ; j < desc.maxParticles ; j ++ ) + { + VxVector mPos; + mesh->GetVertexPosition(j,&mPos); + + srcReference->Transform(&mPos,&mPos); + + NxVec3 p(mPos.x,mPos.y,mPos.z); + + + NxVec3& position = *reinterpret_cast(bufferPos); + position = p; + int stride = dst.bufferPosByteStride; + bufferPos += dst.bufferPosByteStride; + + + NxVec3& velocity = *reinterpret_cast(bufferVel); + NxVec3 vel; + velocity = vel; + bufferVel += dst.bufferVelByteStride; + + if (bufferLife) + { + NxReal& life = *reinterpret_cast(bufferLife); + life = 0.0f; + bufferLife += dst.bufferLifeByteStride; + } + + (*dst.numParticlesPtr)++; + } + +} + +pFluid* pFactory::createFluid(CK3dEntity *srcReference ,pFluidDesc desc) +{ + + //Create a set of initial particles + + pParticle* initParticle = new pParticle[desc.maxParticles]; + unsigned initParticlesNum = 0; + + //Setup structure to pass initial particles. + NxParticleData initParticleData; + initParticleData.numParticlesPtr = &initParticlesNum; + initParticleData.bufferPos = &initParticle[0].position.x; + initParticleData.bufferPosByteStride = sizeof(pParticle); + initParticleData.bufferVel = &initParticle[0].velocity.x; + initParticleData.bufferVelByteStride = sizeof(pParticle); + + CK3dEntity *particleEntity = createFluidEntity(); + + CKMesh *mesh = particleEntity->GetCurrentMesh(); + mesh->SetVertexCount(desc.maxParticles); + + VxVector pos; + + srcReference->GetPosition(&pos); + particleEntity->SetPosition(&pos); + + CK3dPointCloud *cloud = createPointCloud(desc); + if (cloud) + { + cloud->SetReferentialPosition(pos); + } + + //initParticles(desc,initParticleData,srcReference,particleEntity); + + + //Setup fluid descriptor + NxFluidDesc fluidDesc; + fluidDesc.setToDefault(); + + copyToFluidDescr(fluidDesc,desc); + + /*fluidDesc.maxParticles = desc.maxParticles; + fluidDesc.kernelRadiusMultiplier = 2.0f; + fluidDesc.restParticlesPerMeter = 10.0f; + fluidDesc.motionLimitMultiplier = 3.0f; + fluidDesc.packetSizeMultiplier = 8; + fluidDesc.collisionDistanceMultiplier = 0.1; + fluidDesc.stiffness = 50.0f; + fluidDesc.viscosity = 40.0f; + fluidDesc.restDensity = 1000.0f; + fluidDesc.damping = 0.0f; + fluidDesc.restitutionForStaticShapes = 0.2f; + fluidDesc.dynamicFrictionForStaticShapes= 0.05f; + fluidDesc.simulationMethod = NX_F_SPH;*/ + fluidDesc.flags &= ~NX_FF_HARDWARE; + + + //Add initial particles to fluid creation. + fluidDesc.initialParticleData = initParticleData; + + + //Create user fluid. + //- create NxFluid in NxScene + //- setup the buffers to read from data from the SDK + //- set NxFluid::userData field to MyFluid instance + bool trackUserData = false; + bool provideCollisionNormals = false; + + pFluid* fluid = new pFluid(fluidDesc, trackUserData, provideCollisionNormals, getFrom(NxVec3(0.4f,0.5f,0.9f)), 0.03f); + + + if (fluidDesc.flags & NX_FF_HARDWARE) + { + int op = 2; + } + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + CK3dEntity*worldReference = (CK3dEntity*)GetPMan()->m_Context->GetObject(desc.worldReference); + + if (!worldReference) + { + if (GetPMan()->getDefaultWorld()) + { + worldReference = GetPMan()->getDefaultWorld()->getReference(); + }else + return NULL; + } + + pWorld*world = GetPMan()->getWorld(worldReference->GetID()); + if (!world) + { + return NULL; + + } + + int s = fluidDesc.isValid(); + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + NxFluid* xfluid = world->getScene()->createFluid(fluidDesc); + if (xfluid) + { + xfluid->userData = fluid; + fluid->setFluid( xfluid ); + fluid->setEntityID( particleEntity->GetID() ); + + particleEntity->SetRenderCallBack(RenderParticles_P,fluid); + + return fluid; + } + + return NULL; +} + +void pFactory::copyToFluidDescr(NxFluidDesc &dst , pFluidDesc src ) +{ + + dst.attractionForDynamicShapes = src.attractionForDynamicShapes; + dst.attractionForStaticShapes = src.attractionForStaticShapes; + dst.collisionDistanceMultiplier = src.collisionDistanceMultiplier; + dst.collisionGroup = src.collisionGroup; + dst.collisionMethod = src.collisionMethod; + dst.collisionResponseCoefficient =src.collisionResponseCoefficient; + dst.damping = src.damping; + dst.dynamicFrictionForDynamicShapes = src.dynamicFrictionForDynamicShapes; + dst.dynamicFrictionForStaticShapes = src.dynamicFrictionForStaticShapes; + dst.externalAcceleration = getFrom(src.externalAcceleration); + dst.fadeInTime = src.fadeInTime; + dst.kernelRadiusMultiplier = src.kernelRadiusMultiplier; + dst.packetSizeMultiplier = src.packetSizeMultiplier; + dst.maxParticles = src.maxParticles; + dst.motionLimitMultiplier = src.motionLimitMultiplier; + dst.numReserveParticles = src.numReserveParticles; + dst.packetSizeMultiplier = src.packetSizeMultiplier; + dst.restitutionForDynamicShapes = src.restitutionForDynamicShapes; + dst.restitutionForStaticShapes =src.restitutionForStaticShapes; + dst.restParticlesPerMeter = src.restParticlesPerMeter; + dst.restDensity = src.restDensity; + dst.simulationMethod = src.simulationMethod; + dst.staticFrictionForDynamicShapes = src.staticFrictionForDynamicShapes; + dst.staticFrictionForStaticShapes = src.staticFrictionForStaticShapes; + dst.stiffness = src.stiffness; + dst.surfaceTension =src.surfaceTension; + dst.viscosity =src.viscosity; + dst.flags = src.flags; + +} + + + + + +CK3dEntity*pFactory::createFluidEntity() +{ + + CK3dEntity *result = NULL; + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; + + XString name; + name << "_Decal"; + + CK3dEntity* decal = (CK3dEntity*)ctx()->CreateObject(CKCID_3DOBJECT,name.Str(),creaoptions); + + name << "Mesh"; + CKMesh* decalmesh = (CKMesh*)ctx()->CreateObject(CKCID_MESH,name.Str(),creaoptions); + if (!decalmesh) return NULL; + + // Add to the level + CKLevel* level = ctx()->GetCurrentLevel(); + CKScene* scene = ctx()->GetCurrentScene(); + + level->AddObject(decal); + level->AddObject(decalmesh); + + // And to the current scene if any + if (scene != level->GetLevelScene()) { + scene->AddObject(decal); + scene->AddObject(decalmesh); + } + + // 3DEntity + decal->SetWorldMatrix(VxMatrix::Identity()); + decal->SetCurrentMesh(decalmesh); + + return decal; + +} + + +CK3dPointCloud*pFactory::createPointCloud(const pFluidDesc&descr) +{ + + CK3dPointCloud*result = NULL; + CK_OBJECTCREATION_OPTIONS creaoptions = CK_OBJECTCREATION_DYNAMIC; + + XString name; + name << "_FluidCloud"; + + result = (CK3dPointCloud*)ctx()->CreateObject(CKCID_3DPOINTCLOUD,name.Str(),creaoptions); + // Add to the level + CKLevel* level = ctx()->GetCurrentLevel(); + CKScene* scene = ctx()->GetCurrentScene(); + + level->AddObject((CKObject*)result); + + // And to the current scene if any + if (scene != level->GetLevelScene()) { + scene->AddObject((CKSceneObject*)result); + } + + // 3DEntity + result->SetWorldMatrix(VxMatrix::Identity()); + //decal->SetCurrentMesh(decalmesh); + + return result; + + + + +} + +#endif // HAS_FLUIDS \ No newline at end of file diff --git a/usr/Src/old/Core/pFactory/pFactoryJoint.cpp b/usr/Src/old/Core/pFactory/pFactoryJoint.cpp new file mode 100644 index 0000000..d58c2cc --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryJoint.cpp @@ -0,0 +1,1440 @@ +#include +#include "vtPhysXAll.h" + +static pFactory* pFact = NULL; + +int pFactory::cloneLimitPlanes(pJoint *src,pJoint *dst,CK3dEntity *srcReference,CK3dEntity *dstReference) +{ + //---------------------------------------------------------------- + // + // sanity checks + // + #ifdef _DEBUG + assert(src); + assert(dst); + assert(dstReference); + assert(srcReference); + #endif // _DEBUG + + NxJoint *j = src->getJoint(); + if (!j) + return 0; + + + int numLimitPlanes = src->getNbLimitPlanes(); + if (!numLimitPlanes) + return -1; + + NxVec3 *planeNormal = new NxVec3[numLimitPlanes]; + NxReal *planeD = new NxReal[numLimitPlanes]; + NxReal *restitution = new NxReal[numLimitPlanes]; + + NxVec3 planeLimitPt; + bool onActor2 = j->getLimitPoint( planeLimitPt ); + NxVec3 *worldLimitPt = new NxVec3[numLimitPlanes]; + + //---------------------------------------------------------------- + // + // copy to buffer + // + j->resetLimitPlaneIterator(); + + for(int iter=0 ; iter < numLimitPlanes ; iter++ ) + { + j->getNextLimitPlane( planeNormal[iter], planeD[iter], &restitution[iter] ); + } + + + + //---------------------------------------------------------------- + // + // create limitPoints + // + + dst->setLimitPoint(getFrom(planeLimitPt),onActor2); + + + for(int iter=0 ; iter < numLimitPlanes ; iter++ ) + { + + if ( ( fabs(planeNormal[iter].z) > fabs(planeNormal[iter].x) ) && + ( fabs(planeNormal[iter].z) > fabs(planeNormal[iter].y) ) ) + { + worldLimitPt[iter].x = planeLimitPt.x; + worldLimitPt[iter].y = planeLimitPt.y; + worldLimitPt[iter].z = -planeD[iter] / planeNormal[iter].z; + } + // k, that didn't work - try x,z = 0 + else if ( ( fabs(planeNormal[iter].y) > fabs(planeNormal[iter].x) ) && + ( fabs(planeNormal[iter].y) > fabs(planeNormal[iter].z) ) ) + { + worldLimitPt[iter].x = planeLimitPt.x; + worldLimitPt[iter].z = planeLimitPt.z; + worldLimitPt[iter].y = -planeD[iter] / planeNormal[iter].y; + } + else + { + worldLimitPt[iter].y = planeLimitPt.y; + worldLimitPt[iter].z = planeLimitPt.z; + worldLimitPt[iter].x = -planeD[iter] / planeNormal[iter].x; + } + + dst->addLimitPlane(getFrom(planeNormal[iter]),getFrom(worldLimitPt[iter]),restitution[iter]); + + } + + delete []worldLimitPt; + delete []planeNormal; + delete []restitution; + delete []planeD; + + worldLimitPt = NULL; + planeD = NULL; + restitution = NULL; + planeD = NULL; + + + return numLimitPlanes; + +} + +pJoint *pFactory::cloneJoint(pJoint *src,CK3dEntity *srcReference,CK3dEntity *dstReference,int copyFlags) +{ + + //---------------------------------------------------------------- + // + // sanity checks + // + #ifdef _DEBUG + assert(src); + assert(dstReference); + #endif // _DEBUG + + + //---------------------------------------------------------------- + // + // Prepare pointers + // + NxActor *actorA = NULL; + pRigidBody *actorABody = GetPMan()->getBody(dstReference); + if (actorABody){ + actorA = actorABody->getActor(); + } + else{ + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"You need at least one rigid body"); + return NULL; + } + + + + //actorB can be NULL and can not be the same as actorA : + NxActor *actorB = NULL; + pRigidBody *actorBBody = NULL; + CK3dEntity *referenceB = NULL; + + + //---------------------------------------------------------------- + // + // determine the first, this will be the clone ! + // + if ( src->GetVTEntA() && src->GetVTEntA() !=srcReference ) + { + actorBBody = GetPMan()->getBody(src->GetVTEntA()); + if (actorBBody) + { + actorB = actorBBody->getActor(); + referenceB = actorBBody->GetVT3DObject(); + } + } + + //---------------------------------------------------------------- + // + // determine the second + // + if ( src->GetVTEntB() && src->GetVTEntB() !=srcReference ) + { + actorBBody = GetPMan()->getBody(src->GetVTEntB()); + if (actorBBody) + { + actorB = actorBBody->getActor(); + referenceB = actorBBody->GetVT3DObject(); + } + } + + if ( (copyFlags & PB_CF_SWAP_JOINTS_REFERENCES) ) + { + XSwap(actorA,actorB); + XSwap(actorABody,actorBBody); + + } + + CK3dEntity *testA = actorABody->GetVT3DObject(); + CK3dEntity *testB = NULL; + if (actorBBody) + testB = actorBBody->GetVT3DObject(); + + + + switch (src->getType()) + { + + //---------------------------------------------------------------- + // + // Distance Joint : + // + case JT_Distance : + { + + NxDistanceJoint *nxSrc = src->getJoint()->isDistanceJoint(); + if (nxSrc) + { + NxDistanceJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxDistanceJoint *nxJoint = (NxDistanceJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointDistance *joint = new pJointDistance(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + + return joint; + } + break; + } + + //---------------------------------------------------------------- + // + // Fixed Joint : + // + case JT_Fixed : + { + + NxFixedJoint *nxSrc = src->getJoint()->isFixedJoint(); + if (nxSrc) + { + NxFixedJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxFixedJoint *nxJoint = (NxFixedJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointFixed *joint = new pJointFixed(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // Ball Joint : + // + case JT_Spherical: + { + + NxSphericalJoint *nxSrc = src->getJoint()->isSphericalJoint(); + if (nxSrc) + { + NxSphericalJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxSphericalJoint *nxJoint = (NxSphericalJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointBall *joint = new pJointBall(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // Revolute Joint : + // + case JT_Revolute: + { + + NxRevoluteJoint *nxSrc = src->getJoint()->isRevoluteJoint(); + if (nxSrc) + { + NxRevoluteJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxRevoluteJoint *nxJoint = (NxRevoluteJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointRevolute *joint = new pJointRevolute(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // Cylindrical Joint : + // + case JT_Cylindrical: + { + + NxCylindricalJoint *nxSrc = src->getJoint()->isCylindricalJoint(); + if (nxSrc) + { + NxCylindricalJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxCylindricalJoint *nxJoint = (NxCylindricalJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointCylindrical*joint = new pJointCylindrical(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // Prismatic Joint : + // + case JT_Prismatic: + { + + NxPrismaticJoint *nxSrc = src->getJoint()->isPrismaticJoint(); + if (nxSrc) + { + NxPrismaticJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxPrismaticJoint *nxJoint = (NxPrismaticJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPrismatic*joint = new pJointPrismatic(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // PointInPlane Joint : + // + case JT_PointInPlane: + { + + NxPointInPlaneJoint*nxSrc = src->getJoint()->isPointInPlaneJoint(); + if (nxSrc) + { + NxPointInPlaneJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxPointInPlaneJoint *nxJoint = (NxPointInPlaneJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPointInPlane*joint = new pJointPointInPlane(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + + } + break; + } + + //---------------------------------------------------------------- + // + // PointOnLine Joint : + // + case JT_PointOnLine: + { + + NxPointOnLineJoint*nxSrc = src->getJoint()->isPointOnLineJoint(); + if (nxSrc) + { + NxPointOnLineJointDesc descrNew; + nxSrc->saveToDesc(descrNew); + + descrNew.actor[0] = actorA; descrNew.actor[1] = actorB; + + NxPointOnLineJoint *nxJoint = (NxPointOnLineJoint*)actorA->getScene().createJoint(descrNew); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPointOnLine*joint = new pJointPointOnLine(actorABody,actorBBody); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(actorABody->getWorld()); + return joint; + } + break; + } + } + return NULL; +} + +void pFactory::cloneJoints(CK3dEntity *src,CK3dEntity *dst,int copyFlags) +{ + + //---------------------------------------------------------------- + // + // sanity checks + // + #ifdef _DEBUG + assert(src); + assert(dst); + #endif // _DEBUG + + + pRigidBody *srcBody = GetPMan()->getBody(src); + pRigidBody *dstBody = GetPMan()->getBody(dst); + + XString errMsg; + + if ( !srcBody || !dstBody ) + { + errMsg.Format("You need two rigid objects to clone joints from a rigid body"); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMsg.Str()); + return; + } + + pWorld* srcBodyWorld = srcBody->getWorld(); + pWorld* dstBodyWorld = dstBody->getWorld(); + + if( !srcBodyWorld || !dstBodyWorld ) + { + errMsg.Format("You need two valid world objects to clone joints from a rigid body"); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMsg.Str()); + return; + } + + if( srcBodyWorld!=dstBodyWorld ) + { + errMsg.Format("Worlds objects must be same"); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errMsg.Str()); + return; + } + + //---------------------------------------------------------------- + // + // copy process + // + + pWorld *testWorld = dstBodyWorld; + + + NxU32 jointCount = testWorld->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + testWorld->getScene()->resetJointIterator(); + + NxJoint *last = NULL; + pJoint *lastJ = NULL; + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = testWorld->getScene()->getNextJoint(); + pJoint *mJoint = static_cast( j->userData ); + if ( mJoint ) + { + if (mJoint==lastJ)// avoid double clone + { + continue; + } + + if (mJoint->GetVTEntA() == srcBody->GetVT3DObject() || mJoint->GetVTEntB() == srcBody->GetVT3DObject() ) + { + pJoint *clone = pFactory::cloneJoint(mJoint,src,dst,copyFlags); + if (clone ) + { + if ((copyFlags & PB_CF_LIMIT_PLANES)) + { + int limitPlanes = pFactory::cloneLimitPlanes(mJoint,clone,src,dst); + } + } + } + } + lastJ = mJoint; + } + } +} + +pJointPointOnLine*pFactory::createPointOnLineJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) +{ + + if (jointCheckPreRequisites(a,b,JT_PointOnLine) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + NxPointOnLineJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.setGlobalAxis(getFrom(axis)); + desc.setGlobalAnchor(getFrom(anchor)); + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + NxPointOnLineJoint* nxJoint = (NxPointOnLineJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPointOnLine*joint = new pJointPointOnLine(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + return joint; +} + +pJointPointInPlane*pFactory::createPointInPlaneJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) +{ + + if (jointCheckPreRequisites(a,b,JT_PointInPlane) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + NxPointInPlaneJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.setGlobalAxis(getFrom(axis)); + desc.setGlobalAnchor(getFrom(anchor)); + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + NxPointInPlaneJoint* nxJoint = (NxPointInPlaneJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPointInPlane*joint = new pJointPointInPlane(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + return joint; +} + +pJointCylindrical*pFactory::createCylindricalJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) +{ + + if (jointCheckPreRequisites(a,b,JT_Cylindrical) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + NxCylindricalJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.setGlobalAxis(getFrom(axis)); + desc.setGlobalAnchor(getFrom(anchor)); + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + NxCylindricalJoint* nxJoint = (NxCylindricalJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointCylindrical*joint = new pJointCylindrical(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + return joint; + +} +pJointPrismatic *pFactory::createPrismaticJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) +{ + + + + if (jointCheckPreRequisites(a,b,JT_Prismatic) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + NxPrismaticJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.setGlobalAxis(getFrom(axis)); + desc.setGlobalAnchor(getFrom(anchor)); + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + NxPrismaticJoint* nxJoint = (NxPrismaticJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPrismatic*joint = new pJointPrismatic(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + return joint; + +} +pJointRevolute*pFactory::createRevoluteJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector axis) +{ + + if (jointCheckPreRequisites(a,b,JT_Revolute) == -1 ) + { + return NULL; + } + + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + + if (!ba && !bb) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"No body specified"); + return NULL; + } + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world && bb) + { + world = bb->getWorld(); + } + + + NxRevoluteJointDesc descr; + + /*descr.projectionDistance = (NxReal)0.05; + descr.projectionAngle= (NxReal)0.05; + descr.projectionMode = NX_JPM_POINT_MINDIST;*/ + + + + if (ba) + { + descr.actor[0]=ba->getActor(); + } + + if (bb) + { + descr.actor[1]=bb->getActor(); + } + + NxRevoluteJoint *nxJoint=(NxRevoluteJoint*)world->getScene()->createJoint(descr); + + if (!descr.isValid()) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Revolute joint invalid!"); + return NULL; + } + + nxJoint->setGlobalAnchor(getFrom(anchor)); + nxJoint->setGlobalAxis(getFrom(axis)); + + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointRevolute*joint = new pJointRevolute(ba,bb); + nxJoint->userData = joint; + joint->setWorld(world); + joint->setJoint(nxJoint); + + + + return joint; + + + +} + + +pJointPulley* pFactory::createPulleyJoint( CK3dEntity*a,CK3dEntity*b,VxVector pulley0,VxVector pulley1, VxVector anchor0, VxVector anchor1 ) +{ + + if (jointCheckPreRequisites(a,b,JT_Pulley) == -1 ) + { + return NULL; + } + + + VxVector globalAxis(0,1,0); + float distance = 10.0f; + float ratio = 1.0f; + float stiffness = 1.0f; + int flags = 0 ; + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + + if (!ba && !bb) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"You need two bodies for a pulley joint!"); + return NULL; + } + pWorld*world = GetPMan()->getWorldByBody(a); + + + ////////////////////////////////////////////////////////////////////////// + // nx object : + NxPulleyJointDesc descr; + descr.setToDefault(); + + descr.actor[0]=ba->getActor(); + descr.actor[1]=bb->getActor(); + descr.localAnchor[0] = pMath::getFrom(anchor0); + descr.localAnchor[1] = pMath::getFrom(anchor1); + descr.setGlobalAxis(pMath::getFrom(globalAxis)); + + + + descr.pulley[0] = pMath::getFrom(pulley0); // suspension points of two bodies in world space. + descr.pulley[1] = pMath::getFrom(pulley1); // suspension points of two bodies in world space. + descr.distance = distance; // the rest length of the rope connecting the two objects. The distance is computed as ||(pulley0 - anchor0)|| + ||(pulley1 - anchor1)|| * ratio. + descr.stiffness = stiffness; // how stiff the constraint is, between 0 and 1 (stiffest) + descr.ratio = ratio; // transmission ratio + descr.flags = flags; // This is a combination of the bits defined by ::NxPulleyJointFlag. + + if (!descr.isValid()) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"Pully joint invalid!"); + return NULL; + } + NxPulleyJoint *nxJoint = (NxPulleyJoint*)world->getScene()->createJoint(descr); + if (!nxJoint) + { + xLogger::xLog(ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointPulley*joint = new pJointPulley(ba,bb); + nxJoint->userData = joint; + joint->setWorld(world); + joint->setJoint(nxJoint); + return joint; + + + //descr.motor = gMotorDesc; + // pulleyDesc.projectionMode = NX_JPM_NONE; + // pulleyDesc.projectionMode = NX_JPM_POINT_MINDIST; + // pulleyDesc.jointFlags |= NX_JF_COLLISION_ENABLED; + return NULL; +} + +pJointFixed*pFactory::createFixedJoint(CK3dEntity *a, CK3dEntity *b) +{ + + + if (jointCheckPreRequisites(a,b,JT_Fixed) == -1 ) + { + return NULL; + } + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + + NxFixedJointDesc descr; + descr.actor[0] = a0; + descr.actor[1] = a1; + + if (!descr.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + + NxJoint *nxJoint = (NxDistanceJoint*)world->getScene()->createJoint(descr); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointFixed*joint = new pJointFixed(ba,bb); + nxJoint->userData = joint; + joint->setWorld(world); + joint->setJoint(nxJoint); + return joint; + +} + +pJointD6*pFactory::createD6Joint(CK3dEntity *a, CK3dEntity *b, VxVector globalAnchor,VxVector globalAxis,int collision) +{ + + if (jointCheckPreRequisites(a,b,JT_D6) == -1 ) + { + return NULL; + } + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + + NxD6JointDesc d6Desc; + d6Desc.actor[0] = a0; + d6Desc.actor[1] = a1; + d6Desc.setGlobalAnchor(pMath::getFrom(globalAnchor)); + d6Desc.setGlobalAxis(pMath::getFrom(globalAxis)); + if (collision) + { + //d6Desc.flags + d6Desc.jointFlags|=NX_JF_COLLISION_ENABLED; + } + + + + if (!d6Desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + + NxJoint *nxJoint = (NxDistanceJoint*)world->getScene()->createJoint(d6Desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointD6 *joint = new pJointD6(ba,bb); + nxJoint->userData = joint; + + joint->setWorld(world); + joint->setJoint(nxJoint); + return joint; + +} + +pJointBall *pFactory::createBallJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor,VxVector swingAxis) +{ + + pJointBall *result; + + if (jointCheckPreRequisites(a,b,JT_Spherical) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + if (!world) + { + world = GetPMan()->getWorldByBody(b); + } + + NxActor *a0 = NULL; + if (ba) + { + a0 = ba->getActor(); + } + NxActor *a1 = NULL; + if (bb) + { + a1 = bb->getActor(); + } + + + NxSphericalJointDesc desc; + desc.actor[0] = a0; + desc.actor[1] = a1; + desc.swingAxis = pMath::getFrom(swingAxis); + /*desc.projectionDistance = (NxReal)0.15; + desc.projectionMode = NX_JPM_POINT_MINDIST;*/ + + + if (!desc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Description failed"); + return NULL; + } + + + NxSphericalJoint* nxJoint = (NxSphericalJoint*)world->getScene()->createJoint(desc); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointBall*joint = new pJointBall(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + nxJoint->setGlobalAnchor(pMath::getFrom(anchor)); + joint->setWorld(world); + + return joint; +} + +int pFactory::jointCheckPreRequisites(CK3dEntity*_a,CK3dEntity*_b,int type) +{ + + pRigidBody *a = GetPMan()->getBody(_a); + pRigidBody *b = GetPMan()->getBody(_b); + + //bodies have already a joint together ? + if ( !a && !b) + { + return -1; + } + + if (a && !a->isValid() ) + { + return -1; + } + + if (a && !GetPMan()->getWorldByBody(_a)) + { + return -1; + } + + if (b && !GetPMan()->getWorldByBody(_b)) + { + return -1; + } + + if (b && !b->isValid()) + { + return -1; + } + + + if ( a && b ) + { + pWorld*worldA = GetPMan()->getWorldByBody(_a); + pWorld*worldB = GetPMan()->getWorldByBody(_b); + if (!worldA || !worldB || (worldA!=worldB) || !worldA->isValid() ) + { + return -1; + } + } + + + return 1; +} + +pJointDistance*pFactory::createDistanceJoint(CK3dEntity*a,CK3dEntity*b,VxVector anchor0,VxVector anchor1,float minDistance,float maxDistance,pSpring sSettings) +{ + if (jointCheckPreRequisites(a,b,JT_Distance) == -1 ) + { + return NULL; + } + + pRigidBody *ba = GetPMan()->getBody(a); + pRigidBody *bb = GetPMan()->getBody(b); + pWorld*world = GetPMan()->getWorldByBody(a); + + ////////////////////////////////////////////////////////////////////////// + // nx object : + NxDistanceJointDesc descr; + descr.actor[0]=ba->getActor(); + descr.actor[1]= b ? bb->getActor() : NULL ; + + + + + descr.localAnchor[0] = pMath::getFrom(anchor0); + descr.localAnchor[1] = pMath::getFrom(anchor1); + + descr.minDistance = minDistance; + descr.maxDistance = maxDistance; + + if (minDistance!=0.0f) + descr.flags|=NX_DJF_MIN_DISTANCE_ENABLED; + if (maxDistance!=0.0f) + descr.flags|=NX_DJF_MAX_DISTANCE_ENABLED; + + if(sSettings.damper!=0.0f || sSettings.damper!=0.0f ) + { + descr.flags|=NX_DJF_SPRING_ENABLED; + NxSpringDesc sDescr; + sDescr.damper = sSettings.damper; + sDescr.spring = sSettings.spring; + sDescr.targetValue = sSettings.targetValue; + descr.spring = sDescr; + + } + + NxDistanceJoint *nxJoint = (NxDistanceJoint*)world->getScene()->createJoint(descr); + if (!nxJoint) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"failed by PhysX-SDK"); + int v = descr.isValid(); + return NULL; + } + + //////////////////////////////////////////////////////////////////////////, + // vt object : + pJointDistance *joint = new pJointDistance(ba,bb); + nxJoint->userData = joint; + joint->setJoint(nxJoint); + joint->setWorld(world); + + return joint; + +} +pJoint*pFactory::createJoint(CK3dEntity*_a,CK3dEntity*_b,int type) +{ + return NULL ; +} + + +pJointSettings*pFactory::CreateJointSettings(const XString nodeName/* = */,const TiXmlDocument * doc /* = NULL */) +{ + + /* + pJointSettings *result = new pJointSettings(); + if (nodeName.Length() && doc) + { + const TiXmlElement *root = GetFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "JointSettings" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName.CStr() ) ) + { + + float vF=0.0f; + int res; + + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("LowStop",&vF); + if (res == TIXML_SUCCESS) + { + result->LowStop(vF); + } + + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("HiStop",&vF); + if (res == TIXML_SUCCESS) + { + result->HighStop(vF); + } + + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("LowStop2",&vF); + if (res == TIXML_SUCCESS) + { + result->LowStop2(vF); + } + + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("HiStop2",&vF); + if (res == TIXML_SUCCESS) + { + result->HighStop2(vF); + } + + + return result; + } + } + } + } + } + } + */ + return NULL; +} + +pJointSettings*pFactory::CreateJointSettings(const char* nodeName,const char *filename) +{ + + /* + XString fname(filename); + XString nName(nodeName); + if ( nName.Length() && fname.Length() ) + { + TiXmlDocument * document = getDocument(fname); + if (document) + { + pJointSettings *result = CreateJointSettings(nodeName,document); + if ( result) + { + delete document; + return result; + } + } + } + */ + return NULL; + +} + +pJointLimit pFactory::createLimitFromParameter(CKParameter *par) +{ + + + pJointLimit result; + + CKContext *ctx = GetPMan()->GetContext(); + + + if (par) + { + CKParameter* pout = NULL; + CK_ID* ids = (CK_ID*)par->GetReadDataPtr(); + + float value,restitution,hardness; + + pout = (CKParameterOut*)ctx->GetObject(ids[0]); + pout->GetValue(&value); + + pout = (CKParameterOut*)ctx->GetObject(ids[1]); + pout->GetValue(&restitution); + pout = (CKParameterOut*)ctx->GetObject(ids[2]); + pout->GetValue(&hardness); + + + result.value = value; + result.restitution = restitution; + result.hardness =hardness; + return result; + } + return result; + +} + +pSpring pFactory::createSpringFromParameter(CKParameter *par) +{ + + pSpring result; + + CKContext *ctx = GetPMan()->GetContext(); + + + + if (par) + { + CKParameter* pout = NULL; + CK_ID* ids = (CK_ID*)par->GetReadDataPtr(); + + float damping,spring,targetValue; + pout = (CKParameterOut*)ctx->GetObject(ids[0]); + pout->GetValue(&damping); + + pout = (CKParameterOut*)ctx->GetObject(ids[1]); + pout->GetValue(&spring); + pout = (CKParameterOut*)ctx->GetObject(ids[2]); + pout->GetValue(&targetValue); + + result.spring = spring; + result.damper = damping; + result.targetValue = targetValue; + return result; + } + return result; +} + + + +pMotor pFactory::createMotorFromParameter(CKParameter *par) +{ + pMotor result; + CKContext *ctx = GetPMan()->GetContext(); + + + + if (par) + { + CKParameter* pout = NULL; + CK_ID* ids = (CK_ID*)par->GetReadDataPtr(); + + float targetVel,maxF; + int freeSpin; + pout = (CKParameterOut*)ctx->GetObject(ids[0]); + pout->GetValue(&targetVel); + + pout = (CKParameterOut*)ctx->GetObject(ids[1]); + pout->GetValue(&maxF); + pout = (CKParameterOut*)ctx->GetObject(ids[2]); + pout->GetValue(&freeSpin); + result.targetVelocity = targetVel; + result.maximumForce = maxF; + result.freeSpin = freeSpin; + return result; + } + return result; +} + +pJoint*pFactory::GetJoint(CK3dEntity*_a,CK3dEntity*_b) +{ + + /* + if (!_a ||!_b) + { + return 0; + } + + pRigidBody *ba = getBody(_a); + pRigidBody *bb = getBody(_b); + + if ( !ba || !bb || ba == bb ) + return NULL; + + //we check whether both associated bodies are in the same world : + if ( ba->World() != bb->World() ) + { + return 0; + } + + OdeBodyType oba = ba->GetOdeBody(); + OdeBodyType obb = bb->GetOdeBody(); + + if ( !oba || !obb ) + return NULL; + + + for (int i = 0 ; i < dBodyGetNumJoints(oba) ; i++) + { + dJointID jID = dBodyGetJoint(oba,i); + pJoint *joint = static_cast(dJointGetData(jID)); + if (joint && joint->GetOdeBodyB() == obb) + { + return joint; + } + } + + for (int i = 0 ; i < dBodyGetNumJoints(obb) ; i++) + { + dJointID jID = dBodyGetJoint(obb,i); + pJoint *joint = static_cast(dJointGetData(jID)); + if (joint && joint->GetOdeBodyB() == oba) + { + return joint; + } + } + */ + return NULL; +} + diff --git a/usr/Src/old/Core/pFactory/pFactoryMaterial.cpp b/usr/Src/old/Core/pFactory/pFactoryMaterial.cpp new file mode 100644 index 0000000..7bf6e36 --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryMaterial.cpp @@ -0,0 +1,552 @@ +#include +#include "vtPhysXAll.h" +#include "tinyxml.h" + +#include + + +NxMaterialDesc* pFactory::createMaterialFromEntity(CKBeObject*object) +{ + + ////////////////////////////////////////////////////////////////////////// + //sanity checks : + if (!object ) + { + return NULL; + } + + if (!object->HasAttribute(GetPMan()->att_surface_props)) + { + return NULL; + } + ////////////////////////////////////////////////////////////////////////// + CKParameterManager *pm = object->GetCKContext()->GetParameterManager(); + int parameterType = pm->ParameterGuidToType(VTE_XML_MATERIAL_TYPE); + + NxMaterialDesc *result = new NxMaterialDesc(); + using namespace vtTools::AttributeTools; + XString nodeName; + + + int enumID = GetValueFromAttribute(object,GetPMan()->att_surface_props,0); + if (enumID==0) + { + goto takeFromAttribute; + } + + + CKEnumStruct *enumStruct = pm->GetEnumDescByType(parameterType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + if(i == enumID) + { + nodeName = enumStruct->GetEnumDescription(i); + if (nodeName.Length()) + { + result = createMaterialFromXML(nodeName.CStr(),getDefaultDocument()); + if (result) + { + return result; + } + } + } + } + } + + +takeFromAttribute : + { + float dynamicFriction = GetValueFromAttribute(object,GetPMan()->att_surface_props,1); + if (dynamicFriction >=0.0f) + { + result->dynamicFriction =dynamicFriction; + } + + float statFriction = GetValueFromAttribute(object,GetPMan()->att_surface_props,2); + if (statFriction>=0.0f) + { + result->staticFriction=statFriction; + } + + float rest = GetValueFromAttribute(object,GetPMan()->att_surface_props,3); + if (rest>=0.0f) + { + result->restitution=rest; + } + + float dynamicFrictionV = GetValueFromAttribute(object,GetPMan()->att_surface_props,4); + if (dynamicFrictionV >=0.0f) + { + result->dynamicFrictionV =dynamicFrictionV; + } + + float staticFrictionV = GetValueFromAttribute(object,GetPMan()->att_surface_props,5); + if (staticFrictionV>=0.0f) + { + result->staticFriction=staticFrictionV; + } + + VxVector anis = GetValueFromAttribute(object,GetPMan()->att_surface_props,6); + if (anis.Magnitude()>=0.01f) + { + result->dirOfAnisotropy=pMath::getFrom(anis); + } + + int fMode = GetValueFromAttribute(object,GetPMan()->att_surface_props,7); + if (fMode !=-1) + { + result->frictionCombineMode=(NxCombineMode)fMode; + } + int rMode = GetValueFromAttribute(object,GetPMan()->att_surface_props,8); + if (rMode !=-1) + { + result->restitutionCombineMode=(NxCombineMode)rMode; + } + + return result; + + + } + + + return result; + + +} + +bool pFactory::copyTo(pMaterial&dst,NxMaterial*src) +{ + + if (!src) + { + return false; + } + + dst.xmlLinkID = (int)src->userData; + dst.dirOfAnisotropy = getFrom(src->getDirOfAnisotropy()); + dst.dynamicFriction = src->getDynamicFriction(); + dst.dynamicFrictionV = src->getDynamicFrictionV(); + dst.staticFriction = src->getStaticFriction(); + dst.staticFrictionV = src->getStaticFrictionV(); + dst.frictionCombineMode = (CombineMode)src->getFrictionCombineMode(); + dst.restitutionCombineMode = (CombineMode)src->getRestitutionCombineMode(); + dst.restitution = src->getRestitution(); + dst.flags = src->getFlags(); + dst.setNxMaterialID(src->getMaterialIndex()); + + return false; +} +bool pFactory::copyTo(NxMaterialDesc &dst, const pMaterial &src) +{ + + dst.dirOfAnisotropy = getFrom(src.dirOfAnisotropy); + dst.dynamicFriction = src.dynamicFriction; + dst.dynamicFrictionV = src.dynamicFrictionV; + dst.staticFriction = src.staticFriction; + dst.staticFrictionV = src.staticFrictionV; + dst.frictionCombineMode = (NxCombineMode)src.frictionCombineMode; + dst.restitutionCombineMode = (NxCombineMode)src.restitutionCombineMode; + dst.restitution = src.restitution; + dst.flags = src.flags; + + + return true; + +} + +bool pFactory::copyTo(pMaterial& dst,CKParameter*src) +{ + if (!src)return false; + + using namespace vtTools::ParameterTools; + + dst.xmlLinkID = GetValueFromParameterStruct(src,E_MS_XML_TYPE); + dst.dirOfAnisotropy = GetValueFromParameterStruct(src,E_MS_ANIS); + dst.dynamicFriction = GetValueFromParameterStruct(src,E_MS_DFRICTION); + dst.dynamicFrictionV = GetValueFromParameterStruct(src,E_MS_DFRICTIONV); + dst.staticFriction = GetValueFromParameterStruct(src,E_MS_SFRICTION); + dst.staticFrictionV = GetValueFromParameterStruct(src,E_MS_SFRICTIONV); + dst.restitution= GetValueFromParameterStruct(src,E_MS_RESTITUTION); + dst.restitutionCombineMode= (CombineMode)GetValueFromParameterStruct(src,E_MS_RCMODE); + dst.frictionCombineMode= (CombineMode)GetValueFromParameterStruct(src,E_MS_FCMODE); + dst.flags= GetValueFromParameterStruct(src,E_MS_FLAGS); + return true; + + + +} + +bool pFactory::findSettings(pMaterial& dst,CKBeObject*src) +{ + + if (!src)return false; + + CKParameterOut *parMaterial = src->GetAttributeParameter(GetPMan()->att_surface_props); + + if (parMaterial){ + pFactory::Instance()->copyTo(dst,(CKParameter*)parMaterial); + goto EVALUATE; + } + + + + CK3dEntity *ent3D = static_cast(src); + if (ent3D) + { + CKMesh *mesh = ent3D->GetCurrentMesh(); + if (mesh) + { + parMaterial = mesh->GetAttributeParameter(GetPMan()->att_surface_props); + if (!parMaterial) + { + for (int i = 0 ; i < mesh->GetMaterialCount() ; i++) + { + CKMaterial *entMaterial = mesh->GetMaterial(i); + parMaterial = entMaterial->GetAttributeParameter(GetPMan()->att_surface_props); + if (parMaterial) + { + break; + } + } + } + } + } + + if (!parMaterial) return false; + + + ////////////////////////////////////////////////////////////////////////// + //copy parameter content to c++ + pFactory::Instance()->copyTo(dst,(CKParameter*)parMaterial); + + /////////////////////////////////////////////////////////////////////////// + // + // Evaluate from XML + // + + +EVALUATE: + + if ( dst.xmlLinkID !=0 ) + { + XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,dst.xmlLinkID); + bool err = loadFrom(dst,nodeName.Str(),getDefaultDocument()); + if (err) + { + copyTo(parMaterial,dst); + return true; + } + + + } + return false; +} + +bool pFactory::copyTo(CKParameterOut*dst,const pMaterial&src) +{ + if (!dst)return false; + + using namespace vtTools::ParameterTools; + + ////////////////////////////////////////////////////////////////////////// + //@todo : find the xml name ! + + SetParameterStructureValue(dst,E_MS_XML_TYPE,src.xmlLinkID,false); + SetParameterStructureValue(dst,E_MS_DFRICTION,src.dynamicFriction,false); + SetParameterStructureValue(dst,E_MS_DFRICTIONV,src.dynamicFrictionV,false); + SetParameterStructureValue(dst,E_MS_SFRICTION,src.staticFriction,false); + SetParameterStructureValue(dst,E_MS_SFRICTIONV,src.staticFrictionV,false); + SetParameterStructureValue(dst,E_MS_FCMODE,src.frictionCombineMode,false); + SetParameterStructureValue(dst,E_MS_RCMODE,src.restitutionCombineMode,false); + SetParameterStructureValue(dst,E_MS_RESTITUTION,src.restitution,false); + SetParameterStructureValue(dst,E_MS_XML_TYPE,src.xmlLinkID,false); + SetParameterStructureValue(dst,E_MS_FLAGS,src.flags,false); + SetParameterStructureValue(dst,E_MS_ANIS,src.dirOfAnisotropy,false); + +} + +pMaterial pFactory::loadMaterial(const char* nodeName,int& error) +{ + pMaterial result; + if(loadFrom(result,nodeName,getDefaultDocument())) + { + error = 0; + }else + error =1; + + return result; + + + +} +bool pFactory::loadMaterial(pMaterial&dst,const char* nodeName/* = */) +{ + return loadFrom(dst,nodeName,getDefaultDocument()); +} +bool pFactory::loadFrom(pMaterial &dst,const char *nodeName,const TiXmlDocument *doc) +{ + + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if ( strlen(nodeName) && doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "material" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryDoubleAttribute("DynamicFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.dynamicFriction = (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + dst.staticFriction= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + dst.restitution= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + dst.dynamicFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + dst.staticFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + const char* dirOfAnisotropy = NULL; + dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); + if (dirOfAnisotropy && strlen(dirOfAnisotropy)) + { + VxVector vec = _str2Vec(dirOfAnisotropy); + dst.dirOfAnisotropy = vec; + continue; + } + + const char* flags = NULL; + flags = sube->Attribute("Flags"); + if (flags && strlen(flags)) + { + dst.flags = _str2MaterialFlag(flags); + continue; + } + + ////////////////////////////////////////////////////////////////////////// + const char* FrictionCombineMode = NULL; + FrictionCombineMode = sube->Attribute("FrictionCombineMode"); + if (FrictionCombineMode && strlen(FrictionCombineMode)) + { + int fMode = _str2CombineMode(FrictionCombineMode); + dst.frictionCombineMode = (CombineMode)fMode; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + const char* RestitutionCombineMode = NULL; + RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); + if (RestitutionCombineMode && strlen(RestitutionCombineMode)) + { + int fMode = _str2CombineMode(RestitutionCombineMode); + dst.restitutionCombineMode= (CombineMode)fMode; + continue; + } + } + } + return true; + } + } + } + } + } + } + + return false; +} + +NxMaterialDesc*pFactory::createMaterialFromXML(const char* nodeName/* = */,const TiXmlDocument * doc /* = NULL */) +{ + + + + NxMaterialDesc *result = new NxMaterialDesc(); + result->setToDefault(); + + if (doc ==NULL) + return result; + + if (!getFirstDocElement(doc->RootElement())) + return result; + + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if ( strlen(nodeName) && doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "material" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryDoubleAttribute("DynamicFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + result->dynamicFriction = (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFriction= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->restitution= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->dynamicFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + const char* dirOfAnisotropy = NULL; + dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); + if (dirOfAnisotropy && strlen(dirOfAnisotropy)) + { + VxVector vec = _str2Vec(dirOfAnisotropy); + if (vec.Magnitude() >0.1f) + { + result->flags = NX_MF_ANISOTROPIC; + result->dirOfAnisotropy = pMath::getFrom(vec); + continue; + }else + { + result->dirOfAnisotropy = pMath::getFrom(VxVector(0,0,0)); + } + + //result->setGravity(vec); + + } + + ////////////////////////////////////////////////////////////////////////// + const char* FrictionCombineMode = NULL; + FrictionCombineMode = sube->Attribute("FrictionCombineMode"); + if (FrictionCombineMode && strlen(FrictionCombineMode)) + { + int fMode = _str2CombineMode(FrictionCombineMode); + result->frictionCombineMode = (NxCombineMode)fMode; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + const char* RestitutionCombineMode = NULL; + RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); + if (RestitutionCombineMode && strlen(RestitutionCombineMode)) + { + int fMode = _str2CombineMode(RestitutionCombineMode); + result->restitutionCombineMode= (NxCombineMode)fMode; + continue; + } + } + } + return result; + } + } + } + } + } + } + + return result; + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pFactory/pFactoryMesh.cpp b/usr/Src/old/Core/pFactory/pFactoryMesh.cpp new file mode 100644 index 0000000..7e16f62 --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryMesh.cpp @@ -0,0 +1,181 @@ +#include +#include "vtPhysXAll.h" + +NxCCDSkeleton *pFactory::createCCDSkeleton(CKBeObject *meshReference,int flags) +{ + + #ifdef _DEBUG + assert(meshReference); + #endif // _DEBUG + + + NxCCDSkeleton *result = NULL; + CKMesh *mesh = NULL; + + if (meshReference->GetClassID()==CKCID_MESH ) + mesh = static_cast(meshReference); + else if( meshReference->GetClassID() == CKCID_3DOBJECT && + ((CK3dEntity*)meshReference)->GetCurrentMesh() ) + mesh = ((CK3dEntity*)meshReference)->GetCurrentMesh(); + + + if (!mesh) + return NULL; + + + int numVerts = mesh->GetVertexCount(); + int numFaces = mesh->GetFaceCount(); + + + NxReal *vertices = new float[3 * numVerts]; + NxVec3 *verts = new NxVec3[numVerts]; + + for (int i = 0 ; i< numVerts ; i++ ) + { + VxVector v; + mesh->GetVertexPosition(i,&v); + vertices[i * 3] = v.x; + vertices[i * 3 + 1] =v.y; + vertices[i * 3 + 2] = v.z; + } + + NxU32 *indices2 = new NxU32[numFaces*3]; + + for(int j = 0 ; j < numFaces ; j++) + { + + int findicies[3]; + mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); + indices2[ j *3 ] = findicies[0]; + indices2[ j *3 + 1 ] = findicies[1]; + indices2[ j *3 + 2 ] = findicies[2]; + } + + NxSimpleTriangleMesh descr; + descr.numVertices = numVerts; + descr.pointStrideBytes = sizeof(NxReal)*3; + descr.points = vertices; + descr.numTriangles = numFaces; + descr.triangles = indices2; + descr.triangleStrideBytes = sizeof(NxU32)*3; + descr.flags = NX_MF_FLIPNORMALS; + + if (GetPMan()->getPhysicsSDK()) + { + result = GetPMan()->getPhysicsSDK()->createCCDSkeleton(descr); + } + + + delete [] vertices; + delete [] verts; + delete [] indices2; + + return result; + + +} +void pFactory::createConvexMesh(NxScene *scene,CKMesh *mesh,NxConvexMeshDesc&descr) +{ + + + + if (!scene || !mesh) + { + return; + } + + int numVerts = mesh->GetVertexCount(); + int numFaces = mesh->GetFaceCount(); + + + NxReal *vertices = new float[3 * numVerts]; + NxVec3 *verts = new NxVec3[numVerts]; + + for (int i = 0 ; i< numVerts ; i++ ) + { + VxVector v; + mesh->GetVertexPosition(i,&v); + vertices[i * 3] = v.x; + vertices[i * 3 + 1] =v.y; + vertices[i * 3 + 2] = v.z; + } + + NxU32 *indices2 = new NxU32[numFaces*3]; + + for(int j = 0 ; j < numFaces ; j++) + { + + int findicies[3]; + mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); + indices2[ j *3 ] = findicies[0]; + indices2[ j *3 + 1 ] = findicies[1]; + indices2[ j *3 + 2 ] = findicies[2]; + } + descr.numVertices = numVerts; + descr.pointStrideBytes = sizeof(NxReal)*3; + descr.points = vertices; + descr.numTriangles = numFaces; + descr.triangles = indices2; + descr.triangleStrideBytes = sizeof(NxU32)*3; + descr.flags = NX_CF_COMPUTE_CONVEX; + +/* + delete [] vertices; + delete [] verts; + delete [] indices2;*/ + +} +void +pFactory::createMesh(NxScene *scene,CKMesh *mesh,NxTriangleMeshDesc&descr) +{ + + if (!scene || !mesh) + { + return; + } + + int numVerts = mesh->GetVertexCount(); + int numFaces = mesh->GetFaceCount(); + + + NxReal *vertices = new float[3 * numVerts]; + NxVec3 *verts = new NxVec3[numVerts]; + + for (int i = 0 ; i< numVerts ; i++ ) + { + VxVector v; + mesh->GetVertexPosition(i,&v); + vertices[i * 3] = v.x; + vertices[i * 3 + 1] =v.y; + vertices[i * 3 + 2] = v.z; + } + + NxU32 *indices2 = new NxU32[numFaces*3]; + + for(int j = 0 ; j < numFaces ; j++) + { + + int findicies[3]; + mesh->GetFaceVertexIndex(j,findicies[0],findicies[1],findicies[2]); + indices2[ j *3 ] = findicies[0]; + indices2[ j *3 + 1 ] = findicies[1]; + indices2[ j *3 + 2 ] = findicies[2]; + } + descr.numVertices = numVerts; + descr.pointStrideBytes = sizeof(NxReal)*3; + descr.points = vertices; + descr.numTriangles = numFaces; + descr.triangles = indices2; + descr.triangleStrideBytes = sizeof(NxU32)*3; + descr.flags = 0; + + + /* + + delete [] vertices; + delete [] verts; + delete [] indices2; + + */ + +} diff --git a/usr/Src/old/Core/pFactory/pFactorySettings.cpp b/usr/Src/old/Core/pFactory/pFactorySettings.cpp new file mode 100644 index 0000000..0a937cb --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactorySettings.cpp @@ -0,0 +1,533 @@ +#include +#include "vtPhysXAll.h" +#include "IParameter.h" + +bool pFactory::findSettings(pPivotSettings& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_PIVOT_OFFSET); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + return false; +} + +CKParameterOut* pFactory::findSettings(pWheelDescr& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_WHEEL_DESCR); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_WHEEL_DESCR); + if (!par) + { + att = GetPMan()->GetContext()->GetAttributeManager()->GetAttributeTypeByName("Wheel"); + par = src->GetAttributeParameter(att); + } + bool copied = IParameter::Instance()->copyTo(dst,(CKParameter*)par); + return par; +} + +bool pFactory::findSettings(pCollisionSettings& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_COLLISIONS_SETTINGS); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_COLLISIONS_SETTINGS); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + return false; +} + +bool pFactory::findSettings(pOptimization& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_ACTOR_OPTIMIZATION); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + return false; +} + +bool pFactory::findSettings(pMassSettings& dst,CKBeObject*src) +{ + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); + CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_MASS_SETUP); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + return false; +} + +int pFactory::copyTo(CKParameter *src,pDominanceSetupItem&dst) +{ + + int result = 0 ; + +#ifdef _DEBUG + assert(src); +#endif // _DEBUG + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + CKParameter *contraintParameter = GetParameterFromStruct(src,PS_WD_CONSTRAINT); + + dst.constraint.dominanceA = GetValueFromParameterStruct(contraintParameter,PS_WDC_A); + dst.constraint.dominanceB = GetValueFromParameterStruct(contraintParameter,PS_WDC_B); + + dst.dominanceGroup0 = GetValueFromParameterStruct(src,PS_WD_GROUP_A); + dst.dominanceGroup1 = GetValueFromParameterStruct(src,PS_WD_GROUP_B); + + + + return 0; + +} + + + + + +bool pFactory::copyTo(pConvexCylinderSettings&dst,CKParameter*src,bool evaluate/* =true */) +{ + + bool result = false; + + #ifdef _DEBUG + assert(src); + #endif // _DEBUG + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + //int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_MASS_SETUP); + //CKParameterOut *par = findSettingsParameter(src,VTS_PHYSIC_MASS_SETUP); + + /* + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)src); + */ + + + + copyTo(dst.radius, GetParameterFromStruct(src,PS_CC_RADIUS_REFERENCED_VALUE),true); + copyTo(dst.height, GetParameterFromStruct(src,PS_CC_HEIGHT_REFERENCED_VALUE),true); + + dst.approximation = GetValueFromParameterStruct(src,PS_CC_APPROXIMATION); + + + //################################################################ + // + // Calculate Forward Axis, optionally referenced by an entity + // + dst.forwardAxis = GetValueFromParameterStruct(src,PS_CC_FORWARD_AXIS); + dst.forwardAxisRef = (CK3dEntity*)GetPMan()->m_Context->GetObject(GetValueFromParameterStruct(src,PS_CC_FORWARD_AXIS_REF)); + if (dst.forwardAxisRef) + { + VxVector dir,up,right; + dst.forwardAxisRef->GetOrientation(&dir,&up,&right); + dst.forwardAxisRef->TransformVector(&dst.forwardAxis,&dir); + dst.forwardAxis.Normalize(); + } + + + //################################################################ + // + // Calculate Down Axis, optionally referenced by an entity + // + dst.downAxis = GetValueFromParameterStruct(src,PS_CC_DOWN_AXIS); + dst.downAxisRef = (CK3dEntity*)GetPMan()->m_Context->GetObject(GetValueFromParameterStruct(src,PS_CC_DOWN_AXIS_REF)); + if (dst.downAxisRef) + { + VxVector dir,up,right; + dst.downAxisRef->GetOrientation(&dir,&up,&right); + dst.downAxisRef->TransformVector(&dst.downAxis,&up); + dst.downAxis.Normalize(); + } + + //################################################################ + // + // Calculate Right Axis, optionally referenced by an entity + // + dst.rightAxis = GetValueFromParameterStruct(src,PS_CC_RIGHT_AXIS); + dst.rightAxisRef = (CK3dEntity*)GetPMan()->m_Context->GetObject(GetValueFromParameterStruct(src,PS_CC_RIGHT_AXIS_REF)); + if (dst.rightAxisRef) + { + VxVector dir,up,right; + dst.rightAxisRef->GetOrientation(&dir,&up,&right); + dst.rightAxisRef->TransformVector(&dst.rightAxis,&right); + dst.rightAxis.Normalize(); + } + + dst.buildLowerHalfOnly = GetValueFromParameterStruct(src,PS_CC_BUILD_LOWER_HALF_ONLY); + dst.convexFlags = (pConvexFlags)GetValueFromParameterStruct(src,PS_CC_EXTRA_SHAPE_FLAGS); + + return true; +} + +bool pFactory::findSettings(pConvexCylinderSettings&dst,CKBeObject *src) +{ + + bool result = false; + +#ifdef _DEBUG + assert(src); +#endif // _DEBUG + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + int attType = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR); + CKParameterOut *pout = src->GetAttributeParameter(attType); + if (!pout) + { + CKMesh *currentMesh = ((CK3dEntity*)src)->GetCurrentMesh(); + if (currentMesh) + { + pout = currentMesh->GetAttributeParameter(attType); + if (!pout) + { + + dst.forwardAxis.Set(1.0f,0.0f,0.0f); + dst.downAxis.Set(0.0f,-1.0f,0.0f); + dst.rightAxis.Set(0.0f,0.0f,-1.0f); + + dst.buildLowerHalfOnly = false; + dst.approximation = 10; + + VxVector size(0.0f); + + if (src->GetClassID() == CKCID_3DOBJECT ) + { + CK3dEntity *ent3D = (CK3dEntity*)src; + if (ent3D) + { + size = ent3D->GetBoundingBox(true).GetSize(); + } + }else if(src->GetClassID() == CKCID_MESH) + { + CKMesh *mesh = (CKMesh*)src; + if (mesh) + { + size = mesh->GetLocalBox().GetSize(); + } + } + + dst.radius.value = size.x * 0.5f; + dst.height.value = size.y; + + return false; + } + } + } + return copyTo(dst,pout); +} + +bool pFactory::findSettings(pCapsuleSettings&dst,CKBeObject *src) +{ + + bool result = false; + if (!src) + { + return result; + } + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + CKParameterOut *pout = src->GetAttributeParameter(GetPMan()->att_capsule); + if (!pout) + { + CKMesh *currentMesh = ((CK3dEntity*)src)->GetCurrentMesh(); + if (currentMesh) + { + pout = currentMesh->GetAttributeParameter(GetPMan()->att_capsule); + if (!pout) + { + dst.localLengthAxis = CKAXIS_Y; + dst.localRadiusAxis = CKAXIS_X; + dst.height = -1.0f; + dst.radius = -1.0f; + return false; + } + } + } + return copyTo(dst,pout); +} + + +bool pFactory::findSettings(pCapsuleSettingsEx&dst,CKBeObject *src) +{ + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + if (!src)return false; + + int att = GetPMan()->getAttributeTypeByGuid(VTS_CAPSULE_SETTINGS_EX); + CKParameterOut *par = findSettingsParameter(src,VTS_CAPSULE_SETTINGS_EX); + + if (par) + return IParameter::Instance()->copyTo(dst,(CKParameter*)par); + + //dst.height.referenceAxis = CKAXIS_Y; + //dst.radius.referenceAxis = CKAXIS_X; + + return false; + +} + +void pFactory::copyTo(pAxisReferencedLength&dst,CKParameter*src,bool evaluate) +{ + +#ifdef _DEBUG + assert(src); +#endif + + using namespace vtTools::ParameterTools; + + + //################################################################ + // + // Retrieve the value : + // + dst.value = GetValueFromParameterStruct(src,PS_ARL_VALUE); + + dst.referenceAxis = GetValueFromParameterStruct(src,PS_ARL_REF_OBJECT_AXIS); + + + + + + + //################################################################ + // + // Calculate the value basing on the given objects local box and an axis. + // + CK_ID idRef= GetValueFromParameterStruct(src,PS_ARL_REF_OBJECT); + CKBeObject *object = (CKBeObject*)GetPMan()->GetContext()->GetObject(idRef); + + if (!object) + return; + + dst.reference = object; + + if (!evaluate)return; + + + VxVector size(0.0f); + if (object->GetClassID() == CKCID_3DOBJECT ) + { + CK3dEntity *ent3D = (CK3dEntity*)object; + if (ent3D) + { + size = ent3D->GetBoundingBox(true).GetSize(); + } + }else if(object->GetClassID() == CKCID_MESH) + { + CKMesh *mesh = (CKMesh*)object; + if (mesh) + { + size = mesh->GetLocalBox().GetSize(); + } + } + + + dst.value = size[dst.referenceAxis]; +} + + +pWorldSettings*pFactory::getWorldSettings(CK3dEntity*ent) +{ + + /* + ////////////////////////////////////////////////////////////////////////// + //sanity checks : + if (!ent ) + { + return NULL; + } + if (!ent->HasAttribute(GetPMan()->att_world_object )) + { + return NULL; + } + ////////////////////////////////////////////////////////////////////////// + pWorldSettings *result = new pWorldSettings(); + using namespace vtTools::AttributeTools; + + result->m_Gravity= GetValueFromAttribute(ent,GetPMan()->att_world_object,0); + result->m_CFM= GetValueFromAttribute(ent,GetPMan()->att_world_object,1); + result->m_ERP= GetValueFromAttribute(ent,GetPMan()->att_world_object,2); + result->m_MaximumContactCorrectVelocity = GetValueFromAttribute(ent,GetPMan()->att_world_object,3); + result->m_ContactSurfaceLayer = GetValueFromAttribute(ent,GetPMan()->att_world_object,4); + return result; + */ + return NULL; +} + +pObjectDescr* pFactory::createPObjectDescrFromParameter(CKParameter *par) +{ + + if (!par) + return NULL; + + //################################################################ + // + // ATTENTION : + // + + pObjectDescr *descr = new pObjectDescr(); + using namespace vtTools::ParameterTools; + + + int hType,flags,hierarchy,collGroup; + VxVector mOffset,sOffset; + float density,skinWidth,newDensity,totalMass; + + collGroup = GetValueFromParameterStruct(par,E_PPS_COLL_GROUP,false); + hierarchy = GetValueFromParameterStruct(par,E_PPS_HIRARCHY,false); + hType = GetValueFromParameterStruct(par,E_PPS_HULLTYPE,false); + flags = GetValueFromParameterStruct(par,E_PPS_BODY_FLAGS,false); + density = GetValueFromParameterStruct(par,E_PPS_DENSITY,false); + newDensity = GetValueFromParameterStruct(par,E_PPS_NEW_DENSITY,false); + totalMass = GetValueFromParameterStruct(par,E_PPS_TOTAL_MASS,false); + skinWidth = GetValueFromParameterStruct(par,E_PPS_SKIN_WIDTH,false); + mOffset = GetValueFromParameterStruct(par,E_PPS_MASS_OFFSET,false); + sOffset = GetValueFromParameterStruct(par,E_PPS_MASS_OFFSET,false); + + + + descr->density = density; + descr->skinWidth = skinWidth; + descr->massOffset = mOffset; + descr->shapeOffset = sOffset; + descr->hullType = (HullType)hType; + descr->flags = (BodyFlags)flags; + descr->hirarchy = hierarchy; + descr->newDensity = newDensity; + descr->totalMass = totalMass; + + return descr; + + return NULL; +} + +pSleepingSettings*pFactory::getSleepingSettings(CK3dEntity*ent) +{ + /* + ////////////////////////////////////////////////////////////////////////// + //sanity checks : + if (!ent ) + { + return NULL; + } + if (!ent->HasAttribute(GetPMan()->att_sleep_settings )) + { + return NULL; + } + ////////////////////////////////////////////////////////////////////////// + pSleepingSettings *result = new pSleepingSettings(); + using namespace vtTools::AttributeTools; + result->m_SleepSteps= GetValueFromAttribute(ent,GetPMan()->att_sleep_settings,0); + result->m_AngularThresold= GetValueFromAttribute(ent,GetPMan()->att_sleep_settings,1); + result->m_LinearThresold = GetValueFromAttribute(ent,GetPMan()->att_sleep_settings,2); + result->m_AutoSleepFlag = GetValueFromAttribute(ent,GetPMan()->att_sleep_settings,3); + return result; + */ + return NULL; +} + +bool pFactory::copyTo(pCapsuleSettings&dst,CKParameter*src) +{ + if (!src) return false; + + using namespace vtTools::ParameterTools; + + dst.localLengthAxis = GetValueFromParameterStruct(src,E_CS_LENGTH_AXIS); + dst.localRadiusAxis = GetValueFromParameterStruct(src,E_CS_RADIUS_AXIS); + dst.radius = GetValueFromParameterStruct(src,E_CS_RADIUS); + dst.height = GetValueFromParameterStruct(src,E_CS_LENGTH); + + return true; +} +int pFactory::copyTo(CKParameterOut*dst,pGroupsMask src) +{ + + if (!dst) return 0; + + + + using namespace vtTools::ParameterTools; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,0,src.bits0,false); + SetParameterStructureValue(dst,1,src.bits1,false); + SetParameterStructureValue(dst,2,src.bits2,false); + SetParameterStructureValue(dst,3,src.bits3,false); + + return true; +} +int pFactory::copyTo(pGroupsMask &dst,CKParameter*src) +{ + + if (!src) return 0; + using namespace vtTools::ParameterTools; + using namespace vtTools::ParameterTools; + dst.bits0 = GetValueFromParameterStruct(src,0); + dst.bits1 = GetValueFromParameterStruct(src,1); + dst.bits2 = GetValueFromParameterStruct(src,2); + dst.bits3 = GetValueFromParameterStruct(src,3); + return 1; +} + +CKParameterOut *pFactory::findSettingsParameter(CKBeObject *src,CKGUID guid) +{ + + + if (!src)return NULL; + + int att = GetPMan()->getAttributeTypeByGuid(guid); + CKParameterOut *par = src->GetAttributeParameter(att); + if (par){ + return par; + } + //---------------------------------------------------------------- + // + // Try sub objects + // + CK3dEntity *ent3D = static_cast(src); + if (ent3D) + { + CKMesh *mesh = ent3D->GetCurrentMesh(); + if (mesh) + { + par = mesh->GetAttributeParameter(att); + if (!par) + { + for (int i = 0 ; i < mesh->GetMaterialCount() ; i++) + { + CKMaterial *entMaterial = mesh->GetMaterial(i); + par = entMaterial->GetAttributeParameter(att); + if (par) + { + break; + } + } + } + } + } + return par; +} \ No newline at end of file diff --git a/usr/Src/old/Core/pFactory/pFactoryShapes.cpp b/usr/Src/old/Core/pFactory/pFactoryShapes.cpp new file mode 100644 index 0000000..1fefa6f --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryShapes.cpp @@ -0,0 +1,817 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" +#include "IParameter.h" + +#include + + +NxShape *pFactory::cloneShape(CK3dEntity *src,CK3dEntity *dst,CK3dEntity*dstBodyReference,int copyFlags,int bodyFlags/* =0 */) +{ + + if (!src || !dst ) + return NULL; + + pRigidBody *srcBody = GetPMan()->getBody(src); + if (!srcBody) + return NULL; + + pRigidBody *dstBody = GetPMan()->getBody(dstBodyReference); + if (!dstBody) + return NULL; + + if (dstBody->isSubShape(dst)) + return NULL; + + + NxShape *srcShape = srcBody->getSubShape(src); + if (!srcShape) + return NULL; + + bool isSubShape=srcBody->isSubShape(src); + + + pObjectDescr oDescr; + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + + + //---------------------------------------------------------------- + // + // Try to copy it directly from the source object + // + if ( !src->HasAttribute(attTypePBSetup) && isSubShape ) + { + pSubMeshInfo* sInfo = (pSubMeshInfo*)srcShape->userData; + if (sInfo ) + { + const pObjectDescr &srcDescr = sInfo->initDescription; + memcpy(&oDescr,&srcDescr,sizeof(pObjectDescr)); + } + } + + //---------------------------------------------------------------- + // + // Try to copy it directly from the source objects attribute + // + + if (dst->HasAttribute(attTypePBSetup)) + { + //---------------------------------------------------------------- + // + // fill object description + // + + CKParameterOut *par = dst->GetAttributeParameter(attTypePBSetup); + if (!par) + return 0; + + IParameter::Instance()->copyTo(&oDescr,par); + oDescr.version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + + } + + + //---------------------------------------------------------------- + // + // adjust data + // + + + //---------------------------------------------------------------- + // + // find pivot settings + // + if ( (copyFlags & PB_CF_PIVOT_SETTINGS ) ) + { + //check in objects attribute + int attPivot = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_PIVOT_OFFSET); + } + + + if (oDescr.flags & BF_SubShape) + { + if (oDescr.hullType == HT_Wheel) + { + VxVector loc; + pWheel *wheel = createWheel(dstBodyReference,dst,oDescr.wheel,oDescr.convexCylinder,loc); + if(wheel && wheel->castWheel2() ) + return wheel->castWheel2()->getWheelShape(); + else + return NULL; + + }else if( oDescr.hullType != HT_Cloth) + { + + srcBody->addSubShape(NULL,oDescr,dst); + NxShape *result = srcBody->getSubShape(dst); + if (result) + { + //---------------------------------------------------------------- + // + // Adjust mass + // + if ( ( copyFlags & PB_CF_MASS_SETTINGS) ) + { + /* srcBody->updateMassSettings(srcBody->getInitialDescription()->mass); + + result->updateMassSettings(oDescr.mass); + else if(pFactory::Instance()->findSettings(oDescr.mass,referenceObject)) + result->updateMassSettings(oDescr.mass); + */ + + } + return result; + } + } + } + return NULL; + + /* + int sType = vtAgeia::getHullTypeFromShape(srcShape); + + switch(sType) + { + + case HT_Sphere: + { + NxSphereShape *tShape = srcShape->isSphere(); + NxSphereShapeDesc old; + tShape->saveToDesc(old); + + } + } + + + */ + + +} + +NxShape *pFactory::createShape(CK3dEntity *bodyReference,pObjectDescr descr,CK3dEntity *srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + + NxShape *result = NULL; + if (!bodyReference || !mesh ) + { + return result; + } + pRigidBody *body=GetPMan()->getBody(bodyReference); + + if (!body) + return NULL; + + NxActor *actor = body->getActor(); + + if (!actor) + return NULL; + + int hType = descr.hullType; + VxVector box_s = mesh->GetLocalBox().GetSize(); + float density = descr.density; + float skinWidth = descr.skinWidth; + float radius = mesh->GetRadius(); + NxQuat rot = pMath::getFrom(localRotation); + NxVec3 pos = pMath::getFrom(localPos); + CK_ID srcID = mesh->GetID(); + + + pWheel *wheel = NULL; + pSubMeshInfo *sInfo = NULL; + + + switch(hType) + { + + case HT_ConvexCylinder: + { + + + + NxConvexShapeDesc shape; + pConvexCylinderSettings &cSettings = descr.convexCylinder; + + iAssertW( ( descr.mask & OD_ConvexCylinder), + pFactory::Instance()->findSettings(cSettings,srcReference), + "Hull type has been set to convex cylinder but there is no descriptions \ + passed or activated in the pObjectDescr::mask.Trying object attributes...."); + + if (cSettings.radius.reference) + cSettings.radius.evaluate(cSettings.radius.reference); + + if (cSettings.height.reference) + cSettings.height.evaluate(cSettings.height.reference); + + cSettings.radius.value = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); + cSettings.height.value = cSettings.height.value > 0.0f ? cSettings.height.value : (box_s.v[cSettings.height.referenceAxis] * 0.5f); + + iAssertW( cSettings.isValid() , cSettings.setToDefault(),""); + bool resultAssert = true; + + iAssertWR( pFactory::Instance()->_createConvexCylinderMesh(&shape,cSettings,srcReference),"",resultAssert); + /* + NxConvexShapeDesc shape; + if (!_createConvexCylinder(&shape,srcReference)) + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); +*/ + shape.density = density; + shape.localPose.t = pos; + shape.localPose.M = rot; + shape.skinWidth = skinWidth; + + result = actor->createShape(shape); + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + shape.dimensions = pMath::getFrom(box_s)*0.5f; + shape.density = density; + shape.localPose.t = pos; + shape.localPose.M = rot; + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + shape.radius = radius; + shape.density = density; + shape.localPose.M = rot; + shape.localPose.t = pMath::getFrom(localPos); + if (skinWidth!=-1.0f) + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + + pFactory::Instance()->createMesh(&actor->getScene(),mesh,myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return NULL; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + shape.localPose.M = rot; + shape.localPose.t = pMath::getFrom(localPos); + if (skinWidth!=-1.0f) + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + + if (mesh->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshes allowed, by Ageia!"); + goto nothing; + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + pFactory::Instance()->createConvexMesh(&actor->getScene(),mesh,myMesh); + + NxConvexShapeDesc shape; + bool status = InitCooking(); + if (!status) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + goto nothing; + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + goto nothing; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + + shape.localPose.M = rot; + shape.localPose.t = pMath::getFrom(localPos); + if (skinWidth!=-1.0f) + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + CloseCooking(); + + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + NxCapsuleShapeDesc shape; + + pCapsuleSettingsEx &cSettings = descr.capsule; + + iAssertW( ( descr.mask & OD_Capsule), + pFactory::Instance()->findSettings(cSettings,srcReference), + "Hull type has been set to convex cylinder but there is no descriptions \ + passed or activated in the pObjectDescr::mask.Trying object attributes...."); + + bool resultAssert = true; + + if (cSettings.radius.reference) + cSettings.radius.evaluate(cSettings.radius.reference); + + if (cSettings.height.reference) + cSettings.height.evaluate(cSettings.height.reference); + + iAssertWR(cSettings.isValid(),cSettings.setToDefault(),resultAssert); + + shape.radius = cSettings.radius.value > 0.0f ? (cSettings.radius.value*0.5) : (box_s.v[cSettings.radius.referenceAxis] * 0.5f); + shape.height = cSettings.height.value > 0.0f ? (cSettings.height.value-( 2*shape.radius)) : (box_s.v[cSettings.height.referenceAxis] - ( 2*shape.radius)) ; + + shape.density = density; + shape.localPose.M = rot; + shape.localPose.t = pos; + shape.skinWidth = skinWidth; + result = actor->createShape(shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Wheel: + { + + pWheelDescr &wheelDescr = descr.wheel; + CKParameterOut *wheelParameter = NULL; + + //---------------------------------------------------------------- + // + // determine wheel settings + // + if (!(descr.mask & OD_Wheel)) + { + wheelParameter = pFactory::Instance()->findSettings(wheelDescr,srcReference); + } + + bool resultAssert = true; + iAssertWR(wheelDescr.isValid(),wheelDescr.setToDefault(),resultAssert); + //---------------------------------------------------------------- + // + // determine radius + // + if (wheelDescr.radius.reference == 0 && wheelDescr.radius.value == 0.0f ) + { + float radiusBestFit = 0.0f; + if (box_s[0] > radiusBestFit) + radiusBestFit = box_s[0]; + + if (box_s[1] > radiusBestFit) + radiusBestFit = box_s[1]; + + if (box_s[2] > radiusBestFit) + radiusBestFit = box_s[2]; + + wheelDescr.radius.value = radiusBestFit * 0.5f; + + } + + iAssertW(wheelDescr.radius.isValid(),wheelDescr.radius.evaluate(srcReference),""); + if(!wheelDescr.radius.isValid()) + wheelDescr.radius.value = srcReference->GetRadius(); + + + VxVector box_s = mesh->GetLocalBox().GetSize(); + float radius = wheelDescr.radius.value > 0.0f ? wheelDescr.radius.value : box_s.v[wheelDescr.radius.referenceAxis] * 0.5f; + + NxWheelShapeDesc shape; + shape.setToDefault(); + + shape.radius = radius; + shape.localPose.M = rot; + shape.localPose.t = pos; + + float heightModifier = (wheelDescr.wheelSuspension + radius ) / wheelDescr.wheelSuspension; + shape.suspension.spring = wheelDescr.springRestitution*heightModifier; + shape.suspension.damper = wheelDescr.springDamping * heightModifier; + shape.suspension.targetValue = wheelDescr.springBias * heightModifier; + shape.suspensionTravel = wheelDescr.wheelSuspension; + shape.inverseWheelMass = wheelDescr.inverseWheelMass; + + + const pTireFunction& latFunc = wheelDescr.latFunc; + const pTireFunction& longFunc = wheelDescr.longFunc; + + + NxTireFunctionDesc lngTFD; + lngTFD.extremumSlip = longFunc.extremumSlip ; + lngTFD.extremumValue = longFunc.extremumValue; + lngTFD.asymptoteSlip = longFunc.asymptoteSlip; + lngTFD.asymptoteValue = longFunc.asymptoteValue; + lngTFD.stiffnessFactor = longFunc.stiffnessFactor; + + NxTireFunctionDesc latTFD; + latTFD.extremumSlip = latFunc.extremumSlip ; + latTFD.extremumValue = latFunc.extremumValue; + latTFD.asymptoteSlip = latFunc.asymptoteSlip; + latTFD.asymptoteValue = latFunc.asymptoteValue; + latTFD.stiffnessFactor = latFunc.stiffnessFactor; + + + shape.lateralTireForceFunction =latTFD; + shape.longitudalTireForceFunction =lngTFD; + shape.wheelFlags =wheelDescr.wheelShapeFlags; + + //---------------------------------------------------------------- + // + // evaluate wheel settings into attribute parameters + // + if (wheelParameter) + { + IParameter::Instance()->copyTo(wheelParameter,descr.wheel); + + } + + result = actor->createShape(shape); + + } + } + + if(!result) + { + return NULL; + } + + //---------------------------------------------------------------- + // + // add sub mesh meta + + // + sInfo = new pSubMeshInfo(); + + sInfo->meshID = srcID; + sInfo->mesh = mesh; + + sInfo->entID = srcReference->GetID(); + sInfo->refObject = srcReference; + + result->setName(srcReference->GetName()); + result->userData = (void*)sInfo; + sInfo->initDescription = descr; + + //---------------------------------------------------------------- + // + // wheel extra data + // + if ( descr.hullType == HT_Wheel ) + { + sInfo->wheel = new pWheel2(body,&descr.wheel); + int a = (descr.wheel.wheelFlags & WF_VehicleControlled) ? true : false; + int b = (descr.wheel.wheelFlags & WF_Accelerated) ? true : false; + ((pWheel2*)sInfo->wheel)->setWheelShape((NxWheelShape*)result->isWheel()); + sInfo->wheel->setEntID(srcReference->GetID()); + sInfo->wheel->mWheelFlags = descr.wheel.wheelFlags; + + + } + + //---------------------------------------------------------------- + // + // Material + // + if ((descr.mask & OD_Material)) + body->updateMaterialSettings(descr.material,srcReference); + else if(pFactory::Instance()->findSettings(descr.material,srcReference)) + body->updateMaterialSettings(descr.material,srcReference); + + + //---------------------------------------------------------------- + // + // Collision + // + if ((descr.mask & OD_Collision)) + body->updateCollisionSettings(descr.collision,srcReference); + else if(pFactory::Instance()->findSettings(descr.collision,srcReference)) + body->updateCollisionSettings(descr.collision,srcReference); + + + //---------------------------------------------------------------- + // + // Adjust pivot + // + + if ( (descr.mask & OD_Pivot) ) + { + iAssertW1( descr.pivot.isValid(),descr.pivot.setToDefault()); + body->updatePivotSettings(descr.pivot,srcReference); + }else if(pFactory::Instance()->findSettings(descr.pivot,srcReference)) + body->updatePivotSettings(descr.pivot,srcReference); + + + //---------------------------------------------------------------- + // + // post + // + if (descr.flags & BF_TriggerShape ) + { + result->setFlag(NX_TRIGGER_ENABLE,TRUE); + } + + //---------------------------------------------------------------- + // + // Mass + // + if ((descr.mask & OD_Mass)) + body->updateMassSettings(descr.mass); + else if(pFactory::Instance()->findSettings(descr.mass,srcReference)) + body->updateMassSettings(descr.mass); + + return result; + + nothing : + return NULL; + +} + +bool pFactory::_createConvexCylinderMesh(NxConvexShapeDesc *dstShapeDescription,pConvexCylinderSettings& srcSettings,CK3dEntity*referenceObject) +{ + + + +#ifdef _DEBUG + assert(referenceObject); // <- should never happen ! +#endif // _DEBUG + + bool result = false; + + +/* srcSettings.radius.value *=0.5f; + srcSettings.height.value *=0.5f; +*/ + NxArray points; + NxVec3 center(0,0,0); + + NxVec3 frontAxis = getFrom(srcSettings.forwardAxis); // = wheelDesc->downAxis.cross(wheelDesc->wheelAxis); + NxVec3 downAxis = getFrom(srcSettings.downAxis);//downAxis *=-1.0; // = wheelDesc->downAxis; + NxVec3 wheelAxis = getFrom(srcSettings.rightAxis); // = wheelDesc->wheelAxis; + + + //frontAxis.normalize(); + frontAxis *= srcSettings.radius.value; + //downAxis.normalize(); + downAxis *= srcSettings.radius.value; + //wheelAxis.normalize(); + wheelAxis *= srcSettings.height.value; + + NxReal step; + + if(srcSettings.buildLowerHalfOnly) + { + if((srcSettings.approximation& 0x1) == 0) + srcSettings.approximation++; + + step = (NxReal)(NxTwoPi) / (NxReal)(srcSettings.approximation*2); + } + else + { + step = (NxReal)(NxTwoPi) / (NxReal)(srcSettings.approximation); + } + for(NxU32 i = 0; i < srcSettings.approximation; i++) + { + NxReal iReal; + if(srcSettings.buildLowerHalfOnly) + { + iReal = (i > (srcSettings.approximation >> 1))?(NxReal)(i+srcSettings.approximation):(NxReal)i; + } + else + { + iReal = (NxReal)i; + } + NxReal Sin, Cos; + NxMath::sinCos(step * iReal, Sin, Cos); + NxVec3 insPoint = (downAxis * -Cos) + (frontAxis * Sin); + points.pushBack(insPoint + wheelAxis); + points.pushBack(insPoint - wheelAxis); + } + + NxConvexMeshDesc convexDesc; + convexDesc.numVertices = points.size(); + convexDesc.pointStrideBytes = sizeof(NxVec3); + convexDesc.points = &points[0].x; + + +// srcSettings.convexFlags |=NX_CF_COMPUTE_CONVEX; +// convexDesc.flags |= srcSettings.convexFlags; + + int cf = CF_ComputeConvex; + cf |= srcSettings.convexFlags; + + convexDesc.flags |= cf; + + + + + // Cooking from memory + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + int s = convexDesc.isValid(); + if(CookConvexMesh(convexDesc, buf)) + { + //NxConvexShapeDesc convexShapeDesc; + + dstShapeDescription->meshData = getPhysicSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + dstShapeDescription->localPose.t = center; + dstShapeDescription->localPose.M.setColumn(0, NxVec3( 1, 0, 0)); + dstShapeDescription->localPose.M.setColumn(1, NxVec3( 0,-1, 0)); + dstShapeDescription->localPose.M.setColumn(2, NxVec3( 0, 0, -1)); + if(dstShapeDescription->meshData != NULL) + { + result = true; + // NxU32 shapeNumber = actor->getNbShapes(); + // result = actor->createShape(convexShapeDesc)->isConvexMesh(); + // if (!result) { + // xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + // } + //wheel->wheelConvex->userData = wheel; + } + } + CloseCooking(); + return result; +} + + + + +NxShape * pFactory::_createConvexCylinder(NxActor *actor,int approximation,VxVector _forwardAxis,VxVector _downAxis,VxVector _rightAxis,float height,float radius,bool buildLowerHalf,int shapeFlags) +{ + + if (!actor || approximation<1 ) + return NULL; + + NxConvexShape *result = NULL; + NxArray points; + NxVec3 center(0,0,0); + + NxVec3 frontAxis = getFrom(_forwardAxis);// = wheelDesc->downAxis.cross(wheelDesc->wheelAxis); + NxVec3 downAxis = getFrom(_downAxis);// = wheelDesc->downAxis; + + downAxis *=-1.0; + + NxVec3 wheelAxis = getFrom(_rightAxis);// = wheelDesc->wheelAxis; + //frontAxis.normalize(); + frontAxis *= radius; + //downAxis.normalize(); + downAxis *= radius; + //wheelAxis.normalize(); + wheelAxis *= height; + + NxReal step; + + if(buildLowerHalf) + { + if((approximation & 0x1) == 0) + approximation++; + + step = (NxReal)(NxTwoPi) / (NxReal)(approximation*2); + } + else + { + step = (NxReal)(NxTwoPi) / (NxReal)(approximation); + } + for(NxU32 i = 0; i < approximation; i++) + { + NxReal iReal; + if(buildLowerHalf) + { + iReal = (i > (approximation >> 1))?(NxReal)(i+approximation):(NxReal)i; + } + else + { + iReal = (NxReal)i; + } + NxReal Sin, Cos; + NxMath::sinCos(step * iReal, Sin, Cos); + NxVec3 insPoint = (downAxis * -Cos) + (frontAxis * Sin); + points.pushBack(insPoint + wheelAxis); + points.pushBack(insPoint - wheelAxis); + } + + NxConvexMeshDesc convexDesc; + convexDesc.numVertices = points.size(); + convexDesc.pointStrideBytes = sizeof(NxVec3); + convexDesc.points = &points[0].x; + convexDesc.flags |= shapeFlags; + //convexDesc.flags |= NX_CF_COMPUTE_CONVEX; + + // Cooking from memory + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + if(CookConvexMesh(convexDesc, buf)) + { + NxConvexShapeDesc convexShapeDesc; + convexShapeDesc.meshData = actor->getScene().getPhysicsSDK().createConvexMesh(MemoryReadBuffer(buf.data)); + convexShapeDesc.localPose.t = center; + convexShapeDesc.localPose.M.setColumn(0, NxVec3( 1, 0, 0)); + convexShapeDesc.localPose.M.setColumn(1, NxVec3( 0,-1, 0)); + convexShapeDesc.localPose.M.setColumn(2, NxVec3( 0, 0, -1)); + if(convexShapeDesc.meshData != NULL) + { + NxU32 shapeNumber = actor->getNbShapes(); + result = actor->createShape(convexShapeDesc)->isConvexMesh(); + if (!result) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); + } + //wheel->wheelConvex->userData = wheel; + } + } + + CloseCooking(); + + return result; + +} + +NxShapeDesc& pFactory::createShape(int hullType,CK3dEntity*ent,float density) +{ + + assert(ent); + float radius = ent->GetRadius(); + if (ent->GetRadius() < 0.001f ) + { + radius = 1.0f; + } + + VxVector box_s= BoxGetZero(ent); + switch(hullType) + { + + case HT_Box: + { + NxBoxShapeDesc result; + //result.setToDefault(); + result.dimensions = pMath::getFrom(box_s); + + result.density = density; + return result; + } + case HT_Sphere: + { + NxSphereShapeDesc result; + //result.setToDefault(); + result.localPose.t = NxVec3(0,radius,0); + result.radius = radius; + result.density = density; + return result; + } + } + + NxBoxShapeDesc result; + result.setToDefault(); + result.dimensions = pMath::getFrom(box_s); + return result; +} diff --git a/usr/Src/old/Core/pFactory/pFactoryTest.cpp b/usr/Src/old/Core/pFactory/pFactoryTest.cpp new file mode 100644 index 0000000..d6af632 --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryTest.cpp @@ -0,0 +1,62 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" +#include "tinyxml.h" + +#include + +NxShape*pFactory::createWheelShape1(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr) +{ + + NxWheelShape *result = NULL; + pRigidBody *body=GetPMan()->getBody(bodyReference); + + + bool assertResult = true; + iAssertWR(bodyReference && wheelReference && wheelDescr.isValid() && body && body->getActor(),"",assertResult); + if (!assertResult) + return NULL; + + NxActor *actor = body->getActor(); + + + //---------------------------------------------------------------- + // + // prepare data : + // + CKMesh *mesh = wheelReference->GetCurrentMesh(); + VxVector box_s = mesh->GetLocalBox().GetSize(); + + float radius = wheelDescr.radius.value > 0.0f ? wheelDescr.radius.value : box_s.v[wheelDescr.radius.referenceAxis] * 0.5f; + + VxQuaternion quatOffset; + VxVector posOffset; + vtAgeia::calculateOffsets(bodyReference,wheelReference,quatOffset,posOffset); + CK_ID srcID = mesh->GetID(); + + //---------------------------------------------------------------- + // + // create convex cylinder : + // + NxConvexShapeDesc shape; + bool resultAssert = true; + iAssertW(wheelDescr.convexCylinder.isValid(),wheelDescr.convexCylinder.setToDefault(),""); + iAssertW( pFactory::Instance()->_createConvexCylinderMesh(&shape,wheelDescr.convexCylinder,wheelReference),""); + + shape.localPose.M = pMath::getFrom(quatOffset); + shape.localPose.t = pMath::getFrom(posOffset); + + actor->createShape(shape)->isConvexMesh(); + +/* NxConvexShapeDesc shape; + if (!_createConvexCylinder(&shape,wheelReference)) + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); + +*/ + + + + return NULL; +} \ No newline at end of file diff --git a/usr/Src/old/Core/pFactory/pFactoryVehicle.cpp b/usr/Src/old/Core/pFactory/pFactoryVehicle.cpp new file mode 100644 index 0000000..e6efdce --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryVehicle.cpp @@ -0,0 +1,206 @@ +#include +#include "vtPhysXAll.h" + +#include "tinyxml.h" + + +pVehicle *pFactory::createVehicle(CK3dEntity *body,pVehicleDesc descr) +{ + + pVehicle *result =NULL; + + if (!body) + { + return result; + } + + pRigidBody *rBody = GetPMan()->getBody(body); + + if (!rBody) + { + return result; + } + + if (rBody->getVehicle()) + { + return rBody->getVehicle(); + } + + descr.body = rBody; + result = new pVehicle(descr); + +// result->_vehicleMotor = createVehicleMotor(*descr.getMotorDescr()); +//result->_vehicleGears = createVehicleGears(*descr.getGearDescription()); + + result->_vehicleMotor = NULL; + result->_vehicleGears = NULL; + + int wSize = result->getWheels().size(); + + result->setActor(rBody->getActor()); + rBody->setVehicle(result); + + result->initWheels(0); + + //result->control(0, true, 0, true, false); + //result->control(0, true, 0, true, false); + + + return result; + +} + + + +pVehicleGears* pFactory::createVehicleGears(pVehicleGearDesc descr) +{ + + if (!descr.isValid()) + return NULL; + pVehicleGears *gears = new pVehicleGears(); + NxI32 nbForwardGears = gears->_nbForwardGears = descr.nbForwardGears; + + memcpy(gears->_forwardGearRatios, descr.forwardGearRatios, sizeof(NxF32) * nbForwardGears); + memcpy(gears->_forwardGears, descr.forwardGears, sizeof(pLinearInterpolation) * nbForwardGears); + + gears->_curGear = 1; + + //gears->_backwardGear = gearDesc.backwardGear; + gears->_backwardGearRatio = descr.backwardGearRatio; + + return gears; + +} + +pVehicleMotor* pFactory::createVehicleMotor(pVehicleMotorDesc descr) +{ + + if (!descr.isValid()) + return NULL; + pVehicleMotor* motor = new pVehicleMotor(); + motor->_torqueCurve = descr.torqueCurve; + NxReal maxTorque = 0; + NxI32 maxTorquePos = -1; + for (NxU32 i = 0; i < motor->_torqueCurve.getSize(); i++) { + NxReal v = motor->_torqueCurve.getValueAtIndex(i); + if (v > maxTorque) { + maxTorque = v; + maxTorquePos = i; + } + } + motor->_maxTorque = maxTorque; + motor->_maxTorquePos = (float)maxTorquePos; + motor->_maxRpmToGearUp = descr.maxRpmToGearUp; + motor->_minRpmToGearDown = descr.minRpmToGearDown; + motor->_maxRpm = descr.maxRpm; + motor->_minRpm = descr.minRpm; + + motor->_rpm = 0.0f; + + return motor; + +} + +XString pFactory::_getVehicleWheelAsEnumeration(const TiXmlDocument * doc) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + + /************************************************************************/ + /* */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "wheel" ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* vSName = NULL; + vSName = sube->Attribute("name"); + if (vSName && strlen(vSName)) + { + if (result.Length()) + { + result << ","; + } + result << vSName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; +} + +XString pFactory::_getVehicleSettingsAsEnumeration(const TiXmlDocument * doc) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + /************************************************************************/ + /* */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "vehicle" ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* vSName = NULL; + vSName = sube->Attribute("name"); + if (vSName && strlen(vSName)) + { + if (result.Length()) + { + result << ","; + } + result << vSName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; + +} + + + + + + diff --git a/usr/Src/old/Core/pFactory/pFactoryWheel.cpp b/usr/Src/old/Core/pFactory/pFactoryWheel.cpp new file mode 100644 index 0000000..4d56f44 --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryWheel.cpp @@ -0,0 +1,856 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" +#include "tinyxml.h" + +#include + + +pWheel* pFactory::createWheel(CK3dEntity *bodyReference,CK3dEntity*srcReference,pWheelDescr wheelDescr,pConvexCylinderSettings convexCylinder,VxVector localPositionOffset) +{ + //---------------------------------------------------------------- + // + // main objects + // + pRigidBody *body= GetPMan()->getBody(bodyReference); + pWheel *wheel = NULL; + bool assertCondition = true; + + iAssertWR(bodyReference,"",assertCondition); + iAssertWR(body,"",assertCondition); + iAssertWR(srcReference,"",assertCondition); + + if (!assertCondition) + return NULL; + + + iAssertWR(wheelDescr.isValid(),wheelDescr.setToDefault(),assertCondition); + + //---------------------------------------------------------------- + // + // adjust wheel description data + // + iAssertW(wheelDescr.radius.isValid(),wheelDescr.radius.evaluate(srcReference),""); + if(!wheelDescr.radius.isValid()) + wheelDescr.radius.value = srcReference->GetRadius(); + + + + pObjectDescr objectDescription; + objectDescription.hullType = HT_Wheel; + objectDescription.density = 1.0f; + + objectDescription.flags = (BodyFlags)(BF_SubShape|BF_Collision); + + objectDescription.setWheel(wheelDescr); + objectDescription.mask|=OD_Wheel; + + + if(body->addCollider(objectDescription,srcReference)) + { + + NxShape*wheelShape = body->getSubShape(srcReference); + //---------------------------------------------------------------- + // + // handle wheel types + // + //if( wheelShape && wheelShape->isWheel() && wheelDescr.wheelFlags & WF_UseWheelShape) + //WF_UseWheelShape + if( wheelShape && wheelShape->isWheel() ) + { + wheel = (pWheel*)createWheel(body,wheelDescr); + ((pWheel2*)wheel)->setWheelShape((NxWheelShape*)wheelShape); + wheel->setEntID(srcReference->GetID()); + ((pSubMeshInfo*)(wheelShape->userData))->wheel = wheel; + wheel->setFlags(wheelDescr.wheelFlags); + } + } + + return wheel; + +} + +NxShape*pFactory::createWheelShape2(CK3dEntity *bodyReference,CK3dEntity*wheelReference,pWheelDescr wheelDescr) +{ + + + NxWheelShape *result = NULL; + bool assertResult = true; + pRigidBody *body=GetPMan()->getBody(bodyReference); + + iAssertWR(bodyReference && wheelReference && wheelDescr.isValid() && body ,"",assertResult); + if (!assertResult) + return NULL; + + CKMesh *mesh = wheelReference->GetCurrentMesh(); + VxVector box_s = mesh->GetLocalBox().GetSize(); + float radius = wheelDescr.radius.value > 0.0f ? wheelDescr.radius.value : box_s.v[wheelDescr.radius.referenceAxis] * 0.5f; + + VxQuaternion quatOffset; + VxVector posOffset; + vtAgeia::calculateOffsets(bodyReference,wheelReference,quatOffset,posOffset); + + CK_ID srcID = mesh->GetID(); + + + NxWheelShapeDesc shape; + shape.setToDefault(); + + shape.radius = radius; + shape.localPose.M = pMath::getFrom(quatOffset); + shape.localPose.t = pMath::getFrom(posOffset); + + float heightModifier = (wheelDescr.wheelSuspension + radius ) / wheelDescr.wheelSuspension; + shape.suspension.spring = wheelDescr.springRestitution*heightModifier; + shape.suspension.damper = wheelDescr.springDamping * heightModifier; + shape.suspension.targetValue = wheelDescr.springBias * heightModifier; + shape.suspensionTravel = wheelDescr.wheelSuspension; + shape.inverseWheelMass = wheelDescr.inverseWheelMass; + + + const pTireFunction& latFunc = wheelDescr.latFunc; + const pTireFunction& longFunc = wheelDescr.longFunc; + + + NxTireFunctionDesc lngTFD; + lngTFD.extremumSlip = longFunc.extremumSlip ; + lngTFD.extremumValue = longFunc.extremumValue; + lngTFD.asymptoteSlip = longFunc.asymptoteSlip; + lngTFD.asymptoteValue = longFunc.asymptoteValue; + lngTFD.stiffnessFactor = longFunc.stiffnessFactor; + + NxTireFunctionDesc latTFD; + latTFD.extremumSlip = latFunc.extremumSlip ; + latTFD.extremumValue = latFunc.extremumValue; + latTFD.asymptoteSlip = latFunc.asymptoteSlip; + latTFD.asymptoteValue = latFunc.asymptoteValue; + latTFD.stiffnessFactor = latFunc.stiffnessFactor; + + + shape.lateralTireForceFunction =latTFD; + shape.longitudalTireForceFunction = lngTFD; + + shape.wheelFlags =wheelDescr.wheelShapeFlags; + + result = (NxWheelShape*)body->getActor()->createShape(shape); + + + return (NxShape*)result; + +} + +NxShape *pFactory::_createWheelShape1(NxActor *actor,pWheel1 *dstWheel,pObjectDescr *descr,pWheelDescr *wheelDescr,CK3dEntity*srcReference,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + + #ifdef _DEBUG + assert(dstWheel); + assert(descr); + assert(wheelDescr); + assert(srcReference || mesh ); + #endif // _DEBUG + + NxShape *result = NULL; + + + //################################################################ + // + // some setup data + // + NxQuat rot = pMath::getFrom(localRotation); + NxVec3 pos = getFrom(localPos); + CK_ID srcID = mesh->GetID(); + + NxConvexShapeDesc shape; + if (!_createConvexCylinder(&shape,srcReference)) + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); + + shape.density = descr->density; + shape.localPose.t = pMath::getFrom(localPos); + shape.localPose.M = rot; + if (descr->skinWidth!=-1.0f) + shape.skinWidth = descr->skinWidth; + + + //################################################################ + // + // Create the convex shape : + // + dstWheel->setWheelConvex(actor->createShape(shape)->isConvexMesh()); + + //if (!_createConvexCylinder(shape,srcReference)) + // xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create convex cylinder mesh"); + + + //################################################################ + // + // Find the wheels cylinder description + + pConvexCylinderSettings cylDescr; + findSettings(cylDescr,srcReference); + cylDescr.radius.value *=0.5f; + + //################################################################ + // + // Create a joint spring for the suspension + // + + NxReal heightModifier = (wheelDescr->wheelSuspension + cylDescr.radius.value) / wheelDescr->wheelSuspension; + if (wheelDescr->wheelSuspension < 1) + heightModifier = 1.f / wheelDescr->wheelSuspension; + + NxSpringDesc wheelSpring; + wheelSpring.spring = wheelDescr->springRestitution*heightModifier; + wheelSpring.damper = wheelDescr->springDamping*heightModifier; + wheelSpring.targetValue = wheelDescr->springBias*heightModifier; + + + //################################################################ + // + // The original code creates a material here ! We skip this ! + // + + //######################### + + + //################################################################ + // + // The wheel capsule is perpendicular to the floor + // + + NxVec3 forwardAxis = getFrom(cylDescr.forwardAxis); + NxVec3 downAxis = getFrom(cylDescr.downAxis); + NxVec3 wheelAxis = getFrom(cylDescr.rightAxis); + + + NxMaterialDesc materialDesc; + materialDesc.restitution = 0.0f; + materialDesc.dynamicFriction = wheelDescr->frictionToSide; + materialDesc.staticFriction = 2.0f; + materialDesc.staticFrictionV = wheelDescr->frictionToFront*4; + materialDesc.dynamicFrictionV = wheelDescr->frictionToFront; + materialDesc.dirOfAnisotropy = forwardAxis; + materialDesc.frictionCombineMode = NX_CM_MULTIPLY; + materialDesc.flags |= NX_MF_ANISOTROPIC; + + + + dstWheel->material = actor->getScene().createMaterial(materialDesc); + + NxCapsuleShapeDesc capsuleShape; + capsuleShape.radius = cylDescr.radius.value * 0.1f; + capsuleShape.height = wheelDescr->wheelSuspension + cylDescr.radius.value; + capsuleShape.flags = NX_SWEPT_SHAPE; + + //capsuleShape.localPose.M.setColumn(0, NxVec3( 1, 0, 0)); + //capsuleShape.localPose.M.setColumn(1, NxVec3( 0,-1, 0)); + //capsuleShape.localPose.M.setColumn(2, NxVec3( 0, 0,-1)); //rotate 180 degrees around x axis to cast downward! + + capsuleShape.materialIndex = dstWheel->material->getMaterialIndex(); + + + capsuleShape.localPose.M.setColumn(0, forwardAxis); + capsuleShape.localPose.M.setColumn(1, downAxis); + capsuleShape.localPose.M.setColumn(2, wheelAxis); + if(wheelDescr->wheelSuspension >= 1) + { + capsuleShape.localPose.t = pos + downAxis*(cylDescr.radius.value); + } + else + { + capsuleShape.localPose.t = pos + (-1.0f *downAxis)*((cylDescr.radius.value + wheelDescr->wheelSuspension)*0.5f); + } + + //################################################################ + // + // Finalize + // + result = dstWheel->getWheelConvex(); + if (!capsuleShape.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Capsule shape description during wheel1 construction was invalid"); + } + + dstWheel->setWheelCapsule(actor->createShape(capsuleShape)->isCapsule()); + + + + dstWheel->_radius = cylDescr.radius.value; + dstWheel->_turnAngle = 0; + dstWheel->_turnVelocity = 0; + dstWheel->_perimeter = dstWheel->_radius * NxTwoPi; + dstWheel->_maxSuspension = wheelDescr->wheelSuspension; + dstWheel->_wheelWidth = cylDescr.height.value; + dstWheel->_maxPosition = localPos; + + dstWheel->_frictionToFront = wheelDescr->frictionToFront; + dstWheel->_frictionToSide = wheelDescr->frictionToSide; + + + NxU32 contactReportFlags = actor->getContactReportFlags(); + contactReportFlags |=NX_NOTIFY_ON_TOUCH; + actor->setContactReportFlags(contactReportFlags); + return dstWheel->getWheelCapsule(); + +} + + +pWheel *pFactory::createWheelSubShape(pRigidBody *body,CK3dEntity* subEntity,CKMesh *mesh,pObjectDescr *descr,VxVector localPos, VxQuaternion localRotation,NxShape*dstShape) +{ + //################################################################ + // + // Sanity checks + // + #ifdef _DEBUG + assert(body && subEntity && descr ); // Should never occur ! + #endif // _DEBUG + + + XString errorStr; + + //################################################################ + // + // Retrieve the wheel setting from attribute + // + int attTypeWheelSettings = GetPMan()->att_wheelDescr; + int attTypeConvexCylinderSettings = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CONVEX_CYLDINDER_WHEEL_DESCR); + + if (!subEntity->HasAttribute(attTypeWheelSettings)) + { + errorStr.Format("Object %s has been set as wheel but there is no wheel attribute attached",subEntity->GetName()); + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,errorStr.CStr()); + return NULL; + } + + + pWheelDescr *wDescr = new pWheelDescr(); + CKParameterOut *par = subEntity->GetAttributeParameter(attTypeWheelSettings); + if (par) + { + + int err = copyTo(wDescr,par); + if (!wDescr->isValid() ) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Wheel Description is invalid"); + SAFE_DELETE(wDescr); + return NULL; + } + } + + //################################################################ + // + // Construct the final wheel object basing on the type of the wheel + // + + pWheel *result = NULL; + + + //if(wDescr->wheelFlags & WF_UseWheelShape) { + + result = new pWheel2(body,wDescr); + + /*else + { + //################################################################ + // Wheel type 1 specified, check there is also a override for the convex cylinder + if (!subEntity->HasAttribute(attTypeConvexCylinderSettings)) + { + errorStr.Format("Object %s has been created with default settings for convex cylinder shape",subEntity->GetName()); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,errorStr.CStr()); + } + result = new pWheel1(body,wDescr); + }*/ + + //################################################################ + // + // Create the wheel shape + // + + + + //if(wDescr->wheelFlags & WF_UseWheelShape){ + + dstShape=_createWheelShape2(body->getActor(),descr,wDescr,subEntity,mesh,localPos,localRotation); + ((pWheel2*)result)->setWheelShape((NxWheelShape*)dstShape); +// } + /*else + { + dstShape=_createWheelShape1(body->getActor(),(pWheel1*)result,descr,wDescr,subEntity,mesh,localPos,localRotation); + }*/ + + if (!dstShape) + { + errorStr.Format("Couldn't create wheel shape for object %s",subEntity->GetName()); + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,errorStr.CStr()); + + SAFE_DELETE(wDescr); + SAFE_DELETE(result); + return NULL; + } + + + //################################################################ + // + // Finalize wheel setup + // + + result->setEntID(subEntity->GetID()); + + + return result; +} + + +pTireFunction pFactory::createTireFuncFromParameter(CKParameter *par) +{ + pTireFunction result; + result.setToDefault(); + + if (!par) + { + return result; + } + result.extremumSlip = vtTools::ParameterTools::GetValueFromParameterStruct(par,1); + result.extremumValue = vtTools::ParameterTools::GetValueFromParameterStruct(par,2); + result.asymptoteSlip = vtTools::ParameterTools::GetValueFromParameterStruct(par,3); + result.asymptoteValue= vtTools::ParameterTools::GetValueFromParameterStruct(par,4); + result.stiffnessFactor = vtTools::ParameterTools::GetValueFromParameterStruct(par,5); + + /************************************************************************/ + /* Lat Tire Func from XML ? */ + /************************************************************************/ + int xmlLinkId = vtTools::ParameterTools::GetValueFromParameterStruct(par,0); + if (xmlLinkId!=0) + { + XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,xmlLinkId ); + loadFrom(result,nodeName.CStr(),getDefaultDocument()); + if (!result.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Latitude Tire Function was incorrect, setting to default"); + result.setToDefault(); + }else{ + copyTo((CKParameterOut*)par,result); + } + } + + + if (!result.isValid()) + { + result.setToDefault(); + } + return result; +} + +int pFactory::copyTo(pWheelDescr *dst,CKParameter *src) +{ + + int result = 1; + if (!src || !dst) + { + return NULL; + } + + using namespace vtTools::ParameterTools; + dst->setToDefault(); + + + dst->wheelSuspension = GetValueFromParameterStruct(src,E_WD_SUSPENSION); + dst->springRestitution= GetValueFromParameterStruct(src,E_WD_SPRING_RES); + dst->springBias = GetValueFromParameterStruct(src,E_WD_SPRING_BIAS); + dst->springDamping= GetValueFromParameterStruct(src,E_WD_DAMP); + + dst->maxBrakeForce= GetValueFromParameterStruct(src,E_WD_MAX_BFORCE); + dst->frictionToSide= GetValueFromParameterStruct(src,E_WD_FSIDE); + dst->frictionToFront= GetValueFromParameterStruct(src,E_WD_FFRONT); + + CKParameterOut *pOld = GetParameterFromStruct(src,E_WD_INVERSE_WHEEL_MASS); + if (pOld) + { + if (pOld->GetGUID() == CKPGUID_FLOAT) + { + dst->inverseWheelMass= GetValueFromParameterStruct(src,E_WD_INVERSE_WHEEL_MASS); + } + + if (pOld->GetGUID() == CKPGUID_INT) + { + dst->wheelApproximation= GetValueFromParameterStruct(src,E_WD_INVERSE_WHEEL_MASS); + } + } + + //dst->wheelApproximation= GetValueFromParameterStruct(float,E_WD_INVERSE_WHEEL_MASS); + + dst->wheelFlags= (WheelFlags)GetValueFromParameterStruct(src,E_WD_FLAGS); + dst->wheelShapeFlags=(WheelShapeFlags) GetValueFromParameterStruct(src,E_WD_SFLAGS); + + + CKParameterOut *parLatFunc = GetParameterFromStruct(src,E_WD_LAT_FUNC); + CKParameterOut *parLongFunc = GetParameterFromStruct(src,E_WD_LONG_FUNC); + + + + /************************************************************************/ + /* XML Setup ? */ + /************************************************************************/ + int xmlLinkId= GetValueFromParameterStruct(src,E_WD_XML); + bool wIsXML=false; + bool latIsXML= false; + bool longIsXML=false; + + XString nodeName; + if ( xmlLinkId !=0 ) + { + nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_WHEEL_SETTINGS,xmlLinkId); + loadWheelDescrFromXML(*dst,nodeName.CStr(),getDefaultDocument()); + wIsXML =true; + if (!dst->isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Wheel Description was invalid"); + } + + + if (dst->latFunc.xmlLink!=0) + { + latIsXML=true; + } + + if (dst->longFunc.xmlLink!=0) + { + longIsXML=true; + } + } + + + + if (!latIsXML) + { + dst->latFunc = createTireFuncFromParameter(parLatFunc); + } + + + if (!longIsXML) + { + dst->longFunc= createTireFuncFromParameter(parLongFunc); + } + + if (wIsXML) + { + copyTo((CKParameterOut*)src,dst); + } + + + if (longIsXML) + { + copyTo(GetParameterFromStruct(src,E_WD_LONG_FUNC),dst->longFunc); + } + + if (latIsXML) + { + copyTo(GetParameterFromStruct(src,E_WD_LAT_FUNC),dst->latFunc); + } + + return result; +} + + + + + + +NxShape *pFactory::_createWheelShape2(NxActor *actor, pObjectDescr *descr, pWheelDescr *wheelDescr, CK3dEntity*srcReference,CKMesh *mesh, VxVector localPos, VxQuaternion localRotation) +{ + + NxWheelShape *result = NULL; + + if (!actor || !descr || !mesh ) + { + return result; + } + + int hType = descr->hullType; + VxVector box_s = mesh->GetLocalBox().GetSize(); + float density = descr->density; + float skinWidth = descr->skinWidth; + float radius = box_s.x*0.5f; + NxQuat rot = pMath::getFrom(localRotation); + + CK_ID srcID = mesh->GetID(); + + + NxWheelShapeDesc shape; + shape.setToDefault(); + + shape.radius = box_s.z*0.5f; + shape.density = density; + shape.localPose.M = rot; + shape.localPose.t = pMath::getFrom(localPos); + if (skinWidth!=-1.0f) + shape.skinWidth = skinWidth; + + float heightModifier = (wheelDescr->wheelSuspension + radius ) / wheelDescr->wheelSuspension; + shape.suspension.spring = wheelDescr->springRestitution*heightModifier; + shape.suspension.damper = wheelDescr->springDamping * heightModifier; + shape.suspension.targetValue = wheelDescr->springBias * heightModifier; + shape.suspensionTravel = wheelDescr->wheelSuspension; + + //shape.lateralTireForceFunction.stiffnessFactor *= wheelDescr->frictionToSide; + //shape.longitudalTireForceFunction.stiffnessFactor*=wheelDescr->frictionToFront; + shape.inverseWheelMass = wheelDescr->inverseWheelMass; + + + const pTireFunction& latFunc = wheelDescr->latFunc; + const pTireFunction& longFunc = wheelDescr->longFunc; + + + NxTireFunctionDesc lngTFD; + lngTFD.extremumSlip = longFunc.extremumSlip ; + lngTFD.extremumValue = longFunc.extremumValue; + lngTFD.asymptoteSlip = longFunc.asymptoteSlip; + lngTFD.asymptoteValue = longFunc.asymptoteValue; + lngTFD.stiffnessFactor = longFunc.stiffnessFactor; + + NxTireFunctionDesc latTFD; + latTFD.extremumSlip = latFunc.extremumSlip ; + latTFD.extremumValue = latFunc.extremumValue; + latTFD.asymptoteSlip = latFunc.asymptoteSlip; + latTFD.asymptoteValue = latFunc.asymptoteValue; + latTFD.stiffnessFactor = latFunc.stiffnessFactor; + + + shape.lateralTireForceFunction =latTFD; + shape.longitudalTireForceFunction = lngTFD; + + //wshape->setWheelFlags; + //shape.wheelFlags = wheelDescr->wheelFlags; + //shape.wheelFlags |= (NxWheelShapeFlags(NX_WF_WHEEL_AXIS_CONTACT_NORMAL)); + //shape.shapeFlags = wheelDescr->wheelShapeFlags; + shape.wheelFlags =wheelDescr->wheelShapeFlags; + + /* + if (wheelDescr->wheelFlags & (WF_Accelerated|WF_UseWheelShape) ) + { + int isValid = shape.isValid(); + + } + */ + + + + int isValid = shape.isValid(); + result = (NxWheelShape*)actor->createShape(shape); + + if (result) + { + + + //result->setWheelFlags(wheelDescr->wheelFlags); + //pWheel::getWheelFlag() + + + /* if ( & E_WF_VEHICLE_CONTROLLED ) + { + int isValid = shape.isValid(); + + } + */ + } + + + + return (NxShape*)result; + + +} + +NxShape *pFactory::createWheelShape(NxActor *actor, pObjectDescr *descr, pWheelDescr *wheelDescr, CK3dEntity*srcReference,CKMesh *mesh, VxVector localPos, VxQuaternion localRotation) +{ + +// if(wheelDescr->wheelFlags & WF_UseWheelShape){ + + return _createWheelShape2(actor,descr,wheelDescr,srcReference,mesh,localPos,localRotation); + + /*}else + return NULL;//_createWheelShape1(actor,descr,wheelDescr,srcReference,mesh,localPos,localRotation); +*/ + return NULL; + + + +} + + +pWheel*pFactory::createWheel(pRigidBody *body, pWheelDescr descr) +{ + + pWheel *result = NULL; + if (!body || !body->isValid() ) + { + return result; + } + + //if(descr.wheelFlags & WF_UseWheelShape) { + + result = new pWheel2(body,&descr); + +/* }else + { + result = new pWheel1(body,&descr); + } +*/ + + if (result) + { + result->setFlags(descr.wheelFlags); + }// + return result; +} + +XString pFactory::_getVehicleTireFunctionAsEnumeration(const TiXmlDocument * doc) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + /************************************************************************/ + /* */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "tireFunction" ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* vSName = NULL; + vSName = sube->Attribute("name"); + if (vSName && strlen(vSName)) + { + if (result.Length()) + { + result << ","; + } + result << vSName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; +} + + + +int pFactory::copyTo(pWheelDescr &dst,CKParameterOut *src) +{ + if (!src)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + //SetParameterStructureValue(dst,E_WD_SPRING_BIAS,src.,false); + + return result; + + +} + +int pFactory::copyTo(CKParameterOut *dst,const pTireFunction& src) +{ + + if (!dst)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,0,src.xmlLink,false); + SetParameterStructureValue(dst,1,src.extremumSlip,false); + SetParameterStructureValue(dst,2,src.extremumValue,false); + SetParameterStructureValue(dst,3,src.asymptoteSlip,false); + SetParameterStructureValue(dst,4,src.asymptoteValue,false); + SetParameterStructureValue(dst,5,src.stiffnessFactor,false); + + + return result; + +} + +int pFactory::copyTo(CKParameterOut *dst,pWheelDescr *src) +{ + + if (!src)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,E_WD_SPRING_BIAS,src->springBias,false); + SetParameterStructureValue(dst,E_WD_SPRING_RES,src->springRestitution,false); + SetParameterStructureValue(dst,E_WD_DAMP,src->springDamping,false); + SetParameterStructureValue(dst,E_WD_MAX_BFORCE,src->maxBrakeForce,false); + SetParameterStructureValue(dst,E_WD_FFRONT,src->frictionToFront,false); + SetParameterStructureValue(dst,E_WD_FSIDE,src->frictionToSide,false); + SetParameterStructureValue(dst,E_WD_FLAGS,src->wheelFlags,false); + SetParameterStructureValue(dst,E_WD_SFLAGS,src->wheelShapeFlags,false); + SetParameterStructureValue(dst,E_WD_INVERSE_WHEEL_MASS,src->inverseWheelMass,false); + + + return result; + +} + +int pFactory::copyTo(CKParameterOut *dst,const pWheelContactData& src) +{ + + if (!dst)return false; + using namespace vtTools::ParameterTools; + + int result = 0; + + SetParameterStructureValue(dst,E_WCD_CPOINT,src.contactPoint,false); + SetParameterStructureValue(dst,E_WCD_CNORMAL,src.contactNormal,false); + SetParameterStructureValue(dst,E_WCD_LONG_DIR,src.longitudalDirection,false); + SetParameterStructureValue(dst,E_WCD_LAT_DIR,src.lateralDirection,false); + + SetParameterStructureValue(dst,E_WCD_CONTACT_FORCE,src.contactForce,false); + + SetParameterStructureValue(dst,E_WCD_LONG_SLIP,src.longitudalSlip,false); + SetParameterStructureValue(dst,E_WCD_LAT_SLIP,src.longitudalSlip,false); + + SetParameterStructureValue(dst,E_WCD_LONG_IMPULSE,src.longitudalImpulse,false); + SetParameterStructureValue(dst,E_WCD_LAT_IMPULSE,src.longitudalImpulse,false); + + SetParameterStructureValue(dst,E_WCD_C_POS,src.contactPosition,false); + + if (src.contactEntity) + { + SetParameterStructureValue(dst,E_WCD_CONTACT_ENTITY,src.contactEntity->GetID(),false); + } + + CKParameter *materialParameter = vtTools::ParameterTools::GetParameterFromStruct(dst,E_WCD_OTHER_MATERIAL_INDEX,false); + pFactory::Instance()->copyTo((CKParameterOut*)materialParameter,src.otherMaterial); + + + return result; + +} + + +bool pFactory::loadFrom(pWheelDescr& dst,const char* nodeName) +{ + return loadWheelDescrFromXML(dst,nodeName,getDefaultDocument()); + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pFactory/pFactoryWorld.cpp b/usr/Src/old/Core/pFactory/pFactoryWorld.cpp new file mode 100644 index 0000000..92559fa --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryWorld.cpp @@ -0,0 +1,311 @@ +#include +#include "vtPhysXAll.h" + +#include "pWorldSettings.h" +#include "NxUserNotify.h" +#include "NxUserContactReport.h" +#include "pWorldCallbacks.h" + + +struct MyUserNotify : public NxUserNotify +{ +public: + + virtual bool onJointBreak(NxReal breakingImpulse, NxJoint & brokenJoint) + { + pJoint *joint = static_cast(brokenJoint.userData); + if (joint) + { + pBrokenJointEntry *entry = new pBrokenJointEntry(); + entry->joint = joint; + entry->impulse = breakingImpulse; + pWorld *world = joint->getWorld(); + if (world) + { + world->getJointFeedbackList().PushBack(entry); + + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Joint break!"); + } + } + return false; + /*if((&brokenJoint) == gMyBreakableJoint) + { cout << "BANG, The joint broke" << endl; + return true; //delete the joint + } return false; //don't delete the joint */ + } + + virtual void onSleep(NxActor **actors, NxU32 count) + { + /* + NX_ASSERT(count > 0); + while (count--) + { + NxActor *thisActor = *actors; + //Tag the actor as sleeping + size_t currentFlag = (size_t)thisActor->userData; + currentFlag |= gSleepFlag; + thisActor->userData = (void*)currentFlag; + + actors++; + }*/ + + } + + virtual void onWake(NxActor **actors, NxU32 count) + { + + if (count >0) + { + while (count--) + { + NxActor *thisActor = *actors; + if (thisActor) + { + pRigidBody *body = static_cast(thisActor->userData); + if (body) + { + body->getCollisions().Clear(); + body->getTriggers().Clear(); + + } + } + //Tag the actor as non-sleeping + /*size_t currentFlag = (size_t)thisActor->userData; + currentFlag &= ~gSleepFlag; + thisActor->userData = (void*)currentFlag;*/ + + actors++; + } + } + } + +}myNotify; + + +pWorld*pFactory::createWorld(CK3dEntity* referenceObject, pWorldSettings *worldSettings,pSleepingSettings *sleepSettings) +{ + + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + ////////////////////////////////////////////////////////////////////////// + //sanity checks : + if (!referenceObject || !GetPMan() ) + { + return NULL; + } + + + if (!getPhysicSDK()) + { + //xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"No physic sdk loaded"); + return NULL; + } + + int worldAtt = GetPMan()->att_world_object; + int surfaceAttribute = GetPMan()->att_surface_props; + + //exists ? Delete it ! + pWorld *w = GetPMan()->getWorld(referenceObject->GetID()); + if (w) + { + GetPMan()->deleteWorld(referenceObject->GetID()); + } + + //our new world : + pWorld *result = new pWorld(referenceObject); + GetPMan()->getWorlds()->InsertUnique(referenceObject,result); + + result->initUserReports(); + + + + ////////////////////////////////////////////////////////////////////////// + + //there is no world settings attribute : + if (!referenceObject->HasAttribute(worldAtt) ) + { + referenceObject->SetAttribute(worldAtt); + using namespace vtTools; + VxVector grav = worldSettings->getGravity(); + float sWith = worldSettings->getSkinWith(); + AttributeTools::SetAttributeValue(referenceObject,worldAtt,0,&grav); + AttributeTools::SetAttributeValue(referenceObject,worldAtt,1,&sWith); + } + + + if (!worldSettings) + { + worldSettings = pFactory::Instance()->createWorldSettings(XString("Default"),GetPMan()->getDefaultConfig()); + } + if (!worldSettings) + { + worldSettings = new pWorldSettings(); + } + + ////////////////////////////////////////////////////////////////////////// + //pSDK Scene creation : + + // Create a scene + NxSceneDesc sceneDesc; + sceneDesc.gravity = pMath::getFrom(worldSettings->getGravity()); + sceneDesc.upAxis = 1; + sceneDesc.flags |=NX_SF_ENABLE_ACTIVETRANSFORMS; + sceneDesc.userNotify =&myNotify; + sceneDesc.userContactReport = result->contactReport; + + NxScene *scene = NULL; + if (getPhysicSDK()) + { + scene = getPhysicSDK()->createScene(sceneDesc); + if(scene == NULL) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create scene!"); + return NULL; + } + } + + result->setScene(scene); + scene->setUserContactReport(result->contactReport); + scene->setUserTriggerReport(result->triggerReport); + + NxMaterialDesc *materialDescr = NULL; + NxMaterial *material = NULL; + if (referenceObject->HasAttribute(surfaceAttribute)) + { + materialDescr = createMaterialFromEntity(referenceObject); + material = result->getScene()->createMaterial(*materialDescr); + material->userData = (void*)GetValueFromParameterStruct(referenceObject->GetAttributeParameter(surfaceAttribute) ,E_MS_XML_TYPE); + }else{ + + if (getDefaultDocument()) + { + + materialDescr = createMaterialFromXML("Default",getDefaultDocument()); + } + + if (materialDescr) + { + material = result->getScene()->createMaterial(*materialDescr); + } + + if (!material) + { + materialDescr = new NxMaterialDesc(); + materialDescr->setToDefault(); + material = result->getScene()->getMaterialFromIndex(0); + material->loadFromDesc(*materialDescr); + } + } + + int z = (int)material->userData; + NxMaterial *zeroMaterial = result->getScene()->getMaterialFromIndex(0); + zeroMaterial->setDirOfAnisotropy(material->getDirOfAnisotropy()); + zeroMaterial->setStaticFriction(material->getStaticFriction()); + zeroMaterial->setDynamicFriction(material->getDynamicFriction()); + zeroMaterial->setStaticFrictionV(material->getStaticFrictionV()); + zeroMaterial->setDynamicFrictionV(material->getDynamicFrictionV()); + zeroMaterial->setFrictionCombineMode(material->getFrictionCombineMode()); + zeroMaterial->setRestitutionCombineMode(material->getRestitutionCombineMode()); + zeroMaterial->setFlags(material->getFlags()); + zeroMaterial->userData = material->userData; + + + + + if (!material) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create default material!"); + } + result->setDefaultMaterial(material); + + scene->userData = result; + + + //NxConstraintDominance testDom(1.0, 1.0f); + //result->getScene()->setDominanceGroupPair(1, 2,testDom ); //board - debris + + + + ////////////////////////////////////////////////////////////////////////// + //there is no world settings attribute : + /* + if (!referenceObject->HasAttribute(GetPMan()->att_sleep_settings) ) + { + referenceObject->SetAttribute(GetPMan()->att_sleep_settings); + using namespace vtTools; + AttributeTools::SetAttributeValue(referenceObject,GetPMan()->att_sleep_settings,0,&sSettings->m_SleepSteps); + AttributeTools::SetAttributeValue(referenceObject,GetPMan()->att_sleep_settings,1,&sSettings->m_AngularThresold); + AttributeTools::SetAttributeValue(referenceObject,GetPMan()->att_sleep_settings,2,&sSettings->m_LinearThresold); + AttributeTools::SetAttributeValue(referenceObject,GetPMan()->att_sleep_settings,3,&sSettings->m_AutoSleepFlag); + } + */ + + + /* + result->SleepingSettings(sSettings); + ////////////////////////////////////////////////////////////////////////// + + result->Reference(referenceObject); + + result->Init(); +*/ + + + result->_checkForDominanceConstraints(); + result->_construct(); + + + + + + + return result; + + + //return NULL; + +} +//************************************ +// Method: CreateDefaultWorld +// FullName: vtODE::pFactory::CreateDefaultWorld +// Access: public +// Returns: pWorld* +// Qualifier: +// Parameter: XString name +//************************************ +pWorld*pFactory::createDefaultWorld(XString name) +{ + + + CK3dEntity *defaultWorldFrame = createFrame("pDefaultWorld"); + pWorldSettings *wSettings = getManager()->getDefaultWorldSettings(); + + pWorld* world = createWorld(defaultWorldFrame,wSettings,NULL); + getManager()->setDefaultWorld(world); + return world; + + + + + +/* + + pSleepingSettings *sSettings = CreateSleepingSettings("Default",GetPMan()->DefaultDocument()); + pWorldSettings *wSettings = createWorldSettings("Default",GetPMan()->DefaultDocument()); + + GetPMan()->DefaultSleepingSettings(*sSettings); + GetPMan()->DefaultWorldSettings(*wSettings); + + pWorld* world = CreateWorld(defaultWorldFrame,&GetPMan()->DefaultWorldSettings(),&GetPMan()->DefaultSleepingSettings()); + GetPMan()->DefaultWorld(world); + +*/ +// return world; + + return NULL; + +} + diff --git a/usr/Src/old/Core/pFactory/pFactoryXML.cpp b/usr/Src/old/Core/pFactory/pFactoryXML.cpp new file mode 100644 index 0000000..0ae52a2 --- /dev/null +++ b/usr/Src/old/Core/pFactory/pFactoryXML.cpp @@ -0,0 +1,587 @@ +#include +#include "vtPhysXAll.h" + +#include "pSleepingSettings.h" +#include "pWorldSettings.h" + +#include "tinyxml.h" + +TiXmlDocument*pFactory::loadConfig(const char* filename) +{ + + // load and check file + char Ini[MAX_PATH]; + char drive[MAX_PATH]; + char dir[MAX_PATH]; + char szPath[MAX_PATH]; + + GetModuleFileName(NULL,szPath,_MAX_PATH); + _splitpath(szPath, drive, dir, NULL, NULL ); + sprintf(Ini,"%s%s%s",drive,dir,filename); + XString name(Ini); + name << '\0'; + + m_DefaultDocument = new TiXmlDocument(filename); + m_DefaultDocument ->LoadFile(Ini); + m_DefaultDocument ->Parse(Ini); + + if (m_DefaultDocument->Error()) + { + + delete m_DefaultDocument; + m_DefaultDocument = NULL; + + return NULL; + } + + // get the ogreode element. + TiXmlNode* node = m_DefaultDocument->FirstChild( "vtPhysics" ); + if (!node) + { + return NULL; + } + return m_DefaultDocument; + +} + +int pFactory::reloadConfig(const char *fName) +{ + + + if (! fName || !strlen(fName))return -1; + ////////////////////////////////////////Load our physic default xml document : + if (getDefaultDocument()) + { + delete m_DefaultDocument; + m_DefaultDocument = NULL; + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Deleted old default config"); + } + + TiXmlDocument * defaultDoc = loadConfig(fName); + if (!defaultDoc) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Loading default config : PhysicDefaults.xml: failed"); + setDefaultDocument(NULL); + }else + { + setDefaultDocument(defaultDoc); + } + return 1; +} + + +pRemoteDebuggerSettings pFactory::createDebuggerSettings(const TiXmlDocument * doc) +{ + + pRemoteDebuggerSettings result; + result.enabled = -1; + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if (doc) + { + + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "Debugger" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),"Default" ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + int i=0; + + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryIntAttribute("enabled",&i); + if (res == TIXML_SUCCESS) + { + result.enabled = i ; + } + + res = sube->QueryIntAttribute("port",&i); + if (res == TIXML_SUCCESS) + { + result.port = i ; + } + + ////////////////////////////////////////////////////////////////////////// + const char* host = sube->Attribute("host"); + if (strlen(host)) + { + //strcpy(result.mHost,host); + result.mHost = host; + } + return result; + } + } + } + } + } + } + } + } + return result; +} +//************************************ +// Method: GetFirstDocElement +// FullName: vtODE::pFactory::GetFirstDocElement +// Access: public +// Returns: const TiXmlElement* +// Qualifier: +// Parameter: const TiXmlElement *root +//************************************ +const TiXmlElement*pFactory::getFirstDocElement(const TiXmlElement *root) +{ + + if (!strcmp(root->Value(), "vtPhysics")) + { + return root; + } + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling()) + { + if (child->Type() == TiXmlNode::ELEMENT) + { + const TiXmlElement *res = getFirstDocElement(child->ToElement ()); + if (res) + return res; + } + } + return 0; +} +//************************************ +// Method: GetDocument +// FullName: vtPhysics::pFactory::GetDocument +// Access: public +// Returns: TiXmlDocument* +// Qualifier: +// Parameter: XString filename +//************************************ +TiXmlDocument* pFactory::getDocument(XString filename) +{ + + + XString fname(filename.Str()); + if ( fname.Length() ) + { + XString fnameTest = ResolveFileName(fname.CStr()); + if ( fnameTest.Length()) + { + TiXmlDocument* result = new TiXmlDocument(fnameTest.Str()); + result->LoadFile(fnameTest.Str()); + result->Parse(fnameTest.Str()); + + TiXmlNode* node = result->FirstChild( "vtPhysics" ); + if (!node) + { + GetPMan()->m_Context->OutputToConsoleEx("PFactory : Couldn't load Document : %s",filename.Str()); + return NULL; + }else + { + return result; + } + } + } + return NULL; +} + +//************************************ +// Method: CreateWorldSettings +// FullName: vtPhysics::pFactory::CreateWorldSettings +// Access: public +// Returns: pWorldSettings* +// Qualifier: +// Parameter: const char* nodeName +// Parameter: const char* filename +//************************************ +/*! + * \brief + * Write brief comment for createWorldSettings here. + * + * \param nodeName + * Description of parameter nodeName. + * + * \param filename + * Description of parameter filename. + * + * \returns + * Write description of return value here. + * + * \throws + * Description of criteria for throwing this exception. + * + * Write detailed description for createWorldSettings here. + * + * \remarks + * Write remarks for createWorldSettings here. + * + * \see + * Separate items with the '|' character. + */ +pWorldSettings*pFactory::createWorldSettings(const char* nodeName, const char* filename) +{ + + XString fname(filename); + XString nName(nodeName); + if ( nName.Length() && fname.Length() ) + { + pWorldSettings *result = NULL; + TiXmlDocument * document = getDocument(fname); + if (document) + { + result =createWorldSettings(nodeName,document); + if ( result) + { + delete document; + return result; + } + } + + if (document) + { + result = new pWorldSettings(); + result->setGravity(VxVector(0,-9.81,0)); + result->setSkinWith(0.02f); + return result; + } + } + return NULL; +} +//************************************ +// Method: CreateWorldSettings +// FullName: vtPhysics::pFactory::CreateWorldSettings +// Access: public +// Returns: pWorldSettings* +// Qualifier: +// Parameter: XString nodeName +// Parameter: TiXmlDocument * doc +//************************************ + +pWorldSettings* +pFactory::createWorldSettings(const XString nodeName/* = */, const TiXmlDocument * doc /* = NULL */) +{ + + pWorldSettings *result = new pWorldSettings(); + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if (doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "world" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName.CStr() ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryDoubleAttribute("SkinWith",&v); + if (res == TIXML_SUCCESS) + { + result->setSkinWith((float)v); + } + + ////////////////////////////////////////////////////////////////////////// + const char* grav = sube->Attribute("Gravity"); + VxVector vec = _str2Vec(grav); + result->setGravity(vec); + + } + } + } + } + } + } + } + } + + + //result->setGravity(VxVector(0,-9.81,0)); + //result->setSkinWith(0.02f); + + return result; +} + + +//************************************ +// Method: CreateSleepingSettings +// FullName: vtPhysics::pFactory::CreateSleepingSettings +// Access: public +// Returns: pSleepingSettings* +// Qualifier: +// Parameter: const char* nodeName +// Parameter: const char *filename +//************************************ +pSleepingSettings*pFactory::CreateSleepingSettings(const char* nodeName,const char *filename) +{ + + XString fname(filename); + XString nName(nodeName); + if ( nName.Length() && fname.Length() ) + { + TiXmlDocument * document = getDocument(fname); + if (document) + { + pSleepingSettings *result = CreateSleepingSettings(nodeName,document); + if ( result) + { + delete document; + return result; + } + } + } + return NULL; + +} + +//************************************ +// Method: CreateSleepingSettings +// FullName: vtPhysics::pFactory::CreateSleepingSettings +// Access: public +// Returns: pSleepingSettings* +// Qualifier: +// Parameter: XString nodeName +// Parameter: TiXmlDocument * doc +//************************************ +pSleepingSettings*pFactory::CreateSleepingSettings(XString nodeName/* = */, TiXmlDocument * doc /* = NULL */) +{ + pSleepingSettings *result = new pSleepingSettings(); + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if (nodeName.Length() && doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "sleepsettings" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName.CStr() ) ) + { + + ////////////////////////////////////////////////////////////////////////// + int v; + int res = element->QueryIntAttribute("SleepSteps",&v); + if (res == TIXML_SUCCESS) + { + result->SleepSteps(v); + } + ////////////////////////////////////////////////////////////////////////// + res = element->QueryIntAttribute("AutoSleepFlag",&v); + if (res == TIXML_SUCCESS) + { + result->AutoSleepFlag(v); + } + ////////////////////////////////////////////////////////////////////////// + float vF; + res = element->QueryFloatAttribute("AngularThresold",&vF); + if (res == TIXML_SUCCESS) + { + result->AngularThresold(vF); + } + ////////////////////////////////////////////////////////////////////////// + res = element->QueryFloatAttribute("LinearThresold",&vF); + if (res == TIXML_SUCCESS) + { + result->LinearThresold(vF); + } + + return result; + } + } + } + } + } + } + return result; +} + + + +XString pFactory::_getEnumDescription(const TiXmlDocument *doc, XString identifier) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), identifier.Str() ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* matName = NULL; + matName = sube->Attribute("name"); + if (matName && strlen(matName)) + { + if (result.Length()) + { + result << ","; + } + result << matName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; + +} + +XString pFactory::_getBodyXMLInternalEnumeration(const TiXmlDocument * doc) +{ + + return _getEnumDescription(doc,"Body"); + +} +XString pFactory::_getBodyXMLExternalEnumeration(const TiXmlDocument * doc) +{ + + return _getEnumDescription(doc,"Body"); + +} + +XString pFactory::_getMaterialsAsEnumeration(const TiXmlDocument * doc) +{ + + if (!doc) + { + return XString(""); + } + + XString result("None=0"); + int counter = 1; + + + /************************************************************************/ + /* try to load settings from xml : */ + /************************************************************************/ + if ( doc) + { + const TiXmlElement *root = getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + + if (!strcmp(child->Value(), "material" ) ) + { + + const TiXmlElement *sube = (const TiXmlElement*)child; + + const char* matName = NULL; + matName = sube->Attribute("name"); + if (matName && strlen(matName)) + { + if (result.Length()) + { + result << ","; + } + result << matName; + result << "=" << counter; + counter ++; + } + } + } + } + } + + return result; + +} + + +//************************************ +// Method: _str2CombineMode +// FullName: vtAgeia::pFactory::_str2CombineMode +// Access: protected +// Returns: int +// Qualifier: +// Parameter: const char*input +//************************************ +int pFactory::_str2CombineMode(const char*input) +{ + + int result = -1; + if (!strlen(input)) + { + return result; + } + + if (!strcmp(input,"AVERAGE")) + { + return 0; + } + + if (!strcmp(input,"MIN")) + { + return 1; + } + if (!strcmp(input,"MAX")) + { + return 3; + } + + if (!strcmp(input,"MULTIPLY")) + { + return 2; + } + return result; + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pFluid/pFluid.cpp b/usr/Src/old/Core/pFluid/pFluid.cpp new file mode 100644 index 0000000..7fe682c --- /dev/null +++ b/usr/Src/old/Core/pFluid/pFluid.cpp @@ -0,0 +1,348 @@ +#include +#include "vtPhysXAll.h" + +#include "pFluid.h" +#include "pFluidEmitter.h" +#include "CK3dPointCloud.h" + + +#ifdef HAS_FLUIDS + +pFluidEmitter*pFluid::createEmitter(const pFluidEmitterDesc& desc) +{ + + NxFluidEmitterDesc eDesc ; + eDesc.setToDefault(); + + pFactory::Instance()->copyToEmitterDesc(eDesc,desc); + + int valid = eDesc.isValid(); + if (!valid) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Emitter Description not Valid !"); + return NULL; + } + + CK3dEntity*entityReference = (CK3dEntity*)ctx()->GetObject(desc.entityReference); + if (!entityReference) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"You must set a reference object ID in .referenceEntity"); + return NULL; + } + + + eDesc.relPose.M.id(); + eDesc.relPose.M.rotX(-NxHalfPiF32); + eDesc.relPose.t = NxVec3(0,1.1f,0); + + ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// + + NxFluidEmitter *emitter = getFluid()->createEmitter(eDesc); + + if (!emitter) + return NULL; + + pFluidEmitter * result = new pFluidEmitter(); + result->setEmitter(emitter); + result->setFluid(this); + result->setEntityReference(entityReference->GetID()); + VxVector pos; + if (desc.frameShape) + { + desc.frameShape->GetPosition(&pos); + } + emitter->setGlobalPosition(getFrom(pos)); + emitter->userData = result; + + ////////////////////////////////////////////////////////////////////////// + // + // Render Settings : + // + + pFluidRenderSettings *rSettings = new pFluidRenderSettings(ctx(),desc.entityReference,"pFluidEmitter"); + rSettings->setToDefault(); + rSettings->setEmitter(result); + + return result; + +} + + +CK3dEntity*pFluid::getParticleObject() +{ + + CK3dEntity* result = (CK3dEntity*)ctx()->GetObject(entityID); + return result; + +} + + +void pFluid::updateVirtoolsMesh() +{ + +/* + updateCloud(); + return;*/ + //todo, move this into a small billboard rendering lib. + if (!mRenderBuffer) + { + unsigned sizeFloat = mMaxParticles * 3 * 4; + mRenderBuffer = new float[sizeFloat]; + + if (mTrackUserData) + { + mRenderBufferUserData = new float[mMaxParticles * 4 * 4]; + } + + } + + return ; + + CK3dEntity *dstEnt = getParticleObject(); + CKMesh *mesh = getParticleObject()->GetCurrentMesh(); + + if (!dstEnt || !mesh ) + { + return; + } + + if (mParticleBuffer) + { + + for (int i = 0 ; i < mesh->GetVertexCount() ; i++) + { + + pParticle *p = &mParticleBuffer[i]; + if (p) + { + VxVector v = getFrom(p->position); + VxVector outIV; + getParticleObject()->InverseTransform(&outIV,&v); + mesh->SetVertexPosition(i,&outIV); + + } + } + } + + mesh->VertexMove(); +} + +pFluid::pFluid(NxFluidDesc &desc, bool trackUserData, bool provideCollisionNormals, const VxVector& color, float particleSize) : + + mParticleBufferNum(0), + mParticleBuffer(NULL), + mFluid(NULL), + mTrackUserData(trackUserData), + mMyParticleBuffer(NULL), + mCreatedParticleIdsNum(0), + mCreatedParticleIds(NULL), + mDeletedParticleIdsNum(0), + mDeletedParticleIds(NULL), + mParticleColor(color), + mParticleSize(particleSize), + mRenderBuffer(NULL), + mRenderBufferUserData(NULL) +{ + + mMaxParticles = desc.maxParticles; + mParticleBuffer = new pParticle[mMaxParticles]; + desc.userData = this; + + entityID = 0; + + + //Setup particle write data. + NxParticleData particleData; + particleData.numParticlesPtr = &mParticleBufferNum; + particleData.bufferPos = &mParticleBuffer[0].position.x; + particleData.bufferPosByteStride = sizeof(pParticle); + particleData.bufferVel = &mParticleBuffer[0].velocity.x; + particleData.bufferVelByteStride = sizeof(pParticle); + particleData.bufferDensity = &mParticleBuffer[0].density; + particleData.bufferDensityByteStride = sizeof(pParticle); + particleData.bufferLife = &mParticleBuffer[0].lifetime; + particleData.bufferLifeByteStride = sizeof(pParticle); + particleData.bufferId = &mParticleBuffer[0].id; + particleData.bufferIdByteStride = sizeof(pParticle); + + if (provideCollisionNormals) + { + particleData.bufferCollisionNormal = &mParticleBuffer[0].collisionNormal.x; + particleData.bufferCollisionNormalByteStride = sizeof(pParticle); + } + + desc.particlesWriteData = particleData; + + //User data buffers + if (mTrackUserData) + { + //mMyParticleBuffer = new MyParticle[mMaxParticles]; + mCreatedParticleIds = new NxU32[mMaxParticles]; + mDeletedParticleIds = new NxU32[mMaxParticles]; + + //Setup id write data. + NxParticleIdData idData; + + //Creation + idData.numIdsPtr = &mCreatedParticleIdsNum; + idData.bufferId = mCreatedParticleIds; + idData.bufferIdByteStride = sizeof(NxU32); + desc.particleCreationIdWriteData = idData; + + //Deletion + idData.numIdsPtr = &mDeletedParticleIdsNum; + idData.bufferId = mDeletedParticleIds; + idData.bufferIdByteStride = sizeof(NxU32); + desc.particleDeletionIdWriteData = idData; + } + + +} + + + +pFluidDesc::pFluidDesc() +{ + + setToDefault(); +} + +void pFluidDesc::setToDefault() +{ + + maxParticles = 500; + numReserveParticles = 0; + restParticlesPerMeter = 50.0f; + restDensity = 1000.0f; + kernelRadiusMultiplier = 1.2f; + motionLimitMultiplier = 3.0f * kernelRadiusMultiplier; + collisionDistanceMultiplier = 0.1f * kernelRadiusMultiplier; + packetSizeMultiplier = 16; + stiffness = 20.0f; + viscosity = 6.0f; + surfaceTension = 0.0f; + damping = 0.0f; + fadeInTime = 0.0f; + externalAcceleration.Set(0.0f,0.0f,0.0f); + projectionPlane.set(NxVec3(0.0f, 0.0f, 1.0f), 0.0f); + restitutionForStaticShapes = 0.5f; + dynamicFrictionForStaticShapes = 0.05f; + staticFrictionForStaticShapes = 0.05f; + attractionForStaticShapes = 0.0f; + restitutionForDynamicShapes = 0.5f; + dynamicFrictionForDynamicShapes = 0.5f; + staticFrictionForDynamicShapes = 0.5f; + attractionForDynamicShapes = 0.0f; + collisionResponseCoefficient = 0.2f; + + simulationMethod = (pFluidSimulationMethod)(NX_F_SPH); + collisionMethod =(pFluidCollisionMethod)(NX_F_STATIC|NX_F_DYNAMIC); + collisionGroup = 0; + groupsMask.bits0 = 0; + groupsMask.bits1 = 0; + groupsMask.bits2 = 0; + groupsMask.bits3 = 0; + + + flags = (pFluidFlag)(NX_FF_ENABLED); + flags &= ~NX_FF_HARDWARE; + + userData = NULL; + name = NULL; + worldReference = 0 ; + +} + +bool pFluidDesc::isValid()const +{ + + if (kernelRadiusMultiplier < 1.0f) return false; + if (restDensity <= 0.0f) return false; + if (restParticlesPerMeter <= 0.0f) return false; + + if (packetSizeMultiplier < 4) return false; + if (packetSizeMultiplier & ( packetSizeMultiplier - 1 ) ) return false; + + if (motionLimitMultiplier <= 0.0f) return false; + if (motionLimitMultiplier > packetSizeMultiplier*kernelRadiusMultiplier) return false; + + if (collisionDistanceMultiplier <= 0.0f) return false; + if (collisionDistanceMultiplier > packetSizeMultiplier*kernelRadiusMultiplier) return false; + + if (stiffness <= 0.0f) return false; + if (viscosity <= 0.0f) return false; + if (surfaceTension < 0.0f) return false; + + bool isNoInteraction = (simulationMethod & NX_F_NO_PARTICLE_INTERACTION) > 0; + bool isSPH = (simulationMethod & NX_F_SPH) > 0; + bool isMixed = (simulationMethod & NX_F_MIXED_MODE) > 0; + if (!(isNoInteraction || isSPH || isMixed)) return false; + if (isNoInteraction && (isSPH || isMixed)) return false; + if (isSPH && (isNoInteraction || isMixed)) return false; + if (isMixed && (isNoInteraction || isSPH)) return false; + + if (damping < 0.0f) return false; + if (fadeInTime < 0.0f) return false; + + if (projectionPlane.normal.isZero()) return false; + + if (dynamicFrictionForDynamicShapes < 0.0f || dynamicFrictionForDynamicShapes > 1.0f) return false; + if (staticFrictionForDynamicShapes < 0.0f || staticFrictionForDynamicShapes > 1.0f) return false; + if (restitutionForDynamicShapes < 0.0f || restitutionForDynamicShapes > 1.0f) return false; + if (attractionForDynamicShapes < 0.0f) return false; + if (dynamicFrictionForStaticShapes < 0.0f || dynamicFrictionForStaticShapes > 1.0f) return false; + if (staticFrictionForStaticShapes < 0.0f || staticFrictionForStaticShapes > 1.0f) return false; + if (restitutionForStaticShapes < 0.0f || restitutionForStaticShapes > 1.0f) return false; + if (attractionForStaticShapes < 0.0f) return false; + if (collisionResponseCoefficient < 0.0f) return false; + + + if (maxParticles > 32767) return false; + if (maxParticles < 1) return false; + + if (numReserveParticles >= maxParticles) return false; + + if(collisionGroup >= 32) return false; // We only support 32 different collision groups + + return true; +} + +void pFluid::updateCloud() +{ + + CK3dPointCloud *cloud = getPointCloud(); + if (!cloud) + return; + + CKMesh *mesh = getParticleObject()->GetCurrentMesh(); + int count = mesh->GetVertexCount(); + + VxVector *points = new VxVector[count]; + if (mParticleBuffer) + { + for (int i = 0 ; i < mesh->GetVertexCount() ; i++) + { + + pParticle *p = &mParticleBuffer[i]; + if (p) + { + points[i]= getFrom(p->position); + } + } + } + + + VxVector prec(0.5,0.5,0.5); + VxVector a[10]; + + + int b = cloud->CreateFromPointList(2,a,NULL,NULL,NULL,prec); + if (b) + { + int op2=2; + op2++; + } + +} + +#endif // HAS_FLUIDS \ No newline at end of file diff --git a/usr/Src/old/Core/pFluid/pFluidEmitter.cpp b/usr/Src/old/Core/pFluid/pFluidEmitter.cpp new file mode 100644 index 0000000..0524971 --- /dev/null +++ b/usr/Src/old/Core/pFluid/pFluidEmitter.cpp @@ -0,0 +1,16 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + +#include "pFluidEmitterDesc.h" +#include "pFluidEmitter.h" + +pFluidEmitter::pFluidEmitter() +{ + mFluid = NULL; + mEmitter = NULL; + mEntityReference = 0; + mRenderSettings = NULL; +} +#endif // HAS_FLUIDS \ No newline at end of file diff --git a/usr/Src/old/Core/pFluid/pFluidEmitterDesc.cpp b/usr/Src/old/Core/pFluid/pFluidEmitterDesc.cpp new file mode 100644 index 0000000..47f186d --- /dev/null +++ b/usr/Src/old/Core/pFluid/pFluidEmitterDesc.cpp @@ -0,0 +1,53 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + +pFluidEmitterDesc::pFluidEmitterDesc() +{ + setToDefault(); +} + +pFluidEmitterDesc::~pFluidEmitterDesc() +{ +} + +void pFluidEmitterDesc::setToDefault() +{ + frameShape = NULL; + type = (pEmitterType)(NX_FE_CONSTANT_PRESSURE); + maxParticles = 0; + shape = (pEmitterShape)(NX_FE_RECTANGULAR); + dimensionX = 0.25f; + dimensionY = 0.25f; + randomAngle = 0.0f; + randomPos = VxVector(0,0,0); + fluidVelocityMagnitude = 1.0f; + rate = 100.0f; + particleLifetime = 0.0f; + repulsionCoefficient = 1.0f; + flags = (pFluidEmitterFlag)(NX_FEF_ENABLED|NX_FEF_VISUALIZATION|NX_FEF_ADD_BODY_VELOCITY); +} + +bool pFluidEmitterDesc::isValid() const +{ + + if (dimensionX < 0.0f) return false; + if (dimensionY < 0.0f) return false; + + if (randomPos.x < 0.0f) return false; + if (randomPos.y < 0.0f) return false; + if (randomPos.z < 0.0f) return false; + if (randomAngle < 0.0f) return false; + + if (!(((shape & NX_FE_ELLIPSE) > 0) ^ ((shape & NX_FE_RECTANGULAR) > 0))) return false; + if (!(((type & NX_FE_CONSTANT_FLOW_RATE) > 0) ^ ((type & NX_FE_CONSTANT_PRESSURE) > 0))) return false; + + if (rate < 0.0f) return false; + if (fluidVelocityMagnitude < 0.0f) return false; + if (particleLifetime < 0.0f) return false; + if (repulsionCoefficient < 0.0f) return false; + + return true; +} +#endif \ No newline at end of file diff --git a/usr/Src/old/Core/pFluid/pFluidRenderCB.cpp b/usr/Src/old/Core/pFluid/pFluidRenderCB.cpp new file mode 100644 index 0000000..608a86b --- /dev/null +++ b/usr/Src/old/Core/pFluid/pFluidRenderCB.cpp @@ -0,0 +1,115 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + +#include "pFluid.h" + +int RenderParticles_P(CKRenderContext *dev,CKRenderObject *obj,void *arg) +{ + CK3dEntity* ent = (CK3dEntity *)obj; + pFluid *fluid = (pFluid*)arg; + + if (!ent) + return 0; + + + + + if (!fluid) + return 0; + + + CKMesh *mesh = ent->GetCurrentMesh(); + int vCount = mesh->GetVertexCount(); + + VxDrawPrimitiveData* data = dev->GetDrawPrimitiveStructure(CKRST_DP_TR_CL_VC,vCount); + VxMatrix oldmatrix = dev->GetWorldTransformationMatrix(); + dev->SetWorldTransformationMatrix(oldmatrix*ent->GetInverseWorldMatrix()); + + // we don't let write to the ZBuffer + dev->SetTexture(NULL); + dev->SetState(VXRENDERSTATE_ZWRITEENABLE , FALSE); + dev->SetState(VXRENDERSTATE_SRCBLEND, VXBLEND_SRCALPHA); + dev->SetState(VXRENDERSTATE_DESTBLEND, VXBLEND_ONE); + dev->SetState(VXRENDERSTATE_ALPHABLENDENABLE, TRUE); + dev->SetTextureStageState(CKRST_TSS_STAGEBLEND,0,1); + + float averageSize = 1 * 2.0f; + float minSize = 4.0f; + float maxSize = 10000.0f; + + float pointScaleA = 1.0f; + float pointScaleB = 1.0f; + float pointScaleC = 1.0f; + + /************************************************************************/ + /* */ + /************************************************************************/ + + + dev->SetState(VXRENDERSTATE_SPECULARENABLE, FALSE); + dev->SetState(VXRENDERSTATE_FILLMODE, VXFILL_SOLID); + dev->SetState(VXRENDERSTATE_SHADEMODE, VXSHADE_GOURAUD); + + dev->SetTextureStageState(CKRST_TSS_TEXTUREMAPBLEND,VXTEXTUREBLEND_MODULATEALPHA); + dev->SetTextureStageState(CKRST_TSS_MAGFILTER , VXTEXTUREFILTER_LINEAR); + dev->SetTextureStageState(CKRST_TSS_MINFILTER , VXTEXTUREFILTER_LINEARMIPLINEAR); + + // States + dev->SetState(VXRENDERSTATE_WRAP0 , 0); + dev->SetState(VXRENDERSTATE_CULLMODE, VXCULL_NONE); + dev->SetState(VXRENDERSTATE_SRCBLEND, VXBLEND_SRCALPHA); + dev->SetState(VXRENDERSTATE_DESTBLEND, VXBLEND_ONE); + dev->SetState(VXRENDERSTATE_ALPHABLENDENABLE, TRUE); + dev->SetState(VXRENDERSTATE_ZWRITEENABLE , FALSE); + + dev->SetTextureStageState(CKRST_TSS_STAGEBLEND,0,1); + dev->SetTextureStageState(CKRST_TSS_TEXTURETRANSFORMFLAGS, 0); + dev->SetTextureStageState(CKRST_TSS_TEXCOORDINDEX, 0); + + dev->SetState(VXRENDERSTATE_POINTSPRITEENABLE, TRUE); + + dev->SetState(VXRENDERSTATE_POINTSIZE, *(DWORD*)&averageSize); + dev->SetState(VXRENDERSTATE_POINTSIZE_MIN,*(DWORD*)&minSize); + dev->SetState(VXRENDERSTATE_POINTSIZE_MAX,*(DWORD*)&maxSize); + dev->SetState(VXRENDERSTATE_POINTSCALEENABLE, TRUE); + + + + dev->SetState(VXRENDERSTATE_POINTSCALE_A,*(DWORD*)&pointScaleA); + dev->SetState(VXRENDERSTATE_POINTSCALE_B,*(DWORD*)&pointScaleB); + dev->SetState(VXRENDERSTATE_POINTSCALE_C,*(DWORD*)&pointScaleC); + + XPtrStrided positions(data->Positions); + XPtrStrided colors(data->Colors); + + + + pParticle *particles = fluid->getParticles(); + + for (int i = 0 ; i < vCount ; i++) + { + VxColor color; + color.Set(1.0f); + + pParticle *p = &(fluid->mParticleBuffer[i]); + VxVector posi = getFrom(p->position); + *positions = VxVector4(posi.x,posi.y,posi.z,0); + *colors = RGBAFTOCOLOR(&(color)); + // next point + //p = p->next; + + ++colors; + ++positions; + } + + + // The drawing + dev->DrawPrimitive(VX_POINTLIST,(WORD*)NULL,vCount,data); + dev->SetState(VXRENDERSTATE_ZWRITEENABLE , TRUE); + dev->SetWorldTransformationMatrix(oldmatrix); + + return 0; +} +#endif \ No newline at end of file diff --git a/usr/Src/old/Core/pFluid/pFluidRenderSettings.cpp b/usr/Src/old/Core/pFluid/pFluidRenderSettings.cpp new file mode 100644 index 0000000..c31ceaf --- /dev/null +++ b/usr/Src/old/Core/pFluid/pFluidRenderSettings.cpp @@ -0,0 +1,70 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + +#include "pFluidRenderSettings.h" + + +pFluidRenderSettings::pFluidRenderSettings(CKContext* ctx,CK_ID entity,char* name) +{ + + m_Context = ctx; + m_InteractorsFlags = 0; + + m_StartSize = 0; + m_StartSizeVar = 0; + m_EndSize = 0; + m_EndSizeVar = 0; + + m_StartColor.r = 0.6f; + m_StartColor.g = 0.6f; + m_StartColor.b = 0.8f; + m_StartColor.b = 1.0f; + m_StartColorVar.r = 0.0f; + m_StartColorVar.g = 0.0f; + m_StartColorVar.b = 0.0f; + m_StartColorVar.a = 0.0f; + m_EndColor.r = 0.0f; + m_EndColor.g = 0.0f; + m_EndColor.b = 0.0f; + m_EndColor.a = 0.0f; + m_EndColorVar.r = 0.0f; + m_EndColorVar.g = 0.0f; + m_EndColorVar.b = 0.0f; + m_EndColorVar.a = 0.0f; + m_InitialTextureFrame = 0; + m_InitialTextureFrameVariance = 0; + m_SpeedTextureFrame = 0; + m_SpeedTextureFrameVariance = 0; + m_TextureFrameCount = 0; + m_TextureFrameloop = FALSE; + m_EvolutionsFlags = 0; + m_VariancesFlags = 0; + m_InteractorsFlags = 0; + m_DeflectorsFlags = 0; + m_RenderMode = 3; + m_Behavior = NULL; + + mRenderType = PRT_Point; + + + m_Mesh = 0; + m_Entity = entity; + CK3dEntity* ent = (CK3dEntity*)m_Context->GetObject(m_Entity); + if (ent) + m_EntityBbox = ent->GetBoundingBox(TRUE); + + m_Texture = 0; + m_Group = 0; + m_MessageType = -1; + +} + + + +void pFluidRenderSettings::setToDefault() +{ + +} +#endif // HAS_FLUIDS \ No newline at end of file diff --git a/usr/Src/old/Core/pJoint/pJoint.cpp b/usr/Src/old/Core/pJoint/pJoint.cpp new file mode 100644 index 0000000..799a077 --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJoint.cpp @@ -0,0 +1,256 @@ +#include +#include "vtPhysXAll.h" + + +using namespace vtAgeia; + +int pJoint::getNbLimitPlanes() +{ + if (!getJoint()) + return -1; + + NxJoint *j = getJoint(); + j->resetLimitPlaneIterator(); + int numLimitPlanes = 0; + NxVec3 limitPoint; + if ( j->hasMoreLimitPlanes() ) + { + NxVec3 planeNormal; + NxReal planeD; + NxReal restitution; + + bool ok = true; + while ( ok ) + { + j->getNextLimitPlane( planeNormal, planeD, &restitution ); + ++numLimitPlanes; + ok = j->hasMoreLimitPlanes(); + } + } + + return numLimitPlanes; + +} + +////////////////////////////////////////////////////////////////////////// +pJointFixed::pJointFixed(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Fixed) +{ +} + +pJoint::pJoint(pRigidBody* _a,pRigidBody* _b,int _type ) : m_SolidA(_a) , m_SolidB(_b) ,m_type((JType)_type) +{ + m_vtObjectA = _a ? _a->GetVT3DObject() : NULL; + m_vtObjectB = _b ? _b->GetVT3DObject() : NULL; + + mAID = _a ? _a->GetVT3DObject()->GetID() : -1 ; + mBID = _b ? _b->GetVT3DObject()->GetID() : -1 ; + + mJoint = NULL; + m_pWorld = NULL; +} +pJointD6*pJoint::castD6Joint() +{ + + if (getJoint()) + { + if (getJoint()->isD6Joint()) + { + return static_cast(this); + } + } + return NULL; +} + + +pJointPulley* pJoint::castPulley() +{ + + + if (getJoint()) + { + if (getJoint()->isPulleyJoint()) + { + return static_cast(this); + } + } + return NULL; +} +pJointDistance* pJoint::castDistanceJoint() +{ + + + if (getJoint()) + { + if (getJoint()->isDistanceJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointBall* pJoint::castBall() +{ + + + if (getJoint()) + { + if (getJoint()->isSphericalJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointRevolute* pJoint::castRevolute() +{ + + + if (getJoint()) + { + if (getJoint()->isRevoluteJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointPrismatic* pJoint::castPrismatic() +{ + + + if (getJoint()) + { + if (getJoint()->isPrismaticJoint()) + { + return static_cast(this); + } + } + return NULL; +} +pJointCylindrical* pJoint::castCylindrical() +{ + + + if (getJoint()) + { + if (getJoint()->isCylindricalJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointPointInPlane* pJoint::castPointInPlane() +{ + if (getJoint()) + { + if (getJoint()->isPointInPlaneJoint()) + { + return static_cast(this); + } + } + return NULL; +} + +pJointPointOnLine* pJoint::castPointOnLine() +{ + if (getJoint()) + { + if (getJoint()->isPointOnLineJoint()) + { + return static_cast(this); + } + } + return NULL; +} + + + +/************************************************************************/ +/* */ +/************************************************************************/ +int pJoint::addLimitPlane(const VxVector normal, VxVector pointInPlane, float restitution/* =0.0f */) +{ + int res = -1; + if (getJoint()){ + + res = getJoint()->addLimitPlane(pMath::getFrom(normal),pMath::getFrom(pointInPlane),restitution); + + } + return res; +} +void pJoint::setLimitPoint( VxVector point,bool pointIsOnActor2/*=true*/ ) +{ + if (getJoint()){ + return getJoint()->setLimitPoint(getFrom(point),pointIsOnActor2); + } +} +void pJoint::purgeLimitPlanes(){ if (getJoint()) getJoint()->purgeLimitPlanes();} +void pJoint::resetLimitPlaneIterator(){ if (getJoint()) getJoint()->resetLimitPlaneIterator();} +int pJoint::hasMoreLimitPlanes(){ if (getJoint()) return getJoint()->hasMoreLimitPlanes(); return false;} +int pJoint::getNextLimitPlane (VxVector &planeNormal, float &planeD,float *restitution) +{ + if (getJoint()) + { + NxVec3 n; + + int k =getJoint()->getNextLimitPlane(n,planeD,restitution); + planeNormal = pMath::getFrom(n); + return k; + } + return 0; +} + + + +void pJoint::getBreakForces( float& maxForce,float& maxTorque ) +{ + if (getJoint()) + getJoint()->getBreakable(maxForce,maxTorque); +} + +void pJoint::setBreakForces( float maxForce,float maxTorque ) +{ + if (!getJoint()) + return; + + if ( maxTorque !=0.0f && maxForce != 0.0f) + getJoint()->setBreakable(maxForce,maxTorque); + + //if ( maxTorque =0.0f && maxForce = 0.0f) + // getJoint()->setBreakable(,maxTorque); + + +} + +void pJoint::setLocalAnchor0(VxVector anchor0) +{ + if (getJoint()) + { + + if(getJoint()->isRevoluteJoint()) + { + NxRevoluteJointDesc descr; + NxRevoluteJoint *joint = static_cast(getJoint()); + if (!joint)return; + joint->saveToDesc(descr); + descr.localAnchor[0] = getFrom(anchor0); + joint->loadFromDesc(descr); + + } + } +} + + + + + + +/************************************************************************/ +/* */ +/************************************************************************/ + diff --git a/usr/Src/old/Core/pJoint/pJointBall.cpp b/usr/Src/old/Core/pJoint/pJointBall.cpp new file mode 100644 index 0000000..efb7aed --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJointBall.cpp @@ -0,0 +1,227 @@ +#include +#include "vtPhysXAll.h" + +pJointBall::pJointBall(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Spherical) +{ + +} + +pJointLimit pJointBall::getSwingLimit() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pJointLimit(); + joint->saveToDesc(descr); + return pJointLimit (descr.swingLimit.hardness,descr.swingLimit.restitution,descr.swingLimit.value); +} + +pJointLimit pJointBall::getTwistHighLimit() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pJointLimit(); + joint->saveToDesc(descr); + return pJointLimit (descr.twistLimit.high.hardness,descr.twistLimit.high.restitution,descr.twistLimit.high.value); +} + +pJointLimit pJointBall::getTwistLowLimit() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pJointLimit(); + joint->saveToDesc(descr); + return pJointLimit (descr.twistLimit.low.hardness,descr.twistLimit.low.restitution,descr.twistLimit.low.value); +} + +pSpring pJointBall::getSwingSpring() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pSpring(); + joint->saveToDesc(descr); + return pSpring (descr.swingSpring.damper,descr.swingSpring.spring,descr.swingSpring.targetValue); +} +pSpring pJointBall::getTwistSpring() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pSpring(); + joint->saveToDesc(descr); + return pSpring (descr.twistSpring.damper,descr.twistSpring.spring,descr.twistSpring.targetValue); +} + +pSpring pJointBall::getJointSpring() +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return pSpring(); + joint->saveToDesc(descr); + return pSpring (descr.jointSpring.damper,descr.jointSpring.spring,descr.jointSpring.targetValue); +} +void pJointBall::enableFlag(int flag,bool enable) +{ + + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return; + joint->saveToDesc(descr); + + if (enable) + descr.flags |=flag; + else + descr.flags &=~flag; + + joint->loadFromDesc(descr); + return ; + +} +void pJointBall::setSwingLimitAxis( const VxVector& swingLimitAxis ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.swingAxis = pMath::getFrom(swingLimitAxis); + joint->loadFromDesc(descr); + +} + +void pJointBall::enableCollision( bool collision ) +{ + + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); +} + +void pJointBall::setProjectionMode(ProjectionMode mode) +{ + NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionMode = (NxJointProjectionMode)mode; + joint->loadFromDesc(descr); +} + +void pJointBall::setProjectionDistance(float distance) +{ + NxSphericalJointDesc descr; NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionDistance= distance; + joint->loadFromDesc(descr); +} + +bool pJointBall::setSwingLimit( pJointLimit limit ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + + if ( limit.hardness != 0.0f || limit.restitution != 0.0f || limit.value !=0.0f ) + { + enableFlag(NX_SJF_SWING_LIMIT_ENABLED,1); + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.swingLimit= sLimit; + joint->loadFromDesc(descr); + return true; + }else + { + enableFlag(NX_SJF_SWING_LIMIT_ENABLED,0); + } + return false; +} +bool pJointBall::setTwistHighLimit( pJointLimit limit ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + if ( limit.hardness != 0.0f || limit.restitution != 0.0f || limit.value !=0.0f ) + { + + enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,1); + + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.twistLimit.high= sLimit; + joint->loadFromDesc(descr); + return true; + } + else + { + enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,0); + } + return 1; +} +bool pJointBall::setTwistLowLimit( pJointLimit limit ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + + if ( limit.hardness != 0.0f || limit.restitution != 0.0f || limit.value !=0.0f ) + { + + enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,1); + + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.twistLimit.low= sLimit; + joint->loadFromDesc(descr); + return true; + } + else + { + enableFlag(NX_SJF_TWIST_LIMIT_ENABLED,0); + } + return 1; +} +void pJointBall::setAnchor( const VxVector& anchor ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setGlobalAnchor(pMath::getFrom(anchor)); +} + +bool pJointBall::setSwingSpring( pSpring spring ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.swingSpring= sLimit; + joint->loadFromDesc(descr); + return 1; +} +bool pJointBall::setTwistSpring( pSpring spring ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.twistSpring= sLimit; + joint->loadFromDesc(descr); + return 1; +} +bool pJointBall::setJointSpring( pSpring spring ) +{ + NxSphericalJointDesc descr; + NxSphericalJoint *joint = static_cast(getJoint()); + if (!joint)return false ; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.jointSpring= sLimit; + joint->loadFromDesc(descr); + return 1; +} diff --git a/usr/Src/old/Core/pJoint/pJointCylindrical.cpp b/usr/Src/old/Core/pJoint/pJointCylindrical.cpp new file mode 100644 index 0000000..b1daa60 --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJointCylindrical.cpp @@ -0,0 +1,43 @@ +#include +#include "vtPhysXAll.h" + +pJointCylindrical::pJointCylindrical(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Cylindrical) +{ + +} + +void pJointCylindrical::setGlobalAnchor(VxVector anchor) +{ + + + NxCylindricalJointDesc descr; + NxCylindricalJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAnchor(getFrom(anchor)); + joint->loadFromDesc(descr); +} + +void pJointCylindrical::setGlobalAxis(VxVector axis) +{ + + + NxCylindricalJointDesc descr; + NxCylindricalJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAxis(getFrom(axis)); + joint->loadFromDesc(descr); +} + +void pJointCylindrical::enableCollision(int collision) +{ + NxCylindricalJointDesc descr; + NxCylindricalJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pJoint/pJointD6.cpp b/usr/Src/old/Core/pJoint/pJointD6.cpp new file mode 100644 index 0000000..d91f143 --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJointD6.cpp @@ -0,0 +1,387 @@ +#include +#include "vtPhysXAll.h" + + +using namespace vtAgeia; + +pJointD6::pJointD6(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_D6) +{ + +} + +void pJointD6::setDriveAngularVelocity(VxVector angVel) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return; joint->saveToDesc(descr); + //joint->setDriveAngularVelocity(pMath::getFrom(angVel)); + descr.driveAngularVelocity = (pMath::getFrom(angVel)); + joint->loadFromDesc(descr); +} +////////////////////////////////////////////////////////////////////////// +void pJointD6::setDriveLinearVelocity(VxVector linVel) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + //joint->setDriveLinearVelocity(pMath::getFrom(linVel)); + descr.driveLinearVelocity = (pMath::getFrom(linVel)); + joint->loadFromDesc(descr); +} +////////////////////////////////////////////////////////////////////////// +void pJointD6::setDriveRotation(VxQuaternion rot) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setDriveOrientation(pMath::getFrom(rot)); + joint->loadFromDesc(descr); +} +////////////////////////////////////////////////////////////////////////// +void pJointD6::setDrivePosition(VxVector pos) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setDrivePosition(pMath::getFrom(pos)); + descr.drivePosition = (pMath::getFrom(pos)); + joint->loadFromDesc(descr); +} + +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getSlerpDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.slerpDrive.damping,descr.slerpDrive.spring,descr.slerpDrive.forceLimit,descr.slerpDrive.driveType.bitField); + return result; +} + +int pJointD6::setSlerpDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.slerpDrive = sdrive; + descr.flags |=NX_D6JOINT_SLERP_DRIVE; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getTwistDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.twistDrive.damping,descr.twistDrive.spring,descr.twistDrive.forceLimit,descr.twistDrive.driveType); + return result; +} + +int pJointD6::setTwistDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.twistDrive = sdrive; + + joint->loadFromDesc(descr); + return 1; +} + +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getSwingDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.swingDrive.damping,descr.swingDrive.spring,descr.swingDrive.forceLimit,descr.swingDrive.driveType); + return result; +} + +int pJointD6::setSwingDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.swingDrive = sdrive; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getZDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.zDrive.damping,descr.zDrive.spring,descr.zDrive.forceLimit,descr.zDrive.driveType); + return result; +} + +int pJointD6::setZDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.zDrive = sdrive; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getYDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.yDrive.damping,descr.yDrive.spring,descr.yDrive.forceLimit,descr.yDrive.driveType); + return result; +} + +int pJointD6::setYDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.yDrive = sdrive; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6Drive pJointD6::getXDrive() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6Drive result(descr.xDrive.damping,descr.xDrive.spring,descr.xDrive.forceLimit,descr.xDrive.driveType); + return result; +} + + +int pJointD6::setXDrive(pJD6Drive drive) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return -1 ; joint->saveToDesc(descr); + NxJointDriveDesc sdrive; sdrive.damping = drive.damping; sdrive.spring = drive.spring; sdrive.forceLimit = drive.forceLimit; sdrive.driveType=drive.driveType; descr.xDrive = sdrive; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// + + +pJD6SoftLimit pJointD6::getTwistLowLimit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.twistLimit.low.damping,descr.twistLimit.low.spring,descr.twistLimit.low.value,descr.twistLimit.low.restitution); + return result; +} + +int pJointD6::setTwistLowLimit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.twistLimit.low= sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +pJD6SoftLimit pJointD6::getTwistHighLimit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.twistLimit.high.damping,descr.twistLimit.high.spring,descr.twistLimit.high.value,descr.twistLimit.high.restitution); + return result; +} + + +int pJointD6::setTwistHighLimit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.twistLimit.high= sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// + +pJD6SoftLimit pJointD6::getSwing2Limit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.swing2Limit.damping,descr.swing2Limit.spring,descr.swing2Limit.value,descr.swing2Limit.restitution); + return result; +} + +int pJointD6::setSwing2Limit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.swing2Limit= sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// + + +pJD6SoftLimit pJointD6::getSwing1Limit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.swing1Limit.damping,descr.swing1Limit.spring,descr.swing1Limit.value,descr.swing1Limit.restitution); + return result; +} + +int pJointD6::setSwing1Limit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.swing1Limit= sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// + +pJD6SoftLimit pJointD6::getLinearLimit() +{ + NxD6JointDesc descr;NxD6Joint *joint = static_cast(getJoint());joint->saveToDesc(descr); + pJD6SoftLimit result(descr.linearLimit.damping,descr.linearLimit.spring,descr.linearLimit.value,descr.linearLimit.restitution); + return result; +} + +int pJointD6::setLinearLimit(pJD6SoftLimit limit) +{ + NxD6JointDesc descr; + NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return -1 ; + joint->saveToDesc(descr); + + NxJointLimitSoftDesc sLimit; sLimit.value = limit.value; sLimit.spring = limit.spring; sLimit.damping = limit.damping; sLimit.restitution = limit.restitution; + if (!sLimit.isValid())return -1; + descr.linearLimit = sLimit; + joint->loadFromDesc(descr); + return 1; +} +////////////////////////////////////////////////////////////////////////// +void pJointD6::setTwistMotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.twistMotion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setSwing1MotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.swing1Motion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setSwing2MotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.swing2Motion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setXMotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.xMotion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setYMotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.yMotion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +void pJointD6::setZMotionMode(D6MotionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint());if (!joint)return;joint->saveToDesc(descr); + descr.zMotion = (NxD6JointMotion)mode; + joint->loadFromDesc(descr); +} +D6MotionMode pJointD6::getTwist() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.twistMotion; +} +D6MotionMode pJointD6::getSwing1() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.swing1Motion; +} +D6MotionMode pJointD6::getSwing2() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.swing2Motion; +} +D6MotionMode pJointD6::getXMotion() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.xMotion; +} +D6MotionMode pJointD6::getYMotion() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.yMotion; +} +D6MotionMode pJointD6::getZMotion() +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); + if (!joint)return D6MM_Locked; + joint->saveToDesc(descr); + return (D6MotionMode)descr.zMotion; +} + + +void pJointD6::setGlobalAnchor(VxVector anchor) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setGlobalAnchor(pMath::getFrom(anchor)); +} +void pJointD6::setGlobalAxis(VxVector axis) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + joint->setGlobalAxis(pMath::getFrom(axis)); + //joint->setGlobalA(pMath::getFrom(anchor)); +} +void pJointD6::setRatio(float ratio) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + if (ratio!=0.0f) + { + descr.jointFlags|=NX_D6JOINT_GEAR_ENABLED; + descr.gearRatio = ratio; + }else + { + descr.jointFlags&=~NX_D6JOINT_GEAR_ENABLED; + } + joint->loadFromDesc(descr); +} + +void pJointD6::enableCollision( bool value ) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + if (value) + { + descr.jointFlags|=NX_JF_COLLISION_ENABLED; + }else + { + descr.jointFlags&=~NX_JF_COLLISION_ENABLED; + } + joint->loadFromDesc(descr); +} + +void pJointD6::setProjectionMode(ProjectionMode mode) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionMode = (NxJointProjectionMode)mode; + joint->loadFromDesc(descr); +} + +void pJointD6::setProjectionDistance(float distance) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionDistance= distance; + joint->loadFromDesc(descr); +} + +void pJointD6::setProjectionAngle(float angle) +{ + NxD6JointDesc descr; NxD6Joint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionAngle= angle; + joint->loadFromDesc(descr); +} \ No newline at end of file diff --git a/usr/Src/old/Core/pJoint/pJointDistance.cpp b/usr/Src/old/Core/pJoint/pJointDistance.cpp new file mode 100644 index 0000000..8f84792 --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJointDistance.cpp @@ -0,0 +1,140 @@ +#include +#include "vtPhysXAll.h" + +pJointDistance::pJointDistance(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Distance) +{ +} + +void pJointDistance::setMinDistance(float distance) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.minDistance=distance; + + if (distance !=0.0f) + { + descr.flags |=NX_DJF_MIN_DISTANCE_ENABLED; + }else + descr.flags &=~NX_DJF_MIN_DISTANCE_ENABLED; + + joint->loadFromDesc(descr); +} + +void pJointDistance::setMaxDistance(float distance) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.maxDistance=distance; + if (distance !=0.0f) + { + descr.flags |=NX_DJF_MAX_DISTANCE_ENABLED; + }else + descr.flags &=~NX_DJF_MAX_DISTANCE_ENABLED; + joint->loadFromDesc(descr); +} + +void pJointDistance::setLocalAnchor1(VxVector anchor) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.localAnchor[1] =getFrom(anchor); + joint->loadFromDesc(descr); +} + +void pJointDistance::setLocalAnchor0(VxVector anchor) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.localAnchor[0] =getFrom(anchor); + joint->loadFromDesc(descr); +} + +void pJointDistance::enableCollision(int collision) +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} +bool pJointDistance::setSpring( pSpring spring ) +{ + NxDistanceJointDesc descr; + NxDistanceJoint *joint = static_cast(getJoint()); + if (!joint)return false; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.spring= sLimit; + + if(spring.spring!=0.0f || spring.damper!=0.0f ) + descr.flags|=NX_DJF_SPRING_ENABLED; + else + descr.flags &=~NX_DJF_SPRING_ENABLED; + joint->loadFromDesc(descr); + + return true; +} + +VxVector pJointDistance::getLocalAnchor0() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return getFrom(descr.localAnchor[0]); +} +VxVector pJointDistance::getLocalAnchor1() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return getFrom(descr.localAnchor[1]); +} + +float pJointDistance::getMinDistance() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + + if (!joint)return -1.0f; + + joint->saveToDesc(descr); + return descr.minDistance; +} + +float pJointDistance::getMaxDistance() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + + if (!joint)return -1.0f; + + joint->saveToDesc(descr); + return descr.maxDistance; +} + +pSpring pJointDistance::getSpring() +{ + NxDistanceJointDesc descr; + NxDistanceJoint*joint = static_cast(getJoint()); + pSpring result; + if (!joint)result; + joint->saveToDesc(descr); + + result.spring = descr.spring.spring; + result.damper = descr.spring.damper; + result.targetValue = descr.spring.targetValue; + return result; +} \ No newline at end of file diff --git a/usr/Src/old/Core/pJoint/pJointPointInPlane.cpp b/usr/Src/old/Core/pJoint/pJointPointInPlane.cpp new file mode 100644 index 0000000..9a3eb16 --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJointPointInPlane.cpp @@ -0,0 +1,45 @@ +#include +#include "vtPhysXAll.h" + +pJointPointInPlane::pJointPointInPlane(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_PointInPlane) +{ + +} + +void pJointPointInPlane::setGlobalAnchor(VxVector anchor) +{ + + + NxPointInPlaneJointDesc descr; + NxPointInPlaneJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAnchor(getFrom(anchor)); + joint->loadFromDesc(descr); +} + +void pJointPointInPlane::setGlobalAxis(VxVector axis) +{ + + + NxPointInPlaneJointDesc descr; + NxPointInPlaneJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAxis(getFrom(axis)); + joint->loadFromDesc(descr); +} + + + +void pJointPointInPlane::enableCollision(int collision) +{ + NxPointInPlaneJointDesc descr; + NxPointInPlaneJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} diff --git a/usr/Src/old/Core/pJoint/pJointPointOnLine.cpp b/usr/Src/old/Core/pJoint/pJointPointOnLine.cpp new file mode 100644 index 0000000..c8a378a --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJointPointOnLine.cpp @@ -0,0 +1,38 @@ +#include +#include "vtPhysXAll.h" + +pJointPointOnLine::pJointPointOnLine(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_PointOnLine) +{ +} + +void pJointPointOnLine::setGlobalAnchor(VxVector anchor) +{ + NxPointOnLineJointDesc descr; + NxPointOnLineJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAnchor(getFrom(anchor)); + joint->loadFromDesc(descr); +} + +void pJointPointOnLine::setGlobalAxis(VxVector axis) +{ + NxPointOnLineJointDesc descr; + NxPointOnLineJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAxis(getFrom(axis)); + joint->loadFromDesc(descr); +} + +void pJointPointOnLine::enableCollision(int collision) +{ + NxPointOnLineJointDesc descr; + NxPointOnLineJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pJoint/pJointPrismatic.cpp b/usr/Src/old/Core/pJoint/pJointPrismatic.cpp new file mode 100644 index 0000000..23dc44d --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJointPrismatic.cpp @@ -0,0 +1,44 @@ +#include +#include "vtPhysXAll.h" + +pJointPrismatic::pJointPrismatic(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Prismatic) +{ + +} + + +void pJointPrismatic::setGlobalAnchor(VxVector anchor) +{ + + + NxPrismaticJointDesc descr; + NxPrismaticJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAnchor(getFrom(anchor)); + joint->loadFromDesc(descr); +} + +void pJointPrismatic::setGlobalAxis(VxVector axis) +{ + + + NxPrismaticJointDesc descr; + NxPrismaticJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.setGlobalAxis(getFrom(axis)); + joint->loadFromDesc(descr); +} + +void pJointPrismatic::enableCollision(int collision) +{ + NxPrismaticJointDesc descr; + NxPrismaticJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pJoint/pJointPulley.cpp b/usr/Src/old/Core/pJoint/pJointPulley.cpp new file mode 100644 index 0000000..b80243e --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJointPulley.cpp @@ -0,0 +1,207 @@ +#include +#include "vtPhysXAll.h" + +pJointPulley::pJointPulley(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Pulley) +{ + +} + +void pJointPulley::setLocalAnchorA(VxVector anchor) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.localAnchor[0] = pMath::getFrom(anchor); + joint->loadFromDesc(descr); +} + +VxVector pJointPulley::getLocalAnchorA() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return pMath::getFrom(descr.localAnchor[0]); +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setLocalAnchorB(VxVector anchor) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.localAnchor[1] = pMath::getFrom(anchor); + joint->loadFromDesc(descr); +} + + +VxVector pJointPulley::getLocalAnchorB() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return pMath::getFrom(descr.localAnchor[1]); +} + +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setPulleyA(VxVector pulley) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.pulley[0] = pMath::getFrom(pulley); + joint->loadFromDesc(descr); +} + +VxVector pJointPulley::getPulleyA() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return pMath::getFrom(descr.pulley[0]); +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setPulleyB(VxVector pulley) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.pulley[1] = pMath::getFrom(pulley); + joint->loadFromDesc(descr); +} +VxVector pJointPulley::getPulleyB() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return VxVector(); + joint->saveToDesc(descr); + return pMath::getFrom(descr.pulley[1]); +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setStiffness(float stiffness) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.stiffness= stiffness; + joint->loadFromDesc(descr); +} +float pJointPulley::getStiffness() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return -1.0f; + joint->saveToDesc(descr); + return descr.stiffness; +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setRatio(float ratio) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.ratio= ratio; + joint->loadFromDesc(descr); +} +float pJointPulley::getRatio() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return -1.0f; + joint->saveToDesc(descr); + return descr.ratio; +} +////////////////////////////////////////////////////////////////////////// + +void pJointPulley::setDistance(float distance) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + descr.distance= distance; + joint->loadFromDesc(descr); +} +float pJointPulley::getDistance() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return -1.0f; + joint->saveToDesc(descr); + return descr.distance; +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::setRigid( bool rigid ) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (rigid) + { + descr.flags|=NX_PJF_IS_RIGID; + }else{ + descr.flags&=~NX_PJF_IS_RIGID; + + } + joint->loadFromDesc(descr); +} +bool pJointPulley::isRigid() +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return -1.0f; + joint->saveToDesc(descr); + + return ( descr.flags & NX_PJF_IS_RIGID ); +} +////////////////////////////////////////////////////////////////////////// + + +pMotor pJointPulley::getMotor() +{ + NxPulleyJointDesc descr; + NxPulleyJoint *joint = static_cast(getJoint());joint->saveToDesc(descr); + NxMotorDesc mDescr = descr.motor; + pMotor result; + result.freeSpin = mDescr.freeSpin; + result.targetVelocity= mDescr.velTarget; + result.maximumForce = mDescr.maxForce; + return result; +} +void pJointPulley::setMotor(pMotor motor) +{ + NxPulleyJointDesc descr; + NxPulleyJoint *joint = static_cast(getJoint());joint->saveToDesc(descr); + + NxMotorDesc mDescr = descr.motor; + + if (motor.maximumForce!=0.0f && motor.targetVelocity !=0.0f ) + { + mDescr.freeSpin = motor.freeSpin; + mDescr.velTarget= motor.targetVelocity; + mDescr.maxForce= motor.maximumForce; + descr.flags |= NX_PJF_MOTOR_ENABLED; + joint->setMotor(mDescr); + descr.motor = mDescr; + }else{ + descr.flags &=~NX_PJF_MOTOR_ENABLED; + } + + int flagsNow = descr.flags; + int isValid = descr.isValid(); + + joint->loadFromDesc(descr); +} +////////////////////////////////////////////////////////////////////////// +void pJointPulley::enableCollision( bool collision ) +{ + NxPulleyJointDesc descr; + NxPulleyJoint*joint = static_cast(getJoint()); + if (!joint)return ; joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); +} diff --git a/usr/Src/old/Core/pJoint/pJointRevolute.cpp b/usr/Src/old/Core/pJoint/pJointRevolute.cpp new file mode 100644 index 0000000..72fc37b --- /dev/null +++ b/usr/Src/old/Core/pJoint/pJointRevolute.cpp @@ -0,0 +1,207 @@ +#include +#include "vtPhysXAll.h" + + +pJointRevolute::pJointRevolute(pRigidBody* _a,pRigidBody* _b) : pJoint(_a,_b,JT_Revolute) +{ + +} +bool pJointRevolute::setHighLimit(pJointLimit limit) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint *joint = static_cast(getJoint()); + if (!joint)return false; + joint->saveToDesc(descr); + + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.limit.high= sLimit; + + if (sLimit.hardness!=0.0f || sLimit.restitution!=0.0f || sLimit.value !=0.0f ) + { + descr.flags |= NX_RJF_LIMIT_ENABLED; + }else + descr.flags &=~NX_RJF_LIMIT_ENABLED; + + int v = descr.isValid(); + + + joint->loadFromDesc(descr); + return true; +} +bool pJointRevolute::setLowLimit(pJointLimit limit) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint *joint = static_cast(getJoint()); + if (!joint)return false; + joint->saveToDesc(descr); + + NxJointLimitDesc sLimit; sLimit.value = limit.value;sLimit.restitution = limit.restitution;sLimit.hardness = limit.hardness; + if (!sLimit.isValid())return false; + descr.limit.low= sLimit; + if (sLimit.hardness!=0.0f || sLimit.restitution!=0.0f || sLimit.value !=0.0f ) + { + descr.flags |= NX_RJF_LIMIT_ENABLED; + }else + descr.flags &=~NX_RJF_LIMIT_ENABLED; + + bool ret = descr.isValid(); + joint->loadFromDesc(descr); + return ret; +} + +pSpring pJointRevolute::getSpring() +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + + joint->saveToDesc(descr); + return pSpring (descr.spring.damper,descr.spring.spring,descr.spring.targetValue); + +} + +bool pJointRevolute::setSpring(pSpring spring) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + if (!joint)return false ; + joint->saveToDesc(descr); + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + descr.spring= sLimit; + + if (spring.damper!=0.0f || !spring.spring!=0.0f || !spring.targetValue !=0.0f ) + { + descr.flags |= NX_RJF_SPRING_ENABLED; + }else + descr.flags &=~NX_RJF_SPRING_ENABLED; + + + joint->loadFromDesc(descr); + return false; +} + + + +pMotor pJointRevolute::getMotor() +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + + NxMotorDesc mDescr = descr.motor; + pMotor result; + result.freeSpin = mDescr.freeSpin; + result.targetVelocity= mDescr.velTarget; + result.maximumForce = mDescr.maxForce; + return result; +} + +bool pJointRevolute::setMotor(pMotor motor) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + + NxMotorDesc mDescr = descr.motor; + + if (motor.maximumForce!=0.0f && motor.targetVelocity !=0.0f ) + { + mDescr.freeSpin = motor.freeSpin; + mDescr.velTarget= motor.targetVelocity; + mDescr.maxForce= motor.maximumForce; + descr.flags |= NX_RJF_MOTOR_ENABLED; + joint->setMotor(mDescr); + descr.motor = mDescr; + }else{ + descr.flags &=~NX_RJF_MOTOR_ENABLED; + } + joint->loadFromDesc(descr); + + return descr.isValid(); +} +void pJointRevolute::enableCollision(bool collision) +{ + + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + if (collision) + { + descr.jointFlags |= NX_JF_COLLISION_ENABLED; + }else + descr.jointFlags &= ~NX_JF_COLLISION_ENABLED; + joint->loadFromDesc(descr); + +} + + +void pJointRevolute::setGlobalAnchor(const VxVector& anchor) +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + joint->saveToDesc(descr); + //descr.setGlobalAnchor(pMath::getFrom(anchor)); + //descr.localAnchor[0] = NxVec3(0,-40,0); + // joint->loadFromDesc(descr); + + + joint->setGlobalAnchor(pMath::getFrom(anchor)); + +} + +void pJointRevolute::setGlobalAxis(const VxVector& axis) +{ + NxRevoluteJointDesc descr; + + NxRevoluteJoint*joint = static_cast(getJoint()); + //joint->saveToDesc(descr); + //descr.setGlobalAxis(pMath::getFrom(axis)); + //joint->loadFromDesc(descr); + + joint->setGlobalAxis(pMath::getFrom(axis)); +} + + +pJointLimit pJointRevolute::getHighLimit() +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + + joint->saveToDesc(descr); + return pJointLimit (descr.limit.high.hardness,descr.limit.high.restitution,descr.limit.high.value); + +} + +pJointLimit pJointRevolute::getLowLimit() +{ + NxRevoluteJointDesc descr; + NxRevoluteJoint*joint = static_cast(getJoint()); + + joint->saveToDesc(descr); + return pJointLimit (descr.limit.low.hardness,descr.limit.low.restitution,descr.limit.low.value); + +} +void pJointRevolute::setProjectionMode(ProjectionMode mode) +{ + NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionMode = (NxJointProjectionMode)mode; + joint->loadFromDesc(descr); +} + +void pJointRevolute::setProjectionDistance(float distance) +{ + NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionDistance= distance; + joint->loadFromDesc(descr); +} + +void pJointRevolute::setProjectionAngle(float angle) +{ + NxRevoluteJointDesc descr; NxRevoluteJoint *joint = static_cast(getJoint()); if (!joint)return ; joint->saveToDesc(descr); + descr.projectionAngle= angle; + int s = descr.isValid(); + joint->loadFromDesc(descr); +} \ No newline at end of file diff --git a/usr/Src/old/Core/pLogger.cpp b/usr/Src/old/Core/pLogger.cpp new file mode 100644 index 0000000..d5e3a2a --- /dev/null +++ b/usr/Src/old/Core/pLogger.cpp @@ -0,0 +1,16 @@ +#include +#include "vtPhysXAll.h" + +#include "pLogger.h" +#include "pErrorStream.h" + + +static pErrorStream gErrorStream; + +pLogger::pLogger() +{ + + mErrorStream = &gErrorStream; + +} + diff --git a/usr/Src/old/Core/pMathTools.cpp b/usr/Src/old/Core/pMathTools.cpp new file mode 100644 index 0000000..91e0378 --- /dev/null +++ b/usr/Src/old/Core/pMathTools.cpp @@ -0,0 +1,56 @@ +#include +#include "vtPhysXAll.h" + +#include "pMathTools.h" + +namespace pMath +{ + +VxQuaternion getFromStream(NxQuat source) +{ + + VxQuaternion result; + + result.x = source.x; + result.y = source.z; + result.z = source.y; + result.w = source.w; + + return result; + + +} +VxVector getFromStream(NxVec3 source) +{ + + VxVector result; + result.x = source.x; + result.y = source.z; + result.z = source.y; + return result; + +} + + +NxQuat getFrom(VxQuaternion source) +{ + NxQuat result; + result.setx(-source.x); + result.sety(-source.y); + result.setz(-source.z); + result.setw(source.w); + return result; +} + VxQuaternion getFrom(NxQuat source) +{ + + VxQuaternion result; + source.getXYZW(result.v); + result.x = -result.x; + result.z = -result.z; + result.y = -result.y; + return result; +} + +} + diff --git a/usr/Src/old/Core/pMisc.cpp b/usr/Src/old/Core/pMisc.cpp new file mode 100644 index 0000000..b8619f9 --- /dev/null +++ b/usr/Src/old/Core/pMisc.cpp @@ -0,0 +1,264 @@ +#include + +#include "NxShape.h" +#include "Nxp.h" +#include "pMisc.h" + +#include "PhysicManager.h" + +namespace vtAgeia +{ + +bool isChildOf(CK3dEntity*parent,CK3dEntity*test) +{ + + CK3dEntity* subEntity = NULL; + while (subEntity= parent->HierarchyParser(subEntity) ) + { + if (subEntity == test) + { + return true; + } + } + return false; +} + +CK3dEntity* findSimilarInSourceObject(CK3dEntity *parentOriginal,CK3dEntity* partentCopied,CK3dEntity *copiedObject,CK3dEntity*prev) +{ + + + if (!parentOriginal || !copiedObject ) + return NULL; + + if (parentOriginal->GetChildrenCount() < 1) + return NULL; + + + if ( prev && prev!=copiedObject && isChildOf(parentOriginal,prev) && !isChildOf(partentCopied,prev) ) + return prev; + + + CK3dEntity *orginalObject= (CK3dEntity*)ctx()->GetObjectByNameAndClass(copiedObject->GetName(),CKCID_3DOBJECT,prev); + if (orginalObject) + { + + //---------------------------------------------------------------- + // + // tests + // + if ( orginalObject==copiedObject ) + findSimilarInSourceObject(parentOriginal,partentCopied,copiedObject,orginalObject); + + + if ( !isChildOf(parentOriginal,orginalObject)) + findSimilarInSourceObject(parentOriginal,partentCopied,copiedObject,orginalObject); + + if( isChildOf(partentCopied,orginalObject) ) + findSimilarInSourceObject(parentOriginal,partentCopied,copiedObject,orginalObject); + + + + return orginalObject; + } + return NULL; +} + + +bool calculateOffsets(CK3dEntity*source,CK3dEntity*target,VxQuaternion &quat,VxVector& pos) +{ + if (!source && !target) + return false; + + CK3dEntity* child = NULL; + bool isChild = false; + while (child = source->HierarchyParser(child) ) + { + if (child == target ) + { + isChild = true; + } + } + + VxQuaternion refQuad2; + target->GetQuaternion(&refQuad2,source); + VxVector relPos; + target->GetPosition(&relPos,source); + + pos = relPos; + quat = refQuad2; + + return true; + +} +int getNbOfPhysicObjects(CK3dEntity *parentObject,int flags/* =0 */) +{ + #ifdef _DEBUG + assert(parentObject); + #endif // _DEBUG + + int result = 0; + //---------------------------------------------------------------- + // + // parse hierarchy + // + + CK3dEntity* subEntity = NULL; + while (subEntity= parentObject->HierarchyParser(subEntity) ) + { + + pRigidBody *body = GetPMan()->getBody(subEntity); + if (body) + result++; + } + return result; +} +int getHullTypeFromShape(NxShape *shape) +{ + + int result = - 1; + if (!shape) + { + return result; + } + + int nxType = shape->getType(); + switch (nxType) + { + case NX_SHAPE_PLANE: + return HT_Plane; + + case NX_SHAPE_BOX: + return HT_Box; + + case NX_SHAPE_SPHERE: + return HT_Sphere; + + case NX_SHAPE_CONVEX: + return HT_ConvexMesh; + + case NX_SHAPE_CAPSULE: + return HT_Capsule; + + case NX_SHAPE_MESH: + return HT_Mesh; + } + + return -1; + +} + + +int getEnumIndex(CKParameterManager* pm,CKGUID parGuide,XString enumValue) +{ + + int pType = pm->ParameterGuidToType(parGuide); + + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + + if( !strcmp(enumStruct->GetEnumDescription(i),enumValue.Str()) ) + return i; + } + } + return 0; +} + +XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide) +{ + + XString result; + int pType = pm->ParameterGuidToType(parGuide); + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + result << enumStruct->GetEnumDescription(i); + result << "="; + result << enumStruct->GetEnumValue(i); + if (i < enumStruct->GetNumEnums() -1 ) + { + result << ","; + } + } + } + return result; +} + +XString getEnumDescription(CKParameterManager* pm,CKGUID parGuide,int parameterSubIndex) +{ + + XString result="None"; + int pType = pm->ParameterGuidToType(parGuide); + CKEnumStruct *enumStruct = pm->GetEnumDescByType(pType); + if ( enumStruct ) + { + for (int i = 0 ; i < enumStruct->GetNumEnums() ; i ++ ) + { + if(i == parameterSubIndex) + { + result = enumStruct->GetEnumDescription(i); + } + } + } + return result; +} + +//************************************ +// Method: BoxGetZero +// FullName: vtAgeia::BoxGetZero +// Access: public +// Returns: VxVector +// Qualifier: +// Parameter: vt3DObject ent +//************************************ +VxVector BoxGetZero(CK3dEntity* ent) +{ + + VxVector box_s= VxVector(1,1,1); + if (ent) + { + + VxMatrix mat = ent->GetWorldMatrix(); + VxVector g; + Vx3DMatrixToEulerAngles(mat,&g.x,&g.y,&g.z); + SetEulerDirection(ent,VxVector(0,0,0)); + CKMesh *mesh = ent->GetCurrentMesh(); + + + if (mesh!=NULL) + { + box_s = mesh->GetLocalBox().GetSize(); + } + SetEulerDirection(ent,g); + } + return box_s; +} + +//************************************ +// Method: SetEulerDirection +// FullName: vtAgeia::SetEulerDirection +// Access: public +// Returns: void +// Qualifier: +// Parameter: CK3dEntity* ent +// Parameter: VxVector direction +//************************************ +void SetEulerDirection(CK3dEntity* ent,VxVector direction) +{ + + VxVector dir,up,right; + VxMatrix mat; + Vx3DMatrixFromEulerAngles(mat,direction.x,direction.y,direction.z); + dir=(VxVector)mat[2]; + up=(VxVector)mat[1]; + right=(VxVector)mat[0]; + ent->SetOrientation(&dir,&up,&right,NULL,FALSE); + +} + + +} diff --git a/usr/Src/old/Core/pRigidBody/pRigidBody.cpp b/usr/Src/old/Core/pRigidBody/pRigidBody.cpp new file mode 100644 index 0000000..7fd6a2a --- /dev/null +++ b/usr/Src/old/Core/pRigidBody/pRigidBody.cpp @@ -0,0 +1,1031 @@ +#include +#include "vtPhysXAll.h" + +#include "NXU_helper.h" // NxuStream helper functions. +#include "NXU_PhysicsInstantiator.h" + +#include "Stream.h" +#include "cooking.h" + +#include "IParameter.h" + +void pRigidBody::updateMassSettings(pMassSettings massSettings) +{ + + // Referential + CK3dEntity* massRef = (CK3dEntity*)GetPMan()->GetContext()->GetObject(massSettings.massReference); + + VxVector massLocalOut = massSettings.localPosition; + //---------------------------------------------------------------- + // + // position + // + if (XAbs(massSettings.localPosition.SquareMagnitude()) >0.0f ) + { + if (massRef) + { + VxVector tOut = massLocalOut; + massRef->Transform(&massLocalOut,&massLocalOut); + massRef->TransformVector(&tOut,&tOut,GetVT3DObject()); + getActor()->setCMassOffsetLocalPosition(getFrom(tOut)); + }else + { + getActor()->setCMassOffsetLocalPosition(getFrom(massLocalOut)); + } + } + //---------------------------------------------------------------- + // + // rotational offset : todo + // + VxMatrix mat; + Vx3DMatrixFromEulerAngles(mat,massSettings.localOrientation.x,massSettings.localOrientation.y,massSettings.localOrientation.z); + + VxQuaternion outQuat; + outQuat.FromMatrix(mat); + + VxQuaternion referenceQuat=outQuat; + if (XAbs(massSettings.localOrientation.SquareMagnitude()) >0.0f ) + { + if (massRef) + { + massRef->GetQuaternion(&referenceQuat,NULL); + getActor()->setCMassOffsetGlobalOrientation(getFrom(referenceQuat)); + }else{ + getActor()->setCMassOffsetGlobalOrientation(getFrom(outQuat)); + } + } + + //---------------------------------------------------------------- + // + // recompute mass + // + + float newDensity=massSettings.newDensity; + float totalMass =massSettings.totalMass; + + int bMassResult = 0 ; + if (newDensity!=0.0f || totalMass!=0.0f ) + { + bMassResult = getActor()->updateMassFromShapes(newDensity,totalMass); + } + + int op = bMassResult; + + +} + +int pRigidBody::_initMainShape(const pObjectDescr oDescr,NxActorDesc *actorDesc) +{ + + //---------------------------------------------------------------- + // + // Sanity Checks + // + #ifdef _DEBUG + assert(GetVT3DObject()); // has to been set before + #endif // _DEBUG + + //---------------------------------------------------------------- + // + // Collect some data + // + + VxVector box_s= BoxGetZero(GetVT3DObject()); + float density = oDescr.density; + float radius = GetVT3DObject()->GetRadius(); + + + switch(oDescr.hullType) + { + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.dimensions = pMath::getFrom(box_s)*0.5f; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc->shapes.pushBack(&shape); + + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.radius = radius; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc->shapes.pushBack(&shape); + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + + if (! (oDescr.flags & BF_Deformable) ) + { + + //xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Can not use a mesh as de"); + //return NULL; + + } + + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + + pFactory::Instance()->createMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return false; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + shape.group = oDescr.collisionGroup; + + actorDesc->shapes.pushBack(&shape); + + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + if (GetVT3DObject()->GetCurrentMesh()) + { + if (GetVT3DObject()->GetCurrentMesh()->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshs allowed, by Ageia!"); + return false; + } + }else + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); + return false; + + + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + pFactory::Instance()->createConvexMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxConvexShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + return false; + + + } + shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + + actorDesc->shapes.pushBack(&shape); + + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + CloseCooking(); + + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexCylinder: + { + NxConvexShapeDesc shape; + if (!pFactory::Instance()->_createConvexCylinder(&shape,GetVT3DObject())){ + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + return false; + } + + shape.density = density; + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc->shapes.pushBack(&shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + + NxCapsuleShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + + pCapsuleSettings cSettings; + + pFactory::Instance()->findSettings(cSettings,GetVT3DObject()); + + shape.radius = cSettings.radius > 0.0f ? cSettings.radius : box_s.v[cSettings.localRadiusAxis] * 0.5f; + shape.height = cSettings.height > 0.0f ? cSettings.height : box_s.v[cSettings.localLengthAxis] - ( 2*shape.radius) ; + } + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + // shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + actorDesc->shapes.pushBack(&shape); + break; + } + + case HT_Wheel: + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Wheel shape can be sub shape only!"); + return false; + } + } + + return true; + +} + + +/*int pRigidBody::_initMainShape(const pObjectDescr oDescr,NxActorDesc&actorDesc) +{ + + //---------------------------------------------------------------- + // + // Sanity Checks + // + #ifdef _DEBUG + assert(GetVT3DObject()); // has to been set before + #endif // _DEBUG + + //---------------------------------------------------------------- + // + // Collect some data + // + + VxVector box_s= BoxGetZero(GetVT3DObject()); + float density = oDescr.density; + float radius = GetVT3DObject()->GetRadius(); + + + switch(oDescr.hullType) + { + + ////////////////////////////////////////////////////////////////////////// + case HT_Box: + { + NxBoxShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.dimensions = pMath::getFrom(box_s)*0.5f; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc.shapes.pushBack(&shape); + + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Sphere: + { + NxSphereShapeDesc shape; + + + if (! (oDescr.flags & BF_Deformable) ) + { + shape.radius = radius; + } + + shape.density = density; + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + int oG = oDescr.collisionGroup; + shape.group = oDescr.collisionGroup; + + int k = shape.isValid(); + + actorDesc.shapes.pushBack(&shape); + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Mesh: + { + + if (! (oDescr.flags & BF_Deformable) ) + { + + //xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Can not use a mesh as de"); + //return NULL; + + } + + NxTriangleMeshDesc myMesh; + myMesh.setToDefault(); + + pFactory::Instance()->createMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxTriangleMeshShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + } + MemoryWriteBuffer buf; + + status = CookTriangleMesh(myMesh, buf); + if (!status) { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Couldn't cook mesh!"); + return false; + } + shape.meshData = GetPMan()->getPhysicsSDK()->createTriangleMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + shape.group = oDescr.collisionGroup; + + actorDesc.shapes.pushBack(&shape); + + + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + CloseCooking(); + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexMesh: + { + if (GetVT3DObject()->GetCurrentMesh()) + { + if (GetVT3DObject()->GetCurrentMesh()->GetVertexCount()>=256 ) + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Only 256 vertices for convex meshs allowed, by Ageia!"); + return false; + } + }else + { + xLogger::xLog(ELOGERROR,E_LI_AGEIA,"Object has no mesh!"); + return false; + + + } + + NxConvexMeshDesc myMesh; + myMesh.setToDefault(); + pFactory::Instance()->createConvexMesh(getWorld()->getScene(),GetVT3DObject()->GetCurrentMesh(),myMesh); + + NxConvexShapeDesc shape; + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't initiate cooking lib!"); + return false; + + } + MemoryWriteBuffer buf; + + status = CookConvexMesh(myMesh, buf); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't cook convex mesh!"); + return false; + + + } + shape.meshData = GetPMan()->getPhysicsSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + actorDesc.shapes.pushBack(&shape); + //shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + int h = shape.isValid(); + CloseCooking(); + + + if (myMesh.points) + { + delete [] myMesh.points; + } + + if (myMesh.triangles) + { + delete []myMesh.triangles; + } + + + break; + } + + ////////////////////////////////////////////////////////////////////////// + case HT_ConvexCylinder: + { + NxConvexShapeDesc shape; + if (!pFactory::Instance()->_createConvexCylinder(&shape,GetVT3DObject())){ + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + return false; + } + + shape.density = density; + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + + actorDesc.shapes.pushBack(&shape); + break; + } + ////////////////////////////////////////////////////////////////////////// + case HT_Capsule: + { + + NxCapsuleShapeDesc shape; + + if (! (oDescr.flags & BF_Deformable) ) + { + + pCapsuleSettings cSettings; + + pFactory::Instance()->findSettings(cSettings,GetVT3DObject()); + + shape.radius = cSettings.radius > 0.0f ? cSettings.radius : box_s.v[cSettings.localRadiusAxis] * 0.5f; + shape.height = cSettings.height > 0.0f ? cSettings.height : box_s.v[cSettings.localLengthAxis] - ( 2*shape.radius) ; + } + shape.density = density; + // shape.materialIndex = result->getMaterial()->getMaterialIndex(); + // shape.localPose.t = pMath::getFrom(shapeOffset); + if (oDescr.skinWidth!=-1.0f) + shape.skinWidth = oDescr.skinWidth; + actorDesc.shapes.pushBack(&shape); + break; + } + + case HT_Wheel: + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Wheel shape can be sub shape only!"); + return false; + } + } + + return true; + +} +*/ + +int pRigidBody::getNbJoints() +{ + + pWorld *wA =getWorld(); + + int result = 0 ; + + if (!wA) + { + return result; + } + + + NxU32 jointCount = wA->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + wA->getScene()->resetJointIterator(); + + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = wA->getScene()->getNextJoint(); + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == GetVT3DObject() || mJoint->GetVTEntB() == GetVT3DObject() ) + { + result++; + } + } + } + } + + return result; +} + +void pRigidBody::test() +{ + + pRigidBody *body = this; + CK3dEntity* test = (CK3dEntity*)body; + +} +void pRigidBody::readFrom(NXU::NxActorDesc *desc,int flags) +{ + + if ( desc->mHasBody ) // only for dynamic actors + { + for (NxU32 k=0; kmShapes.size(); k++) + { + NXU::NxShapeDesc *shape = desc->mShapes[k]; + NxVec3 locPos = shape->localPose.t; + NxQuat localQuad = shape->localPose.M; + } + } + +} + +float pRigidBody::getMass(CK3dEntity *shapeReference/* =NULL */) +{ + float result = 0 ; + if (getActor()) + { + result = getActor()->getMass(); + } + return result; +} +VxVector pRigidBody::getLocalPointVelocity( const VxVector& point ) const +{ + if(isValid()) + return pMath::getFrom(getActor()->getLocalPointVelocity(getFrom(point))); + return VxVector(); +} + +VxVector pRigidBody::getPointVelocity( const VxVector& point ) const +{ + if(isValid()) + return pMath::getFrom(getActor()->getPointVelocity(getFrom(point))); + return VxVector(); +} +pJoint* pRigidBody::isConnected(CK3dEntity*ent) +{ + + + pJoint *result = NULL; + pWorld *wA =getWorld(); + pWorld *wB =NULL; + pRigidBody *b = NULL; + if (!wA) + { + return NULL; + } + + if (ent) + { + b = GetPMan()->getBody(ent); + } + if (b) + { + wB = b->getWorld(); + } + + NxU32 jointCount = wA->getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + wA->getScene()->resetJointIterator(); + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = wA->getScene()->getNextJoint(); + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == GetVT3DObject() && mJoint->GetVTEntB() == ent ) + { + return mJoint; + } + if (mJoint->GetVTEntB() == GetVT3DObject() && mJoint->GetVTEntA() == ent ) + { + return mJoint; + } + } + } + } + return NULL; +} + +int pRigidBody::JGetNumJoints() +{ + int result = 0 ; + /* + OdeBodyType bid = GetOdeBody(); + if (bid) + { + dxJoint *j = NULL; + for (j=World()->World()->firstjoint; j; j=(dxJoint*)j->next) + { + pJoint *pJ = static_cast(dJointGetData(j)); + if (pJ) + { + if (pJ->GetOdeBodyA() == bid || pJ->GetOdeBodyA() == bid ) + { + result ++; + } + } + } + } + */ + return 0; +} +void pRigidBody::setLocalShapePosition(VxVector relative,CK3dEntity*shapeReference/* =NULL */) +{ + + + if(!getActor()) + return; + + NxShape *subShape = getSubShape(shapeReference); + if (subShape ) + { + subShape->setLocalPosition(getFrom(relative)); + } + + /*NxU32 nbShapes = getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; jsetLocalPosition(pMath::getFrom(relative)); + int op=2; + return; + + //getActor()->updateMassFromShapes() + } + //addShapeMesh(c,s); + } + }*/ + +} + + + + + + +pRigidBody::pRigidBody(CK3dEntity* _e,pWorld *world) : xEngineObjectAssociation(_e,_e->GetID()) , mVTObject(_e) , m_pWorld(world) +{ + + using namespace vtTools::AttributeTools; + mActor = NULL; + + context = NULL; + if (_e) + { + mEntID = _e->GetID(); + mVTObject = _e; + } + mMaterial = NULL; + mDataFlags = 0; + mMainShape = NULL; + mMaterial = NULL; + mVehicle = NULL; + mMainShape = NULL; + mActor =NULL; + mCloth = NULL; + + //mClothRecieveBuffer=NULL; + +} + + +pRigidBody::pRigidBody(CK3dEntity* _e) +{ + SetVT3DObject(_e); + if (_e){ + mEntID = _e->GetID(); + mVTObject = _e; + + } + mMaterial = NULL; + mDataFlags = 0; + mVehicle = NULL; + mMainShape = NULL; + mActor =NULL; + mVTObject = NULL; + m_pWorld = NULL; + mCloth = NULL; + mInitialDescription = NULL; + + + +} + + +void pRigidBody::addLocalForceAtLocalPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addLocalForceAtLocalPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode,wakeUp); +} +void pRigidBody::addLocalForceAtPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addLocalForceAtPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode,wakeUp); +} +void pRigidBody::addForceAtLocalPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addForceAtLocalPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode,wakeUp); +} +void pRigidBody::addForceAtPos(const VxVector& force, const VxVector& point,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addForceAtPos(pMath::getFrom(force),pMath::getFrom(point),(NxForceMode)mode); +} +void pRigidBody::addTorque(const VxVector& torque,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addTorque(pMath::getFrom(torque),(NxForceMode)mode,wakeUp); +} +void pRigidBody::addLocalTorque(const VxVector& torque,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addLocalTorque(pMath::getFrom(torque),(NxForceMode)mode); +} + +void pRigidBody::addLocalForce(const VxVector& force,ForceMode mode,bool wakeUp) +{ + if(isValid()) + getActor()->addLocalForce(pMath::getFrom(force),(NxForceMode)mode,wakeUp); +} + +void pRigidBody::addForce( const VxVector& force,ForceMode mode/*=E_FM_FORCE*/,bool wakeUp/*=true*/ ) +{ + if(isValid()) + getActor()->addForce(pMath::getFrom(force),(NxForceMode)mode,wakeUp); +} + + +void pRigidBody::setLinearMomentum( const VxVector& linMoment ) +{ if(isValid()) getActor()->setLinearMomentum(pMath::getFrom(linMoment)); } +void pRigidBody::setAngularMomentum( const VxVector& angMoment ) +{ + if(isValid()) + getActor()->setAngularMomentum(pMath::getFrom(angMoment)); +} +VxVector pRigidBody::getAngularMomentum() const +{ + if(isValid()) + return pMath::getFrom(getActor()->getAngularMomentum()); + return VxVector(); +} + +float pRigidBody::getAngularDamping() const +{ + if(isValid()) + return getActor()->getAngularDamping(); + return 0.0f; +} +float pRigidBody::getLinearDamping() const +{ + if(isValid()) + return getActor()->getLinearDamping(); + return 0.0f; +} +VxVector pRigidBody::getLinearMomentum()const{ + if(isValid()) + return pMath::getFrom(getActor()->getLinearMomentum()); + return VxVector(); +} +void pRigidBody::setPosition(const VxVector& pos,CK3dEntity *subShapeReference) +{ + if(isValid()){ + + + NxShape *subShape = getSubShape(subShapeReference); + if (subShape == getMainShape() ) + { + if (!isKinematic()) + { + getActor()->setGlobalPosition(pMath::getFrom(pos)); + + }else{ + getActor()->moveGlobalPosition(pMath::getFrom(pos)); + + } + }else{ + if (subShape) + { + subShape->setGlobalPosition(getFrom(pos)); + } + } + } +} + +void pRigidBody::setRotation(const VxQuaternion& rot,CK3dEntity *subShapeReference) +{ + if(isValid()) + { + NxShape *subShape = getSubShape(subShapeReference); + if (subShape == getMainShape() ) + { + getActor()->setGlobalOrientation(pMath::getFrom(rot)); + }else + { + if (subShape) + { + subShape->setGlobalOrientation(getFrom(rot)); + } + } + } +} +float pRigidBody::getMaxAngularSpeed() const +{ + if(isValid())return getActor()->getMaxAngularVelocity(); + return 0.0f; +} +void pRigidBody::setMaxAngularSpeed(float val) { if(isValid())getActor()->setMaxAngularVelocity(val); } +VxVector pRigidBody::getLinearVelocity() const{ return pMath::getFrom(getActor()->getLinearVelocity());} +VxVector pRigidBody::getAngularVelocity() const{ return pMath::getFrom(getActor()->getAngularVelocity());} +void pRigidBody::setLinearVelocity( const VxVector& linVel ) +{ if(isValid()) + getActor()->setLinearVelocity(pMath::getFrom(linVel)); +} +void pRigidBody::setAngularVelocity( const VxVector& angVel ) +{ + if(isValid()) + getActor()->setAngularVelocity(pMath::getFrom(angVel)); +} + +void pRigidBody::setAngularDamping(float scale) +{ + + if (getActor() && getActor()->isDynamic()) + { + getActor()->setAngularDamping(scale); + } +} +void pRigidBody::setLinearDamping(float scale) +{ + + if (getActor() && getActor()->isDynamic()) + { + getActor()->setLinearDamping(scale); + } + +} + + +void pRigidBody::setCMassOffsetLocalPosition(VxVector offset) +{ + if (getActor()) + { + getActor()->setCMassOffsetLocalPosition( getFrom(offset) ); + } +} + +void pRigidBody::translateLocalShapePosition(VxVector vec) +{ + + if (getActor()) + { + + if (getMainShape()) + { + NxVec3 currentPos = getMainShape()->getLocalPosition(); + getMainShape()->setLocalPosition( currentPos + getFrom(vec)); + } + } +} + +pJoint* pRigidBody::isConnected(CK3dEntity*ent,int type) +{ + /* + pJoint *result = NULL; + + if ( GetVT3DObject()!=ent) + { + pRigidBody *b = GetPMan()->getBody(ent); + + OdeBodyType abid = GetOdeBody(); + OdeBodyType bbid = NULL; + + if (b) + { + bbid = b->GetOdeBody(); + } + + dxJoint *j = NULL; + for (j=World()->World()->firstjoint; j; j=(dxJoint*)j->next) + { + pJoint *pJ = static_cast(dJointGetData(j)); + if (pJ) + { + + if (!bbid) + { + if (dJointGetType(j) ==dJointTypeFixed ) + { + if (pJ->GetOdeBodyA()==abid) + { + return pJ; + } + } + } + + if ( pJ->GetOdeBodyA()==abid && dJointGetType(j) == type) + { + if (pJ->GetOdeBodyB()==bbid ) + { + return pJ; + } + } + + if ( pJ->GetOdeBodyA()==bbid && dJointGetType(j) == type) + { + if (pJ->GetOdeBodyB()==abid ) + { + return pJ; + } + } + } + } + } + return result; + */ + return NULL; +} + +void pRigidBody::SetVT3DObject(CK3dEntity* _obj) +{ mEntID = _obj->GetID(); mVTObject=_obj;} + +CK3dEntity*pRigidBody::GetVT3DObject() +{ return mVTObject; } \ No newline at end of file diff --git a/usr/Src/old/Core/pRigidBody/pRigidBodyCollision.cpp b/usr/Src/old/Core/pRigidBody/pRigidBodyCollision.cpp new file mode 100644 index 0000000..2aafb4a --- /dev/null +++ b/usr/Src/old/Core/pRigidBody/pRigidBodyCollision.cpp @@ -0,0 +1,354 @@ +#include +#include "vtPhysXAll.h" + +#include "Stream.h" +#include "cooking.h" +#include "IParameter.h" + + +bool pFactory::_createConvexCylinder(NxConvexShapeDesc* shape, + CK3dEntity*dstBodyReference, + pObjectDescr *oDescr) +{ + + + #ifdef _DEBUG + assert(dstBodyReference); // <- should never happen ! + #endif // _DEBUG + + bool result = false; + + pConvexCylinderSettings cSettingsZero; + + pConvexCylinderSettings &cSettings = cSettingsZero; + + if (oDescr ) + { + if( (oDescr->mask & OD_ConvexCylinder) ) + cSettings = oDescr->convexCylinder; + }else + { + findSettings(cSettings,dstBodyReference); + } + + + cSettings.radius.value *=0.5f; + cSettings.height.value *=0.5f; + + NxArray points; + NxVec3 center(0,0,0); + + NxVec3 frontAxis = getFrom(cSettings.forwardAxis); // = wheelDesc->downAxis.cross(wheelDesc->wheelAxis); + NxVec3 downAxis = getFrom(cSettings.downAxis);//downAxis *=-1.0; // = wheelDesc->downAxis; + NxVec3 wheelAxis = getFrom(cSettings.rightAxis); // = wheelDesc->wheelAxis; + + + //frontAxis.normalize(); + frontAxis *= cSettings.radius.value; + //downAxis.normalize(); + downAxis *= cSettings.radius.value; + //wheelAxis.normalize(); + wheelAxis *= cSettings.height.value; + + NxReal step; + + if(cSettings.buildLowerHalfOnly) + { + if((cSettings.approximation& 0x1) == 0) + cSettings.approximation++; + + step = (NxReal)(NxTwoPi) / (NxReal)(cSettings.approximation*2); + } + else + { + step = (NxReal)(NxTwoPi) / (NxReal)(cSettings.approximation); + } + for(NxU32 i = 0; i < cSettings.approximation; i++) + { + NxReal iReal; + if(cSettings.buildLowerHalfOnly) + { + iReal = (i > (cSettings.approximation >> 1))?(NxReal)(i+cSettings.approximation):(NxReal)i; + } + else + { + iReal = (NxReal)i; + } + NxReal Sin, Cos; + NxMath::sinCos(step * iReal, Sin, Cos); + NxVec3 insPoint = (downAxis * -Cos) + (frontAxis * Sin); + points.pushBack(insPoint + wheelAxis); + points.pushBack(insPoint - wheelAxis); + } + + NxConvexMeshDesc convexDesc; + convexDesc.numVertices = points.size(); + convexDesc.pointStrideBytes = sizeof(NxVec3); + convexDesc.points = &points[0].x; + + int cf = CF_ComputeConvex; + cf |= cSettings.convexFlags; + convexDesc.flags |= cf; + + // Cooking from memory + bool status = InitCooking(); + if (!status) { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't initiate cooking lib!"); + return NULL; + } + MemoryWriteBuffer buf; + int s = convexDesc.isValid(); + if(CookConvexMesh(convexDesc, buf)) + { + //NxConvexShapeDesc convexShapeDesc; + + shape->meshData = getPhysicSDK()->createConvexMesh(MemoryReadBuffer(buf.data)); + shape->localPose.t = center; + shape->localPose.M.setColumn(0, NxVec3( 1, 0, 0)); + shape->localPose.M.setColumn(1, NxVec3( 0,-1, 0)); + shape->localPose.M.setColumn(2, NxVec3( 0, 0, -1)); + if(shape->meshData != NULL) + { + result = true; + // NxU32 shapeNumber = actor->getNbShapes(); + // result = actor->createShape(convexShapeDesc)->isConvexMesh(); + // if (!result) { + // xLogger::xLog(XL_START,ELOGERROR,E_LI_AGEIA,"Couldn't create convex cylinder mesh"); + // } + //wheel->wheelConvex->userData = wheel; + } + } + CloseCooking(); + return result; +} + +void pRigidBody::updateCollisionSettings(pCollisionSettings collision,CK3dEntity*shapeReference/* =NULL */) +{ + + if (shapeReference==NULL) + assert (getMainShape()); + + NxShape *shape = getSubShape(shapeReference); + if (shape) + { + //---------------------------------------------------------------- + // + // Update groups mask + // + NxGroupsMask mask1; + + mask1.bits0 = collision.groupsMask.bits0; + mask1.bits1 = collision.groupsMask.bits1; + mask1.bits2 = collision.groupsMask.bits2; + mask1.bits3 = collision.groupsMask.bits3; + + shape->setGroupsMask(mask1); + + //---------------------------------------------------------------- + // + // Collisions group + // + shape->setGroup(collision.collisionGroup); + + //---------------------------------------------------------------- + // + // Skin Width + // + shape->setSkinWidth(collision.skinWidth); + } +} + +void pRigidBody::updateCollisionSettings(const pObjectDescr oDescr,CK3dEntity*shapeReference/* =NULL */) +{ + + int v = oDescr.version; + assert(oDescr.version == pObjectDescr::E_OD_VERSION::OD_DECR_V1); + + if (shapeReference==NULL) + assert (getMainShape()); + + NxShape *shape = getSubShape(shapeReference); + if (shape) + { + //---------------------------------------------------------------- + // + // Update groups mask + // + NxGroupsMask mask1; + + mask1.bits0 = oDescr.groupsMask.bits0; + mask1.bits1 = oDescr.groupsMask.bits1; + mask1.bits2 = oDescr.groupsMask.bits2; + mask1.bits3 = oDescr.groupsMask.bits3; + + shape->setGroupsMask(mask1); + + //---------------------------------------------------------------- + // + // Collisions group + // + shape->setGroup(oDescr.collisionGroup); + + //---------------------------------------------------------------- + // + // Skin Width + // + shape->setSkinWidth(oDescr.skinWidth); + + + + + //---------------------------------------------------------------- + // + // CCD Setup : + // + if (oDescr.ccdMeshReference) + { + + NxCCDSkeleton *skeleton = NULL; + if (oDescr.ccdFlags && CCD_Shared && GetPMan()->GetContext()->GetObject(oDescr.ccdMeshReference) ) + skeleton = GetPMan()->getCCDSkeleton(((CKBeObject*)(GetPMan()->GetContext()->GetObject(oDescr.ccdMeshReference)))); + + if (skeleton == NULL ) + skeleton = pFactory::Instance()->createCCDSkeleton(shapeReference,oDescr.ccdFlags); + + XString errorString; + + if (!skeleton){ + errorString.Format("Creation of CCD skeleton for %s failed!",GetVT3DObject()->GetName()); + xLogger::xLog(ELOGERROR,E_LI_MANAGER,errorString.Str()); + return; + } + + shape->setCCDSkeleton(skeleton); + + //---------------------------------------------------------------- + // + // update sub mesh info : + // + + pSubMeshInfo *sInfo = static_cast(shape->userData); + if (sInfo){ + sInfo->ccdReference = oDescr.ccdMeshReference; + sInfo->ccdSkeleton = skeleton; + } + + //---------------------------------------------------------------- + // + // update actors ccd motion threshold + // + if(getActor()) + getActor()->setCCDMotionThreshold(oDescr.ccdMotionThresold); + + + //NX_SF_DYNAMIC_DYNAMIC_CCD + + + //---------------------------------------------------------------- + // + // Check we have CCD enabled at all, if not then produce warning + // + + NxPhysicsSDK *sdk = GetPMan()->getPhysicsSDK(); + if (sdk) + { + float ccdParameter = sdk->getParameter(NX_CONTINUOUS_CD); + if (ccdParameter < 0.5f) + { + errorString.Format("CCD Skeleton for %s created successfully but CCD is not enabled.\n Please goto Variable Manager and set ´Continues Collision Detection´ to 1.0f",GetVT3DObject()); + xLogger::xLog(ELOGWARNING,E_LI_MANAGER,errorString.Str()); + } + } + + + } + } + + +} + +int pRigidBody::handleContactPair(NxContactPair* pair,int shapeIndex) +{ + + handleContactPairWheel(pair,shapeIndex); + + return 0; +} + + +int pRigidBody::handleContactPairWheel(NxContactPair* pair,int shapeIndex) +{ + if (!hasWheels()) + return 0; + + NxContactStreamIterator i(pair->stream); + + while(i.goNextPair()) + { + NxShape * s = i.getShape(shapeIndex); + + while(i.goNextPatch()) + { + const NxVec3& contactNormal = i.getPatchNormal(); + + while(i.goNextPoint()) + { + + const NxVec3& contactPoint = i.getPoint(); + + //assuming front wheel drive we need to apply a force at the wheels. + if (s->is(NX_SHAPE_CAPSULE) && s->userData != NULL) + { + //assuming only the wheels of the car are capsules, otherwise we need more checks. + //this branch can't be pulled out of loops because we have to do a full iteration through the stream + + NxQuat local2global = s->getActor().getGlobalOrientationQuat(); + + pSubMeshInfo *sInfo = static_cast(s->userData); + if (!sInfo)return 0; + + pWheel1* wheel = dynamic_cast(sInfo->wheel); + if (!wheel)return 0; + + + /* + if (!wheel->getWheelFlag(WF_UseWheelShape)) + { + wheel->contactInfo->otherActor = pair->actors[1-shapeIndex]; + wheel->contactInfo->contactPosition = contactPoint; + + wheel->contactInfo->contactPositionLocal = contactPoint; + wheel->contactInfo->contactPositionLocal -= wheel->getActor()->getGlobalPosition(); + local2global.inverseRotate(wheel->contactInfo->contactPositionLocal); + + wheel->contactInfo->contactNormal = contactNormal; + + if (wheel->contactInfo->otherActor->isDynamic()) + { + NxVec3 globalV = s->getActor().getLocalPointVelocity( getFrom(wheel->getWheelPos()) ); + globalV -= wheel->contactInfo->otherActor->getLinearVelocity(); + local2global.inverseRotate(globalV); + wheel->contactInfo->relativeVelocity = globalV.x; + //printf("%2.3f (%2.3f %2.3f %2.3f)\n", wheel->contactInfo.relativeVelocity, + // globalV.x, globalV.y, globalV.z); + } + else + { + NxVec3 vel = s->getActor().getLocalPointVelocity( getFrom(wheel->getWheelPos())); + local2global.inverseRotate(vel); + wheel->contactInfo->relativeVelocity = vel.x; + wheel->contactInfo->relativeVelocitySide = vel.z; + } + + //NX_ASSERT(wheel->hasGroundContact()); + //printf(" Wheel %x is touching\n", wheel); + } + */ + } + } + } + } + //printf("----\n"); + + return 0; +} \ No newline at end of file diff --git a/usr/Src/old/Core/pRigidBody/pRigidBodyMisc.cpp b/usr/Src/old/Core/pRigidBody/pRigidBodyMisc.cpp new file mode 100644 index 0000000..a46cb96 --- /dev/null +++ b/usr/Src/old/Core/pRigidBody/pRigidBodyMisc.cpp @@ -0,0 +1,704 @@ +#include +#include "vtPhysXAll.h" +#include + +void pRigidBody::updateMaterialSettings(pMaterial& material,CK3dEntity*shapeReference/* =NULL */) +{ + + if (shapeReference==NULL) + assert (getMainShape()); + + NxShape *shape = getSubShape(shapeReference); + if (shape) + { + + pMaterial &bMaterial = material; + if (bMaterial.xmlLinkID !=0) + { + int bIndex = bMaterial.xmlLinkID; + XString nodeName = vtAgeia::getEnumDescription(GetPMan()->GetContext()->GetParameterManager(),VTE_XML_MATERIAL_TYPE,bMaterial.xmlLinkID); + bool err = pFactory::Instance()->loadFrom(bMaterial,nodeName.Str(), pFactory::Instance()->getDefaultDocument() ); + } + iAssertW( bMaterial.isValid(),pFactory::Instance()->findSettings(bMaterial,shapeReference), + "Material settings invalid, try to find material attributes"); + + iAssertW( bMaterial.isValid(),bMaterial.setToDefault(), + "Material settings were still invalid : "); + + NxMaterialDesc nxMatDescr; + pFactory::Instance()->copyTo(nxMatDescr,bMaterial); + NxMaterial *nxMaterial = getWorld()->getScene()->createMaterial(nxMatDescr); + if (nxMaterial) + { + shape->setMaterial(nxMaterial->getMaterialIndex()); + } + } +} + +void pRigidBody::updatePivotSettings(pPivotSettings pivot,CK3dEntity*shapeReference/* =NULL */) +{ + + if (shapeReference==NULL) + assert (getMainShape()); + + NxShape *shape = getSubShape(shapeReference); + if (shape) + { + + // Referential + CK3dEntity* pivotRef = (CK3dEntity*)GetPMan()->GetContext()->GetObject(pivot.pivotReference); + + VxVector pivotLocalOut = pivot.localPosition; + //---------------------------------------------------------------- + // + // position + // + if (pivotRef) + { + pivotRef->Transform(&pivotLocalOut,&pivotLocalOut); + shape->setGlobalPosition(getFrom(pivotLocalOut)); + }else + { + shape->setLocalPosition(getFrom(pivotLocalOut)); + } + //---------------------------------------------------------------- + // + // rotational offset : todo + // + VxMatrix mat; + Vx3DMatrixFromEulerAngles(mat,pivot.localOrientation.x,pivot.localOrientation.y,pivot.localOrientation.z); + + VxQuaternion outQuat; + outQuat.FromMatrix(mat); + VxQuaternion referenceQuat=outQuat; + if (pivotRef) + { + pivotRef->GetQuaternion(&referenceQuat,NULL); + shape->setLocalOrientation(getFrom(referenceQuat)); + }else{ + + shape->setLocalOrientation(getFrom(outQuat)); + } + } +} + +void pRigidBody::saveToAttributes(pObjectDescr* oDescr) +{ + if (!oDescr) + return; + + + using namespace vtTools::AttributeTools; + using namespace vtTools::ParameterTools; + + + int attTypeActor = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + int attTypeMaterial = GetPMan()->getAttributeTypeByGuid(VTS_MATERIAL); + int attTypeOptimization = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); + int attTypeCCD = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_CCD_SETTINGS); + + //---------------------------------------------------------------- + // + // disable attribute callback + // + CKAttributeManager *aMan = GetPMan()->GetContext()->GetAttributeManager(); + if (aMan) + { + //aMan->SetAttributeCallbackFunction(attTypeActor) + } + + CK3dEntity *referenceObject = GetVT3DObject(); + + ////////////////////////////////////////////////////////////////////////// + // we remove the old physic attribute : + if (referenceObject->HasAttribute(attTypeActor)) + { + referenceObject->RemoveAttribute(attTypeActor); + } + referenceObject->SetAttribute(attTypeActor); + + CKParameterOut* actorAttribute = referenceObject->GetAttributeParameter(attTypeActor); + + //---------------------------------------------------------------- + // + // Common Settings + // + CKParameterOut *parBCommon = GetParameterFromStruct(actorAttribute,PS_COMMON_SETTINGS); + if (parBCommon) + { + SetParameterStructureValue(parBCommon,PS_BC_HULL_TYPE,oDescr->hullType); + SetParameterStructureValue(parBCommon,PS_BC_FLAGS,oDescr->flags); + SetParameterStructureValue(parBCommon,PS_BC_DENSITY,oDescr->density); + SetParameterStructureValue(parBCommon,PS_BC_WORLD,oDescr->worlReference); + } + + //---------------------------------------------------------------- + // + // Collision Setting + // + CKParameterOut *parBCollision = GetParameterFromStruct(actorAttribute,PS_COLLISION_SETTINGS); + CKParameterOut *parGroupsMask = GetParameterFromStruct(parBCollision,PS_BC_GROUPSMASK); + if (parBCollision) + { + SetParameterStructureValue(parBCollision,PS_BC_GROUP,oDescr->collisionGroup); + SetParameterStructureValue(parBCollision,PS_BC_SKINWITDH,oDescr->skinWidth); + + if (parGroupsMask) + { + SetParameterStructureValue(parGroupsMask,0,oDescr->groupsMask.bits0); + SetParameterStructureValue(parGroupsMask,1,oDescr->groupsMask.bits1); + SetParameterStructureValue(parGroupsMask,2,oDescr->groupsMask.bits2); + SetParameterStructureValue(parGroupsMask,3,oDescr->groupsMask.bits3); + } + } + + //---------------------------------------------------------------- + // + // Optimization + // + if (oDescr->mask & OD_Optimization) + { + if (referenceObject->HasAttribute(attTypeOptimization)) + { + referenceObject->RemoveAttribute(attTypeOptimization); + } + + referenceObject->SetAttribute(attTypeOptimization); + + + CKParameterOut *parBOptimization = referenceObject->GetAttributeParameter(attTypeOptimization); + if (parBOptimization) + { + SetParameterStructureValue(parBOptimization,PS_BO_LOCKS,oDescr->optimization.transformationFlags); + SetParameterStructureValue(parBOptimization,PS_BO_SOLVER_ITERATIONS,oDescr->optimization.solverIterations); + SetParameterStructureValue(parBOptimization,PS_BO_DOMINANCE_GROUP,oDescr->optimization.dominanceGroup); + SetParameterStructureValue(parBOptimization,PS_BO_COMPARTMENT_ID,oDescr->optimization.compartmentGroup); + } + + //---------------------------------------------------------------- + // + // sleeping + // + CKParameterOut *parBSleeping = GetParameterFromStruct(parBOptimization,PS_BO_SLEEPING); + if (parBSleeping) + { + SetParameterStructureValue(parBSleeping,PS_BS_ANGULAR_SLEEP,oDescr->optimization.angSleepVelocity); + SetParameterStructureValue(parBSleeping,PS_BS_LINEAR_SLEEP,oDescr->optimization.linSleepVelocity); + SetParameterStructureValue(parBSleeping,PS_BS_THRESHOLD,oDescr->optimization.sleepEnergyThreshold); + } + + //---------------------------------------------------------------- + // + // damping + // + CKParameterOut *parBDamping = GetParameterFromStruct(parBOptimization,PS_BO_DAMPING); + if (parBDamping) + { + SetParameterStructureValue(parBDamping,PS_BD_ANGULAR,oDescr->optimization.angDamping); + SetParameterStructureValue(parBDamping,PS_BD_LINEAR,oDescr->optimization.linDamping); + } + } + + //---------------------------------------------------------------- + // + // CCD + // + if (oDescr->mask & OD_CCD ) + { + if (referenceObject->HasAttribute(attTypeCCD)) + { + referenceObject->RemoveAttribute(attTypeCCD); + } + + referenceObject->SetAttribute(attTypeCCD); + + CKParameterOut *parBCCD = referenceObject->GetAttributeParameter(attTypeCCD); + if (parBCCD) + { + SetParameterStructureValue(parBCCD,PS_B_CCD_MOTION_THRESHOLD,oDescr->ccd.motionThresold); + SetParameterStructureValue(parBCCD,PS_B_CCD_FLAGS,oDescr->ccd.flags); + SetParameterStructureValue(parBCCD,PS_B_CCD_SCALE,oDescr->ccd.scale); + SetParameterStructureValue(parBCCD,PS_B_CCD_MESH_REFERENCE,oDescr->ccd.meshReference); + + } + } + //---------------------------------------------------------------- + // + // Material + // + if (oDescr->mask & OD_Material ) + { + if (referenceObject->HasAttribute(attTypeMaterial)) + { + referenceObject->RemoveAttribute(attTypeMaterial); + } + + referenceObject->SetAttribute(attTypeMaterial); + + CKParameterOut *parBMaterial = referenceObject->GetAttributeParameter(attTypeMaterial); + if (parBMaterial) + { + pFactory::Instance()->copyTo(parBMaterial,oDescr->material); + } + } + + + } + + + + void pRigidBody::updateOptimizationSettings(pOptimization optimization) +{ + + lockTransformation(optimization.transformationFlags); + setSolverIterationCount(optimization.solverIterations); + getActor()->setDominanceGroup(optimization.dominanceGroup); + setAngularDamping(optimization.angDamping); + setLinearDamping(optimization.linDamping); + setSleepAngularVelocity(optimization.angSleepVelocity); + setSleepLinearVelocity(optimization.linSleepVelocity); + setSleepEnergyThreshold(optimization.sleepEnergyThreshold); +} +void pRigidBody::setSleepAngularVelocity(float threshold) +{ + getActor()->setSleepAngularVelocity(threshold); + +} +void pRigidBody::setSleepLinearVelocity(float threshold) +{ + getActor()->setSleepLinearVelocity(threshold); +} +void pRigidBody::setSleepEnergyThreshold(float threshold) +{ + getActor()->setSleepEnergyThreshold(threshold); +} + +void pRigidBody::setDominanceGroup(int dominanceGroup) +{ + getActor()->setDominanceGroup(dominanceGroup); +} + +void pRigidBody::setSolverIterationCount(int count) +{ + + + + if (getActor()) + { + if (count > 0) + { + getActor()->setSolverIterationCount(count); + } + } +} + +void pRigidBody::checkForOptimization() +{ + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION); + CK3dEntity *ent = (CK3dEntity*)ctx()->GetObject(mEntID); + if ( !ent ) + return; + + if (!ent->HasAttribute(att)) + return; + + + + CKParameterOut *optPar = ent->GetAttributeParameter(att); + if(!optPar) + return; + + + using namespace vtTools::ParameterTools; + using namespace vtTools::AttributeTools; + + ////////////////////////////////////////////////////////////////////////// + // + // Lock transformation degrees : + // + int transformationlockFlags = GetValueFromAttribute(ent,att,PS_BO_LOCKS); + lockTransformation(transformationlockFlags); + + ////////////////////////////////////////////////////////////////////////// + // + // Damping + // + CKParameterOut * dampPar= GetParameterFromStruct(optPar,PS_BO_DAMPING); + + float linDamp = GetValueFromParameterStruct(dampPar,PS_BD_LINEAR); + float angDamp = GetValueFromParameterStruct(dampPar,PS_BD_ANGULAR); + if ( linDamp !=0.0f) + setLinearDamping(linDamp); + + if ( angDamp!=0.0f) + setAngularDamping(angDamp); + + /////////////////////////////////////////////////////////////////////////// + // + // Sleeping Settings + // + + CKParameterOut * sleepPar= GetParameterFromStruct(optPar,PS_BO_SLEEPING); + float linSleep = GetValueFromParameterStruct(dampPar,PS_BS_LINEAR_SLEEP); + + + ////////////////////////////////////////////////////////////////////////// + // + // Solver Iterations + // + //CKParameterOut * sleepPar= GetParameterFromStruct(optPar,); + int solverIterations = GetValueFromParameterStruct(optPar,PS_BO_SOLVER_ITERATIONS); + if (solverIterations !=0) + { + setSolverIterationCount(solverIterations); + } + + ////////////////////////////////////////////////////////////////////////// + // + // Dominance + // + int dGroup = GetValueFromParameterStruct(optPar,PS_BO_DOMINANCE_GROUP); + if (dGroup!=0) + { + getActor()->setDominanceGroup(dGroup); + } + + + +} +void pRigidBody::checkDataFlags() +{ + + using namespace vtTools::AttributeTools; + int att = GetPMan()->GetPAttribute(); + int att_damping = GetPMan()->att_damping; + int att_ss = GetPMan()->att_sleep_settings; + int att_surface =GetPMan()->att_surface_props; + int att_deformable =GetPMan()->att_deformable; + + xBitSet& dFlags = getDataFlags(); + CK3dEntity *ent = GetVT3DObject(); + + if (!ent) { return; } + + if (ent->HasAttribute(att_surface)) + enableFlag(dFlags,EDF_MATERIAL_PARAMETER); + else disableFlag(dFlags,EDF_MATERIAL_PARAMETER); + + if (ent->HasAttribute(att_damping)) + enableFlag(dFlags,EDF_DAMPING_PARAMETER); + else disableFlag(dFlags,EDF_DAMPING_PARAMETER); + + if (ent->HasAttribute(att_ss)) + enableFlag(dFlags,EDF_SLEEPING_PARAMETER); + else disableFlag(dFlags,EDF_SLEEPING_PARAMETER); + + if (ent->HasAttribute(att_deformable)) + enableFlag(dFlags,EDF_DEFORMABLE_PARAMETER); + else disableFlag(dFlags,EDF_DEFORMABLE_PARAMETER); + + + if (ent->HasAttribute( GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR_OPTIMIZATION) )) + enableFlag(dFlags,EDF_OPTIMIZATION_PARAMETER); + else disableFlag(dFlags,EDF_OPTIMIZATION_PARAMETER); + +} +void pRigidBody::destroy() +{ + if(!getActor()) + return; + + NxU32 nbShapes = getActor()->getNbShapes(); + + + /* + CKSTRING name = GetVT3DObject()->GetName(); + while(nbShapes ) + { + + NxShape *s = ((NxShape **)getActor()->getShapes())[0]; + pSubMeshInfo *sinfo = static_cast(s->userData); + + ////////////////////////////////////////////////////////////////////////// + // Wheel attached ! + if (sinfo && s->isWheel() && sinfo->wheel ) + { + pWheel2 *wheel = (pWheel2*)sinfo->wheel; + delete wheel; + wheel = NULL; + sinfo->wheel =NULL; + } + + if (sinfo) + { + delete sinfo; + sinfo = NULL; + } + + s->userData = NULL; + + if (getActor()->isDynamic() || ( !getActor()->isDynamic() && nbShapes >1 ) ) + { + getActor()->releaseShape(*s); + s=NULL; + destroy(); + }break; + } + + */ + + + /************************************************************************/ + /* */ + /************************************************************************/ + pVehicle *v = getVehicle(); + if ( v ) + { + getVehicle()->getWheels().clear(); + getVehicle()->setActor(NULL); + getVehicle()->setBody(NULL); + + delete v; + setVehicle(NULL); + } + + pCloth *cloth = getCloth(); + if (cloth) + { + cloth->releaseReceiveBuffers(); + getActor()->getScene().releaseCloth(*cloth->getCloth()); + } + getActor()->getScene().releaseActor(*getActor()); + setActor(NULL); +} + +int pRigidBody::getTransformationsLockFlags() +{ + + int result = 0 ; + if (getActor()->readBodyFlag(NX_BF_FROZEN_POS_X))result|=NX_BF_FROZEN_POS_X; + if (getActor()->readBodyFlag(NX_BF_FROZEN_POS_Y))result|=NX_BF_FROZEN_POS_Y; + if (getActor()->readBodyFlag(NX_BF_FROZEN_POS_Z))result|=NX_BF_FROZEN_POS_Z; + + if (getActor()->readBodyFlag(NX_BF_FROZEN_ROT_X))result|=NX_BF_FROZEN_ROT_X; + if (getActor()->readBodyFlag(NX_BF_FROZEN_ROT_Y))result|=NX_BF_FROZEN_ROT_Y; + if (getActor()->readBodyFlag(NX_BF_FROZEN_ROT_Z))result|=NX_BF_FROZEN_ROT_Z; + + return result; + +} +void pRigidBody::lockTransformation(int flags) +{ + + + if (getActor() && getActor()->isDynamic()) + { + if (flags & NX_BF_FROZEN_POS_X) + getActor()->raiseBodyFlag(NX_BF_FROZEN_POS_X); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_POS_X); + + + if (flags & NX_BF_FROZEN_POS_Y) + getActor()->raiseBodyFlag(NX_BF_FROZEN_POS_Y); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_POS_Y); + + if (flags & NX_BF_FROZEN_POS_Z) + getActor()->raiseBodyFlag(NX_BF_FROZEN_POS_Z); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_POS_Z); + + + if (flags & NX_BF_FROZEN_ROT_X) + getActor()->raiseBodyFlag(NX_BF_FROZEN_ROT_X); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_ROT_X); + + if (flags & NX_BF_FROZEN_ROT_Y) + getActor()->raiseBodyFlag(NX_BF_FROZEN_ROT_Y); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_ROT_Y); + + if (flags & NX_BF_FROZEN_ROT_Z) + getActor()->raiseBodyFlag(NX_BF_FROZEN_ROT_Z); + else + getActor()->clearBodyFlag(NX_BF_FROZEN_ROT_Z); + } +} +bool pRigidBody::isSleeping()const +{ + if (getActor()) + { + return getActor()->isSleeping(); + } + return true; +} + +void pRigidBody::setSleeping(bool sleeping) +{ + if (getActor()) + { + if (sleeping) + { + getActor()->putToSleep(); + }else{ + getActor()->wakeUp(); + } + } +} +void pRigidBody::enableGravity(bool enable) +{ + + if (getActor()) + { + if (!enable) + { + getActor()->raiseBodyFlag(NX_BF_DISABLE_GRAVITY); + }else{ + getActor()->clearBodyFlag(NX_BF_DISABLE_GRAVITY); + } + } +} + +bool pRigidBody::isAffectedByGravity()const +{ + if (getActor()) + { + return !getActor()->readBodyFlag(NX_BF_DISABLE_GRAVITY); + } + return false; +} +void pRigidBody::setKinematic(bool enabled) +{ + if (getActor()) + { + if (enabled) + getActor()->raiseBodyFlag(NX_BF_KINEMATIC); + else + getActor()->clearBodyFlag(NX_BF_KINEMATIC); + } +} +bool pRigidBody::isKinematic()const +{ + if (getActor()) + { + return getActor()->readBodyFlag(NX_BF_KINEMATIC); + } + return false; +} + +bool pRigidBody::isValid()const { + + return GetPMan()->GetContext()->GetObject(getEntID()) ? true : false && getActor() ? true : false; +} +int pRigidBody::getHullType(){ return m_HullType;} +void pRigidBody::setHullType(int _type){ m_HullType= _type;} +void pRigidBody::recalculateFlags(int _flags) +{ + if (!isValid()) + { + return; + } + + int current = m_sFlags; + + if (getActor()->isDynamic() && !getActor()->readBodyFlag(NX_BF_DISABLE_GRAVITY)) + { + current |=BF_Gravity; + } + + + if (!getActor()->readActorFlag(NX_AF_DISABLE_COLLISION)) + { + current |=BF_Collision; + } + + if (getActor()->isSleeping()) + { + current |=BF_Sleep; + } + + if (getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) + { + current |=BF_CollisionNotify; + } + + if (isKinematic()) + { + current |=BF_Kinematic; + } + + m_sFlags = current; +} + +void pRigidBody::updateFlags( int _flags,CK3dEntity*shapeReference/*=NULL*/ ) +{ + + if (!isValid())return; + + setKinematic(_flags & BF_Kinematic); + enableCollision(_flags & BF_Collision,shapeReference); + enableCollisionsNotify(_flags & BF_CollisionNotify); + enableGravity(_flags & BF_Gravity); + setSleeping(_flags & BF_Sleep); + enableTriggerShape(_flags & BF_TriggerShape,shapeReference); + m_sFlags |=_flags; + +} + +int pRigidBody::getFlags(){ + + return m_sFlags;; +} +void pRigidBody::setFlags(int _flags){ m_sFlags = _flags;} +void pRigidBody::retrieveSettingsFromAttribute() +{ + + assert(getWorld()); + assert(getWorld()->getScene()); + assert(getWorld()->getReference()); + assert(GetVT3DObject()); + + using namespace vtTools::AttributeTools; + setDataFlags(0x000); + + int att = GetPMan()->GetPAttribute(); + + //---------------------------------------------------------------- + // + // Old version + // + + CK_ID id = getWorld()->getReference()->GetID(); + SetAttributeValue(GetVT3DObject(),att,E_PPS_WORLD,&id); + setHullType(GetValueFromAttribute(GetVT3DObject(),att,E_PPS_HULLTYPE)); + + + //Sets some flags like movable , etc... + setFlags(GetValueFromAttribute(GetVT3DObject(),att,E_PPS_BODY_FLAGS)); + setDensity(GetValueFromAttribute(GetVT3DObject(),att, E_PPS_DENSITY)); + setMassOffset(GetValueFromAttribute(GetVT3DObject(),att, E_PPS_MASS_OFFSET)); + setPivotOffset(GetValueFromAttribute(GetVT3DObject(),att, E_PPS_SHAPE_OFFSET)); + setSkinWidth(GetValueFromAttribute(GetVT3DObject(),att, E_PPS_SKIN_WIDTH)); + + + +} +int pRigidBody::isBodyFlagOn(int flags) +{ + if (getActor() && getActor()->isDynamic()) + { + return getActor()->readBodyFlag((NxBodyFlag)flags); + } + return -1; +} +void pRigidBody::wakeUp(float wakeCounterValue/* =NX_SLEEP_INTERVAL */) +{ + getActor()->wakeUp(wakeCounterValue); + +} + + + diff --git a/usr/Src/old/Core/pRigidBody/pRigidBodyShape.cpp b/usr/Src/old/Core/pRigidBody/pRigidBodyShape.cpp new file mode 100644 index 0000000..6833b2c --- /dev/null +++ b/usr/Src/old/Core/pRigidBody/pRigidBodyShape.cpp @@ -0,0 +1,1544 @@ +#include +#include "vtPhysXAll.h" + +#include "IParameter.h" + +#include +int pRigidBody::addCollider(pObjectDescr objectDescr,CK3dEntity*srcRefEntity) +{ + + int result = 0 ; + + using namespace vtTools::AttributeTools; + + CK3dEntity* child = NULL; + CKMesh *srcMesh = NULL; + + if (!srcRefEntity ||!srcRefEntity->GetCurrentMesh()) + return 0; + bool isChild = vtAgeia::isChildOf(GetVT3DObject(), srcRefEntity); + + objectDescr.subEntID = srcRefEntity->GetID(); + //---------------------------------------------------------------- + // + // essential values + // + VxVector box_s = BoxGetZero(srcRefEntity); + + float radius = 1.0f; + radius = srcRefEntity->GetCurrentMesh()->GetRadius(); + + VxQuaternion refQuad; + srcRefEntity->GetQuaternion(&refQuad,GetVT3DObject()); + VxVector relPos; + srcRefEntity->GetPosition(&relPos,GetVT3DObject()); + + NxQuat rot = pMath::getFrom(refQuad); + + srcMesh = srcRefEntity->GetCurrentMesh(); + + pWheel *wheel =NULL; + NxShape *shape = NULL; + + + if (objectDescr.hullType != HT_Wheel) + { + shape = pFactory::Instance()->createShape(GetVT3DObject(),objectDescr,srcRefEntity,srcMesh,relPos,refQuad); + } + else + { + iAssertW( objectDescr.wheel.isValid(),objectDescr.wheel.setToDefault()); + iAssertW( objectDescr.wheel.radius.isValid(),objectDescr.wheel.radius.evaluate(srcRefEntity)); + shape = pFactory::Instance()->createWheelShape2(GetVT3DObject(),srcRefEntity, objectDescr.wheel ); + } + + if (!shape) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create sub shape!"); + return 0; + } + + pSubMeshInfo *sInfo = new pSubMeshInfo(); + + sInfo->meshID = srcMesh->GetID(); + sInfo->mesh =(CKBeObject*)srcMesh; + + sInfo->entID = srcRefEntity->GetID(); + sInfo->refObject = (CKBeObject*)srcRefEntity; + sInfo->wheel = NULL; + + shape->setName(srcRefEntity->GetName()); + shape->userData = (void*)sInfo; + sInfo->initDescription = objectDescr; + + getActor()->wakeUp(); + + + if ( (!objectDescr.flags &BF_Hierarchy) ) + { + return result; + } + /* + + //################################################################ + // + // If more entities in hierarchy, invoke this function recursively + // + CK3dEntity* subEntity = NULL; + while (subEntity= srcRefEntity->HierarchyParser(subEntity) ) + { + + pObjectDescr *subDescr = NULL; + + //-try old version : + if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) + { + subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + + //-try new version + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + if (subEntity->HasAttribute(attTypePBSetup)) + { + subDescr = new pObjectDescr(); + CKParameterOut *par = subEntity->GetAttributeParameter(attTypePBSetup); + IParameter::Instance()->copyTo(subDescr,par); + subDescr->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + + } + + if (!subDescr) + continue; + + if (subDescr->flags & BF_SubShape) + { + + ////////////////////////////////////////////////////////////////////////// + if (subDescr->hullType != HT_Cloth) + { + addSubShape(NULL,*subDescr,subEntity); + } + + if (subDescr->hullType == HT_Cloth) + { + + } + } + } + */ + return 1; +} + + + + +int pRigidBody::addSubShape( CKMesh *mesh,pObjectDescr& objectDescr,CK3dEntity*srcRefEntity,VxVector localPosition,VxQuaternion localRotation) +{ + + + int result = 0 ; + + int att = GetPMan()->GetPAttribute(); + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + bool isNewType = ( objectDescr.version == pObjectDescr::E_OD_VERSION::OD_DECR_V1) ? true : false ; + + + using namespace vtTools::AttributeTools; + + + + CK3dEntity* child = NULL; + bool isChild = false; + while (child = GetVT3DObject()->HierarchyParser(child) ) + { + if (child == srcRefEntity ) + { + isChild = true; + } + } + + /************************************************************************/ + /* parameters for final composition : */ + /************************************************************************/ + CKMesh *srcMesh = NULL; + float density = 0.0f; + VxVector mOffset; + VxVector sOffset; + float skinWidth; + int hType = 0; + + + if (!mesh && !srcRefEntity ) + { + return result; + } + if (!mesh && srcRefEntity && !srcRefEntity->GetCurrentMesh() ) + { + return result; + } + + CKBeObject *attObject = NULL; + if (mesh && (mesh->HasAttribute(att) || isNewType) ) + { + attObject = (CKBeObject*)mesh; + } + if (srcRefEntity && (srcRefEntity->HasAttribute(att) || isNewType ) ) + { + attObject = (CKBeObject*)srcRefEntity; + } + + + //################################################################ + // + // Fill sub shapes object description. + // + + if (attObject && !isNewType ) //we have attribute values: + { + objectDescr.density = GetValueFromAttribute(attObject ,att, E_PPS_DENSITY); + objectDescr.massOffset= GetValueFromAttribute(attObject ,att, E_PPS_MASS_OFFSET); + objectDescr.shapeOffset = GetValueFromAttribute(attObject ,att, E_PPS_SHAPE_OFFSET); + objectDescr.skinWidth = GetValueFromAttribute(attObject,att, E_PPS_SKIN_WIDTH); + objectDescr.hullType = GetValueFromAttribute(attObject,att,E_PPS_HULLTYPE); + objectDescr.hirarchy = GetValueFromAttribute(attObject,att,E_PPS_HIRARCHY); + objectDescr.collisionGroup = GetValueFromAttribute(attObject,att,E_PPS_COLL_GROUP); + objectDescr.newDensity = GetValueFromAttribute(attObject,att,E_PPS_NEW_DENSITY); + objectDescr.totalMass = GetValueFromAttribute(attObject,att,E_PPS_TOTAL_MASS); + } + + if (srcRefEntity) + { + objectDescr.subEntID = srcRefEntity->GetID(); + } + + //################################################################ + // + // Transformation values + // + VxVector box_s; + + if (!mesh && srcRefEntity) + { + box_s = BoxGetZero(srcRefEntity); + } + if (!srcRefEntity && mesh) + { + box_s = mesh->GetLocalBox().GetSize(); + } + if (srcRefEntity && mesh ) + { + box_s = mesh->GetLocalBox().GetSize(); + } + + //################################################################ + // + // Determine radius + // + float radius = 1.0f; + if ( mesh && !srcRefEntity ) + { + radius = mesh->GetRadius(); + } + if (!mesh && srcRefEntity && srcRefEntity->GetCurrentMesh() ) + { + radius = srcRefEntity->GetCurrentMesh()->GetRadius(); + } + if (mesh && srcRefEntity) + { + radius = mesh->GetRadius(); + } + + //################################################################ + // + // Calculate destination matrix + // + VxMatrix v_matrix ; + VxVector pos,scale; + VxQuaternion quat; + + + if (srcRefEntity) + { + if (isChild) + { + v_matrix = srcRefEntity->GetLocalMatrix(); + }else + { + v_matrix = srcRefEntity->GetWorldMatrix(); + } + } + Vx3DDecomposeMatrix(v_matrix,quat,pos,scale); + + + if (mesh && !srcRefEntity) + { + pos = localPosition; + quat = localRotation; + } + + if (mesh && srcRefEntity ) + { + + VxQuaternion refQuad2; + srcRefEntity->GetQuaternion(&refQuad2,GetVT3DObject()); + VxVector relPos; + srcRefEntity->GetPosition(&relPos,GetVT3DObject()); + if (!isChild) + { + pos = relPos; + quat = refQuad2; + } + } + + if (!mesh && srcRefEntity ) + { + VxVector relPos; + srcRefEntity->GetPosition(&relPos,GetVT3DObject()); + VxQuaternion refQuad2; + srcRefEntity->GetQuaternion(&refQuad2,GetVT3DObject()); + pos = relPos; + quat = refQuad2; + } + NxQuat rot = pMath::getFrom(quat); + + //################################################################ + // + // Determine the mesh + // + if (mesh && srcRefEntity==NULL ) + { + srcMesh = mesh; + } + if (!mesh && srcRefEntity && srcRefEntity->GetCurrentMesh() ) + { + srcMesh = srcRefEntity->GetCurrentMesh(); + } + + if (mesh && srcRefEntity && srcRefEntity->GetCurrentMesh()) + { + srcMesh = mesh; + } + + CK_ID srcID = 0 ; + if (srcMesh) + { + srcID = srcMesh->GetID(); + } + + + //################################################################ + // + // Create the final sub shape + // + + pSubMeshInfo *sInfo = new pSubMeshInfo(); + bool isWheel1 = false; + pWheel *wheel =NULL; + NxShape *shape = NULL; + + + if (objectDescr.hullType != HT_Wheel) + { + shape = pFactory::Instance()->createShape(GetVT3DObject(),objectDescr,srcRefEntity,srcMesh,pos,quat); + }else + { + wheel = pFactory::Instance()->createWheelSubShape(this,srcRefEntity,srcMesh,&objectDescr,pos,quat,shape); + if (wheel) + { + sInfo->wheel = wheel; + pWheel1* w1 = dynamic_cast(wheel); + if (w1){ + + isWheel1 = true; + shape = (NxShape*)w1->getWheelConvex(); + } + + pWheel2* w2 = dynamic_cast(wheel); + if (w2) + { + shape =(NxShape*)w2->getWheelShape(); + } + + }else + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Creating wheel sub shape failed"); + return NULL; + } + } + + if (!shape) + { + + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Couldn't create sub shape!"); + } + + if (shape) + { + + //################################################################ + // + // Setup the material + // + int materialIndex = 0; + + pMaterial bMaterial; + bool hasMaterial = pFactory::Instance()->findSettings(bMaterial,srcRefEntity); + if (!hasMaterial) + { + hasMaterial = pFactory::Instance()->findSettings(bMaterial,mesh); + } + + if (hasMaterial) + { + NxMaterialDesc nxMatDescr; + pFactory::Instance()->copyTo(nxMatDescr,bMaterial); + NxMaterial *nxMaterial = getWorld()->getScene()->createMaterial(nxMatDescr); + if (nxMaterial) + { + materialIndex = nxMaterial->getMaterialIndex(); + nxMaterial->userData = (void*)bMaterial.xmlLinkID; + } + }else + { + materialIndex = getWorld()->getDefaultMaterial()->getMaterialIndex(); + } + shape->setMaterial(materialIndex); + + //################################################################ + // + // Store meta info in shape user data. + // + + shape->setGroup(objectDescr.collisionGroup); + + + + if (srcMesh) + { + sInfo->meshID = srcMesh->GetID(); + sInfo->mesh =(CKBeObject*)srcMesh; + shape->setName(srcMesh->GetName()); + } + + if(srcRefEntity) + { + sInfo->entID = srcRefEntity->GetID(); + sInfo->refObject = (CKBeObject*)srcRefEntity; + shape->setName(srcRefEntity->GetName()); + } + + shape->userData = (void*)sInfo; + } + + + //################################################################ + // + // Wheel Type one has an additional capsule swept shape + // We store the shape meta data there as well + if ( + isWheel1 && + wheel && + dynamic_cast(wheel) && + (pWheel1*)(dynamic_cast(wheel))->getWheelCapsule() + ) + { + ((pWheel1*)(dynamic_cast(wheel)))->getWheelCapsule()->userData = sInfo; + } + + //################################################################ + // + // Modify mass + // + if (objectDescr.mass.newDensity!=0.0f || objectDescr.mass.totalMass!=0.0f ) + { + getActor()->updateMassFromShapes(objectDescr.mass.newDensity,objectDescr.mass.totalMass); + } + + //################################################################ + // + // Post routine + // + getActor()->wakeUp(); + if(mesh) + return result; + + if (!objectDescr.hirarchy) + { + return result; + } + + if (!srcRefEntity) + { + return result; + } + + + //################################################################ + // + // If more entities in hierarchy, invoke this function recursively + // + CK3dEntity* subEntity = NULL; + while (subEntity= srcRefEntity->HierarchyParser(subEntity) ) + { + + pObjectDescr *subDescr = NULL; + + //-try old version : + if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) + { + subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + + //-try new version + int attTypePBSetup = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_ACTOR); + if (subEntity->HasAttribute(attTypePBSetup)) + { + subDescr = new pObjectDescr(); + CKParameterOut *par = subEntity->GetAttributeParameter(attTypePBSetup); + IParameter::Instance()->copyTo(subDescr,par); + subDescr->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; + + } + + if (!subDescr) + continue; + + if (subDescr->flags & BF_SubShape) + { + + ////////////////////////////////////////////////////////////////////////// + if (subDescr->hullType != HT_Cloth) + { + addSubShape(NULL,*subDescr,subEntity); + } + + if (subDescr->hullType == HT_Cloth) + { + + } + } + + } + + return result; +} + + + +void pRigidBody::setBoxDimensions( const VxVector&dimension,CKBeObject* subShapeReference/*=NULL*/ ) +{ + if (!isValid() || !getMainShape() ) + { + return; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxBoxShape *box = static_cast(getMainShape()->isBox()); + if (!box) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); + return; + } + box->setDimensions(getFrom(dimension)); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxBoxShape *box = static_cast(s->isBox()); + if (!box) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); + return; + } + box->setDimensions(getFrom(dimension)); + } +} +VxVector pRigidBody::getBoxDimensions(CKBeObject* subShapeReference) +{ + VxVector result(-1.f,-1.f,-1.f); + if (!isValid() || !getMainShape() ) + { + return result; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxBoxShape *box = static_cast(getMainShape()->isBox()); + if (!box) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); + return result; + } + return getFrom(box->getDimensions()); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxBoxShape *box = static_cast(s->isBox()); + if (!box) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a box!"); + return result; + } + getFrom(box->getDimensions()); + } + return result; +} + + + + + +void pRigidBody::setSphereRadius(float radius,CKBeObject* subShapeReference/* =NULL */) +{ + + if (!isValid() || !getMainShape() ) + { + return; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxSphereShape *sphere = static_cast(getMainShape()->isSphere()); + if (!sphere) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); + return; + } + sphere->setRadius(radius); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxSphereShape*sphere = static_cast(s->isSphere()); + if (!sphere) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); + return; + } + sphere->setRadius(radius); + } +} + + + +float pRigidBody::getSphereRadius(CKBeObject* subShapeReference/* =NULL */) +{ + + if (!isValid() || !getMainShape() ) + { + return -1.0f; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxSphereShape *sphere = static_cast(getMainShape()->isSphere()); + if (!sphere) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); + return -1.0f; + } + return sphere->getRadius(); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxSphereShape*sphere = static_cast(s->isSphere()); + if (!sphere) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a sphere!"); + return -1.0f; + } + return sphere->getRadius(); + } + return -1.0f; +} + + + + +void pRigidBody::setCapsuleDimensions(float radius,float length,CKBeObject* subShapeReference) +{ + + if (!isValid() || !getMainShape() ) + { + return; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxCapsuleShape *capsule = static_cast(getMainShape()->isCapsule()); + if (!capsule) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); + return; + } + capsule->setHeight(length); + capsule->setRadius(radius); + + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxCapsuleShape*capsule = static_cast(s->isCapsule()); + if (!capsule) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); + return; + } + capsule->setHeight(length); + capsule->setRadius(radius); + } +} + +void pRigidBody::getCapsuleDimensions(float& radius,float& length,CKBeObject* subShapeReference) +{ + if (!isValid() || !getMainShape() ) + { + return; + } + + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + NxCapsuleShape *capsule = static_cast(getMainShape()->isCapsule()); + if (!capsule) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); + radius = -1.0f; + length = -1.0f; + return; + } + + radius = capsule->getRadius(); + length = capsule->getHeight(); + + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try a mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + NxCapsuleShape*capsule = static_cast(s->isCapsule()); + if (!capsule) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"target shape is not a capsule!"); + radius = -1.0f; + length = -1.0f; + return; + } + radius = capsule->getRadius(); + length = capsule->getHeight(); + } + +} +HullType pRigidBody::getShapeType(CKBeObject* subShapeReference) +{ + if (!isValid() || !getMainShape() ) + { + return HT_Unknown; + } + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL) + { + return (HullType)vtAgeia::getHullTypeFromShape(getMainShape()); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try a mesh : + s = _getSubShape(subShapeReference->GetID()); + } + if (!s) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"couldn't find sub shape!"); + return HT_Unknown; + } + return (HullType)vtAgeia::getHullTypeFromShape(s); + } + return HT_Unknown; +} + +float pRigidBody::getSkinWidth(CKBeObject* subShapeReference) +{ + + if (!isValid() || !getMainShape() ) + { + return -1.0f; + } + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL && !getMainShape() ) + { + return mSkinWidth; + + } + if(subShapeReference == NULL && getMainShape() ) + { + return getMainShape()->getSkinWidth(); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try a mesh : + s = _getSubShape(subShapeReference->GetID()); + } + if (!s) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"couldn't find sub shape!"); + return -1.0f; + } + return s->getSkinWidth(); + } + return -1.0f; +} + +void pRigidBody::setSkinWidth(const float skinWidth,CKBeObject* subShapeReference) +{ + if (!isValid() || !getMainShape() ) + { + mSkinWidth = mSkinWidth; + return; + } + /// shape is specified -> modify bodies first shape : + if (subShapeReference == NULL && !getMainShape() ) + { + mSkinWidth = skinWidth; + } + if(subShapeReference == NULL && getMainShape() ) + { + getMainShape()->setSkinWidth(skinWidth); + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try a mesh : + s = _getSubShape(subShapeReference->GetID()); + } + if (!s) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"couldn't find sub shape!"); + return; + } + s->setSkinWidth(skinWidth); + } +} + + +int pRigidBody::removeSubShape( CKBeObject *reference,float newensity/*=0.0f*/,float totalMass/*=0.0f*/ ) +{ + + + int result = -1; + if (!reference || !getActor()) + { + return result; + } + + NxShape *subShape = NULL; + bool found = false; + while(subShape = _getSubShape(reference->GetID())) + { + getActor()->releaseShape(*subShape); + found =true; + } + + ////////////////////////////////////////////////////////////////////////// + + if (!found) + { + while(subShape = _getSubShape(reference->GetID())) + { + getActor()->releaseShape(*subShape); + found =true; + } + } + + if (found && newensity !=0.0f || totalMass!=0.0f ) + { + getActor()->updateMassFromShapes(newensity,totalMass); + } + getActor()->wakeUp(); + + return 1; +} + +NxShape * pRigidBody::_getSubShapeByEntityID( CK_ID id ) +{ + if (!getActor()) + { + return NULL; + } + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->entID == id) + { + return s; + } + } + } + return NULL; +} +bool pRigidBody::isSubShape(CKBeObject *object) +{ + + bool result = false; + if (!object) + { + return result; + } + + if ( _getSubShape(object->GetID()) || _getSubShapeByEntityID(object->GetID() )) + { + return true ; + } + return result; +} +NxShape *pRigidBody::_getSubShape(CK_ID meshID) +{ + + if (!getActor()) + { + return NULL; + } + + int nbShapes = getActor()->getNbShapes(); + + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->meshID == meshID) + { + return s; + } + } + } + return NULL; +} + + +int pRigidBody::updateMassFromShapes( float density, float totalMass ) +{ + + if (getActor()) + { + return getActor()->updateMassFromShapes(density,totalMass); + } + return -1; +} + + +NxShape *pRigidBody::getShapeByIndex(int index/* =0 */) +{ + + NxU32 nbShapes = getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; jreadActorFlag(NX_AF_DISABLE_COLLISION); + } + }else{ + return !subShape->getFlag(NX_SF_DISABLE_COLLISION); + } + } + return false; +} +void pRigidBody::enableCollision( bool enable,CK3dEntity* subShapeReference/*=NULL*/ ) +{ + NxShape *subShape = getSubShape(subShapeReference); + + if (!subShape) + { + subShape==getMainShape(); + } + if (subShape ) + { + if (subShape ==getMainShape()) + { + if (!enable) + { + getActor()->raiseActorFlag(NX_AF_DISABLE_COLLISION); + }else + { + getActor()->clearActorFlag(NX_AF_DISABLE_COLLISION); + } + }else{ + + subShape->setFlag(NX_SF_DISABLE_RESPONSE, !enable ); + } + } +} +void pRigidBody::enableTriggerShape( bool enable,CK3dEntity* subShapeReference/*=NULL*/ ) +{ + + NxShape *subShape = getSubShape(subShapeReference); + if (subShape) + { + subShape->setFlag(NX_TRIGGER_ENABLE,enable); + } +} + +bool pRigidBody::isTriggerShape( CK3dEntity* subShapeReference/*=NULL*/ ) +{ + NxShape *subShape = getSubShape(subShapeReference); + if (subShape) + { + return subShape->getFlag(NX_TRIGGER_ENABLE); + } + return false; +} + +bool pRigidBody::isCollisionsNotifyEnabled() +{ + + return ( getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ); +} + +void pRigidBody::enableCollisionsNotify( bool enable ) +{ + if (enable) + { + getActor()->setContactReportFlags(NX_NOTIFY_ON_TOUCH); + }else + getActor()->setContactReportFlags(NX_IGNORE_PAIR); +} + +VxVector pRigidBody::getPivotOffset(CK3dEntity*shapeReference) +{ + + NxShape *subshape = getSubShape(shapeReference); + if (subshape) return getFrom(subshape->getLocalPosition()); + + return VxVector(); +} + +NxShape*pRigidBody::getSubShape(CK3dEntity*shapeReference/* =NULL */) +{ + + + if (shapeReference) + { + + NxShape *inputShape = _getSubShapeByEntityID(shapeReference->GetID()); + if (getMainShape() ==inputShape) + { + return getMainShape(); + }else{ + return inputShape; + } + } + + return getMainShape(); + +} +void pRigidBody::setShapeMaterial(pMaterial&material,CK3dEntity*shapeReference/* =NULL */) +{ + + NxShape *dstShape = NULL; + + + if (shapeReference) + { + dstShape = _getSubShapeByEntityID(shapeReference->GetID()); + }else{ + dstShape = getMainShape(); + } + + + #ifdef _DEBUG + assert(dstShape); + #endif + + + int materialIndex = dstShape->getMaterial(); + + NxMaterial *currentMaterial = getActor()->getScene().getMaterialFromIndex(materialIndex); + + if (!material.isValid()) + return; + + NxMaterialDesc nxMatDescr; + + ////////////////////////////////////////////////////////////////////////// + // + // We dont alter the default material ! We create a new one !! + // + + int defaultID = getWorld()->getDefaultMaterial()->getMaterialIndex(); + if ( !currentMaterial || materialIndex ==0 || materialIndex == getWorld()->getDefaultMaterial()->getMaterialIndex() ) + { + + pFactory::Instance()->copyTo(nxMatDescr,material); + + NxMaterial *newMaterial = getActor()->getScene().createMaterial(nxMatDescr); + if (newMaterial){ + dstShape->setMaterial(newMaterial->getMaterialIndex()); + newMaterial->userData = (void*)material.xmlLinkID; + } + } + else + { + pFactory::Instance()->copyTo(nxMatDescr,material); + currentMaterial->loadFromDesc(nxMatDescr); + } + + +} +pMaterial&pRigidBody::getShapeMaterial(CK3dEntity *shapeReference/* =NULL */) +{ + + pMaterial result; + + if (shapeReference && !isSubShape(shapeReference)) + { + return result; + } + + NxShape *srcShape = NULL; + CK3dEntity *ent = GetVT3DObject(); + + if (shapeReference) + { + srcShape = getSubShape(shapeReference); + }else{ + srcShape = getMainShape(); + } + + #ifdef _DEBUG + assert(srcShape); + #endif + + int index = srcShape->getMaterial(); + NxMaterial *mat = getActor()->getScene().getMaterialFromIndex(srcShape->getMaterial()); + + pFactory::Instance()->copyTo(result,getActor()->getScene().getMaterialFromIndex(srcShape->getMaterial())); + + + return result; + +} +void pRigidBody::_checkForRemovedSubShapes() +{ + + +} + +void pRigidBody::_checkForNewSubShapes() +{ + + pObjectDescr *oDescr = pFactory::Instance()->createPObjectDescrFromParameter(GetVT3DObject()->GetAttributeParameter(GetPMan()->GetPAttribute())); + if (!oDescr) + { + return; + } + + if (! ( getFlags() & BF_Hierarchy ) ) + { + return ; + } + + CK3dEntity* subEntity = NULL; + while (subEntity= GetVT3DObject()->HierarchyParser(subEntity) ) + { + if ( !_getSubShapeByEntityID(subEntity->GetID()) ) + { + CKSTRING name = subEntity->GetName(); + int s = isSubShape(subEntity); + + if ( subEntity->HasAttribute(GetPMan()->GetPAttribute() ) ) + { + pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + if (subDescr->flags & BF_SubShape) + { + if (subDescr->hullType != HT_Cloth) + { + addSubShape(NULL,*oDescr,subEntity); + } + + if (subDescr->hullType == HT_Cloth) + { + //pClothDesc *cloth = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + } + } + } + } + } + + + if (( getFlags() & BF_Hierarchy )) + { + if (oDescr->newDensity!=0.0f || oDescr->totalMass!=0.0f ) + { + updateMassFromShapes(oDescr->newDensity,oDescr->totalMass); + } + } +} +int pRigidBody::updateSubShapes(bool fromPhysicToVirtools/* = true */,bool position/* =true */,bool rotation/* =true */) +{ + if(!getActor()) + return -1; + NxU32 nbShapes = getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (info) + { + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(info->entID)); + if (ent) + { + + if (s == getMainShape()) + continue; + + + if (fromPhysicToVirtools) + { + //pVehicle *v =getVehicle(); + pWheel* wheel = (pWheel*)getWheel(ent); + if (wheel) + { + wheel->_updateVirtoolsEntity(position,rotation); + }else + { + + if (position) + { + VxVector gPos = getFrom(s->getLocalPose().t); + ent->SetPosition(&gPos,GetVT3DObject()); + } + if (rotation) + { + VxQuaternion rot = pMath::getFrom( s->getLocalPose().M ); + if(s->isWheel()) + { + }else + { + ent->SetQuaternion(&rot,GetVT3DObject()); + } + } + } + }else//Virtools to Ageia ! + { + if (position) + { + VxVector relPos; + ent->GetPosition(&relPos,GetVT3DObject()); + s->setLocalPosition(getFrom(relPos)); + } + + if (rotation) + { + VxQuaternion refQuad2; + ent->GetQuaternion(&refQuad2,GetVT3DObject()); + s->setLocalOrientation(getFrom(refQuad2)); + } + + } + /*if (s->getType() ==NX_SHAPE_WHEEL ) + { + NxWheelShape *wShape = static_cast(s); + if (wShape) + { + + float cS = wShape->getSuspension().spring; + float cST = wShape->getSuspensionTravel(); + + VxVector gPos = getFrom(s->getGlobalPose().t); + VxVector lPos = getFrom(s->getLocalPose().t); + VxVector diff ; + ent->GetPosition(&diff,GetVT3DObject()); + ent->SetPosition(&gPos); + + + } + } + */ + } + } + } + } + } + + + return 0; +} +int pRigidBody::getCollisionsGroup( CK3dEntity* subShapeReference/*=NULL*/ ) +{ + + NxShape *subShape = getSubShape(subShapeReference); + if (subShape) + { + return subShape->getGroup(); + } + return -1; +} +void pRigidBody::setCollisionsGroup( int index,CK3dEntity* subShapeReference/*=NULL*/ ) +{ + + if(!getActor()) + return; + + if (subShapeReference == NULL) + { + if(index>=0 && index <=32) + getActor()->setGroup(index); + + NxU32 nbShapes = getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j=0 && index <=32) + s->setGroup(index); + } + } + } + } + + // shape reference is specified - > modify sub shape : + if (subShapeReference !=NULL && isSubShape(subShapeReference) ) + { + // try an entity : + NxShape *s = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!s) + { + //try an mesh : + s = _getSubShape(subShapeReference->GetID()); + } + + if (!s) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"there is no such sub shape!"); + return; + } + s->setGroup(index); + } +} + +void pRigidBody::setGroupsMask(CK3dEntity *shapeReference,const pGroupsMask& mask) +{ + + + NxShape *mainshape = getMainShape(); + NxShape *dstShape = getMainShape(); + + if (shapeReference) + { + NxShape *inputShape = _getSubShapeByEntityID(shapeReference->GetID()); + if (mainshape==inputShape) + { + dstShape = mainshape; + }else{ + dstShape = inputShape; + } + } + + + NxGroupsMask mask1; + mask1.bits0 = mask.bits0; + mask1.bits1 = mask.bits1; + mask1.bits2 = mask.bits2; + mask1.bits3 = mask.bits3; + + if (dstShape) + { + dstShape->setGroupsMask(mask1); + } + +} + + +pGroupsMask pRigidBody::getGroupsMask(CK3dEntity *shapeReference) +{ + + NxShape *mainshape = getMainShape(); + NxShape *dstShape = getMainShape(); + + if (shapeReference) + { + NxShape *inputShape = _getSubShapeByEntityID(shapeReference->GetID()); + if (mainshape==inputShape) + { + dstShape = mainshape; + }else{ + dstShape = inputShape; + } + } + + if (dstShape) + { + + NxGroupsMask gMask = dstShape->getGroupsMask(); + + pGroupsMask vtGMask; + + vtGMask.bits0 = gMask.bits0; + vtGMask.bits1 = gMask.bits1; + vtGMask.bits2 = gMask.bits2; + vtGMask.bits3 = gMask.bits3; + return vtGMask; + + } + + + return pGroupsMask(); + +} + +/* +if (srcRefEntity && srcRefEntity->HasAttribute(GetPMan()->att_wheelDescr )) +{ + CKParameterOut *par = srcRefEntity->GetAttributeParameter(GetPMan()->att_wheelDescr ); + if (par) + { + pWheelDescr *wDescr = new pWheelDescr(); + int err = pFactory::Instance()->copyTo(wDescr,par); + + if (wDescr && !wDescr->isValid() ) + { + xLogger::xLog(XL_START,ELOGWARNING,E_LI_MANAGER,"Wheel Description was invalid"); + delete wDescr; + } + + if (wDescr) + { + pWheel *wheel = pFactory::Instance()->createWheel(this,*wDescr); + + shape = pFactory::Instance()->createWheelShape(getActor(),&objectDescr,wDescr,srcRefEntity,srcMesh,pos,quat); + if (shape) + { + + if(wDescr->wheelFlags & E_WF_USE_WHEELSHAPE) + { + pWheel2 * wheel2 = (pWheel2*)wheel; + wheel2->setWheelShape((NxWheelShape*)shape); + + }else{ + + } + + if (wheel->getWheelFlag(E_WF_VEHICLE_CONTROLLED) && mVehicle) + mVehicle->getWheels().push_back(wheel); + + wheel->mWheelFlags = wDescr->wheelFlags; + sInfo->wheel = wheel; + wheel->setEntID(srcRefEntity->GetID()); + + } + } + } +} +*/ \ No newline at end of file diff --git a/usr/Src/old/Core/pRigidBody/pRigidBodyTypes.cpp b/usr/Src/old/Core/pRigidBody/pRigidBodyTypes.cpp new file mode 100644 index 0000000..71bf743 --- /dev/null +++ b/usr/Src/old/Core/pRigidBody/pRigidBodyTypes.cpp @@ -0,0 +1,233 @@ +#include +#include "vtPhysXAll.h" + +#include "IParameter.h" +#include + +bool pPivotSettings::isValid() +{ + return true; + +} + +bool pObjectDescr::setToDefault() +{ + + hullType =HT_Sphere; + density = 1.0f; + massOffset = VxVector(); + shapeOffset = VxVector(); + flags = (BodyFlags)0; + skinWidth =0.0f; + newDensity = 0.0f; + totalMass = 0.0f; + collisionGroup = 0; + hirarchy = 0; + subEntID = -1; + transformationFlags = 0; + worlReference = 0; + + + internalXmlID = externalXmlID = xmlImportFlags = 0; + + massOffsetReference = 0; + + pivotOffsetReference = 0; + + + ccdMotionThresold = 0.0; + ccdFlags = 0 ; + ccdMeshReference =NULL; + ccdScale = 1.0f; + + linearDamping = angularDamping = 0.0f; + + linearSleepVelocity = angularSleepVelocity = sleepingEnergyThresold = 0.0f; + + solverIterations = dominanceGroups = compartmentID = 0; + + version = OD_DECR_V0; + mask = (pObjectDescrMask)0; + + groupsMask.bits0=0; + groupsMask.bits1=0; + groupsMask.bits2=0; + groupsMask.bits3=0; + + + wheel.setToDefault(); + optimization.setToDefault(); + material.setToDefault(); + collision.setToDefault(); + pivot.setToDefault(); + //mass.setToDefault(); + ccd.setToDefault(); + + + return true; +} + +bool pCollisionSettings::setToDefault() +{ + collisionGroup = 0; + collisionGroup = 0; + skinWidth = 0.025f; + return true; +} + +bool pPivotSettings::setToDefault() +{ + pivotReference = 0; + return true; +} +bool pCCDSettings::setToDefault() +{ + motionThresold = 0.0; + flags = 0 ; + meshReference =0; + scale = 1.0f; + + return true; +} + +bool pOptimization::setToDefault() +{ + transformationFlags = (BodyLockFlags)0; + + linDamping = angDamping = 0.0f; + solverIterations = 24 ; + dominanceGroup=0; + compartmentGroup=0; + sleepEnergyThreshold =0.0f; + linSleepVelocity = angSleepVelocity = 0.0; + + return true; + +} +bool pOptimization::isValid() +{ + + bool result = true; + + iAssertWR( X_IS_BETWEEN(solverIterations,1,255) ,solverIterations=24,result ); + iAssertWR( !(linDamping < 0) ,"",result ); + iAssertWR( !(angDamping< 0) ,"",result ); + iAssertWR( !(transformationFlags < 0) ,transformationFlags=((BodyLockFlags)0),result ); + iAssertWR( !(linSleepVelocity < 0) ,"",result ); + iAssertWR( !(angSleepVelocity < 0) ,"",result ); + + + return true; + +} +bool pMaterial::isValid() +{ + bool result = true; + + + iAssertWR( !(dynamicFriction < 0.0f) ,"",result ); + iAssertWR( !(staticFriction < 0.0f) ,"",result ); + iAssertWR( !(restitution < 0.0f || restitution > 1.0f) ,"",result ); + + if (flags & 1) + { + float sMagnitude = dirOfAnisotropy.SquareMagnitude(); + iAssertWR( sMagnitude > 0.98f || sMagnitude < 1.03f ,"",result ); + iAssertWR( !(dynamicFrictionV < 0.0f) ,"",result ); + iAssertWR( !(staticFrictionV < 0.0f) ,"",result ); + } + + iAssertWR( frictionCombineMode <= 4 ,"",result ); + iAssertWR( restitutionCombineMode <= 4 ,"",result ); + + + return result; + +} + +bool pConvexCylinderSettings::setToDefault() +{ + radius.setToDefault(); + height.setToDefault(); + approximation = 4; + + downAxis.Set(0,-1,0); + rightAxis.Set(1,0,0); + forwardAxis.Set(0,0,1); + + convexFlags = CF_ComputeConvex; + + + return true; + +} +bool pConvexCylinderSettings::isValid() +{ + + bool result=true; + iAssertWR(radius.isValid(),"",result); + iAssertWR(height.isValid(),"",result); + iAssertWR(approximation >= 4 && approximation > 0,"",result); + iAssertWR( XAbs(forwardAxis.SquareMagnitude()) > 0.1f || forwardAxisRef,"",result); + iAssertWR( XAbs(downAxis.SquareMagnitude()) > 0.1f || downAxisRef,"",result); + iAssertWR( XAbs(rightAxis.SquareMagnitude()) > 0.1f || rightAxisRef,"",result); + + return result; +} + +bool pAxisReferencedLength::isValid() +{ + return ( referenceAxis<3 && referenceAxis >=0) && (value > 0.0f || reference ) ; +} + +bool pAxisReferencedLength::evaluate(CKBeObject *referenceObject) +{ + if (!reference && referenceObject) + { + this->reference = referenceObject; + } + + if (reference) + { + VxVector size; + + if (reference->GetClassID() == CKCID_3DOBJECT ) + { + CK3dEntity *ent = (CK3dEntity*)reference; + if (ent && ent->GetCurrentMesh() ) + size = ent->GetCurrentMesh()->GetLocalBox().GetSize(); + } + else if(reference->GetClassID() == CKCID_MESH) + { + CKMesh *mesh = (CKMesh*)reference; + if (mesh) + { + size = mesh->GetLocalBox().GetSize(); + } + } + value = size[referenceAxis]; + return XAbs(size.SquareMagnitude()) >0.0f; + } + return false; +} +bool pAxisReferencedLength::setToDefault() +{ + value=0.0f; + referenceAxis = 0; + reference = NULL; + + return true; +} + +bool pCapsuleSettingsEx::setToDefault() +{ + radius.setToDefault(); + height.setToDefault(); + return true; +} +bool pCapsuleSettingsEx::isValid() +{ + return radius.isValid() && height.isValid(); +} + + diff --git a/usr/Src/old/Core/pRigidBody/pRigidBodyWheel.cpp b/usr/Src/old/Core/pRigidBody/pRigidBodyWheel.cpp new file mode 100644 index 0000000..5a9b067 --- /dev/null +++ b/usr/Src/old/Core/pRigidBody/pRigidBodyWheel.cpp @@ -0,0 +1,252 @@ +#include +#include "vtPhysXAll.h" + +#include "NXU_helper.h" // NxuStream helper functions. +#include "NXU_PhysicsInstantiator.h" + + +void pRigidBody::updateWheels(float step) +{ + + + + NxVec3 _localVelocity; + + bool _breaking=false; + + + /* + _computeMostTouchedActor(); + NxVec3 relativeVelocity; + if (_mostTouchedActor == NULL || !_mostTouchedActor->isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - _mostTouchedActor->getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + NxQuat global2Local; + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + char master[512]; + */ + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + pWheel *wheel = sinfo->wheel; + pWheel2* wheel2 = dynamic_cast(wheel); + + if (wheel->getWheelFlag(WF_VehicleControlled)) + { + continue; + } + + wheel->_tick(step); + + /* + + NxWheelShape *wShape = wheel2->getWheelShape(); + if (!wShape) continue; + + + + ////////////////////////////////////////////////////////////////////////// + // + // + // + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + + if (contactShape) + { + + NxVec3 relativeVelocity; + if ( !contactShape->getActor().isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - contactShape->getActor().getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + _breaking = NxMath::abs(_localVelocity.z) < ( 0.1 ); +// wShape->setAxleSpeed() + } + + + float rollAngle = wheel2->getWheelRollAngle(); + rollAngle+=wShape->getAxleSpeed() * (step* 0.01f); + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + wheel2->setWheelRollAngle(rollAngle); + + NxMat34& wheelPose = wShape->getGlobalPose(); + + + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( contactShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + wheel2->getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - wheel2->getSuspensionTravel(), wheelPose.t.z ); + } + + float rAngle = wheel2->getWheelRollAngle(); + float steer = wShape->getSteerAngle(); + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + wheel2->setWheelPose(wheelPose); + + */ + + } + } + } +/* //motorTorque *= 0.1f; + brakeTorque *= 500.0f; + if(handBrake && getWheelFlag(E_WF_AFFECTED_BY_HANDBRAKE)) + brakeTorque = 1000.0f; + if(getWheelFlag(E_WF_ACCELERATED)) + mWheelShape->setMotorTorque(motorTorque); + mWheelShape->setBrakeTorque(brakeTorque); + + + + + + mWheelPose = mWheelShape->getGlobalPose(); + + NxWheelContactData wcd; + NxShape* s = mWheelShape->getContact(wcd); + NxReal stravel = mWheelShape->getSuspensionTravel(); + NxReal radius = mWheelShape->getRadius(); + + + //have ground contact? + if( s && wcd.contactPosition <= (stravel + radius) ) { + mWheelPose.t = NxVec3( mWheelPose.t.x, wcd.contactPoint.y + radius, mWheelPose.t.z ); + } + else { + mWheelPose.t = NxVec3( mWheelPose.t.x, mWheelPose.t.y - stravel, mWheelPose.t.z ); + } + + + NxMat33 rot, axisRot, rollRot; + rot.rotY( mWheelShape->getSteerAngle() ); + //rot.rotX(0); + axisRot.rotY(0); + rollRot.rotX(_wheelRollAngle); + mWheelPose.M = rot * mWheelPose.M * axisRot * rollRot; + + */ + +} +bool pRigidBody::hasWheels() +{ + + bool result = false; + + if (!getActor()) + { + return false; + } + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + return true; + } + } + } + + return result; + +} + +int pRigidBody::getNbWheels() +{ + + int result = 0; + + if (!getActor()) + { + return NULL; + } + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + result ++; + } + } + } + return result; +} + +pWheel *pRigidBody::getWheel(CK3dEntity* subShapeReference) +{ + + pWheel *result = NULL; + if (!subShapeReference) + { + return result; + } + + NxShape *subShape = _getSubShapeByEntityID(subShapeReference->GetID()); + if (!subShape) + return result; + + pSubMeshInfo *sInfo = static_cast(subShape->userData); + + if (sInfo && sInfo->wheel) + { + return sInfo->wheel; + } + /* + + NxWheelShape *wheel = static_cast(subShape->isWheel()); + if (wheel) + { + pSubMeshInfo *sInfo = static_cast(subShape->userData); + + if (sInfo && sInfo->wheel) + { + return sInfo->wheel; + } + } + */ + return result; + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pSerializer/pSerializer.cpp b/usr/Src/old/Core/pSerializer/pSerializer.cpp new file mode 100644 index 0000000..132e197 --- /dev/null +++ b/usr/Src/old/Core/pSerializer/pSerializer.cpp @@ -0,0 +1,226 @@ +#include +#include "vtPhysXAll.h" + +#include "NXU_helper.h" // NxuStream helper functions. +#include "NXU_PhysicsInstantiator.h" + +#include "UserAllocator.h" +#include "ErrorStream.h" +#include "Utilities.h" + +static ErrorStream gErrorStream; +static pSerializer *gSerializer = NULL; + +void pSerializer::parseFile(const char*filename,int flags) +{ + + if(!GetPMan()->getPhysicsSDK()) + return; + + + if (!loadCollection(filename,1)) + { + return ; + } + + + NXU::instantiateCollection(mCollection, *GetPMan()->getPhysicsSDK(), 0, 0, 0); + NXU::NxuPhysicsInstantiator Instantiator(mCollection); + Instantiator.instantiate(*GetPMan()->getPhysicsSDK()); + int sCount = mCollection->mScenes.size(); + + for (NxU32 i=0; imScenes.size(); i++) + { + NXU::NxSceneDesc *sd = mCollection->mScenes[i]; + + for (NxU32 j=0; jmActors.size(); j++) + { + + NXU::NxActorDesc *ad = sd->mActors[j]; + const char*name = ad->name; + XString nameStr(name); + + CK3dEntity *ent = (CK3dEntity*)ctx()->GetObjectByNameAndClass(nameStr.Str(),CKCID_3DOBJECT); + if (ent) + { + pRigidBody *body = GetPMan()->getBody(nameStr.CStr()); + if (body) + body->readFrom(ad,0); + else + body = pFactory::Instance()->createBody(ent,NULL,ad,1); + + } + + if ( ad->mHasBody ) // only for dynamic actors + { + for (NxU32 k=0; kmShapes.size(); k++) + { + NXU::NxShapeDesc *shape = ad->mShapes[k]; + NxVec3 locPos = shape->localPose.t; + NxQuat localQuad = shape->localPose.M; + } + } + } + } + +} + + + +class MyUserNotify: public NXU_userNotify, public NXU_errorReport +{ +public: + virtual void NXU_errorMessage(bool isError, const char *str) + { + if (isError) + { + printf("NxuStream ERROR: %s\r\n", str); + } + else + { + printf("NxuStream WARNING: %s\r\n", str); + } + } + + virtual void NXU_notifyScene(NxU32 sno, NxScene *scene, const char *userProperties) + { + + }; + + + +}; +MyUserNotify gUserNotify; + + + + + +bool pSerializer::overrideBody(pRigidBody *body,int flags) +{ + + if (!mCollection) + { + return false; + } + + NXU::instantiateCollection(mCollection, *GetPMan()->getPhysicsSDK(), 0, 0, 0); + NXU::NxuPhysicsInstantiator Instantiator(mCollection); + Instantiator.instantiate(*GetPMan()->getPhysicsSDK()); + + int sCount = mCollection->mScenes.size(); + for (NxU32 i=0; imScenes.size(); i++) + { + + NXU::NxSceneDesc *sd = mCollection->mScenes[i]; + + for (NxU32 j=0; jmActors.size(); j++) + { + + NXU::NxActorDesc *ad = sd->mActors[j]; + const char*name = ad->name; + XString nameStr(name); + + + if ( ad->mHasBody ) // only for dynamic actors + { + for (NxU32 k=0; kmShapes.size(); k++) + { + NXU::NxShapeDesc *shape = ad->mShapes[k]; + NxVec3 locPos = shape->localPose.t; + NxQuat localQuad = shape->localPose.M; + } + } + } + } + + return true; +} + + +int pSerializer::loadCollection(const char*fileName,int flags) +{ + if (mCollection) + { + releaseCollection(mCollection); + mCollection = NULL; + } + mCollection = getCollection(fileName,flags); + if (mCollection) + { + return 1; + }else + { + return 0; + } +} + + +pSerializer::pSerializer() +{ + gSerializer = this; + mCollection = NULL; + +} + +//************************************ +// Method: Instance +// FullName: vtAgeia::pSerializer::Instance +// Access: public static +// Returns: pSerializer* +// Qualifier: +//************************************ +pSerializer*pSerializer::Instance() +{ + + + if (!gSerializer) + { + gSerializer = new pSerializer(); + } + + return gSerializer; +} + +NXU::NxuPhysicsCollection* pSerializer::getCollection(const char *pFilename,int type) +{ + + NXU::NxuPhysicsCollection* c = NULL; + c = NXU::loadCollection(pFilename,(NXU::NXU_FileType)type); + if (!c) + { + return NULL; + } + return c; +} + + +int pSerializer::saveCollection(const char*filename) +{ + + char SaveFilename[512]; + //GetTempFilePath(SaveFilename); + strcat(SaveFilename, filename); + + NXU::setUseClothActiveState(false); + NXU::setUseSoftBodyActiveState(false); + + NXU::setErrorReport(&gUserNotify); + NXU::setEndianMode(isProcessorBigEndian()); + + NXU::NxuPhysicsCollection *c = NXU::extractCollectionScene(GetPMan()->getDefaultWorld()->getScene()); + if (c) + { + char scratch[512]; + XString fName(filename); + //fName << "\0"; + sprintf(scratch, "%s.xml", SaveFilename); + printf("Saving NxuStream XML file to '%s'\r\n", scratch); + NXU::saveCollection(c, fName.CStr(), NXU::FT_BINARY, false, false); + NXU::releaseCollection(c); + + } + + releaseCollection(c); + return 0; +} diff --git a/usr/Src/old/Core/pVehicle/pDifferential.cpp b/usr/Src/old/Core/pVehicle/pDifferential.cpp new file mode 100644 index 0000000..1de8e63 --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pDifferential.cpp @@ -0,0 +1,614 @@ +#include "pDifferential.h" + + +void pDifferential::setToDefault() +{ + + type = 1; + SetRatio(2.53f); + SetInertia(0.15f); + lockingCoeff = 275.0f; + + +} +pDifferential::pDifferential(pVehicle *_car) + : pDriveLineComp() +{ + SetName("differential"); + + car=_car; + type=FREE; + lockingCoeff=0; + powerAngle=coastAngle=0; + clutches=0; + clutchFactor=0; + flags=0; + Reset(); + + setToDefault(); +} +pDifferential::~pDifferential() +{ +} + +void pDifferential::Reset() +{ + torqueIn=0; + torqueOut[0]=torqueOut[1]=0; + torqueBrakingOut[0]=torqueBrakingOut[1]=0; + inertiaIn=0; + inertiaOut[0]=inertiaOut[1]=0; + accIn=0; + accOut[0]=accOut[1]=0; + torqueLock=0; + rotVdriveShaft=0; + + velASymmetric=0; + locked=0; + + engine=0; + wheel[0]=wheel[1]=0; + + pDriveLineComp::Reset(); +} +/******** +* Input * +********/ +void pDifferential::Lock(int wheel) +// Lock a side (0 or 1) +// The wheel calls this function as soon as it sees rotational +// velocity reversal (the wheel from moving forward suddenly starts +// moving backward due to (mostly) braking or rolling resistance) +// In CalcForces(), the side can be unlocked again if the reaction +// torques exceed the (potential) braking torque. +{ + locked|=(1<GetInertiaAtDifferential(); + inertiaOut[0]=wheel[0]->GetRotationalInertia()->x; + inertiaOut[1]=wheel[1]->GetRotationalInertia()->x; +#else + inertiaIn=1; + inertiaOut[0]=1; + inertiaOut[1]=1; +#endif + + // Retrieve torques at all ends + // Notice that inside the diff, there can be a ratio. If this is 2 for + // example, the driveshaft will rotate twice as fast as the wheel axles. +#ifdef ND_DRIVELINE + torqueIn=engine->GetTorqueAtDifferential(); +#else + torqueIn=1; +#endif + /* + torqueOut[0]=wheel[0]->GetTorqueFeedbackTC()->x; + torqueOut[1]=wheel[1]->GetTorqueFeedbackTC()->x; + */ + // Retrieve potential braking torque; if bigger than the reaction + // torque, the output will become unlocked. If not, the output is + // locked. + // Note that the braking torque already points in the opposite + // direction of the output (mostly a wheel) rotation. This is contrary + // to Gregor Veble's approach, which only calculates the direction + // in the formulae below. + + /* + torqueBrakingOut[0]=wheel[0]->GetTorqueBrakingTC()->x; + torqueBrakingOut[1]=wheel[1]->GetTorqueBrakingTC()->x; + */ +#ifdef LTRACE + qdbg(" torqueIn=%f, torqueOut0=%f, 1=%f\n",torqueIn,torqueOut[0],torqueOut[1]); +#endif + + // Proceed to Gregor's naming convention and algorithm + // Determine locking + switch(type) + { + case FREE: + // No locking; both wheels run free + m0=0; + break; + case VISCOUS: +// velASymmetric=wheel[1]->GetRotationV()-wheel[0]->GetRotationV(); + m0=-lockingCoeff*velASymmetric; +#ifdef LTRACE +qdbg(" velASymm=%f, lockCoeff=%f => m0=%f\n",velASymmetric,lockingCoeff,m0); +#endif + break; + case SALISBURY: + // Salisbury diff locks based on the ratio of reaction torques on + // the tires. + // Calculate torque bias ratio + if(fabs(torqueOut[1])>D3_EPSILON) + torqueBiasRatio=torqueOut[0]/torqueOut[1]; + else if(fabs(torqueOut[0])>D3_EPSILON) + torqueBiasRatio=torqueOut[1]/torqueOut[0]; + else + torqueBiasRatio=1; // Both wheels doing pretty much nothing + // Get a number which always has a ratio>1 + if(torqueBiasRatio<1.0)torqueBiasRatioAbs=1.0f/torqueBiasRatio; + else torqueBiasRatioAbs=torqueBiasRatio; + // Is the ratio exceeded? +//xxxx continue here + if(torqueIn>0) + { + // Power + if(torqueBiasRatioAbs>maxBiasRatioPower); + } + m0=0; break; + default: + m0=0; break; + } + m3=torqueIn; // Entails engine braking already +#ifdef LTRACE +qdbg(" torqueIn=%f, locked=%d\n",m3,locked); +#endif + + j1=inertiaOut[0]; + j2=inertiaOut[1]; + j3=inertiaIn; + jw=j1+j2; + jt=jw+j3; + jd=j1-j2; // Inertia difference (of outputs) + // Calculate determinant of 2x2 matrix + det=4.0f*j1*j2+j3*jw; + + m3=torqueIn; + switch(locked) + { + case 0: // No outputs locked + m1=torqueOut[0]+torqueBrakingOut[0]; + m2=torqueOut[1]+torqueBrakingOut[1]; +//qdbg(" m1=%f, m2=%f\n",m1,m2); + break; + case 1: + // Output 0 is locked, output 1 is unlocked + m2=torqueOut[1]+torqueBrakingOut[1]; + m1=(m2*j3-2.0f*m3*j2-m0*(2.0f*j2+j3))/(4.0f*j2+j3); + if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) + locked=0; + break; + case 2: + // Output 1 is locked, output 0 is unlocked + m1=torqueOut[0]+torqueBrakingOut[0]; + m2=(m1*j3-2.0f*m3*j1+m0*(2.0f*j1+j3))/(4.0f*j1+j3); + if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) + locked=0; + break; + case 3: + // Both outputs locked + m1=-m3/2.0f; + m2=m1; + m0=0; + if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) + locked^=1; + if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) + locked^=2; + break; + default: + //qerr("Bug: pDifferential locked not in 0..3 (%d)",locked); + m1=m2=0; + break; + } + mt=m1+m2+m3; + md=m2-m1+m0; + + // Calculate asymmetric acceleration + accASymmetric=md/jw; +#ifdef ND_OLD_NAMES + accASymmetric=(torqueOut[1]-torqueOut[0]+torqueLock)/ + (inertiaOut[0]+inertiaOut[1]); +#endif + + // Calculate total acceleration based on all torques + // (which is in fact the driveshaft rotational acceleration) + accIn=mt/jt; +#ifdef ND_OLD_NAMES + accIn=(torqueIn+torqueOut[0]+torqueOut[1])/ + (inertiaIn+inertiaOut[0]+inertiaOut[1]); +#endif + + // Derive from these the acceleration of the 2 output parts + accOut[1]=accIn+accASymmetric; + accOut[0]=accIn-accASymmetric; + + // Add torque to body because of the accelerating drivetrain + // This gives a bit of the GPL effect where your car rolls when + // you throttle with the clutch disengaged. +/* + float tr=car->GetEngine()->GetTorqueReaction(); + if(tr>0) + { + DVector3 torque(0,0,accIn*inertiaIn*tr); +//qdbg("torque.z=%f\n",torque.z); + car->GetBody()->AddBodyTorque(&torque); + } +*/ + +#ifdef LTRACE + qdbg("inertia: I%f, O %f, %f\n",inertiaIn,inertiaOut[0],inertiaOut[1]); + qdbg("torqueBraking: I%f, O %f, %f\n",0,torqueBrakingOut[0], + torqueBrakingOut[1]); + qdbg("torque: I%f, O %f, %f, locking %f\n",m3,m1,m2,m0); + qdbg("Vel: wheel0=%f, wheel1=%f\n",wheel[0]->GetRotationV(), + wheel[1]->GetRotationV()); + qdbg("Acc: asym %f, in %f, out %f, %f\n",accASymmetric,accIn, + accOut[0],accOut[1]); +#endif +} + +float pDifferential::CalcLockingTorque() +// Calculates the locking torque of the differential +{ + float m0; + + switch(type) + { + case FREE: + // No locking; both wheels run free + m0=0; + break; + case VISCOUS: + //velASymmetric=wheel[1]->GetRotationV()-wheel[0]->GetRotationV(); + m0=-lockingCoeff*velASymmetric; +#ifdef LTRACE +qdbg(" velASymm=%f, lockCoeff=%f => m0=%f\n",velASymmetric,lockingCoeff,m0); +#endif + break; + case SALISBURY: + // Salisbury diff locks based on the ratio of reaction torques on + // the tires. + // Calculate torque bias ratio + if(fabs(torqueOut[1])>D3_EPSILON) + torqueBiasRatio=torqueOut[0]/torqueOut[1]; + else if(fabs(torqueOut[0])>D3_EPSILON) + torqueBiasRatio=torqueOut[1]/torqueOut[0]; + else + torqueBiasRatio=1; // Both wheels doing pretty much nothing + // Get a number which always has a ratio>1 + if(torqueBiasRatio<1.0)torqueBiasRatioAbs=1.0f/torqueBiasRatio; + else torqueBiasRatioAbs=torqueBiasRatio; + // Is the ratio exceeded? +//xxxx continue here + if(torqueIn>0) + { + // Power + if(torqueBiasRatioAbs>maxBiasRatioPower); + } + m0=0; break; + default: + //qwarn("pDifferential:CalcLockingTorque(); unknown diff type"); + m0=0; break; + } + return m0; +} + +void pDifferential::CalcSingleDiffForces(float torqueIn,float inertiaIn) +// Special version in case there is only 1 differential. +// Differences with regular operating: +// - 'torqueIn' is directly passed in from the driveline root (engine). +// - 'inertiaIn' is directly passed from the driveline (engine's eff. inertia) +// Calculates accelerations of the 3 sides of the differential +// based on incoming torques and inertia's. +// Also unlocks sides (only the wheels can be locked for now) +// if the engine torques exceeds the reaction/braking torque +// (if that side was locked, see Lock()) +{ + // Gregor Veble's naming convention + float j1,j2,j3, // Inertia of output1/output2/input + jw, // Total inertia of wheels + jt, // Total inertia of all attached components + jd; // Difference of wheel inertia's + float m0, // Locking torque + m1, // Output1 torque + m2, // Output2 torque + m3; // Input torque (from the engine probably) + float mt, // Total net torque + md; // Asymmetric torque (?) + float det; + + // Check that everything is ok + if(!engine)return; + if(wheel[0]==0||wheel[1]==0)return; + + // Note that no ratios are used here; the input and outputs + // are geared 1:1:1. This makes the formulas easier. To add + // a differential ratio, the other functions for the input torques + // take care of this. +#ifdef LTRACE +qdbg("RDiff:CalcSingleDiffForces(%.2f)\n",torqueIn); +#endif + // Retrieve current effective inertia + // The base is the driveshaft; the accelerations and torques are + // related to its position in the drivetrain. + //inertiaIn=engine->GetInertiaAtDifferential(); + + //inertiaOut[0]=wheel[0]->GetInertia(); + //inertiaOut[1]=wheel[1]->GetInertia(); + + // Retrieve torques at all ends + // Notice that inside the diff, there can be a ratio. If this is 2 for + // example, the driveshaft will rotate twice as fast as the wheel axles. + //torqueIn=engine->GetTorqueAtDifferential(); +// torqueOut[0]=wheel[0]->GetTorqueFeedbackTC()->x; + //torqueOut[1]=wheel[1]->GetTorqueFeedbackTC()->x; + + // Retrieve potential braking torque; if bigger than the reaction + // torque, the output will become unlocked. If not, the output is + // locked. + // Note that the braking torque already points in the opposite + // direction of the output (mostly a wheel) rotation. This is contrary + // to Gregor Veble's approach, which only calculates the direction + // in the formulae below. +// torqueBrakingOut[0]=wheel[0]->GetTorqueBrakingTC()->x; +// torqueBrakingOut[1]=wheel[1]->GetTorqueBrakingTC()->x; +#ifdef LTRACE +qdbg(" torqueIn=%f, torqueOut0=%f, 1=%f\n",torqueIn, + torqueOut[0],torqueOut[1]); +#endif + + // Proceed to Gregor's naming convention and algorithm + // Determine locking + m0=CalcLockingTorque(); +#ifdef OBS + switch(type) + { + case FREE: + // No locking; both wheels run free + m0=0; + break; + case VISCOUS: + velASymmetric=wheel[1]->GetRotationV()-wheel[0]->GetRotationV(); + m0=-lockingCoeff*velASymmetric; +#ifdef LTRACE +qdbg(" velASymm=%f, lockCoeff=%f => m0=%f\n",velASymmetric,lockingCoeff,m0); +#endif + break; + case SALISBURY: + // Salisbury diff locks based on the ratio of reaction torques on + // the tires. + // Calculate torque bias ratio + if(fabs(torqueOut[1])>D3_EPSILON) + torqueBiasRatio=torqueOut[0]/torqueOut[1]; + else if(fabs(torqueOut[0])>D3_EPSILON) + torqueBiasRatio=torqueOut[1]/torqueOut[0]; + else + torqueBiasRatio=1; // Both wheels doing pretty much nothing + // Get a number which always has a ratio>1 + if(torqueBiasRatio<1.0)torqueBiasRatioAbs=1.0f/torqueBiasRatio; + else torqueBiasRatioAbs=torqueBiasRatio; + // Is the ratio exceeded? +//xxxx continue here + if(torqueIn>0) + { + // Power + if(torqueBiasRatioAbs>maxBiasRatioPower); + } + m0=0; break; + default: + m0=0; break; + } +#endif + + m3=torqueIn; // Entails engine braking already +#ifdef LTRACE +qdbg(" torqueIn=%f, locked=%d\n",m3,locked); +#endif + + j1=inertiaOut[0]; + j2=inertiaOut[1]; + j3=inertiaIn; + jw=j1+j2; + jt=jw+j3; + jd=j1-j2; // Inertia difference (of outputs) + // Calculate determinant of 2x2 matrix + det=4.0f*j1*j2+j3*jw; + + m3=torqueIn; + switch(locked) + { + case 0: // No outputs locked + m1=torqueOut[0]+torqueBrakingOut[0]; + m2=torqueOut[1]+torqueBrakingOut[1]; +//qdbg(" m1=%f, m2=%f\n",m1,m2); + break; + case 1: + // Output 0 is locked, output 1 is unlocked + m2=torqueOut[1]+torqueBrakingOut[1]; + m1=(m2*j3-2.0f*m3*j2-m0*(2.0f*j2+j3))/(4.0f*j2+j3); + if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) + locked=0; + break; + case 2: + // Output 1 is locked, output 0 is unlocked + m1=torqueOut[0]+torqueBrakingOut[0]; + m2=(m1*j3-2.0f*m3*j1+m0*(2.0f*j1+j3))/(4.0f*j1+j3); + if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) + locked=0; + break; + case 3: + // Both outputs locked + m1=-m3/2.0f; + m2=m1; + m0=0; + if(fabs(m1-torqueOut[0])>fabs(torqueBrakingOut[0])) + locked^=1; + if(fabs(m2-torqueOut[1])>fabs(torqueBrakingOut[1])) + locked^=2; + break; + default: + //qerr("Bug: pDifferential locked not in 0..3 (%d)",locked); + m1=m2=0; + break; + } + mt=m1+m2+m3; + md=m2-m1+m0; + + // Calculate asymmetric acceleration + accASymmetric=md/jw; +#ifdef ND_OLD_NAMES + accASymmetric=(torqueOut[1]-torqueOut[0]+torqueLock)/ + (inertiaOut[0]+inertiaOut[1]); +#endif + + // Calculate total acceleration based on all torques + // (which is in fact the driveshaft rotational acceleration) + accIn=mt/jt; +#ifdef ND_OLD_NAMES + accIn=(torqueIn+torqueOut[0]+torqueOut[1])/ + (inertiaIn+inertiaOut[0]+inertiaOut[1]); +#endif + + // Derive from these the acceleration of the 2 output parts + accOut[1]=accIn+accASymmetric; + accOut[0]=accIn-accASymmetric; + + // Add torque to body because of the accelerating drivetrain + // This gives a bit of the GPL effect where your car rolls when + // you throttle with the clutch disengaged. + /* + float tr=car->GetEngine()->GetTorqueReaction(); + if(tr>0) + { + DVector3 torque(0,0,accIn*inertiaIn*tr); +//qdbg("torque.z=%f\n",torque.z); + car->GetBody()->AddBodyTorque(&torque); + } + */ + +#ifdef LTRACE + qdbg("inertia: I%f, O %f, %f\n",inertiaIn,inertiaOut[0],inertiaOut[1]); + qdbg("torqueBraking: I%f, O %f, %f\n",0,torqueBrakingOut[0], + torqueBrakingOut[1]); + qdbg("torque: I%f, O %f, %f, locking %f\n",m3,m1,m2,m0); + qdbg("Vel: wheel0=%f, wheel1=%f\n",wheel[0]->GetRotationV(), + wheel[1]->GetRotationV()); + qdbg("Acc: asym %f, in %f, out %f, %f\n",accASymmetric,accIn, + accOut[0],accOut[1]); +#endif +} +/************ +* Integrate * +************/ +void pDifferential::Integrate() +// Maintain differential objects rotations +{ + float rotAds; + + // Check that everything is ok + if(!engine)return; + if(wheel[0]==0||wheel[1]==0)return; + + // Driveshaft rotation + rotAds=accIn; +#ifdef OBS_DIRECTLY_LINKED_TO_WHEELS + rotVdriveShaft+=rotAds*RR_TIMESTEP; +#endif + //rotVdriveShaft=(wheel[0]->GetRotationV()+wheel[1]->GetRotationV())/2.0f; +} + + +/* +bool pDifferential::LoadState(QFile *f) +{ + RDriveLineComp::LoadState(f); + f->Read(&rotVdriveShaft,sizeof(rotVdriveShaft)); + f->Read(&locked,sizeof(locked)); + return TRUE; +} +bool pDifferential::SaveState(QFile *f) +{ + RDriveLineComp::SaveState(f); + f->Write(&rotVdriveShaft,sizeof(rotVdriveShaft)); + f->Write(&locked,sizeof(locked)); + return TRUE; +} + +bool pDifferential::Load(QInfo *info,cstring path) +// Read settings from the car file +{ + char buf[256]; + + sprintf(buf,"%s.type",path); + type=info->GetInt(buf); + // Read the ratio + sprintf(buf,"%s.ratio",path); + if(info->PathExists(buf)) + { + SetRatio(info->GetFloat(buf)); + //qdbg("Diff ratio (%s) = %.2f\n",buf,ratio); + } else + { + // Backward compatible (v0.4.9 and before); use old gearbox setting + qwarn("No differential ratio in car.ini; using gearbox.end_ratio instead"); + qwarn("(this is obsolete; use differential.diff.ratio from now on)"); + SetRatio(info->GetFloat("gearbox.end_ratio")); + } + sprintf(buf,"%s.inertia",path); + SetInertia(info->GetFloat(buf)); + + // Type-specific parameters + if(type==VISCOUS) + { + // Viscous locking differential + sprintf(buf,"%s.locking_coeff",path); + lockingCoeff=info->GetFloat(buf); + } else if(type==SALISBURY) + { + // Salisbury (known from GPL) + sprintf(buf,"%s.power_angle",path); + powerAngle=info->GetFloat(buf)/RR_RAD2DEG; + sprintf(buf,"%s.coast_angle",path); + coastAngle=info->GetFloat(buf)/RR_RAD2DEG; + sprintf(buf,"%s.clutches",path); + clutches=info->GetInt(buf); + sprintf(buf,"%s.clutch_factor",path); + clutchFactor=info->GetFloat(buf); + + // Calculate resulting constants + maxBiasRatioPower=cos(powerAngle)*(1.0+2.0*clutches)*clutchFactor; + maxBiasRatioCoast=cos(coastAngle)*(1.0+2.0*clutches)*clutchFactor; + } + return TRUE; +} +*/ \ No newline at end of file diff --git a/usr/Src/old/Core/pVehicle/pDriveLine.cpp b/usr/Src/old/Core/pVehicle/pDriveLine.cpp new file mode 100644 index 0000000..c90f5cb --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pDriveLine.cpp @@ -0,0 +1,618 @@ +#include "pDriveLine.h" + +#include "vtPhysXAll.h" +#include "pVehicle.h" +#include "pGearbox.h" +#include "pDifferential.h" + + +#include + + +/********************** +* Driveline component * +**********************/ +pDriveLineComp::pDriveLineComp() +{ + // Init member variables + parent=0; + child[0]=child[1]=0; + driveLine=0; + name=""; + + inertia=0.01f; + ratio=invRatio=1; + effectiveInertiaDownStream=0; + cumulativeRatio=0; + tReaction=tBraking=tEngine=0; + rotV=rotA=0; +} +pDriveLineComp::~pDriveLineComp() +{ +} + +// +// Attribs +// +void pDriveLineComp::SetParent(pDriveLineComp *_parent) +// Set a parent for this component. Mostly, this is done implicitly +// using AddChild(). +{ + parent=_parent; +} +void pDriveLineComp::SetRatio(float r) +{ + if(fabs(r)0; adjusted to 1",r); + r=1; + } + ratio=r; + // Precalculate inverse ratio for faster calculations later + invRatio=1.0f/r; +} +void pDriveLineComp::Reset() +// Reset variables for a fresh start (like when Shift-R is used) +{ + rotV=rotA=0; +} + +pDriveLineComp *pDriveLineComp::GetChild(int n) +{ + switch(n) + { case 0: return child[0]; + case 1: return child[1]; + default: /*qwarn("RDriveLineComp:GetChild(%d) out of range",n);*/ return 0; + } +} + +void pDriveLineComp::AddChild(pDriveLineComp *comp) +// Add 'comp' as a child +{ + if(!child[0])child[0]=comp; + else if(!child[1])child[1]=comp; + //else qwarn("RDriveLineComp:AddChild() failed; already has 2 children"); + + // Declare us as parent of the child + comp->SetParent(this); +} + + +/***************** +* Precalculation * +*****************/ +void pDriveLineComp::CalcEffectiveInertia() +// Calculate the total effective inertia for this node plus the children +{ + +//qdbg("RDLC:CalcEffectiveInertia() '%s'\n",name.cstr()); + effectiveInertiaDownStream=inertia*cumulativeRatio*cumulativeRatio; + if(child[0]) + { + child[0]->CalcEffectiveInertia(); + effectiveInertiaDownStream+=child[0]->GetEffectiveInertia(); + } + if(child[1]) + { + child[1]->CalcEffectiveInertia(); + effectiveInertiaDownStream+=child[1]->GetEffectiveInertia(); + } +} +void pDriveLineComp::CalcCumulativeRatio() +// Calculate the cumulative ratio for this component and entire tree +{ + cumulativeRatio=ratio; + if(child[0]) + { + child[0]->CalcCumulativeRatio(); + } + if(child[1]) + { + child[1]->CalcCumulativeRatio(); + } + // Take ratio if child[0] only, since only singular links are supported + // (like engine->gear->driveshaft) + if(child[0]) + cumulativeRatio*=child[0]->GetCumulativeRatio(); + //cumulativeRatio*=child[0]->GetRatio(); +} +void pDriveLineComp::CalcReactionForces() +// Calculate reaction forces from the leaves up +{ + tReaction=tBraking=0; + if(child[0]) + { + child[0]->CalcReactionForces(); + tReaction+=child[0]->GetReactionTorque(); + tBraking+=child[0]->GetBrakingTorque(); + } + if(child[1]) + { + child[1]->CalcReactionForces(); + tReaction+=child[1]->GetReactionTorque(); + tBraking+=child[1]->GetBrakingTorque(); + } + // Multiply by the inverse ratio for upstream + tReaction*=invRatio; + tBraking*=invRatio; +} + +// Stub base class function +void pDriveLineComp::CalcForces(){} +// Stub base class function +void pDriveLineComp::CalcAccelerations(){} +// Stub base class function +void pDriveLineComp::Integrate() +{ +//qdbg("RDLC:Integrate() base class\n"); + rotV+=rotA*RR_TIMESTEP; +//qdbg(" rotV=%.2f (rotA=%.2f)\n",rotV,rotA); +} + +/* +void pDriveLineComp::DbgPrint(int depth,XString& s) +{ + + // Tab + if(depth>0) + qdbg("%*s",depth*2," "); + qdbg("comp. '%s', ratio %.2f (cum. %.2f, 1/%.2f), inertia %.2f" + " (effective %.2f)\n",name.cstr(),ratio,cumulativeRatio,invRatio, + inertia,effectiveInertiaDownStream); + + if(child[0])child[0]->DbgPrint(depth+1,s); + if(child[1])child[1]->DbgPrint(depth+1,s); + +} +*/ +pDriveLine::pDriveLine(pVehicle *_car) +{ + // Init members + car=_car; + root=0; + preClutchInertia=postClutchInertia=totalInertia=0; + prepostLocked=true; + diffs=0; + + // Clutch defaults + clutchMaxTorque=100; + clutchLinearity=DEFAULT_CLUTCH_LINEARITY; + SetClutchApplication(1); + tClutch=0; + // Handbrake defaults + handbrakeApplication=0; +} +pDriveLine::~pDriveLine() +{ +} +// Set the root component +void pDriveLine::SetRoot(pDriveLineComp *comp) + +{ + root=comp; +} + +/* +bool pDriveLine::Load(QInfo *info) +// Read driveline specs +// Assumes wheels have been loaded, and engine has been loaded too. +{ + char buf[256],*s; + RWheel *w; + int i,n; + RDifferential *d; + + // Differentials + n=info->GetInt("differentials.count"); + if(!n) + { + // Pre v0.5 Racer versions used a single differential definition. + // Still support that for backward compatibility for older (mostly + // converted) cars. + d=new RDifferential(car); + d->Load(info,"differential"); + d->wheel[0]=car->GetWheel(2); + car->GetWheel(2)->SetDifferential(d,0); + d->wheel[1]=car->GetWheel(3); + car->GetWheel(3)->SetDifferential(d,1); + d->engine=car->GetEngine(); + car->AddDifferential(d); + } else + { + // True set of differentials + // Check for known situations. + if(n!=1&&n!=3) + { qwarn("pDriveLine:Load(); unsupported number of differentials (%d)",n); + qlog(QLOG_INFO,"Forcing to 1 differential"); + n=1; + } + for(i=0;iLoad(info,buf); + car->AddDifferential(d); + } + } + + // Clutch + clutchMaxTorque=info->GetFloat("clutch.max_torque"); + + // Handbrakes + info->GetString("handbrakes.wheels",buf); + // Enable handbrakes for all the given wheels + for(s=buf;*s;s++) + { + if(*s>='0'&&*s<='0'+car->GetWheels()) + { + w=car->GetWheel(*s-'0'); + if(w)w->EnableHandbrakes(); + } + } + return TRUE; +} +bool pDriveLine::LoadState(QFile *f) +{ + f->Read(&preClutchInertia,sizeof(preClutchInertia)); + f->Read(&postClutchInertia,sizeof(postClutchInertia)); + f->Read(&totalInertia,sizeof(totalInertia)); + f->Read(&prepostLocked,sizeof(prepostLocked)); + f->Read(&tClutch,sizeof(tClutch)); + return TRUE; +} +bool pDriveLine::SaveState(QFile *f) +{ + f->Write(&preClutchInertia,sizeof(preClutchInertia)); + f->Write(&postClutchInertia,sizeof(postClutchInertia)); + f->Write(&totalInertia,sizeof(totalInertia)); + f->Write(&prepostLocked,sizeof(prepostLocked)); + f->Write(&tClutch,sizeof(tClutch)); + return TRUE; +} +*/ + +/******** +* Reset * +********/ +void pDriveLine::Reset() +{ + autoClutch=true; + prepostLocked=false; +} + +/***************** +* Precalculation * +*****************/ +void pDriveLine::CalcCumulativeRatios() +// Calculate the resulting spin factors (ratios) throughout the driveline +{ + if(root) + root->CalcCumulativeRatio(); +} + +void pDriveLine::CalcEffectiveInertiae() +// Calculate all effective inertiae in the driveline +{ + if(root) + root->CalcEffectiveInertia(); +} + +void pDriveLine::CalcPreClutchInertia() +// Calculate all inertia before the clutch (engine) +{ + // Engine should be the root + if(!root) + { + //qwarn("pDriveLine:CalcPreClutchInertia(); no root component"); + return; + } + // Note that we take the inertia without adding the ratios, since + // this will be used when the engine rotates at a different speed + // from the rest of the drivetrain. + preClutchInertia=root->GetInertia(); +} + +void pDriveLine::CalcPostClutchInertia() +// Calculate all inertia after the clutch (gearbox, diffs, wheels) +{ + // Check for a driveline to be present + if(!root) + { + //qwarn("pDriveLine:CalcPreClutchInertia(); no root component"); + return; + } + postClutchInertia=root->GetChild(0)->GetEffectiveInertia(); + + // Also calculate total inertia + totalInertia=preClutchInertia+postClutchInertia; +} + +void pDriveLine::SetClutchApplication(float app) +// Set clutch application. +{ + if(app<0)app=0; else if(app>1.0f)app=1.0f; + // Make it undergo severe linearity; I couldn't get + // a smooth take-off without stalling the engine. + app=clutchLinearity*app+(1.0f-clutchLinearity)*(app*app*app); + clutchApplication=app; + clutchCurrentTorque=app*clutchMaxTorque; +} + + +void pDriveLine::DbgPrint(XString& s) +{ + //qdbg("Driveline (%s); clutch: app=%.2f, maxT=%.2f, T=%.2f\n",s,clutchApplication,clutchMaxTorque,clutchCurrentTorque); + // Print tree + /* + if(root) + root->DbgPrint(0,s); + */ +} + +/******** +* Input * +********/ +void pDriveLine::SetInput(int ctlClutch,int ctlHandbrake) +// Inputs controller state. May be overruled though is some assisting is on. +{ + // Clutch + if(IsAutoClutchActive()) + { + // Automatic assist is on; don't accept user input for a while + //SetClutchApplication(car->GetEngine()->GetAutoClutch()); + } else + { + // Manual + SetClutchApplication(((float)ctlClutch)/1000.0f); + } + + // Handbrakes + handbrakeApplication=((float)ctlHandbrake)/1000.0f; + if(handbrakeApplication<0)handbrakeApplication=0; + else if(handbrakeApplication>1)handbrakeApplication=1; +} + +/********** +* Physics * +**********/ +// Determine forces throughout the driveline. +// Assumes the wheel reaction forces are already calculated. +void pDriveLine::CalcForces() +{ + + if(root==0||gearbox==0) + { + /*qwarn("pDriveLine:CalcForces(); driveline not built yet");*/ + return; + } + + // In neutral gear the pre and post parts are always unlocked, + // and no clutch torque is applied. + + + if(car->GetGearBox()->IsNeutral()) + { + UnlockPrePost(); + //tClutch=0; + clutchCurrentTorque=0; + //goto skip_clutch_calc; + } + + + // Calculate current clutch torque (including torque direction) + if(!IsPrePostLocked()) + { + // Engine is running separately from the rest of the driveline. + // The clutch works to make the velocity of pre-clutch (engine) and + // post-clutch (rest) equal. + if(root->GetRotationVel()>gearbox->GetRotationVel()*gearbox->GetRatio()) + tClutch=GetClutchCurrentTorque(); + else + tClutch=-GetClutchCurrentTorque(); + + +#ifdef LTRACE + qdbg("RDL:CF; engine rotV=%.2f, gearbox rotV=%.2f => clutchT=%.2f\n",root->GetRotationVel(),gearbox->GetRotationVel(),tClutch); +#endif + + } // else acceleration will be given by the driveline (engine rotates + // along with the rest of the driveline as a single assembly) + + // Spread wheel (leaf) reaction forces all the way to the engine (root) + root->CalcReactionForces(); + + if(IsPrePostLocked()) + { + // Check if pre and post are still locked + float Te,Tr,Tb,Tc; + Te=root->GetEngineTorque(); + Tr=root->GetReactionTorque(); + Tb=root->GetBrakingTorque(); + Tc=GetClutchCurrentTorque(); + +/*#ifdef LTRACE +qdbg("pre-post is locked: Te(%.2f) > (%.2f+%.2f+%.2f=%.2f) ?\n", +Te,Tr,Tb,Tc,Tr+Tb+Tc); +#endif +*/ + if(fabs(Te-(Tr+Tb))>Tc) + { +//qdbg(" pre-post gets UNLOCKED\n"); + UnlockPrePost(); + } + } // else it will get locked again when velocity reversal happens + // of the engine vs. rest of the drivetrain (=gearbox in angular velocity) + + if(IsSingleDiff()) + { + + // Special case where some optimizations can be done + pDifferential *diff=car->GetDifferential(0); +//qdbg("Single diff case:\n"); + if(IsPrePostLocked()) + { + + + float Te,r; + Te=root->GetEngineTorque(); + r=root->GetCumulativeRatio(); +#ifdef LTRACE + qdbg(" Diff gets Te=%.2f * ratio %.2f = %.2f\n",Te,r,Te*r); +#endif + + diff->CalcSingleDiffForces(Te*r,root->GetEffectiveInertia()); + } else + { + + // Engine spins at a different rate from the rest of the driveline + // In this case the clutch fully works on getting the pre- and post- + // clutch angular velocities equal. + // Note that if the clutch is fully depressed (engine totally decoupled + // from the rest of the driveline), this torque will be 0, and the + // postclutch driveline will just rotate freely. +#ifdef LTRACE + qdbg(" SingleDiff and prepost unlocked.\n"); +#endif + + float Tc,r; + Tc=GetClutchTorque(); + r=root->GetCumulativeRatio(); +#ifdef LTRACE + qdbg(" Diff gets Tc=%.2f * ratio %.2f = %.2f\n",Tc,r,Tc*r); +#endif + + diff->CalcSingleDiffForces(Tc*r,root->GetEffectiveInertia()); + + } + } +} +// Calculate the accelerations of all the parts in the driveline +void pDriveLine::CalcAccelerations() +{ + +#ifdef LTRACE + qdbg("pDriveLine::CalcAccelerations()\n"); +#endif + + if(IsSingleDiff()) + { + // Special case with speedier calculations + pDifferential *diff=car->GetDifferential(0); + pDriveLineComp *comp; + float acc=diff->GetAccIn(); + if(IsPrePostLocked()) + { + //qdbg("Single diff, prepost LOCKED\n"); + // Everything is decided by the differential acceleration + // Wheels got their acceleration in RWheel::CalcAccelerations() + // Pass acceleration up the tree; mind the ratios + for(comp=diff;comp;comp=comp->GetParent()) + { + comp->SetRotationAcc(acc); + acc*=comp->GetRatio(); +#ifdef LTRACE + qdbg(" comp '%s' acc %.2f (ratio %.2f)\n",comp->GetName(),acc,comp->GetRatio()); +#endif + + } + } else + { + // Separate pre- and postclutch accelerations + // First calculate the engine's acceleration. + root->CalcAccelerations(); + // Rest of the driveline takes its acceleration from the diff + // Wheels got their acceleration in RWheel::CalcAccelerations() + // Pass acceleration up the tree, EXCEPT for the engine; mind the ratios + // May combine this into the loop above by a sentinel component + // which is either '0' or 'root'. (for the PrePostLocked case) + for(comp=diff;comp!=root;comp=comp->GetParent()) + { + comp->SetRotationAcc(acc); + acc*=comp->GetRatio(); + //qdbg(" comp '%s' acc %.2f (ratio %.2f)\n",//comp->GetName(),acc,comp->GetRatio()); + } + } + } +} + +void pDriveLine::Integrate() +{ + + float deltaVel,newDeltaVel; + + // Remember difference between engine and gear rotation + deltaVel=root->GetRotationVel()-gearbox->GetRotationVel()*gearbox->GetRatio(); + if(IsPrePostLocked()) + { + // Check for the engine and gearbox (ratio'd) + // to rotate just about equally. + // If not, the driver may have speedshifted without + // applying the clutch. Unfortunately, this is possible + // but should result in damage in the future, since + // you get a lot of gear noise. + if(fabs(deltaVel)>DELTA_VEL_THRESHOLD) + { + + // Unlock pre-post to let things catch up again + UnlockPrePost(); + } + } + +#ifdef LTRACE + + qdbg("rotV: engine=%.3f, gearbox=%.3f\n",root->GetRotationVel(),gearbox->GetRotationVel()); + qdbg(" engine=%p, root=%p, gearbox=%p\n",car->GetEngine(),root,gearbox); + qdbg(" rpm=%f\n",car->GetEngine()->GetRPM()); + + int cGear =car->GetGearBox()->GetGear(); + qdbg(" currentGear=%d %s \n",cGear,car->GetGearBox()->GetGearName(cGear).CStr()); + +#endif + + + // Engine + if(root)root->Integrate(); + if(gearbox)gearbox->Integrate(); + + if(!IsPrePostLocked()) + { + // Check if gearbox is catching up with engine + newDeltaVel=root->GetRotationVel()-gearbox->GetRotationVel()*gearbox->GetRatio(); +//qdbg("Check lock; oldDV=%.3f, newDV=%.3f\n",deltaVel,newDeltaVel); + if((deltaVel>0&&newDeltaVel<0)|| + (deltaVel<0&&newDeltaVel>0)) + { + +#ifdef LTRACE +qdbg(" RE-LOCKED!\n"); +#endif + + LockPrePost(); + // Force engine and gearbox velocity to be the same +#ifdef LTRACE + qdbg(" engine rotV=%.3f, gearbox rotV=%.3f\n",root->GetRotationVel(),gearbox->GetRotationVel()); +#endif + + root->SetRotationVel(gearbox->GetRotationVel()*gearbox->GetRatio()); + } + } +} + + +/* +//******* I/O * + +bool pDriveLineComp::LoadState(QFile *f) +{ +f->Read(&rotV,sizeof(rotV)); +f->Read(&rotA,sizeof(rotA)); +return TRUE; +} +bool pDriveLineComp::SaveState(QFile *f) +{ +f->Write(&rotV,sizeof(rotV)); +f->Write(&rotA,sizeof(rotA)); +return TRUE; +} +*/ \ No newline at end of file diff --git a/usr/Src/old/Core/pVehicle/pEngine.cpp b/usr/Src/old/Core/pVehicle/pEngine.cpp new file mode 100644 index 0000000..6a97259 --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pEngine.cpp @@ -0,0 +1,619 @@ +#include "vtPhysXAll.h" + +#include "pEngine.h" +#include + + +// Local trace? +//#define LTRACE + +#define DEF_SIZE .25 +#define DEF_MAXRPM 5000 +#define DEF_MAXPOWER 100 +#define DEF_FRICTION 0 +#define DEF_MAXTORQUE 340 // ~ F1 Jos Verstappen + +#define DEF_TORQUE 100 // In case no curve is present + +//#define LTRACE + + +// If USE_HARD_REVLIMIT is used, any rpm above the max. RPM +// returns a 0 engine torque. Although this works, it gives quite +// hard rev limits (esp. when in 1st gear). Better is to supply +// a curve which moves down to 0 torque when rpm gets above maxRPM, +// so a more natural (smooth) balance is obtained (and turn +// this define off) +//#define USE_HARD_REVLIMIT + +pEngine::pEngine(pVehicle *_car) + : pDriveLineComp() +{ + SetName("engine"); + car=_car; + driveLine=car->GetDriveLine(); + crvTorque=0; + Init(); +} + +pEngine::~pEngine() +{ + /* + if(quad)gluDeleteQuadric(quad); + QDELETE(crvTorque); + */ +} + +void pEngine::Init() +// Init all member variables +{ + + flags=0; + size=DEF_SIZE; + + mass=0; + torqueReaction=0; + maxRPM=DEF_MAXRPM; + idleRPM=500; + stallRPM=400; + startRPM=500; + autoClutchRPM=idleRPM*1.5f; + //autoClutch=0; + starterTorque=50; + idleThrottle=0.1f; + throttleRange=1000.0-idleThrottle*1000.0; + friction=0; + brakingCoeff=0; + position.Set(0,0,0); + + maxTorque=0; + throttle=0; + brakes=0; + + //QDELETE(crvTorque); + + Reset(); +} + +void pEngine::Reset() +// Reset engine before usage (after Shift-R for example) +{ + torqueReaction=0; + + pDriveLineComp::Reset(); + + // No automatic clutch engaged + //flags&=~AUTOCLUTCH_ACTIVE; + flags|=AUTOCLUTCH_ACTIVE; + + // Start engine (or not) and make it stable; AFTER RDLC:Reset(), since that + // sets the rotational velocity to 0. + if(flags&START_STALLED) + { + // Start with the engine off + EnableStall(); + SetRPM(0); + } else + { + // Pre-start engine + DisableStall(); + SetRPM(idleRPM); + } +} + +/********** +* Attribs * +**********/ +void pEngine::SetRPM(float rpm) +{ + // Convert to radians and seconds + rotV=rpm*2*PI/60.0f; +} + + +/************* +* Definition * +*************/ +void pEngine::PreCalculate() +// Precalculate known numbers to speed up calculations during gameplay +{ + float minT,maxT; + + // Calculate idle throttle based on desired idle RPM + maxT=GetMaxTorque(idleRPM); + minT=GetMinTorque(idleRPM); + if(fabs(minT)SetDefaultMaterial(); + + glPushMatrix(); + + // Location + glTranslatef(position.GetX(),position.GetY(),position.GetZ()); + +#ifdef OBS + // Stats + char buf[80]; + float p; + // Calc generated power in Watts (J/s) + // Note also that 1hp = 746W + p=2*PI*(rpm/60)*torque; + sprintf(buf,"RPM=%.f, Torque=%.f Nm, Power %.3fhp, Gear-ratio %.2f", + rpm,torque,p/746,gearRatio[curGear]*endRatio); + GfxText3D(position.GetX(),position.GetY(),position.GetZ(),buf); +#endif + + // Discs are painted at Z=0 + //glRotatef(90,0,1,0); + + // Center point for quad + //glTranslatef(0,0,-size/2); + + float colMotor[]={ .8,.8,.82 }; + int slices=6; + glMaterialfv(GL_FRONT,GL_DIFFUSE,colMotor); + // Draw a box (=cylinder with 4 slices) + gluCylinder(quad,size,size,size,slices,1); + + // Caps + gluQuadricOrientation(quad,GLU_INSIDE); + gluDisk(quad,0,size,slices,1); + gluQuadricOrientation(quad,GLU_OUTSIDE); + glTranslatef(0,0,size); + gluDisk(quad,0,size,slices,1); + + glPopMatrix(); +#endif +} +*/ + +/******** +* Input * +********/ +void pEngine::SetInput(int ctlThrottle) +// Controller input from 0..1000 +// Calculates resulting throttle. +{ + // Convert throttle to 0..1 (mind idle throttle offset) + throttle=((float)ctlThrottle)*throttleRange+idleThrottle; + if(throttle>1)throttle=1; + else if(throttle<0)throttle=0; + +//qdbg("pEngine:SetInput(); ctlT=%d, throttle=%f\n",ctlThrottle,throttle); +//qdbg(" idleThrottle=%f, idleRPM=%f\n",idleThrottle,idleRPM); +//qdbg("pEngine:SetInput(ctlClutch=%d)\n",ctlClutch); +#ifdef ND_AUTO_CLUTCH + // Only update clutch value when the car is not auto-shifting + if(!autoShiftStart) + { + clutch=((float)ctlClutch)/1000.0f; + if(clutch>1)clutch=1; + else if(clutch<0)clutch=0; + } +#else + // Pass clutch on to driveline + //driveLine->SetClutchApplication(((float)ctlClutch)/1000.0f); + // Directly set clutch + //clutch=((float)ctlClutch)/1000.0f; + //if(clutch>1)clutch=1; + //else if(clutch<0)clutch=0; +#endif +} + +/******************** +* Torque generation * +********************/ +float pEngine::GetMaxTorque(float rpm) +// Returns the maximum torque generated at 'rpm' +{ +#ifdef USE_HARD_REVLIMIT + // Clip hard at max rpm (return 0 torque if rpm gets too high) + if(rpm>maxRPM) + return 0; +#endif + if(!crvTorque) + { + // No curve available, use a less realistic constant torque + return DEF_TORQUE; + } else + { + float t; + // Find normalized torque in RPM-to-torque curve +// t=(float)crvTorque->GetValue(rpm); +//qdbg("pEngine: rpm=%.2f => T=%.2f, (curve)maxTorque=%.2f\n",rpm,t,maxTorque); + return t*maxTorque; + } +} +// Returns the minimum torque generated at 'rpm' (engine braking). +float pEngine::GetMinTorque(float rpm) + +{ + // If 0% throttle, this is the minimal torque which is generated + // by the engine + return -brakingCoeff*rpm/60.0f; +} + + +/************** +* Calc Forces * +**************/ +void pEngine::CalcForces() +{ + float minTorque,maxTorque; + float rpm=GetRPM(); + static int starterDelay; // Temp crap to avoid multiple starter smps + +#ifdef LTRACE + qdbg("pEngine::CalcForces()\n"); + qdbg(" rpm=%f, throttle=%.2f\n",rpm,throttle); +#endif + + if(starterDelay>0) + starterDelay--; + + // Check starter; this section assumes CalcForces() is called + // only once per simulation step. Although this may not be + // the case in the future, it should not harm that much. + if(IsStalled()) + { + // There's only some engine braking + // Note this skips calculating min/maxTorque + tEngine=GetMinTorque(rpm); +//qdbg("Stalled; check starter=%d\n",RMGR->controls->control[RControls::T_STARTER]->value); + bool starter = true; + if(starter) + { + + // Use the starter + tEngine+=starterTorque; + // Raise the starter sample volume + if(starterDelay==0) + { + starterDelay=1000/car->_lastDT; + } + + +#ifdef LTRACE + qdbg(" starting; T_starter=%f, tEngine=%f\n",starterTorque,tEngine); +#endif + + + } +#ifdef LTRACE + qdbg("Stalled engine torque: %.3f\n",tEngine); +#endif + } else + { + // Engine is running + // Calculate minimal torque (if 0% throttle) + minTorque=GetMinTorque(rpm); + + // Calculate maximum torque (100% throttle situation) + maxTorque=GetMaxTorque(rpm); + + // The throttle accounts for how much of the torque is actually + // produced. + // NOTE: The output power then is 2*PI*rps*outputTorque + // (rps=rpm/60; rotations per second). Nothing but a statistic now. + tEngine=(maxTorque-minTorque)*throttle+minTorque; +#ifdef LTRACE + qdbg("minTorque=%f, maxTorque=%.f, throttle=%f => torque=%f\n",minTorque,maxTorque,throttle,tEngine); +#endif + + + } +} + +/********************* +* Calc accelerations * +*********************/ +void pEngine::CalcAccelerations() +{ +#ifdef LTRACE + qdbg("pEngine:CalcAcc()\n"); +#endif + + if(!driveLine->IsPrePostLocked()) + { + // Engine moves separately from the rest of the driveLine + rotA=(tEngine-driveLine->GetClutchTorque())/GetInertia(); +#ifdef LTRACE + qdbg(" tEngine=%.2f, tClutch=%.2f, rotA=%.2f\n",tEngine,driveLine->GetClutchTorque(),rotA); +#endif + } // else rotA is calculated in the driveline (passed up + // from the wheels on to the root - the engine) +} + +/************ +* Integrate * +************/ +void pEngine::Integrate() +// Step the engine. +// Also looks at the stall state (you can kickstart the engine when driving). +{ + float rpm=GetRPM(); +//qdbg("pEngine:Integrate()\n"); +//qdbg(" rotV=%.2f, rotA=%.2f\n",rotV,rotA); + + // This is normally done by RDriveLineComp, but avoid the function call + rotV+=rotA*RR_TIMESTEP; + + // Deduce state of engine (stalling) + if(IsStalled()) + { + // Turning back on? + if(rpm>=startRPM) + { +//qdbg("UNStalling engine!\n"); + DisableStall(); + } + } else + { + // Stalling? + if(rpmGetDriveLine()->EnableAutoClutch(); + //flags|=AUTOCLUTCH_ACTIVE; + if(autoClutch<0)autoClutch=0; + else if(autoClutch>1)autoClutch=1; + car->GetDriveLine()->SetClutchApplication(autoClutch); + } else + { + // Turn off auto-clutch + car->GetDriveLine()->DisableAutoClutch(); + } + + } + +//qdbg(" post rotV=%.2f\n",rotV); +} + + +void pEngine::setToDefault() +{ + + + char buf[128],fname[128]; + position.Set(0,0,0); + size = 0.0f; + maxRPM = 8000; + idleRPM = 1110; + mass = 0.0f; + + // Physical attribs +#ifdef OBS + sprintf(buf,"%s.rolling_friction_coeff",path); + rollingFrictionCoeff=info->GetFloat(buf); +#endif + + torqueReaction=1.0f; + maxTorque=468; + SetInertia(0.35f); + +#ifdef OBS + sprintf(buf,"%s.inertia.final_drive",path); + inertiaDriveShaft=info->GetFloat(buf); +#endif + + friction=0.0f; + brakingCoeff=3.3f; + //flags|=HAS_STARTER; +// if(info->GetInt(buf,1)) +// flags|=START_STALLED; +// sprintf(buf,"%s.starter_torque",path); + starterTorque=90.0f; + stallRPM=400.0f; + stallRPM=1250.0f; + autoClutchRPM=1250.0f; + + //flags|=AUTOMATIC; + flags|=AUTOCLUTCH_ACTIVE; + + PreCalculate(); + + + + +} + +/* +bool pEngine::Load(QInfo *info,cstring path) +// 'path' may be 0, in which case the default "engine" is used +{ + char buf[128],fname[128]; + QInfo *infoCurve; + + if(!path)path="engine"; + + // Location + sprintf(buf,"%s.x",path); + position.x=info->GetFloat(buf); + sprintf(buf,"%s.y",path); + position.y=info->GetFloat(buf); + sprintf(buf,"%s.z",path); + position.z=info->GetFloat(buf); + sprintf(buf,"%s.size",path); + size=info->GetFloat(buf,DEF_SIZE); + + // Physical attribs +#ifdef OBS + sprintf(buf,"%s.rolling_friction_coeff",path); + rollingFrictionCoeff=info->GetFloat(buf); +#endif + sprintf(buf,"%s.mass",path); + mass=info->GetFloat(buf); + + // Power/torque + sprintf(buf,"%s.max_rpm",path); + maxRPM=info->GetFloat(buf,DEF_MAXRPM); + sprintf(buf,"%s.idle_rpm",path); + idleRPM=info->GetFloat(buf,1000); + + // Torque reaction + sprintf(buf,"%s.torque_reaction",path); + torqueReaction=info->GetFloat(buf); + + // Torque curve or constant (curve is preferred) + //sprintf(buf,"%s.constant_torque",path); + sprintf(buf,"%s.max_torque",path); + maxTorque=info->GetFloat(buf,DEF_MAXTORQUE); + crvTorque=new QCurve(); + sprintf(buf,"%s.curve_torque",path); + info->GetString(buf,fname); + + //qdbg("fname_torque='%s', maxTorque=%.2f\n",fname,maxTorque); + if(fname[0]) + { + + infoCurve=new QInfo(RFindFile(fname,car->GetDir())); + crvTorque->Load(infoCurve,"curve"); + QDELETE(infoCurve); + + + } else + { // No torque curve + //QDELETE(crvTorque); + } + + // Check torque curve in that it makes sense and is usable + if(!crvTorque) + { + //qwarn("No torque curve (torque.crv?) present; you really should have one"); + } else + { + // Make sure it ends at 0 (assuming no engine will rev above 100,000 rpm) + if(fabs(crvTorque->GetValue(100000))>D3_EPSILON) + { + //qwarn("The torque curve needs to end at 0 torque (is now %.2f)", crvTorque->GetValue(100000)); + } + } + + sprintf(buf,"%s.inertia.engine",path); + SetInertia(info->GetFloat(buf)); + //inertiaEngine=info->GetFloat(buf); +#ifdef OBS + sprintf(buf,"%s.inertia.final_drive",path); + inertiaDriveShaft=info->GetFloat(buf); +#endif + sprintf(buf,"%s.friction",path); + friction=info->GetFloat(buf,DEF_FRICTION); + sprintf(buf,"%s.braking_coeff",path); + brakingCoeff=info->GetFloat(buf); + + // Starter engine + sprintf(buf,"%s.starter",path); + if(info->GetInt(buf,1)) + flags|=HAS_STARTER; + sprintf(buf,"%s.start_stalled",path); + if(info->GetInt(buf,1)) + flags|=START_STALLED; + sprintf(buf,"%s.starter_torque",path); + starterTorque=info->GetFloat(buf); + sprintf(buf,"%s.stall_rpm",path); + stallRPM=info->GetFloat(buf); + sprintf(buf,"%s.start_rpm",path); + startRPM=info->GetFloat(buf); + sprintf(buf,"%s.autoclutch_rpm",path); + autoClutchRPM=info->GetFloat(buf); + +#ifdef OBS + // Shifting + sprintf(buf,"%s.shifting.automatic",path); + if(info->GetInt(buf)) + flags|=AUTOMATIC; + //qdbg("Autoshift: flags=%d, buf='%s'\n",flags,buf); + sprintf(buf,"%s.shifting.shift_up_rpm",path); + shiftUpRPM=info->GetFloat(buf,3500); + sprintf(buf,"%s.shifting.shift_down_rpm",path); + shiftDownRPM=info->GetFloat(buf,2000); + sprintf(buf,"%s.shifting.time_to_declutch",path); + timeToDeclutch=info->GetInt(buf,500); + sprintf(buf,"%s.shifting.time_to_clutch",path); + timeToClutch=info->GetInt(buf,500); + + // Gearbox + path="gearbox"; // ! + sprintf(buf,"%s.gears",path); + gears=info->GetInt(buf,4); + for(i=0;iGetFloat(buf,1.0); + sprintf(buf,"%s.gear%d.inertia",path,i); + gearInertia[i]=info->GetFloat(buf); + } + sprintf(buf,"%s.end_ratio",path); + endRatio=info->GetFloat(buf,3.0); +#endif + + // Calculate static facts + PreCalculate(); + + return TRUE; +} +*/ + +/* +void pEngine::OnGfxFrame() +{ +} + +void pEngine::DbgPrint(cstring s) +{ +qdbg("pEngine state (%s):\n",s); +qdbg(" rpm=%.2f, stalled: %d, idleThrottle: %.2f, Treaction=%.2f\n", +GetRPM(),IsStalled(),idleThrottle,torqueReaction); +} + + +bool pEngine::LoadState(QFile *f) +{ +RDriveLineComp::LoadState(f); +return TRUE; +} +bool pEngine::SaveState(QFile *f) +{ +RDriveLineComp::LoadState(f); +return TRUE; +} +*/ diff --git a/usr/Src/old/Core/pVehicle/pGearBox.cpp b/usr/Src/old/Core/pVehicle/pGearBox.cpp new file mode 100644 index 0000000..f21affc --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pGearBox.cpp @@ -0,0 +1,396 @@ +#include "pGearbox.h" +#include "vtPhysXAll.h" + +#include + +#define DEF_SIZE .25 +#define DEF_MAXRPM 5000 +#define DEF_MAXPOWER 100 +#define DEF_FRICTION 0 +#define DEF_MAXTORQUE 340 // ~ F1 Jos Verstappen + +#define DEF_TORQUE 100 // In case no curve is present + +// If USE_HARD_REVLIMIT is used, any rpm above the max. RPM +// returns a 0 engine torque. Although this works, it gives quite +// hard rev limits (esp. when in 1st gear). Better is to supply +// a curve which moves down to 0 torque when rpm gets above maxRPM, +// so a more natural (smooth) balance is obtained (and turn +// this define off) +//#define USE_HARD_REVLIMIT + + +void pGearBox::SetGear(int gear) +{ + +/*#ifdef LTRACE +qdbg("pGearBox:SetGear(%d)\n",gear); +#endif +*/ + //QASSERT_V(gear>=0&&gearPreCalcDriveLine(); +} + + + +void pGearBox::CalcForces() +{ + +/*#ifdef LTRACE +//qdbg("pGearBox::CalcForces()\n"); +#endif + */ +} + +/************ +* Integrate * +************/ +void pGearBox::Integrate() +// Based on current input values, adjust the engine +{ + int t; + bool ac=true;// RMGR->IsEnabled(RManager::ASSIST_AUTOCLUTCH); + + pDriveLineComp::Integrate(); + + // The shifting process + if(autoShiftStart) + { + + + //t=RMGR->time->GetSimTime()-autoShiftStart; + t=car->_lastDT; + if(ac)car->GetDriveLine()->EnableAutoClutch(); + + // We are in a shifting operation + if(curGear!=futureGear) + { + + // We are in the pre-shift phase + if(t>=timeToDeclutch) + { + + //qdbg("Shift: declutch ready, change gear\n"); + // Declutch is ready, change gear + SetGear(futureGear); + // Trigger gear shift sample + //car->GetRAPGear()->GetSample()->Play(); + if(ac) + car->GetDriveLine()->SetClutchApplication(1.0f); + } else + { + // Change clutch + if(ac) + car->GetDriveLine()->SetClutchApplication((t*1000/timeToDeclutch)/1000.0f); + } + + } else + { + // We are in the post-shift phase + if(t>=timeToClutch+timeToDeclutch) + { +//qdbg("Shift: clutch ready, end shift\n"); + // Clutch is ready, end shifting process +#ifdef OBS_MANUAL_CLUTCH + clutch=1.0f; +#endif + // Conclude the shifting process + autoShiftStart=0; + if(ac) + { + + car->GetDriveLine()->SetClutchApplication(0.0f); + car->GetDriveLine()->DisableAutoClutch(); + } + } else + { + // Change clutch + + if(ac)car->GetDriveLine()->SetClutchApplication( + ((t-timeToClutch)*1000/timeToDeclutch)/1000.0f); + + } + } + } +} +void pGearBox::OnGfxFrame() +{ + /* +//qdbg("pGearBox:OnGfxFrame()\n"); + + if(autoShiftStart==0) + { + // No shift in progress; check shift commands from the controllers + if(RMGR->controls->control[RControls::T_SHIFTUP]->value) + { +//qdbg("Shift Up!\n"); + if(curGeartime->GetSimTime(); + switch(curGear) + { + case 0: futureGear=2; break; // From neutral to 1st + case 1: futureGear=0; break; // From reverse to neutral + default: futureGear=curGear+1; break; + } + } + } else if(RMGR->controls->control[RControls::T_SHIFTDOWN]->value) + { + autoShiftStart=RMGR->time->GetSimTime(); + if(curGear!=1) // Not in reverse? + { + switch(curGear) + { + case 0: futureGear=1; break; // From neutral to reverse + case 2: futureGear=0; break; // From 1st to neutral + default: futureGear=curGear-1; break; + } + } +qdbg("Switch back to futureGear=%d\n",futureGear); + } + } + */ +} +/* +bool pGearBox::LoadState(QFile *f) +{ +RDriveLineComp::LoadState(f); +f->Read(&curGear,sizeof(curGear)); +f->Read(&autoShiftStart,sizeof(autoShiftStart)); +f->Read(&futureGear,sizeof(futureGear)); +return TRUE; +} +bool pGearBox::SaveState(QFile *f) +{ +RDriveLineComp::SaveState(f); +f->Write(&curGear,sizeof(curGear)); +f->Write(&autoShiftStart,sizeof(autoShiftStart)); +f->Write(&futureGear,sizeof(futureGear)); +return TRUE; +} + +*/ +/* +bool pGearBox::Load(QInfo *info,cstring path) +// 'path' may be 0, in which case the default "engine" is used +{ +char buf[128]; +int i; + +if(!path)path="engine"; + +// Shifting (still in the 'engine' section for historical reasons) +sprintf(buf,"%s.shifting.automatic",path); +if(info->GetInt(buf)) +flags|=AUTOMATIC; +//qdbg("Autoshift: flags=%d, buf='%s'\n",flags,buf); +sprintf(buf,"%s.shifting.shift_up_rpm",path); +shiftUpRPM=info->GetFloat(buf,3500); +sprintf(buf,"%s.shifting.shift_down_rpm",path); +shiftDownRPM=info->GetFloat(buf,2000); +sprintf(buf,"%s.shifting.time_to_declutch",path); +timeToDeclutch=info->GetInt(buf,500); +sprintf(buf,"%s.shifting.time_to_clutch",path); +timeToClutch=info->GetInt(buf,500); + +//qdbg("declutch=%d, clutch=%d (buf=%s)\n",timeToDeclutch,timeToClutch,buf); + +// Gearbox +path="gearbox"; // ! +sprintf(buf,"%s.gears",path); +gears=info->GetInt(buf,4); +if(gears>=MAX_GEAR-1) +{ qwarn("Too many gears defined (%d, max=%d)",gears,MAX_GEAR-1); +gears=MAX_GEAR-1; +} +for(i=0;iGetFloat(buf,1.0); +sprintf(buf,"%s.gear%d.inertia",path,i); +gearInertia[i+1]=info->GetFloat(buf); +} + +return TRUE; +} +*/ + + + +#ifdef OBS + +float pGearBox::GetInertiaAtDifferential() +// Returns effective inertia as seen at the input of the differential. +// This may be used as the input for the differential. +// Notice the gearing from differential to engine. +{ + float totalInertia; + float ratio,ratioSquared; + + // From differential towards engine + // First, the driveshaft + ratio=endRatio; + ratioSquared=ratio*ratio; + totalInertia=inertiaDriveShaft*ratioSquared; + + // Gearing and engine + // Both engine and the faster rotating part of the gearbox are at + // the engine side of the clutch. Therefore, both interia's from those + // 2 objects must be scaled to get the effective inertia. + // Note this scaling factor is squared, for reasons + // I explain on the Racer website. + ratio=gearRatio[curGear]*endRatio; + ratioSquared=ratio*ratio; + totalInertia+=clutch*(gearInertia[curGear]+inertiaEngine)*ratioSquared; + return totalInertia; +} + +float pGearBox::GetInertiaForWheel(RWheel *w) +// Return effective inertia as seen in the perspective of wheel 'w' +// Takes into account any clutch effects +{ + float totalInertia; + float inertiaBehindClutch; + float NtfSquared,NfSquared; + //float rotationA; + RWheel *wheel; + int i; + + // Calculate total ratio multiplier; note the multipliers are squared, + // and not just a multiplier for the inertia. See Gillespie's book, + // 'Fundamentals of Vehicle Dynamics', page 33. + NtfSquared=gearRatio[curGear]*endRatio; + NtfSquared*=NtfSquared; + + // Calculate total inertia that is BEHIND the clutch + NfSquared=endRatio*endRatio; + inertiaBehindClutch=gearInertia[curGear]*NtfSquared+ + inertiaDriveShaft*NfSquared; + // Add inertia of attached and powered wheels + // This is a constant, so it should be cached actually (except + // when a wheel breaks off) + + /* for(i=0;iGetWheels();i++) + { + wheel=car->GetWheel(i); + if(wheel->IsPowered()&&wheel->IsAttached()) + inertiaBehindClutch+=wheel->GetRotationalInertia()->x; + } + */ + // Add the engine's inertia based on how far the clutch is engaged + /* + totalInertia=inertiaBehindClutch+clutch*inertiaEngine*NtfSquared; + */ + return totalInertia; +} +// Return effective torque for wheel 'w' +// Takes into account any clutch effects +float pGearBox::GetTorqueForWheel(pWheel *w) + +{ + //qdbg("clutch=%f, T=%f, ratio=%f\n",clutch,torque,gearRatio[curGear]*endRatio); + + //return clutch*torque*gearRatio[curGear]*endRatio; +} + + +#endif + + + +void pGearBox::setToDefault() +{ + + gears = 7; + gearRatio[0]=-2.59f; + gearInertia[0]=0.1f; + + gearRatio[1]=2.94f; + gearInertia[1]=0.06f; + + gearRatio[2]=2.056f; + gearInertia[2]=0.05f; + + gearRatio[3]=1.520f; + gearInertia[3]=0.04f; + + gearRatio[4]=1.179f; + gearInertia[4]=0.03f; + + gearRatio[5]=1.030f; + gearInertia[5]=0.02f; + + gearRatio[6]=0.914f; + gearInertia[6]=0.01f; + + autoShiftStart = 1; + timeToClutch=25.0f; + timeToDeclutch=352.0f; + shiftDownRPM= 3000.0f; + shiftUpRPM=7000.0f; + + + +} + +pGearBox::pGearBox(pVehicle *_car) +: pDriveLineComp() +{ + //SetName("gearbox"); + + car=_car; + Reset(); +} +pGearBox::~pGearBox() +{ +} + +void pGearBox::Reset() +// Reset all variables +{ + int i; + + flags=0; + timeToDeclutch=timeToClutch=0; + autoShiftStart=1; + futureGear=0; + for(i=0;i +#include "vtPhysXAll.h" + +#include "pVTireFunction.h" + + pTireFunction::pTireFunction() +{ + setToDefault(); +} + + void pTireFunction::setToDefault() +{ + extremumSlip = 1.0f; + extremumValue = 0.02f; + asymptoteSlip = 2.0f; + asymptoteValue = 0.01f; + stiffnessFactor = 1000000.0f; //quite stiff by default. + xmlLink =0; + +} + + bool pTireFunction::isValid() const +{ + if(!(0.0f < extremumSlip)) return false; + if(!(extremumSlip < asymptoteSlip)) return false; + if(!(0.0f < extremumValue)) return false; + if(!(0.0f < asymptoteValue)) return false; + if(!(0.0f <= stiffnessFactor)) return false; + + return true; +} + + + float pTireFunction::hermiteEval(float t) const +{ + + // This fix for TTP 3429 & 3675 is from Sega. + // Assume blending functions (look these up in a graph): + // H0(t) = 2ttt - 3tt + 1 + // H1(t) = -2ttt + 3tt + // H2(t) = ttt - 2tt + t + // H3(t) = ttt - tt + + float v = NxMath::abs(t); + float s = (t>=0) ? 1.0f : -1.0f; + + float F; + + if(v +#include "vtPhysXAll.h" + +#include "pVehicleMotor.h" +#include "pVehicleGears.h" + +#include +#include "NxArray.h" + + + +int pVehicle::_calculateCurrentStatus() +{ + + int result = 0; + + //---------------------------------------------------------------- + // + // is moving ? + // + { + + _computeLocalVelocity(); + if ( NxMath::abs(_localVelocity.z) > 0.1f) + result |=VS_IsMoving; + } + + NxVec3 _loc = _localVelocity; + //---------------------------------------------------------------- + // + // is accelerated ? + // + + if ( _cAcceleration > 0.1f ) + result |=VS_IsAcceleratedForward; + + if ( _cAcceleration < 0.0f ) + result |=VS_IsAcceleratedBackward; + + if ( (result & VS_IsAcceleratedForward) || (result & VS_IsAcceleratedBackward) ) + result |=VS_IsAccelerated; + + //---------------------------------------------------------------- + // + // is Braking ? + // + if ( (result & VS_IsMoving ) ) + { + if ( _localVelocity.z > 0.0f && ( result & VS_IsAcceleratedBackward ) ) + { + result |=VS_IsBraking; + } + + if ( _localVelocity.z < 0.0f && (result & VS_IsAcceleratedForward ) ) + { + result |=VS_IsBraking; + } + } + + //---------------------------------------------------------------- + // + // is steering + // + if( XAbs(_cSteering) > 0.01f ) + result|=VS_IsSteering; + + //---------------------------------------------------------------- + // + // is falling + handbrake + // + + _nbNotTouching =0; + _nbTouching =0; + _nbHandbrakeOn =0; + + int nbWheels = _wheels.size(); + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if (!wheel->hasGroundContact()) + { + _nbNotTouching++; + } else { + _nbTouching++; + } + + if(_cHandbrake && wheel->getWheelFlag(WF_AffectedByHandbrake)) + { + _nbHandbrakeOn++; + } + } + if (_nbNotTouching == _wheels.size()) + result |= VS_IsFalling; + + if (_cHandbrake && _nbHandbrakeOn ) + { + result|=VS_Handbrake; + } + + + /* + if ( !(result & VS_IsBraking) ) + { + mBreakLastFrame = false; + mTimeBreaking = 0.0f; + } + */ + + _accelerationPedal = _cAcceleration; + return result; +} + + + + +void pVehicle::updateControl(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) +{ + setControlState(E_VCS_ACCELERATION,acceleration); + setControlState(E_VCS_HANDBRAKE,handBrake); + setControlState(E_VCS_STEERING,steering); + setControlMode(E_VCS_ACCELERATION,analogAcceleration ? E_VCSM_ANALOG : E_VCSM_DIGITAL); + setControlMode(E_VCS_STEERING, analogSteering ? E_VCSM_ANALOG : E_VCSM_DIGITAL); + + +} +void pVehicle::control(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) +{ + + if (steering != 0 || acceleration != 0 || handBrake) + getActor()->wakeUp(0.05); + + return; + + _controlSteering(steering, analogSteering); + _computeLocalVelocity(); + + NxVec3 locVel = _localVelocity; + float lcx = locVel.x; + float lcz = locVel.z; + + + float test = _localVelocity.z * acceleration < ( NxMath::sign(-acceleration) ); + float test2 = _localVelocity.z * acceleration < ( -0.1f ); + float test3 = XAbs(_localVelocity.z) * acceleration < ( -0.1f ); + + + if (!_braking || _releaseBraking) + { + //_braking = _localVelocity.x * acceleration < (-0.1f /** NxMath::sign(-acceleration) */); + _braking = _localVelocity.z * acceleration < ( -0.1 /*NxMath::sign(acceleration) */ ); + + //_braking = _localVelocity.z * acceleration < ( NxMath::sign(acceleration)); + _releaseBraking = false; + } + + if(_handBrake != handBrake) + { + _handBrake = handBrake; + _brakePedalChanged; + } + //printf("Braking: %s, Handbrake: %s\n", _braking?"true":"false", handBrake?"true":"false"); + _controlAcceleration(acceleration, analogAcceleration); +} + + +void pVehicle::updateVehicle( float lastTimeStepSize ) +{ + _lastDT = lastTimeStepSize; + + _currentStatus = _calculateCurrentStatus(); + + + + + VehicleStatus status = (VehicleStatus)_currentStatus; + + if (_cSteering != 0 || _cAcceleration != 0 || _cHandbrake) + getActor()->wakeUp(0.05); + + _performAcceleration(lastTimeStepSize); + _performSteering(lastTimeStepSize); + + if (getMotor()) + { + _currentStatus |= E_VSF_HAS_MOTOR; + } + + if (getGears()) + { + _currentStatus |= E_VSF_HAS_GEARS; + } + + setVSFlags(_currentStatus); + + if (engine && gearbox && driveLine ) + { + + doEngine(0,lastTimeStepSize); + + } + + + return; + + //---------------------------------------------------------------- + // + // old code + // + + //control(_cSteering,_cAnalogSteering,_cAcceleration,_cAnalogAcceleration,_cHandbrake); + //printf("updating %x\n", this); + + NxReal distanceSteeringAxisCarTurnAxis = _steeringSteerPoint.x - _steeringTurnPoint.x; + NX_ASSERT(_steeringSteerPoint.z == _steeringTurnPoint.z); + NxReal distance2 = 0; + if (NxMath::abs(_steeringWheelState) > 0.01f) + distance2 = distanceSteeringAxisCarTurnAxis / NxMath::tan(_steeringWheelState * _steeringMaxAngleRad); + + NxU32 nbTouching = 0; + NxU32 nbNotTouching = 0; + NxU32 nbHandBrake = 0; + int wSize = _wheels.size(); + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_SteerableInput)) + { + if(distance2 != 0) + { + NxReal xPos = wheel->getWheelPos().x; + NxReal xPos2 = _steeringSteerPoint.x- wheel->getWheelPos().x; + NxReal zPos = wheel->getWheelPos().z; + NxReal dz = -zPos + distance2; + NxReal dx = xPos - _steeringTurnPoint.x; + float atan3 = NxMath::atan(dx/dz); + + float angle =(NxMath::atan(dx/dz)); + if (dx < 0.0f) + { + angle*=-1.0f; + } + wheel->setAngle(angle); + //errMessage.Format("w%d dz:%f dx:%f dx2%f distance:%f atan3:%f",i,dz,dx,xPos2,distance2,atan3); + //xInfo(errMessage.Str()); + + + } else { + wheel->setAngle(0.0f); + } + //printf("%2.3f\n", wheel->getAngle()); + + } else if(wheel->getWheelFlag(WF_SteerableAuto)) + { + NxVec3 localVelocity = getActor()->getLocalPointVelocity(getFrom(wheel->getWheelPos())); + NxQuat local2Global = getActor()->getGlobalOrientationQuat(); + local2Global.inverseRotate(localVelocity); + // printf("%2.3f %2.3f %2.3f\n", wheel->getWheelPos().x,wheel->getWheelPos().y,wheel->getWheelPos().z); + localVelocity.y = 0; + if(localVelocity.magnitudeSquared() < 0.1f) + { + wheel->setAngle(0.0f); + } else { + localVelocity.normalize(); + // printf("localVelocity: %2.3f %2.3f\n", localVelocity.x, localVelocity.z); + if(localVelocity.x < 0) + localVelocity = -localVelocity; + NxReal angle = NxMath::clamp((NxReal)atan(localVelocity.z / localVelocity.x), 0.3f, -0.3f); + wheel->setAngle(angle); + } + } + + // now the acceleration part + if(!wheel->getWheelFlag(WF_Accelerated)) + continue; + + if(_handBrake && wheel->getWheelFlag(WF_AffectedByHandbrake)) + { + nbHandBrake++; + } + else + { + if (!wheel->hasGroundContact()) + { + nbNotTouching++; + } else { + nbTouching++; + } + } + } + + NxReal motorTorque = 0.0; + float _acc = NxMath::abs(_accelerationPedal); + + XString errMessage; + if(nbTouching && NxMath::abs(_accelerationPedal) > 0.1f ) + { + NxReal axisTorque = _computeAxisTorque(); + NxReal wheelTorque = axisTorque / (NxReal)(_wheels.size() - nbHandBrake); + NxReal wheelTorqueNotTouching = nbNotTouching>0?wheelTorque*(NxMath::pow(0.5f, (NxReal)nbNotTouching)):0; + NxReal wheelTorqueTouching = wheelTorque - wheelTorqueNotTouching; + motorTorque = wheelTorqueTouching / (NxReal)nbTouching; + } else { + _updateRpms(); + } + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + wheel->tick(_handBrake, motorTorque, _brakePedal, lastTimeStepSize); + //wheel->tick(_handBrake, motorTorque, _brakePedal, 1/60); + } + +} + + +pWheel*pVehicle::getWheel(CK3dEntity *wheelReference) +{ + + if (!wheelReference) + { + return NULL; + } + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if (wheel->getEntID() == wheelReference->GetID()) + { + return wheel; + } + } + return NULL; +} +void pVehicle::handleContactPair(NxContactPair* pair, int carIndex) +{ + NxContactStreamIterator i(pair->stream); + + while(i.goNextPair()) + { + NxShape * s = i.getShape(carIndex); + + while(i.goNextPatch()) + { + const NxVec3& contactNormal = i.getPatchNormal(); + + while(i.goNextPoint()) + { + //user can also call getPoint() and getSeparation() here + + const NxVec3& contactPoint = i.getPoint(); + + //add forces: + + //assuming front wheel drive we need to apply a force at the wheels. + if (s->is(NX_SHAPE_CAPSULE) && s->userData != NULL) { + //assuming only the wheels of the car are capsules, otherwise we need more checks. + //this branch can't be pulled out of loops because we have to do a full iteration through the stream + + + NxQuat local2global = s->getActor().getGlobalOrientationQuat(); + /* + NxWheel* w = (NxWheel*)s->userData; + if (!w->getWheelFlag(E_WF_USE_WHEELSHAPE)) + { + NxWheel1 * wheel = static_cast(w); + wheel->contactInfo.otherActor = pair.actors[1-carIndex]; + wheel->contactInfo.contactPosition = contactPoint; + + wheel->contactInfo.contactPositionLocal = contactPoint; + wheel->contactInfo.contactPositionLocal -= _bodyActor->getGlobalPosition(); + local2global.inverseRotate(wheel->contactInfo.contactPositionLocal); + + wheel->contactInfo.contactNormal = contactNormal; + if (wheel->contactInfo.otherActor->isDynamic()) + { + NxVec3 globalV = s->getActor().getLocalPointVelocity(wheel->getWheelPos()); + globalV -= wheel->contactInfo.otherActor->getLinearVelocity(); + local2global.inverseRotate(globalV); + wheel->contactInfo.relativeVelocity = globalV.x; + //printf("%2.3f (%2.3f %2.3f %2.3f)\n", wheel->contactInfo.relativeVelocity, + // globalV.x, globalV.y, globalV.z); + } + else + { + NxVec3 vel = s->getActor().getLocalPointVelocity(wheel->getWheelPos()); + local2global.inverseRotate(vel); + wheel->contactInfo.relativeVelocity = vel.x; + wheel->contactInfo.relativeVelocitySide = vel.z; + } + NX_ASSERT(wheel->hasGroundContact()); + //printf(" Wheel %x is touching\n", wheel); + } + */ + } + } + } + } + //printf("----\n"); +} +float pVehicle::_computeAxisTorqueV2() +{ + if(_vehicleMotor != NULL) + { + NxReal rpm = _computeRpmFromWheels(); + NxReal motorRpm = _computeMotorRpm(rpm); + _vehicleMotor->setRpm(motorRpm); + float acc = _accelerationPedal; + NxReal torque = _accelerationPedal * _vehicleMotor->getTorque(); + NxReal v = getActor()->getLinearVelocity().magnitude(); + + /* + printf("v: %2.3f m/s (%2.3f km/h)\n", v, v*3.6f); + printf("rpm %2.3f, motorrpm %2.3f, torque %2.3f, realtorque %2.3f\n", + rpm, motorRpm, torque, torque*_getGearRatio()*_differentialRatio*_transmissionEfficiency); + */ + return torque * _getGearRatio() * _differentialRatio * _transmissionEfficiency; + } else { + _computeRpmFromWheels(); + return _cAcceleration * _motorForce; + } +} +float pVehicle::_computeRpmFromWheels() +{ + NxReal wheelRpms = 0; + NxI32 nbWheels = 0; + int nbAcc=0; + int nbNotAcc=0; + + int s = _wheels.size(); + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if (wheel->getWheelFlag(WF_Accelerated)) + { + nbWheels++; + wheelRpms += wheel->getRpm(); + } + + + } + return wheelRpms / (NxReal)nbWheels; +} + + +float pVehicle::_getGearRatio() +{ + if(_vehicleGears == NULL) + { + return 1; + } else { + return _vehicleGears->getCurrentRatio(); + } +} +void pVehicle::gearUp() +{ + if (_vehicleGears) + { + printf("Changing gear from %d to", _vehicleGears->getGear()); + _vehicleGears->gearUp(); + printf(" %d\n", _vehicleGears->getGear()); + } else { + printf("gearUp not supported if no gears available\n"); + } +} +void pVehicle::gearDown() +{ + if(_vehicleGears) + { + printf("Changing gear from %d to", _vehicleGears->getGear()); + _vehicleGears->gearDown(); + printf(" %d\n", _vehicleGears->getGear()); + } else { + printf("gearDown not supported if no gears available\n"); + } +} + +void pVehicle::setAutomaticMode(bool autoMode) +{ + mAutomaticMode=autoMode; + +} +float pVehicle::_computeMotorRpm(float rpm) +{ + NxReal temp = _getGearRatio() * _differentialRatio; + NxReal motorRpm = rpm * temp; + NxI32 change = -1; + if(_vehicleMotor) + { + NxI32 change; + if(_vehicleGears && (change = _vehicleMotor->changeGears(_vehicleGears, 0.2f))) + { + change = _vehicleMotor->changeGears(_vehicleGears, 0.2f); + if(change == 1 && mAutomaticMode ) + { + gearUp(); + } else { + NX_ASSERT(change == -1); + gearDown(); + } + } + temp = _getGearRatio() * _differentialRatio; + motorRpm = NxMath::max(rpm * temp, _vehicleMotor->getMinRpm()); + } + return motorRpm; +} +void pVehicle::_updateRpms() +{ + NxReal rpm = _computeRpmFromWheels(); + if(_vehicleMotor != NULL) + { + NxReal motorRpm = _computeMotorRpm(rpm); + _vehicleMotor->setRpm(motorRpm); + } +} +NxActor* pVehicle::getActor(){ return mActor; } + + + +float pVehicle::getDriveVelocity() +{ + return NxMath::abs(_localVelocity.x); +} + +const pWheel*pVehicle::getWheel(int i) +{ + NX_ASSERT(i < _wheels.size()); + return _wheels[i]; + +} + + + + + + +void pVehicle::_computeLocalVelocity() +{ + _computeMostTouchedActor(); + NxVec3 relativeVelocity; + if (_mostTouchedActor == NULL || !_mostTouchedActor->isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - _mostTouchedActor->getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + NxQuat global2Local; + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + char master[512]; + + //sprintf(master,"Velocity: %2.3f %2.3f %2.3f\n", _localVelocity.x, _localVelocity.y, _localVelocity.z); + //OutputDebugString(master); +} +void pVehicle::_controlSteering(float steering, bool analogSteering) +{ + if(analogSteering) + { + _steeringWheelState = steering; + } else if (NxMath::abs(steering) > 0.0001f) { + _steeringWheelState += NxMath::sign(steering) * getDigitalSteeringDelta(); + } else if (NxMath::abs(_steeringWheelState) > 0.0001f) { + _steeringWheelState -= NxMath::sign(_steeringWheelState) * getDigitalSteeringDelta(); + } + _steeringWheelState = NxMath::clamp(_steeringWheelState, 1.f, -1.f); +} + +void pVehicle::_computeMostTouchedActor() +{ + std::map actors; + typedef std::map Map; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + NxActor* curActor = _wheels[i]->getTouchedActor(); + Map::iterator it = actors.find(curActor); + if (it == actors.end()) + { + actors[curActor] = 1; + } else { + it->second++; + } + } + + NxU32 count = 0; + _mostTouchedActor = NULL; + for(Map::iterator it = actors.begin(); it != actors.end(); ++it) + { + if(it->second > count) + { + count = it->second; + _mostTouchedActor = it->first; + } + } +} + + +int pVehicle::initWheels(int flags) +{ + getWheels().clear(); + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + pWheel *wheel = sinfo->wheel; + pWheel2* wheel2 = (pWheel2*)wheel; + NxWheelShape *wShape = wheel2->getWheelShape(); + if (!wShape) continue; + if (wheel2->getWheelFlag(WF_VehicleControlled) ) + { + getWheels().push_back(wheel); + wheel2->setVehicle(this); + + } + } + } + } + + return getWheels().size(); + + + /* + int result = 0 ; + + if (!getBody() || !getBody()->isValid() ) + { + return result; + } + + getWheels().clear(); + + + CK3dEntity* subEntity = NULL; + while (subEntity= getBody()->GetVT3DObject()->HierarchyParser(subEntity) ) + { + if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) + { + pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + if (subDescr->flags & BF_SubShape) + { + if (subDescr->hullType == HT_Wheel) + { + + if (subEntity->HasAttribute(GetPMan()->att_wheelDescr )) + { + CKParameter *par = subEntity->GetAttributeParameter(GetPMan()->att_wheelDescr ); + if (par) + { + pWheelDescr *wDescr = pFactory::Instance()->createWheelDescrFromParameter(par); + if (wDescr) + { + pWheel *wheel = pFactory::Instance()->createWheel(getBody(),*wDescr); + if (wheel) + { + NxWheelShape *wShape = static_cast(getBody()->_getSubShapeByEntityID(subEntity->GetID())); + + if(wDescr->wheelFlags & E_WF_USE_WHEELSHAPE) + { + pWheel2 *wheel2 = static_cast(wheel); + if (wheel2) + { + if(wShape) + wheel2->setWheelShape(wShape); + + } + } + wheel->setEntID(subEntity->GetID()); + getWheels().push_back(wheel); +// subEntity->SetParent(NULL); + + } + } + } + } + } + } + } + } + + + + return getWheels().size(); + */ +} + +void pVehicle::findDifferentialWheels(int& wheel1Index,int& wheel2Index) +{ + pWheel *wheel1 = NULL; + pWheel* wheel2 = NULL; + wheel1 = wheel2 = 0; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + + + pWheel *cW = _wheels[i]; + + if (cW->getWheelFlag(WF_AffectedByDifferential)) + { + if (!wheel1){ + wheel1 = cW; wheel1Index=i; } + else{ + wheel2 = cW;wheel2Index=i; } + } + } + if (!wheel1) + { + xWarning("couldn't find first differential wheel"); + wheel1Index = -1; + } + + if (!wheel2) + { + xWarning("couldn't find second differential wheel"); + wheel2Index = -1; + } +} + +pVehicle::pVehicle() +{ + +} +void pVehicle::setControlState(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) +{ + _cAcceleration = acceleration; + _cSteering = steering; + + _cAnalogAcceleration = analogAcceleration; + _cAnalogSteering = analogSteering; + _cHandbrake = handBrake; + +} +pVehicle::pVehicle(pVehicleDesc descr) +{ + _digitalSteeringDelta = descr.digitalSteeringDelta; + _steeringSteerPoint = descr.steeringSteerPoint; + _steeringTurnPoint = descr.steeringTurnPoint; + _steeringMaxAngleRad = NxMath::degToRad(descr.steeringMaxAngle); + _transmissionEfficiency = descr.transmissionEfficiency; + _differentialRatio = descr.differentialRatio; + _maxVelocity = descr.maxVelocity; + _motorForce = descr.motorForce; + + _cSteering = 0.0f; + _cAcceleration = 0.0f; + _cAnalogAcceleration = false; + _cAnalogSteering = false; + _cHandbrake = false; + mAutomaticMode = true; + + setBody(descr.body); + + _vehicleMotor = NULL; + _vehicleGears = NULL; + + //---------------------------------------------------------------- + // + // Break settings + // + + mBreakLastFrame = false; + mTimeBreaking = 0.0f; + mBrakeMediumThresold = 1.5f; + mBrakeHighThresold = 3.0f; + + mBreakPressures[BL_Small] = 0.1f; + mBreakPressures[BL_Medium] = 0.3f; + mBreakPressures[BL_High] = 1.0f; + + useBreakTable = false; + + mSmallBrakeTable.brakeEntries[0] = 10.0f; + mSmallBrakeTable.brakeEntries[1] = 20.0f; + mSmallBrakeTable.brakeEntries[2] = 30.0f; + mSmallBrakeTable.brakeEntries[3] = 40.0f; + mSmallBrakeTable.brakeEntries[4] = 50.0f; + mSmallBrakeTable.brakeEntries[5] = 100.0f; + mSmallBrakeTable.brakeEntries[6] = 200.0f; + mSmallBrakeTable.brakeEntries[7] = 400.0f; + mSmallBrakeTable.brakeEntries[8] = 1000.0f; + mSmallBrakeTable.brakeEntries[9] = 1000.0f; + + mMediumBrakeTable.brakeEntries[0] = 400.0f; + mMediumBrakeTable.brakeEntries[1] = 450.0f; + mMediumBrakeTable.brakeEntries[2] = 550.0f; + mMediumBrakeTable.brakeEntries[3] = 650.0f; + mMediumBrakeTable.brakeEntries[4] = 725.0f; + mMediumBrakeTable.brakeEntries[5] = 900.0f; + mMediumBrakeTable.brakeEntries[6] = 1050.0f; + mMediumBrakeTable.brakeEntries[7] = 1000.0f; + mMediumBrakeTable.brakeEntries[8] = 1000.0f; + + mHighBrakeTable.brakeEntries[0] = 700.0f; + mHighBrakeTable.brakeEntries[1] = 775.0f; + mHighBrakeTable.brakeEntries[2] = 950.0f; + mHighBrakeTable.brakeEntries[3] = 1100.0f; + mHighBrakeTable.brakeEntries[4] = 1200.0f; + mHighBrakeTable.brakeEntries[5] = 1250.0f; + mHighBrakeTable.brakeEntries[6] = 1500.0f; + mHighBrakeTable.brakeEntries[7] = 2000.0f; + mHighBrakeTable.brakeEntries[8] = 1000.0f; + mHighBrakeTable.brakeEntries[9] = 1000.0f; + + breakConditionLevels[BC_NoUserInput]=BL_Small; + breakConditionLevels[BC_DirectionChange]=BL_High; + breakConditionLevels[BC_Handbrake]=BL_Medium; + breakConditionLevels[BC_UserBreak]=BL_Medium; + + +} + + +pVehicleDesc::pVehicleDesc() //constructor sets to default +{ + setToDefault(); +} + +void pVehicleDesc::setToDefault() +{ + userData = NULL; + transmissionEfficiency = 1.0f; + differentialRatio = 1.0f; + maxVelocity = 80; + motorForce = 100.0f; + + body = NULL; + gearDescription = NULL;//new pVehicleGearDesc(); + motorDescr = NULL;//new pVehicleMotorDesc(); + steeringMaxAngle = 30; + steeringSteerPoint = VxVector(0,0,0); + steeringTurnPoint = VxVector(0,0,0); + digitalSteeringDelta = 0.04f; + +} + + +bool pVehicleDesc::isValid() const +{ + /*for (NxU32 i = 0; i < carWheels.size(); i++) { + if (!carWheels[i]->isValid()) + return false; + } + */ + if (mass < 0) + return false; + + return true; +} + + +void pVehicle::setControlState(int parameter,float value) +{ + + switch (parameter) + { + + case E_VCS_GUP: + _cShiftStateUp = (int)value; + break; + + case E_VCS_GDOWN: + _cShiftStateDown = (int)value; + break; + case E_VCS_ACCELERATION: + _cAcceleration = value; + break; + + case E_VCS_STEERING: + _cSteering = value; + break; + + case E_VCS_HANDBRAKE: + _cHandbrake= (int)value; + break; + } +} + +void pVehicle::setControlMode(int parameter,int mode) +{ + switch (parameter) + { + case E_VCS_ACCELERATION: + _cAnalogAcceleration = (mode == E_VCSM_ANALOG) ? true : false; + break; + + case E_VCS_STEERING: + _cAnalogSteering = (mode == E_VCSM_ANALOG) ? true : false; + break; + } +} + +float pVehicle::_computeAxisTorque() +{ + if(_vehicleMotor != NULL) + { + NxReal rpm = _computeRpmFromWheels(); + NxReal motorRpm = _computeMotorRpm(rpm); + _vehicleMotor->setRpm(motorRpm); + NxReal torque = _accelerationPedal * _vehicleMotor->getTorque(); + NxReal v = getActor()->getLinearVelocity().magnitude(); + //printf("v: %2.3f m/s (%2.3f km/h)\n", v, v*3.6f); + //printf("rpm %2.3f, motorrpm %2.3f, torque %2.3f, realtorque %2.3f\n", + // rpm, motorRpm, torque, torque*_getGearRatio()*_differentialRatio*_transmissionEfficiency); + return torque * _getGearRatio() * _differentialRatio * _transmissionEfficiency; + } else { + _computeRpmFromWheels(); + return _accelerationPedal * _motorForce; + } +} +void pVehicle::getControlState(int parameter,float &value,int &mode) +{ + switch (parameter) + { + case E_VCS_ACCELERATION: + value = _cAcceleration; + mode = _cAnalogAcceleration; + break; + + case E_VCS_STEERING: + value = _cSteering; + mode = _cAnalogSteering; + break; + + case E_VCS_HANDBRAKE: + value = ((float)_cHandbrake); + mode = _cHandbrake; + break; + + } + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pVehicle/pVehicleEngine.cpp b/usr/Src/old/Core/pVehicle/pVehicleEngine.cpp new file mode 100644 index 0000000..e1840c9 --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pVehicleEngine.cpp @@ -0,0 +1,165 @@ +#include +#include "vtPhysXAll.h" + +#include "pVehicleMotor.h" +#include "pVehicleGears.h" + +#include +#include "NxArray.h" + +#include "pEngine.h" +#include "pGearbox.h" +#include "pDifferential.h" + +void pVehicle::AddDifferential(pDifferential *diff) +{ + if(differentials==MAX_DIFFERENTIAL) + { + xWarning("RCar::AddDifferential(); maximum (%d) exceeded"); + return; + } + differential[differentials]=diff; + differentials++; +} + + +int pVehicle::doEngine(int flags,float dt) +{ + + if (engine && gearbox && driveLine ) + { + engine->SetInput(_cAcceleration); + engine->CalcForces(); + + driveLine->CalcForces(); + driveLine->CalcAccelerations(); + + driveLine->Integrate(); + + for(int i=0;iIntegrate(); + } + + + } + return 0; +} + +int pVehicle::initEngine(int flags) +{ + + driveLine=new pDriveLine(this); + + engine=new pEngine(this); + engine->setToDefault(); + + gearbox=new pGearBox(this); + gearbox->setToDefault(); + + driveLine->SetRoot(engine); + engine->AddChild(gearbox); + + driveLine->SetGearBox(gearbox); + + differentials = 0 ; + + //---------------------------------------------------------------- + // + // setup differential , a single one for the first + // + + pDifferential *d = new pDifferential(this); + d->setToDefault(); + + pWheel *w1 = NULL;int w1Index = -1; + pWheel *w2 = NULL;int w2Index = -1; + + + findDifferentialWheels(w1Index,w2Index); + w1 = (w1Index !=-1) ? _wheels[w1Index] : NULL; + w2 = (w2Index !=-1) ? _wheels[w2Index] : NULL; + + if ( !w1||!w2 || ( !w1&&!w2 ) ) + { + xError("Couldn't find differential wheels"); + return -1; + } + + d->wheel[0]=w1; w1->setDifferential(d,0); + d->wheel[1]=w2; w2->setDifferential(d,1); + + d->engine = engine; + AddDifferential(d); + + // Add differentials and wheels to the driveline + // Note this code does NOT work for 3 diffs, need more work for that. + driveLine->SetDifferentials(differentials); + if(differentials>0) + { + // Hook first diff to the gearbox + gearbox->AddChild(differential[0]); + } + // Make the wheels children of the differentials + // A diff with 2 diffs as children is not yet supported. + for(int i=0;iAddChild(differential[i]->wheel[0]); + differential[i]->AddChild(differential[i]->wheel[1]); + } + + + + driveLine->CalcPreClutchInertia(); + gearbox->SetGear(0); + + return 0; +} + +//---------------------------------------------------------------- +// +// +// + +float pVehicle::getTorque(int component) +{ + if (isValidEngine()) + { + return GetEngine()->GetTorque(); + } + return -1.0f; +} + +bool pVehicle::isStalled() +{ + if (isValidEngine()) + { + return GetEngine()->IsStalled(); + } + return false; +} +float pVehicle::getRPM() +{ + if (isValidEngine()) + { + return GetEngine()->GetRPM(); + } + return -1.0f; +} +int pVehicle::getGear() +{ + if (isValidEngine()) + { + return GetGearBox()->GetGear(); + } +} + +bool pVehicle::hasDifferential() +{ + return differentials; +} + +bool pVehicle::isValidEngine() +{ + return engine && gearbox && driveLine && differentials; +} diff --git a/usr/Src/old/Core/pVehicle/pVehicleGears.cpp b/usr/Src/old/Core/pVehicle/pVehicleGears.cpp new file mode 100644 index 0000000..17aa873 --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pVehicleGears.cpp @@ -0,0 +1,63 @@ +#include +#include "vtPhysXAll.h" + +void pVehicleGearDesc::setToCorvette() { + + forwardGearRatios[0] = 1.66f; + forwardGearRatios[1] = 1.78f; + forwardGearRatios[2] = 1.30f; + forwardGearRatios[3] = 1; + forwardGearRatios[4] = 0.74f; + forwardGearRatios[5] = 0.50f; + nbForwardGears = 6; + + backwardGearRatio = -2.90f; + +} + + +void pVehicleGearDesc::setToDefault() +{ + //forwardGears.clear(); +} + +bool pVehicleGearDesc::isValid() const +{ + if (nbForwardGears > getMaxNumOfGears()) { + fprintf(stderr, "NxVehicleGearDesc::isValid(): nbForwardGears(%d) is bigger than max (%d)\n", + nbForwardGears, getMaxNumOfGears()); + return false; + } + if (nbForwardGears <= 0) { + fprintf(stderr, "NxVehicleGearDesc::isValid(): nbForwardGears(%d) smaller or equal 0\n", nbForwardGears); + return false; + } + if (backwardGearRatio > 0) { + fprintf(stderr, "NxVehilceGearDesc::isValid(): backwardGearRatio(%2.3f) is bigger than 0, make it negative\n", backwardGearRatio); + return false; + } + for (int i = 0; i < nbForwardGears; i++) + { + if (forwardGearRatios[i] < 0) + { + fprintf(stderr, "NxVehilceGearDesc::isValid(): forwardGearRatios[%d] (%2.3f) has value smaller 0\n", i, forwardGearRatios[i]); + return false; + } + } + return true; +} + + +float pVehicleGears::getCurrentRatio() const { + return getRatio(_curGear); +} + +float pVehicleGears::getRatio(NxI32 gear) const { + if (gear > 0) + return _forwardGearRatios[gear-1]; + //return _forwardGears[gear-1]; + if (gear == -1) + return _backwardGearRatio; + return 0; +} + diff --git a/usr/Src/old/Core/pVehicle/pVehicleMotor.cpp b/usr/Src/old/Core/pVehicle/pVehicleMotor.cpp new file mode 100644 index 0000000..a7750b7 --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pVehicleMotor.cpp @@ -0,0 +1,105 @@ +#include +#include "vtPhysXAll.h" + + +int pVehicleMotor::loadNewTorqueCurve(pLinearInterpolation newTCurve) +{ + + _torqueCurve.clear(); + _torqueCurve = newTCurve; + + NxReal maxTorque = 0; + NxI32 maxTorquePos = -1; + for (NxU32 i = 0; i < _torqueCurve.getSize(); i++) + { + NxReal v = _torqueCurve.getValueAtIndex(i); + if (v > maxTorque) { + maxTorque = v; + maxTorquePos = i; + } + } + + _maxTorque = maxTorque; + _maxTorquePos = (float)maxTorquePos; + + + return 1; +} + +void pVehicleMotorDesc::setToDefault() +{ + torqueCurve.clear(); + minRpmToGearDown = 1000.0f; + maxRpmToGearUp = 4000.f; + maxRpm = 5000.f; + minRpm = 1000.f; + + + + setToCorvette(); + +} + +void pVehicleMotorDesc::setToCorvette() { + + // Default should be values for a corvette! + // These are corresponding numbers for rotations and torque (in rpm and Nm) + + /* torqueCurve.insert(1000.f, 193.f); + torqueCurve.insert(2000.f, 234.f); + torqueCurve.insert(4000.f, 275.f); + torqueCurve.insert(5000.f, 275.f); + torqueCurve.insert(6000.f, 166.f);*/ + torqueCurve.insert(1000, 400); + torqueCurve.insert(3000, 500); + torqueCurve.insert(5000, 300); + minRpmToGearDown = 1500.f; + maxRpmToGearUp = 4000.f; + minRpm = 1000.f; + maxRpm = 5000.f; +} + +bool pVehicleMotorDesc::isValid() const +{ + + if (torqueCurve.getSize() == 0) { + fprintf(stderr, "pVehicleMotorDesc::isValid(): Empty TorqueCurve\n"); + return false; + } + if (maxRpmToGearUp < minRpmToGearDown) { + fprintf(stderr, "pVehicleMotorDesc::isValid(): maxRpmToGearUp (%2.3f) is smaller than minRpmToGearDown (%2.3f)\n", + maxRpmToGearUp, minRpmToGearDown); + return false; + } + return true; + +} + + +int pVehicleMotor::changeGears(const pVehicleGears* gears, float threshold) const +{ + NxI32 gear = gears->getGear(); + if (_rpm > _maxRpmToGearUp && gear < gears->getMaxGear()) + return 1; + else if (_rpm < _minRpmToGearDown && gear > 1) + return -1; + /* + NxReal normalTorque = _torqueCurve.getValue(_rpm); + + NxReal lowerGearRatio = gears->getRatio(gear-1); + NxReal normalGearRatio = gears->getCurrentRatio(); + NxReal upperGearRatio = gears->getRatio(gear+1); + NxReal lowerGearRpm = _rpm / normalGearRatio * lowerGearRatio; + NxReal upperGearRpm = _rpm / normalGearRatio * upperGearRatio; + NxReal lowerTorque = _torqueCurve.getValue(lowerGearRpm); + NxReal upperTorque = _torqueCurve.getValue(upperGearRpm); + NxReal lowerWheelTorque = lowerTorque * lowerGearRatio; + NxReal normalWheelTorque = normalTorque * normalGearRatio; + NxReal upperWheelTorque = upperTorque * upperGearRatio; + //printf("%2.3f %2.3f %2.3f\n", lowerWheelTorque, normalWheelTorque, upperWheelTorque); + */ + + return 0; +} + + diff --git a/usr/Src/old/Core/pVehicle/pVehicleMovement.cpp b/usr/Src/old/Core/pVehicle/pVehicleMovement.cpp new file mode 100644 index 0000000..a0483c0 --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pVehicleMovement.cpp @@ -0,0 +1,399 @@ +#include +#include "vtPhysXAll.h" + +#include "pVehicleMotor.h" +#include "pVehicleGears.h" + +#include +#include "NxArray.h" + + +float pVehicle::getBrakeAmountFromTable(pVehicleBreakLevel brakeLevel) +{ + + int value = abs((int(getMPH()) / 10)); + if(value > BREAK_TABLE_ENTRIES - 1) + value = BREAK_TABLE_ENTRIES - 1; + if(value < 0 || value == BREAK_TABLE_ENTRIES) + { + return 1.0f; + } + + switch(brakeLevel) + { + case BL_Small: + return mSmallBrakeTable.brakeEntries[brakeLevel]; + case BL_Medium: + return mMediumBrakeTable.brakeEntries[brakeLevel]; + case BL_High: + return mHighBrakeTable.brakeEntries[brakeLevel]; + } + + return 1.0f; + +} + +pVehicleBreakCase pVehicle::calculateBreakCase(int currentAccelerationStatus) +{ + + //---------------------------------------------------------------- + // + // is rolling or no user input ? + // + if( !(currentAccelerationStatus & VS_Handbrake ) && + (currentAccelerationStatus & VS_IsMoving ) && + !(currentAccelerationStatus & VS_IsAccelerated) + ) + return BC_NoUserInput; + + //---------------------------------------------------------------- + // + // direction change ? + // + if( !(currentAccelerationStatus & VS_Handbrake ) && + (currentAccelerationStatus & VS_IsBraking ) && + (currentAccelerationStatus & VS_IsMoving ) && + (currentAccelerationStatus & VS_IsAccelerated) + ) + return BC_DirectionChange; + + //---------------------------------------------------------------- + // + // handbrake + // + if( (currentAccelerationStatus & VS_Handbrake ) ) + return BC_Handbrake; + + return BC_NoUserInput; + +} +int pVehicle::_performSteering(float dt) +{ + _controlSteering(_cSteering, _cAnalogSteering); + + NxReal distanceSteeringAxisCarTurnAxis = _steeringSteerPoint.x - _steeringTurnPoint.x; + //NX_ASSERT(_steeringSteerPoint.z == _steeringTurnPoint.z); + NxReal distance2 = 0; + if (NxMath::abs(_steeringWheelState) > 0.01f) + distance2 = distanceSteeringAxisCarTurnAxis / NxMath::tan(_steeringWheelState * getMaxSteering()); + + float tanS = NxMath::tan(_steeringWheelState * getMaxSteering()); + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_SteerableInput)) + { + if(distance2 != 0) + { + //NxReal xPos = wheel->getWheelPos().x; + NxReal xPos = ((pWheel2*)wheel)->getWheelShape()->getLocalPosition().x; + //NxReal xPos2 = _steeringSteerPoint.x- wheel->getWheelPos().x; + //NxReal xPos2 = _steeringSteerPoint.x- ((pWheel2*)wheel)->getWheelShape()->getLocalPosition().z; + NxReal zPos = ((pWheel2*)wheel)->getWheelShape()->getLocalPosition().z; + //NxReal zPos = wheel->getWheelPos().z; + + NxReal dz = -zPos + distance2; + NxReal dx = xPos - _steeringTurnPoint.x; + float angle =(NxMath::atan(dx/dz)); + if (dx < 0.0f) + { + angle*=-1.0f; + } + wheel->setAngle(angle); + } else { + wheel->setAngle(0.0f); + } + + } else if(wheel->getWheelFlag(WF_SteerableAuto)) + { + NxVec3 localVelocity = getActor()->getLocalPointVelocity(getFrom(wheel->getWheelPos())); + NxQuat local2Global = getActor()->getGlobalOrientationQuat(); + local2Global.inverseRotate(localVelocity); + // printf("%2.3f %2.3f %2.3f\n", wheel->getWheelPos().x,wheel->getWheelPos().y,wheel->getWheelPos().z); + localVelocity.y = 0; + if(localVelocity.magnitudeSquared() < 0.1f) + { + wheel->setAngle(0.0f); + } else { + localVelocity.normalize(); + // printf("localVelocity: %2.3f %2.3f\n", localVelocity.x, localVelocity.z); + if(localVelocity.x < 0) + localVelocity = -localVelocity; + NxReal angle = NxMath::clamp((NxReal)atan(localVelocity.z / localVelocity.x), 0.3f, -0.3f); + wheel->setAngle(angle); + } + } + } + + + + return 0; +} +int pVehicle::_performAcceleration(float dt) +{ + + + + pVehicleBreakCase currentBreakCase = calculateBreakCase(_currentStatus); + + /* + int currentBreakLevel = getBreaklevelForCase(currentBreakCase); + */ + float bTorque = 0.0f; + float motorTorque = 0.0f; + bool calculateBreaking = false; + + + XString errMessage; + + + if( + ((_currentStatus & VS_IsBraking ) && (_currentStatus & VS_IsMoving)) + ) calculateBreaking = true; + + + if ( (_currentStatus & VS_IsMoving ) && + (getBreakFlags() & VBF_Autobreak) && + (currentBreakCase == BC_NoUserInput)&& + (_currentStatus & VS_IsMoving ) && + !(_currentStatus & VS_IsAccelerated ) + ) + { + calculateBreaking = true; +/* errMessage.Format("autobreak");*/ + //xInfo(errMessage.Str()); + } + + + if (_currentStatus & VS_Handbrake) + { + /*errMessage.Format("handbrake"); + xInfo(errMessage.Str());*/ + goto performAcceleration; + } + + //---------------------------------------------------------------- + // + // calculate break torque + // + if ( calculateBreaking ) + { + + + //---------------------------------------------------------------- + // + // increase break time counter + // + if(mBreakLastFrame) + mTimeBreaking+=dt; + + //---------------------------------------------------------------- + // + // determine break amount by table + // + if ( (getBreakFlags() & VBF_UseTable) ) + { + + if(mTimeBreaking < mBrakeMediumThresold) + { + bTorque = getBrakeAmountFromTable(BL_Small); + errMessage.Format("breaking at small : bt : %f at %f",bTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + + }else if(mTimeBreaking >= mBrakeMediumThresold && mTimeBreaking < mBrakeHighThresold ) + { + bTorque = getBrakeAmountFromTable(BL_Medium); + errMessage.Format("breaking at medium : bt : %f at %f",bTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + }else + { + bTorque = getBrakeAmountFromTable(BL_High); + errMessage.Format("breaking at high : bt : %f at %f",bTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + } + }else + { + + //---------------------------------------------------------------- + // + // use break pressures + // + float mCurrentBrakeTorque = getBrakeTorque()*0.01f; + float AmountToBrakeFinal = 0.0f; + if(mTimeBreaking < mBrakeMediumThresold) + { + bTorque = mCurrentBrakeTorque * mBreakPressures[BL_Small]; + errMessage.Format("breaking at small : bt : %f at %f",bTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + + } + else if(mTimeBreaking >= mBrakeMediumThresold && mTimeBreaking < mBrakeHighThresold ) + { + bTorque = mCurrentBrakeTorque * mBreakPressures[BL_Medium]; + errMessage.Format("breaking at medium : bt : %f at %f",bTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + } + else + { + bTorque = mCurrentBrakeTorque * mBreakPressures[BL_High]; + errMessage.Format("breaking at high : bt : %f at %f",bTorque,mTimeBreaking); + //xInfo(errMessage.Str()); + } + + + if (bTorque > 1000.f) + { + bTorque= 1000.0f; + } + + } + + }else + { + mBreakLastFrame = false; + mTimeBreaking = 0.0f; + } + + performAcceleration: + + if (bTorque > 0.0f) + { + mBreakLastFrame = true; + } + + + if ( _nbTouching && _currentStatus & VS_IsAccelerated ) + { + NxReal axisTorque = _computeAxisTorqueV2(); + NxReal wheelTorque = axisTorque / (NxReal)(_wheels.size() - _nbHandbrakeOn ); + NxReal wheelTorqueNotTouching = _nbNotTouching > 0 ? wheelTorque * ( NxMath::pow(0.5f, (NxReal) _nbNotTouching )):0; + NxReal wheelTorqueTouching = wheelTorque - wheelTorqueNotTouching; + motorTorque = wheelTorqueTouching / (NxReal)_nbTouching; + float a = motorTorque; + + }else + { + _updateRpms(); + } + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + + //---------------------------------------------------------------- + // + // determine break torque : + // + + // is moving in the opposite direction than its accelerated + pWheel* wheel = _wheels[i]; + wheel->tick( ( _currentStatus & VS_Handbrake) , motorTorque, bTorque , dt ); + + } + return 1; +} + +void pVehicle::setBreakPressure(int breakLevel,float pressure) +{ + mBreakPressures[breakLevel]=pressure; +} +void pVehicle::setBreakCaseLevel(pVehicleBreakCase breakCase,pVehicleBreakLevel level) +{ + breakConditionLevels[breakCase]=level; +} + +// ( X * 10 * 60) / (5280* 12) * 100 = X * 0.9469696 +//return (-((10 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed() * 60) / (5280 * 12)) * 100); +//return -0.9469696 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed(); + +float pVehicle::getBrakeTorque() +{ + int nbAWheels =0; + float radius = 0.0; + float axleSpeed = 0.0; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_Accelerated)) + { + nbAWheels++; + if (wheel->getRadius() > radius) + radius = wheel->getRadius(); + + pWheel2* w2 = (pWheel2*)wheel; + if (w2->getWheelShape()->getAxleSpeed() > axleSpeed) + { + axleSpeed = w2->getWheelShape()->getAxleSpeed(); + } + } + } + + if(fabs(axleSpeed) != 0) + { + return ((5252 * getMotorForce()) / (fabs(axleSpeed) * 10)); + } + + return 0.0f; +} + +float pVehicle::getMPH(int type) +{ + + int nbAWheels =0; + float radius = 0.0; + float axleSpeed = 0.0; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_Accelerated)) + { + nbAWheels++; + if (wheel->getRadius() > radius) + radius = wheel->getRadius(); + + pWheel2* w2 = (pWheel2*)wheel; + if (w2->getWheelShape()->getAxleSpeed() > axleSpeed) + { + axleSpeed = w2->getWheelShape()->getAxleSpeed(); + } + } + } + + + // ( X * 10 * 60) / (5280* 12) * 100 = X * 0.9469696 + //return (-((10 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed() * 60) / (5280 * 12)) * 100); + return 0.9469696 * radius * NxPi * axleSpeed; + +} +void pVehicle::_controlAcceleration(float acceleration, bool analogAcceleration) +{ + if(NxMath::abs(acceleration) < 0.001f) + { + _releaseBraking = true; + //xInfo("set release breaking = true"); + } + + if(!_braking) + { + _accelerationPedal = NxMath::clamp(acceleration, 1.f, -1.f); + _brakePedalChanged = _brakePedal == 0; + _brakePedal = 0; + //xInfo("breaking = false : clamp accPedal 1|-1"); + } else { + //xInfo("breaking = true : accPeal = 0"); + _accelerationPedal = 0; + NxReal newv = NxMath::clamp(NxMath::abs(acceleration), 1.f, 0.f); + _brakePedalChanged = _brakePedal == newv; + _brakePedal = newv; + } + char master[512]; + sprintf(master,"Acceleration: %2.3f, Braking %2.3f\n", _accelerationPedal, _brakePedal); + xInfo(master); + //OutputDebugString(master); + + +} + + + + diff --git a/usr/Src/old/Core/pVehicle/pVehicleXML.cpp b/usr/Src/old/Core/pVehicle/pVehicleXML.cpp new file mode 100644 index 0000000..15da38e --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pVehicleXML.cpp @@ -0,0 +1,494 @@ +#include +#include "vtPhysXAll.h" + +#include "tinyxml.h" + +int pFactory::loadFrom(pTireFunction& dst,const char* nodeName,const TiXmlDocument * doc ) +{ + int result = 0 ; + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "tireFunction" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + + int res = sube->QueryDoubleAttribute("ExtremumSlip",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.extremumSlip = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("ExtremumValue",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.extremumValue = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("AsymptoteSlip",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.asymptoteSlip = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("AsymptoteValue",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.asymptoteValue = static_cast(v); + } + } + res = sube->QueryDoubleAttribute("StiffnessFactor",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.stiffnessFactor = static_cast(v); + } + } + } + } + } + } + } + } + } + return result; +} + +int pFactory::loadWheelDescrFromXML(pWheelDescr& dst,const char* nodeName,const TiXmlDocument * doc ) +{ + int result = 0 ; + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "wheel" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + + int res = sube->QueryDoubleAttribute("Suspension",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.wheelSuspension = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.springRestitution = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("Damping",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.springDamping = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("Bias",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.springBias= static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("MaxBreakForce",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.maxBrakeForce = static_cast(v); + continue; + } + } + + + res = sube->QueryDoubleAttribute("FrictionToSide",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.frictionToSide = static_cast(v); + continue; + } + } + + res = sube->QueryDoubleAttribute("FrictionToFront",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.frictionToFront = static_cast(v); + continue; + } + } + + res = sube->QueryDoubleAttribute("InverseWheelMass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.inverseWheelMass = static_cast(v); + continue; + } + } + + const char* flags = NULL; + flags = sube->Attribute("Flags"); + if (flags && strlen(flags)) + { + dst.wheelFlags = (WheelFlags)_str2WheelFlag(flags); + } + + + const char* latFunc = NULL; + latFunc = sube->Attribute("LateralFunction"); + if (latFunc && strlen(latFunc)) + { + int index = getEnumIndex(getManager()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,latFunc); + if (index!=0) + { + loadFrom(dst.latFunc,latFunc,doc); + dst.latFunc.xmlLink = index; + if (!dst.latFunc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Lateral Tire Function from XML was incorrect, setting to default"); + dst.latFunc.setToDefault(); + } + } + } + + const char* longFunc = NULL; + longFunc = sube->Attribute("LongitudeFunction"); + if (longFunc && strlen(longFunc)) + { + int index = getEnumIndex(getManager()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,longFunc); + if (index!=0) + { + loadFrom(dst.longFunc,longFunc,doc); + dst.longFunc.xmlLink = index; + if (!dst.longFunc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Longitude Tire Function from XML was incorrect, setting to default"); + dst.longFunc.setToDefault(); + } + } + } + } + } + } + } + } + } + } + return result; +} +int pFactory::loadVehicleDescrFromXML(pVehicleDesc& dst,const char* nodeName,const TiXmlDocument * doc ) +{ + + + int result = 0 ; + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "vehicle" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + + int res = sube->QueryDoubleAttribute("Mass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.mass = static_cast(v); + continue; + } + } + + ////////////////////////////////////////////////////////////////////////// + + /* + int res = sube->QueryDoubleAttribute("Mass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.mass = static_cast(v); + continue; + } + } + + */ + } + } + } + } + } + } + } + return result; +} + +int pFactory::_str2WheelFlag(XString _in) +{ + + + short nb = 0 ; + int result = 0; + XStringTokenizer tokizer(_in.CStr(), "|"); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) ) + { + XString tokx(tok); + + if ( _stricmp(tokx.CStr(),"Steerable") == 0 ) + { + result |= WF_SteerableInput; + } + + if ( _stricmp(tokx.CStr(),"VehicleControlled") == 0 ) + { + result |= WF_VehicleControlled; + } + if ( _stricmp(tokx.CStr(),"SteerableAuto") == 0 ) + { + result |= WF_SteerableAuto; + } + if ( _stricmp(tokx.CStr(),"Handbrake") == 0 ) + { + result |= WF_AffectedByHandbrake; + } + + if ( _stricmp(tokx.CStr(),"Accelerated") == 0 ) + { + result |= WF_Accelerated; + } + + if ( _stricmp(tokx.CStr(),"Differential") == 0 ) + { + result |= WF_AffectedByDifferential; + } + if ( _stricmp(tokx.CStr(),"IgnoreTireFunction") == 0 ) + { + result |= WF_IgnoreTireFunction; + } + + /*if ( _stricmp(tokx.CStr(),"Wheelshape") == 0 ) + { + result |= WF_UseWheelShape; + }*/ + + nb++; + } + return result; +} + +/* + +int pVehicle::loadFromXML(const char* nodeName,const TiXmlDocument * doc ) +{ + NxMaterialDesc *result = new NxMaterialDesc(); + result->setToDefault(); + + int res = 0; + + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + + + if ( strlen(nodeName) && doc) + { + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "vehicle" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryDoubleAttribute("Mass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + //setMass() = + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFriction= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->restitution= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->dynamicFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + const char* dirOfAnisotropy = NULL; + dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); + if (dirOfAnisotropy && strlen(dirOfAnisotropy)) + { + VxVector vec = pFactory::Instance()->_str2Vec(dirOfAnisotropy); + if (vec.Magnitude() >0.1f) + { + result->flags = NX_MF_ANISOTROPIC; + result->dirOfAnisotropy = pMath::getFrom(vec); + continue; + }else + { + result->dirOfAnisotropy = pMath::getFrom(VxVector(0,0,0)); + } + + //result->setGravity(vec); + + } + + ////////////////////////////////////////////////////////////////////////// + const char* FrictionCombineMode = NULL; + FrictionCombineMode = sube->Attribute("FrictionCombineMode"); + if (FrictionCombineMode && strlen(FrictionCombineMode)) + { +// int fMode = _str2CombineMode(FrictionCombineMode); +// result->frictionCombineMode = (NxCombineMode)fMode; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + const char* RestitutionCombineMode = NULL; + RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); + if (RestitutionCombineMode && strlen(RestitutionCombineMode)) + { +// int fMode = _str2CombineMode(RestitutionCombineMode); +// result->restitutionCombineMode= (NxCombineMode)fMode; + continue; + } + } + } +// return result; + } + } + } + } + } + } + + + + return 0; +} +*/ + + + diff --git a/usr/Src/old/Core/pVehicle/pWheel.cpp b/usr/Src/old/Core/pVehicle/pWheel.cpp new file mode 100644 index 0000000..d18c157 --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pWheel.cpp @@ -0,0 +1,98 @@ +#include +#include "vtPhysXAll.h" +#include + +NxActor*pWheel::getTouchedActor()const{ return NULL;} + +void pWheelDescr::setToDefault() +{ + + userData = NULL; + wheelFlags =(WheelFlags)0; + + //radius.setToDefault(); + springBias = 0; + springRestitution = 1.f; + springDamping = 0.f; + + wheelSuspension = 1.f; + maxBrakeForce = 0.0f; + frictionToSide = 1.0f; + frictionToFront = 1.0f; + latFuncXML_Id=0; + longFuncXML_Id=0; + inverseWheelMass = 0.1f; + wheelShapeFlags =(WheelShapeFlags)0; + + latFunc.setToDefault(); + longFunc.setToDefault(); + + +} +bool pWheelDescr::isValid() const +{ + + /*if(!NxMath::isFinite(radius)) return false; + if(radius<=0.0f) return false;*/ + + bool result = true; + int a=X_NEGATE(NxMath::isFinite(wheelSuspension)); + //iAssertWR(X_NEGATE(NxMath::isFinite(wheelSuspension)),"",result ); + iAssertWR(inverseWheelMass > 0.0f,"",result ); + iAssertWR(X_NEGATE(inverseWheelMass<0.0f),"",result ); + //iAssertWR(X_NEGATE(brakeTorque<0.0f),"",result ); + //iAssertWR(X_NEGATE(NxMath::isFinite(steerAngle)),"",result ); + //iAssertWR(X_NEGATE(brakeTorque<0.0f),"",result ); + iAssertWR(longFunc.isValid(),"",result ); + iAssertWR(latFunc.isValid(),"",result ); + +/* if (!suspension.isValid()) return false; + if (!longitudalTireForceFunction.isValid()) return false; + if (!lateralTireForceFunction.isValid()) return false; +*/ + //if (NxMath::abs(1-wheelAxis.magnitudeSquared()) > 0.001f) + // return false; + if (wheelApproximation > 0 && wheelApproximation < 4) { + + return false; + } + if ((wheelFlags & WF_SteerableAuto) && (wheelFlags & WF_SteerableInput)) + { + return false; + } + return result; +} + +int pWheel::_constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + return 1; +} + +void pWheel::setFlags(int flags) +{ + mWheelFlags = flags; +} + +pWheel::pWheel(pRigidBody *body,pWheelDescr *descr) +{ + + mBody = body; + mWheelFlags = descr->wheelFlags; + _wheelRollAngle = 0.0f; + mActor= body->getActor(); + +} + +pWheel1*pWheel::castWheel1() +{ + return dynamic_cast(this); +} +pWheel2*pWheel::castWheel2() +{ + + return dynamic_cast(this); +} + + + + diff --git a/usr/Src/old/Core/pVehicle/pWheel1.cpp b/usr/Src/old/Core/pVehicle/pWheel1.cpp new file mode 100644 index 0000000..356f5f5 --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pWheel1.cpp @@ -0,0 +1,262 @@ +#include +#include "vtPhysXAll.h" + +pWheelContactData* +pWheel1::getContact(){ + + return new pWheelContactData(); +} + +float pWheel1::getRpm()const{ return NxMath::abs(_turnVelocity * 60.f);} + +NxActor *pWheel1::getTouchedActor(){ return contactInfo->otherActor; } + +void pWheel1::_tick(float dt) +{ + + if(!hasGroundContact()) + updateContactPosition(); + + //################################################################ + // + // Calculate the wheel rotation around the roll axis + // + updateAngularVelocity(dt*0.001f, false); + + float motorTorque=0.0; + + if(getWheelFlag(WF_Accelerated)) + { + /*if (handBrake && getWheelFlag(NX_WF_AFFECTED_BY_HANDBRAKE)) + { + // Handbrake, blocking! + }*/ + + if (hasGroundContact()) + { + // Touching, force applies + NxVec3 steeringDirection; + getSteeringDirection(steeringDirection); + steeringDirection.normalize(); + NxReal localTorque = motorTorque; + NxReal wheelForce = localTorque / _radius; + steeringDirection *= wheelForce; + wheelCapsule->getActor().addForceAtPos(steeringDirection, contactInfo->contactPosition); + if(contactInfo->otherActor->isDynamic()) + contactInfo->otherActor->addForceAtPos(-steeringDirection, contactInfo->contactPosition); + } + } + + NxMat34& wheelPose = getWheelCapsule()->getGlobalPose(); + NxMat33 rot, axisRot, rollRot; + rot.rotY( _angle ); + axisRot.rotY(0); + rollRot.rotX(_turnAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + + float a = _angle; + float b = getWheelRollAngle(); + + + setWheelPose(wheelPose); + //setWheelOrientation(wheelPose.M); + + + contactInfo->reset(); +} + + +void pWheel1::_updateVirtoolsEntity(bool position,bool rotation) +{ + + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(getEntID())); + if (ent && position) + { + + /* + NxWheelShape *wShape = getWheelShape(); + NxMat34 pose = wShape->getGlobalPose(); + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + NxVec3 suspensionOffsetDirection; + pose.M.getColumn(1, suspensionOffsetDirection); + suspensionOffsetDirection =-suspensionOffsetDirection; + + if (contactShape && wcd.contactForce > -1000) + { + NxVec3 toContact = wcd.contactPoint - pose.t; + double alongLength = suspensionOffsetDirection.dot(toContact); + NxVec3 across = toContact - alongLength * suspensionOffsetDirection; + double r = wShape->getRadius(); + double pullBack = sqrt(r*r - across.dot(across)); + pose.t += (alongLength - pullBack) * suspensionOffsetDirection; + } else { + pose.t += wShape->getSuspensionTravel() * suspensionOffsetDirection; + } + + VxVector oPos = getFrom(pose.t); + ent->SetPosition(&oPos); + + if (hasGroundContact()) + { + + + }else + { + // VxVector gPos = getWheelPos(); + // ent->SetPosition(&gPos,getBody()->GetVT3DObject()); + } + + */ + } + if (ent && rotation) + { + //float rollAngle = getWheelRollAngle(); + //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + + VxQuaternion rot = pMath::getFrom( getWheelPose().M ); + ent->SetQuaternion(&rot,NULL); + } + +} + + + + +void pWheel1::updateContactPosition() +{ + contactInfo->contactPositionLocal = getFrom(_maxPosition) - NxVec3(0, _maxSuspension+_radius, 0); +} +void pWheel1::setAngle(float angle) +{ + _angle = angle; + + NxReal Cos, Sin; + NxMath::sinCos(_angle, Sin, Cos); + NxMat33 wheelOrientation = wheelCapsule->getLocalOrientation(); + wheelOrientation.setColumn(0, NxVec3( Cos, 0, Sin )); + wheelOrientation.setColumn(2, NxVec3( Sin, 0,-Cos )); + setWheelOrientation(wheelOrientation); + +} + +void pWheel1::updateAngularVelocity(float lastTimeStepSize, bool handbrake) +{ + if((mWheelFlags & WF_AffectedByHandbrake) && handbrake) + { + _turnVelocity = 0; + } + else if (contactInfo->isTouching()) + { + NxReal wheelPerimeter = NxTwoPi * _radius; + NxReal newTurnVelocity = contactInfo->relativeVelocity / wheelPerimeter; + _turnVelocity = newTurnVelocity; + _turnAngle += _turnVelocity * lastTimeStepSize * NxTwoPi; + } + else + { + _turnVelocity *= 0.99f; + _turnAngle += _turnVelocity; + } + + while(_turnAngle >= NxTwoPi) + _turnAngle -= NxTwoPi; + while (_turnAngle < 0) + _turnAngle += NxTwoPi; + + setWheelRollAngle(_turnAngle); + +} + +void pWheel1::getSteeringDirection(NxVec3& dir) +{ + if(mWheelFlags & (WF_SteerableInput | WF_SteerableAuto)) + { + wheelCapsule->getGlobalOrientation().getColumn(0, dir); + } + else + { + wheelCapsule->getActor().getGlobalOrientation().getColumn(0, dir); + } +} + +void pWheel1::tick(bool handbrake, float motorTorque, float brakeTorque, float dt) +{ + + if(getWheelFlag(WF_Accelerated)) + { + if (handbrake && getWheelFlag(WF_AffectedByHandbrake)) + { + // Handbrake, blocking! + } + else if (hasGroundContact()) + { + // Touching, force applies + NxVec3 steeringDirection; + getSteeringDirection(steeringDirection); + steeringDirection.normalize(); + NxReal localTorque = motorTorque; + NxReal wheelForce = localTorque / _radius; + steeringDirection *= wheelForce; + wheelCapsule->getActor().addForceAtPos(steeringDirection, contactInfo->contactPosition); + if(contactInfo->otherActor->isDynamic()) + contactInfo->otherActor->addForceAtPos(-steeringDirection, contactInfo->contactPosition); + } + } + + NxReal OneMinusBreakPedal = 1-brakeTorque; + + /* + if(handBrake && getWheelFlag(WF_AffectedByHandbrake)) + { + material->setDynamicFrictionV(1); + material->setStaticFrictionV(4); + material->setDynamicFriction(0.4f); + material->setStaticFriction(1.0f); + } + else + { + NxReal newv = OneMinusBreakPedal * _frictionToFront + brakeTorque; + NxReal newv4= OneMinusBreakPedal * _frictionToFront + brakeTorque*4; + material->setDynamicFrictionV(newv); + material->setDynamicFriction(_frictionToSide); + + material->setStaticFrictionV(newv*4); + material->setStaticFriction(2); + }*/ + + if(!hasGroundContact()) + updateContactPosition(); + updateAngularVelocity(dt, handbrake); + + contactInfo->reset(); +} +VxVector pWheel1::getWheelPos()const{ return getFrom(wheelCapsule->getLocalPosition()); } +void pWheel1::setWheelOrientation(const NxMat33& m) +{ + wheelCapsule->setLocalOrientation(m); + if (wheelConvex != NULL) + wheelConvex->setLocalOrientation(m); +} + +void pWheel1::_updateAgeiaShape(bool position,bool rotation) +{ + +} + +int pWheel1::_constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + return 1; +} +pWheel1::pWheel1(pRigidBody *body, pWheelDescr *descr) : pWheel(body,descr) +{ + wheelCapsule = NULL; + wheelConvex = NULL; + + contactInfo = new ContactInfo(); + + +} + + + diff --git a/usr/Src/old/Core/pVehicle/pWheel2.cpp b/usr/Src/old/Core/pVehicle/pWheel2.cpp new file mode 100644 index 0000000..f6e1931 --- /dev/null +++ b/usr/Src/old/Core/pVehicle/pWheel2.cpp @@ -0,0 +1,452 @@ +#include +#include "vtPhysXAll.h" + +#include + +void pWheel2::_tick(float dt) +{ + NxWheelShape *wShape = getWheelShape(); + if (!wShape) return; + + + NxVec3 _localVelocity; + bool _breaking=false; + ////////////////////////////////////////////////////////////////////////// + // + // + // + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + + if (contactShape) + { + + NxVec3 relativeVelocity; + if ( !contactShape->getActor().isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - contactShape->getActor().getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + _breaking = false; //NxMath::abs(_localVelocity.z) < ( 0.1 ); + // wShape->setAxleSpeed() + } + + + float rollAngle = getWheelRollAngle(); + + rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + //rollAngle+=wShape->getAxleSpeed() * (1.0f/60.0f /*dt* 0.01f*/); + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + + NxMat34& wheelPose = wShape->getGlobalPose(); + + + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( contactShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } + + + float rAngle = getWheelRollAngle(); + float steer = wShape->getSteerAngle(); + + NxVec3 p0; + NxVec3 dir; + /* + getWorldSegmentFast(seg); + seg.computeDirection(dir); + dir.normalize(); + */ + NxReal r = wShape->getRadius(); + NxReal st = wShape->getSuspensionTravel(); + NxReal steerAngle = wShape->getSteerAngle(); + p0 = wheelPose.t; //cast from shape origin + wheelPose.M.getColumn(1, dir); + dir = -dir; //cast along -Y. + NxReal castLength = r + st; //cast ray this long + + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + setWheelPose(wheelPose); +} + +pWheelContactData* pWheel2::getContact() +{ + NxWheelShape *wShape = getWheelShape(); + if (!wShape) + { + return new pWheelContactData(); + } + + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + + pWheelContactData result; + result.contactEntity = NULL; + + + if (contactShape) + { + + result.contactForce = wcd.contactForce; + result.contactNormal = getFrom(wcd.contactNormal); + result.contactPoint= getFrom(wcd.contactPoint); + result.contactPosition= wcd.contactPosition; + + + result.lateralDirection= getFrom(wcd.lateralDirection); + result.lateralImpulse= wcd.lateralImpulse; + result.lateralSlip = wcd.lateralSlip; + + result.longitudalDirection = getFrom(wcd.longitudalDirection); + result.longitudalImpulse = wcd.longitudalImpulse; + result.longitudalSlip= wcd.longitudalSlip; + + pSubMeshInfo *sInfo = static_cast(contactShape->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + result.contactEntity = (CK3dEntity*)obj; + }else + { + result.contactEntity = NULL; + } + } + + result.otherShapeMaterialIndex = contactShape->getMaterial(); + + NxMaterial* otherMaterial = contactShape->getActor().getScene().getMaterialFromIndex(contactShape->getMaterial()); + if (otherMaterial) + { + pFactory::Instance()->copyTo(result.otherMaterial,otherMaterial); + } + } + return &result; +} + +void pWheel2::_updateVirtoolsEntity(bool position,bool rotation) +{ + + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(getEntID())); + if (ent && position) + { + + NxWheelShape *wShape = getWheelShape(); + NxMat34 pose = wShape->getGlobalPose(); + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + NxVec3 suspensionOffsetDirection; + pose.M.getColumn(1, suspensionOffsetDirection); + suspensionOffsetDirection =-suspensionOffsetDirection; + + if (contactShape && wcd.contactForce > -1000) + { + NxVec3 toContact = wcd.contactPoint - pose.t; + double alongLength = suspensionOffsetDirection.dot(toContact); + NxVec3 across = toContact - alongLength * suspensionOffsetDirection; + double r = wShape->getRadius(); + double pullBack = sqrt(r*r - across.dot(across)); + pose.t += (alongLength - pullBack) * suspensionOffsetDirection; + } else { + pose.t += wShape->getSuspensionTravel() * suspensionOffsetDirection; + } + + VxVector oPos = getFrom(pose.t); + ent->SetPosition(&oPos); + + if (hasGroundContact()) + { + + NxWheelShape *wShape = getWheelShape(); + NxMat34& wheelPose = wShape->getGlobalPose(); + +/* NxWheelContactData wcd; + NxShape* cShape = wShape->getContact(wcd); + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + VxVector gPos = getFrom(getWheelPose().t); + + /* + if( cShape && wcd.contactPosition <= (stravel + radius) ) + { + }*/ + + ////////////////////////////////////////////////////////////////////////// + + /*VxVector gPos = getFrom(getWheelPose().t); + //gPos*=-1.0f; + gPos -=getWheelPos(); + V 3. + xVector gPos2 = getFrom(getWheelShape()->getLocalPose().t); + ent->SetPosition(&gPos2,getBody()->GetVT3DObject()); + */ + }else + { +// VxVector gPos = getWheelPos(); +// ent->SetPosition(&gPos,getBody()->GetVT3DObject()); + } + } + if (ent && rotation) + { + + + //float rollAngle = getWheelRollAngle(); + //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + + VxQuaternion rot = pMath::getFrom( getWheelPose().M ); + ent->SetQuaternion(&rot,NULL); + } + + + /* + + + + NxWheelShape *wShape = getWheelShape(); + + + + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + + + NxMat34& wheelPose = wShape->getGlobalPose(); + + NxWheelContactData wcd; + NxShape* cShape = wShape->getContact(wcd); + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( cShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } + + float rAngle = rollAngle; + float steer = wShape->getSteerAngle(); + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rollAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + setWheelPose(wheelPose); + + */ +} + +void pWheel2::_updateAgeiaShape(bool position,bool rotation) +{ + +} + +float pWheel2::getRadius()const +{ + return mWheelShape->getRadius(); +} + +float pWheel2::getRpm() const +{ + + float a = NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; + if (getVehicle()) + { + + float b = NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * getVehicle()->_lastDT; + return b; + } + + return NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; +} +VxVector pWheel2::getWheelPos() const +{ + return getFrom(mWheelShape->getLocalPosition()); +} + +void pWheel2::setAngle(float angle) +{ + mWheelShape->setSteerAngle(-angle); +} + +NxActor*pWheel2::getTouchedActor()const +{ + NxWheelContactData wcd; + NxShape * s = mWheelShape->getContact(wcd); + if (s) + { + if (&s->getActor()) + { + return &s->getActor(); + }else + { + return NULL; + } + + }else + { + return NULL; + } + + return NULL; + //return s ? &s->getActor() : NULL; +} +float pWheel2::getAxleSpeed()const +{ + if (mWheelShape) + { + return mWheelShape->getAxleSpeed(); + } + return -1.f; + +} +bool pWheel2::hasGroundContact() const +{ + return getTouchedActor() != NULL; +} +void pWheel2::tick(bool handBrake, float motorTorque, float brakeTorque, float dt) +{ + if(handBrake && getWheelFlag(WF_AffectedByHandbrake)) + brakeTorque = 1000.0f; + + if(getWheelFlag(WF_Accelerated)) + mWheelShape->setMotorTorque(motorTorque); + + mWheelShape->setBrakeTorque(brakeTorque); + + NxWheelShape *wShape = getWheelShape(); + float rollAngle = getWheelRollAngle(); + rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + NxMat34& wheelPose = wShape->getGlobalPose(); + + NxWheelContactData wcd; + NxShape* cShape = wShape->getContact(wcd); + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( cShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } + + float rAngle = rollAngle; + float steer = wShape->getSteerAngle(); + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rollAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + setWheelPose(wheelPose); +} +VxVector pWheel2::getGroundContactPos()const +{ + VxVector pos = getWheelPos()+VxVector(0, -mWheelShape->getRadius(), 0); + + if (pos.Magnitude()) + { + int op2 = 0 ; + op2++; + } + return pos; +} + +float pWheel2::getSuspensionTravel()const +{ + + if (mWheelShape) + { + return mWheelShape->getSuspensionTravel(); + } + return 0.0f; +} + + +bool pWheel2::setSuspensionSpring(const pSpring& spring) +{ + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + NxWheelShape *wShape = getWheelShape(); + if (!wShape) + { + return false; + } + wShape->setSuspension(sLimit); + return true; +} + +void pWheel2::setAxleSpeed(float speed) +{ + + getWheelShape()->setAxleSpeed(speed); +} + +void pWheel2::setMotorTorque(float torque) +{ + getWheelShape()->setMotorTorque(torque); +} +void pWheel2::setBreakTorque(float torque) +{ + getWheelShape()->setBrakeTorque(torque); +} + +void pWheel2::setSuspensionTravel(float travel) +{ + getWheelShape()->setSuspensionTravel(travel); +} + + +pWheel2::pWheel2(pRigidBody *body, pWheelDescr *descr) : pWheel(body,descr) +{ + this->setBody(body); + mWheelShape = NULL; + mWheelFlags = descr->wheelFlags; + _wheelRollAngle = 0.0f; + mVehicle = NULL; + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pWorld/pWorld.cpp b/usr/Src/old/Core/pWorld/pWorld.cpp new file mode 100644 index 0000000..b137104 --- /dev/null +++ b/usr/Src/old/Core/pWorld/pWorld.cpp @@ -0,0 +1,642 @@ +#include +#include "vtPhysXAll.h" + +using namespace vtTools::AttributeTools; + +void pWorld::_construct() +{ + //mAllocator = new UserAllocator; + //mCManager = NxCreateControllerManager(mAllocator); +} + +void pWorld::destroyCloth(CK_ID id) +{ + + pCloth*cloth = getCloth(id); + if (cloth) + { + delete cloth; + } +} + +pCloth *pWorld::getCloth(CK_ID id) +{ + + int nbClothes = getScene()->getNbCloths(); + NxCloth** clothes = getScene()->getCloths(); + while(nbClothes--) + { + NxCloth* cloth = *clothes++; + if(cloth->userData != NULL) + { + pCloth *vCloth = static_cast(cloth->userData); + if (vCloth) + { + if (id == vCloth->getEntityID() ) + { + return vCloth; + } + } + } + } + + return NULL; +} + +pCloth *pWorld::getCloth(CK3dEntity*reference) +{ + if (!reference) + { + return NULL; + } + + int nbClothes = getScene()->getNbCloths(); + NxCloth** clothes = getScene()->getCloths(); + while(nbClothes--) + { + NxCloth* cloth = *clothes++; + if(cloth->userData != NULL) + { + pCloth *vCloth = static_cast(cloth->userData); + if (vCloth) + { + if (reference->GetID() == vCloth->getEntityID() ) + { + return vCloth; + } + } + } + } + return NULL; +} + +void pWorld::updateClothes() +{ + int nbClothes = getScene()->getNbCloths(); + NxCloth** clothes = getScene()->getCloths(); + while(nbClothes--) + { + NxCloth* cloth = *clothes++; + if(cloth->userData != NULL) + { + pCloth *vCloth = static_cast(cloth->userData); + if (vCloth) + { + vCloth->updateVirtoolsMesh(); + } + } + } + +} + + + +int pWorld::getNbBodies() +{ + int result = 0; + if (!getScene()) + { + return result; + } + result+= getScene()->getNbActors(); + return result; +} +int pWorld::getNbJoints() +{ + int result = 0; + if (!getScene()) + { + return result; + } + result+= getScene()->getNbJoints(); + return result; +} + + + +NxShape *pWorld::getShapeByEntityID(CK_ID id) +{ + + if (!getScene() ) + { + return NULL; + } + + CK3dEntity *entA = static_cast(GetPMan()->GetContext()->GetObject(id)); + if (!entA) + { + return NULL; + } + + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return NULL; + } + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body =static_cast(actor->userData); + if (body) + { + NxU32 nbShapes = body->getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)body->getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (info) + { + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(info->entID)); + if (ent == entA ) + { + return s; + } + } + } + } + } + } + } + } + return NULL; +} + +pRigidBody* pWorld::getBodyFromSubEntity(CK3dEntity *sub) +{ + + if (!getScene() ) + { + return NULL; + } + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return NULL; + } + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body =static_cast(actor->userData); + if (body) + { + NxU32 nbShapes = body->getActor()->getNbShapes(); + if ( nbShapes ) + { + NxShape ** slist = (NxShape **)body->getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (info) + { + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(info->entID)); + if (ent) + { + if (sub == ent) + { + return body; + } + } + } + } + } + } + } + } + } + return NULL; +} +void pWorld::checkList() +{ + if (!getScene() ) + { + return; + } + + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return; + } + + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body = (pRigidBody*)actor->userData; + if (body) + { + CK3dEntity * ent = static_cast(GetPMan()->GetContext()->GetObject(body->getEntID())); + if (!ent) + { + deleteBody(body); + } + } + } + } + + + int nbClothes = getScene()->getNbCloths(); + NxCloth** clothes = getScene()->getCloths(); + while(nbClothes--) + { + NxCloth* cloth = *clothes++; + if(cloth->userData != NULL) + { + pCloth *vCloth = static_cast(cloth->userData); + if (vCloth) + { + + CK3dEntity * ent = static_cast(GetPMan()->GetContext()->GetObject(vCloth->getEntityID())); + if (!ent) + { + destroyCloth(vCloth->getEntityID()); + } + } + } + } +} +void pWorld::deleteBody(pRigidBody*body) +{ + + if (body) + { + body->destroy(); + if (body->getWorld() && body->getWorld()->getScene() ) + { + + for (int i = 0 ; i < body->getWorld()->getJointFeedbackList().Size(); i++ ) + { + pBrokenJointEntry *entry = *body->getWorld()->getJointFeedbackList().At(i); + if (entry && entry->joint) + { + + /*if (entry->joint->GetVTEntA() == body->GetVT3DObject() || entry->joint->GetVTEntB() == body->GetVT3DObject() ) + { + + i = 0; + + }*/ + } + } + } + delete body; + body =NULL; + } + + checkList(); + + +} + +void pWorld::deleteJoint(pJoint*joint) +{ + + if (!joint) + { + return; + } + + pWorld *world = joint->getWorld(); + if (world && world->getScene() ) + { + + + for (int i = 0 ; i < world->getJointFeedbackList().Size(); i++ ) + { + pBrokenJointEntry *entry = *world->getJointFeedbackList().At(i); + if (entry && entry->joint == joint) + { + world->getJointFeedbackList().EraseAt(i); + break; + } + } + + joint->getJoint()->userData = NULL; + world->getScene()->releaseJoint(*joint->getJoint()); + delete joint; + + } +} + +pJoint* pWorld::getJoint(CK3dEntity *_a, CK3dEntity *_b, JType type) +{ + + if (!getScene()) + { + return NULL; + } + + pRigidBody *a = GetPMan()->getBody(_a); + pRigidBody *b = GetPMan()->getBody(_b); + + //bodies have already a joint together ? + if ( !a && !b) + { + return NULL; + } + + if ( a == b) + { + return NULL; + } + + if (a && !a->isValid() ) + { + return NULL; + } + + if (a && !GetPMan()->getWorldByBody(_a)) + { + return NULL; + } + + if (b && !GetPMan()->getWorldByBody(_b) ) + { + return NULL; + } + + if (b && !b->isValid()) + { + return NULL; + } + + if ( a && b ) + { + pWorld*worldA = GetPMan()->getWorldByBody(_a); + pWorld*worldB = GetPMan()->getWorldByBody(_b); + if (!worldA || !worldB || (worldA!=worldB) || !worldA->isValid() || !worldB->isValid() ) + { + return NULL; + } + } + + NxU32 jointCount = getScene()->getNbJoints(); + if (jointCount) + { + NxArray< NxJoint * > joints; + + getScene()->resetJointIterator(); + for (NxU32 i = 0; i < jointCount; ++i) + { + NxJoint *j = getScene()->getNextJoint(); + + if (type == JT_Any) + { + + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == _a && mJoint->GetVTEntB() == _b ) + { + return mJoint; + } + + CK3dEntity *inA = _b; + CK3dEntity *inB = _a; + if (mJoint->GetVTEntA() == inA && mJoint->GetVTEntB() == inB ) + { + return mJoint; + } + } + } + + + if ( j->getType() == type) + { + + pJoint *mJoint = static_cast( j->userData ); + + if ( mJoint ) + { + if (mJoint->GetVTEntA() == _a && mJoint->GetVTEntB() == _b ) + { + return mJoint; + } + + CK3dEntity *inA = _b; + CK3dEntity *inB = _a; + if (mJoint->GetVTEntA() == inA && mJoint->GetVTEntB() == inB ) + { + return mJoint; + } + } + } + } + } + + return NULL; +} + +bool pWorld::isValid() +{ + + return getScene() ? true : false; +} + +void pWorld::step(float stepsize) +{ + + if (getScene()) + { + NxU32 nbTransforms = 0; + NxActiveTransform *activeTransforms = getScene()->getActiveTransforms(nbTransforms); + + //getScene()->fetchResults(NX_ALL_FINISHED,true); + + //stepsize *=0.001f; + + updateVehicles(stepsize); + + updateClothes(); + + #ifdef HAS_FLUIDS + updateFluids(); + #endif + + getScene()->simulate(stepsize); + + if(nbTransforms && activeTransforms) + { + for(NxU32 i = 0; i < nbTransforms; ++i) + { + // the user data of the actor holds the game object pointer + NxActor *actor = activeTransforms[i].actor; + if (actor) + { + + pRigidBody *body = (pRigidBody*)actor->userData; + // update the game object's transform to match the NxActor + if(body) + { + + //gameObject->setTransform(activeTransforms[i].actor2World); + NxMat34 transformation = activeTransforms[i].actor2World; + VxQuaternion rot = pMath::getFrom(transformation.M); + VxVector pos = pMath::getFrom(transformation.t); + VxVector pos2 = pMath::getFrom(transformation.t); + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(body->getEntID())); + + NxShape *mainShape=body->getMainShape(); + if (mainShape) + { + VxVector diff = getFrom(mainShape->getLocalPosition()); + if (XAbs(diff.SquareMagnitude()) > 0.01f) + { + //pos+=diff; + } + } + + if (ent) + { + ent->SetPosition(&pos); + ent->SetQuaternion(&rot); + body->updateSubShapes(); + }else{ + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Invalid Body due simulation."); + } + } + } + } + } + + NxU32 error; + getScene()->flushStream(); + getScene()->fetchResults(NX_RIGID_BODY_FINISHED,true,&error); + + + int err = error; + + + } +} + + + +pRigidBody*pWorld::getBody(CK3dEntity*ent) +{ + pRigidBody *result = NULL; + + if (!ent || !getScene() ) + { + return NULL; + } + + int nbActors = getScene()->getNbActors(); + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + + pRigidBody* body = (pRigidBody*)actor->userData; + if (body && body->getEntID() == ent->GetID() ) + { + return body; + } + + if (body && body->isSubShape(ent) ) + { + return body; + } + } + } + + return NULL; +} + +pWorld::pWorld(CK3dEntity* _o) +{ + + m_SleepingSettings = NULL; + m_worldSettings =NULL; + m_vtReference = _o; + mScene = NULL; + contactReport = NULL; + triggerReport = NULL; + +} +pWorld::~pWorld() +{ + + //m_worldSettings = NULL; + //m_SleepingSettings =NULL; + mScene = NULL; + //m_vtReference =NULL; +} +void pWorld::destroy() +{ + + + if (getScene()) + { + int nbActors = getScene()->getNbActors(); + if (!nbActors)return; + + + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + if(actor->userData != NULL) + { + pRigidBody* body = (pRigidBody*)actor->userData; + if (body) + { + body->destroy(); + if (body->GetVT3DObject()) + { + xLogger::xLog(XL_START,ELOGTRACE,E_LI_MANAGER,"Body destroyed :"); + } + delete body; + body =NULL; + } + } + } + } + + if (GetPMan()->getPhysicsSDK()) + { + GetPMan()->getPhysicsSDK()->releaseScene(*mScene); + mScene = NULL; + } + + if (m_SleepingSettings) + { + delete m_SleepingSettings; + m_SleepingSettings = NULL; + } + + if (m_worldSettings) + { + delete m_worldSettings; + m_worldSettings = NULL; + } + +} +int pWorld::UpdateProperties(DWORD mode,DWORD flags) +{ + + return 0; + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pWorld/pWorldCollision.cpp b/usr/Src/old/Core/pWorld/pWorldCollision.cpp new file mode 100644 index 0000000..bab074b --- /dev/null +++ b/usr/Src/old/Core/pWorld/pWorldCollision.cpp @@ -0,0 +1,1204 @@ +#include +#include "vtPhysXAll.h" +#include "pWorldCallbacks.h" + +void pContactReport::onContactNotify(NxContactPair& pair, NxU32 events) +{ + + pRigidBody *bodyA = NULL; + pRigidBody *bodyB = NULL; + + if (pair.actors[0]) + { + bodyA = static_cast(pair.actors[0]->userData); + } + if (pair.actors[1]) + { + bodyB = static_cast(pair.actors[1]->userData); + } + + if (bodyA) + { + if (bodyA->hasWheels()) + { + bodyA->handleContactPair(&pair,0); + return ; + } + + if (bodyA->getVehicle()) + { + pVehicle* v = bodyA->getVehicle(); + v->handleContactPair(&pair, 0); + return ; + } + } + if ( bodyB ) + { + if (bodyB->hasWheels()) + { + bodyB->handleContactPair(&pair,1); + return ; + } + + if (bodyB->getVehicle()) + { + pVehicle* v = bodyB->getVehicle(); + v->handleContactPair(&pair, 1); + return ; + } + + + } + + // Iterate through contact points + NxContactStreamIterator i(pair.stream); + //user can call getNumPairs() here + while(i.goNextPair()) + { + //user can also call getShape() and getNumPatches() here + while(i.goNextPatch()) + { + //user can also call getPatchNormal() and getNumPoints() here + const NxVec3& contactNormal = i.getPatchNormal(); + while(i.goNextPoint()) + { + //user can also call getPoint() and getSeparation() here + const NxVec3& contactPoint = i.getPoint(); + pCollisionsEntry entry; + entry.point = pMath::getFrom(contactPoint); + NxU32 faceIndex = i.getFeatureIndex0(); + if(faceIndex==0xffffffff) + faceIndex = i.getFeatureIndex1(); + if(faceIndex!=0xffffffff) + { + entry.faceIndex = faceIndex; + } + + entry.actors[0] = pair.actors[0]; + entry.actors[1] = pair.actors[1]; + entry.faceIndex = faceIndex; + entry.sumNormalForce = pMath::getFrom(pair.sumNormalForce); + entry.sumFrictionForce = pMath::getFrom(pair.sumFrictionForce); + entry.faceNormal = pMath::getFrom(contactNormal); + pRigidBody *bodyA = NULL; + pRigidBody *bodyB = NULL; + if (pair.actors[0]) + { + bodyA = static_cast(pair.actors[0]->userData); + } + if (pair.actors[1]) + { + bodyB = static_cast(pair.actors[1]->userData); + } + + if (bodyA && bodyA->getActor() && (bodyA->getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) ) + { + + entry.bodyA = bodyA; + entry.bodyB = bodyB; + bodyA->getCollisions().Clear(); + bodyA->getCollisions().PushBack(entry); + } + + if (bodyB && bodyB->getActor() && (bodyB->getActor()->getContactReportFlags() & NX_NOTIFY_ON_TOUCH ) ) + { + + entry.bodyA = bodyA; + entry.bodyB = bodyB; + bodyB->getCollisions().Clear(); + bodyB->getCollisions().PushBack(entry); + } + + // result->getActor()->setContactReportFlags(NX_NOTIFY_ON_TOUCH); + /* + { + entry.bodyA = body; + body->getCollisions().Clear(); + body->getCollisions().PushBack(entry); + } + + if (pair.actors[1]) + { + pRigidBody *body = static_cast(pair.actors[1]->userData); + if (body) + { + entry.bodyB = body; + body->getCollisions().Clear(); + body->getCollisions().PushBack(entry); + + } + }*/ + /*getWorld()->getCollisions().PushBack(entry);*/ + } + } + } +} + +int pWorld::overlapOBBShapes(const VxBbox& worldBounds, CK3dEntity*shapeReference, pShapesType shapeType,CKGroup *shapes,int activeGroups/* =0xffffffff */, const pGroupsMask* groupsMask/* =NULL */, bool accurateCollision/* =false */) +{ + + int result=0; + + NxBox box; + + if (shapeReference) + { + + NxShape *shape = getShapeByEntityID(shapeReference->GetID()); + if (shape) + { + //shape->checkOverlapAABB() + + NxBoxShape*boxShape = static_cast(shape->isBox()); + if (boxShape) + { + boxShape->getWorldOBB(box); + } + } + + }else{ + + box.center = getFrom(worldBounds.GetCenter()); + box.extents = getFrom(worldBounds.GetSize()); + } + + int total = 0; + if (shapeType & ST_Dynamic ) + { + total+=getScene()->getNbDynamicShapes(); + } + + if (shapeType & ST_Static) + { + total+=getScene()->getNbStaticShapes(); + } + + NxShape** _shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); + for (NxU32 i = 0; i < total; i++) _shapes[i] = NULL; + + + + NxGroupsMask mask; + if (groupsMask) + { + mask.bits0 = groupsMask->bits0; + mask.bits1 = groupsMask->bits1; + mask.bits2 = groupsMask->bits2; + mask.bits3 = groupsMask->bits3; + }else{ + + mask.bits0 = 0; + mask.bits1 = 0; + mask.bits2 = 0; + mask.bits3 = 0; + + } + + + + + result = getScene()->overlapOBBShapes(box,(NxShapesType)shapeType,total,_shapes,NULL,activeGroups,&mask,accurateCollision); + + if (_shapes && shapes ) + { + for (int i = 0 ; i < result ; i++) + { + NxShape *s = _shapes[i]; + if (s) + { + const char* name =s->getName(); + pSubMeshInfo *sInfo = static_cast(s->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + + shapes->AddObject((CKBeObject*)obj); + } + } + } + } + } + + int op=2; + + + + + return result; + +} + +int pWorld::overlapSphereShapes(const VxSphere& worldSphere,CK3dEntity*shapeReference,pShapesType shapeType,CKGroup*shapes,int activeGroups/* =0xffffffff */, const pGroupsMask* groupsMask/* =NULL */, bool accurateCollision/* =false */) +{ + + int result=0; + + NxSphere sphere; + + if (shapeReference) + { + + NxShape *shape = getShapeByEntityID(shapeReference->GetID()); + if (shape) + { + //shape->checkOverlapAABB() + + NxSphereShape *sphereShape = static_cast(shape->isSphere()); + if (sphereShape) + { + sphere.radius = sphereShape->getRadius() + worldSphere.Radius(); + + //ori : + VxVector ori = worldSphere.Center(); + VxVector oriOut = ori; + if (shapeReference) + { + shapeReference->Transform(&oriOut,&ori); + } + + sphere.center = getFrom(oriOut); + + } + } + + }else{ + + sphere.center = getFrom(worldSphere.Center()); + sphere.radius = worldSphere.Radius(); + + } + + int total = 0; + if (shapeType & ST_Dynamic ) + { + total+=getScene()->getNbDynamicShapes(); + } + + if (shapeType & ST_Static) + { + total+=getScene()->getNbStaticShapes(); + } + + NxShape** _shapes = (NxShape**)NxAlloca(total*sizeof(NxShape*)); + for (NxU32 i = 0; i < total; i++) _shapes[i] = NULL; + + + + NxGroupsMask mask; + if (groupsMask) + { + mask.bits0 = groupsMask->bits0; + mask.bits1 = groupsMask->bits1; + mask.bits2 = groupsMask->bits2; + mask.bits3 = groupsMask->bits3; + }else{ + + mask.bits0 = 0; + mask.bits1 = 0; + mask.bits2 = 0; + mask.bits3 = 0; + + } + + + + + result = getScene()->overlapSphereShapes(sphere,(NxShapesType)shapeType,total,_shapes,NULL,activeGroups,&mask,accurateCollision); + + if (_shapes && shapes ) + { + for (int i = 0 ; i < result ; i++) + { + NxShape *s = _shapes[i]; + if (s) + { + const char* name =s->getName(); + pSubMeshInfo *sInfo = static_cast(s->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + + shapes->AddObject((CKBeObject*)obj); + } + } + } + } + } + + int op=2; + + + + + return result; + +} + +int pWorld::raycastAllShapes(const VxRay& worldRay, pShapesType shapesType, int groups, float maxDist, pRaycastBit hintFlags, const pGroupsMask* groupsMask) +{ + + int result = 0; + + NxRay rayx; + rayx.dir = getFrom(worldRay.m_Direction); + rayx.orig = getFrom(worldRay.m_Origin); + + pRayCastReport &report = *getRaycastReport(); + + NxGroupsMask *mask = NULL; + if (groupsMask) + { + mask = new NxGroupsMask(); + mask->bits0 = groupsMask->bits0; + mask->bits1 = groupsMask->bits1; + mask->bits2 = groupsMask->bits2; + mask->bits3 = groupsMask->bits3; + + } + + result = getScene()->raycastAllShapes(rayx,report,(NxShapesType)shapesType,groups,maxDist,hintFlags,mask); + return result; + + +} +bool pWorld::raycastAnyBounds(const VxRay& worldRay, pShapesType shapesType, pGroupsMask *groupsMask/* =NULL */,int groups/* =0xffffffff */, float maxDist/* =NX_MAX_F32 */) +{ + + if (!getScene()) + { + return false; + } + + NxRay _worldRay; + _worldRay.dir = getFrom(worldRay.m_Direction); + _worldRay.orig = getFrom(worldRay.m_Origin); + + NxShapesType _shapesType = (NxShapesType)shapesType; + + NxReal _maxDist=maxDist; + + NxGroupsMask *mask = NULL; + if (groupsMask) + { + mask = new NxGroupsMask(); + mask->bits0 = groupsMask->bits0; + mask->bits1 = groupsMask->bits1; + mask->bits2 = groupsMask->bits2; + mask->bits3 = groupsMask->bits3; + + } + bool result = getScene()->raycastAnyBounds(_worldRay,_shapesType,groups,_maxDist,mask); + return result; + +} + +void pWorld::cIgnorePair(CK3dEntity *_a, CK3dEntity *_b, int ignore) +{ + + pRigidBody *a = GetPMan()->getBody(_a); + pRigidBody *b = GetPMan()->getBody(_b); + if (a&&b && a->getActor() && b->getActor() ) + { + if (getScene()) + { + getScene()->setActorPairFlags(*a->getActor(),*b->getActor(),ignore ? NX_IGNORE_PAIR : NX_NOTIFY_ALL ); + } + } +} + +void pWorld::cSetGroupCollisionFlag(int g1 , int g2,int enabled) +{ + + if (getScene()) + { + + if (g1 >=0 && g1 <= 31 && g2 >=0 && g2 <= 31) + { + if (enabled==0 || enabled ==1) + { + getScene()->setGroupCollisionFlag(g1,g2,enabled); + } + } + } +} + +void pTriggerReport::onTrigger(NxShape& triggerShape, NxShape& otherShape, NxTriggerFlag status) +{ + + NxActor *triggerActor = &triggerShape.getActor(); + NxActor *otherActor = &otherShape.getActor(); + + + + + pRigidBody *triggerBody = NULL; + pRigidBody *otherBody = NULL; + + if (triggerActor) + { + triggerBody = static_cast(triggerActor->userData); + triggerBody->getTriggers().Clear(); + } + + if (otherActor) + { + otherBody = static_cast(otherActor->userData); + otherBody->getTriggers().Clear(); + } + + + pTriggerEntry entry; + entry.shapeA = &triggerShape; + entry.shapeB = &otherShape; + entry.triggerEvent = status; + + if (triggerBody) + { + triggerBody->getTriggers().PushBack(entry); + + } + /*if(status & NX_TRIGGER_ON_ENTER) + { + + + } + if(status & NX_TRIGGER_ON_LEAVE) + { + + } + if(status & NX_TRIGGER_ON_STAY) + { + // A body entered the trigger area for the first time + + }*/ + + + + +} + + +void pWorld::initUserReports() +{ + + contactReport = new pContactReport(); + contactReport->setWorld(this); + + triggerReport = new pTriggerReport(); + triggerReport->setWorld(this); + + raycastReport = new pRayCastReport(); + raycastReport->setWorld(this); + + //getScene()->raycastAllShapes() + + +} +bool pRayCastReport::onHit(const NxRaycastHit& hit) +{ + + CKBehavior *beh =(CKBehavior*)GetPMan()->m_Context->GetObject(mCurrentBehavior); + if ( beh ) + { + pRayCastHits *carray = NULL; + beh->GetLocalParameterValue(0,&carray); + if (carray) + { + //carray->clear(); + }else + { + carray = new pRayCastHits(); + } + + //carray->push_back(const_cast(&hit)); + + NxRaycastHit *_hit = new NxRaycastHit(); + + _hit->distance = hit.distance; + _hit->faceID = hit.faceID; + _hit->flags = hit.flags; + _hit->internalFaceID = hit.internalFaceID; + _hit->materialIndex = hit.materialIndex; + _hit->shape = hit.shape; + _hit->u = hit.u; + _hit->v = hit.v; + _hit->worldImpact = hit.worldImpact; + _hit->worldNormal = hit.worldNormal; + + const char *name = hit.shape->getName(); + + carray->push_back(_hit); + + + + + beh->SetLocalParameterValue(0,&carray); + + + } + return true; +} + +void pWorld::setFilterOps(pFilterOp op0,pFilterOp op1, pFilterOp op2) +{ + getScene()->setFilterOps((NxFilterOp)op0,(NxFilterOp)op1,(NxFilterOp)op2); +} + +void pWorld::setFilterBool(bool flag) +{ + getScene()->setFilterBool(flag); +} +void pWorld::setFilterConstant0(const pGroupsMask& mask) +{ + NxGroupsMask _mask; + _mask.bits0=mask.bits0; + _mask.bits1=mask.bits1; + _mask.bits2=mask.bits2; + _mask.bits3=mask.bits3; + + getScene()->setFilterConstant0(_mask); +} + +void pWorld::setFilterConstant1(const pGroupsMask& mask) +{ + NxGroupsMask _mask; + _mask.bits0=mask.bits0; + _mask.bits1=mask.bits1; + _mask.bits2=mask.bits2; + _mask.bits3=mask.bits3; + + getScene()->setFilterConstant1(_mask); +} + +bool pWorld::getFilterBool()const +{ + return getScene()->getFilterBool(); +} + +pGroupsMask pWorld::getFilterConstant0()const +{ + NxGroupsMask mask = getScene()->getFilterConstant0(); + pGroupsMask _mask; + + _mask.bits0=mask.bits0; + _mask.bits1=mask.bits1; + _mask.bits2=mask.bits2; + _mask.bits3=mask.bits3; + + return _mask; + +} + +pGroupsMask pWorld::getFilterConstant1()const +{ + NxGroupsMask mask = getScene()->getFilterConstant1(); + pGroupsMask _mask; + + _mask.bits0=mask.bits0; + _mask.bits1=mask.bits1; + _mask.bits2=mask.bits2; + _mask.bits3=mask.bits3; + + return _mask; + +} + + + +/* +int +pWorld::CIsInCollision(CK3dEntity*_a,CK3dEntity*_b) +{ + + pWorld *world=GetPMan()->getWorldByBody(_a); + pWorld *world2=GetPMan()->getWorldByBody(_b); + + + if (!world || !world2 || world!=world2 ) + return false; + + pRigidBody*bodyA= world->getBody(_a); + pRigidBody*bodyB= world->getBody(_b); + + dSurfaceParameters *surface = NULL; + bool worldHasSurface = ( world->GetDataFlags() & WDF_HAS_SURFACE_PARAMETER ) ; + + + bool useSurface = false; + + if (worldHasSurface) + { + surface = &GetDefaultSurface(); + useSurface = true; + } + + if ( bodyA->GetDataFlags() & BDF_HAS_SURFACE_PARAMETER ) + { + surface = &bodyA->GetDefaultSurface(); + useSurface = true; + } + + if ( bodyB->GetDataFlags() & BDF_HAS_SURFACE_PARAMETER ) + { + surface = &bodyB->GetDefaultSurface(); + useSurface = true; + } + + + pRigidBody *surfaceMaterialBody=NULL; + + if (bodyA->GetDataFlags() & BDF_HAS_MATERIAL_SURFACE_PARAMETER) + { + + surfaceMaterialBody = bodyA; + useSurface = true; + } + + if (bodyB->GetDataFlags() & BDF_HAS_MATERIAL_SURFACE_PARAMETER) + { + + surfaceMaterialBody = bodyB; + useSurface = true; + } + + if (bodyA && bodyB && bodyA !=bodyB) + { + dGeomID gid1 = bodyA->GetOdeGeom(); + dGeomID gid2 = bodyB->GetOdeGeom(); + if (gid1 && gid2 && gid1!=gid2) + { + dContact *contact = new dContact[1]; + int nbContacts = dCollide (gid1,gid2,1,&contact[0].geom,sizeof(dContactGeom)); + if (nbContacts) + { + for (int i=0; i < nbContacts; i++) + { + if (surfaceMaterialBody) + { + + CK3dEntity *colliderB = NULL; + if (surfaceMaterialBody->GetVT3DObject() == _a ) + { + colliderB = _b; + }else + colliderB = _a; + + if (surfaceMaterialBody->GetVT3DObject() == colliderB ) + { + int op = 3; + } + + VxVector cPos(contact[i].geom.pos[0],contact[i].geom.pos[1],contact[i].geom.pos[2] ); + + int faceIndex = vtAgeia::math::GetNearestFace(surfaceMaterialBody->GetVT3DObject(),cPos); + + + CKMesh * mesh = surfaceMaterialBody->GetVT3DObject()->GetCurrentMesh(); + if (mesh) + { + + + VxVector pos1,pos2; + surfaceMaterialBody->GetVT3DObject()->GetBaryCenter(&pos2); + surfaceMaterialBody->GetVT3DObject()->Transform(&pos2,&pos2); + + VxIntersectionDesc desc; + surfaceMaterialBody->GetVT3DObject()->RayIntersection(&cPos,&pos2,&desc,NULL); + CKMaterial *material = mesh->GetFaceMaterial(desc.FaceIndex); + if (material) + { + + PhysicMaterialList& mList = surfaceMaterialBody->GetPhysicMaterials(); + int mSize = mList.Size(); + PhysicMaterialList::Iterator it = mList.Find(material->GetID() ); + if( it != mList.End() ) + { + dSurfaceParameters *sPar = *it; + if (sPar) + { + surface = sPar; + + } + } + } + } + } + } + } + } + } + + return 0; +} +void collisionCallback(void *data,dGeomID o1,dGeomID o2) +{ + + pWorld *world = static_cast(data); + if(!world) + return; + + + if( !o1 || !o2) + return; + if (!o1->body && !o2->body) return; + + if( o1 == o2 ) + return; + + if (dGeomIsSpace(o1) || dGeomIsSpace(o2)) + { + // colliding a space with something + dSpaceCollide2(o1,o2,data,&collisionCallback); + // Note we do not want to test intersections within a space, + // only between spaces. + return; + } + + dBodyID b1,b2; + + b1 = dGeomgetBody(o1); + b2 = dGeomgetBody(o2); + + CK_ID e1 = (CK_ID)(dGeomGetData(o1)); + CK_ID e2 = (CK_ID)(dGeomGetData(o2)); + + + CK3dEntity *_e1 = static_cast(GetPMan()->m_Context->GetObject(e1)); + CK3dEntity* _e2 = static_cast(GetPMan()->m_Context->GetObject(e2)); + + // exit without doing anything if the two bodies are connected by a joint + if (b1 && b2 && dAreConnected (b1,b2)) return; + + pRigidBody *solid1 = world->getBody(_e1); + pRigidBody *solid2 = world->getBody(_e2); + + if (!solid1 || !solid2) + { + return; + } + float friction=solid1->GetFriction(); + float restitution = solid1->GetRestitution(); + //for friction, take minimum + + friction=(friction < solid2->GetFriction() ? friction :solid2->GetFriction()); + + //restitution:take minimum + restitution = restitution < solid2->GetRestitution() ? restitution : solid2->GetRestitution(); + + + + dSurfaceParameters *surface = NULL; + bool worldHasSurface = ( world->GetDataFlags() & WDF_HAS_SURFACE_PARAMETER ) ; + + + bool useSurface = false; + + if (worldHasSurface) + { + surface = &world->GetDefaultSurface(); + useSurface = true; + } + + if ( solid1->GetDataFlags() & BDF_HAS_SURFACE_PARAMETER ) + { + surface = &solid1->GetDefaultSurface(); + useSurface = true; + } + + if ( solid2->GetDataFlags() & BDF_HAS_SURFACE_PARAMETER ) + { + surface = &solid2->GetDefaultSurface(); + useSurface = true; + } + + + pRigidBody *surfaceMaterialBody=NULL; + + if (solid1->GetDataFlags() & BDF_HAS_MATERIAL_SURFACE_PARAMETER) + { + + surfaceMaterialBody = solid1; + useSurface = true; + } + + if (solid2->GetDataFlags() & BDF_HAS_MATERIAL_SURFACE_PARAMETER) + { + + surfaceMaterialBody = solid2; + useSurface = true; + } + + + dContact contact[10]; + + if (int numc = dCollide (o1, o2, 10,&contact[0].geom, sizeof(dContact))) + { + for (int i=0; i < numc; i++) + { + + if (contact[i].geom.depth > 0.0f && contact[i].geom.depth <= 0.0001f) + { + contact[i].geom.depth = 0.001f; + } + if (contact[i].geom.depth == 0.0f) + { + continue; + } + + if (surfaceMaterialBody) + { + + + CK3dEntity *colliderB = NULL; + if (surfaceMaterialBody->GetVT3DObject() == _e1 ) + { + colliderB = _e2; + }else + colliderB = _e1; + + VxVector cPos(contact[i].geom.pos[0],contact[i].geom.pos[1],contact[i].geom.pos[2] ); + //int faceIndex = vtODE::math::GetNearestFace(surfaceMaterialBody->GetVT3DObject(),cPos); + VxVector pos1,pos2; + surfaceMaterialBody->GetVT3DObject()->GetBaryCenter(&pos2); + surfaceMaterialBody->GetVT3DObject()->Transform(&pos2,&pos2); + + VxIntersectionDesc desc; + surfaceMaterialBody->GetVT3DObject()->RayIntersection(&cPos,&pos2,&desc,NULL); + int faceIndex = desc.FaceIndex; + CKMesh * mesh = surfaceMaterialBody->GetVT3DObject()->GetCurrentMesh(); + if (mesh) + { + + CKMaterial *material = mesh->GetFaceMaterial(faceIndex); + if (material) + { + + PhysicMaterialList& mList = surfaceMaterialBody->GetPhysicMaterials(); + int mSize = mList.Size(); + PhysicMaterialList::Iterator it = mList.Find(material->GetID() ); + if( it != mList.End() ) + { + dSurfaceParameters *sPar = *it; + if (sPar) + { + surface = sPar; + + } + } + } + } + } + + if ( useSurface) + { + + + contact[i].surface.mode = surface->mode; + contact[i].surface.mu = surface->mu; + contact[i].surface.mu2 = friction; + contact[i].surface.slip1 = surface->slip1; + contact[i].surface.slip2 = surface->slip2; + contact[i].surface.motion1 = surface->motion1; + contact[i].surface.motion2 = surface->motion2; + contact[i].surface.motionN = surface->motionN; + contact[i].surface.soft_erp = surface->soft_erp; + contact[i].surface.soft_cfm = surface->soft_cfm; + contact[i].surface.bounce = restitution;//0.5; + contact[i].surface.bounce_vel = surface->bounce_vel; + }else + { + + //contact[i].surface.mode = dContactSlip1 | dContactSlip2 |dContactBounce|dContactSoftERP | dContactSoftCFM | dContactApprox1; + //contact[i].surface.mode = dContactSoftERP | dContactApprox1| dContactApprox0 | dContactSoftCFM|dContactBounce ; + //contact[i].surface.mode = dContactSlip1 | dContactSlip2 | dContactSoftERP | dContactApprox1 |dContactBounce; + contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactSlip1 | dContactSlip2; + //contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactBounce| dContactApprox0| dContactSlip1 | dContactSlip2; + //contact[i].surface.mode = dContactSlip1 | dContactSlip2 | dContactSoftERP | dContactApprox1 ; + contact[i].surface.mu = dInfinity; + contact[i].surface.mu2 = friction; + contact[i].surface.slip1 = 0.000001; + contact[i].surface.slip2 = 0.000001; + contact[i].surface.soft_erp = 0.4; + contact[i].surface.soft_cfm = 0.000000005; + contact[i].surface.bounce = restitution;//0.5; + contact[i].surface.bounce_vel = 0.0000001f; + } + + dJointID c = dJointCreateContact (world->World(),world->ContactGroup(),contact+i); + dJointAttach (c,dGeomgetBody(o1),dGeomgetBody(o2)); + } + } +} +////////////////////////////////////////////////////////////////////////// +bool pWorld::collide() +{ + + SpaceID()->collide(this,&collisionCallback); + + return true; +} +////////////////////////////////////////////////////////////////////////// +vt3DObjectType pWorld::CIsInCollision(vt3DObjectType a, CKGroup *group,VxVector& pos, VxVector& normal,float &length) +{ + + pRigidBody *bodyA = getBody(a); + + dGeomID gid1 = NULL; + if (bodyA) + { + gid1 = bodyA->GetOdeGeom(); + } + + if (!a || !group || !bodyA || !gid1) + { + return NULL; + } + + for (int i = 0 ; i < group->GetObjectCount() ; i ++) + { + + pRigidBody*bodyB= getBody((CK3dEntity*)group->GetObject(i)); + if (bodyB) + { + + if (bodyB==bodyA) + { + continue; + } + + if (bodyB) + { + dGeomID gid2 = bodyB->GetOdeGeom(); + if (gid1==gid2) + { + continue; + } + + if (gid2) + { + dContact *contact = new dContact[1]; + + int nbContacts = dCollide (gid1,gid2,1,&contact[0].geom,sizeof(dContactGeom)); + if (nbContacts) + { + for (int i = 0 ; i < nbContacts ; i++ ) + { + pos.x = contact[0].geom.pos[0]; + pos.y = contact[0].geom.pos[1]; + pos.z = contact[0].geom.pos[2]; + + normal.x =contact[0].geom.normal[0]; + normal.y =contact[0].geom.normal[1]; + normal.z = contact[0].geom.normal[2]; + + return bodyB->GetVT3DObject(); + } + } + } + } + + } + } + return NULL; +} + +////////////////////////////////////////////////////////////////////////// +vt3DObjectType pWorld::CRayCollision(VxVector point,CK3dEntity*pointRef,VxVector dir,CK3dEntity*dirRef,float depth,bool skipPosRef,VxVector& pos, VxVector& normal) +{ + + ////////////////////////////////////////////////////////////////////////// + //origin of the ray : + VxVector origin = point; + VxVector originOut = origin; + if (pointRef) + { + pointRef->Transform(&originOut,&origin); + } + + ////////////////////////////////////////////////////////////////////////// + //direction of the ray : + VxVector dirIn = dir; + VxVector dirOut = dirIn; + if (dirRef) + { + VxVector dirl,up,right; + dirRef->GetOrientation(&dirl,&up,&right); + dirRef->TransformVector(&dirOut,&dirIn); + } + + //dirOut*=dirIn; + + ////////////////////////////////////////////////////////////////////////// + pRigidBody *bodyA = NULL; + dGeomID gid1 = NULL; + //if position reference is given : + if (pointRef) + { + bodyA = getBody(pointRef); + if (bodyA) + { + gid1 = bodyA->GetOdeGeom(); + } + } + + + ////////////////////////////////////////////////////////////////////////// + //our ray : + dGeomID raygeom = dCreateRay(SpaceID(),depth); + if (raygeom) + { + dGeomRaySet(raygeom,originOut.x,originOut.y,originOut.z,dirOut.x,dirOut.y,dirOut.z); + } + + if (!raygeom) + { + return NULL; + } + + ////////////////////////////////////////////////////////////////////////// + //we check through the world : + + dxBody *bb; + for (bb=World()->firstbody; bb; bb=(dxBody*)bb->next) + { + pRigidBody *bodyB = static_cast(dBodyGetData(bb)); + if (bodyB) + { + dGeomID gid2 = bodyB->GetOdeGeom(); + CK3dEntity *ent2 = bodyB->GetVT3DObject(); + + if (gid2) + { + dContact *contact = new dContact[1]; + + int nbContacts = dCollide (raygeom,gid2,1,&contact[0].geom,sizeof(dContactGeom)); + if (nbContacts) + { + if (gid1 && gid2 == gid1 && skipPosRef ) + { + continue; + } + + pos.x = contact[0].geom.pos[0]; + pos.y = contact[0].geom.pos[1]; + pos.z = contact[0].geom.pos[2]; + + normal.x =contact[0].geom.normal[0]; + normal.y =contact[0].geom.normal[1]; + normal.z = contact[0].geom.normal[2]; + + return bodyB->GetVT3DObject(); + + } + } + } + } + + return NULL; + +} + +////////////////////////////////////////////////////////////////////////// +vt3DObjectType pWorld::CIsInCollision(vt3DObjectType a, VxVector& pos, VxVector& normal,float &length) +{ + pWorld *world=GetPMan()->getWorldByBody(a); + if (world) + { + + pRigidBody*bodyA= world->getBody(a); + if (bodyA) + { + dGeomID gid1 = bodyA->GetOdeGeom(); + if (gid1) + { + dxBody *bb; + for (bb=world->World()->firstbody; bb; bb=(dxBody*)bb->next) + { + pRigidBody *bodyB = static_cast(dBodyGetData(bb)); + if (bodyB==bodyA) + { + continue; + } + if (bodyB) + { + + dGeomID gid2 = bodyB->GetOdeGeom(); + if (gid1==gid2) + { + continue; + } + if (gid2) + { + dContact *contact = new dContact[1]; + + int nbContacts = dCollide (gid1,gid2,1,&contact[0].geom,sizeof(dContactGeom)); + if (nbContacts) + { + + pos.x = contact[0].geom.pos[0]; + pos.y = contact[0].geom.pos[1]; + pos.z = contact[0].geom.pos[2]; + + normal.x =contact[0].geom.normal[0]; + normal.y =contact[0].geom.normal[1]; + normal.z = contact[0].geom.normal[2]; + + length = contact[0].geom.depth; + return bodyB->GetVT3DObject(); + } + } + } + } + } + } + } + return NULL; +} + + + +////////////////////////////////////////////////////////////////////////// +bool pWorld::CIsInCollision(vt3DObjectType a, vt3DObjectType b,VxVector& pos, VxVector& normal,float &length) +{ + + bool result = false; + + pWorld *world=GetPMan()->getWorldByBody(a); + pWorld *world2=GetPMan()->getWorldByBody(b); + + + if (!world || !world2 || world!=world2 ) + return false; + + pRigidBody*bodyA= world->getBody(a); + pRigidBody*bodyB= world->getBody(b); + + if (bodyA && bodyB && bodyA !=bodyB) + { + dGeomID gid1 = bodyA->GetOdeGeom(); + dGeomID gid2 = bodyB->GetOdeGeom(); + if (gid1 && gid2 && gid1!=gid2) + { + dContact *contact = new dContact[1]; + int nbContacts = dCollide (gid1,gid2,1,&contact[0].geom,sizeof(dContactGeom)); + if (nbContacts) + { + pos.x = contact[0].geom.pos[0]; + pos.y = contact[0].geom.pos[1]; + pos.z = contact[0].geom.pos[2]; + + normal.x =contact[0].geom.normal[0]; + normal.y =contact[0].geom.normal[1]; + normal.z = contact[0].geom.normal[2]; + length = contact[0].geom.depth; + return true; + } + } + } + return result; +} +*/ \ No newline at end of file diff --git a/usr/Src/old/Core/pWorld/pWorldFluids.cpp b/usr/Src/old/Core/pWorld/pWorldFluids.cpp new file mode 100644 index 0000000..d45e379 --- /dev/null +++ b/usr/Src/old/Core/pWorld/pWorldFluids.cpp @@ -0,0 +1,65 @@ +#include +#include "vtPhysXAll.h" + +#ifdef HAS_FLUIDS + + + +pFluid *pWorld::getFluid(CK_ID id) +{ + + int nbFluids= getScene()->getNbFluids(); + NxFluid** fluids = getScene()->getFluids(); + while(nbFluids--) + { + NxFluid* fluid = *fluids++; + if(fluid->userData != NULL) + { + pFluid *vFluid = static_cast(fluid->userData); + if (vFluid) + { + + if (vFluid->getEntityID() == id) + { + return vFluid; + + } + } + } + } + + return NULL; +} + +pFluid*pWorld::getFluid(CK3dEntity* entity) +{ + if (!entity) + { + return NULL; + } + + return getFluid(entity->GetID()); + +} +void pWorld::updateFluids() +{ + + + int nbFluids= getScene()->getNbFluids(); + NxFluid** fluids = getScene()->getFluids(); + while(nbFluids--) + { + NxFluid* fluid = *fluids++; + if(fluid->userData != NULL) + { + pFluid *vFluid = static_cast(fluid->userData); + if (vFluid) + { + vFluid->updateVirtoolsMesh(); + + } + } + } + +} +#endif \ No newline at end of file diff --git a/usr/Src/old/Core/pWorld/pWorldSettings.cpp b/usr/Src/old/Core/pWorld/pWorldSettings.cpp new file mode 100644 index 0000000..1537be1 --- /dev/null +++ b/usr/Src/old/Core/pWorld/pWorldSettings.cpp @@ -0,0 +1,158 @@ +#include +#include "vtPhysXAll.h" +#include "pWorldSettings.h" + +#include + +std::vector&_getValidDominanceGroups(std::vector&_inputGroups,pDominanceSetupItem *testItem) +{ + std::vector result; + + if (!_inputGroups.size()) + return result; + + + /* + + g1A + g1A + g1A != g1B ! + + g2A + g2B + + 1 2 3 + + + 1 : 1 - 2 + 2 : 1 - 3 + + */ + + for (int i = 0 ; i < _inputGroups.size() ; i++) + { + pDominanceSetupItem* cItem =_inputGroups[i]; + + if ( cItem == testItem ) + { + result.push_back(cItem); + continue; + } + + if ( cItem->dominanceGroup0 != testItem->dominanceGroup0 ) + { + + } + + + } + +} + + +void pWorld::_checkForDominanceConstraints() +{ + +#ifndef _DEBUG + assert(getReference()); + assert(getScene()); +#endif + + int att = GetPMan()->getAttributeTypeByGuid(VTS_PHYSIC_DOMINANCE_SCENE_SETTINGS); + + if (!getReference()->HasAttribute(att)) + return; + + CKParameterOut *domPar = getReference()->GetAttributeParameter(att); + if(!domPar) + return; + + + using namespace vtTools::ParameterTools; + using namespace vtTools::AttributeTools; + + + CKParameterOut *d1 = GetParameterFromStruct(domPar,PS_WDS_ITEM1); + CKParameterOut *d2 = GetParameterFromStruct(domPar,PS_WDS_ITEM2); + CKParameterOut *d3 = GetParameterFromStruct(domPar,PS_WDS_ITEM3); + CKParameterOut *d4 = GetParameterFromStruct(domPar,PS_WDS_ITEM4); + CKParameterOut *d5 = GetParameterFromStruct(domPar,PS_WDS_ITEM5); + + pDominanceSetupItem item1; + pDominanceSetupItem item2; + pDominanceSetupItem item3; + pDominanceSetupItem item4; + pDominanceSetupItem item5; + + + + int error = pFactory::Instance()->copyTo(d1,item1); + + error = pFactory::Instance()->copyTo(d2,item2); + error = pFactory::Instance()->copyTo(d3,item3); + error = pFactory::Instance()->copyTo(d4,item4); + error = pFactory::Instance()->copyTo(d5,item5); + + std::vector allDominanceItems; + + //################################################################ + // + // gather all in an array + // + + + + int a = item1.dominanceGroup0; + int a1 = item1.dominanceGroup1; + + if (item1.dominanceGroup0 !=0 && item1.dominanceGroup1 !=0 && (item1.dominanceGroup0 != item1.dominanceGroup1 ) ) + allDominanceItems.push_back(&item1); + + if (item2.dominanceGroup0 !=0 && item2.dominanceGroup1 !=0 && (item2.dominanceGroup0 != item1.dominanceGroup1 ) ) + allDominanceItems.push_back(&item2); + + if (item3.dominanceGroup0 !=0 && item3.dominanceGroup1 !=0 && (item3.dominanceGroup0 != item3.dominanceGroup1 ) ) + allDominanceItems.push_back(&item3); + + if (item4.dominanceGroup0 !=0 && item4.dominanceGroup1 !=0 && (item4.dominanceGroup0 != item4.dominanceGroup1 ) ) + allDominanceItems.push_back(&item4); + + if (item5.dominanceGroup0 !=0 && item5.dominanceGroup1 !=0 && (item5.dominanceGroup0 != item5.dominanceGroup1 ) ) + allDominanceItems.push_back(&item5); + + + //std::vector_validDominanceItems1 = _getValidDominanceGroups(allDominanceItems,&item1); + //int s = _validDominanceItems1.size(); + + + + for (int i = 0 ; i < allDominanceItems.size() ; i++) + { + pDominanceSetupItem* cItem = allDominanceItems[i]; + NxConstraintDominance cD1( cItem->constraint.dominanceA , cItem->constraint.dominanceB ); + + getScene()->setDominanceGroupPair(cItem->dominanceGroup0, cItem->dominanceGroup1,cD1); + + + + + } + + + + +} + + + +namespace vtAgeia +{ + + +pWorldSettings::pWorldSettings() : + m_Gravity(VxVector(0.0f,-9.81f,0.0f)) , + m_SkinWith(0.1) +{ + +} + + +} \ No newline at end of file diff --git a/usr/Src/old/Core/pWorld/pWorldVehicle.cpp b/usr/Src/old/Core/pWorld/pWorldVehicle.cpp new file mode 100644 index 0000000..7ab18c1 --- /dev/null +++ b/usr/Src/old/Core/pWorld/pWorldVehicle.cpp @@ -0,0 +1,60 @@ +#include +#include "vtPhysXAll.h" + + +void pWorld::updateVehicle(pVehicle *vehicle, float dt) +{ + if (vehicle) + { + vehicle->updateVehicle(dt); + } +} + +void pWorld::updateVehicles(float dt) +{ + + int nbActors = getScene()->getNbActors(); + if (!nbActors) + { + return; + } + NxActor** actors = getScene()->getActors(); + while(nbActors--) + { + NxActor* actor = *actors++; + pRigidBody *body = static_cast(actor->userData); + if (body) + { + if (!isVehicle(actor) && body->hasWheels()) + { + body->updateWheels(dt); + } + } + + if (body && isVehicle(actor)) + { + updateVehicle(body->getVehicle(),dt); + } + } +} +bool pWorld::isVehicle(NxActor* actor) +{ + + pRigidBody *body = static_cast(actor->userData); + if (body) + { + return body->getVehicle() ? true : false; + } + return false; +} + +pVehicle*pWorld::getVehicle(CK3dEntity* body) +{ + + pRigidBody *rbody = getBody(body); + if (body && rbody->getVehicle() ) + { + return rbody->getVehicle(); + } + return NULL; +} diff --git a/usr/Src/old/PhysicManagerJointVSL.cpp b/usr/Src/old/PhysicManagerJointVSL.cpp new file mode 100644 index 0000000..3dbeae8 --- /dev/null +++ b/usr/Src/old/PhysicManagerJointVSL.cpp @@ -0,0 +1,217 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + +//#include "pVehicle.h" + + + + +PhysicManager *ourMan = NULL; + +CKGUID GetPhysicManagerGUID() { return GUID_MODULE_MANAGER;} + +void __newpVehicleDescr(BYTE *iAdd) +{ + + new (iAdd)pVehicleDesc(); +} + +void __newpVehicleMotorDesc(BYTE *iAdd) +{ + new (iAdd)pVehicleMotorDesc(); +} + +void __newpVehicleGearDesc(BYTE *iAdd) +{ + new(iAdd)pVehicleGearDesc(); +} + +////////////////////////////////////////////////////////////////////////// + +#define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) + + +void PhysicManager::_RegisterVSL() +{ + + ourMan = GetPMan(); + + int z = D6DT_Position; + int y = D6DT_Velocity; + + + STARTVSLBIND(m_Context) + + DECLAREPOINTERTYPE(pVehicleMotorDesc) + DECLAREMEMBER(pVehicleMotorDesc,float,maxRpmToGearUp) + DECLAREMEMBER(pVehicleMotorDesc,float,minRpmToGearDown) + DECLAREMEMBER(pVehicleMotorDesc,float,maxRpm) + DECLAREMEMBER(pVehicleMotorDesc,float,minRpm) + DECLAREMETHOD_0(pVehicleMotorDesc,void,setToCorvette) + + DECLAREPOINTERTYPE(pVehicleGearDesc) + DECLAREMEMBER(pVehicleGearDesc,int,nbForwardGears) + DECLAREMETHOD_0(pVehicleGearDesc,void,setToDefault) + DECLAREMETHOD_0(pVehicleGearDesc,void,setToCorvette) + DECLAREMETHOD_0(pVehicleGearDesc,bool,isValid) + + + + DECLAREOBJECTTYPE(pWheelDescr) + DECLARECTOR_0(__newpWheelDescr) + + DECLAREOBJECTTYPE(pVehicleDesc) + DECLARECTOR_0(__newpVehicleDescr) + DECLAREMEMBER(pVehicleDesc,float,digitalSteeringDelta) + DECLAREMEMBER(pVehicleDesc,VxVector,steeringSteerPoint) + DECLAREMEMBER(pVehicleDesc,VxVector,steeringTurnPoint) + DECLAREMEMBER(pVehicleDesc,float,steeringMaxAngle) + DECLAREMEMBER(pVehicleDesc,float,transmissionEfficiency) + DECLAREMEMBER(pVehicleDesc,float,differentialRatio) + DECLAREMEMBER(pVehicleDesc,float,maxVelocity) + DECLAREMEMBER(pVehicleDesc,float,motorForce) + + DECLAREMETHOD_0(pVehicleDesc,pVehicleGearDesc*,getGearDescription) + DECLAREMETHOD_0(pVehicleDesc,pVehicleMotorDesc*,getMotorDescr) + DECLAREMETHOD_0(pVehicleDesc,void,setToDefault) + + DECLAREPOINTERTYPE(pWheel) + DECLAREPOINTERTYPE(pVehicle) + DECLAREPOINTERTYPE(pVehicleMotor) + DECLAREPOINTERTYPE(pVehicleGears) + + DECLAREPOINTERTYPE(pWheel1) + DECLAREPOINTERTYPE(pWheel2) + + DECLAREINHERITANCESIMPLE("pWheel","pWheel1") + DECLAREINHERITANCESIMPLE("pWheel","pWheel2") + + + ////////////////////////////////////////////////////////////////////////// + // + // Vehicle : + // + DECLAREMETHOD_1(pVehicle,void,updateVehicle,float) + DECLAREMETHOD_5(pVehicle,void,setControlState,float,bool,float,bool,bool) + + + DECLAREMETHOD_1(pVehicle,pWheel*,getWheel,CK3dEntity*) + DECLAREMETHOD_0(pVehicle,pVehicleMotor*,getMotor) + DECLAREMETHOD_0(pVehicle,pVehicleGears*,getGears) + + DECLAREMETHOD_0(pVehicle,void,gearUp) + DECLAREMETHOD_0(pVehicle,void,gearDown) + + + DECLAREMETHOD_0(pVehicleGears,int,getGear) + + + + ////////////////////////////////////////////////////////////////////////// + //motor : + DECLAREMETHOD_0(pVehicleMotor,float,getRpm) + DECLAREMETHOD_0(pVehicleMotor,float,getTorque) + + + DECLAREMETHOD_0(pWheel,pWheel1*,castWheel1) + DECLAREMETHOD_0(pWheel,pWheel2*,castWheel2) + + DECLAREMETHOD_0(pWheel,float,getWheelRollAngle) + DECLAREMETHOD_0(pWheel2,float,getRpm) + DECLAREMETHOD_0(pWheel2,float,getAxleSpeed) + DECLAREMETHOD_0(pWheel2,float,getSuspensionTravel) + DECLAREMETHOD_0(pWheel2,VxVector,getGroundContactPos) + + + + DECLAREMETHOD_2(pFactory,pVehicle*,createVehicle,CK3dEntity*,pVehicleDesc) + + + + + ////////////////////////////////////////////////////////////////////////// + // + // MANAGER + // + DECLAREFUN_C_0(CKGUID, GetPhysicManagerGUID) + DECLAREOBJECTTYPE(PhysicManager) + DECLARESTATIC_1(PhysicManager,PhysicManager*,Cast,CKBaseManager* iM) + DECLAREFUN_C_0(PhysicManager*, GetPhysicManager) + + DECLAREMETHOD_0(PhysicManager,pWorld*,getDefaultWorld) + DECLAREMETHOD_1(PhysicManager,pRigidBody*,getBody,CK3dEntity*) + DECLAREMETHOD_1(PhysicManager,pWorld*,getWorldByBody,CK3dEntity*) + DECLAREMETHOD_1(PhysicManager,pWorld*,getWorld,CK_ID) + DECLAREMETHOD_3_WITH_DEF_VALS(PhysicManager,pJoint*,getJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NULL,JType,JT_Any) + +// DECLAREMETHOD_0(PhysicManager,void,makeDongleTest) + + + ////////////////////////////////////////////////////////////////////////// + // + // World + // + + DECLAREMETHOD_1(pWorld,pRigidBody*,getBody,CK3dEntity*) + DECLAREMETHOD_1(pWorld,pVehicle*,getVehicle,CK3dEntity*) + DECLAREMETHOD_3(pWorld,pJoint*,getJoint,CK3dEntity*,CK3dEntity*,JType) + + DECLAREMETHOD_3(pWorld,void,setFilterOps,pFilterOp,pFilterOp,pFilterOp) + DECLAREMETHOD_1(pWorld,void,setFilterBool,bool) + DECLAREMETHOD_1(pWorld,void,setFilterConstant0,const pGroupsMask&) + DECLAREMETHOD_1(pWorld,void,setFilterConstant1,const pGroupsMask&) + + + + + // + DECLAREMETHOD_5_WITH_DEF_VALS(pWorld,bool,raycastAnyBounds,const VxRay&,NODEFAULT,pShapesType,NODEFAULT,pGroupsMask,NODEFAULT,int,0xffffffff,float,NX_MAX_F32) + DECLAREMETHOD_8(pWorld,bool,overlapSphereShapes,CK3dEntity*,const VxSphere&,CK3dEntity*,pShapesType,CKGroup*,int,const pGroupsMask*,BOOL) + + //(const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,unsigned int groups=0xffffffff, float maxDist=NX_MAX_F32); + + + STOPVSLBIND + + +} + + +PhysicManager*GetPhysicManager() +{ + return GetPMan(); +} + +/* +void __newvtWorldSettings(BYTE *iAdd) +{ +new (iAdd) pWorldSettings(); +} +void __newvtSleepingSettings(BYTE *iAdd) +{ +new (iAdd) pSleepingSettings(); +} +void __newvtJointSettings(BYTE *iAdd) +{ +new (iAdd) pJointSettings(); +} + + +int TestWS(pWorldSettings pWS) +{ +VxVector grav = pWS.Gravity(); +return 2; +} + +pFactory* GetPFactory(); + + +pFactory* GetPFactory() +{ +return pFactory::Instance(); +} + + +extern pRigidBody*getBody(CK3dEntity*ent); +*/ \ No newline at end of file diff --git a/usr/Src/old/PhysicManagerVTClothVSL.cpp b/usr/Src/old/PhysicManagerVTClothVSL.cpp new file mode 100644 index 0000000..a3ec121 --- /dev/null +++ b/usr/Src/old/PhysicManagerVTClothVSL.cpp @@ -0,0 +1,823 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + +//#include "pVehicle.h" + + + + +PhysicManager *ourMan = NULL; +void __newpClothDescr(BYTE *iAdd) +{ + new(iAdd)pClothDesc(); +} + + +void PhysicManager::_RegisterVSLCloth() +{ + + ourMan = GetPMan(); + + + STARTVSLBIND(m_Context) + + DECLAREOBJECTTYPE(pClothDesc) + + DECLAREMEMBER(pClothDesc,float,thickness) + DECLAREMEMBER(pClothDesc,float,density) + DECLAREMEMBER(pClothDesc,float,bendingStiffness) + + DECLAREMEMBER(pClothDesc,float,stretchingStiffness) + DECLAREMEMBER(pClothDesc,float,dampingCoefficient) + DECLAREMEMBER(pClothDesc,float,friction) + DECLAREMEMBER(pClothDesc,float,pressure) + DECLAREMEMBER(pClothDesc,float,tearFactor) + DECLAREMEMBER(pClothDesc,float,collisionResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,attachmentResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,attachmentTearFactor) + DECLAREMEMBER(pClothDesc,float,toFluidResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,fromFluidResponseCoefficient) + DECLAREMEMBER(pClothDesc,float,minAdhereVelocity) + DECLAREMEMBER(pClothDesc,int,solverIterations) + DECLAREMEMBER(pClothDesc,VxVector,externalAcceleration) + DECLAREMEMBER(pClothDesc,VxVector,windAcceleration) + DECLAREMEMBER(pClothDesc,float,wakeUpCounter) + DECLAREMEMBER(pClothDesc,float,sleepLinearVelocity) + DECLAREMEMBER(pClothDesc,int,collisionGroup) + DECLAREMEMBER(pClothDesc,VxBbox,validBounds) + DECLAREMEMBER(pClothDesc,float,relativeGridSpacing) + DECLAREMEMBER(pClothDesc,pClothFlag,flags) + DECLAREMEMBER(pClothDesc,pClothAttachmentFlag,attachmentFlags) + DECLAREMEMBER(pClothDesc,VxColor,tearVertexColor) + DECLAREMEMBER(pClothDesc,CK_ID,worldReference) + + + DECLAREMETHOD_0(pClothDesc,void,setToDefault) + DECLARECTOR_0(__newpClothDescr) + DECLAREPOINTERTYPE(pWorld) + + DECLAREPOINTERTYPE(pRigidBody) + DECLAREPOINTERTYPEALIAS(pRigidBody,"pBody") + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Serializer : + // + DECLAREPOINTERTYPE(pSerializer) + DECLAREFUN_C_0(pSerializer*, GetSerializer) + DECLAREMETHOD_2(pSerializer,void,overrideBody,pRigidBody*,int) + DECLAREMETHOD_2(pSerializer,int,loadCollection,const char*,int) + DECLAREMETHOD_1(pSerializer,int,saveCollection,const char*) + DECLAREMETHOD_2(pSerializer,void,parseFile,const char*,int) + + + ////////////////////////////////////////////////////////////////////////// + // + // Joints : + // + + + DECLAREPOINTERTYPE(pJoint) + DECLAREPOINTERTYPE(pJointFixed) + DECLAREPOINTERTYPE(pJointDistance) + DECLAREPOINTERTYPE(pJointD6) + DECLAREPOINTERTYPE(pJointPulley) + DECLAREPOINTERTYPE(pJointBall) + DECLAREPOINTERTYPE(pJointRevolute) + DECLAREPOINTERTYPE(pJointPrismatic) + DECLAREPOINTERTYPE(pJointCylindrical) + DECLAREPOINTERTYPE(pJointPointInPlane) + DECLAREPOINTERTYPE(pJointPointOnLine) + + + DECLAREINHERITANCESIMPLE("pJoint","pJointDistance") + DECLAREINHERITANCESIMPLE("pJoint","pJointD6") + DECLAREINHERITANCESIMPLE("pJoint","pJointFixed") + DECLAREINHERITANCESIMPLE("pJoint","pJointPulley") + DECLAREINHERITANCESIMPLE("pJoint","pJointBall") + DECLAREINHERITANCESIMPLE("pJoint","pJointRevolute") + DECLAREINHERITANCESIMPLE("pJoint","pJointPrismatic") + DECLAREINHERITANCESIMPLE("pJoint","pJointCylindrical") + DECLAREINHERITANCESIMPLE("pJoint","pJointPointOnLine") + DECLAREINHERITANCESIMPLE("pJoint","pJointPointInPlane") + + + + ////////////////////////////////////////////////////////////////////////// + // + // Factory + // + + DECLAREPOINTERTYPE(pFactory) + DECLAREFUN_C_0(pFactory,getPFactory) + + + + ////////////////////////////////////////////////////////////////////////// + // + // ENUMERATION + // + + DECLAREENUM("D6DriveType") + + DECLAREENUMVALUE("D6DriveType", "D6DT_Position" ,1 ) + DECLAREENUMVALUE("D6DriveType", "D6DT_Velocity" ,2 ) + + + DECLAREENUM("PForceMode") + + DECLAREENUMVALUE("PForceMode", "PFM_Force" , 0) + DECLAREENUMVALUE("PForceMode", "PFM_Impulse" , 1) + DECLAREENUMVALUE("PForceMode", "PFM_VelocityChange" , 2) + DECLAREENUMVALUE("PForceMode", "PFM_SmoothImpulse" , 3) + DECLAREENUMVALUE("PForceMode", "PFM_SmoothVelocityChange" , 4) + DECLAREENUMVALUE("PForceMode", "PFM_Acceleration" , 5) + + DECLAREENUM("D6MotionMode") + + DECLAREENUMVALUE("D6MotionMode", "D6MM_Locked" , 0) + DECLAREENUMVALUE("D6MotionMode", "D6MM_Limited" , 1) + DECLAREENUMVALUE("D6MotionMode", "D6MM_Free" , 2) + + DECLAREENUM("JType") + DECLAREENUMVALUE("JType", "JT_Any" , -1) + DECLAREENUMVALUE("JType", "JT_Prismatic" , 0) + DECLAREENUMVALUE("JType", "JT_Revolute" , 1) + DECLAREENUMVALUE("JType", "JT_Cylindrical" , 2) + DECLAREENUMVALUE("JType", "JT_Spherical" , 3) + DECLAREENUMVALUE("JType", "JT_PointOnLine" , 4) + DECLAREENUMVALUE("JType", "JT_PointInPlane" , 5) + DECLAREENUMVALUE("JType", "JT_Distance" , 6) + DECLAREENUMVALUE("JType", "JT_Pulley" , 7) + DECLAREENUMVALUE("JType", "JT_Fixed" ,8 ) + DECLAREENUMVALUE("JType", "JT_D6" ,9 ) + + + ////////////////////////////////////////////////////////////////////////// + // + // Bindings for pVehicle related classes : + // + // + DECLAREMETHOD_2(pFactory,pVehicle*,createVehicle,CK3dEntity*,pVehicleDesc) + + + //DECLAREMETHOD_0(pVehicle,float,getWheelRollAngle) + //DECLAREMETHOD_0(pVehicle,float,getRpm) + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT CREATION + // + DECLAREMETHOD_7_WITH_DEF_VALS(pFactory,pJointDistance*,createDistanceJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NODEFAULT,VxVector,VxVector(),VxVector,VxVector(),float,0.0f,float,0.0f,pSpring,pSpring()) + DECLAREMETHOD_5(pFactory,pJointD6*,createD6Joint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,bool) + DECLAREMETHOD_2(pFactory,pJointFixed*,createFixedJoint,CK3dEntity*,CK3dEntity*) + DECLAREMETHOD_3_WITH_DEF_VALS(pFactory,pRigidBody*,createBody,CK3dEntity*,NODEFAULT,pObjectDescr,NODEFAULT,CK3dEntity*,NULL) + DECLAREMETHOD_6(pFactory,pJointPulley*,createPulleyJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointBall*,createBallJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointRevolute*,createRevoluteJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointPrismatic*,createPrismaticJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointCylindrical*,createCylindricalJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointPointInPlane*,createPointInPlaneJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + DECLAREMETHOD_4(pFactory,pJointPointOnLine*,createPointOnLineJoint,CK3dEntity*,CK3dEntity*,VxVector,VxVector) + + + + DECLAREMETHOD_2(pFactory,pCloth*,createCloth,CK3dEntity*,pClothDesc) + + + + ////////////////////////////////////////////////////////////////////////// + // + // Cloth + // + DECLAREMETHOD_4(pCloth,void,attachToCore,CK3dEntity*,float,float,float) + DECLAREMETHOD_2(pCloth,void,attachToShape,CK3dEntity*,pClothAttachmentFlag) + + + ////////////////////////////////////////////////////////////////////////// + // + // MANAGER + // + DECLAREFUN_C_0(CKGUID, GetPhysicManagerGUID) + DECLAREOBJECTTYPE(PhysicManager) + DECLARESTATIC_1(PhysicManager,PhysicManager*,Cast,CKBaseManager* iM) + DECLAREFUN_C_0(PhysicManager*, GetPhysicManager) + + DECLAREMETHOD_0(PhysicManager,pWorld*,getDefaultWorld) + DECLAREMETHOD_1(PhysicManager,pRigidBody*,getBody,CK3dEntity*) + DECLAREMETHOD_1(PhysicManager,pWorld*,getWorldByBody,CK3dEntity*) + DECLAREMETHOD_1(PhysicManager,pWorld*,getWorld,CK_ID) + DECLAREMETHOD_3_WITH_DEF_VALS(PhysicManager,pJoint*,getJoint,CK3dEntity*,NODEFAULT,CK3dEntity*,NULL,JType,JT_Any) + +// DECLAREMETHOD_0(PhysicManager,void,makeDongleTest) + + + ////////////////////////////////////////////////////////////////////////// + // + // World + // + + DECLAREMETHOD_1(pWorld,pRigidBody*,getBody,CK3dEntity*) + DECLAREMETHOD_1(pWorld,pVehicle*,getVehicle,CK3dEntity*) + DECLAREMETHOD_3(pWorld,pJoint*,getJoint,CK3dEntity*,CK3dEntity*,JType) + + DECLAREMETHOD_3(pWorld,void,setFilterOps,pFilterOp,pFilterOp,pFilterOp) + DECLAREMETHOD_1(pWorld,void,setFilterBool,bool) + DECLAREMETHOD_1(pWorld,void,setFilterConstant0,const pGroupsMask&) + DECLAREMETHOD_1(pWorld,void,setFilterConstant1,const pGroupsMask&) + + + + + // + DECLAREMETHOD_5_WITH_DEF_VALS(pWorld,bool,raycastAnyBounds,const VxRay&,NODEFAULT,pShapesType,NODEFAULT,pGroupsMask,NODEFAULT,int,0xffffffff,float,NX_MAX_F32) + DECLAREMETHOD_8(pWorld,bool,overlapSphereShapes,CK3dEntity*,const VxSphere&,CK3dEntity*,pShapesType,CKGroup*,int,const pGroupsMask*,BOOL) + + //(const VxRay& worldRay, pShapesType shapesType, pGroupsMask groupsMask,unsigned int groups=0xffffffff, float maxDist=NX_MAX_F32); + + + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT :: Revolute + // + DECLAREMETHOD_0(pJoint,pJointRevolute*,castRevolute) + DECLAREMETHOD_1(pJointRevolute,void,setGlobalAnchor,const VxVector&) + DECLAREMETHOD_1(pJointRevolute,void,setGlobalAxis,const VxVector&) + + + DECLAREMETHOD_1(pJointRevolute,void,setSpring,pSpring) + DECLAREMETHOD_1(pJointRevolute,void,setHighLimit,pJointLimit) + DECLAREMETHOD_1(pJointRevolute,void,setLowLimit,pJointLimit) + DECLAREMETHOD_1(pJointRevolute,void,setMotor,pMotor) + + DECLAREMETHOD_0(pJointRevolute,pSpring,getSpring) + DECLAREMETHOD_0(pJointRevolute,pJointLimit,getLowLimit) + DECLAREMETHOD_0(pJointRevolute,pJointLimit,getHighLimit) + DECLAREMETHOD_0(pJointRevolute,pMotor,getMotor) + DECLAREMETHOD_1(pJointRevolute,void,enableCollision,bool) + + + + + + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT :: Ball + // + DECLAREMETHOD_0(pJoint,pJointBall*,castBall) + + DECLAREMETHOD_1(pJointBall,void,setAnchor,VxVector) + + DECLAREMETHOD_1(pJointBall,void,setSwingLimitAxis,VxVector) + DECLAREMETHOD_1(pJointBall,bool,setSwingLimit,pJointLimit) + DECLAREMETHOD_1(pJointBall,bool,setTwistHighLimit,pJointLimit) + DECLAREMETHOD_1(pJointBall,bool,setTwistLowLimit,pJointLimit) + + + DECLAREMETHOD_0(pJointBall,pJointLimit,getSwingLimit) + DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistHighLimit) + DECLAREMETHOD_0(pJointBall,pJointLimit,getTwistLowLimit) + + DECLAREMETHOD_1(pJointBall,bool,setSwingSpring,pSpring) + DECLAREMETHOD_1(pJointBall,bool,setTwistSpring,pSpring) + DECLAREMETHOD_1(pJointBall,void,setJointSpring,pSpring) + + DECLAREMETHOD_0(pJointBall,pSpring,getSwingSpring) + DECLAREMETHOD_0(pJointBall,pSpring,getTwistSpring) + DECLAREMETHOD_0(pJointBall,pSpring,getJointSpring) + + DECLAREMETHOD_1(pJointBall,void,enableCollision,bool) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Prismatic + // + // + DECLAREMETHOD_0(pJoint,pJointPrismatic*,castPrismatic) + + DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointPrismatic,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointPrismatic,void,enableCollision,bool) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Cylindrical + // + // + DECLAREMETHOD_0(pJoint,pJointCylindrical*,castCylindrical) + + DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointCylindrical,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointCylindrical,void,enableCollision,int) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Point In Plane + // + // + DECLAREMETHOD_0(pJoint,pJointPointInPlane*,castPointInPlane) + + DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointPointInPlane,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointPointInPlane,void,enableCollision,bool) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT Point In Plane + // + // + DECLAREMETHOD_0(pJoint,pJointPointOnLine*,castPointOnLine) + + DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAnchor,VxVector) + DECLAREMETHOD_1(pJointPointOnLine,void,setGlobalAxis,VxVector) + DECLAREMETHOD_1(pJointPointOnLine,void,enableCollision,bool) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT BASE + // + // + DECLAREMETHOD_1(pJoint,void,setLocalAnchor0,VxVector) + + DECLAREMETHOD_2(pJoint,void,setBreakForces,float,float) + DECLAREMETHOD_2(pJoint,void,getBreakForces,float&,float&) + DECLAREMETHOD_3(pJoint,int,addLimitPlane,VxVector,VxVector,float) + DECLAREMETHOD_2_WITH_DEF_VALS(pJoint,void,setLimitPoint,VxVector,NODEFAULT,bool,true) + DECLAREMETHOD_0(pJoint,void,purgeLimitPlanes) + DECLAREMETHOD_0(pJoint,void,resetLimitPlaneIterator) + DECLAREMETHOD_0(pJoint,int,hasMoreLimitPlanes) + DECLAREMETHOD_3(pJoint,int,getNextLimitPlane,VxVector&,float&,float&) + DECLAREMETHOD_0(pJoint,int,getType) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT :: DISTANCE + // + DECLAREMETHOD_0(pJoint,pJointDistance*,castDistanceJoint) + + DECLAREMETHOD_1(pJointDistance,void,setMinDistance,float) + DECLAREMETHOD_1(pJointDistance,void,setMaxDistance,float) + DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor0,VxVector) + DECLAREMETHOD_1(pJointDistance,void,setLocalAnchor1,VxVector) + DECLAREMETHOD_1(pJointDistance,void,setSpring,pSpring) + DECLAREMETHOD_0(pJointDistance,float,getMinDistance) + DECLAREMETHOD_0(pJointDistance,float,getMaxDistance) + DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor0) + DECLAREMETHOD_0(pJointDistance,float,getLocalAnchor1) + DECLAREMETHOD_0(pJointDistance,pSpring,getSpring) + DECLAREMETHOD_1(pJointDistance,void,enableCollision,bool) + ////////////////////////////////////////////////////////////////////////// + // + // JOINT PULLEY + // + + DECLAREMETHOD_0(pJoint,pJointPulley*,castPulley) + + DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorA,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setLocalAnchorB,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setPulleyA,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setPulleyB,VxVector) + DECLAREMETHOD_1(pJointPulley,void,setStiffness,float) + DECLAREMETHOD_1(pJointPulley,void,setRatio,float) + DECLAREMETHOD_1(pJointPulley,void,setRigid,int) + DECLAREMETHOD_1(pJointPulley,void,setDistance,float) + DECLAREMETHOD_1(pJointPulley,void,setMotor,pMotor) + DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorA) + DECLAREMETHOD_0(pJointPulley,VxVector,getLocalAnchorB) + DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyA) + DECLAREMETHOD_0(pJointPulley,VxVector,getPulleyB) + DECLAREMETHOD_0(pJointPulley,float,getStiffness) + + DECLAREMETHOD_0(pJointPulley,float,getRatio) + DECLAREMETHOD_0(pJointPulley,float,getDistance) + DECLAREMETHOD_1(pJointPulley,void,enableCollision,bool) + DECLAREMETHOD_0(pJointPulley,pMotor,getMotor) + + ////////////////////////////////////////////////////////////////////////// + // + // JOINT D6 + // + + DECLAREMETHOD_0(pJoint,pJointD6*,castD6Joint) + + DECLAREMETHOD_1(pJointD6,void,setTwistMotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setSwing1MotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setSwing2MotionMode,D6MotionMode) + + DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) + + + DECLAREMETHOD_1(pJointD6,void,setXMotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setYMotionMode,D6MotionMode) + DECLAREMETHOD_1(pJointD6,void,setZMotionMode,D6MotionMode) + + DECLAREMETHOD_0(pJointD6,D6MotionMode,getXMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getYMotion) + DECLAREMETHOD_0(pJointD6,D6MotionMode,getZMotion) + + ////////////////////////////////////////////////////////////////////////// + //softwLimits + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getLinearLimit) + DECLAREMETHOD_1(pJointD6,int,setLinearLimit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing1Limit) + DECLAREMETHOD_1(pJointD6,int,setSwing1Limit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getSwing2Limit) + DECLAREMETHOD_1(pJointD6,int,setSwing2Limit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistHighLimit) + DECLAREMETHOD_1(pJointD6,int,setTwistHighLimit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6SoftLimit,getTwistLowLimit) + DECLAREMETHOD_1(pJointD6,int,setTwistLowLimit,pJD6SoftLimit) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getXDrive) + DECLAREMETHOD_1(pJointD6,int,setXDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getYDrive) + DECLAREMETHOD_1(pJointD6,int,setYDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getZDrive) + DECLAREMETHOD_1(pJointD6,int,setZDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getSwingDrive) + DECLAREMETHOD_1(pJointD6,int,setSwingDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getTwistDrive) + DECLAREMETHOD_1(pJointD6,int,setTwistDrive,pJD6Drive) + + DECLAREMETHOD_0(pJointD6,pJD6Drive,getSlerpDrive) + DECLAREMETHOD_1(pJointD6,int,setSlerpDrive,pJD6Drive) + + DECLAREMETHOD_1(pJointD6,void,setDrivePosition,VxVector) + DECLAREMETHOD_1(pJointD6,void,setDriveRotation,VxQuaternion) + + DECLAREMETHOD_1(pJointD6,void,setDriveLinearVelocity,VxVector) + DECLAREMETHOD_1(pJointD6,void,setDriveAngularVelocity,VxVector) + + DECLAREMETHOD_1(pJointD6,void,enableCollision,bool) + + + + + ////////////////////////////////////////////////////////////////////////// + // + // Rigid Body Exports + // + // + + + /************************************************************************/ + /* Forces */ + /************************************************************************/ + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addForce,const VxVector&,NODEFAULT, PForceMode, 0,bool,true) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addTorque,const VxVector&,NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalForce,const VxVector&,NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,void,addLocalTorque,const VxVector&,NODEFAULT, PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtPos, const VxVector&,NODEFAULT,const VxVector&,NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addForceAtLocalPos,const VxVector,NODEFAULT, const VxVector&, NODEFAULT,PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtPos, const VxVector&, NODEFAULT,const VxVector&,NODEFAULT, PForceMode,0,bool,true) + DECLAREMETHOD_4_WITH_DEF_VALS(pRigidBody,void,addLocalForceAtLocalPos, const VxVector&, NODEFAULT,const VxVector&, NODEFAULT,PForceMode,0,bool,true) + + + /************************************************************************/ + /* Momentum */ + /************************************************************************/ + DECLAREMETHOD_1(pRigidBody,void,setAngularMomentum,const VxVector&) + DECLAREMETHOD_1(pRigidBody,void,setLinearMomentum,const VxVector&) + DECLAREMETHOD_0(pRigidBody,VxVector,getAngularMomentum) + DECLAREMETHOD_0(pRigidBody,VxVector,getLinearMomentum) + + /************************************************************************/ + /* Pose : */ + /************************************************************************/ + DECLAREMETHOD_1(pRigidBody,void,setPosition,const VxVector&) + DECLAREMETHOD_1(pRigidBody,void,setRotation,const VxQuaternion&) + DECLAREMETHOD_1(pRigidBody,void,translateLocalShapePosition,VxVector) + + /************************************************************************/ + /* Velocity : */ + /************************************************************************/ + + DECLAREMETHOD_1(pRigidBody,void,setLinearVelocity,const VxVector&) + DECLAREMETHOD_1(pRigidBody,void,setAngularVelocity,const VxVector&) + DECLAREMETHOD_0(pRigidBody,float,getMaxAngularSpeed) + DECLAREMETHOD_0(pRigidBody,VxVector,getLinearVelocity) + DECLAREMETHOD_0(pRigidBody,VxVector,getAngularVelocity) + + /************************************************************************/ + /* Mass */ + /************************************************************************/ + + DECLAREMETHOD_1(pRigidBody,void,setMassOffset,VxVector) + DECLAREMETHOD_1(pRigidBody,void,setMaxAngularSpeed,float) + + /************************************************************************/ + /* Hull */ + /************************************************************************/ + DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) + + + DECLAREMETHOD_0(pRigidBody,pWorld*,getWorld) + DECLAREMETHOD_1(pRigidBody,pJoint*,isConnected,CK3dEntity*) + //DECLAREMETHOD_2_WITH_DEF_VALS(pRigidBody,void,setBoxDimensions,const VxVector&,NODEFAULT,CKBeObject*,NULL) + DECLAREMETHOD_1_WITH_DEF_VALS(pRigidBody,float,getMass,CK3dEntity*,NULL) + DECLAREMETHOD_0(pRigidBody,int,getHullType) + + DECLAREMETHOD_2(pRigidBody,void,setGroupsMask,CK3dEntity*,const pGroupsMask&) + + DECLAREMETHOD_0(pRigidBody,int,getFlags) + DECLAREMETHOD_1(pRigidBody,VxVector,getPointVelocity,VxVector) + DECLAREMETHOD_1(pRigidBody,VxVector,getLocalPointVelocity,VxVector) + + DECLAREMETHOD_1(pRigidBody,void,enableCollision,bool) + DECLAREMETHOD_0(pRigidBody,bool,isCollisionEnabled) + + DECLAREMETHOD_1(pRigidBody,void,setKinematic,int) + DECLAREMETHOD_0(pRigidBody,int,isKinematic) + + DECLAREMETHOD_1(pRigidBody,void,enableGravity,int) + DECLAREMETHOD_0(pRigidBody,bool,isAffectedByGravity) + + DECLAREMETHOD_1(pRigidBody,void,setSleeping,int) + DECLAREMETHOD_0(pRigidBody,int,isSleeping) + DECLAREMETHOD_1(pRigidBody,void,setLinearDamping,float) + DECLAREMETHOD_1(pRigidBody,void,setAngularDamping,float) + DECLAREMETHOD_1(pRigidBody,void,lockTransformation,BodyLockFlags) + DECLAREMETHOD_1(pRigidBody,int,isBodyFlagOn,int) + DECLAREMETHOD_1(pRigidBody,void,setSolverIterationCount,int) + + + + DECLAREMETHOD_1(pRigidBody,void,setCollisionsGroup,int) + DECLAREMETHOD_0(pRigidBody,int,getCollisionsGroup) + DECLAREMETHOD_2(pRigidBody,int,updateMassFromShapes,float,float) + DECLAREMETHOD_5_WITH_DEF_VALS(pRigidBody,int,addSubShape,CKMesh*,NULL,pObjectDescr,NODEFAULT,CK3dEntity*,NULL,VxVector,VxVector(),VxQuaternion,VxQuaternion()) + DECLAREMETHOD_3_WITH_DEF_VALS(pRigidBody,int,removeSubShape,CKMesh*,NODEFAULT,float,0.0,float,0.0) + + + + + /* + DECLAREENUM("WORLD_UPDATE_MODE") + DECLAREENUMVALUE("WORLD_UPDATE_MODE", "WUM_UPDATE_FROM_ATTRIBUTE" , 0x0001) + + DECLAREENUM("WORLD_UPDATE_FLAGS") + DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_WORLD_SETTINGS" , 0x0001) + DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_DAMPING_PARAMETER" , 0x0002) + DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_SLEEPING_PARAMETER" , 0x0004) + DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_SURFACE_SETTINGS" , 0x0008) + DECLAREENUMVALUE("WORLD_UPDATE_FLAGS", "WUF_ALL_PARAMETERS" , 0x0010) + + DECLAREENUM("BODY_UPDATE_FLAGS") + + DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_PHY_PARAMETER" , 0x0001) + DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_DAMPING_PARAMETER" , 0x0002) + DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_SLEEPING_PARAMETER" , 0x0004) + DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_JOINT_PARAMETERS" , 0x0008) + DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_ALL_PARAMETERS" , 0x0010) + DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_GEOMETRY" , 0x0020) + DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_PIVOT" , 0x0040) + DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_MASS" , 0x0080) + DECLAREENUMVALUE("BODY_UPDATE_FLAGS", "BUF_ALL" , 0x0100) + + + + + + DECLAREENUM("JType") + DECLAREENUMVALUE("JType", "JT_NONE" , 0) + DECLAREENUMVALUE("JType", "JT_BALL" , 1) + DECLAREENUMVALUE("JType", "JT_HINGE" , 2) + DECLAREENUMVALUE("JType", "JT_SLIDER" , 3) + DECLAREENUMVALUE("JType", "JT_CONTACT" , 4) + DECLAREENUMVALUE("JType", "JT_UNIVERSAL" , 5) + DECLAREENUMVALUE("JType", "JT_HINGE2" , 6) + DECLAREENUMVALUE("JType", "JT_FIXED" , 7) + DECLAREENUMVALUE("JType", "JT_MOTOR" ,8 ) + + + + + + + DECLAREENUM("J_LIMITPARAMETER"); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JLoStop" , 0); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JHiStop", 1); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JVel" , 2); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JFMax" , 3); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JFudgeFactor" , 4); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JBounce" , 5); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JCFM" , 6); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JStopERP" , 7); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JStopCFM" , 8); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JSuspensionERP" , 9); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JSuspensionCFM" , 10); + DECLAREENUMVALUE("J_LIMITPARAMETER", "JERP" , 11); + + DECLAREENUM("J_MOTOR_AXIS_TYPE") + DECLAREENUMVALUE("J_MOTOR_AXIS_TYPE", "AXIS_GLOBAL_FRAME" , 0) + DECLAREENUMVALUE("J_MOTOR_AXIS_TYPE", "AXIS_FIRST_BODY" , 1) + DECLAREENUMVALUE("J_MOTOR_AXIS_TYPE", "AXIS_SECOND_BODY" , 2) +*/ + +/* + DECLAREOBJECTTYPE(pSleepingSettings) + DECLARECTOR_0(__newvtSleepingSettings) + + DECLAREMETHODC_0(pSleepingSettings,int,SleepSteps) + DECLAREMETHOD_1(pSleepingSettings,void,SleepSteps,int) + DECLAREMETHODC_0(pSleepingSettings,float,AngularThresold) + DECLAREMETHOD_1(pSleepingSettings,void,AngularThresold,float) + DECLAREMETHODC_0(pSleepingSettings,float,LinearThresold) + DECLAREMETHOD_1(pSleepingSettings,void,LinearThresold,float) + DECLAREMETHODC_0(pSleepingSettings,int,AutoSleepFlag) + DECLAREMETHOD_1(pSleepingSettings,void,AutoSleepFlag,int) + + + DECLAREOBJECTTYPE(pWorldSettings) + DECLARECTOR_0(__newvtWorldSettings) + DECLAREMETHODC_0(pWorldSettings,VxVector,Gravity) + DECLAREMETHOD_1(pWorldSettings,void,Gravity,VxVector) + DECLAREMETHODC_0(pWorldSettings,float,ContactSurfaceLayer) + DECLAREMETHOD_1(pWorldSettings,void,ContactSurfaceLayer,float) + DECLAREMETHODC_0(pWorldSettings,float,ERP) + DECLAREMETHOD_1(pWorldSettings,void,ERP,float) + DECLAREMETHODC_0(pWorldSettings,float,CFM) + DECLAREMETHOD_1(pWorldSettings,void,CFM,float) + DECLAREMETHODC_0(pWorldSettings,float,MaximumContactCorrectVelocity) + DECLAREMETHOD_1(pWorldSettings,void,MaximumContactCorrectVelocity,float) + + DECLAREOBJECTTYPE(pJointSettings) + DECLARECTOR_0(__newvtJointSettings) + + + + + + + DECLAREFUN_C_1(int,TestWS,pWorldSettings) + + + DECLAREMETHODC_0(pWorld,pSleepingSettings*,SleepingSettings) + DECLAREMETHOD_1(pWorld,void,SleepingSettings,pSleepingSettings*) + + DECLAREMETHODC_0(pWorld,pWorldSettings*,WorldSettings) + DECLAREMETHOD_1(pWorld,void,WorldSettings,pWorldSettings*) + DECLAREMETHOD_0(pWorld,int,NumJoints) +*/ + ////////////////////////////////////////////////////////////////////////// + //collision + +/* + DECLAREMETHOD_0(pRigidBody,float,GetFriction) + DECLAREMETHOD_1(pRigidBody,void,SetFriction,float) + DECLAREMETHOD_1(pRigidBody,void,SetPosition,VxVector) + DECLAREMETHOD_1(pRigidBody,void,SetQuaternion, VxQuaternion) + DECLAREMETHOD_0(pRigidBody,VxBbox,GetAABB) + + + DECLAREMETHOD_0(pRigidBody,float,GetLastHFHeight) + DECLAREMETHOD_0(pRigidBody,int,GetLastHFColor) + DECLAREMETHOD_0(pRigidBody,Vx2DVector,GetLastHCoord) +*/ + + // Velocity : + //DECLAREMETHOD_1(pRigidBody,void,setLinearVel,VxVector) + //DECLAREMETHOD_1(pRigidBody,void,setAngularVel, VxVector) + + /* + //DECLAREMETHOD_0(pRigidBody,VxVector,GetLinearVel) + //DECLAREMETHOD_0(pRigidBody,VxVector,GetAngularVel) + // Forces : + */ + + //DECLAREMETHOD_2(pRigidBody,void,addForce, VxVector , PForceMode ) + + + + + + + + + ////////////////////////////////////////////////////////////////////////// + //rotation axis : + + /* + + + + + DECLAREMETHOD_2(pFactory,pWorldSettings*,CreateWorldSettings,const char *,const char*) + DECLAREMETHOD_2_WITH_DEF_VALS(pFactory,pWorldSettings*,CreateWorldSettings,const char *,"Default",const char*,"PhysicDefaults.xml") + + DECLAREMETHOD_2(pFactory,pSleepingSettings*,CreateSleepingSettings,const char *,const char*) + + ////////////////////////////////////////////////////////////////////////// + //world : + DECLAREMETHOD_3(pFactory,pWorld*,CreateWorld,CK3dEntity*,pWorldSettings*,pSleepingSettings*) + + + ////////////////////////////////////////////////////////////////////////// + //bodies : + DECLAREMETHOD_3(pFactory,pRigidBody*,CreateRigidBody,CK3dEntity*,pWorld*,pSleepingSettings*) + DECLAREMETHOD_3(pFactory,pRigidBody*,CreateRigidBody,CK3dEntity*,CK3dEntity*,pSleepingSettings*) + + DECLAREMETHOD_3_WITH_DEF_VALS(pFactory,pRigidBody*,CreateBall,CK3dEntity*,NULL,CK3dEntity*,NULL,pSleepingSettings*,NULL) + DECLAREMETHOD_3(pFactory,pRigidBody*,CreateRigidBodyFull,CK3dEntity*,pWorld*,pSleepingSettings*) + DECLAREMETHOD_8_WITH_DEF_VALS(pFactory,pRigidBody*,CreateBody,CK3dEntity*,NULL,CK3dEntity*,NULL,pSleepingSettings*,NULL,int,(BodyFlags)(BF_MOVING|BF_P2V|BF_WORLD_GRAVITY|BF_ENABLED|BF_COLLISION),int,HT_BOX,float,1.0f,float,0.0f,float,1.0f) + + + ////////////////////////////////////////////////////////////////////////// + //joint + + DECLAREMETHOD_2(pRigidBody,pJoint*,IsConnected, CK3dEntity*,int) + + ////////////////////////////////////////////////////////////////////////// + //collision : + + DECLAREMETHOD_4(pWorld,CK3dEntity*,CIsInCollision,CK3dEntity*,VxVector&,VxVector&,float&) + DECLAREMETHOD_5(pWorld,CK3dEntity*,CIsInCollision,CK3dEntity*,CKGroup*,VxVector&,VxVector&,float&) + DECLAREMETHOD_5(pWorld,bool,CIsInCollision,CK3dEntity*,CK3dEntity*,VxVector&,VxVector&,float&) + DECLAREMETHOD_8(pWorld,CK3dEntity*,CRayCollision,VxVector ,CK3dEntity*,VxVector,CK3dEntity*,float,bool,VxVector&, VxVector&) + DECLAREMETHOD_2(pWorld,int,CIsInCollision,CK3dEntity*,CK3dEntity*) + + // DECLAREMETHOD_7(PhysicManager,int,CTestRayCollision,CKGroup*,VxVector,VxVector,float,VxVector*,VxVector*,CK3dEntity**) + + + + + +*/ + + + + /* + + DECLAREMETHODC_0(PhysicManager,pWorldSettings,DefaultWorldSettings) + DECLAREMETHOD_1(PhysicManager,void,DefaultWorldSettings,pWorldSettings) + + DECLAREMETHODC_0(PhysicManager,pSleepingSettings,DefaultSleepingSettings) + DECLAREMETHOD_1(PhysicManager,void,DefaultSleepingSettings,pSleepingSettings) + + DECLAREMETHOD_0(PhysicManager,void,CheckWorlds) + DECLARESTATIC_0(pWorld,pWorld*,GetDefault) + */ + + + + STOPVSLBIND + + +} + + +PhysicManager*GetPhysicManager() +{ + return GetPMan(); +} + +/* +void __newvtWorldSettings(BYTE *iAdd) +{ +new (iAdd) pWorldSettings(); +} +void __newvtSleepingSettings(BYTE *iAdd) +{ +new (iAdd) pSleepingSettings(); +} +void __newvtJointSettings(BYTE *iAdd) +{ +new (iAdd) pJointSettings(); +} + + +int TestWS(pWorldSettings pWS) +{ +VxVector grav = pWS.Gravity(); +return 2; +} + +pFactory* GetPFactory(); + + +pFactory* GetPFactory() +{ +return pFactory::Instance(); +} + + +extern pRigidBody*getBody(CK3dEntity*ent); +*/ \ No newline at end of file diff --git a/usr/Src/old/PhysicManagerVTRigidBody.cpp b/usr/Src/old/PhysicManagerVTRigidBody.cpp new file mode 100644 index 0000000..a5c427a --- /dev/null +++ b/usr/Src/old/PhysicManagerVTRigidBody.cpp @@ -0,0 +1,76 @@ +#include +#include "vtPhysXAll.h" +#include "VSLManagerSDK.h" + +//#include "pVehicle.h" + + + + +PhysicManager *ourMan = NULL; + +CKGUID GetPhysicManagerGUID() { return GUID_MODULE_MANAGER;} + +typedef ForceMode PForceMode; +typedef D6MotionMode PJMotion; +typedef D6DriveType PDriveType; +typedef int BodyLockFlags; +////////////////////////////////////////////////////////////////////////// + +#define TESTGUID CKGUID(0x2c5c47f6,0x1d0755d9) + + +void PhysicManager::_RegisterVSLRigidBody() +{ + + + + STARTVSLBIND(m_Context) + + + + + + STOPVSLBIND + + +} + + +PhysicManager*GetPhysicManager() +{ + return GetPMan(); +} + +/* +void __newvtWorldSettings(BYTE *iAdd) +{ +new (iAdd) pWorldSettings(); +} +void __newvtSleepingSettings(BYTE *iAdd) +{ +new (iAdd) pSleepingSettings(); +} +void __newvtJointSettings(BYTE *iAdd) +{ +new (iAdd) pJointSettings(); +} + + +int TestWS(pWorldSettings pWS) +{ +VxVector grav = pWS.Gravity(); +return 2; +} + +pFactory* GetPFactory(); + + +pFactory* GetPFactory() +{ +return pFactory::Instance(); +} + + +extern pRigidBody*getBody(CK3dEntity*ent); +*/ \ No newline at end of file diff --git a/usr/Src/old/pVehicle/pVTireFunction.cpp b/usr/Src/old/pVehicle/pVTireFunction.cpp new file mode 100644 index 0000000..b0143b6 --- /dev/null +++ b/usr/Src/old/pVehicle/pVTireFunction.cpp @@ -0,0 +1,88 @@ +#include +#include "vtPhysXAll.h" + +#include "pVTireFunction.h" + + pTireFunction::pTireFunction() +{ + setToDefault(); +} + + void pTireFunction::setToDefault() +{ + extremumSlip = 1.0f; + extremumValue = 0.02f; + asymptoteSlip = 2.0f; + asymptoteValue = 0.01f; + stiffnessFactor = 1000000.0f; //quite stiff by default. + xmlLink =0; + +} + + bool pTireFunction::isValid() const +{ + if(!(0.0f < extremumSlip)) return false; + if(!(extremumSlip < asymptoteSlip)) return false; + if(!(0.0f < extremumValue)) return false; + if(!(0.0f < asymptoteValue)) return false; + if(!(0.0f <= stiffnessFactor)) return false; + + return true; +} + + + float pTireFunction::hermiteEval(float t) const +{ + + // This fix for TTP 3429 & 3675 is from Sega. + // Assume blending functions (look these up in a graph): + // H0(t) = 2ttt - 3tt + 1 + // H1(t) = -2ttt + 3tt + // H2(t) = ttt - 2tt + t + // H3(t) = ttt - tt + + float v = NxMath::abs(t); + float s = (t>=0) ? 1.0f : -1.0f; + + float F; + + if(v +#include "vtPhysXAll.h" + +#include "pVehicleMotor.h" +#include "pVehicleGears.h" + +#include +#include "NxArray.h" + +enum VehicleStatus +{ + + VS_IsMoving=(1<<0), + VS_IsAccelerated=(1<<1), + VS_IsAcceleratedForward=(1<<2), + VS_IsAcceleratedBackward=(1<<3), + VS_AllWheelsOnGround=(1<<4), + VS_Handbrake=(1<<5), + VS_IsBraking=(1<<6), + +}; + +int pVehicle::_calculateCurrentStatus(){ + + int result = 0; + + //---------------------------------------------------------------- + // + // is moving ? + // + { + _computeLocalVelocity(); + if ( NxMath::abs(_localVelocity.z) > 0.1f) + result |=VS_IsMoving; + } + + //---------------------------------------------------------------- + // + // is accelerated ? + // + { + if ( _cAcceleration > 0.1f ) + result |=VS_IsAcceleratedForward; + + if ( _cAcceleration < 0.0f ) + result |=VS_IsAcceleratedBackward; + + if ( (result & VS_IsAcceleratedForward) || (result & VS_IsAcceleratedBackward) ) + result |=VS_IsAccelerated; + } + + //---------------------------------------------------------------- + // + // is falling + handbrake + // + { + _nbNotTouching =0; + _nbTouching =0; + _nbHandbrakeOn =0; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if (!wheel->hasGroundContact()) + { + _nbNotTouching++; + } else { + _nbTouching++; + } + + if(_cHandbrake && wheel->getWheelFlag(WF_AffectedByHandbrake)) + { + _nbHandbrakeOn++; + } + } + if (_nbTouching == _wheels.size()) + result |= VS_AllWheelsOnGround; + + if (_cHandbrake && _nbHandbrakeOn ) + { + result|=VS_Handbrake; + } + } + + + + return NULL; +} + +void pVehicle::_controlAcceleration(float acceleration, bool analogAcceleration) +{ + if(NxMath::abs(acceleration) < 0.001f) + { + _releaseBraking = true; + //xInfo("set release breaking = true"); + } + + if(!_braking) + { + _accelerationPedal = NxMath::clamp(acceleration, 1.f, -1.f); + _brakePedalChanged = _brakePedal == 0; + _brakePedal = 0; + //xInfo("breaking = false : clamp accPedal 1|-1"); + } else { + //xInfo("breaking = true : accPeal = 0"); + _accelerationPedal = 0; + NxReal newv = NxMath::clamp(NxMath::abs(acceleration), 1.f, 0.f); + _brakePedalChanged = _brakePedal == newv; + _brakePedal = newv; + } + char master[512]; + sprintf(master,"Acceleration: %2.3f, Braking %2.3f\n", _accelerationPedal, _brakePedal); + xInfo(master); + //OutputDebugString(master); + + +} +void pVehicle::control(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) +{ + + if (steering != 0 || acceleration != 0 || handBrake) + getActor()->wakeUp(0.05); + + _controlSteering(steering, analogSteering); + _computeLocalVelocity(); + + NxVec3 locVel = _localVelocity; + float lcx = locVel.x; + float lcz = locVel.z; + + + float test = _localVelocity.z * acceleration < ( NxMath::sign(-acceleration) ); + float test2 = _localVelocity.z * acceleration < ( -0.1f ); + float test3 = XAbs(_localVelocity.z) * acceleration < ( -0.1f ); + + + if (!_braking || _releaseBraking) + { + //_braking = _localVelocity.x * acceleration < (-0.1f /** NxMath::sign(-acceleration) */); + _braking = _localVelocity.z * acceleration < ( -0.1 /*NxMath::sign(acceleration) */ ); + + //_braking = _localVelocity.z * acceleration < ( NxMath::sign(acceleration)); + _releaseBraking = false; + } + + if(_handBrake != handBrake) + { + _handBrake = handBrake; + _brakePedalChanged; + } + //printf("Braking: %s, Handbrake: %s\n", _braking?"true":"false", handBrake?"true":"false"); + _controlAcceleration(acceleration, analogAcceleration); +} + + +void pVehicle::updateVehicle( float lastTimeStepSize ) +{ + + control(_cSteering,_cAnalogSteering,_cAcceleration,_cAnalogAcceleration,_cHandbrake); + //printf("updating %x\n", this); + + NxReal distanceSteeringAxisCarTurnAxis = _steeringSteerPoint.x - _steeringTurnPoint.x; + NX_ASSERT(_steeringSteerPoint.z == _steeringTurnPoint.z); + NxReal distance2 = 0; + if (NxMath::abs(_steeringWheelState) > 0.01f) + distance2 = distanceSteeringAxisCarTurnAxis / NxMath::tan(_steeringWheelState * _steeringMaxAngleRad); + + NxU32 nbTouching = 0; + NxU32 nbNotTouching = 0; + NxU32 nbHandBrake = 0; + int wSize = _wheels.size(); + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_SteerableInput)) + { + if(distance2 != 0) + { + NxReal xPos = wheel->getWheelPos().x; + NxReal xPos2 = _steeringSteerPoint.x- wheel->getWheelPos().x; + NxReal zPos = wheel->getWheelPos().z; + NxReal dz = -zPos + distance2; + NxReal dx = xPos - _steeringTurnPoint.x; + float atan3 = NxMath::atan(dx/dz); + + float angle =(NxMath::atan(dx/dz)); + if (dx < 0.0f) + { + angle*=-1.0f; + } + wheel->setAngle(angle); + //errMessage.Format("w%d dz:%f dx:%f dx2%f distance:%f atan3:%f",i,dz,dx,xPos2,distance2,atan3); + //xInfo(errMessage.Str()); + + + } else { + wheel->setAngle(0.0f); + } + //printf("%2.3f\n", wheel->getAngle()); + + } else if(wheel->getWheelFlag(WF_SteerableAuto)) + { + NxVec3 localVelocity = getActor()->getLocalPointVelocity(getFrom(wheel->getWheelPos())); + NxQuat local2Global = getActor()->getGlobalOrientationQuat(); + local2Global.inverseRotate(localVelocity); + // printf("%2.3f %2.3f %2.3f\n", wheel->getWheelPos().x,wheel->getWheelPos().y,wheel->getWheelPos().z); + localVelocity.y = 0; + if(localVelocity.magnitudeSquared() < 0.1f) + { + wheel->setAngle(0.0f); + } else { + localVelocity.normalize(); + // printf("localVelocity: %2.3f %2.3f\n", localVelocity.x, localVelocity.z); + if(localVelocity.x < 0) + localVelocity = -localVelocity; + NxReal angle = NxMath::clamp((NxReal)atan(localVelocity.z / localVelocity.x), 0.3f, -0.3f); + wheel->setAngle(angle); + } + } + + // now the acceleration part + if(!wheel->getWheelFlag(WF_Accelerated)) + continue; + + if(_handBrake && wheel->getWheelFlag(WF_AffectedByHandbrake)) + { + nbHandBrake++; + } + else + { + if (!wheel->hasGroundContact()) + { + nbNotTouching++; + } else { + nbTouching++; + } + } + } + + NxReal motorTorque = 0.0; + float _acc = NxMath::abs(_accelerationPedal); + + XString errMessage; + if (!nbTouching) + { + + /* + errMessage.Format("wheels in air ? : %d",nbTouching); + xInfo(errMessage.Str()); + */ + } + + if(nbTouching && NxMath::abs(_accelerationPedal) > 0.1f ) + { + NxReal axisTorque = _computeAxisTorque(); + NxReal wheelTorque = axisTorque / (NxReal)(_wheels.size() - nbHandBrake); + NxReal wheelTorqueNotTouching = nbNotTouching>0?wheelTorque*(NxMath::pow(0.5f, (NxReal)nbNotTouching)):0; + NxReal wheelTorqueTouching = wheelTorque - wheelTorqueNotTouching; + motorTorque = wheelTorqueTouching / (NxReal)nbTouching; + } else { + _updateRpms(); + } + + + if ( (NxMath::abs(_accelerationPedal) > 0.1f) && motorTorque == 0.0f) + { + + } + + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + wheel->tick(_handBrake, motorTorque, _brakePedal, lastTimeStepSize); + //wheel->tick(_handBrake, motorTorque, _brakePedal, 1/60); + } + + + int flags =0; + + flags = 0; + + + if (_brakePedal) + { + flags |= E_VSF_IS_BREAKPEDAL; + } + + if (_braking) + { + flags |= E_VSF_IS_BRAKING; + } + + if (_releaseBraking) + { + flags |= E_VSF_RELEASING_BRAKE_PEDAL; + } + + if (_accelerationPedal > 0.01f ) + { + flags |= E_VSF_ACC_PEDAL; + } + + + if (nbTouching) + { + flags |= E_VSF_HAS_GROUND; + } + + if (getMotor()) + { + flags |= E_VSF_HAS_MOTOR; + } + + if (getGears()) + { + flags |= E_VSF_HAS_GEARS; + } + + if (_brakePedalChanged) + { + flags |= E_VSF_BREAKPEDAL_CHANGED; + } + + if (_cHandbrake) + { + flags |= E_VCS_HANDBRAKE; + } + + if ( (flags & E_VSF_BREAKPEDAL_CHANGED) && + (flags & E_VSF_IS_BREAKPEDAL) && + (NxMath::abs(_cAcceleration)>0.01f ) && + (!_cHandbrake) + ) + { + _braking = false; + } + + if (_cHandbrake) + { + _braking = true; + } + + + + setVSFlags(flags); + +} + + +pWheel*pVehicle::getWheel(CK3dEntity *wheelReference) +{ + + if (!wheelReference) + { + return NULL; + } + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if (wheel->getEntID() == wheelReference->GetID()) + { + return wheel; + } + } + return NULL; +} +void pVehicle::handleContactPair(NxContactPair* pair, int carIndex) +{ + NxContactStreamIterator i(pair->stream); + + while(i.goNextPair()) + { + NxShape * s = i.getShape(carIndex); + + while(i.goNextPatch()) + { + const NxVec3& contactNormal = i.getPatchNormal(); + + while(i.goNextPoint()) + { + //user can also call getPoint() and getSeparation() here + + const NxVec3& contactPoint = i.getPoint(); + + //add forces: + + //assuming front wheel drive we need to apply a force at the wheels. + if (s->is(NX_SHAPE_CAPSULE) && s->userData != NULL) { + //assuming only the wheels of the car are capsules, otherwise we need more checks. + //this branch can't be pulled out of loops because we have to do a full iteration through the stream + + + NxQuat local2global = s->getActor().getGlobalOrientationQuat(); + /* + NxWheel* w = (NxWheel*)s->userData; + if (!w->getWheelFlag(E_WF_USE_WHEELSHAPE)) + { + NxWheel1 * wheel = static_cast(w); + wheel->contactInfo.otherActor = pair.actors[1-carIndex]; + wheel->contactInfo.contactPosition = contactPoint; + + wheel->contactInfo.contactPositionLocal = contactPoint; + wheel->contactInfo.contactPositionLocal -= _bodyActor->getGlobalPosition(); + local2global.inverseRotate(wheel->contactInfo.contactPositionLocal); + + wheel->contactInfo.contactNormal = contactNormal; + if (wheel->contactInfo.otherActor->isDynamic()) + { + NxVec3 globalV = s->getActor().getLocalPointVelocity(wheel->getWheelPos()); + globalV -= wheel->contactInfo.otherActor->getLinearVelocity(); + local2global.inverseRotate(globalV); + wheel->contactInfo.relativeVelocity = globalV.x; + //printf("%2.3f (%2.3f %2.3f %2.3f)\n", wheel->contactInfo.relativeVelocity, + // globalV.x, globalV.y, globalV.z); + } + else + { + NxVec3 vel = s->getActor().getLocalPointVelocity(wheel->getWheelPos()); + local2global.inverseRotate(vel); + wheel->contactInfo.relativeVelocity = vel.x; + wheel->contactInfo.relativeVelocitySide = vel.z; + } + NX_ASSERT(wheel->hasGroundContact()); + //printf(" Wheel %x is touching\n", wheel); + } + */ + } + } + } + } + //printf("----\n"); +} +float pVehicle::_computeAxisTorque() +{ + if(_vehicleMotor != NULL) + { + NxReal rpm = _computeRpmFromWheels(); + NxReal motorRpm = _computeMotorRpm(rpm); + _vehicleMotor->setRpm(motorRpm); + NxReal torque = _accelerationPedal * _vehicleMotor->getTorque(); + NxReal v = getActor()->getLinearVelocity().magnitude(); + //printf("v: %2.3f m/s (%2.3f km/h)\n", v, v*3.6f); + //printf("rpm %2.3f, motorrpm %2.3f, torque %2.3f, realtorque %2.3f\n", + // rpm, motorRpm, torque, torque*_getGearRatio()*_differentialRatio*_transmissionEfficiency); + return torque * _getGearRatio() * _differentialRatio * _transmissionEfficiency; + } else { + _computeRpmFromWheels(); + return _accelerationPedal * _motorForce; + } +} +float pVehicle::_computeRpmFromWheels() +{ + NxReal wheelRpms = 0; + NxI32 nbWheels = 0; + + int s = _wheels.size(); + + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if (wheel->getWheelFlag(WF_Accelerated)) + { + nbWheels++; + wheelRpms += wheel->getRpm(); + } + + + } + return wheelRpms / (NxReal)nbWheels; +} + + +float pVehicle::_getGearRatio() +{ + if(_vehicleGears == NULL) + { + return 1; + } else { + return _vehicleGears->getCurrentRatio(); + } +} +void pVehicle::gearUp() +{ + if (_vehicleGears) + { + printf("Changing gear from %d to", _vehicleGears->getGear()); + _vehicleGears->gearUp(); + printf(" %d\n", _vehicleGears->getGear()); + } else { + printf("gearUp not supported if no gears available\n"); + } +} +void pVehicle::gearDown() +{ + if(_vehicleGears) + { + printf("Changing gear from %d to", _vehicleGears->getGear()); + _vehicleGears->gearDown(); + printf(" %d\n", _vehicleGears->getGear()); + } else { + printf("gearDown not supported if no gears available\n"); + } +} + +float pVehicle::_computeMotorRpm(float rpm) +{ + NxReal temp = _getGearRatio() * _differentialRatio; + NxReal motorRpm = rpm * temp; + NxI32 change = -1; +/* if(_vehicleMotor) + { + if(_vehicleGears && mAutomaticMode ) + { + */ + if(_vehicleMotor) + { + NxI32 change; + if(_vehicleGears && (change = _vehicleMotor->changeGears(_vehicleGears, 0.2f))) + { + change = _vehicleMotor->changeGears(_vehicleGears, 0.2f); + if(change == 1 && mAutomaticMode ) + { + gearUp(); + } else { + NX_ASSERT(change == -1); + gearDown(); + } + } + temp = _getGearRatio() * _differentialRatio; + motorRpm = NxMath::max(rpm * temp, _vehicleMotor->getMinRpm()); + } + return motorRpm; +} +void pVehicle::_updateRpms() +{ + NxReal rpm = _computeRpmFromWheels(); + if(_vehicleMotor != NULL) + { + NxReal motorRpm = _computeMotorRpm(rpm); + _vehicleMotor->setRpm(motorRpm); + } +} +NxActor* pVehicle::getActor(){ return mActor; } + + + +float pVehicle::getDriveVelocity() +{ + return NxMath::abs(_localVelocity.x); +} + +const pWheel*pVehicle::getWheel(int i) +{ + NX_ASSERT(i < _wheels.size()); + return _wheels[i]; + +} + + +float pVehicle::getMPH(int type) +{ + + int nbAWheels =0; + float radius = 0.0; + float axleSpeed = 0.0; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + pWheel* wheel = _wheels[i]; + if(wheel->getWheelFlag(WF_Accelerated)) + { + nbAWheels++; + if (wheel->getRadius() > radius) + radius = wheel->getRadius(); + + pWheel2* w2 = (pWheel2*)wheel; + if (w2->getWheelShape()->getAxleSpeed() > axleSpeed) + { + axleSpeed = w2->getWheelShape()->getAxleSpeed(); + } + } + } + + + // ( X * 10 * 60) / (5280* 12) * 100 = X * 0.9469696 + //return (-((10 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed() * 60) / (5280 * 12)) * 100); + return -0.9469696 * radius * NxPi * axleSpeed; + +} + +// ( X * 10 * 60) / (5280* 12) * 100 = X * 0.9469696 +//return (-((10 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed() * 60) / (5280 * 12)) * 100); +//return -0.9469696 * GetWheelSizeWidth() * NxPi * mOurWheels[BACK_LEFT]->getAxleSpeed(); + + +void pVehicle::_computeLocalVelocity() +{ + _computeMostTouchedActor(); + NxVec3 relativeVelocity; + if (_mostTouchedActor == NULL || !_mostTouchedActor->isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - _mostTouchedActor->getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + NxQuat global2Local; + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + char master[512]; + + //sprintf(master,"Velocity: %2.3f %2.3f %2.3f\n", _localVelocity.x, _localVelocity.y, _localVelocity.z); + //OutputDebugString(master); +} +void pVehicle::_controlSteering(float steering, bool analogSteering) +{ + if(analogSteering) + { + _steeringWheelState = steering; + } else if (NxMath::abs(steering) > 0.0001f) { + _steeringWheelState += NxMath::sign(steering) * _digitalSteeringDelta; + } else if (NxMath::abs(_steeringWheelState) > 0.0001f) { + _steeringWheelState -= NxMath::sign(_steeringWheelState) * _digitalSteeringDelta; + } + _steeringWheelState = NxMath::clamp(_steeringWheelState, 1.f, -1.f); + //printf("SteeringWheelState: %2.3f\n", _steeringWheelState); +} + +void pVehicle::_computeMostTouchedActor() +{ + std::map actors; + typedef std::map Map; + for(NxU32 i = 0; i < _wheels.size(); i++) + { + NxActor* curActor = _wheels[i]->getTouchedActor(); + Map::iterator it = actors.find(curActor); + if (it == actors.end()) + { + actors[curActor] = 1; + } else { + it->second++; + } + } + + NxU32 count = 0; + _mostTouchedActor = NULL; + for(Map::iterator it = actors.begin(); it != actors.end(); ++it) + { + if(it->second > count) + { + count = it->second; + _mostTouchedActor = it->first; + } + } +} + + +int pVehicle::initWheels(int flags) +{ + + getWheels().clear(); + int nbShapes = getActor()->getNbShapes(); + NxShape ** slist = (NxShape **)getActor()->getShapes(); + for (NxU32 j=0; j(s->userData); + if (sinfo && sinfo->wheel !=NULL) + { + pWheel *wheel = sinfo->wheel; + pWheel2* wheel2 = (pWheel2*)wheel; + NxWheelShape *wShape = wheel2->getWheelShape(); + if (!wShape) continue; + + if (wheel2->getWheelFlag(WF_VehicleControlled) ) + { + getWheels().push_back(wheel); + } + } + } + } + + return getWheels().size(); + + + /* + int result = 0 ; + + if (!getBody() || !getBody()->isValid() ) + { + return result; + } + + getWheels().clear(); + + + CK3dEntity* subEntity = NULL; + while (subEntity= getBody()->GetVT3DObject()->HierarchyParser(subEntity) ) + { + if (subEntity->HasAttribute(GetPMan()->GetPAttribute())) + { + pObjectDescr *subDescr = pFactory::Instance()->createPObjectDescrFromParameter(subEntity->GetAttributeParameter(GetPMan()->GetPAttribute())); + if (subDescr->flags & BF_SubShape) + { + if (subDescr->hullType == HT_Wheel) + { + + if (subEntity->HasAttribute(GetPMan()->att_wheelDescr )) + { + CKParameter *par = subEntity->GetAttributeParameter(GetPMan()->att_wheelDescr ); + if (par) + { + pWheelDescr *wDescr = pFactory::Instance()->createWheelDescrFromParameter(par); + if (wDescr) + { + pWheel *wheel = pFactory::Instance()->createWheel(getBody(),*wDescr); + if (wheel) + { + NxWheelShape *wShape = static_cast(getBody()->_getSubShapeByEntityID(subEntity->GetID())); + + if(wDescr->wheelFlags & E_WF_USE_WHEELSHAPE) + { + pWheel2 *wheel2 = static_cast(wheel); + if (wheel2) + { + if(wShape) + wheel2->setWheelShape(wShape); + + } + } + wheel->setEntID(subEntity->GetID()); + getWheels().push_back(wheel); +// subEntity->SetParent(NULL); + + } + } + } + } + } + } + } + } + + + + return getWheels().size(); + */ +} + +pVehicle::pVehicle() +{ + +} +void pVehicle::setControlState(float steering, bool analogSteering, float acceleration, bool analogAcceleration, bool handBrake) +{ + _cAcceleration = acceleration; + _cSteering = steering; + + _cAnalogAcceleration = analogAcceleration; + _cAnalogSteering = analogSteering; + _cHandbrake = handBrake; + +} +pVehicle::pVehicle(pVehicleDesc descr) +{ + _digitalSteeringDelta = descr.digitalSteeringDelta; + _steeringSteerPoint = descr.steeringSteerPoint; + _steeringTurnPoint = descr.steeringTurnPoint; + _steeringMaxAngleRad = NxMath::degToRad(descr.steeringMaxAngle); + _transmissionEfficiency = descr.transmissionEfficiency; + _differentialRatio = descr.differentialRatio; + _maxVelocity = descr.maxVelocity; + _motorForce = descr.motorForce; + + _cSteering = 0.0f; + _cAcceleration = 0.0f; + _cAnalogAcceleration = false; + _cAnalogSteering = false; + _cHandbrake = false; + mAutomaticMode = true; + + setBody(descr.body); + + _vehicleMotor = NULL; + _vehicleGears = NULL; + + +} +pVehicleDesc::pVehicleDesc() //constructor sets to default +{ + setToDefault(); +} + +void pVehicleDesc::setToDefault() +{ + userData = NULL; + transmissionEfficiency = 1.0f; + differentialRatio = 1.0f; + maxVelocity = 80; + motorForce = 100.0f; + + body = NULL; + gearDescription = NULL;//new pVehicleGearDesc(); + motorDescr = NULL;//new pVehicleMotorDesc(); + steeringMaxAngle = 30; + steeringSteerPoint = VxVector(0,0,0); + steeringTurnPoint = VxVector(0,0,0); + digitalSteeringDelta = 0.04f; + +} + + +bool pVehicleDesc::isValid() const +{ + /*for (NxU32 i = 0; i < carWheels.size(); i++) { + if (!carWheels[i]->isValid()) + return false; + } + */ + if (mass < 0) + return false; + + return true; +} + + +void pVehicle::setControlState(int parameter,float value) +{ + + switch (parameter) + { + case E_VCS_ACCELERATION: + _cAcceleration = value; + break; + + case E_VCS_STEERING: + _cSteering = value; + break; + + case E_VCS_HANDBRAKE: + _cHandbrake= (int)value; + break; + } +} + +void pVehicle::setControlMode(int parameter,int mode) +{ + switch (parameter) + { + case E_VCS_ACCELERATION: + _cAnalogAcceleration = (mode == E_VCSM_ANALOG) ? true : false; + break; + + case E_VCS_STEERING: + _cAnalogSteering = (mode == E_VCSM_ANALOG) ? true : false; + break; + } +} + +void pVehicle::getControlState(int parameter,float &value,int &mode) +{ + switch (parameter) + { + case E_VCS_ACCELERATION: + value = _cAcceleration; + mode = _cAnalogAcceleration; + break; + + case E_VCS_STEERING: + value = _cSteering; + mode = _cAnalogSteering; + break; + + case E_VCS_HANDBRAKE: + value = ((float)_cHandbrake); + mode = _cHandbrake; + break; + + } + +} \ No newline at end of file diff --git a/usr/Src/old/pVehicle/pVehicleGears.cpp b/usr/Src/old/pVehicle/pVehicleGears.cpp new file mode 100644 index 0000000..17aa873 --- /dev/null +++ b/usr/Src/old/pVehicle/pVehicleGears.cpp @@ -0,0 +1,63 @@ +#include +#include "vtPhysXAll.h" + +void pVehicleGearDesc::setToCorvette() { + + forwardGearRatios[0] = 1.66f; + forwardGearRatios[1] = 1.78f; + forwardGearRatios[2] = 1.30f; + forwardGearRatios[3] = 1; + forwardGearRatios[4] = 0.74f; + forwardGearRatios[5] = 0.50f; + nbForwardGears = 6; + + backwardGearRatio = -2.90f; + +} + + +void pVehicleGearDesc::setToDefault() +{ + //forwardGears.clear(); +} + +bool pVehicleGearDesc::isValid() const +{ + if (nbForwardGears > getMaxNumOfGears()) { + fprintf(stderr, "NxVehicleGearDesc::isValid(): nbForwardGears(%d) is bigger than max (%d)\n", + nbForwardGears, getMaxNumOfGears()); + return false; + } + if (nbForwardGears <= 0) { + fprintf(stderr, "NxVehicleGearDesc::isValid(): nbForwardGears(%d) smaller or equal 0\n", nbForwardGears); + return false; + } + if (backwardGearRatio > 0) { + fprintf(stderr, "NxVehilceGearDesc::isValid(): backwardGearRatio(%2.3f) is bigger than 0, make it negative\n", backwardGearRatio); + return false; + } + for (int i = 0; i < nbForwardGears; i++) + { + if (forwardGearRatios[i] < 0) + { + fprintf(stderr, "NxVehilceGearDesc::isValid(): forwardGearRatios[%d] (%2.3f) has value smaller 0\n", i, forwardGearRatios[i]); + return false; + } + } + return true; +} + + +float pVehicleGears::getCurrentRatio() const { + return getRatio(_curGear); +} + +float pVehicleGears::getRatio(NxI32 gear) const { + if (gear > 0) + return _forwardGearRatios[gear-1]; + //return _forwardGears[gear-1]; + if (gear == -1) + return _backwardGearRatio; + return 0; +} + diff --git a/usr/Src/old/pVehicle/pVehicleMotor.cpp b/usr/Src/old/pVehicle/pVehicleMotor.cpp new file mode 100644 index 0000000..a7750b7 --- /dev/null +++ b/usr/Src/old/pVehicle/pVehicleMotor.cpp @@ -0,0 +1,105 @@ +#include +#include "vtPhysXAll.h" + + +int pVehicleMotor::loadNewTorqueCurve(pLinearInterpolation newTCurve) +{ + + _torqueCurve.clear(); + _torqueCurve = newTCurve; + + NxReal maxTorque = 0; + NxI32 maxTorquePos = -1; + for (NxU32 i = 0; i < _torqueCurve.getSize(); i++) + { + NxReal v = _torqueCurve.getValueAtIndex(i); + if (v > maxTorque) { + maxTorque = v; + maxTorquePos = i; + } + } + + _maxTorque = maxTorque; + _maxTorquePos = (float)maxTorquePos; + + + return 1; +} + +void pVehicleMotorDesc::setToDefault() +{ + torqueCurve.clear(); + minRpmToGearDown = 1000.0f; + maxRpmToGearUp = 4000.f; + maxRpm = 5000.f; + minRpm = 1000.f; + + + + setToCorvette(); + +} + +void pVehicleMotorDesc::setToCorvette() { + + // Default should be values for a corvette! + // These are corresponding numbers for rotations and torque (in rpm and Nm) + + /* torqueCurve.insert(1000.f, 193.f); + torqueCurve.insert(2000.f, 234.f); + torqueCurve.insert(4000.f, 275.f); + torqueCurve.insert(5000.f, 275.f); + torqueCurve.insert(6000.f, 166.f);*/ + torqueCurve.insert(1000, 400); + torqueCurve.insert(3000, 500); + torqueCurve.insert(5000, 300); + minRpmToGearDown = 1500.f; + maxRpmToGearUp = 4000.f; + minRpm = 1000.f; + maxRpm = 5000.f; +} + +bool pVehicleMotorDesc::isValid() const +{ + + if (torqueCurve.getSize() == 0) { + fprintf(stderr, "pVehicleMotorDesc::isValid(): Empty TorqueCurve\n"); + return false; + } + if (maxRpmToGearUp < minRpmToGearDown) { + fprintf(stderr, "pVehicleMotorDesc::isValid(): maxRpmToGearUp (%2.3f) is smaller than minRpmToGearDown (%2.3f)\n", + maxRpmToGearUp, minRpmToGearDown); + return false; + } + return true; + +} + + +int pVehicleMotor::changeGears(const pVehicleGears* gears, float threshold) const +{ + NxI32 gear = gears->getGear(); + if (_rpm > _maxRpmToGearUp && gear < gears->getMaxGear()) + return 1; + else if (_rpm < _minRpmToGearDown && gear > 1) + return -1; + /* + NxReal normalTorque = _torqueCurve.getValue(_rpm); + + NxReal lowerGearRatio = gears->getRatio(gear-1); + NxReal normalGearRatio = gears->getCurrentRatio(); + NxReal upperGearRatio = gears->getRatio(gear+1); + NxReal lowerGearRpm = _rpm / normalGearRatio * lowerGearRatio; + NxReal upperGearRpm = _rpm / normalGearRatio * upperGearRatio; + NxReal lowerTorque = _torqueCurve.getValue(lowerGearRpm); + NxReal upperTorque = _torqueCurve.getValue(upperGearRpm); + NxReal lowerWheelTorque = lowerTorque * lowerGearRatio; + NxReal normalWheelTorque = normalTorque * normalGearRatio; + NxReal upperWheelTorque = upperTorque * upperGearRatio; + //printf("%2.3f %2.3f %2.3f\n", lowerWheelTorque, normalWheelTorque, upperWheelTorque); + */ + + return 0; +} + + diff --git a/usr/Src/old/pVehicle/pVehicleXML.cpp b/usr/Src/old/pVehicle/pVehicleXML.cpp new file mode 100644 index 0000000..44891b9 --- /dev/null +++ b/usr/Src/old/pVehicle/pVehicleXML.cpp @@ -0,0 +1,485 @@ +#include +#include "vtPhysXAll.h" + +#include "tinyxml.h" + +int pFactory::loadFrom(pTireFunction& dst,const char* nodeName,const TiXmlDocument * doc ) +{ + int result = 0 ; + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "tireFunction" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + + int res = sube->QueryDoubleAttribute("ExtremumSlip",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.extremumSlip = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("ExtremumValue",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.extremumValue = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("AsymptoteSlip",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.asymptoteSlip = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("AsymptoteValue",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.asymptoteValue = static_cast(v); + } + } + res = sube->QueryDoubleAttribute("StiffnessFactor",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.stiffnessFactor = static_cast(v); + } + } + } + } + } + } + } + } + } + return result; +} + +int pFactory::loadWheelDescrFromXML(pWheelDescr& dst,const char* nodeName,const TiXmlDocument * doc ) +{ + int result = 0 ; + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "wheel" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + + int res = sube->QueryDoubleAttribute("Suspension",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.wheelSuspension = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.springRestitution = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("Damping",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.springDamping = static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("Bias",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.springBias= static_cast(v); + } + } + + res = sube->QueryDoubleAttribute("MaxBreakForce",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.maxBrakeForce = static_cast(v); + continue; + } + } + + + res = sube->QueryDoubleAttribute("FrictionToSide",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.frictionToSide = static_cast(v); + continue; + } + } + + res = sube->QueryDoubleAttribute("FrictionToFront",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.frictionToFront = static_cast(v); + continue; + } + } + + res = sube->QueryDoubleAttribute("InverseWheelMass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.inverseWheelMass = static_cast(v); + continue; + } + } + + const char* flags = NULL; + flags = sube->Attribute("Flags"); + if (flags && strlen(flags)) + { + dst.wheelFlags = (WheelFlags)_str2WheelFlag(flags); + } + + + const char* latFunc = NULL; + latFunc = sube->Attribute("LateralFunction"); + if (latFunc && strlen(latFunc)) + { + int index = getEnumIndex(getManager()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,latFunc); + if (index!=0) + { + loadFrom(dst.latFunc,latFunc,doc); + dst.latFunc.xmlLink = index; + if (!dst.latFunc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Lateral Tire Function from XML was incorrect, setting to default"); + dst.latFunc.setToDefault(); + } + } + } + + const char* longFunc = NULL; + longFunc = sube->Attribute("LongitudeFunction"); + if (longFunc && strlen(longFunc)) + { + int index = getEnumIndex(getManager()->GetContext()->GetParameterManager(),VTE_XML_TIRE_SETTINGS,longFunc); + if (index!=0) + { + loadFrom(dst.longFunc,longFunc,doc); + dst.longFunc.xmlLink = index; + if (!dst.longFunc.isValid()) + { + xLogger::xLog(XL_START,ELOGERROR,E_LI_MANAGER,"Longitude Tire Function from XML was incorrect, setting to default"); + dst.longFunc.setToDefault(); + } + } + } + } + } + } + } + } + } + } + return result; +} +int pFactory::loadVehicleDescrFromXML(pVehicleDesc& dst,const char* nodeName,const TiXmlDocument * doc ) +{ + + + int result = 0 ; + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "vehicle" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + + int res = sube->QueryDoubleAttribute("Mass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.mass = static_cast(v); + continue; + } + } + + ////////////////////////////////////////////////////////////////////////// + + /* + int res = sube->QueryDoubleAttribute("Mass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + dst.mass = static_cast(v); + continue; + } + } + + */ + } + } + } + } + } + } + } + return result; +} + +int pFactory::_str2WheelFlag(XString _in) +{ + + + short nb = 0 ; + int result = 0; + XStringTokenizer tokizer(_in.CStr(), "|"); + const char*tok = NULL; + while ((tok=tokizer.NextToken(tok)) && nb < 3) + { + XString tokx(tok); + + if ( _stricmp(tokx.CStr(),"Steerable") == 0 ) + { + result |= WF_SteerableInput; + } + + if ( _stricmp(tokx.CStr(),"VehicleControlled") == 0 ) + { + result |= WF_VehicleControlled; + } + if ( _stricmp(tokx.CStr(),"SteerableAuto") == 0 ) + { + result |= WF_SteerableAuto; + } + if ( _stricmp(tokx.CStr(),"Handbrake") == 0 ) + { + result |= WF_AffectedByHandbrake; + } + + if ( _stricmp(tokx.CStr(),"Accelerated") == 0 ) + { + result |= WF_Accelerated; + } + + /*if ( _stricmp(tokx.CStr(),"Wheelshape") == 0 ) + { + result |= WF_UseWheelShape; + }*/ + + nb++; + } + return result; +} + +/* + +int pVehicle::loadFromXML(const char* nodeName,const TiXmlDocument * doc ) +{ + NxMaterialDesc *result = new NxMaterialDesc(); + result->setToDefault(); + + int res = 0; + + if (!strlen(nodeName)) { return -1; } + if (!doc) { return -1; } + + + if ( strlen(nodeName) && doc) + { + const TiXmlElement *root = pFactory::Instance()->getFirstDocElement(doc->RootElement()); + for (const TiXmlNode *child = root->FirstChild(); child; child = child->NextSibling() ) + { + if ( (child->Type() == TiXmlNode::ELEMENT)) + { + XString name = child->Value(); + if (!strcmp(child->Value(), "vehicle" ) ) + { + const TiXmlElement *element = (const TiXmlElement*)child; + if (element->Type() == TiXmlNode::ELEMENT ) + { + if(!strcmp( element->Attribute("name"),nodeName ) ) + { + for (const TiXmlNode *node = element->FirstChild(); node; node = node->NextSibling() ) + { + if ((node->Type() == TiXmlNode::ELEMENT) && (!stricmp(node->Value(),"settings"))) + { + const TiXmlElement *sube = (const TiXmlElement*)node; + double v; + + ////////////////////////////////////////////////////////////////////////// + int res = sube->QueryDoubleAttribute("Mass",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f) + { + //setMass() = + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFriction",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFriction= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("Restitution",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->restitution= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("DynamicFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->dynamicFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + res = sube->QueryDoubleAttribute("StaticFrictionV",&v); + if (res == TIXML_SUCCESS) + { + if(v >=0.0f){ + result->staticFrictionV= (float)v; + continue; + } + } + ////////////////////////////////////////////////////////////////////////// + const char* dirOfAnisotropy = NULL; + dirOfAnisotropy = sube->Attribute("DirOfAnisotropy"); + if (dirOfAnisotropy && strlen(dirOfAnisotropy)) + { + VxVector vec = pFactory::Instance()->_str2Vec(dirOfAnisotropy); + if (vec.Magnitude() >0.1f) + { + result->flags = NX_MF_ANISOTROPIC; + result->dirOfAnisotropy = pMath::getFrom(vec); + continue; + }else + { + result->dirOfAnisotropy = pMath::getFrom(VxVector(0,0,0)); + } + + //result->setGravity(vec); + + } + + ////////////////////////////////////////////////////////////////////////// + const char* FrictionCombineMode = NULL; + FrictionCombineMode = sube->Attribute("FrictionCombineMode"); + if (FrictionCombineMode && strlen(FrictionCombineMode)) + { +// int fMode = _str2CombineMode(FrictionCombineMode); +// result->frictionCombineMode = (NxCombineMode)fMode; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + const char* RestitutionCombineMode = NULL; + RestitutionCombineMode = sube->Attribute("RestitutionCombineMode"); + if (RestitutionCombineMode && strlen(RestitutionCombineMode)) + { +// int fMode = _str2CombineMode(RestitutionCombineMode); +// result->restitutionCombineMode= (NxCombineMode)fMode; + continue; + } + } + } +// return result; + } + } + } + } + } + } + + + + return 0; +} +*/ + + + diff --git a/usr/Src/old/pVehicle/pWheel.cpp b/usr/Src/old/pVehicle/pWheel.cpp new file mode 100644 index 0000000..d18c157 --- /dev/null +++ b/usr/Src/old/pVehicle/pWheel.cpp @@ -0,0 +1,98 @@ +#include +#include "vtPhysXAll.h" +#include + +NxActor*pWheel::getTouchedActor()const{ return NULL;} + +void pWheelDescr::setToDefault() +{ + + userData = NULL; + wheelFlags =(WheelFlags)0; + + //radius.setToDefault(); + springBias = 0; + springRestitution = 1.f; + springDamping = 0.f; + + wheelSuspension = 1.f; + maxBrakeForce = 0.0f; + frictionToSide = 1.0f; + frictionToFront = 1.0f; + latFuncXML_Id=0; + longFuncXML_Id=0; + inverseWheelMass = 0.1f; + wheelShapeFlags =(WheelShapeFlags)0; + + latFunc.setToDefault(); + longFunc.setToDefault(); + + +} +bool pWheelDescr::isValid() const +{ + + /*if(!NxMath::isFinite(radius)) return false; + if(radius<=0.0f) return false;*/ + + bool result = true; + int a=X_NEGATE(NxMath::isFinite(wheelSuspension)); + //iAssertWR(X_NEGATE(NxMath::isFinite(wheelSuspension)),"",result ); + iAssertWR(inverseWheelMass > 0.0f,"",result ); + iAssertWR(X_NEGATE(inverseWheelMass<0.0f),"",result ); + //iAssertWR(X_NEGATE(brakeTorque<0.0f),"",result ); + //iAssertWR(X_NEGATE(NxMath::isFinite(steerAngle)),"",result ); + //iAssertWR(X_NEGATE(brakeTorque<0.0f),"",result ); + iAssertWR(longFunc.isValid(),"",result ); + iAssertWR(latFunc.isValid(),"",result ); + +/* if (!suspension.isValid()) return false; + if (!longitudalTireForceFunction.isValid()) return false; + if (!lateralTireForceFunction.isValid()) return false; +*/ + //if (NxMath::abs(1-wheelAxis.magnitudeSquared()) > 0.001f) + // return false; + if (wheelApproximation > 0 && wheelApproximation < 4) { + + return false; + } + if ((wheelFlags & WF_SteerableAuto) && (wheelFlags & WF_SteerableInput)) + { + return false; + } + return result; +} + +int pWheel::_constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + return 1; +} + +void pWheel::setFlags(int flags) +{ + mWheelFlags = flags; +} + +pWheel::pWheel(pRigidBody *body,pWheelDescr *descr) +{ + + mBody = body; + mWheelFlags = descr->wheelFlags; + _wheelRollAngle = 0.0f; + mActor= body->getActor(); + +} + +pWheel1*pWheel::castWheel1() +{ + return dynamic_cast(this); +} +pWheel2*pWheel::castWheel2() +{ + + return dynamic_cast(this); +} + + + + diff --git a/usr/Src/old/pVehicle/pWheel1.cpp b/usr/Src/old/pVehicle/pWheel1.cpp new file mode 100644 index 0000000..356f5f5 --- /dev/null +++ b/usr/Src/old/pVehicle/pWheel1.cpp @@ -0,0 +1,262 @@ +#include +#include "vtPhysXAll.h" + +pWheelContactData* +pWheel1::getContact(){ + + return new pWheelContactData(); +} + +float pWheel1::getRpm()const{ return NxMath::abs(_turnVelocity * 60.f);} + +NxActor *pWheel1::getTouchedActor(){ return contactInfo->otherActor; } + +void pWheel1::_tick(float dt) +{ + + if(!hasGroundContact()) + updateContactPosition(); + + //################################################################ + // + // Calculate the wheel rotation around the roll axis + // + updateAngularVelocity(dt*0.001f, false); + + float motorTorque=0.0; + + if(getWheelFlag(WF_Accelerated)) + { + /*if (handBrake && getWheelFlag(NX_WF_AFFECTED_BY_HANDBRAKE)) + { + // Handbrake, blocking! + }*/ + + if (hasGroundContact()) + { + // Touching, force applies + NxVec3 steeringDirection; + getSteeringDirection(steeringDirection); + steeringDirection.normalize(); + NxReal localTorque = motorTorque; + NxReal wheelForce = localTorque / _radius; + steeringDirection *= wheelForce; + wheelCapsule->getActor().addForceAtPos(steeringDirection, contactInfo->contactPosition); + if(contactInfo->otherActor->isDynamic()) + contactInfo->otherActor->addForceAtPos(-steeringDirection, contactInfo->contactPosition); + } + } + + NxMat34& wheelPose = getWheelCapsule()->getGlobalPose(); + NxMat33 rot, axisRot, rollRot; + rot.rotY( _angle ); + axisRot.rotY(0); + rollRot.rotX(_turnAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + + float a = _angle; + float b = getWheelRollAngle(); + + + setWheelPose(wheelPose); + //setWheelOrientation(wheelPose.M); + + + contactInfo->reset(); +} + + +void pWheel1::_updateVirtoolsEntity(bool position,bool rotation) +{ + + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(getEntID())); + if (ent && position) + { + + /* + NxWheelShape *wShape = getWheelShape(); + NxMat34 pose = wShape->getGlobalPose(); + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + NxVec3 suspensionOffsetDirection; + pose.M.getColumn(1, suspensionOffsetDirection); + suspensionOffsetDirection =-suspensionOffsetDirection; + + if (contactShape && wcd.contactForce > -1000) + { + NxVec3 toContact = wcd.contactPoint - pose.t; + double alongLength = suspensionOffsetDirection.dot(toContact); + NxVec3 across = toContact - alongLength * suspensionOffsetDirection; + double r = wShape->getRadius(); + double pullBack = sqrt(r*r - across.dot(across)); + pose.t += (alongLength - pullBack) * suspensionOffsetDirection; + } else { + pose.t += wShape->getSuspensionTravel() * suspensionOffsetDirection; + } + + VxVector oPos = getFrom(pose.t); + ent->SetPosition(&oPos); + + if (hasGroundContact()) + { + + + }else + { + // VxVector gPos = getWheelPos(); + // ent->SetPosition(&gPos,getBody()->GetVT3DObject()); + } + + */ + } + if (ent && rotation) + { + //float rollAngle = getWheelRollAngle(); + //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + + VxQuaternion rot = pMath::getFrom( getWheelPose().M ); + ent->SetQuaternion(&rot,NULL); + } + +} + + + + +void pWheel1::updateContactPosition() +{ + contactInfo->contactPositionLocal = getFrom(_maxPosition) - NxVec3(0, _maxSuspension+_radius, 0); +} +void pWheel1::setAngle(float angle) +{ + _angle = angle; + + NxReal Cos, Sin; + NxMath::sinCos(_angle, Sin, Cos); + NxMat33 wheelOrientation = wheelCapsule->getLocalOrientation(); + wheelOrientation.setColumn(0, NxVec3( Cos, 0, Sin )); + wheelOrientation.setColumn(2, NxVec3( Sin, 0,-Cos )); + setWheelOrientation(wheelOrientation); + +} + +void pWheel1::updateAngularVelocity(float lastTimeStepSize, bool handbrake) +{ + if((mWheelFlags & WF_AffectedByHandbrake) && handbrake) + { + _turnVelocity = 0; + } + else if (contactInfo->isTouching()) + { + NxReal wheelPerimeter = NxTwoPi * _radius; + NxReal newTurnVelocity = contactInfo->relativeVelocity / wheelPerimeter; + _turnVelocity = newTurnVelocity; + _turnAngle += _turnVelocity * lastTimeStepSize * NxTwoPi; + } + else + { + _turnVelocity *= 0.99f; + _turnAngle += _turnVelocity; + } + + while(_turnAngle >= NxTwoPi) + _turnAngle -= NxTwoPi; + while (_turnAngle < 0) + _turnAngle += NxTwoPi; + + setWheelRollAngle(_turnAngle); + +} + +void pWheel1::getSteeringDirection(NxVec3& dir) +{ + if(mWheelFlags & (WF_SteerableInput | WF_SteerableAuto)) + { + wheelCapsule->getGlobalOrientation().getColumn(0, dir); + } + else + { + wheelCapsule->getActor().getGlobalOrientation().getColumn(0, dir); + } +} + +void pWheel1::tick(bool handbrake, float motorTorque, float brakeTorque, float dt) +{ + + if(getWheelFlag(WF_Accelerated)) + { + if (handbrake && getWheelFlag(WF_AffectedByHandbrake)) + { + // Handbrake, blocking! + } + else if (hasGroundContact()) + { + // Touching, force applies + NxVec3 steeringDirection; + getSteeringDirection(steeringDirection); + steeringDirection.normalize(); + NxReal localTorque = motorTorque; + NxReal wheelForce = localTorque / _radius; + steeringDirection *= wheelForce; + wheelCapsule->getActor().addForceAtPos(steeringDirection, contactInfo->contactPosition); + if(contactInfo->otherActor->isDynamic()) + contactInfo->otherActor->addForceAtPos(-steeringDirection, contactInfo->contactPosition); + } + } + + NxReal OneMinusBreakPedal = 1-brakeTorque; + + /* + if(handBrake && getWheelFlag(WF_AffectedByHandbrake)) + { + material->setDynamicFrictionV(1); + material->setStaticFrictionV(4); + material->setDynamicFriction(0.4f); + material->setStaticFriction(1.0f); + } + else + { + NxReal newv = OneMinusBreakPedal * _frictionToFront + brakeTorque; + NxReal newv4= OneMinusBreakPedal * _frictionToFront + brakeTorque*4; + material->setDynamicFrictionV(newv); + material->setDynamicFriction(_frictionToSide); + + material->setStaticFrictionV(newv*4); + material->setStaticFriction(2); + }*/ + + if(!hasGroundContact()) + updateContactPosition(); + updateAngularVelocity(dt, handbrake); + + contactInfo->reset(); +} +VxVector pWheel1::getWheelPos()const{ return getFrom(wheelCapsule->getLocalPosition()); } +void pWheel1::setWheelOrientation(const NxMat33& m) +{ + wheelCapsule->setLocalOrientation(m); + if (wheelConvex != NULL) + wheelConvex->setLocalOrientation(m); +} + +void pWheel1::_updateAgeiaShape(bool position,bool rotation) +{ + +} + +int pWheel1::_constructWheel(NxActor *actor,pObjectDescr *descr,pWheelDescr *wheelDescr,CKMesh *mesh,VxVector localPos,VxQuaternion localRotation) +{ + return 1; +} +pWheel1::pWheel1(pRigidBody *body, pWheelDescr *descr) : pWheel(body,descr) +{ + wheelCapsule = NULL; + wheelConvex = NULL; + + contactInfo = new ContactInfo(); + + +} + + + diff --git a/usr/Src/old/pVehicle/pWheel2.cpp b/usr/Src/old/pVehicle/pWheel2.cpp new file mode 100644 index 0000000..0be0a85 --- /dev/null +++ b/usr/Src/old/pVehicle/pWheel2.cpp @@ -0,0 +1,439 @@ +#include +#include "vtPhysXAll.h" + +#include + +void pWheel2::_tick(float dt) +{ + NxWheelShape *wShape = getWheelShape(); + if (!wShape) return; + + + NxVec3 _localVelocity; + bool _breaking=false; + ////////////////////////////////////////////////////////////////////////// + // + // + // + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + + if (contactShape) + { + + NxVec3 relativeVelocity; + if ( !contactShape->getActor().isDynamic()) + { + relativeVelocity = getActor()->getLinearVelocity(); + } else { + relativeVelocity = getActor()->getLinearVelocity() - contactShape->getActor().getLinearVelocity(); + } + NxQuat rotation = getActor()->getGlobalOrientationQuat(); + + _localVelocity = relativeVelocity; + rotation.inverseRotate(_localVelocity); + _breaking = false; //NxMath::abs(_localVelocity.z) < ( 0.1 ); + // wShape->setAxleSpeed() + } + + + float rollAngle = getWheelRollAngle(); + + rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + //rollAngle+=wShape->getAxleSpeed() * (1.0f/60.0f /*dt* 0.01f*/); + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + + NxMat34& wheelPose = wShape->getGlobalPose(); + + + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( contactShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } + + + float rAngle = getWheelRollAngle(); + float steer = wShape->getSteerAngle(); + + NxVec3 p0; + NxVec3 dir; + /* + getWorldSegmentFast(seg); + seg.computeDirection(dir); + dir.normalize(); + */ + NxReal r = wShape->getRadius(); + NxReal st = wShape->getSuspensionTravel(); + NxReal steerAngle = wShape->getSteerAngle(); + p0 = wheelPose.t; //cast from shape origin + wheelPose.M.getColumn(1, dir); + dir = -dir; //cast along -Y. + NxReal castLength = r + st; //cast ray this long + + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + setWheelPose(wheelPose); +} + +pWheelContactData* pWheel2::getContact() +{ + NxWheelShape *wShape = getWheelShape(); + if (!wShape) + { + return new pWheelContactData(); + } + + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + + pWheelContactData result; + + if (contactShape) + { + + result.contactForce = wcd.contactForce; + result.contactNormal = getFrom(wcd.contactNormal); + result.contactPoint= getFrom(wcd.contactPoint); + result.contactPosition= wcd.contactPosition; + + + result.lateralDirection= getFrom(wcd.lateralDirection); + result.lateralImpulse= wcd.lateralImpulse; + result.lateralSlip = wcd.lateralSlip; + + result.longitudalDirection = getFrom(wcd.longitudalDirection); + result.longitudalImpulse = wcd.longitudalImpulse; + result.longitudalSlip= wcd.longitudalSlip; + + pSubMeshInfo *sInfo = static_cast(contactShape->userData); + if (sInfo->entID) + { + CKObject *obj = (CKObject*)GetPMan()->m_Context->GetObject(sInfo->entID); + if (obj) + { + result.contactEntity = (CK3dEntity*)obj; + }else + { + result.contactEntity = NULL; + } + } + + result.otherShapeMaterialIndex = contactShape->getMaterial(); + + NxMaterial* otherMaterial = contactShape->getActor().getScene().getMaterialFromIndex(contactShape->getMaterial()); + if (otherMaterial) + { + pFactory::Instance()->copyTo(result.otherMaterial,otherMaterial); + } + } + return &result; +} + +void pWheel2::_updateVirtoolsEntity(bool position,bool rotation) +{ + + CK3dEntity *ent = static_cast(GetPMan()->GetContext()->GetObject(getEntID())); + if (ent && position) + { + + NxWheelShape *wShape = getWheelShape(); + NxMat34 pose = wShape->getGlobalPose(); + NxWheelContactData wcd; + NxShape* contactShape = wShape->getContact(wcd); + NxVec3 suspensionOffsetDirection; + pose.M.getColumn(1, suspensionOffsetDirection); + suspensionOffsetDirection =-suspensionOffsetDirection; + + if (contactShape && wcd.contactForce > -1000) + { + NxVec3 toContact = wcd.contactPoint - pose.t; + double alongLength = suspensionOffsetDirection.dot(toContact); + NxVec3 across = toContact - alongLength * suspensionOffsetDirection; + double r = wShape->getRadius(); + double pullBack = sqrt(r*r - across.dot(across)); + pose.t += (alongLength - pullBack) * suspensionOffsetDirection; + } else { + pose.t += wShape->getSuspensionTravel() * suspensionOffsetDirection; + } + + VxVector oPos = getFrom(pose.t); + ent->SetPosition(&oPos); + + if (hasGroundContact()) + { + + NxWheelShape *wShape = getWheelShape(); + NxMat34& wheelPose = wShape->getGlobalPose(); + +/* NxWheelContactData wcd; + NxShape* cShape = wShape->getContact(wcd); + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + VxVector gPos = getFrom(getWheelPose().t); + + /* + if( cShape && wcd.contactPosition <= (stravel + radius) ) + { + }*/ + + ////////////////////////////////////////////////////////////////////////// + + /*VxVector gPos = getFrom(getWheelPose().t); + //gPos*=-1.0f; + gPos -=getWheelPos(); + V 3. + xVector gPos2 = getFrom(getWheelShape()->getLocalPose().t); + ent->SetPosition(&gPos2,getBody()->GetVT3DObject()); + */ + }else + { +// VxVector gPos = getWheelPos(); +// ent->SetPosition(&gPos,getBody()->GetVT3DObject()); + } + } + if (ent && rotation) + { + + + //float rollAngle = getWheelRollAngle(); + //rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + + VxQuaternion rot = pMath::getFrom( getWheelPose().M ); + ent->SetQuaternion(&rot,NULL); + } + + + /* + + + + NxWheelShape *wShape = getWheelShape(); + + + + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + + + NxMat34& wheelPose = wShape->getGlobalPose(); + + NxWheelContactData wcd; + NxShape* cShape = wShape->getContact(wcd); + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( cShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } + + float rAngle = rollAngle; + float steer = wShape->getSteerAngle(); + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rollAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + setWheelPose(wheelPose); + + */ +} + +void pWheel2::_updateAgeiaShape(bool position,bool rotation) +{ + +} + +float pWheel2::getRadius()const +{ + return mWheelShape->getRadius(); +} + +float pWheel2::getRpm() const +{ + float a = NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; + return NxMath::abs(mWheelShape->getAxleSpeed())/NxTwoPi * 60.0f; +} +VxVector pWheel2::getWheelPos() const +{ + return getFrom(mWheelShape->getLocalPosition()); +} + +void pWheel2::setAngle(float angle) +{ + mWheelShape->setSteerAngle(-angle); +} + +NxActor*pWheel2::getTouchedActor()const +{ + NxWheelContactData wcd; + NxShape * s = mWheelShape->getContact(wcd); + return s ? &s->getActor() : NULL; +} +float pWheel2::getAxleSpeed()const +{ + if (mWheelShape) + { + return mWheelShape->getAxleSpeed(); + } + return -1.f; + +} +bool pWheel2::hasGroundContact() const +{ + return getTouchedActor() != NULL; +} +void pWheel2::tick(bool handBrake, float motorTorque, float brakeTorque, float dt) +{ + motorTorque *= 10.0f; + brakeTorque *= 50.0f; + if(handBrake && getWheelFlag(WF_AffectedByHandbrake)) + brakeTorque = 1000.0f; + + + if(getWheelFlag(WF_Accelerated)) + mWheelShape->setMotorTorque(motorTorque); + mWheelShape->setBrakeTorque(brakeTorque); + + + XString errMessage; + //errMessage.Format("mT:%f | bT:%f",motorTorque,brakeTorque); + //xInfo(errMessage.Str()); + + + NxWheelShape *wShape = getWheelShape(); + + float rollAngle = getWheelRollAngle(); + rollAngle+=wShape->getAxleSpeed() * (dt* 0.01f); + //rollAngle+=wShape->getAxleSpeed() * (1/60); + + + while (rollAngle > NxTwoPi) //normally just 1x + rollAngle-= NxTwoPi; + while (rollAngle< -NxTwoPi) //normally just 1x + rollAngle+= NxTwoPi; + + setWheelRollAngle(rollAngle); + + + NxMat34& wheelPose = wShape->getGlobalPose(); + + NxWheelContactData wcd; + NxShape* cShape = wShape->getContact(wcd); + NxReal stravel = wShape->getSuspensionTravel(); + NxReal radius = wShape->getRadius(); + + + //have ground contact? + if( cShape && wcd.contactPosition <= (stravel + radius) ) { + wheelPose.t = NxVec3( wheelPose.t.x, wcd.contactPoint.y + getRadius(), wheelPose.t.z ); + } + else { + wheelPose.t = NxVec3( wheelPose.t.x, wheelPose.t.y - getSuspensionTravel(), wheelPose.t.z ); + } + + float rAngle = rollAngle; + float steer = wShape->getSteerAngle(); + + NxMat33 rot, axisRot, rollRot; + rot.rotY( wShape->getSteerAngle() ); + axisRot.rotY(0); + rollRot.rotX(rollAngle); + wheelPose.M = rot * wheelPose.M * axisRot * rollRot; + setWheelPose(wheelPose); +} +VxVector pWheel2::getGroundContactPos()const +{ + VxVector pos = getWheelPos()+VxVector(0, -mWheelShape->getRadius(), 0); + + if (pos.Magnitude()) + { + int op2 = 0 ; + op2++; + } + + return pos; +} + +float pWheel2::getSuspensionTravel()const +{ + + if (mWheelShape) + { + return mWheelShape->getSuspensionTravel(); + } + return 0.0f; +} + + +bool pWheel2::setSuspensionSpring(const pSpring& spring) +{ + + NxSpringDesc sLimit; sLimit.damper = spring.damper;sLimit.spring=spring.spring;sLimit.targetValue=spring.targetValue; + if (!sLimit.isValid())return false; + NxWheelShape *wShape = getWheelShape(); + if (!wShape) + { + return false; + } + wShape->setSuspension(sLimit); + return true; +} + +void pWheel2::setAxleSpeed(float speed) +{ + + getWheelShape()->setAxleSpeed(speed); +} + +void pWheel2::setMotorTorque(float torque) +{ + getWheelShape()->setMotorTorque(torque); +} +void pWheel2::setBreakTorque(float torque) +{ + getWheelShape()->setBrakeTorque(torque); +} + +void pWheel2::setSuspensionTravel(float travel) +{ + getWheelShape()->setSuspensionTravel(travel); +} + + +pWheel2::pWheel2(pRigidBody *body, pWheelDescr *descr) : pWheel(body,descr) +{ + this->setBody(body); + mWheelShape = NULL; + mWheelFlags = descr->wheelFlags; + _wheelRollAngle = 0.0f; + +} \ No newline at end of file diff --git a/usr/Src/xmlstream/XloaderCharacter.cpp b/usr/Src/xmlstream/XloaderCharacter.cpp new file mode 100644 index 0000000..73e2979 --- /dev/null +++ b/usr/Src/xmlstream/XloaderCharacter.cpp @@ -0,0 +1,139 @@ +#include "XLoader.h" +#include "InitGuid.h" +#include "CKAll.h" + +#include "pCommon.h" + + +#define X_PLUGIN_VERSION 0x0000001 +#define X_READER_GUID CKGUID(0x499d11a7,0x24aa03b6) + + + +#ifdef CK_LIB +#define RegisterBehSDatorDeclarations Register_SDatReader_BehaviorDeclarations +#define InitInstance _SDatReader_InitInstance +#define ExitInstance _SDatReader_ExitInstance +#define CKGetPluginInfoCount CKGet_SDatReader_PluginInfoCount +#define CKGetPluginInfo CKGet_SDatReader_PluginInfo +#define g_PluginInfo g_SDatReader_PluginInfo +#define CKGetReader CKGet_SDatReader_Reader +#else +#define RegisterBehaviorDeclarations RegisterBehaviorDeclarations +#define InitInstance InitInstance +#define ExitInstance ExitInstance +#define CKGetPluginInfoCount CKGetPluginInfoCount +#define CKGetPluginInfo CKGetPluginInfo +#define g_PluginInfo g_PluginInfo +#define CKGetReader CKGetReader +#endif + + +CKPluginInfo g_PluginInfo; + +/********************************************** +Called by the engine when a file with the AVI +extension is being loaded, a reader has to be +created. +***********************************************/ +CKDataReader *CKGetReader(int pos) +{ + return new CKXReader(); +} + + +CKPluginInfo* CKGetPluginInfo(int index) +{ + // Not Valid under Win NT 4 + if (VxGetOs() == VXOS_WINNT4) return 0; + g_PluginInfo.m_GUID=X_READER_GUID; + g_PluginInfo.m_Extension="dae"; + g_PluginInfo.m_Description="NxStream Parser"; + g_PluginInfo.m_Author="Guenter Baumgart"; + g_PluginInfo.m_Summary="Loads xml files, created by Maya/Max Exporters"; + g_PluginInfo.m_Version=X_PLUGIN_VERSION; + g_PluginInfo.m_InitInstanceFct=NULL; // + g_PluginInfo.m_Type=CKPLUGIN_MODEL_READER; // Plugin Type + return &g_PluginInfo; +} + + + + +CKPluginInfo g_PluginInfos; +int CKGetPluginInfoCount() +{ + return 1; +} + + +CKPluginInfo* CKXReader::GetReaderInfo() { + return &g_PluginInfo; +} +///////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////// +//------- Returns the name of a LPDIRECTXFILEOBJECT +XString GetFileObjectName(LPDIRECTXFILEOBJECT obj) +{ + if (!obj) return XString(""); + + + DWORD NameSize = 0; + + if (FAILED(obj->GetName(NULL,&NameSize))) + return XString(""); + if (!NameSize) + return XString(""); + NameSize++; + XString Temp(NameSize); + if (FAILED(obj->GetName(Temp.Str(),&NameSize))) + return XString(""); + return Temp; +} +////////////////////////////////////////////////////////////////////////// +CKERROR CKXReader::Load(CKContext* context,CKSTRING FileName,CKObjectArray *array,CKDWORD LoadFlags,CKCharacter *carac) +{ + if(!array) return CKERR_INVALIDPARAMETER; + if(!FileName) return CKERR_INVALIDPARAMETER; + + + + + HRESULT hr = S_OK; + + m_Context = context; + m_LoadFlags = LoadFlags; + m_FileName = FileName; + + + XString filename(FileName); + filename.Trim(); + int ok = context->GetPathManager()->ResolveFileName(filename,DATA_PATH_IDX,-1); + + pSerializer *ser = pSerializer::Instance(); + if (ser && ok==0 ) + { + ser->parseFile(filename.CStr(),0); + //ser->loadCollection(filename.CStr()) + } + + + + + int t = 0; + + + + //LoadFromFileC(context,FileName,false,LoadFlags,array,"null"); + + return CK_OK; +} + +////////////////////////////////////////////////////////////////////////// +BOOL CKXReader::LoadFromFileC(CKContext *ctx, XString filename, CKBOOL hidden, CKDWORD loadflags, CKObjectArray* targetArray, XString password) +{ + CKBOOL result = false; + + return result; +} diff --git a/usr/Src/xmlstream/XloaderCharacter.def b/usr/Src/xmlstream/XloaderCharacter.def new file mode 100644 index 0000000..cd80d8e --- /dev/null +++ b/usr/Src/xmlstream/XloaderCharacter.def @@ -0,0 +1,13 @@ +;************************************************************************* +; File : XLoader.def : Declares the module parameters for the DLL. * +; The only functions that need to be export are CKGetPluginInfo which * +; return information about this plugin and CKGetReader that returns * +; an instance of the CKXReader class * +; Virtools SDK * +; Copyright (c) Virtools 2000, All Rights Reserved. * +;************************************************************************* +EXPORTS + ; Explicit exports can go here + CKGetPluginInfoCount + CKGetPluginInfo + CKGetReader \ No newline at end of file