diff options
| author | git perforce import user <a@b> | 2016-10-25 12:29:14 -0600 |
|---|---|---|
| committer | Sheikh Dawood Abdul Ajees <Sheikh Dawood Abdul Ajees> | 2016-10-25 18:56:37 -0500 |
| commit | 3dfe2108cfab31ba3ee5527e217d0d8e99a51162 (patch) | |
| tree | fa6485c169e50d7415a651bf838f5bcd0fd3bfbd /APEX_1.4/include | |
| download | physx-3.4-3dfe2108cfab31ba3ee5527e217d0d8e99a51162.tar.xz physx-3.4-3dfe2108cfab31ba3ee5527e217d0d8e99a51162.zip | |
Initial commit:
PhysX 3.4.0 Update @ 21294896
APEX 1.4.0 Update @ 21275617
[CL 21300167]
Diffstat (limited to 'APEX_1.4/include')
158 files changed, 30426 insertions, 0 deletions
diff --git a/APEX_1.4/include/Actor.h b/APEX_1.4/include/Actor.h new file mode 100644 index 00000000..482756e3 --- /dev/null +++ b/APEX_1.4/include/Actor.h @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef ACTOR_H +#define ACTOR_H + +/*! +\file +\brief classes ApexActor, ApexActorSource +*/ + +#include "ApexInterface.h" + +#if PX_PHYSICS_VERSION_MAJOR == 3 +#include "PxActor.h" +#include "PxShape.h" +#include "PxFiltering.h" +namespace nvidia { namespace apex +{ + +/** Corresponds to 20 frames for a time step of 0.02, PhysX 3.3 took PX_SLEEP_INTERVAL away */ +#define APEX_DEFAULT_WAKE_UP_COUNTER 0.4f + +/** Used to define generic get/set methods for 1-parameter values in PhysX3DescTemplate. */ +#define APEX_ACTOR_TEMPLATE_PARAM(_type, _name, _valid, _default) \ +bool is##_name##Valid(_type x) const { PX_UNUSED(x); return _valid; } \ +_type getDefault##_name() const { return _default; } \ +virtual _type get##_name() const = 0; \ +virtual bool set##_name(_type) = 0 + +/** + Template for PhysX3.x actor, body and shape. Used by the Destruction module when creating PhysX objects. + + See ApexActorSource::setPhysX3Template and ActorSource::getPhysX3Template. +*/ +class PhysX3DescTemplate +{ +public: + /* + For each Name below, there are functions: getName(), setName(), isNameValid(), and getDefaultName(). For example: + + PxDominanceGroup getDominanceGroup() const; + bool setDominanceGroup(PxDominanceGroup); // Returns true iff the passed-in value is valid. (Note, will set the internal values even if they are not valid.) + bool isDominanceGroupValid() const; + PxDominanceGroup getDefaultDominanceGroup() const; + */ + + /* Type Name Validity Condition Default Value */ + // Actor + /** getX(), setX(), getDefaultX(), and isXValid() for X=DominanceGroup (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(physx::PxDominanceGroup, DominanceGroup, (1), 0); + /** getX(), setX(), getDefaultX(), and isXValid() for X=ActorFlags (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(uint8_t, ActorFlags, (1), physx::PxActorFlag::eSEND_SLEEP_NOTIFIES); + /** getX(), setX(), getDefaultX(), and isXValid() for X=OwnerClient (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(physx::PxClientID, OwnerClient, (1), 0); + /** getX(), setX(), getDefaultX(), and isXValid() for X=ClientBehaviorBits (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(uint32_t, ClientBehaviorBits, (1), 0); + /** getX(), setX(), getDefaultX(), and isXValid() for X=ContactReportFlags (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(uint16_t, ContactReportFlags, (1), 0); + /** getX(), setX(), getDefaultX(), and isXValid() for X=UserData (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(void*, UserData, (1), NULL); + /** getX(), setX(), getDefaultX(), and isXValid() for X=Name (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(const char*, Name, (1), NULL); + + // Body + /** getX(), setX(), getDefaultX(), and isXValid() for X=Density (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, Density, (x >= 0.0f), 1.0f); + /** getX(), setX(), getDefaultX(), and isXValid() for X=BodyFlags (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(uint8_t, BodyFlags, (1), 0); + /** getX(), setX(), getDefaultX(), and isXValid() for X=WakeUpCounter (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, WakeUpCounter, (x >= 0.0f), APEX_DEFAULT_WAKE_UP_COUNTER); + /** getX(), setX(), getDefaultX(), and isXValid() for X=LinearDamping (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, LinearDamping, (x >= 0.0f), 0.0f); + /** getX(), setX(), getDefaultX(), and isXValid() for X=AngularDamping (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, AngularDamping, (x >= 0.0f), 0.05f); + /** getX(), setX(), getDefaultX(), and isXValid() for X=MaxAngularVelocity (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, MaxAngularVelocity, (1), 7.0f); + /** getX(), setX(), getDefaultX(), and isXValid() for X=SleepLinearVelocity (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, SleepLinearVelocity, (1), 0.0f); + /** getX(), setX(), getDefaultX(), and isXValid() for X=SolverIterationCount (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(uint32_t, SolverIterationCount, (x >= 1 && x <= 255), 4); + /** getX(), setX(), getDefaultX(), and isXValid() for X=VelocityIterationCount (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(uint32_t, VelocityIterationCount, (x >= 1 && x <= 255), 1); + /** getX(), setX(), getDefaultX(), and isXValid() for X=ContactReportThreshold (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, ContactReportThreshold, (1), PX_MAX_F32); + /** getX(), setX(), getDefaultX(), and isXValid() for X=SleepThreshold (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, SleepThreshold, (1), 0.005f); + + // Shape + /** getX(), setX(), getDefaultX(), and isXValid() for X=ShapeFlags (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(uint8_t, ShapeFlags, (1), physx::PxShapeFlag::eSIMULATION_SHAPE | physx::PxShapeFlag::eSCENE_QUERY_SHAPE | physx::PxShapeFlag::eVISUALIZATION); + /** getX(), setX(), getDefaultX(), and isXValid() for X=ShapeUserData (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(void*, ShapeUserData, (1), NULL); + /** getX(), setX(), getDefaultX(), and isXValid() for X=ShapeName (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(const char*, ShapeName, (1), NULL); + /** getX(), setX(), getDefaultX(), and isXValid() for X=SimulationFilterData (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(physx::PxFilterData, SimulationFilterData, (1), physx::PxFilterData(0, 0, 0, 0)); + /** getX(), setX(), getDefaultX(), and isXValid() for X=QueryFilterData (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(physx::PxFilterData, QueryFilterData, (1), physx::PxFilterData(0, 0, 0, 0)); + /** getX(), setX(), getDefaultX(), and isXValid() for X=ContactOffset (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, ContactOffset, (1), -1.0f); + /** getX(), setX(), getDefaultX(), and isXValid() for X=RestOffset (see APEX_ACTOR_TEMPLATE_PARAM) */ + APEX_ACTOR_TEMPLATE_PARAM(float, RestOffset, (1), PX_MAX_F32); + // Shape materials get explicitly defined API: + /** getMaterials function is non-generic, as it returns two parameters (the materials array and the array size in materialCount) */ + virtual physx::PxMaterial** getMaterials(uint32_t& materialCount) const = 0; + /** setMaterials function is non-generic, as it sets two parameters (the materials array in materialArray and the array size in materialCount) */ + virtual bool setMaterials(physx::PxMaterial** materialArray, uint32_t materialCount) = 0; // Must have non-zero sized array of materials to be valid. + + + /** Use this method to release this object */ + virtual void release() = 0; + +protected: + virtual ~PhysX3DescTemplate() {} +}; // PhysX3DescTemplate + +#undef APEX_ACTOR_TEMPLATE_PARAM + +}} +#endif + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class Asset; + +/** +\brief Base class for APEX module objects. +*/ +class Actor : public ApexInterface +{ +public: + /** + \brief Returns the owning asset + */ + virtual Asset* getOwner() const = 0; + + /** + \brief Returns the range of possible values for physical Lod overwrite + + \param [out] min The minimum lod value + \param [out] max The maximum lod value + \param [out] intOnly Only integers are allowed if this is true, gets rounded to nearest + + \note The max value can change with different graphical Lods + \see Actor::forceLod() + */ + virtual void getLodRange(float& min, float& max, bool& intOnly) const = 0; + + /** + \brief Get current physical lod. + */ + virtual float getActiveLod() const = 0; + + /** + \brief Force an APEX Actor to use a certian physical Lod + + \param [in] lod Overwrite the Lod system to use this Lod. + + \note Setting the lod value to a negative number will turn off the overwrite and proceed with regular Lod computations + \see Actor::getLodRange() + */ + virtual void forceLod(float lod) = 0; + + /** + \brief Ensure that all module-cached data is cached. + */ + virtual void cacheModuleData() const {} + + /** + \brief Selectively enables/disables debug visualization of a specific APEX actor. Default value it true. + */ + virtual void setEnableDebugVisualization(bool state) = 0; + + +protected: + virtual ~Actor() {} // use release() method instead! +}; + +#if PX_PHYSICS_VERSION_MAJOR == 3 +/** +\brief Base class for APEX classes that spawn PhysX SDK Actors +*/ +class ActorSource +{ +public: + /** + \brief Sets the current body template + + User can specify a descriptor template for bodies that this object may create. APEX may customize these suggested settings. + Already created / existing bodies will not be changed if the body template is changed! The body template will only be used for + new bodies created after this is called! + + members that are ignored: + massLocalPose + massSpaceInertia + mass + linearVelocity + angularVelocity + + These fields should be left at their default values as set by the desc constructor. + */ + virtual void setPhysX3Template(const PhysX3DescTemplate*) = 0; + + /** + \brief Retrieve the current body template + */ + virtual bool getPhysX3Template(PhysX3DescTemplate& dest) const = 0; + + /** + \brief Create an PhysX3DescTemplate object to pass into the get/set methods. + */ + virtual PhysX3DescTemplate* createPhysX3DescTemplate() const = 0; +}; + +#endif + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // ACTOR_H diff --git a/APEX_1.4/include/Apex.h b/APEX_1.4/include/Apex.h new file mode 100644 index 00000000..299106d7 --- /dev/null +++ b/APEX_1.4/include/Apex.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef APEX_H +#define APEX_H + +/** +\file +\brief The top level include file for all of the APEX API. + +Include this whenever you want to use anything from the APEX API +in a source file. +*/ + +#include "foundation/Px.h" + +#include "ApexUsingNamespace.h" + + +namespace NvParameterized +{ +class Traits; +class Interface; +class Serializer; +}; + + +#include "foundation/PxPreprocessor.h" +#include "foundation/PxSimpleTypes.h" +#include "foundation/PxAssert.h" +#include "foundation/PxBounds3.h" +#include "foundation/PxVec2.h" +#include "foundation/PxVec3.h" + + +// APEX public API: +// In general, APEX public headers will not be included 'alone', so they +// should not include their prerequisites. + +#include "ApexDefs.h" +#include "ApexDesc.h" +#include "ApexInterface.h" +#include "ApexSDK.h" + +#include "Actor.h" +#include "Context.h" +#include "ApexNameSpace.h" +#include "PhysXObjectDesc.h" +#include "RenderDataProvider.h" +#include "Renderable.h" +#include "AssetPreview.h" +#include "Asset.h" +#include "RenderContext.h" +#include "Scene.h" +#include "ApexSDKCachedData.h" +#include "IProgressListener.h" +#include "Module.h" +#include "IosAsset.h" + +#include "RenderDataFormat.h" +#include "RenderBufferData.h" +#include "UserRenderResourceManager.h" +#include "UserRenderVertexBufferDesc.h" +#include "UserRenderInstanceBufferDesc.h" +#include "UserRenderSpriteBufferDesc.h" +#include "UserRenderIndexBufferDesc.h" +#include "UserRenderBoneBufferDesc.h" +#include "UserRenderResourceDesc.h" +#include "UserRenderSurfaceBufferDesc.h" +#include "UserRenderSurfaceBuffer.h" +#include "UserRenderResource.h" +#include "UserRenderVertexBuffer.h" +#include "UserRenderInstanceBuffer.h" +#include "UserRenderSpriteBuffer.h" +#include "UserRenderIndexBuffer.h" +#include "UserRenderBoneBuffer.h" +#include "UserRenderer.h" + +#include "VertexFormat.h" +#include "RenderMesh.h" +#include "RenderMeshActorDesc.h" +#include "RenderMeshActor.h" +#include "RenderMeshAsset.h" +#include "ResourceCallback.h" +#include "ResourceProvider.h" + +#endif // APEX_H diff --git a/APEX_1.4/include/ApexCudaContextManager.h b/APEX_1.4/include/ApexCudaContextManager.h new file mode 100644 index 00000000..58d13a58 --- /dev/null +++ b/APEX_1.4/include/ApexCudaContextManager.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef APEX_CUDA_CONTEXT_MANAGER_H +#define APEX_CUDA_CONTEXT_MANAGER_H + +/** +\file +\brief The file contains API for PxCudaConextManager public functions +*/ + +#include "foundation/Px.h" +#include "ApexSDK.h" + +namespace physx +{ + class PxCudaContextManager; + class PxCudaContextManagerDesc; +} + +namespace nvidia +{ +namespace apex +{ + +/** + * \brief Ask the NVIDIA control panel which GPU has been selected for use by + * PhysX. Returns -1 if no PhysX capable GPU is found or GPU PhysX has + * been disabled. + */ +APEX_API int CALL_CONV GetSuggestedCudaDeviceOrdinal(PxErrorCallback& errc); + +/** + * \brief Allocate a CUDA Context manager, complete with heaps and task dispatcher. + * You only need one CUDA context manager per GPU device you intend to use for + * CUDA tasks. If mgr is NULL, no profiling of CUDA code will be possible. + */ +APEX_API PxCudaContextManager* CALL_CONV CreateCudaContextManager( + const PxCudaContextManagerDesc& desc, PxErrorCallback& errorCallback); +} +} + +#endif // APEX_CUDA_CONTEXT_MANAGER_H diff --git a/APEX_1.4/include/ApexDefs.h b/APEX_1.4/include/ApexDefs.h new file mode 100644 index 00000000..929d453e --- /dev/null +++ b/APEX_1.4/include/ApexDefs.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef APEX_DEFS_H +#define APEX_DEFS_H + +/*! +\file +\brief Version identifiers and other macro definitions + + This file is intended to be usable without picking up the entire + public APEX API, so it explicitly does not include Apex.h +*/ + +#include "PhysXSDKVersion.h" + +/*! + \def APEX_SDK_VERSION + \brief APEX Framework API version + + Used for making sure you are linking to the same version of the SDK files + that you have included. Should be incremented with every API change. + + \def APEX_SDK_RELEASE + \brief APEX SDK Release version + + Used for conditionally compiling user code based on the APEX SDK release version. + + \def DYNAMIC_CAST + \brief Determines use of dynamic_cast<> by APEX modules + + \def APEX_USE_PARTICLES + \brief Determines use of particle-related APEX modules + + \def APEX_DEFAULT_NO_INTEROP_IMPLEMENTATION + \brief Provide API stubs with no CUDA interop support + + Use this to add default implementations of interop-related interfaces for UserRenderer. +*/ + +#include "foundation/PxPreprocessor.h" + +#define APEX_SDK_VERSION 1 +#define APEX_SDK_RELEASE 0x01040000 + +#if USE_RTTI +#define DYNAMIC_CAST(type) dynamic_cast<type> +#else +#define DYNAMIC_CAST(type) static_cast<type> +#endif + +/// Enables CUDA code +#if defined(EXCLUDE_CUDA) && (EXCLUDE_CUDA > 0) +#define APEX_CUDA_SUPPORT 0 +#else +#define APEX_CUDA_SUPPORT (PX_SUPPORT_GPU_PHYSX) && !(PX_LINUX) +#endif + +/// Enables particles related code +#if !defined(EXCLUDE_PARTICLES) && PX_WINDOWS +#define APEX_USE_PARTICLES 1 +#else +#define APEX_USE_PARTICLES 0 +#endif + +/// Enables code specific for UE4 +#ifndef APEX_UE4 +#define APEX_UE4 0 +#endif + + +#define APEX_DEFAULT_NO_INTEROP_IMPLEMENTATION 1 + + +#endif // APEX_DEFS_H diff --git a/APEX_1.4/include/ApexDesc.h b/APEX_1.4/include/ApexDesc.h new file mode 100644 index 00000000..677d103e --- /dev/null +++ b/APEX_1.4/include/ApexDesc.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef APEX_DESC_H +#define APEX_DESC_H + +/*! +\file +\brief class ApexDesc +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Base class for all APEX Descriptor classes + +A descriptor class of type NxXDesc is typically passed to a createX() function. Descriptors have +several advantages over simply passing a number of explicit parameters to create(): + +- all parameters can have default values so the user only needs to know about the ones he needs to change +- new parameters can be added without changing the user code, along with defaults +- the user and the SDK can validate the parameter's correctness using isValid() +- if creation fails, the user can look at the code of isValid() to see what exactly is not being accepted by the SDK +- some object types can save out their state into descriptors again for serialization + +Care should be taken that derived descriptor classes do not initialize their base class members multiple times, +once in the constructor, and once in setToDefault()! +*/ +class ApexDesc +{ +public: + /** + \brief for standard init of user data member + */ + void* userData; + + /** + \brief constructor sets to default. + */ + PX_INLINE ApexDesc() + { + setToDefault(); + } + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault() + { + userData = 0; + } + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid. + */ + PX_INLINE bool isValid() const + { + return true; + } +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // APEX_DESC_H diff --git a/APEX_1.4/include/ApexInterface.h b/APEX_1.4/include/ApexInterface.h new file mode 100644 index 00000000..42afcb4c --- /dev/null +++ b/APEX_1.4/include/ApexInterface.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef APEX_INTERFACE_H +#define APEX_INTERFACE_H + +/*! +\file +\brief class ApexInterface +*/ + +#include "ApexUsingNamespace.h" +#include "RWLockable.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Base class for all interface classes implemented by APEX SDK + +User callback interfaces should not derive from this class. +*/ +class ApexInterface : public RWLockable +{ +public: + ApexInterface() : userData(NULL) {} + + /** + \brief Release an object instance. + + Calling this will unhook the class and delete it from memory. + You should not keep any reference to this class instance after calling release + */ + virtual void release() = 0; + + /** + \brief User data variable. + + Practical in scenarios where this object has a clear and unique owner, + not so useful in other scenarios. + */ + void* userData; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // APEX_INTERFACE_H diff --git a/APEX_1.4/include/ApexNameSpace.h b/APEX_1.4/include/ApexNameSpace.h new file mode 100644 index 00000000..32c3ca97 --- /dev/null +++ b/APEX_1.4/include/ApexNameSpace.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef APEX_NAME_SPACE_H +#define APEX_NAME_SPACE_H + +#include "ApexUsingNamespace.h" + +/*! +\file +\brief Defines APEX namespace strings + +These are predefined framework namespaces in the named resource provider +*/ + +/*! +\brief A namespace for names of collision groups (CollisionGroup). + +Each name in this namespace must map to a 5-bit integer in the range [0..31] (stored in a void*). +The NRP will not automatically generate release requests for names in this namespace. +*/ +#define APEX_COLLISION_GROUP_NAME_SPACE "NSCollisionGroup" + +/*! +\brief A namespace for names of GroupsMasks + +Each name in this namespace must map to a pointer to a persistent 128-bit GroupsMask type. +The NRP will not automatically generate release requests for names in this namespace. +*/ +#define APEX_COLLISION_GROUP_128_NAME_SPACE "NSCollisionGroup128" + +/*! +\brief A namespace for names of GroupsMasks64 + +Each name in this namespace must map to a pointer to a persistent 64-bit GroupsMask64 type. +The NRP will not automatically generate release requests for names in this namespace. +*/ +#define APEX_COLLISION_GROUP_64_NAME_SPACE "NSCollisionGroup64" + +/*! +\brief A namespace for names of collision group masks + +Each name in this namespace must map to a 32-bit integer (stored in a void*), wherein each +bit represents a collision group (CollisionGroup). The NRP will not automatically generate +release requests for names in this namespace. +*/ +#define APEX_COLLISION_GROUP_MASK_NAME_SPACE "NSCollisionGroupMask" + +/*! +\brief Internal namespace for authorable asset types + +For examples, there are entries in this namespace for "ApexRenderMesh", "NxClothingAsset", +"DestructibleAsset", etc... +The values stored in this namespace are the namespace IDs of the authorable asset types. +So if your module needs to get a pointer to a FooAsset created by module Foo, you can ask +the ApexSDK for that asset's namespace ID. +*/ +#define APEX_AUTHORABLE_ASSETS_TYPES_NAME_SPACE "AuthorableAssetTypes" + +/*! +\brief Internal namespace for parameterized authorable assets +*/ +#define APEX_NV_PARAM_AUTH_ASSETS_TYPES_NAME_SPACE "NvParamAuthorableAssetTypes" + +/*! +\brief A namespace for graphical material names + +Each name in this namespace maps to a pointer to a game-engine defined graphical material data +structure. APEX does not interpret or dereference this pointer in any way. APEX provides this +pointer to the UserRenderResource::setMaterial(void *material) callback to the rendering engine. +This mapping allows APEX assets to refer to game engine materials (e.g.: texture maps and shader +programs) without imposing any limitations on what a game engine graphical material can contain. +The NRP will not automatically generate release requests for names in this namespace. +*/ +#define APEX_MATERIALS_NAME_SPACE "ApexMaterials" + +/*! +\brief A namespace for volumetric rendering material names + +*/ +#define APEX_VOLUME_RENDER_MATERIALS_NAME_SPACE "ApexVolumeRenderMaterials" + + +/*! +\brief A namespace for physical material names + +Each name in this namespace maps to MaterialID, which is a data type defined +by the PhysX SDK. The NRP will not automatically generate release requests for +names in this namespace. +*/ +#define APEX_PHYSICS_MATERIAL_NAME_SPACE "NSPhysicalMaterial" + +/*! +\brief A namespace for custom vertex buffer semantics names + +Each name in this namespace maps to a pointer to a game-engine defined data structure identifying +a custom vertex buffer semantic. APEX does not interpret or dereference this pointer in any way. +APEX provides an array of these pointers in UserRenderVertexBufferDesc::customBuffersIdents, +which is passed the rendering engine when requesting allocation of vertex buffers. +*/ +#define APEX_CUSTOM_VB_NAME_SPACE "NSCustomVBNames" + +#endif // APEX_NAME_SPACE_H diff --git a/APEX_1.4/include/ApexSDK.h b/APEX_1.4/include/ApexSDK.h new file mode 100644 index 00000000..ab888758 --- /dev/null +++ b/APEX_1.4/include/ApexSDK.h @@ -0,0 +1,738 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef APEX_SDK_H +#define APEX_SDK_H + +/*! +\file +\brief APEX SDK classes +*/ + +#include "ApexDefs.h" +#include "ApexUsingNamespace.h" +#include "ApexDesc.h" +#include "ApexInterface.h" + +#include "nvparameterized/NvSerializer.h" +#include "nvparameterized/NvParameterized.h" +#include "nvparameterized/NvParameterizedTraits.h" +#include "Shape.h" + + +namespace RENDER_DEBUG +{ + class RenderDebugInterface; +}; + +namespace physx +{ + class PxFoundation; + class PxCpuDispatcher; + + namespace profile + { + class PxProfileZoneManager; + } + class PxPvd; +} + +//! \brief nvidia namespace +namespace nvidia +{ +//! \brief apex namespace +namespace apex +{ + +class UserRenderResourceManager; +class Scene; +class SceneDesc; +class AssetPreviewScene; +class RenderMeshAsset; +class RenderMeshAssetAuthoring; +class Module; +class PhysXObjectDesc; +class ResourceProvider; +class ResourceCallback; +class RenderDebugInterface; +class Asset; +class AssetAuthoring; +class ApexSDKCachedData; +class RenderMeshActor; + +PX_PUSH_PACK_DEFAULT + +/** +\brief 64-bit mask used for collision filtering between IOSes and Field Samplers. +*/ +class GroupsMask64 +{ +public: + /** + \brief Default constructor. + */ + PX_INLINE GroupsMask64() + { + bits0 = bits1 = 0; + } + + /** + \brief Constructor to set filter data initially. + */ + PX_INLINE GroupsMask64(uint32_t b0, uint32_t b1) : bits0(b0), bits1(b1) {} + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault() + { + *this = GroupsMask64(); + } + + /** \brief Mask bits. */ + uint32_t bits0; + /** \brief Mask bits. */ + uint32_t bits1; +}; + +/** +\brief Collision groups filtering operations. +*/ +struct GroupsFilterOp +{ + /** + \brief Enum of names for group filtering operations. + */ + enum Enum + { + AND, + OR, + XOR, + NAND, + NOR, + NXOR, + SWAP_AND + }; +}; + +/** +\brief Integer values, each representing a unique authorable object class/type +*/ +typedef unsigned int AuthObjTypeID; + +/** +\brief Descriptor class for ApexSDK +*/ +class ApexSDKDesc : public ApexDesc +{ +public: + /** + \brief The PxFoundation you are building with + */ + PxFoundation* foundation; + + /** + \brief The PhysX SDK version you are building with + + A particular APEX build will be against a particular PhysX version except the case physXSDKVersion = 0. + If physXSDKVersion = 0 APEX will be built without PhysX. + Versioning the PhysX API will require versioning of APEX. + */ + uint32_t physXSDKVersion; + +#if PX_PHYSICS_VERSION_MAJOR == 3 + /** + \brief Pointer to the physX sdk (PhysX SDK version specific structure) + */ + PxPhysics* physXSDK; + + /** + \brief Pointer to the cooking interface (PhysX SDK version specific structure) + */ + PxCooking* cooking; +#endif + + /** + \brief Pointer to PVD (optional) + */ + PxPvd* pvd; + + /** + \brief User defined interface for creating renderable resources. + */ + UserRenderResourceManager* renderResourceManager; + + /** + \brief Pointer to a user-callback for unresolved named resources. + + This function will be called by APEX when + an unresolved named resource is requested. The function will be called at most once for each named + resource. The function must directly return the pointer to the resource or NULL. + */ + ResourceCallback* resourceCallback; + + /** + \brief Path to APEX module DLLs (Windows Only) + + If specified, this string will be prepended to the APEX module names prior to calling LoadLibrary() to load them. You can + use this mechanism to ship the APEX module DLLS into their own subdirectory. For example: "APEX/" + */ + const char* dllLoadPath; + + /** + \brief Wireframe material name + + If specified, this string designates the material to use when rendering wireframe data. + It not specified, the default value is "ApexWireframe" + */ + const char* wireframeMaterial; + + /** + \brief Solid material name + + If specified, this string designates the material to use when rendering solid shaded (per vertex color) lit triangles. + If not specified, the default value is "ApexSolidShaded" + */ + const char* solidShadedMaterial; + + /** + \brief Delays material loading + + Any RenderMeshActor will issue callbacks to the ResourceCallback to create one or more materials. This happens either + at actor creation or lazily during updateRenderResource upon necessity. + Additionally it will call UserRenderResourceManager::getMaxBonesPerMaterial for the freshly created material right + after a successful material creation. + If this is set to true, the updateRenderResource calls should not run asynchronously. + */ + bool renderMeshActorLoadMaterialsLazily; + + /** + \brief APEX module DLL name postfix (Windows Only) + + If specified, this string will be appended to the APEX module DLL names prior to calling LoadLibrary() to load them. You can + use this mechanism to load the APEX module DLLS for two different PhysX SDKs in the same process (DCC tools). + + For example, the APEX_Destructible_x86.dll is renamed to APEX_Destructible_x86_PhysX-2.8.4.dll. + dllNamePostfix would be "_PhysX-2.8.4" + */ + const char* dllNamePostfix; + + /** + \brief Application-specific GUID (Windows Only) + + Provide an optional appGuid if you have made local modifications to your APEX DLLs. + Application GUIDs are available from NVIDIA. For non-Windows platforms the appGuid + is ignored. + */ + const char* appGuid; + + + /** + \brief Sets the resource provider's case sensitive mode. + + \note This is a reference to the ResourceProvider string lookups + */ + bool resourceProviderIsCaseSensitive; + + /** + \brief Sets the number of physX object descriptor table entries that are allocated when it gets full. + + */ + uint32_t physXObjDescTableAllocationIncrement; + + /** + \brief Enables warnings upon detection of concurrent access to the APEX SDK + + */ + bool enableConcurrencyCheck; + + /** + \brief constructor sets to default. + */ + PX_INLINE ApexSDKDesc() : ApexDesc() + { + init(); + } + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault() + { + ApexDesc::setToDefault(); + init(); + } + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid + */ + PX_INLINE bool isValid() const + { + bool retVal = ApexDesc::isValid(); + + if (foundation == NULL) + { + return false; + } +#if PX_PHYSICS_VERSION_MAJOR == 3 + if (physXSDK == NULL) + { + return false; + } + if (cooking == NULL) + { + return false; + } + if (physXSDKVersion != PX_PHYSICS_VERSION) + { + return false; + } +#endif + return retVal; + } + +private: + PX_INLINE void init() + { + renderResourceManager = NULL; + foundation = NULL; +#if PX_PHYSICS_VERSION_MAJOR == 3 + physXSDKVersion = PX_PHYSICS_VERSION; + physXSDK = NULL; + cooking = NULL; +#endif + pvd = NULL; + resourceCallback = NULL; + dllLoadPath = NULL; + solidShadedMaterial = "ApexSolidShaded"; + wireframeMaterial = "ApexWireframe"; + renderMeshActorLoadMaterialsLazily = true; + dllNamePostfix = NULL; + appGuid = NULL; + resourceProviderIsCaseSensitive = false; + physXObjDescTableAllocationIncrement = 128; + enableConcurrencyCheck = false; + } +}; + + +/** +\brief These errors are returned by the CreateApexSDK() and ApexSDK::createModule() functions +*/ +enum ApexCreateError +{ + /** + \brief No errors occurred when creating the Physics SDK. + */ + APEX_CE_NO_ERROR = 0, + + /** + \brief Unable to find the libraries. + For statically linked APEX, a module specific instantiate function must be called + prior to the createModule call. + */ + APEX_CE_NOT_FOUND = 1, + + /** + \brief The application supplied a version number that does not match with the libraries. + */ + APEX_CE_WRONG_VERSION = 2, + + /** + \brief The supplied descriptor is invalid. + */ + APEX_CE_DESCRIPTOR_INVALID = 3, + + /** + \brief This module cannot be created by the application, it is created via a parent module use as APEX_Particles or APEX_Legacy + */ + APEX_CE_CREATE_NO_ALLOWED = 4, + +}; + + +/** +\brief The ApexSDK abstraction. Manages scenes and modules. +*/ +class ApexSDK : public ApexInterface +{ +public: + /** + \brief Create an APEX Scene + */ + virtual Scene* createScene(const SceneDesc&) = 0; + + /** + \brief Release an APEX Scene + */ + virtual void releaseScene(Scene*) = 0; + + /** + \brief Create an APEX Asset Preview Scene + */ + virtual AssetPreviewScene* createAssetPreviewScene() = 0; + + /** + \brief Release an APEX Asset Preview Scene + */ + virtual void releaseAssetPreviewScene(AssetPreviewScene* nxScene) = 0; + + /** + \brief Create/Load a module + */ + virtual Module* createModule(const char* name, ApexCreateError* err = NULL) = 0; + +#if PX_PHYSICS_VERSION_MAJOR == 0 + /** + \brief Allocates a CpuDispatcher with a thread pool of the specified number of threads + + If numThreads is zero, the thread pool will use the default number of threads for the + current platform. + */ + virtual physx::PxCpuDispatcher* createCpuDispatcher(uint32_t numThreads = 0) = 0; + /** + \brief Releases a CpuDispatcher + */ + virtual void releaseCpuDispatcher(physx::PxCpuDispatcher& cd) = 0; +#endif + +#if PX_PHYSICS_VERSION_MAJOR == 3 + /** + \brief Return an object describing how APEX is using the PhysX Actor. + \return NULL if PhysX Actor is not owned by APEX. + */ + virtual const PhysXObjectDesc* getPhysXObjectInfo(const PxActor* actor) const = 0; + + /** + \brief Return an object describing how APEX is using the PhysX Shape. + \return NULL if PhysX Shape is not owned by APEX. + */ + virtual const PhysXObjectDesc* getPhysXObjectInfo(const PxShape* shape) const = 0; + + /** + \brief Return an object describing how APEX is using the PhysX Joint. + \return NULL if PhysX Joint is not owned by APEX. + */ + virtual const PhysXObjectDesc* getPhysXObjectInfo(const PxJoint* joint) const = 0; + + /** + \brief Return an object describing how APEX is using the PhysX Cloth. + \return NULL if PhysX Cloth is not owned by APEX. + */ + virtual const PhysXObjectDesc* getPhysXObjectInfo(const PxCloth* cloth) const = 0; + + /** + \brief Returns the cooking interface. + */ + virtual PxCooking* getCookingInterface() = 0; +#endif + + /** + \brief Return the user error callback. + \deprecated Use getErrorCallback() instead. + */ + PX_DEPRECATED virtual PxErrorCallback* getOutputStream() = 0; + + /** + \brief Return the user error callback. + */ + virtual PxErrorCallback* getErrorCallback() const = 0; + + /** + \brief Return the user allocator callback. + */ + virtual PxAllocatorCallback* getAllocator() const = 0; + + /** + \brief Return the named resource provider. + */ + virtual ResourceProvider* getNamedResourceProvider() = 0; + + /** + \brief Return an APEX PxFileBuf instance. For use by APEX + tools and samples, not by APEX internally. Internally, APEX will use an + PxFileBuf directly provided by the user. + */ + virtual PxFileBuf* createStream(const char* filename, PxFileBuf::OpenMode mode) = 0; + + /** + \brief Return a PxFileBuf which reads from a buffer in memory. + */ + virtual PxFileBuf* createMemoryReadStream(const void* mem, uint32_t len) = 0; + + /** + \brief Return a PxFileBuf which writes to memory. + */ + virtual PxFileBuf* createMemoryWriteStream(uint32_t alignment = 0) = 0; + + /** + \brief Return the address and length of the contents of a memory write buffer stream. + */ + virtual const void* getMemoryWriteBuffer(PxFileBuf& stream, uint32_t& len) = 0; + + /** + \brief Release a previously created PxFileBuf used as a read stream + */ + virtual void releaseMemoryReadStream(PxFileBuf& stream) = 0; + + /** + \brief Release a previously created PxFileBuf used as a write stream + */ + virtual void releaseMemoryWriteStream(PxFileBuf& stream) = 0; + +#if PX_PHYSICS_VERSION_MAJOR == 3 + /** + \brief Return the PhysX SDK. + */ + virtual PxPhysics* getPhysXSDK() = 0; +#endif + + /** + \brief Return the number of modules. + */ + virtual uint32_t getNbModules() = 0; + + /** + \brief Return an array of module pointers. + */ + virtual Module** getModules() = 0; + + /** + \brief Release a previously loaded module + */ + virtual void releaseModule(Module* module) = 0; + + /** + \brief Creates an ApexDebugRender interface + */ + virtual RenderDebugInterface* createApexRenderDebug(RENDER_DEBUG::RenderDebugInterface* iface, bool useRemoteDebugVisualization = false) = 0; + + /** + \brief Releases an ApexDebugRender interface + */ + virtual void releaseApexRenderDebug(RenderDebugInterface& debug) = 0; + + /** + \brief Creates an ApexSphereShape interface + */ + virtual SphereShape* createApexSphereShape() = 0; + + /** + \brief Creates an ApexCapsuleShape interface + */ + virtual CapsuleShape* createApexCapsuleShape() = 0; + + /** + \brief Creates an ApexBoxShape interface + */ + virtual BoxShape* createApexBoxShape() = 0; + + /** + \brief Creates an ApexHalfSpaceShape interface + */ + virtual HalfSpaceShape* createApexHalfSpaceShape() = 0; + + /** + \brief Release an Shape interface + */ + virtual void releaseApexShape(Shape& shape) = 0; + + /** + \brief Return the number of assets force loaded by all of the existing APEX modules + */ + virtual uint32_t forceLoadAssets() = 0; + + /** + \brief Get a list of the APEX authorable types. + + The memory for the strings returned is owned by the APEX SDK and should only be read, not written or freed. + Returns false if 'inCount' is not large enough to contain all of the names. + */ + virtual bool getAuthorableObjectNames(const char** authTypeNames, uint32_t& outCount, uint32_t inCount) = 0; + + /** + \brief Get the a pointer to APEX's instance of the ::NvParameterized::Traits class + */ + virtual ::NvParameterized::Traits* getParameterizedTraits() = 0; + + /** + \brief Creates an APEX asset from an AssetAuthoring object. + */ + virtual Asset* createAsset(AssetAuthoring&, const char* name) = 0; + + /** + \brief Creates an APEX asset from a parameterized object. + \note The NvParameterized::Interface object's ownership passes to the asset, if a copy is needed, use the NvParameterized::Interface::copy() method + */ + virtual Asset* createAsset(::NvParameterized::Interface*, const char* name) = 0; + + /** + \brief Release an APEX asset + */ + virtual void releaseAsset(Asset&) = 0; + + /** + \brief Creates an APEX asset authoring object + */ + virtual AssetAuthoring* createAssetAuthoring(const char* authorTypeName) = 0; + + /** + \brief Create an APEX asset authoring object with a name + */ + virtual AssetAuthoring* createAssetAuthoring(const char* authorTypeName, const char* name) = 0; + + /** + \brief Create an APEX asset authoring object from a parameterized object. + */ + virtual AssetAuthoring* createAssetAuthoring(::NvParameterized::Interface*, const char* name) = 0; + + /** + \brief Releases an APEX asset authoring object + */ + virtual void releaseAssetAuthoring(AssetAuthoring&) = 0; + + /** + \brief Returns the scene data cache for actors in the scene + */ + virtual ApexSDKCachedData& getCachedData() const = 0; + + /** + \brief Create a Serialization object + */ + virtual ::NvParameterized::Serializer* createSerializer(::NvParameterized::Serializer::SerializeType type) = 0; + + /** + \brief Create a Serialization object from custom traits + */ + virtual ::NvParameterized::Serializer* createSerializer(::NvParameterized::Serializer::SerializeType type, ::NvParameterized::Traits* traits) = 0; + + /** + \brief Figure out whether a given chunk of data was xml or binary serialized. + To properly detect XML formats, 32 bytes of data are scanned, so dlen should be at least 32 bytes + */ + virtual ::NvParameterized::Serializer::SerializeType getSerializeType(const void* data, uint32_t dlen) = 0; + + /** + \brief Figure out whether a given chunk of data was xml or binary serialized. + */ + virtual ::NvParameterized::Serializer::SerializeType getSerializeType(PxFileBuf& stream) = 0; + + /** + \brief Find native platform for a given chunk of data. + */ + virtual NvParameterized::Serializer::ErrorType getSerializePlatform(PxFileBuf& stream, NvParameterized::SerializePlatform& platform) = 0; + + /** + \brief Find native platform for a given chunk of data. + \note To properly detect platform 64 bytes of data are scanned, so dlen should be at least 64 bytes + */ + virtual NvParameterized::Serializer::ErrorType getSerializePlatform(const void* data, uint32_t dlen, NvParameterized::SerializePlatform& platform) = 0; + + /** + \brief Get current (native) platform + */ + virtual void getCurrentPlatform(NvParameterized::SerializePlatform& platform) const = 0; + + /** + \brief Get platform from human-readable name + \param [in] name platform name + \param [out] platform Platform corresponding to name + \return Success + + Name format: compiler + compiler version (if needed) + architecture. + Supported names: VcWin32, VcWin64, VcXboxOne, GccPs4, AndroidARM, GccLinux32, GccLinux64, GccOsX32, Pib. + */ + virtual bool getPlatformFromString(const char* name, NvParameterized::SerializePlatform& platform) const = 0; + + /** + \brief Get canonical name for platform + */ + virtual const char* getPlatformName(const NvParameterized::SerializePlatform& platform) const = 0; + + /** + \brief Gets NvParameterized debug rendering color parameters. + Modiying NvParameterized debug colors automatically updates color table in debug renderer + */ + virtual ::NvParameterized::Interface* getDebugColorParams() const = 0; + + /** + \brief Gets a string for the material to use when rendering wireframe data. + */ + virtual const char* getWireframeMaterial() = 0; + + /** + \brief Gets a string for the material to use when rendering solid shaded (per vertex color) lit triangles. + */ + virtual const char* getSolidShadedMaterial() = 0; + + /** + \brief Enable or disable the APEX module-specific stat collection (some modules can be time consuming) + */ + virtual void setEnableApexStats(bool enableApexStats) = 0; + + /** + \brief Enable or disable the APEX concurrent access check + */ + virtual void setEnableConcurrencyCheck(bool enableConcurrencyChecks) = 0; + + /** + \brief Returns current setting for APEX concurrent access check + */ + virtual bool isConcurrencyCheckEnabled() = 0; + +protected: + virtual ~ApexSDK() {} + +}; + +/** +\def APEX_API +\brief Export the function declaration from its DLL +*/ + +/** +\def CALL_CONV +\brief Use C calling convention, required for exported functions +*/ + +PX_POP_PACK + +#ifdef CALL_CONV +#undef CALL_CONV +#endif + +#if PX_WINDOWS_FAMILY + +#define APEX_API extern "C" __declspec(dllexport) +#define CALL_CONV __cdecl +#else +#define APEX_API extern "C" +#define CALL_CONV /* void */ +#endif + +/** +\brief Global function to create the SDK object. APEX_SDK_VERSION must be passed for the APEXsdkVersion. +*/ +APEX_API ApexSDK* CALL_CONV CreateApexSDK( const ApexSDKDesc& desc, + ApexCreateError* errorCode = NULL, + uint32_t APEXsdkVersion = APEX_SDK_VERSION, + PxAllocatorCallback* alloc = 0); + +/** +\brief Returns global SDK pointer. +*/ +APEX_API ApexSDK* CALL_CONV GetApexSDK(); + +} +} // end namespace nvidia::apex + +#endif // APEX_SDK_H diff --git a/APEX_1.4/include/ApexSDKCachedData.h b/APEX_1.4/include/ApexSDKCachedData.h new file mode 100644 index 00000000..2009280c --- /dev/null +++ b/APEX_1.4/include/ApexSDKCachedData.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef APEX_SDKCACHED_DATA_H +#define APEX_SDKCACHED_DATA_H + +/*! +\file +\brief classes ModuleCachedData, ApexSDKCachedData +*/ + +#include "ApexSDK.h" + +namespace NvParameterized +{ +class Interface; +}; + +namespace nvidia +{ +namespace apex +{ + + +/** +\brief Cached data is stored per-module. +*/ +class ModuleCachedData +{ +public: + /** + * \brief Retreives the cached data for the asset, if it exists. + * + * Otherwise returns NULL. + */ + virtual ::NvParameterized::Interface* getCachedDataForAssetAtScale(Asset& asset, const PxVec3& scale) = 0; + + /** + * \brief Serializes the cooked data for a single asset into a stream. + */ + virtual PxFileBuf& serializeSingleAsset(Asset& asset, PxFileBuf& stream) = 0; + + /** + * \brief Deserializes the cooked data for a single asset from a stream. + */ + virtual PxFileBuf& deserializeSingleAsset(Asset& asset, PxFileBuf& stream) = 0; +}; + +/** +\brief A method for storing actor data in a scene +*/ +class ApexSDKCachedData +{ +public: + /** + * \brief Retreives the scene cached data for the actor, if it exists. + * + * Otherwise returns NULL. + */ + virtual ModuleCachedData* getCacheForModule(AuthObjTypeID moduleID) = 0; + + /** + * \brief Save cache configuration to a stream + */ + virtual PxFileBuf& serialize(PxFileBuf&) const = 0; + + /** + * \brief Load cache configuration from a stream + */ + virtual PxFileBuf& deserialize(PxFileBuf&) = 0; + + /** + * \brief Clear data + */ + virtual void clear(bool force = true) = 0; + +protected: + ApexSDKCachedData() {} + virtual ~ApexSDKCachedData() {} +}; + +} +} // end namespace nvidia::apex + + +#endif // APEX_SDKCACHED_DATA_H diff --git a/APEX_1.4/include/ApexSDKVersionString.h b/APEX_1.4/include/ApexSDKVersionString.h new file mode 100644 index 00000000..a62d0a23 --- /dev/null +++ b/APEX_1.4/include/ApexSDKVersionString.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef APEX_SDKVERSION_STRING_H +#define APEX_SDKVERSION_STRING_H + +/*! +\file +\brief APEX SDK versioning definitions +*/ + +#include "foundation/PxPreprocessor.h" +#include "ApexDefs.h" + +//! \brief physx namespace +namespace nvidia +{ +//! \brief apex namespace +namespace apex +{ + +/** +\brief These values are used to select version string GetApexSDKVersionString function should return +*/ +enum ApexSDKVersionString +{ + /** + \brief APEX version + */ + VERSION = 0, + /** + \brief APEX build changelist + */ + CHANGELIST = 1, + /** + \brief APEX tools build changelist + */ + TOOLS_CHANGELIST = 2, + /** + \brief APEX branch used to create build + */ + BRANCH = 3, + /** + \brief Time at which the build was created + */ + BUILD_TIME = 4, + /** + \brief Author of the build + */ + AUTHOR = 5, + /** + \brief Reason to prepare the build + */ + REASON = 6 +}; + +/** +\def APEX_API +\brief Export the function declaration from its DLL +*/ + +/** +\def CALL_CONV +\brief Use C calling convention, required for exported functions +*/ + +#ifdef CALL_CONV +#undef CALL_CONV +#endif + +#if PX_WINDOWS_FAMILY +#define APEX_API extern "C" __declspec(dllexport) +#define CALL_CONV __cdecl +#else +#define APEX_API extern "C" +#define CALL_CONV /* void */ +#endif + +/** +\brief Returns version strings +*/ +APEX_API const char* CALL_CONV GetApexSDKVersionString(ApexSDKVersionString versionString); + +} +} // end namespace nvidia::apex + +#endif // APEX_SDKVERSION_STRING_H diff --git a/APEX_1.4/include/ApexUsingNamespace.h b/APEX_1.4/include/ApexUsingNamespace.h new file mode 100644 index 00000000..b2fde0b3 --- /dev/null +++ b/APEX_1.4/include/ApexUsingNamespace.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef APEX_USING_NAMESPACE_H +#define APEX_USING_NAMESPACE_H + +#include "foundation/Px.h" +#include "ApexDefs.h" + +#define FORWARD_DECLARATION_AND_USING(T, X) \ + namespace physx \ + { \ + T X ; \ + }; \ + +FORWARD_DECLARATION_AND_USING(class, PxActor); +FORWARD_DECLARATION_AND_USING(class, PxBase); +FORWARD_DECLARATION_AND_USING(class, PxBoxGeometry); +FORWARD_DECLARATION_AND_USING(class, PxCapsuleGeometry); +FORWARD_DECLARATION_AND_USING(class, PxCloth); +FORWARD_DECLARATION_AND_USING(class, PxCooking); +FORWARD_DECLARATION_AND_USING(struct, PxConvexFlag); +FORWARD_DECLARATION_AND_USING(class, PxConvexMesh); +FORWARD_DECLARATION_AND_USING(class, PxConvexMeshGeometry); +FORWARD_DECLARATION_AND_USING(struct, PxDebugPoint); +FORWARD_DECLARATION_AND_USING(struct, PxDebugLine); +FORWARD_DECLARATION_AND_USING(struct, PxDebugTriangle); +FORWARD_DECLARATION_AND_USING(struct, PxDebugText); +FORWARD_DECLARATION_AND_USING(struct, PxFilterData); +FORWARD_DECLARATION_AND_USING(struct, PxFilterFlag); +FORWARD_DECLARATION_AND_USING(class, PxGeometry); +FORWARD_DECLARATION_AND_USING(struct, PxGeometryType); +FORWARD_DECLARATION_AND_USING(class, PxJoint); +FORWARD_DECLARATION_AND_USING(class, PxMaterial); +FORWARD_DECLARATION_AND_USING(struct, PxPairFlag); +FORWARD_DECLARATION_AND_USING(class, PxParticleBase); +FORWARD_DECLARATION_AND_USING(class, PxParticleFluid); +FORWARD_DECLARATION_AND_USING(class, PxParticleSystem); +FORWARD_DECLARATION_AND_USING(class, PxPhysics); +FORWARD_DECLARATION_AND_USING(struct, PxQueryFilterData); +FORWARD_DECLARATION_AND_USING(struct, PxQueryFlag); +FORWARD_DECLARATION_AND_USING(struct, PxQueryHit); +FORWARD_DECLARATION_AND_USING(struct, PxQueryHitType); +FORWARD_DECLARATION_AND_USING(class, PxRenderBuffer); +FORWARD_DECLARATION_AND_USING(class, PxRigidActor); +FORWARD_DECLARATION_AND_USING(class, PxRigidBody); +FORWARD_DECLARATION_AND_USING(struct, PxRigidBodyFlag); +FORWARD_DECLARATION_AND_USING(class, PxRigidDynamic); +FORWARD_DECLARATION_AND_USING(class, PxSimulationEventCallback); +FORWARD_DECLARATION_AND_USING(class, PxContactModifyCallback); +FORWARD_DECLARATION_AND_USING(class, PxScene); +FORWARD_DECLARATION_AND_USING(class, PxShape); +FORWARD_DECLARATION_AND_USING(struct, PxShapeFlag); +FORWARD_DECLARATION_AND_USING(class, PxSphereGeometry); +FORWARD_DECLARATION_AND_USING(class, PxTriangleMesh); +FORWARD_DECLARATION_AND_USING(class, PxTriangleMeshGeometry); + +namespace physx +{ + namespace shdfnd {} + using namespace shdfnd; + + namespace general_PxIOStream2 + { + class PxFileBuf; + } +} + +namespace nvidia +{ + namespace apex {} + using namespace apex; + + using namespace physx; + using namespace physx::shdfnd; + using namespace physx::general_PxIOStream2; +}; + + + +#endif // APEX_USING_NAMESPACE_H diff --git a/APEX_1.4/include/Asset.h b/APEX_1.4/include/Asset.h new file mode 100644 index 00000000..83ee785e --- /dev/null +++ b/APEX_1.4/include/Asset.h @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef ASSET_H +#define ASSET_H + +/*! +\file +\brief class Asset +*/ + +#include "ApexInterface.h" +#include "ApexSDK.h" +#include "AssetPreviewScene.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/// Usual typedef +typedef const char* PlatformTag; + +class Actor; +class AssetPreview; + +/** +\brief Base class of all APEX assets +*/ +class Asset : public ApexInterface +{ +public: + /** + * \brief Returns the name of this deserialized asset + */ + virtual const char* getName() const = 0; + + /** + * \brief Returns the ID of the asset's authorable object type. + * + * Every asset will correspond to an APEX authorable object type. + * The module must register those types with the SDK at startup. + */ + virtual AuthObjTypeID getObjTypeID() const = 0; + + /** + * \brief Returns the name of this asset's authorable object type + */ + virtual const char* getObjTypeName() const = 0; + + /** + * \brief Returns the number of assets force loaded by all of + * this asset's named asset references + */ + virtual uint32_t forceLoadAssets() = 0; + + /** + * \brief Returns the default actor descriptor NvParamaterized interface + * Memory ownership stays with this asset. The user may modify the interface values, but they will not persist past another acll to 'getDefaultActorDesc' + * Typically used to create an actor after making small local editing changes. + */ + virtual ::NvParameterized::Interface* getDefaultActorDesc() = 0; + + /** + * \brief Returns the default AssetPreview descriptor NvParamaterized interface + */ + virtual ::NvParameterized::Interface* getDefaultAssetPreviewDesc() = 0; + + /** + * \brief Returns the asset's NvParamaterized interface + * This cannot be directly modified! It is read only to the user. + */ + virtual const ::NvParameterized::Interface* getAssetNvParameterized() const = 0; + + /** + * \brief Creates an Actor representing the Asset in a Scene + */ + virtual Actor* createApexActor(const ::NvParameterized::Interface& actorParams, Scene& apexScene) = 0; + + /** + * \brief Creates an Asset Preview for the asset. + */ + virtual AssetPreview* createApexAssetPreview(const ::NvParameterized::Interface& params, AssetPreviewScene* previewScene) = 0; + + /** + * \brief Releases the ApexAsset but returns the NvParameterized::Interface and *ownership* to the caller. + */ + virtual NvParameterized::Interface* releaseAndReturnNvParameterizedInterface(void) = 0; + + /** + * \brief Returns true if the asset is in a state that is valid for creating an actor. + * \param actorParams parameters of actor to create + * \returns true if call to createApexActor will return true on inputs, false otherwise + */ + virtual bool isValidForActorCreation(const ::NvParameterized::Interface& actorParams, Scene& /*apexScene*/) const = 0; + + /** + * \brief Returns true if the parameterized object of the asset has been modified. + * + * This flag will be reset once the parameterized object has been serialized again. + */ + virtual bool isDirty() const = 0; + +protected: + virtual ~Asset() {}; // illegal, do not call +}; + +/** +\brief base class of all APEX asset authoring classes +*/ +class AssetAuthoring : public ApexInterface +{ +public: + /** + * \brief Returns the name of asset author + */ + virtual const char* getName() const = 0; + + /** + * \brief Returns the name of this APEX authorable object type + */ + virtual const char* getObjTypeName() const = 0; + + /** + * \brief Prepares a fully authored Asset Authoring object for a specified platform + */ + virtual bool prepareForPlatform(nvidia::apex::PlatformTag) = 0; + + /** + * \brief Returns the asset's NvParameterized interface, may return NULL + */ + virtual ::NvParameterized::Interface* getNvParameterized() const = 0; + + /** + * \brief Releases the ApexAsset but returns the NvParameterized::Interface and *ownership* to the caller. + */ + virtual NvParameterized::Interface* releaseAndReturnNvParameterizedInterface(void) = 0; + + /** + * \brief Generates a string that is stored in the asset with all the relevant information about the build + * + * \param toolName The name of the tool with proper casing, i.e. "Clothing Tool". + * \param toolVersion The version of the tool as a string, can be NULL. + * \param toolChangelist The CL# of the tool, will use internal tools directory CL if 0 + */ + virtual void setToolString(const char* toolName, const char* toolVersion, uint32_t toolChangelist) = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // ASSET_H diff --git a/APEX_1.4/include/AssetPreview.h b/APEX_1.4/include/AssetPreview.h new file mode 100644 index 00000000..8b0b100a --- /dev/null +++ b/APEX_1.4/include/AssetPreview.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef ASSET_PREVIEW_H +#define ASSET_PREVIEW_H + +/*! +\file +\brief class AssetPreview +*/ + +#include "ApexInterface.h" +#include "Renderable.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Base class of all APEX asset previews + + The preview is a lightweight Renderable instance which can be + rendered without having to create an ApexScene. It is intended to be + used by level editors to place assets within a level. +*/ +class AssetPreview : public ApexInterface, public Renderable +{ +public: + + /** + \brief Set the preview instance's world pose. This may include scaling. + */ + virtual void setPose(const PxMat44& pose) = 0; + + /** + \brief Get the preview instance's world pose. + + \note can't return by reference as long as the internal representation is not identical. + */ + virtual const PxMat44 getPose() const = 0; +protected: + AssetPreview() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // ASSET_PREVIEW_H diff --git a/APEX_1.4/include/AssetPreviewScene.h b/APEX_1.4/include/AssetPreviewScene.h new file mode 100644 index 00000000..721787f8 --- /dev/null +++ b/APEX_1.4/include/AssetPreviewScene.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef ASSET_PREVIEW_SCENE_H +#define ASSET_PREVIEW_SCENE_H + +/*! +\file +\brief classes Scene, SceneStats, SceneDesc +*/ + +#include "ApexDesc.h" +#include "Renderable.h" +#include "Context.h" +#include "foundation/PxVec3.h" +#include <ApexDefs.h> + +#if PX_PHYSICS_VERSION_MAJOR == 3 +#include "PxFiltering.h" +#endif +namespace physx +{ + class PxActor; + class PxScene; + class PxRenderBuffer; + + class PxCpuDispatcher; + class PxGpuDispatcher; + class PxTaskManager; + class PxBaseTask; +} + +namespace NvParameterized +{ +class Interface; +} + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + + +/** +\brief An APEX class for +*/ +class AssetPreviewScene : public ApexInterface +{ +public: + /** + \brief Sets the view matrix. Should be called whenever the view matrix needs to be updated. + */ + virtual void setCameraMatrix(const PxMat44& viewTransform) = 0; + + /** + \brief Returns the view matrix set by the user for the given viewID. + */ + virtual PxMat44 getCameraMatrix() const = 0; + + /** + \brief Sets whether the asset preview should simply show asset names or many other parameter values + */ + virtual void setShowFullInfo(bool showFullInfo) = 0; + + /** + \brief Get the bool which determines whether the asset preview shows just asset names or parameter values + */ + virtual bool getShowFullInfo() const = 0; +}; + + +PX_POP_PACK +} +} // end namespace nvidia::apex + +#endif // ASSET_PREVIEW_SCENE_H diff --git a/APEX_1.4/include/Context.h b/APEX_1.4/include/Context.h new file mode 100644 index 00000000..5f144f70 --- /dev/null +++ b/APEX_1.4/include/Context.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CONTEXT_H +#define CONTEXT_H + +/*! +\file +\brief class Context +*/ + +#include "ApexInterface.h" + +namespace nvidia +{ +namespace apex +{ + +class Renderable; +class RenderableIterator; + +PX_PUSH_PACK_DEFAULT + +/** +\brief A container for Actors +*/ +class Context +{ +public: + /** + \brief Removes all actors from the context and releases them + */ + virtual void removeAllActors() = 0; + + /** + \brief Create an iterator for all renderables in this context + */ + virtual RenderableIterator* createRenderableIterator() = 0; + + /** + \brief Release a renderable iterator + + Equivalent to calling the iterator's release method. + */ + virtual void releaseRenderableIterator(RenderableIterator&) = 0; + +protected: + virtual ~Context() {} +}; + +/** +\brief Iterate over all renderable Actors in an Context + +An RenderableIterator is a lock-safe iterator over all renderable +Actors in an Context. Actors which are locked are skipped in the initial +pass and deferred till the end. The returned Renderable is locked by the +iterator and remains locked until you call getNext(). + +The RenderableIterator is also deletion safe. If an actor is deleted +from the Context in another thread, the iterator will skip that actor. + +An RenderableIterator should not be held for longer than a single simulation +step. It should be allocated on demand and released after use. +*/ +class RenderableIterator : public ApexInterface +{ +public: + /** + \brief Return the first renderable in an Context + */ + virtual Renderable* getFirst() = 0; + /** + \brief Return the next unlocked renderable in an Context + */ + virtual Renderable* getNext() = 0; + /** + \brief Refresh the renderable actor list for this context + + This function is only necessary if you believe actors have been added or + deleted since the iterator was created. + */ + virtual void reset() = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // CONTEXT_H diff --git a/APEX_1.4/include/ConvexHullMethod.h b/APEX_1.4/include/ConvexHullMethod.h new file mode 100644 index 00000000..e6c9dae9 --- /dev/null +++ b/APEX_1.4/include/ConvexHullMethod.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CONVEX_HULL_METHOD_H +#define CONVEX_HULL_METHOD_H + +/*! +\file +\brief Misc utility classes +*/ + +#include "Module.h" +#include "foundation/PxMath.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + + +/** +\brief Method by which chunk mesh collision hulls are generated. +*/ +struct ConvexHullMethod +{ + /** + \brief Enum of methods by which chunk mesh collision hulls are generated. + */ + enum Enum + { + USE_6_DOP, + USE_10_DOP_X, + USE_10_DOP_Y, + USE_10_DOP_Z, + USE_14_DOP_XY, + USE_14_DOP_YZ, + USE_14_DOP_ZX, + USE_18_DOP, + USE_26_DOP, + WRAP_GRAPHICS_MESH, + CONVEX_DECOMPOSITION, + + COUNT + }; +}; + + + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // CONVEX_HULL_METHOD_H diff --git a/APEX_1.4/include/CudaTestManager.h b/APEX_1.4/include/CudaTestManager.h new file mode 100644 index 00000000..4ca921ac --- /dev/null +++ b/APEX_1.4/include/CudaTestManager.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CUDA_TEST_MANAGER_H +#define CUDA_TEST_MANAGER_H + +/*! +\file +\brief classes CudaTestManager +*/ + +#include <ApexUsingNamespace.h> + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** + */ + + /** +\brief A class that set information on kernels should be tested and give directive for creation ApexCudaTestContext +*/ +class CudaTestManager +{ +public: + /** + \brief Set the write path + */ + virtual void setWritePath(const char* path) = 0; + + /** + \brief Set write for function + */ + virtual void setWriteForFunction(const char* functionName, const char* moduleName) = 0; + + /** + \brief Set the maximum number of frames + */ + virtual void setMaxSamples(uint32_t maxFrames) = 0; + + /** + \brief Set the frames + */ + virtual void setFrames(uint32_t numFrames, const uint32_t* frames) = 0; + + /** + \brief Set the frame period + */ + virtual void setFramePeriod(uint32_t period) = 0; + + /** + \brief Set maximal count of kernel calls per frame + */ + virtual void setCallPerFrameMaxCount(uint32_t cpfMaxCount) = 0; + + /** + \brief Set flag for writing kernel context for kernel that return not successful error code + */ + virtual void setWriteForNotSuccessfulKernel(bool flag) = 0; + + /** + \brief Run a kernel + */ + virtual bool runKernel(const char* path) = 0; +}; + +PX_POP_PACK + +} +} + +#endif // CUDA_TEST_MANAGER_H + diff --git a/APEX_1.4/include/Curve.h b/APEX_1.4/include/Curve.h new file mode 100644 index 00000000..51c114f5 --- /dev/null +++ b/APEX_1.4/include/Curve.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CURVE_H +#define CURVE_H + +#include "Apex.h" +#include "nvparameterized/NvParameterized.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** + \brief A trivial templatized math vector type for pairs. +*/ +template <typename T> +struct Vec2T +{ + /** + \brief Constructor that takes 0, 1, or 2 parameters to initialize the pair + */ + Vec2T(T _x = T(), T _y = T()) : x(_x), y(_y) { } + + /** + \brief The first element in the pair + */ + T x; + + /** + \brief The second element in the pair + */ T y; + + /** + \brief Overloading the subscript operator to access the members of the pair + */ + T& operator[](uint32_t ndx) + { + PX_ASSERT(ndx < 2); + return ((T*)&x)[ndx]; + } +}; + +/** +\brief Vec2R is a helpful typedef for a pair of 32bit floats. +*/ +typedef Vec2T<float> Vec2R; + +/** + The Curve is a class for storing control points on a curve and evaluating the results later. +*/ +class Curve +{ +public: + virtual ~Curve() {} + + /** + Retrieve the output Y for the specified input x, based on the properties of the stored curve described + by mControlPoints. + */ + virtual float evaluate(float x) const = 0; + + /** + Add a control point to the list of control points, returning the index of the new point. + */ + virtual uint32_t addControlPoint(const Vec2R& controlPoint) = 0; + + /** + Add a control points to the list of control points. Assuming the + hPoints points to a list of vec2s + */ + virtual void addControlPoints(::NvParameterized::Interface* param, ::NvParameterized::Handle& hPoints) = 0; + + /** + Locates the control points that contain x, placing the resulting control points in the two + out parameters. Returns true if the points were found, false otherwise. If the points were not + found, the output variables are untouched + */ + virtual bool calculateControlPoints(float x, Vec2R& outXPoints, Vec2R& outYPoints) const = 0; + + /** + Locates the first control point with x larger than xValue or the nimber of control points if such point doesn't exist + */ + virtual uint32_t calculateFollowingControlPoint(float xValue) const = 0; + + ///get the array of control points + virtual const Vec2R* getControlPoints(uint32_t& outCount) const = 0; +}; + +PX_POP_PACK + +} +} // namespace apex + +#endif // CURVE_H diff --git a/APEX_1.4/include/CustomBufferIterator.h b/APEX_1.4/include/CustomBufferIterator.h new file mode 100644 index 00000000..677ed534 --- /dev/null +++ b/APEX_1.4/include/CustomBufferIterator.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CUSTOM_BUFFER_ITERATOR_H +#define CUSTOM_BUFFER_ITERATOR_H + +/*! +\file +\brief class CustomBufferIterator +*/ + +#include "RenderMesh.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief This class is used to access specific elements in an untyped chunk of memory +*/ +class CustomBufferIterator +{ +public: + /** + \brief Returns the memory start of a specific vertex. + + All custom buffers are stored interleaved, so this is also the memory start of the first attribute of this vertex. + */ + virtual void* getVertex(uint32_t triangleIndex, uint32_t vertexIndex) const = 0; + + /** + \brief Returns the index of a certain custom buffer. + + \note This is constant throughout the existence of this class. + */ + virtual int32_t getAttributeIndex(const char* attributeName) const = 0; + + /** + \brief Returns a pointer to a certain attribute of the specified vertex/triangle. + + \param [in] triangleIndex Which triangle + \param [in] vertexIndex Which of the vertices of this triangle (must be either 0, 1 or 2) + \param [in] attributeName The name of the attribute you wish the data for + \param [out] outFormat The format of the attribute, reinterpret_cast the void pointer accordingly. + */ + virtual void* getVertexAttribute(uint32_t triangleIndex, uint32_t vertexIndex, const char* attributeName, RenderDataFormat::Enum& outFormat) const = 0; + + /** + \brief Returns a pointer to a certain attribute of the specified vertex/triangle. + + \note This is the faster method than the one above since it won't do any string comparisons + + \param [in] triangleIndex Which triangle + \param [in] vertexIndex Which of the vertices of this triangle (must be either 0, 1 or 2) + \param [in] attributeIndex The indexof the attribute you wish the data for (use CustomBufferIterator::getAttributeIndex to find the index to a certain attribute name + \param [out] outFormat The format of the attribute, reinterpret_cast the void pointer accordingly. + \param [out] outName The name associated with the attribute + */ + virtual void* getVertexAttribute(uint32_t triangleIndex, uint32_t vertexIndex, uint32_t attributeIndex, RenderDataFormat::Enum& outFormat, const char*& outName) const = 0; + +protected: + CustomBufferIterator() {} + virtual ~CustomBufferIterator() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // CUSTOM_BUFFER_ITERATOR_H diff --git a/APEX_1.4/include/IProgressListener.h b/APEX_1.4/include/IProgressListener.h new file mode 100644 index 00000000..ddeef943 --- /dev/null +++ b/APEX_1.4/include/IProgressListener.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef IPROGRESS_LISTENER_H +#define IPROGRESS_LISTENER_H + +/*! +\file +\brief class IProgressListener +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +//! \brief User-provided class for following the progress of a task +class IProgressListener +{ +public: + //! \brief APEX calls this method to update the progress of a task + virtual void setProgress(int progress, const char* taskName = NULL) = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // IPROGRESS_LISTENER_H diff --git a/APEX_1.4/include/IosAsset.h b/APEX_1.4/include/IosAsset.h new file mode 100644 index 00000000..4245a0ec --- /dev/null +++ b/APEX_1.4/include/IosAsset.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef IOS_ASSET_H +#define IOS_ASSET_H + +/*! +\file +\brief class IosAsset +*/ + +#include "Asset.h" + +namespace nvidia +{ +namespace apex +{ + +class Scene; +class Actor; + +class IofxAsset; + +PX_PUSH_PACK_DEFAULT + +/** +\brief The base class of all Instanced Object Simulation classes +*/ +class IosAsset : public Asset +{ +public: + //! \brief create a generic IOS Actor in a specific Scene + virtual Actor* createIosActor(Scene& scene, IofxAsset* iofxAsset) = 0; + //! \brief release a generic IOS Actor + virtual void releaseIosActor(Actor& actor) = 0; + //! \brief get supports density + virtual bool getSupportsDensity() const = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // IOS_ASSET_H diff --git a/APEX_1.4/include/Lock.h b/APEX_1.4/include/Lock.h new file mode 100644 index 00000000..260f6721 --- /dev/null +++ b/APEX_1.4/include/Lock.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + + +#ifndef LOCK_H +#define LOCK_H + +/*! +\file +\brief classes PxSceneReadLock, PxSceneWriteLock +*/ + +#include "ApexInterface.h" + +namespace nvidia +{ +namespace apex +{ + +/** +\brief RAII wrapper for the Scene read lock. + +Use this class as follows to lock the scene for reading by the current thread +for the duration of the enclosing scope: + + ReadLock lock(sceneRef); + +\see Scene::apexacquireReadLock(), Scene::apexUnacquireReadLock(), SceneDesc::useRWLock +*/ +class ReadLock +{ + ReadLock(const ReadLock&); + ReadLock& operator=(const ReadLock&); + +public: + + /** + \brief Constructor + \param lockable The object to lock for reading + \param file Optional string for debugging purposes + \param line Optional line number for debugging purposes + */ + ReadLock(const ApexInterface& lockable, const char* file=NULL, uint32_t line=0) + : mLockable(lockable) + { + mLockable.acquireReadLock(file, line); + } + + ~ReadLock() + { + mLockable.releaseReadLock(); + } + +private: + + const ApexInterface& mLockable; +}; + +/** +\brief RAII wrapper for the Scene write lock. + +Use this class as follows to lock the scene for writing by the current thread +for the duration of the enclosing scope: + + WriteLock lock(sceneRef); + +\see Scene::apexacquireWriteLock(), Scene::apexUnacquireWriteLock(), SceneDesc::useRWLock +*/ +class WriteLock +{ + WriteLock(const WriteLock&); + WriteLock& operator=(const WriteLock&); + +public: + + /** + \brief Constructor + \param lockable The object to lock for writing + \param file Optional string for debugging purposes + \param line Optional line number for debugging purposes + */ + WriteLock(const ApexInterface& lockable, const char* file=NULL, uint32_t line=0) + : mLockable(lockable) + { + mLockable.acquireWriteLock(file, line); + } + + ~WriteLock() + { + mLockable.releaseWriteLock(); + } + +private: + const ApexInterface& mLockable; +}; + + +} // namespace apex +} // namespace nvidia + +/** +\brief Lock an object for writing by the current thread for the duration of the enclosing scope. +*/ +#define WRITE_LOCK(LOCKABLE) nvidia::apex::WriteLock __WriteLock(LOCKABLE, __FILE__, __LINE__); +/** +\brief Lock an object for reading by the current thread for the duration of the enclosing scope. +*/ +#define READ_LOCK(LOCKABLE) nvidia::apex::ReadLock __ReadLock(LOCKABLE, __FILE__, __LINE__); + +/** @} */ +#endif diff --git a/APEX_1.4/include/MirrorScene.h b/APEX_1.4/include/MirrorScene.h new file mode 100644 index 00000000..04a424d1 --- /dev/null +++ b/APEX_1.4/include/MirrorScene.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MIRROR_SCENE_H + +#define MIRROR_SCENE_H + +/*! +\file +\brief classes MirrorScene, MirrorScene::MirrorFilter +*/ + +#include "ApexDefs.h" +#include "ApexUsingNamespace.h" +#include "foundation/PxPreprocessor.h" + + +namespace nvidia +{ + namespace apex + { + + /** + \brief MirrorScene is used to create a selected mirrored copy of a primary scene. Works only with PhysX 3.x + */ + class MirrorScene + { + public: + /** + \brief MirrorFilter is a callback interface implemented by the application to confirm which actors and shapes are, or are not, replicated into the mirrored scene + */ + class MirrorFilter + { + public: + /** + \brief The application returns true if this actor should be mirrored into the secondary mirrored scene. + + \param[in] actor A const reference to the actor in the primary scene to be considered mirrored into the secondary scene. + */ + virtual bool shouldMirror(const PxActor &actor) = 0; + + /** + \brief The application returns true if this shape should be mirrored into the secondary mirrored scene. + + \param[in] shape A const reference to the shape in the primary scene to be considered mirrored into the secondary scene. + */ + virtual bool shouldMirror(const PxShape &shape) = 0; + + /** + \brief Affords the application with an opportunity to modify the contents/state of the shape before is placed into the mirrored scene. + + \param[in] shape A reference to the shape that is about to be placed into the mirrored scene. + */ + virtual void reviseMirrorShape(physx::PxShape &shape) = 0; + + /** + \brief Affords the application with an opportunity to modify the contents/state of the actor before is placed into the mirrored scene. + + \param[in] actor A reference to the actor that is about to be placed into the mirrored scene + */ + virtual void reviseMirrorActor(physx::PxActor &actor) = 0; + }; + + /** + \brief SynchronizePrimaryScene updates the positions of the objects around the camera relative to the static and dynamic distances specified + These objects are then put in a thread safe queue to be processed when the mirror scene synchronize is called + + \param[in] cameraPos The current position of the camera relative to where objects are being mirrored + */ + virtual void synchronizePrimaryScene(const PxVec3 &cameraPos) = 0; + + /** + \brief Processes the updates to get this mirrored scene to reflect the subset of the + primary scene that is being mirrored. Completely thread safe, assumes that + the primary scene and mirrored scene are most likely being run be completely + separate threads. + */ + virtual void synchronizeMirrorScene(void) = 0; + + /** + \brief Releases the MirrorScene class and all associated mirrored objects; it is important to not that this does *not* release + the actual APEX scnee; simply the MirrorScene helper class. + */ + virtual void release(void) = 0; + + }; + + }; // end of apex namespace +}; // end of physx namespace + +#endif diff --git a/APEX_1.4/include/Module.h b/APEX_1.4/include/Module.h new file mode 100644 index 00000000..7b754137 --- /dev/null +++ b/APEX_1.4/include/Module.h @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_H +#define MODULE_H + +/*! +\file +\brief APEX Module API +*/ + +#include "ApexInterface.h" +#include "ApexSDK.h" +#include "foundation/PxSimpleTypes.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderableIterator; + +/** +\brief Render lock modes. These are used per-module to determine how render locking is done. +*/ +struct RenderLockMode +{ + /** + \brief Enum of render lock modes + */ + enum Enum + { + /** + \brief Disables render locking in the module scene. + */ + NO_RENDER_LOCK = 0, + + /** + \brief Locks all apex actors in the module scene individually. + */ + PER_ACTOR_RENDER_LOCK = 1, + + /** + \brief Locks an entire module scene with one lock. + */ + PER_MODULE_SCENE_RENDER_LOCK = 2, + }; +}; + +/** +\brief A structure that holds two templated values, a min and a max +*/ +template <typename T> +struct Range +{ + Range() {}; + /** + \brief Constructor, sets min amd max values + */ + Range(T inMin, T inMax) : minimum(inMin), maximum(inMax) {}; + + /** + \brief operator == + */ + bool operator== (const Range& r) const + { + return minimum == r.minimum && maximum == r.maximum; + } + + /** + \brief Minimal value + */ + T minimum; + /** + \brief Maximal value + */ + T maximum; +}; + + + +/** +\brief base class of all APEX modules + +It describes the LODParameters and weights defined by the module. +*/ +class Module : public ApexInterface +{ +public: + /** + \brief Initialize the module + \param[in] desc use Module::getDefaultModuleDesc() to get the descriptor necessary for initializing the module + */ + virtual void init(::NvParameterized::Interface& desc) = 0; + + /** + \brief Returns the name of the module + */ + virtual const char* getName() const = 0; + + /** + \brief Returns the unique ID of the module + */ + virtual AuthObjTypeID getModuleID() const = 0; + + /** + \brief Returns the NvParameterized interface that contains module initialization parameters + \note The module itself owns this object, so there's no need for the application to destroy it + */ + virtual ::NvParameterized::Interface* getDefaultModuleDesc() + { + return NULL; + } + + /** + \brief Allocate a renderable iterator + + Returns an Renderable iterator instance for the specified Scene. The iterator + will return pointers to renderables in this scene that were generated by this module. This + is the preferred method for rendering IOFX actors. + */ + virtual RenderableIterator* createRenderableIterator(const Scene&) = 0; + + /** + \brief Choose the locking mode for the module scene. See RenderLockMode. + + Returns true if successful. + */ + virtual bool setRenderLockMode(RenderLockMode::Enum, Scene&) { return false; } + + /** + \brief Returns the current render lock mode for the module scene. + */ + virtual RenderLockMode::Enum getRenderLockMode(const Scene&) const { return RenderLockMode::NO_RENDER_LOCK; } + + /** + \brief Sets a render lock for the module scene. Used when the SDK render lock mode is RenderLockMode::PER_MODULE_SCENE_RENDER_LOCK. See ApexSDK::setRenderLockMode(). + + Returns true iff successful. + */ + virtual bool lockModuleSceneRenderLock(Scene&) { return false; } + + /** + \brief Releases the render lock for the module scene. See lockModuleSceneRenderLock(). + + Returns true iff successful. + */ + virtual bool unlockModuleSceneRenderLock(Scene&) { return false; } +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // MODULE_H diff --git a/APEX_1.4/include/PhysX0/PhysXSDKVersion.h b/APEX_1.4/include/PhysX0/PhysXSDKVersion.h new file mode 100644 index 00000000..f22c92f6 --- /dev/null +++ b/APEX_1.4/include/PhysX0/PhysXSDKVersion.h @@ -0,0 +1,44 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2015 NVIDIA Corporation. All rights reserved. + +#ifndef PHYSX_SDK_VERSION_H +#define PHYSX_SDK_VERSION_H + +/*! +\file +\brief Version identifiers for PhysX less configuration + + This file is intended to be included by ApexDefs.h +*/ + +/// helper PhysX version +#define PX_PHYSICS_VERSION 0 + +/// helper PhysX version, major part +#define PX_PHYSICS_VERSION_MAJOR 0 + +#endif // PHYSX_SDK_VERSION_H diff --git a/APEX_1.4/include/PhysX3/PhysXSDKVersion.h b/APEX_1.4/include/PhysX3/PhysXSDKVersion.h new file mode 100644 index 00000000..703e3bdf --- /dev/null +++ b/APEX_1.4/include/PhysX3/PhysXSDKVersion.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef PHYSX_SDK_VERSION_H +#define PHYSX_SDK_VERSION_H + +/*! +\file +\brief Version identifiers for PhysX major release 3 + + This file is intended to be included by ApexDefs.h +*/ + +/// helper Version number, this number should not be trusted for differentiating between different PhysX 3 versions +#define SDK_VERSION_NUMBER 300 + +/// Major version of PhysX +#define PX_PHYSICS_VERSION_MAJOR 3 +/// Minor version of PhysX +#define PX_PHYSICS_VERSION_MINOR 4 +/// Bugfix version of PhysX +#define PX_PHYSICS_VERSION_BUGFIX 0 + +/** +The constant PX_PHYSICS_VERSION is used when creating certain PhysX module objects. +This is to ensure that the application is using the same header version as the library was built with. +*/ +#define PX_PHYSICS_VERSION ((PX_PHYSICS_VERSION_MAJOR<<24) + (PX_PHYSICS_VERSION_MINOR<<16) + (PX_PHYSICS_VERSION_BUGFIX<<8) + 0) + +#endif // PHYSX_SDK_VERSION_H diff --git a/APEX_1.4/include/PhysXObjectDesc.h b/APEX_1.4/include/PhysXObjectDesc.h new file mode 100644 index 00000000..f3666b98 --- /dev/null +++ b/APEX_1.4/include/PhysXObjectDesc.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef PHYS_XOBJECT_DESC_H +#define PHYS_XOBJECT_DESC_H + +/*! +\file +\brief class PhysXObjectDesc +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +class Actor; + +PX_PUSH_PACK_DEFAULT + +/** + * \brief PhysX object descriptor + * + * Class which describes how a PhysX object is being used by APEX. Data access is + * non virtual for performance reasons. + */ +class PhysXObjectDesc +{ +protected: + /** + \brief Object interaction flags + + These flags determine how this PhysX object should interact with user callbacks. For + instance whether contact callbacks with the object should be ignored. + */ + uint32_t mFlags; + + enum + { + TRANSFORM = (1U << 31), //!< If set, ignore this object's xform in active actor callbacks + RAYCASTS = (1U << 30), //!< If set, ignore this object in raycasts + CONTACTS = (1U << 29) //!< If set, ignore this object in contact callbacks + }; + + +public: + /** \brief Returns the number of Actors associated with the PhysX object */ + virtual uint32_t getApexActorCount() const = 0; + /** \brief Returns the indexed Actor pointer */ + virtual const Actor* getApexActor(uint32_t i) const = 0; + + /** \brief Returns whether this object's xform should be ignored */ + bool ignoreTransform() const + { + return (mFlags & (uint32_t)TRANSFORM) ? true : false; + } + /** \brief Returns whether this object should be ignored by raycasts */ + bool ignoreRaycasts() const + { + return (mFlags & (uint32_t)RAYCASTS) ? true : false; + } + /** \brief Returns whether this object should be ignored by contact report callbacks */ + bool ignoreContacts() const + { + return (mFlags & (uint32_t)CONTACTS) ? true : false; + } + /** \brief Returns a user defined status bit */ + bool getUserDefinedFlag(uint32_t index) const + { + return (mFlags & (uint32_t)(1 << index)) ? true : false; + } + + /** + \brief User data, for use by APEX + + For internal use by APEX. Please do not modify this field. You may use the PhysX object + userData or Actor userData field. + */ + void* userData; +}; + +// To get owning Actor's authorable object type name: +// getActor()->getOwner()->getAuthObjName(); +// To get owning Actor's authorable object type ID: +// getActor()->getOwner()->getAuthObjType(); + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // PHYS_XOBJECT_DESC_H diff --git a/APEX_1.4/include/PxStreamFromFileBuf.h b/APEX_1.4/include/PxStreamFromFileBuf.h new file mode 100644 index 00000000..eb755675 --- /dev/null +++ b/APEX_1.4/include/PxStreamFromFileBuf.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef PX_STREAM_FROM_FILE_BUF_H +#define PX_STREAM_FROM_FILE_BUF_H + +/*! +\file +\brief Conversion utilities between PhysX 2.8 and 3.0 data types +*/ + +#include "ApexDefs.h" +#include "foundation/PxIO.h" +#include "filebuf/PxFileBuf.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief A wrapper class that provides an NvStream API for a PxFileBuf +*/ +class PxStreamFromFileBuf : + public physx::PxInputStream, public physx::PxOutputStream +{ +private: + physx::PxFileBuf& mFileBuf; + PxStreamFromFileBuf& operator=(const PxStreamFromFileBuf&) + { + return *this; + } + +public: + //! \brief Constructor that takes a PxFileBuf + PxStreamFromFileBuf(physx::PxFileBuf& fb) : mFileBuf(fb) {} + + //! \brief Read data from the stream + uint32_t read(void* dest, uint32_t count) + { + return mFileBuf.read(dest, count); + } + + //! \brief Read data to the stream + uint32_t write(const void* src, uint32_t count) + { + return mFileBuf.write(src, count); + } +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // PX_STREAM_FROM_FILE_BUF_H diff --git a/APEX_1.4/include/RWLockable.h b/APEX_1.4/include/RWLockable.h new file mode 100644 index 00000000..2990f749 --- /dev/null +++ b/APEX_1.4/include/RWLockable.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RWLOCKABLE_H +#define RWLOCKABLE_H + +/** +\file +\brief The include containing the interface for any rw-lockable object in the APEX SDK +*/ + +#include "foundation/PxSimpleTypes.h" + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +/** + * \brief Base class for any rw-lockable object implemented by APEX SDK + */ +class RWLockable +{ +public: + /** + \brief Acquire RW lock for read access. + + The APEX 1.3.3 SDK (and higher) provides a multiple-reader single writer mutex lock to coordinate + access to the APEX SDK API from multiple concurrent threads. This method will in turn invoke the + lockRead call on the APEX Scene. The source code fileName and line number are provided for debugging + purposes. + */ + virtual void acquireReadLock(const char *fileName, const uint32_t lineno) const = 0; + + /** + \brief Acquire RW lock for write access. + + The APEX 1.3.3 SDK (and higher) provides a multiple-reader single writer mutex lock to coordinate + access to the APEX SDK API from multiple concurrent threads. This method will in turn invoke the + lockRead call on the APEX Scene. The source code fileName and line number are provided for debugging + purposes. + */ + virtual void acquireWriteLock(const char *fileName, const uint32_t lineno) const = 0; + + /** + \brief Release the RW read lock + */ + virtual void releaseReadLock(void) const = 0; + + /** + \brief Release the RW write lock + */ + virtual void releaseWriteLock(void) const = 0; +}; + +} +} +#endif // RWLOCKABLE_H diff --git a/APEX_1.4/include/RenderBufferData.h b/APEX_1.4/include/RenderBufferData.h new file mode 100644 index 00000000..d78fe1cb --- /dev/null +++ b/APEX_1.4/include/RenderBufferData.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_BUFFER_DATA_H +#define RENDER_BUFFER_DATA_H + +/*! +\file +\brief classes RenderSemanticData, RenderBufferData, ModuleSpecificRenderBufferData +*/ + +#include "ApexUsingNamespace.h" +#include "RenderDataFormat.h" +#include "ApexSDK.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Describes the data location and layout of a single semantic +*/ +class RenderSemanticData +{ +public: + const void* data; //!< Pointer to first semantic data element + uint32_t stride; //!< Semantic stride, in bytes + void* ident; //!< Used for custom semantics only: value retrieved from NRP + RenderDataFormat::Enum format; //!< Format used for this semantic + /** + \brief When this class is used for mesh authoring, this is the format of the source (user's) buffer. + If different from 'format', and not RenderDataFormat::UNSPECIFIED, the data will be converted to + from srcFormat to format (if a converter exists). + If srcFormat = RenderDataFormat::UNSPECIFIED (default value), it is assumed that srcFormat = format. + */ + RenderDataFormat::Enum srcFormat; + /** + \brief Copy this buffer from the authoring asset to the asset. + + This will only be used at render mesh asset creation time. + */ + bool serialize; +public: + PX_INLINE RenderSemanticData(void) + { + data = 0; + stride = 0; + ident = 0; + format = RenderDataFormat::UNSPECIFIED; + srcFormat = RenderDataFormat::UNSPECIFIED; + serialize = false; + } +}; + +/** +\brief Describes all of the semantics of a render buffer +*/ +template < class SemanticClass, class SemanticEnum> +class RenderBufferData +{ +public: + PX_INLINE RenderBufferData(void) + { + m_numCustomSemantics = 0; + m_customSemanticData = 0; + } + + /** + \brief Returns the properties of a base semantic + */ + PX_INLINE const RenderSemanticData& getSemanticData(SemanticEnum semantic) const + { + PX_ASSERT(semantic < SemanticClass::NUM_SEMANTICS); + return m_semanticData[semantic]; + } + + /** + \brief Returns the number of custom semantics + */ + PX_INLINE uint32_t getNumCustomSemantics() const + { + return m_numCustomSemantics; + } + + /** + \brief Returns the properties of a custom semantic + */ + PX_INLINE const RenderSemanticData& getCustomSemanticData(uint32_t index) const + { + PX_ASSERT(index < m_numCustomSemantics); + return m_customSemanticData[index]; + } + + /** + \brief Set a specific set of custom semantics on this data buffer. + + If there are named custom semantics in a RenderMeshAsset, its RenderMeshActor will + call this function to set those semantics on this buffer. + */ + PX_INLINE void setCustomSemanticData(RenderSemanticData* data, uint32_t num) + { + m_numCustomSemantics = num; + m_customSemanticData = data; + } + + /** + \brief Set the properties (pointer and stride) of a base semantic. + */ + PX_INLINE void setSemanticData(SemanticEnum semantic, const void* data, uint32_t stride, RenderDataFormat::Enum format, RenderDataFormat::Enum srcFormat = RenderDataFormat::UNSPECIFIED) + { + PX_ASSERT(semantic < SemanticClass::NUM_SEMANTICS); + RenderSemanticData& sd = m_semanticData[semantic]; + sd.data = data; + sd.stride = stride; + sd.format = format; + sd.srcFormat = srcFormat == RenderDataFormat::UNSPECIFIED ? format : srcFormat; + } + +private: + RenderSemanticData m_semanticData[SemanticClass::NUM_SEMANTICS]; //!< Base semantics for this buffer type + uint32_t m_numCustomSemantics; //!< Number of custom semantics + RenderSemanticData* m_customSemanticData; //!< An array of custom semantics +}; + +/** +\brief Describes data semantics provided by a particular module +*/ +class ModuleSpecificRenderBufferData +{ +public: + AuthObjTypeID moduleId; //!< Unique module identifier, from Module::getModuleID() + RenderSemanticData* moduleSpecificSemanticData; //!< Pointer to an array of custom semantics + uint32_t numModuleSpecificSemantics; //!< Count of custom semantics provided by this module + +public: + PX_INLINE ModuleSpecificRenderBufferData(void) + { + moduleId = 0; + moduleSpecificSemanticData = 0; + numModuleSpecificSemantics = 0; + } +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RENDER_BUFFER_DATA_H diff --git a/APEX_1.4/include/RenderContext.h b/APEX_1.4/include/RenderContext.h new file mode 100644 index 00000000..39c30bc8 --- /dev/null +++ b/APEX_1.4/include/RenderContext.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_CONTEXT_H +#define RENDER_CONTEXT_H + +/*! +\file +\brief class RenderContext +*/ + +#include "ApexUsingNamespace.h" +#include "foundation/PxMat44.h" + +namespace nvidia +{ +namespace apex +{ + +class UserRenderResource; +class UserOpaqueMesh; + +PX_PUSH_PACK_DEFAULT + +/** +\brief Describes the context of a renderable object +*/ +class RenderContext +{ +public: + RenderContext(void) + { + renderResource = 0; + isScreenSpace = false; + renderMeshName = NULL; + } + +public: + UserRenderResource* renderResource; //!< The renderable resource to be rendered + bool isScreenSpace; //!< The data is in screenspace and should use a screenspace projection that transforms X -1 to +1 and Y -1 to +1 with zbuffer disabled. + PxMat44 local2world; //!< Reverse world pose transform for this renderable + PxMat44 world2local; //!< World pose transform for this renderable + const char* renderMeshName; //!< The name of the render mesh this context is associated with. +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RENDER_CONTEXT_H diff --git a/APEX_1.4/include/RenderDataFormat.h b/APEX_1.4/include/RenderDataFormat.h new file mode 100644 index 00000000..d4d89b44 --- /dev/null +++ b/APEX_1.4/include/RenderDataFormat.h @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_DATA_FORMAT_H +#define RENDER_DATA_FORMAT_H + +#include "ApexUsingNamespace.h" +#include "foundation/PxAssert.h" +#include "foundation/PxMat44.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Enumeration of possible formats of various buffer semantics + +N.B.: DO NOT CHANGE THE VALUES OF OLD FORMATS. +*/ +struct RenderDataFormat +{ + /** \brief the enum type */ + enum Enum + { + UNSPECIFIED = 0, //!< No format (semantic not used) + + //!< Integer formats + UBYTE1 = 1, //!< One unsigned 8-bit integer (uint8_t[1]) + UBYTE2 = 2, //!< Two unsigned 8-bit integers (uint8_t[2]) + UBYTE3 = 3, //!< Three unsigned 8-bit integers (uint8_t[3]) + UBYTE4 = 4, //!< Four unsigned 8-bit integers (uint8_t[4]) + + USHORT1 = 5, //!< One unsigned 16-bit integer (uint16_t[1]) + USHORT2 = 6, //!< Two unsigned 16-bit integers (uint16_t[2]) + USHORT3 = 7, //!< Three unsigned 16-bit integers (uint16_t[3]) + USHORT4 = 8, //!< Four unsigned 16-bit integers (uint16_t[4]) + + SHORT1 = 9, //!< One signed 16-bit integer (int16_t[1]) + SHORT2 = 10, //!< Two signed 16-bit integers (int16_t[2]) + SHORT3 = 11, //!< Three signed 16-bit integers (int16_t[3]) + SHORT4 = 12, //!< Four signed 16-bit integers (int16_t[4]) + + UINT1 = 13, //!< One unsigned integer (uint32_t[1]) + UINT2 = 14, //!< Two unsigned integers (uint32_t[2]) + UINT3 = 15, //!< Three unsigned integers (uint32_t[3]) + UINT4 = 16, //!< Four unsigned integers (uint32_t[4]) + + //!< Color formats + R8G8B8A8 = 17, //!< Four unsigned bytes (uint8_t[4]) representing red, green, blue, alpha + B8G8R8A8 = 18, //!< Four unsigned bytes (uint8_t[4]) representing blue, green, red, alpha + R32G32B32A32_FLOAT = 19, //!< Four floats (float[4]) representing red, green, blue, alpha + B32G32R32A32_FLOAT = 20, //!< Four floats (float[4]) representing blue, green, red, alpha + + //!< Normalized formats + BYTE_UNORM1 = 21, //!< One unsigned normalized value in the range [0,1], packed into 8 bits (uint8_t[1]) + BYTE_UNORM2 = 22, //!< Two unsigned normalized value in the range [0,1], each packed into 8 bits (uint8_t[2]) + BYTE_UNORM3 = 23, //!< Three unsigned normalized value in the range [0,1], each packed into bits (uint8_t[3]) + BYTE_UNORM4 = 24, //!< Four unsigned normalized value in the range [0,1], each packed into 8 bits (uint8_t[4]) + + SHORT_UNORM1 = 25, //!< One unsigned normalized value in the range [0,1], packed into 16 bits (uint16_t[1]) + SHORT_UNORM2 = 26, //!< Two unsigned normalized value in the range [0,1], each packed into 16 bits (uint16_t[2]) + SHORT_UNORM3 = 27, //!< Three unsigned normalized value in the range [0,1], each packed into 16 bits (uint16_t[3]) + SHORT_UNORM4 = 28, //!< Four unsigned normalized value in the range [0,1], each packed into 16 bits (uint16_t[4]) + + BYTE_SNORM1 = 29, //!< One signed normalized value in the range [-1,1], packed into 8 bits (uint8_t[1]) + BYTE_SNORM2 = 30, //!< Two signed normalized value in the range [-1,1], each packed into 8 bits (uint8_t[2]) + BYTE_SNORM3 = 31, //!< Three signed normalized value in the range [-1,1], each packed into bits (uint8_t[3]) + BYTE_SNORM4 = 32, //!< Four signed normalized value in the range [-1,1], each packed into 8 bits (uint8_t[4]) + + SHORT_SNORM1 = 33, //!< One signed normalized value in the range [-1,1], packed into 16 bits (uint16_t[1]) + SHORT_SNORM2 = 34, //!< Two signed normalized value in the range [-1,1], each packed into 16 bits (uint16_t[2]) + SHORT_SNORM3 = 35, //!< Three signed normalized value in the range [-1,1], each packed into 16 bits (uint16_t[3]) + SHORT_SNORM4 = 36, //!< Four signed normalized value in the range [-1,1], each packed into 16 bits (uint16_t[4]) + + //!< Float formats + HALF1 = 37, //!< One 16-bit floating point value + HALF2 = 38, //!< Two 16-bit floating point values + HALF3 = 39, //!< Three 16-bit floating point values + HALF4 = 40, //!< Four 16-bit floating point values + + FLOAT1 = 41, //!< One 32-bit floating point value + FLOAT2 = 42, //!< Two 32-bit floating point values + FLOAT3 = 43, //!< Three 32-bit floating point values + FLOAT4 = 44, //!< Four 32-bit floating point values + + FLOAT4x4 = 45, //!< A 4x4 matrix (see PxMat44) + FLOAT3x4 = 46, //!< A 3x4 matrix (see float[12]) + FLOAT3x3 = 47, //!< A 3x3 matrix (see PxMat33) + + FLOAT4_QUAT = 48, //!< A quaternion (see PxQuat) + BYTE_SNORM4_QUATXYZW = 49, //!< A normalized quaternion with signed byte elements, X,Y,Z,W format (uint8_t[4]) + SHORT_SNORM4_QUATXYZW = 50, //!< A normalized quaternion with signed short elements, X,Y,Z,W format (uint16_t[4]) + + NUM_FORMATS + }; + + /// Get byte size of format type + static PX_INLINE uint32_t getFormatDataSize(Enum format) + { + switch (format) + { + default: + PX_ALWAYS_ASSERT(); + case UNSPECIFIED: + return 0; + + case UBYTE1: + case BYTE_UNORM1: + case BYTE_SNORM1: + return sizeof(uint8_t); + case UBYTE2: + case BYTE_UNORM2: + case BYTE_SNORM2: + return sizeof(uint8_t) * 2; + case UBYTE3: + case BYTE_UNORM3: + case BYTE_SNORM3: + return sizeof(uint8_t) * 3; + case UBYTE4: + case BYTE_UNORM4: + case BYTE_SNORM4: + case BYTE_SNORM4_QUATXYZW: + return sizeof(uint8_t) * 4; + + case USHORT1: + case SHORT1: + case HALF1: + case SHORT_UNORM1: + case SHORT_SNORM1: + return sizeof(uint16_t); + case USHORT2: + case SHORT2: + case HALF2: + case SHORT_UNORM2: + case SHORT_SNORM2: + return sizeof(uint16_t) * 2; + case USHORT3: + case SHORT3: + case HALF3: + case SHORT_UNORM3: + case SHORT_SNORM3: + return sizeof(uint16_t) * 3; + case USHORT4: + case SHORT4: + case HALF4: + case SHORT_UNORM4: + case SHORT_SNORM4: + case SHORT_SNORM4_QUATXYZW: + return sizeof(uint16_t) * 4; + + case UINT1: + return sizeof(uint32_t); + case UINT2: + return sizeof(uint32_t) * 2; + case UINT3: + return sizeof(uint32_t) * 3; + case UINT4: + return sizeof(uint32_t) * 4; + + case R8G8B8A8: + case B8G8R8A8: + return sizeof(uint8_t) * 4; + + case R32G32B32A32_FLOAT: + case B32G32R32A32_FLOAT: + return sizeof(float) * 4; + + case FLOAT1: + return sizeof(float); + case FLOAT2: + return sizeof(float) * 2; + case FLOAT3: + return sizeof(float) * 3; + case FLOAT4: + return sizeof(float) * 4; + + case FLOAT4x4: + return sizeof(PxMat44); + + case FLOAT3x4: + return sizeof(float) * 12; + + case FLOAT3x3: + return sizeof(PxMat33); + + case FLOAT4_QUAT: + return sizeof(PxQuat); + } + } +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RENDER_DATA_FORMAT_H diff --git a/APEX_1.4/include/RenderDataProvider.h b/APEX_1.4/include/RenderDataProvider.h new file mode 100644 index 00000000..3edb05af --- /dev/null +++ b/APEX_1.4/include/RenderDataProvider.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_DATA_PROVIDER_H +#define RENDER_DATA_PROVIDER_H + +/*! +\file +\brief class RenderDataProvider +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief An actor instance that provides renderable data +*/ +class RenderDataProvider +{ +public: + /** + \brief Lock the renderable resources of this Renderable actor + + Locks the renderable data of this Renderable actor. If the user uses an RenderableIterator + to retrieve the list of Renderables, then locking is handled for them automatically by APEX. If the + user is storing Renderable pointers and using them ad-hoc, then they must use this API to lock the + actor while updateRenderResources() and/or dispatchRenderResources() is called. If an iterator is not being + used, the user is also responsible for insuring the Renderable has not been deleted by another game + thread. + */ + virtual void lockRenderResources() = 0; + + /** + \brief Unlocks the renderable data of this Renderable actor. + + See locking semantics for RenderDataProvider::lockRenderResources(). + */ + virtual void unlockRenderResources() = 0; + + /** + \brief Update the renderable data of this Renderable actor. + + When called, this method will use the UserRenderResourceManager interface to inform the user + about its render resource needs. It will also call the writeBuffer() methods of various graphics + buffers. It must be called by the user each frame before any calls to dispatchRenderResources(). + If the actor is not being rendered, this function may also be skipped. + + \param [in] rewriteBuffers If true then static buffers will be rewritten (in the case of a graphics + device context being lost if managed buffers aren't being used) + + \param [in] userRenderData A pointer used by the application for context information which will be sent in + the UserRenderResourceManager::createResource() method as a member of the UserRenderResourceDesc class. + */ + virtual void updateRenderResources(bool rewriteBuffers = false, void* userRenderData = 0) = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RENDER_DATA_PROVIDER_H diff --git a/APEX_1.4/include/RenderDebugInterface.h b/APEX_1.4/include/RenderDebugInterface.h new file mode 100644 index 00000000..d13bc20c --- /dev/null +++ b/APEX_1.4/include/RenderDebugInterface.h @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_DEBUG_INTERFACE_H +#define RENDER_DEBUG_INTERFACE_H + +/*! +\file +\brief debug rendering classes and structures +*/ + +#include "ApexDefs.h" +#include "RenderDebugTyped.h" // include the header file containing the base class +#include "ApexInterface.h" +#include "Renderable.h" + +#if PX_PHYSICS_VERSION_MAJOR == 3 +#include "common/PxRenderBuffer.h" +#endif + +/// Macros for getting render debug interface for argument +#define RENDER_DEBUG_IFACE(ptr) ((ptr)->getRenderDebugInterface()) + +namespace nvidia +{ + +namespace apex +{ +class UserRenderer; +class UserRenderResourceManager; + +PX_PUSH_PACK_DEFAULT + +#if PX_PHYSICS_VERSION_MAJOR == 3 + +/** +\brief This is a helper class implementation of PxRenderBuffer that holds the counts +and pointers for renderable data. Does not own the memory, simply used to transfer +the state. The append method is not supported. +*/ +class PhysXRenderBuffer : public PxRenderBuffer +{ +public: + PhysXRenderBuffer() + { + clear(); + } + + /** + \brief Get number of points in the render buffer + */ + virtual uint32_t getNbPoints() const + { + return mNbPoints; + } + + /** + \brief Get points data + */ + virtual const PxDebugPoint* getPoints() const + { + return mPoints; + } + + /** + \brief Get number of lines in the render buffer + */ + virtual uint32_t getNbLines() const + { + return mNbLines; + } + + /** + \brief Get lines data + */ + virtual const PxDebugLine* getLines() const + { + return mLines; + } + + /** + \brief Get number of triangles in the render buffer + */ + virtual uint32_t getNbTriangles() const + { + return mNbTriangles; + } + + /** + \brief Get triangles data + */ + virtual const PxDebugTriangle* getTriangles() const + { + return mTriangles; + } + + /** + \brief Get number of texts in the render buffer + */ + virtual uint32_t getNbTexts() const + { + return mNbTexts; + } + + /** + \brief Get texts data + */ + virtual const PxDebugText* getTexts() const + { + return mTexts; + } + + /** + \brief Append PhysX render buffer + */ + virtual void append(const PxRenderBuffer& other) + { + PX_UNUSED(other); + PX_ALWAYS_ASSERT(); // this method not implemented! + } + + /** + \brief Clear this buffer + */ + virtual void clear() + { + mNbPoints = 0; + mPoints = NULL; + mNbLines = 0; + mLines = NULL; + mNbTriangles = 0; + mTriangles = NULL; + mNbTexts = 0; + mTexts = NULL; + } + + /** + \brief Number of points + */ + uint32_t mNbPoints; + /** + \brief Points data + */ + PxDebugPoint *mPoints; + /** + \brief Number of lines + */ + uint32_t mNbLines; + /** + \brief Lines data + */ + PxDebugLine *mLines; + /** + \brief Number of triangles + */ + uint32_t mNbTriangles; + /** + \brief Triangles data + */ + PxDebugTriangle *mTriangles; + /** + \brief Number of texts + */ + uint32_t mNbTexts; + /** + \brief Text data + */ + PxDebugText *mTexts; +}; +#endif + +/** +\brief wrapper for DebugRenderable + */ +class RenderDebugInterface : public ApexInterface, public Renderable +{ +public: + /** + \brief Method to support rendering to a legacy PhysX SDK DebugRenderable object instead + of to the APEX Render Resources API (i.e.: Renderable). + + This method is used to enable or disable the use of a legacy DebugRenderable. When enabled, + use the getDebugRenderable() method to get a legacy DebugRenerable object that will contain + all the debug output. + */ + virtual void setUseDebugRenderable(bool state) = 0; + + +#if PX_PHYSICS_VERSION_MAJOR == 3 + + /** + \brief Method to support rendering to a legacy PhysX SDK PxRenderBuffer object instead + of to the APEX Render Resources API (i.e.: Renderable). + + When enabled with a call to setUseDebugRenderable(true), this method will return a legacy + PxRenderBuffer object that contains all of the output of the RenderDebug class. + */ + virtual void getRenderBuffer(PhysXRenderBuffer& renderable) = 0; + + /** + \brief Method to support rendering to a legacy PhysX SDK PxRenderBuffer object instead + of to the APEX Render Resources API (i.e.: Renderable). Lines and triangle in + screen space + + When enabled with a call to setUseDebugRenderable(true), this method will return a legacy + PxRenderBuffer object that contains all of the output of the RenderDebug class. + */ + virtual void getRenderBufferScreenSpace(PhysXRenderBuffer& renderable) = 0; + + /** + \brief Method to support rendering from an existing PhysX SDK PxRenderBuffer object. + + The contents of the PxRenderBuffer is added to the current contents of the + RenderDebug object, and is output through the APEX Render Resources API. + */ + virtual void addDebugRenderable(const physx::PxRenderBuffer& renderBuffer) = 0; + +#endif //PX_PHYSICS_VERSION_MAJOR == 3 + + virtual void release() = 0; + + /** + \brief Returns render debug interface RENDER_DEBUG::RenderDebugTyped + */ + virtual RENDER_DEBUG::RenderDebugTyped* getRenderDebugInterface() = 0; + +protected: + + virtual ~RenderDebugInterface(void) { }; + +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RENDER_DEBUG_INTERFACE_H diff --git a/APEX_1.4/include/RenderMesh.h b/APEX_1.4/include/RenderMesh.h new file mode 100644 index 00000000..e666d00a --- /dev/null +++ b/APEX_1.4/include/RenderMesh.h @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_MESH_H +#define RENDER_MESH_H + +/*! +\file +\brief classes RenderSubmesh, VertexBuffer, and MaterialNamingConvention enums +*/ + +#include "ApexUsingNamespace.h" +#include "VertexFormat.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderMeshActor; +class Context; +struct VertexUV; + + +/** +\brief a vertex buffer that supports multiple formats + */ +class VertexBuffer +{ +public: + /** + \brief Returns the number of vertices in the buffer + */ + virtual uint32_t getVertexCount() const = 0; + + /** + \brief Returns the data format. See VertexFormat. + */ + virtual const VertexFormat& getFormat() const = 0; + + /** + \brief Returns the data format. See VertexFormat. Can be changed. + */ + virtual VertexFormat& getFormatWritable() = 0; + + /** + \brief Accessor for the data buffer indexed by bufferIndex. To get the buffer format, use getFormat().getBufferFormat( index ). + If the data channel doesn't exist then this function returns NULL. + */ + virtual const void* getBuffer(uint32_t bufferIndex) const = 0; + + /** + \brief Like getBuffer(), but also returns the buffer's format. + */ + virtual const void* getBufferAndFormat(RenderDataFormat::Enum& format, uint32_t bufferIndex) const = 0; + + /** + \brief Like getBuffer(), but also returns the buffer's format. Can be changed. + */ + virtual void* getBufferAndFormatWritable(RenderDataFormat::Enum& format, uint32_t bufferIndex) = 0; + + /** + \brief Accessor for data in a desired format from the buffer indexed by bufferIndex. If the channel does not exist, or if it is in + a format for which there is not presently a converter to the the desired format dstBufferFormat, this function returns false. + The dstBufferStride field must be at least the size of the dstBufferFormat data, or zero (in which case the stride is assumed to be + the size of the dstBufferFormat data). If neither of these conditions hold, this function returns false. + Otherwise, dstBuffer is filled in with elementCount elements of the converted data, starting from startVertexIndex, withe the given stride. + */ + virtual bool getBufferData(void* dstBuffer, nvidia::RenderDataFormat::Enum dstBufferFormat, uint32_t dstBufferStride, uint32_t bufferIndex, + uint32_t startVertexIndex, uint32_t elementCount) const = 0; + +protected: + /* Do not allow class to be created directly */ + VertexBuffer() {} +}; + + +/** +\brief a mesh that has only one material (or render state, in general) + */ +class RenderSubmesh +{ +public: + virtual ~RenderSubmesh() {} + + /** + Returns the number of vertices associated with the indexed part. + */ + virtual uint32_t getVertexCount(uint32_t partIndex) const = 0; + + /** + Returns the submesh's vertex buffer (contains all parts' vertices) + */ + virtual const VertexBuffer& getVertexBuffer() const = 0; + + /** + Returns the submesh's index buffer (contains all parts' vertices). Can be changed. + */ + virtual VertexBuffer& getVertexBufferWritable() = 0; + + /** + Vertices for a given part are contiguous within the vertex buffer. This function + returns the first vertex index for the indexed part. + */ + virtual uint32_t getFirstVertexIndex(uint32_t partIndex) const = 0; + + /** + Returns the number of indices in the part's index buffer. + */ + virtual uint32_t getIndexCount(uint32_t partIndex) const = 0; + + /** + Returns the index buffer associated with the indexed part. + */ + virtual const uint32_t* getIndexBuffer(uint32_t partIndex) const = 0; + + /** + Returns an array of smoothing groups for the given part, if one exists. Otherwise, returns NULL. + If not NULL, the size of the array is the number of triangles in the part. Since only triangle + lists are currently supported, the size of this array is getIndexCount(partIndex)/3. + */ + virtual const uint32_t* getSmoothingGroups(uint32_t partIndex) const = 0; + +protected: + RenderSubmesh() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RENDER_MESH_H diff --git a/APEX_1.4/include/RenderMeshActor.h b/APEX_1.4/include/RenderMeshActor.h new file mode 100644 index 00000000..9147095e --- /dev/null +++ b/APEX_1.4/include/RenderMeshActor.h @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_MESH_ACTOR_H +#define RENDER_MESH_ACTOR_H + +/*! +\file +\brief class RenderMeshActor +*/ + +#include "Actor.h" +#include "Renderable.h" +#include "UserRenderResourceManager.h" // For RenderCullMode +#include "foundation/PxVec3.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class UserRenderInstanceBuffer; + +/** +\brief Flags used for raycasting an RenderMeshActor +*/ +struct RenderMeshActorRaycastFlags +{ + /** + \brief Enum of flags used for raycasting an RenderMeshActor + */ + enum Enum + { + VISIBLE_PARTS = (1 << 0), + INVISIBLE_PARTS = (1 << 1), + + ALL_PARTS = VISIBLE_PARTS | INVISIBLE_PARTS + }; +}; + +/** +\brief Return data from raycasting an RenderMeshActor +*/ +struct RenderMeshActorRaycastHitData +{ + /** + The time to the hit point. That is, the hit point is given by worldOrig + time*worldDisp. + */ + float time; + + /** + The part index containing the hit triangle. + */ + uint32_t partIndex; + + /** + The submesh index of the triangle hit. + */ + uint32_t submeshIndex; + + /** + The vertex indices of the triangle hit. + */ + uint32_t vertexIndices[3]; + + /** + The lighting normal at the hit point, if the vertex format supports this. Otherwise set to (0,0,0). + */ + PxVec3 normal; + + /** + The lighting tangent at the hit point, if the vertex format supports this. Otherwise set to (0,0,0). + */ + PxVec3 tangent; + + /** + The lighting binormal at the hit point, if the vertex format supports this. Otherwise set to (0,0,0). + */ + PxVec3 binormal; +}; + + +/** +\brief Renderable mesh (dynamic data associated with RenderMeshAsset) +*/ +class RenderMeshActor : public Actor, public Renderable +{ +public: + + enum + { + InvalidInstanceID = 0xFFFFFFFF + }; + + /** + \brief Returns the visibilities of all mesh parts in the given array. + + The user must supply the array size. If the size is less than the + part count, then the list will be truncated to fit the given array. + + Returns true if any of the visibility values in visibilityArray are changed. + */ + virtual bool getVisibilities(uint8_t* visibilityArray, uint32_t visibilityArraySize) const = 0; + + /** + \brief Set the visibility of the indexed part. Returns true iff the visibility for the part is changed by this operation. + */ + virtual bool setVisibility(bool visible, uint16_t partIndex = 0) = 0; + + /** + \brief Returns the visibility of the indexed part. + */ + virtual bool isVisible(uint16_t partIndex = 0) const = 0; + + /** + \brief Returns the number of visible parts. + */ + virtual uint32_t visiblePartCount() const = 0; + + /** + \brief Returns an array of visible part indices. + + The size of this array is given by visiblePartCount(). Note: the + indices are in an arbitrary order. + */ + virtual const uint32_t* getVisibleParts() const = 0; + + /** + \brief Returns the number of bones used by this render mesh + */ + virtual uint32_t getBoneCount() const = 0; + + /** + \brief Sets the local-to-world transform for the indexed bone. The transform need not be orthonormal. + */ + virtual void setTM(const PxMat44& tm, uint32_t boneIndex = 0) = 0; + + /** + \brief Same as setTM(), but assumes tm is pure rotation. + + This can allow some optimization. The user must supply scaling + separately. The scale vector is interpreted as the diagonal of a + diagonal matrix, applied before the rotation component of tm. + */ + virtual void setTM(const PxMat44& tm, const PxVec3& scale, uint32_t boneIndex = 0) = 0; + + /** + \brief Update the axis-aligned bounding box which encloses all visible parts in their world-transformed poses. + */ + virtual void updateBounds() = 0; + + /** + \brief Returns the local-to-world transform for the indexed bone. + */ + virtual const PxMat44 getTM(uint32_t boneIndex = 0) const = 0; + + /** + \brief If the number of visible parts becomes 0, or if instancing and the number of instances + becomes 0, then release resources if this bool is true. + */ + virtual void setReleaseResourcesIfNothingToRender(bool value) = 0; + + /** + \brief If this set to true, render visibility will not be updated until the user calls syncVisibility(). + */ + virtual void setBufferVisibility(bool bufferVisibility) = 0; + + /** + \brief Sets the override material for the submesh with the given index. + */ + virtual void setOverrideMaterial(uint32_t submeshIndex, const char* overrideMaterialName) = 0; + + /** + \brief Sync render visibility with that set by the user. Only + needed if bufferVisibility(true) is called, or bufferVisibility = true + in the actor's descriptor. + + If useLock == true, the RenderMeshActor's lock is used during the sync. + */ + virtual void syncVisibility(bool useLock = true) = 0; + + /** + \brief get the user-provided instance buffer. + */ + virtual UserRenderInstanceBuffer* getInstanceBuffer() const = 0; + /** + \brief applies the user-provided instance buffer to all submeshes. + */ + virtual void setInstanceBuffer(UserRenderInstanceBuffer* instBuf) = 0; + /** + \brief allows the user to change the max instance count in the case that the instance buffer was changed + */ + virtual void setMaxInstanceCount(uint32_t count) = 0; + /** + \brief sets the range for the instance buffer + + \param from the position in the buffer (measured in number of elements) to start reading from + \param count number of instances to be rendered. Must not exceed maxInstances for this actor + */ + virtual void setInstanceBufferRange(uint32_t from, uint32_t count) = 0; + + /** + Returns true if and only if a part is hit matching various criteria given in the function + parameters. If a part is hit, the hitData field contains information about the ray intersection. + (hitData may be modified even if the function returns false.) + hitData (output) = information about the mesh at the hitpoint. See RenderMeshActorRaycastHitData. + worldOrig = the origin of the ray in world space + worldDisp = the displacement of the ray in world space (need not be normalized) + flags = raycast control flags (see RenderMeshActorRaycastFlags) + winding = winding filter for hit triangle. If RenderCullMode::CLOCKWISE or + RenderCullMode::COUNTER_CLOCKWISE, then triangles will be assumed to have + that winding, and will only contribute to the raycast if front-facing. If + RenderCullMode::NONE, then all triangles will contribute. + partIndex = If -1, then all mesh parts will be raycast, and the result returned for + the earliest hit. Otherwise only the part indexed by partIndex will be raycast. + + N.B. Currently only works for static (unskinned) and one transform per-part, single-weighted vertex skinning. + */ + virtual bool rayCast(RenderMeshActorRaycastHitData& hitData, + const PxVec3& worldOrig, const PxVec3& worldDisp, + RenderMeshActorRaycastFlags::Enum flags = RenderMeshActorRaycastFlags::VISIBLE_PARTS, + RenderCullMode::Enum winding = RenderCullMode::CLOCKWISE, + int32_t partIndex = -1) const = 0; + +protected: + + virtual ~RenderMeshActor() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RENDER_MESH_ACTOR_H diff --git a/APEX_1.4/include/RenderMeshActorDesc.h b/APEX_1.4/include/RenderMeshActorDesc.h new file mode 100644 index 00000000..06e876e2 --- /dev/null +++ b/APEX_1.4/include/RenderMeshActorDesc.h @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_MESH_ACTOR_DESC_H +#define RENDER_MESH_ACTOR_DESC_H + +/*! +\file +\brief class RenderMeshActorDesc +*/ + +#include "ApexDesc.h" +#include "UserRenderResourceManager.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Descriptor for creating a rendering mesh (collection of parts and submesh extra data) +*/ +class RenderMeshActorDesc : public ApexDesc +{ +public: + + /** + \brief constructor sets to default. + */ + PX_INLINE RenderMeshActorDesc() + { + setToDefault(); + } + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault() + { + visible = true; + bufferVisibility = false; + keepVisibleBonesPacked = false; + renderWithoutSkinning = false; + forceFallbackSkinning = false; + maxInstanceCount = 0; + indexBufferHint = RenderBufferHint::STATIC; + overrideMaterials = NULL; + overrideMaterialCount = 0; + keepPreviousFrameBoneBuffer = false; + forceBoneIndexChannel = false; + } + + /** + \brief Returns true if the descriptor is valid. + \return true if the current settings are valid. + */ + PX_INLINE bool isValid() const + { + if (overrideMaterialCount != 0 && overrideMaterials == NULL) + { + return false; + } + return ApexDesc::isValid(); + } + + /** + \brief Initial visibility of all parts. + */ + bool visible; + + /** + \brief If this set to true, render visibility will not be updated until the + user calls syncVisibility(). + */ + bool bufferVisibility; + + /** + \brief Pack visible bones + + If set, bone transform order will be maitained in an order that keeps visible bones + contiguous. This is more efficient for cases where there are large number of + nonvisible parts (it reduces the number of bone transforms that need to be updated + in writeBuffer). This only works when vertices are single-weighted, and + the number of bones equals the number of parts. + */ + bool keepVisibleBonesPacked; + + /** + \brief Render without skinning + + If set, all vertices will be transformed by one transform, set using + RenderMeshActor::setTM with boneIndex = 0 (the default). + */ + bool renderWithoutSkinning; + + /** + \brief Enforce the use of fallback skinning + + This will not create render resources with bone buffers since all the skinning will be done on the CPU already. + Does not work if keepVisibleBones is set. These two features are mutually exclusive. + */ + bool forceFallbackSkinning; + + /** + \brief If maxInstanceCount = 0, mesh will be renedered without instancing. + Otherwise, instance buffers (below) will be used. + */ + uint32_t maxInstanceCount; + + /** + \brief Hint passed along to the user describing whether the index buffer of + this render mesh can be modified. + */ + RenderBufferHint::Enum indexBufferHint; + + /** + \brief Per-actor material names, to override those in the asset. + The number of override material names is given by overrideMaterialCount. + */ + const char** overrideMaterials; + + /** + \brief Number of override material names in the overrideMaterials array. + If this number is less than the number of materials in the asset, only + the first overrideMaterialCount names will be overridden. If this number + is greater than the number of materials in the asset, the extra override + material names will be ignored. + */ + uint32_t overrideMaterialCount; + + /** + \brief If true, the previous frame's bone buffer is kept and delivered + during updateRenderResources as a second bone buffer. + */ + bool keepPreviousFrameBoneBuffer; + + /** + \brief If true, a static runtime bone index channel will be created. + */ + bool forceBoneIndexChannel; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RENDER_MESH_ACTOR_DESC_H diff --git a/APEX_1.4/include/RenderMeshAsset.h b/APEX_1.4/include/RenderMeshAsset.h new file mode 100644 index 00000000..3c0204a4 --- /dev/null +++ b/APEX_1.4/include/RenderMeshAsset.h @@ -0,0 +1,521 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_MESH_ASSET_H +#define RENDER_MESH_ASSET_H + +/*! +\file +\brief APEX RenderMesh Asset +*/ + +#include "ApexUsingNamespace.h" +#include "VertexFormat.h" +#include "Asset.h" +#include "RenderBufferData.h" +#include "RenderMesh.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderMeshActor; +class RenderMeshActorDesc; +class CustomBufferIterator; + +//! \brief Name of RenderMesh authoring type namespace +#define RENDER_MESH_AUTHORING_TYPE_NAME "ApexRenderMesh" + +/** +\brief Stats for an RenderMeshAsset: memory usage, counts, etc. +*/ +struct RenderMeshAssetStats +{ + uint32_t totalBytes; //!< Total byte size of mesh + uint32_t submeshCount; //!< Number of submeshes + uint32_t partCount; //!< Number of mesh parts + uint32_t vertexCount; //!< Number of vertices + uint32_t indexCount; //!< Size (count) of index buffer + uint32_t vertexBufferBytes; //!< Byte size of vertex buffer + uint32_t indexBufferBytes; //!< Byte size of index buffer +}; + +/** +\brief Instance buffer data mode. DEPRECATED, to be removed by APEX 1.0 +*/ +struct RenderMeshAssetInstanceMode +{ + /** + \brief Enum of instance buffer data. + */ + enum Enum + { + POSE_SCALE = 0, + POS_VEL_LIFE, + + NUM_MODES + }; +}; + + +/** +\brief The full RGBA color of a vertex +*/ +struct VertexColor +{ +public: + + PX_INLINE VertexColor() {} + + /** + \brief Constructor + */ + PX_INLINE VertexColor(const ColorRGBA c) + { + const float recip255 = 1 / (float)255; + set((float)c.r * recip255, (float)c.g * recip255, (float)c.b * recip255, (float)c.a * recip255); + } + + /** + \brief Copy assignment operator + */ + PX_INLINE VertexColor& operator = (const VertexColor& c) + { + r = c.r; + g = c.g; + b = c.b; + a = c.a; + return *this; + } + + /// \brief set the color as RGBA floats + PX_INLINE void set(float _r, float _g, float _b, float _a) + { + r = _r; + g = _g; + b = _b; + a = _a; + } + + /// \brief return the color as a 32bit integer + PX_INLINE ColorRGBA toColorRGBA() const + { + return ColorRGBA((uint8_t)(255 * r + (float)0.5), + (uint8_t)(255 * g + (float)0.5), + (uint8_t)(255 * b + (float)0.5), + (uint8_t)(255 * a + (float)0.5)); + } + + float r; //!< RED + float g; //!< GREEN + float b; //!< BLUE + float a; //!< ALPHA +}; + + +/** +\brief a simple u, v coordinate struct +*/ +struct VertexUV +{ + VertexUV() {} + + /** + \brief Constructor + */ + VertexUV(float _u, float _v) + { + set(_u, _v); + } + + /** + \brief Constructor + */ + VertexUV(const float uv[]) + { + set(uv); + } + + /** + \brief Set coordinates + */ + void set(float _u, float _v) + { + u = _u; + v = _v; + } + + /** + \brief Set coordinates + */ + void set(const float uv[]) + { + u = uv[0]; + v = uv[1]; + } + + /** + \brief operator [] + */ + float& operator [](int i) + { + PX_ASSERT(i >= 0 && i <= 1); + return (&u)[i]; + } + + /** + \brief const operator [] + */ + const float& operator [](int i) const + { + PX_ASSERT(i >= 0 && i <= 1); + return (&u)[i]; + } + + /// coordinate + float u; + /// coordinate + float v; +}; + + +/** +\brief An inefficient vertex description used for authoring +*/ +struct Vertex +{ + PxVec3 position; //!< Vertex position + PxVec3 normal; //!< Surface normal at this position + PxVec3 tangent; //!< Surface tangent at this position + PxVec3 binormal; //!< Surface binormal at this position + VertexUV uv[VertexFormat::MAX_UV_COUNT]; //!< Texture UV coordinates + VertexColor color; //!< Color ar this position + uint16_t boneIndices[VertexFormat::MAX_BONE_PER_VERTEX_COUNT]; //!< Bones which are attached to this vertex + float boneWeights[VertexFormat::MAX_BONE_PER_VERTEX_COUNT]; //!< Per bone wieght, 0.0 if no bone + uint16_t displacementFlags; //!< Flags for vertex displacement + + /** + \brief Constructor which clears the entire structure + */ + Vertex() + { + memset(this, 0, sizeof(Vertex)); + } +}; + + +/** +\brief A less inefficient triangle description used for authoring +*/ +struct ExplicitRenderTriangle +{ + Vertex vertices[3]; //!< The three verts that define the triangle + int32_t submeshIndex; //!< The submesh to which this triangle belongs + uint32_t smoothingMask; //!< Smoothing mask + uint32_t extraDataIndex; //!< Index of extra data + + /** + \brief Returns an unnormalized normal, in general + */ + PxVec3 calculateNormal() const + { + return (vertices[1].position - vertices[0].position).cross(vertices[2].position - vertices[0].position); + } +}; + + + +/** +\brief Descriptor for creating a rendering mesh part +*/ +struct RenderMeshPartData +{ + RenderMeshPartData() : triangleCount(0), userData(NULL) {} + + /** + \brief Constructor + */ + RenderMeshPartData(uint32_t _triCount, void* _data) : triangleCount(_triCount), userData(_data) {} + + uint32_t triangleCount; //!< Number of triangles in this mesh part + void* userData; //!< User definable pointer to part data, passed back to createTriangles +}; + + +/** +\brief Authoring interface for an RenderMeshAsset +*/ +class RenderMeshAssetAuthoring : public AssetAuthoring +{ +public: + /** \brief Vertex buffer class used for mesh creation */ + class VertexBuffer : public RenderBufferData<RenderVertexSemantic, RenderVertexSemantic::Enum> {}; + + /** \brief How the geometry is stored. Currently only supporting triangles. */ + struct Primitive + { + /** + \brief Enum of geometry stored types. + */ + enum Enum + { + TRIANGLE_LIST, + // TRIANGLE_STRIP, // Not supported for now + // TRIANGLE_FAN, // Not supported for now + + COUNT + }; + }; + + /** What kind of integer is used for indices. */ + struct IndexType + { + /** + \brief Enum of integers types using for indices. + */ + enum Enum + { + UINT, + USHORT, + + COUNT + }; + }; + + /** Description of one submesh, corresponding to one material. The vertex buffer format contains bone indices, so these do not need + to be described here. The submesh's partitioning into parts is described here. */ + class SubmeshDesc + { + public: + /** Name of material associated with this geometry. */ + const char* m_materialName; + + /** Vertex buffers for this submesh. One may pass in the same buffers for each submesh. */ + const VertexBuffer* m_vertexBuffers; + + /** Number of vertex buffers in m_VertexBuffers array. */ + uint32_t m_numVertexBuffers; + + /** Number of vertices. Each vertex buffer in m_VertexBuffers must have this many vertices. */ + uint32_t m_numVertices; + + /** How the geometry is represented. See the Primitive enum. */ + Primitive::Enum m_primitive; + + /** Type of the indices used in m_VertexIndices. See the IndexType enum. */ + IndexType::Enum m_indexType; + + /** Buffer of vertex indices, stored as described by primitive and indexSize. If NULL, m_vertexIndices = {0,1,2,...} is implied. */ + const void* m_vertexIndices; + + /** Size (in indices) of m_VertexIndices. */ + uint32_t m_numIndices; + + /** + Smoothing groups associated with each triangle. The size of this array (if not NULL) must be appropriate for the m_primitive type. + Since only triangle lists are currently supported, the size of this array (if not NULL) must currently be m_numIndices/3. + */ + uint32_t* m_smoothingGroups; + + /** Vertex index offset. */ + uint32_t m_firstVertex; + + /** If not NULL, an array (of m_IndexType-sized indices) into m_VertexIndices, at the start of each part. */ + const void* m_partIndices; + + /** If m_PartIndices is not NULL, the number of parts. */ + uint32_t m_numParts; + + /** Winding order of the submesh */ + RenderCullMode::Enum m_cullMode; + + /** Constructor sets default values. */ + SubmeshDesc() + { + memset(this, 0, sizeof(SubmeshDesc)); + } + + /** Validity check, returns true if this descriptor contains valid fields. */ + bool isValid() const + { + return m_materialName != NULL && + m_vertexBuffers != NULL && // BRG - todo: check the vertex buffers for validity + m_numVertexBuffers > 0 && + m_numVertices > 0 && + m_primitive >= (Primitive::Enum)0 && m_primitive < Primitive::COUNT && + m_indexType >= (IndexType::Enum)0 && m_indexType < IndexType::COUNT && + m_numIndices > 0 && + (m_partIndices == NULL || m_numParts > 0) && + (m_cullMode == RenderCullMode::CLOCKWISE || m_cullMode == RenderCullMode::COUNTER_CLOCKWISE || m_cullMode == RenderCullMode::NONE); + } + }; + + /** Description of a mesh, used for authoring an Render mesh. It contains a number of vertex buffers and submeshes. */ + class MeshDesc + { + public: + /** Array of descriptors for the submeshes in this mesh. */ + const SubmeshDesc* m_submeshes; + + /** The number of elements in m_submeshes. */ + uint32_t m_numSubmeshes; + + /** Texture UV direction. */ + TextureUVOrigin::Enum m_uvOrigin; + + + + /** Constructor sets default values. */ + MeshDesc() : m_submeshes(NULL), m_numSubmeshes(0), m_uvOrigin(TextureUVOrigin::ORIGIN_TOP_LEFT) {} + + /** Validity check, returns true if this descriptor contains valid fields. */ + bool isValid() const + { + return m_submeshes != NULL && + m_numSubmeshes > 0; + } + }; + + + /** + \brief Mesh-building function. + \param [in] meshDesc contains the setup for all vertex buffers + \param [in] createMappingInformation A vertex buffer with remapping indices will be generated. The name of the buffer is VERTEX_ORIGINAL_INDEX + */ + virtual void createRenderMesh(const MeshDesc& meshDesc, bool createMappingInformation) = 0; + + + /** + Utility to reduce a vertex buffer of explicit vertices (Vertex). + The parameters 'map' and 'vertices' must point to arrays of size vertexCount. + The parameter 'smoothingGroups' must point to an array of size vertexCount, or be NULL. If not NULL, only vertices with equal smoothing groups will be merged. + Upon return, the map array will be filled in with remapped vertex positions for a new vertex buffer. + The return value is the number of vertices in the reduced buffer. + Note: this function does NOT actually create the new vertex buffer. + */ + virtual uint32_t createReductionMap(uint32_t* map, const Vertex* vertices, const uint32_t* smoothingGroups, uint32_t vertexCount, + const PxVec3& positionTolerance, float normalTolerance, float UVTolerance) = 0; + + + /** + If set, static data buffers will be deleted after they are used in createRenderResources. + */ + virtual void deleteStaticBuffersAfterUse(bool set) = 0; + + /** + Old mesh-building interface follows (DEPRECATED, to be removed by beta release): + */ + + /* Public access to RenderMeshAsset get methods */ + + /// \brief Return the number of submeshes + virtual uint32_t getSubmeshCount() const = 0; + /// \brief Return the number of mesh parts + virtual uint32_t getPartCount() const = 0; + /// \brief Return the name of a submesh + virtual const char* getMaterialName(uint32_t submeshIndex) const = 0; + /// \brief Set the name of a submesh + virtual void setMaterialName(uint32_t submeshIndex, const char* name) = 0; + /// \brief Set the winding order of a submesh + virtual void setWindingOrder(uint32_t submeshIndex, RenderCullMode::Enum winding) = 0; + /// \brief Return the winding order of a submesh + virtual RenderCullMode::Enum getWindingOrder(uint32_t submeshIndex) const = 0; + /// \brief Return a submesh + virtual const RenderSubmesh& getSubmesh(uint32_t submeshIndex) const = 0; + /// \brief Return a mutable submesh + virtual RenderSubmesh& getSubmeshWritable(uint32_t submeshIndex) = 0; + /// \brief Return the bounds of a mesh part + virtual const PxBounds3& getBounds(uint32_t partIndex = 0) const = 0; + /// \brief Get the asset statistics + virtual void getStats(RenderMeshAssetStats& stats) const = 0; +}; + + +/** +\brief Rendering mesh (data) class. + +To render a mesh asset, you must create an instance +*/ +class RenderMeshAsset : public Asset +{ +public: + + /** + \brief Instance this asset, return the created RenderMeshActor. + + See RenderMeshActor + */ + virtual RenderMeshActor* createActor(const RenderMeshActorDesc& desc) = 0; + + /** + \brief Releases an RenderMeshActor instanced by this asset. + */ + virtual void releaseActor(RenderMeshActor&) = 0; + + /** + \brief Number of submeshes. + + Each part effectively has the same number of submeshes, even if some are empty. + */ + virtual uint32_t getSubmeshCount() const = 0; + + /** + \brief Number of parts. + + These act as separate meshes, but they share submesh data (like materials). + */ + virtual uint32_t getPartCount() const = 0; + + /** + \brief Returns an array of length submeshCount() + */ + virtual const char* getMaterialName(uint32_t submeshIndex) const = 0; + + /** + \brief Returns an submesh + + A submesh contains all the triangles in all parts with the same material + (indexed by submeshIndex) + */ + virtual const RenderSubmesh& getSubmesh(uint32_t submeshIndex) const = 0; + + /** + \brief Returns the axis-aligned bounding box of the vertices for the given part. + + Valid range of partIndex is {0..partCount()-1} + */ + virtual const PxBounds3& getBounds(uint32_t partIndex = 0) const = 0; + + /** + \brief Returns stats (sizes, counts) for the asset. + + See RenderMeshAssetStats. + */ + virtual void getStats(RenderMeshAssetStats& stats) const = 0; + + /** + \brief Returns opaque mesh resource (NULL when opaque mesh isn't specified) + */ + virtual UserOpaqueMesh* getOpaqueMesh(void) const = 0; + +protected: + virtual ~RenderMeshAsset() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RENDER_MESH_ASSET_H diff --git a/APEX_1.4/include/Renderable.h b/APEX_1.4/include/Renderable.h new file mode 100644 index 00000000..6ac89bc9 --- /dev/null +++ b/APEX_1.4/include/Renderable.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDERABLE_H +#define RENDERABLE_H + +/*! +\file +\brief class Renderable +*/ + +#include "RenderDataProvider.h" + +namespace nvidia +{ +namespace apex +{ + +class UserRenderer; + +PX_PUSH_PACK_DEFAULT + +/** +\brief Base class of any actor that can be rendered + */ +class Renderable : public RenderDataProvider +{ +public: + /** + When called, this method will use the UserRenderer interface to render itself (if visible, etc) + by calling renderer.renderResource( RenderContext& ) as many times as necessary. See locking + semantics for RenderDataProvider::lockRenderResources(). + */ + virtual void dispatchRenderResources(UserRenderer& renderer) = 0; + + /** + Returns AABB covering rendered data. The actor's world bounds is updated each frame + during Scene::fetchResults(). This function does not require the Renderable actor to be locked. + */ + virtual PxBounds3 getBounds() const = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif diff --git a/APEX_1.4/include/ResourceCallback.h b/APEX_1.4/include/ResourceCallback.h new file mode 100644 index 00000000..f28b8576 --- /dev/null +++ b/APEX_1.4/include/ResourceCallback.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RESOURCE_CALLBACK_H +#define RESOURCE_CALLBACK_H + +/*! +\file +\brief class ResourceCallback +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief User defined callback for resource management + +The user may implement a subclass of this abstract class and provide an instance to the +ApexSDK descriptor. These callbacks can only be triggered directly by ApexSDK API calls, +so they do not need to be re-entrant or thread safe. +*/ +class ResourceCallback +{ +public: + virtual ~ResourceCallback() {} + + /** + \brief Request a resource from the user + + Will be called by the ApexSDK if a named resource is required but has not yet been provided. + The resource pointer is returned directly, ResourceProvider::setResource() should not be called. + This function will be called at most once per named resource, unless an intermediate call to + releaseResource() has been made. + + \note If this call results in the application calling ApexSDK::createAsset, the name given + to the asset must match the input name parameter in this method. + */ + virtual void* requestResource(const char* nameSpace, const char* name) = 0; + + /** + \brief Request the user to release a resource + + Will be called by the ApexSDK when all internal references to a named resource have been released. + If this named resource is required again in the future, a new call to requestResource() will be made. + */ + virtual void releaseResource(const char* nameSpace, const char* name, void* resource) = 0; +}; + +PX_POP_PACK + +} +} // namespace nvidia::apex + +#endif // RESOURCE_CALLBACK_H diff --git a/APEX_1.4/include/ResourceProvider.h b/APEX_1.4/include/ResourceProvider.h new file mode 100644 index 00000000..f7214a3f --- /dev/null +++ b/APEX_1.4/include/ResourceProvider.h @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RESOURCE_PROVIDER_H +#define RESOURCE_PROVIDER_H + +/*! +\file +\brief class ResourceProvider +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +class ResourceCallback; + +PX_PUSH_PACK_DEFAULT + +/*! +\brief A user provided class for mapping names to pointers or integers + +Named resource provider - a name-to-pointer utility. User must provide the pointed-to data. + - also supports name-to-integer +*/ + +class ResourceProvider +{ +public: + /** + \brief Register a callback + + Register a callback function for unresolved named resources. This function will be called by APEX when + an unresolved named resource is requested. The function will be called at most once for each named + resource. The function must directly return the pointer to the resource or NULL. + */ + virtual void registerCallback(ResourceCallback* impl) = 0; + + /** + \brief Provide the pointer for the specified named resource + */ + virtual void setResource(const char* nameSpace, const char* name, void* resource, bool incRefCount = false) = 0; + + + /** + \brief Provide the unsigned integer for the specified named resource + */ + virtual void setResourceU32(const char* nameSpace, const char* name, uint32_t id, bool incRefCount = false) = 0; + + /** + \brief Retrieve the pointer to the specified named resource. + + The game application (level loader) may use this to find assets by + name, as a convenience. If the named resource has not yet been + loaded it will trigger a call to ResourceCallback::requestResource(), + assuming an ResourceCallback instance was registered with the APEX SDK. + If the named resource has already been loaded, getResource will not + increment the reference count. + */ + virtual void* getResource(const char* nameSpace, const char* name) = 0; + + /** + \brief Releases all resources in this namespace. + \return the total number of resources released. + */ + virtual uint32_t releaseAllResourcesInNamespace(const char* nameSpace) = 0; + + /** + \brief Releases a single resource. + \return the outstanding referernce count after the release is performed. + */ + virtual uint32_t releaseResource(const char* nameSpace, const char* name) = 0; + + /** + \brief Reports if a current resource exists and, if so, the reference count. + */ + virtual bool findRefCount(const char* nameSpace, const char* name, uint32_t& refCount) = 0; + + /** + \brief Locates an existing resource + + This function will *not* call back to the application if the resource does not exist. + Only reports currently set resources. + */ + virtual void* findResource(const char* nameSpace, const char* name) = 0; + + /** + \brief Locates an existing integer resource. + */ + virtual uint32_t findResourceU32(const char* nameSpace, const char* name) = 0; + + /** + \brief Returns a list of all resources in a particular namespace. + */ + virtual void** findAllResources(const char* nameSpace, uint32_t& count) = 0; + + /** + \brief Returns a list of the names of all resources within a particular namespace + */ + virtual const char** findAllResourceNames(const char* nameSpace, uint32_t& count) = 0; + + /** + \brief Returns a list of all registered namespaces. + */ + virtual const char** findNameSpaces(uint32_t& count) = 0; + + /** + \brief Write contents of resource table to error stream. + */ + virtual void dumpResourceTable() = 0; + + /** + \brief Returns if the resource provider is operating in a case sensitive mode. + + \note By default the resource provider is NOT case sensitive + + \note It's not possible to change the case sensitivity of the NRP + once the APEX SDK is created, so the the switch is available in the + ApexSDKDesc::resourceProviderIsCaseSensitive member variable. + */ + virtual bool isCaseSensitive() = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // RESOURCE_PROVIDER_H diff --git a/APEX_1.4/include/Scene.h b/APEX_1.4/include/Scene.h new file mode 100644 index 00000000..1cc11325 --- /dev/null +++ b/APEX_1.4/include/Scene.h @@ -0,0 +1,686 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef SCENE_H +#define SCENE_H + +/*! +\file +\brief classes Scene, SceneStats, SceneDesc +*/ + +#include "ApexDesc.h" +#include "Renderable.h" +#include "RenderDebugInterface.h" +#include "Context.h" +#include "foundation/PxVec3.h" +#include <ApexDefs.h> + +#if PX_PHYSICS_VERSION_MAJOR == 3 +#include "PxFiltering.h" +#endif +#include "MirrorScene.h" + +namespace NvParameterized +{ +class Interface; +} + +namespace physx +{ + class PxBaseTask; + class PxTaskManager; + class PxCpuDispatcher; + class PxGpuDispatcher; +} + +namespace nvidia +{ +namespace apex +{ +// Forward declaration for the PhysX3Interface::setContactReportFlags() callback +class DestructibleActor; + +PX_PUSH_PACK_DEFAULT + +#if PX_PHYSICS_VERSION_MAJOR == 3 +/** +\brief Interface used to call setter function for PhysX 3.0 +*/ +class PhysX3Interface +{ +public: + /** + \brief Set the current contact report pair flags any time the Destructible module creates a PhysX 3.x shape + + User can set the report pair flags to specified actor + */ + virtual void setContactReportFlags(PxShape* shape, physx::PxPairFlags flags, DestructibleActor* actor, uint16_t actorChunkIndex) = 0; + + /** + \brief Get the current contact report pair flags + + */ + virtual physx::PxPairFlags getContactReportFlags(const physx::PxShape* shape) const = 0; +}; +#endif + +/** +\brief Data used to initialize a new Scene +*/ +class SceneDesc : public ApexDesc +{ +public: + + PX_INLINE SceneDesc() : ApexDesc() + { + init(); + } + + PX_INLINE void setToDefault() + { + ApexDesc::setToDefault(); + init(); + } + + + /** \brief Give this ApexScene an existing PxScene + + The ApexScene will use the same CpuDispatcher and GpuDispatcher that were + provided to the PxScene when it was created. There is no need to provide + these pointers in the ApexScene descriptor. + */ + PxScene* scene; + + /** \brief Give this ApexScene an existing RenderDebugInterface + */ + RenderDebugInterface* debugInterface; + +#if PX_PHYSICS_VERSION_MAJOR == 0 + + /** + \brief Give this ApexScene a user defined CpuDispatcher + + If cpuDispatcher is NULL, the APEX SDK will create and use a default + thread pool. + */ + PxCpuDispatcher* cpuDispatcher; + + /** + \brief Give this ApexScene a user defined GpuDispatcher + + If gpuDispatcher is NULL, this APEX scene will not use any GPU accelerated + features. + */ + PxGpuDispatcher* gpuDispatcher; + +#elif PX_PHYSICS_VERSION_MAJOR == 3 + + /** \brief Give this ApexScene a user defined interface to the PhysX 3.* + */ + PhysX3Interface* physX3Interface; + +#endif + + /** + \brief Toggle the use of a legacy DebugRenderable for PhysX 2.8.x or PxRenderBuffer for 3.x + + If true, then debug rendering will happen through the legacy DebugRenderable interface. + If false (the default value) it will render through the UserRenderResources interface. + */ + bool useDebugRenderable; + + /** + \brief Transmits debug rendering to PVD2 as well + */ + bool debugVisualizeRemotely; + + /** + \brief If 'debugVisualizeLocally' is true, then debug visualization which is being transmitted remotely will also be shown locally as well. + */ + bool debugVisualizeLocally; + + /** + \brief Switch for particles (BasicIOS, ParticleIOS, FieldSampler) which defines whether to use CUDA or not. + */ + bool useCuda; + +private: + PX_INLINE void init() + { +#if PX_PHYSICS_VERSION_MAJOR == 0 + cpuDispatcher = 0; + gpuDispatcher = 0; +#elif PX_PHYSICS_VERSION_MAJOR == 3 + physX3Interface = 0; +#endif + scene = 0; + debugInterface = 0; + useDebugRenderable = false; + debugVisualizeRemotely = false; + debugVisualizeLocally = true; +#if APEX_CUDA_SUPPORT + useCuda = true; +#else + useCuda = false; +#endif + } +}; + + +/** +\brief APEX stat struct that contains the type enums +*/ +struct StatDataType +{ + /** + \brief Enum of the APEX stat types + */ + enum Enum + { + INVALID = 0, + STRING = 1, + INT = 2, + FLOAT = 3, + ENUM = 4, + BOOL = 5, + }; +}; + +/** +\brief data value definitions for stats (derived from openautomate) +*/ +typedef struct oaValueStruct +{ + union + { + char* String; + int32_t Int; + float Float; + char* Enum; + bool Bool; + }; +} StatValue; + +/** +\brief data value definitions for stats +*/ +typedef struct +{ + ///name + const char* StatName; + + ///type + StatDataType::Enum StatType; + + ///current value + StatValue StatCurrentValue; +} StatsInfo; + +/** +\brief Per scene statistics +*/ +struct SceneStats +{ + /**\brief The number of ApexStats structures stored. + */ + uint32_t numApexStats; + /**\brief Array of StatsInfo structures. + */ + StatsInfo* ApexStatsInfoPtr; +}; + +/** +\brief Types of view matrices handled by APEX + +USER_CUSTOMIZED : APEX simply uses the view matrix given. Need to setViewParams() +LOOK_AT_RH: APEX gets the eye direction and eye position based on this kind of matrix. +LOOK_AT_LH: APEX gets the eye direction and eye position based on this kind of matrix. + +*/ +struct ViewMatrixType +{ + /** + \brief Enum of the view matrices types + */ + enum Enum + { + USER_CUSTOMIZED = 0, + LOOK_AT_RH, + LOOK_AT_LH, + }; +}; + +/** +\brief Types of projection matrices handled by APEX + +USER_CUSTOMIZED : APEX simply uses the projection matrix given. Need to setProjParams() + +*/ +struct ProjMatrixType +{ + /** + \brief Enum of the projection matrices types + */ + enum Enum + { + USER_CUSTOMIZED = 0, + }; +}; + +/** +\brief Enum of the bounding box types +*/ +struct UserBoundingBoxFlags +{ + /** + \brief Enum of the bounding box types + */ + enum Enum + { + NONE = 1 << 0, + ENTER = 1 << 1, + LEAVE = 1 << 2 + }; +}; + +/** +\brief An APEX wrapper for an PxScene +*/ +class Scene : public Renderable, public Context, public ApexInterface +{ +public: + +#if PX_PHYSICS_VERSION_MAJOR == 3 + /** + \brief Associate an PxScene with this Scene. + + All Actors in the Scene will be added to the PxScene. + The PxScene pointer can be NULL, which will cause all APEX actors to be removed + from the previously specified PxScene. This must be done before the PxScene + can be released. + */ + virtual void setPhysXScene(PxScene* s) = 0; + + /** + \brief Retrieve the PxScene associated with this Scene + */ + virtual PxScene* getPhysXScene() const = 0; + +#endif + + /** + \brief Retrieve scene statistics + */ + virtual const SceneStats* getStats(void) const = 0; + + /** + \brief Start simulation of the APEX (and PhysX) scene + + Start simulation of the Actors and the PxScene associated with this Scene. + No Actors should be added, deleted, or modified until fetchResults() is called. + + Calls to simulate() should pair with calls to fetchResults(): + Each fetchResults() invocation corresponds to exactly one simulate() + invocation; calling simulate() twice without an intervening fetchResults() + or fetchResults() twice without an intervening simulate() causes an error + condition. + + \param[in] elapsedTime Amount of time to advance simulation by. <b>Range:</b> (0,inf) + + \param[in] finalStep should be left as true, unless your application is manually sub stepping APEX + (and PhysX) and you do not intend to try to render the output of intermediate steps. + + \param[in] completionTask if non-NULL, this task will have its refcount incremented in simulate(), then + decremented when the scene is ready to have fetchResults called. So the task will not run until the + application also calls removeReference() after calling simulate. + + \param[in] scratchMemBlock a memory region for physx to use for temporary data during simulation. This block may be reused by the application + after fetchResults returns. Must be aligned on a 16-byte boundary + + \param[in] scratchMemBlockSize the size of the scratch memory block. Must be a multiple of 16K. + */ + virtual void simulate(float elapsedTime, + bool finalStep = true, + PxBaseTask *completionTask = NULL, + void* scratchMemBlock = 0, + uint32_t scratchMemBlockSize = 0) = 0; + + /** + \brief Checks, and optionally blocks, for simulation completion. Updates scene state. + + Checks if Scene has completed simulating (optionally blocking for completion). Updates + new state of Actors and the PxScene. Returns true if simulation is complete. + + \param block [in] - block until simulation is complete + \param errorState [out] - error value is written to this address, if not NULL + */ + virtual bool fetchResults(bool block, uint32_t* errorState) = 0; + + /** + \brief Returns an DebugRenderable object that contains the data for debug rendering of this scene + */ + virtual const PxRenderBuffer* getRenderBuffer() const = 0; + + /** + \brief Returns an DebugRenderable object that contains the data for debug rendering of this scene, in screenspace + */ + virtual const PxRenderBuffer* getRenderBufferScreenSpace() const = 0; + + /** + \brief Checks, and optionally blocks, for simulation completion. + + Performs same function as fetchResults(), but does not update scene state. fetchResults() + must still be called before the next simulation step can begin. + */ + virtual bool checkResults(bool block) const = 0; + + /** + \brief Allocate a view matrix. Returns a viewID that identifies this view matrix + for future calls to setViewMatrix(). The matrix is de-allocated automatically + when the scene is released. + + Each call of this function allocates space for one view matrix. Since many features in + APEX require a projection matrix it is _required_ that the application call this method. + Max calls restricted to 1 for now. + If ViewMatrixType is USER_CUSTOMIZED, setViewParams() as well using this viewID. + If connected to PVD, PVD camera is set up. + @see ViewMatrixType + @see setViewParams() + */ + virtual uint32_t allocViewMatrix(ViewMatrixType::Enum) = 0; + + /** + \brief Allocate a projection matrix. Returns a projID that identifies this projection matrix + for future calls to setProjMatrix(). The matrix is de-allocated automatically + when the scene is released. + + Each call of this function allocates space for one projection matrix. Since many features in + APEX require a projection matrix it is _required_ that the application call this method. + Max calls restricted to 1 for now. + If ProjMatrixType is USER_CUSTOMIZED, setProjParams() as well using this projID + @see ProjMatrixType + @see setProjParams() + */ + virtual uint32_t allocProjMatrix(ProjMatrixType::Enum) = 0; + + /** + \brief Returns the number of view matrices allocated. + */ + virtual uint32_t getNumViewMatrices() const = 0; + + /** + \brief Returns the number of projection matrices allocated. + */ + virtual uint32_t getNumProjMatrices() const = 0; + + /** + \brief Sets the view matrix for the given viewID. Should be called whenever the view matrix needs to be updated. + + If the given viewID's matrix type is identifiable as indicated in ViewMatrixType, eye position and eye direction are set as well, using values from this matrix. + Otherwise, make a call to setViewParams(). + If connected to PVD, PVD camera is updated. + */ + virtual void setViewMatrix(const PxMat44& viewTransform, const uint32_t viewID = 0) = 0; + + /** + \brief Returns the view matrix set by the user for the given viewID. + + @see setViewMatrix() + */ + virtual PxMat44 getViewMatrix(const uint32_t viewID = 0) const = 0; + + /** + \brief Sets the projection matrix for the given projID. Should be called whenever the projection matrix needs to be updated. + + Make a call to setProjParams(). + @see setProjParams() + */ + virtual void setProjMatrix(const PxMat44& projTransform, const uint32_t projID = 0) = 0; + + /** + \brief Returns the projection matrix set by the user for the given projID. + + @see setProjMatrix() + */ + virtual PxMat44 getProjMatrix(const uint32_t projID = 0) const = 0; + + /** + \brief Sets the use of the view matrix and projection matrix as identified by their IDs. Should be called whenever either matrices needs to be updated. + */ + virtual void setUseViewProjMatrix(const uint32_t viewID = 0, const uint32_t projID = 0) = 0; + + /** + \brief Sets the necessary information for the view matrix as identified by its viewID. Should be called whenever any of the listed parameters needs to be updated. + + @see ViewMatrixType + */ + virtual void setViewParams(const PxVec3& eyePosition, const PxVec3& eyeDirection, const PxVec3& worldUpDirection = PxVec3(0, 1, 0), const uint32_t viewID = 0) = 0; + + /** + \brief Sets the necessary information for the projection matrix as identified by its projID. Should be called whenever any of the listed parameters needs to be updated. + + @see ProjMatrixType + */ + virtual void setProjParams(float nearPlaneDistance, float farPlaneDistance, float fieldOfViewDegree, uint32_t viewportWidth, uint32_t viewportHeight, const uint32_t projID = 0) = 0; + + /** + \brief Returns the world space eye position. + + @see ViewMatrixType + @see setViewMatrix() + */ + virtual PxVec3 getEyePosition(const uint32_t viewID = 0) const = 0; + + /** + \brief Returns the world space eye direction. + + @see ViewMatrixType + @see setViewMatrix() + */ + virtual PxVec3 getEyeDirection(const uint32_t viewID = 0) const = 0; + + /** + \brief Returns the APEX scene's task manager + */ + virtual PxTaskManager* getTaskManager() const = 0; + + /** + \brief Toggle the use of a debug renderable + */ + virtual void setUseDebugRenderable(bool state) = 0; + + /** + \brief Gets debug rendering parameters from NvParameterized + */ + virtual ::NvParameterized::Interface* getDebugRenderParams() const = 0; + + /** + \brief Gets module debug rendering parameters from NvParameterized + */ + virtual ::NvParameterized::Interface* getModuleDebugRenderParams(const char* name) const = 0; + + /** + \brief Gets gravity value from PhysX or Apex scene for non PhysX configuration + */ + virtual PxVec3 getGravity() const = 0; + + /** + \brief Sets gravity for PhysX or Apex scene for non PhysX configuration + */ + virtual void setGravity(const PxVec3& gravity) = 0; + + +#if PX_PHYSICS_VERSION_MAJOR == 3 + /** + \brief Acquire the PhysX scene lock for read access. + + The PhysX 3.2.2 SDK (and higher) provides a multiple-reader single writer mutex lock to coordinate + access to the PhysX SDK API from multiple concurrent threads. This method will in turn invoke the + lockRead call on the PhysX Scene. The source code fileName and line number a provided for debugging + purposes. + */ + virtual void lockRead(const char *fileName,uint32_t lineo) = 0; + + /** + \brief Acquire the PhysX scene lock for write access. + + The PhysX 3.2.2 SDK (and higher) provides a multiple-reader single writer mutex lock to coordinate + access to the PhysX SDK API from multiple concurrent threads. This method will in turn invoke the + lockWrite call on the PhysX Scene. The source code fileName and line number a provided for debugging + purposes. + */ + virtual void lockWrite(const char *fileName,uint32_t lineno) = 0; + + /** + \brief Release the PhysX scene read lock + */ + virtual void unlockRead() = 0; + + /** + \brief Release the PhysX scene write lock + */ + virtual void unlockWrite() = 0; + + /** + \brief Allows the application to specify a pair of PhysX actors for the purposes of collision filtering. + + The set of methods addActorPair/removeActorPair and findActorPair can be used to implement collision filtering. + This is a feature typically required to implement ragdoll systems to prevent nearby bodies from generating + contacts which create jitter in the simulation; causing artifacts and preventing a ragdoll from coming to rest. + + These methods are not required but are helper methods available if needed by the application. + + \param actor0 The first actor in the actor pair to consider + \param actor1 The second actor in the actor pair to consider for filtering + */ + virtual void addActorPair(PxActor *actor0,PxActor *actor1) = 0; + + /** + \brief Removes a previously specified pair of actors from the actor-pair filter table + + \param actor0 The first actor in the actor pair to remove + \param actor1 The second actor in the actor pair to remove + */ + virtual void removeActorPair(PxActor *actor0,PxActor *actor1) = 0; + + /** + \brief This method is used to determine if two actor pairs match. + + If actor0 and actor1 were previously added to the actor-pair filter table, then this method will return true. + Order is not important, actor0+actor1 will return the same result as actor1+actor0 + + \param actor0 The first actor to consider + \param actor1 The second actor to consider + + \return Returns true if the two actors match false if they have not been previously defined. + */ + virtual bool findActorPair(PxActor *actor0,PxActor *actor1) const = 0; + + + /** + \brief Returns an MirrorScene helper class which keeps a primary APEX scene mirrored into a secondary scene. + + + \param mirrorScene [in] - The APEX scene that this scene will be mirrored into. + \param mirrorFilter [in] - The application provided callback interface to filter which actors/shapes get mirrored. + \param mirrorStaticDistance [in] - The distance to mirror static objects from the primary scene into the mirrored scene. + \param mirrorDynamicDistance [in] - The distance to mirror dynamic objects from the primary scene into the mirrored scene. + \param mirrorRefreshDistance [in] - The distance the camera should have moved before revising the trigger shapes controlling which actors get mirrored. + */ + virtual MirrorScene *createMirrorScene(nvidia::apex::Scene &mirrorScene, + MirrorScene::MirrorFilter &mirrorFilter, + float mirrorStaticDistance, + float mirrorDynamicDistance, + float mirrorRefreshDistance) = 0; +#endif + + + /** + \brief Adds user-defined bounding box into the scene. Each module can use these bounding boxes in a module-specific way. See documentation on each module. + Some modules might use it as a valid volume of simulation, deleting actors or parts of actors upon leaving a BB. + + + \param bounds [in] - The bounding box in world coordinates. + \param flags [in] - The flag for supplied bounding box. + */ + virtual void addBoundingBox(const PxBounds3& bounds, UserBoundingBoxFlags::Enum flags) = 0; + + /** + \brief Returns user-defined bounding box added previously. In case there is no bounding box for the given index, zero sized PxBounds3 is returned. + + + \param index [in] - Index of the bounding box. User could acquire total number of bounding boxes using getBoundingBoxCount. + */ + virtual const PxBounds3 getBoundingBox(const uint32_t index) const = 0; + + /** + \brief Returns user-defined bounding box flags. In case there is no bounding box (and its flags) for the given index, UserBoundingBoxFlags::NONE is returned. + + + \param index [in] - Index of the bounding box. User could acquire total number of bounding boxes using getBoundingBoxCount. + */ + virtual UserBoundingBoxFlags::Enum getBoundingBoxFlags(const uint32_t index) const = 0; + + /** + \brief Returns user-defined bounding box count. + */ + virtual uint32_t getBoundingBoxCount() const = 0; + + /** + \brief Removes user-defined bounding box at index. In case index is invalid (there is no bounding box for this index) nothing is happenning. + + \param index [in] - Index of the bounding box. User could acquire total number of bounding boxes using getBoundingBoxCount. + */ + virtual void removeBoundingBox(const uint32_t index) = 0; + + /** + \brief Removed all of the user-specified bounding boxes. + */ + virtual void removeAllBoundingBoxes() = 0; + + /** + \brief Returns CUDA test manager. For distribution builds return NULL + */ + virtual void* getCudaTestManager() const = 0; + + /** + \brief Returns CUDA profile manager. For distribution builds return NULL + */ + virtual void* getCudaProfileManager() const = 0; + + /** + \brief Enables/disables CUDA error check after each kernel launch. + + Use ONLY for DEBUG purposes, when enabled could dramatically slowdown performance! + */ + virtual void setCudaKernelCheckEnabled(bool enabled) = 0; + + /** + \brief Returns whether CUDA error check enabled + */ + virtual bool getCudaKernelCheckEnabled() const = 0; + +#if APEX_UE4 + /** + \brief Update gravity + */ + virtual void updateGravity() = 0; +#endif +}; + + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // SCENE_H diff --git a/APEX_1.4/include/ScopedPhysXLock.h b/APEX_1.4/include/ScopedPhysXLock.h new file mode 100644 index 00000000..47eb969a --- /dev/null +++ b/APEX_1.4/include/ScopedPhysXLock.h @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef SCOPED_PHYS_XLOCK_H + +#define SCOPED_PHYS_XLOCK_H + +#include "foundation/PxPreprocessor.h" +#include "ApexDefs.h" + + +#include "PxScene.h" +#include "Scene.h" + +namespace nvidia +{ + namespace apex + { + + /** + \brief This helper class creates a scoped read access to the PhysX SDK API + + This helper class is used to create a scoped read lock/unlock pair around a section of code + which is trying to do read access against the PhysX SDK. + */ + + class ScopedPhysXLockRead + { + public: + + /** + \brief Constructor for ScopedPhysXLockRead + \param[in] scene the APEX scene + \param[in] fileName used to determine what file called the lock for debugging purposes + \param[in] lineno used to determine what line number called the lock for debugging purposes + */ + ScopedPhysXLockRead(nvidia::Scene* scene, const char *fileName, int lineno) : mApexScene(scene), mPhysXScene(0) + { + if (mApexScene) + { + mApexScene->lockRead(fileName, (uint32_t)lineno); + } + } + + /** + \brief Constructor for ScopedPhysXLockRead + \param[in] scene the PhysX scene + \param[in] fileName used to determine what file called the lock for debugging purposes + \param[in] lineno used to determine what line number called the lock for debugging purposes + */ + ScopedPhysXLockRead(physx::PxScene* scene, const char *fileName, int lineno) : mPhysXScene(scene), mApexScene(0) + { + if (mPhysXScene) + { + mPhysXScene->lockRead(fileName, (uint32_t)lineno); + } + } + + ~ScopedPhysXLockRead() + { + if (mApexScene) + { + mApexScene->unlockRead(); + } + if (mPhysXScene) + { + mPhysXScene->unlockRead(); + } + } + private: + nvidia::Scene* mApexScene; + physx::PxScene* mPhysXScene; + }; + + /** + \brief This helper class creates a scoped write access to the PhysX SDK API + + This helper class is used to create a scoped write lock/unlock pair around a section of code + which is trying to do read access against the PhysX SDK. + */ + class ScopedPhysXLockWrite + { + public: + /** + \brief Constructor for ScopedPhysXLockWrite + \param[in] scene the APEX scene + \param[in] fileName used to determine what file called the lock for debugging purposes + \param[in] lineno used to determine what line number called the lock for debugging purposes + */ + ScopedPhysXLockWrite(nvidia::Scene *scene, const char *fileName, int lineno) : mApexScene(scene), mPhysXScene(0) + { + if (mApexScene) + { + mApexScene->lockWrite(fileName, (uint32_t)lineno); + } + } + + /** + \brief Constructor for ScopedPhysXLockWrite + \param[in] scene the PhysX scene + \param[in] fileName used to determine what file called the lock for debugging purposes + \param[in] lineno used to determine what line number called the lock for debugging purposes + */ + ScopedPhysXLockWrite(physx::PxScene *scene, const char *fileName, int lineno) : mPhysXScene(scene), mApexScene(0) + { + if (mPhysXScene) + { + mPhysXScene->lockWrite(fileName, (uint32_t)lineno); + } + } + + ~ScopedPhysXLockWrite() + { + if (mApexScene) + { + mApexScene->unlockWrite(); + } + if (mPhysXScene) + { + mPhysXScene->unlockWrite(); + } + } + private: + nvidia::Scene* mApexScene; + physx::PxScene* mPhysXScene; + }; + } +} + + +#if defined(_DEBUG) || PX_CHECKED +/** +\brief This macro creates a scoped write lock/unlock pair +*/ +#define SCOPED_PHYSX_LOCK_WRITE(x) nvidia::apex::ScopedPhysXLockWrite _wlock(x,__FILE__,__LINE__); +#else +/** +\brief This macro creates a scoped write lock/unlock pair +*/ +#define SCOPED_PHYSX_LOCK_WRITE(x) nvidia::apex::ScopedPhysXLockWrite _wlock(x,"",0); +#endif + +#if defined(_DEBUG) || PX_CHECKED +/** +\brief This macro creates a scoped read lock/unlock pair +*/ +#define SCOPED_PHYSX_LOCK_READ(x) nvidia::apex::ScopedPhysXLockRead _rlock(x,__FILE__,__LINE__); +#else +/** +\brief This macro creates a scoped read lock/unlock pair +*/ +#define SCOPED_PHYSX_LOCK_READ(x) nvidia::apex::ScopedPhysXLockRead _rlock(x,"",0); +#endif + + + +#endif diff --git a/APEX_1.4/include/Shape.h b/APEX_1.4/include/Shape.h new file mode 100644 index 00000000..1ad895de --- /dev/null +++ b/APEX_1.4/include/Shape.h @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef SHAPE_H +#define SHAPE_H + +/*! +\file +\brief class Shape +*/ + +#include "foundation/PxPreprocessor.h" +#include "ApexUsingNamespace.h" + +#include "ApexDefs.h" + +/*#if PX_PHYSICS_VERSION_MAJOR < 3 +#include "Nxp.h" +#endif*/ + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + + +class SphereShape; +class CapsuleShape; +class BoxShape; +class HalfSpaceShape; +class RenderDebugInterface; + +/** +\brief Describes the format of an Shape. +*/ +class Shape +{ +public: + + ///intersect the collision shape against a given AABB + virtual bool intersectAgainstAABB(PxBounds3) = 0; + + ///AABB of collision shape + virtual PxBounds3 getAABB() const = 0; + + ///If it is a box, cast to box class, return NULL otherwise + virtual const BoxShape* isBoxGeom() const + { + return NULL; + } + + ///If it is a sphere, cast to sphere class, return NULL otherwise + virtual const SphereShape* isSphereGeom() const + { + return NULL; + } + + ///If it is a capsule, cast to the capsule class, return NULL otherwise + virtual const CapsuleShape* isCapsuleGeom() const + { + return NULL; + } + + ///If it is a half space, cast to half space class, return NULL otherwise + virtual const HalfSpaceShape* isHalfSpaceGeom() const + { + return NULL; + } + + ///Release shape + virtual void releaseApexShape() = 0; + + ///Visualize shape + virtual void visualize(RenderDebugInterface* renderer) const = 0; + + ///get the pose of the shape + virtual PxMat44 getPose() const = 0; + + ///set the pose of the shape - this pose will modify the scale, orientation and position of the shape + virtual void setPose(PxMat44 pose) = 0; + + ///get the previous pose of the shape + virtual PxMat44 getPreviousPose() const = 0; +}; + +/// helper Sphere shape +class SphereShape : public Shape +{ +public: + ///get radius of the sphere + virtual float getRadius() const = 0; + + ///set radius of the sphere + virtual void setRadius(float radius) = 0; + +}; + +/// helper the capsule is oriented along the y axis by default and its total height is height+2*radius +class CapsuleShape : public Shape +{ +public: + ///get height and radius of the capsule + virtual void getDimensions(float& height, float& radius) const = 0; + + ///set height and radius of the capsule + virtual void setDimensions(float height, float radius) = 0; + +}; + +/// helper Box shape +class BoxShape : public Shape +{ +public: + ///set the length of the sides of the box. The default value is 1.0f for each of the sides. + ///the size of the sides can also be changed by using the setPose method + virtual void setSize(PxVec3 size) = 0; + + ///get size of the box + virtual PxVec3 getSize() const = 0; + +}; + +/// helper HalfSpace shape +class HalfSpaceShape : public Shape +{ +public: + ///set origin and normal of the halfspace + virtual void setOriginAndNormal(PxVec3 origin, PxVec3 normal) = 0; + + ///get normal of the halfspace + virtual PxVec3 getNormal() const = 0; + + ///get origin of the halfspace + virtual PxVec3 getOrigin() const = 0; + + ///get previous origin of the halfspace + virtual PxVec3 getPreviousOrigin() const = 0; +}; + + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // SHAPE_H diff --git a/APEX_1.4/include/TestBase.h b/APEX_1.4/include/TestBase.h new file mode 100644 index 00000000..60a20454 --- /dev/null +++ b/APEX_1.4/include/TestBase.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef TEST_BASE_H +#define TEST_BASE_H + +#include "ApexUsingNamespace.h" + +/*! +\file +\brief An TestBase is an interface for managing unit tests +*/ + +namespace nvidia +{ + +namespace apex +{ + +class Actor; + +/** + Interface for user's unit tests +*/ +class TestFunctionInterface +{ +public: + + /** + Constructor for TestFunctionInterface + */ + TestFunctionInterface(const char* name) : mName(name) {} + + /** + Run CPU tests, returns true if all tests passed + */ + virtual bool run(void*, void*) = 0; + + /** + Check state, true if user's test object in correct state + */ + virtual bool check(void*, void*) = 0; + + /** + Run GPU tests, returns true if all tests passed + */ + virtual bool runGpu(void*, void*, void*) = 0; + + /** + User's test name + */ + const char* mName; +}; + +/** + Defines the UnitTestsActor API which is instantiated from an UnitTestsAsset +*/ +class TestBase +{ +public: + + /** + \brief Returns the name of the test at this index. + + \param [in] unitTestsIndex : The test number to refer to; must be less than the result of getUnitTestCount + */ + virtual const char* getUnitTestsName(uint32_t unitTestsIndex) const = 0; + + /** + \brief Returns the index of the test for this name. + + \param [in] unitTestsName : The test name to refer to; if there is no such name method returns -1 + */ + virtual uint32_t getUnitTestsIndex(const char* unitTestsName) const = 0; + + /** + \brief run unit test + + \param [in] unitTestsID : The unit test number to refer to; must be less than the result of getUnitTestsCount + \param [in] dataPtr : The pointer to data which is needed for unit test. + */ + virtual bool runUnitTests(uint32_t unitTestsID, void* dataPtr) const = 0; + + /** + \brief check unit test + */ + virtual bool checkUnitTests(uint32_t unitTestsID, void* dataPtr) const = 0; + + /** + \brief returns the number of unit tests + */ + virtual uint32_t getUnitTestsCount() const = 0; + + /** + \brief set level of runtime check + \param [in] level - level of runtime check + + level = 0 - no runtime checks + level = 1 - easy-weight checks. Perfomance should not drop more than 10-20% + level = 2 - medium-weight checks. Perfomance drop less than 300-500% + level = 3 - hard-weight checks. Perfomance drop isn't limited + */ + virtual void setRuntimeCheckLevel(uint32_t level) = 0; +}; + + +}; // end of apex namespace +}; // end of nvidia namespace + +#endif diff --git a/APEX_1.4/include/UserOpaqueMesh.h b/APEX_1.4/include/UserOpaqueMesh.h new file mode 100644 index 00000000..f6b40051 --- /dev/null +++ b/APEX_1.4/include/UserOpaqueMesh.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_OPAQUE_MESH_H +#define USER_OPAQUE_MESH_H + +/*! +\file +\brief class UserOpaqueMesh +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +//! \brief Name of OpaqueMesh authoring type namespace +#define APEX_OPAQUE_MESH_NAME_SPACE "ApexOpaqueMesh" + +/** +\brief Opaque mesh description +*/ +class UserOpaqueMeshDesc +{ +public: + ///the name of the opaque mesh + const char* mMeshName; +}; + +/** +\brief An abstract interface to an opaque mesh +* +* An 'opaque' mesh is a binding between the 'name' of a mesh and some internal mesh representation used by the +* application. This allows the application to refer to meshes by name without involving duplciation of index buffer and +* vertex buffer data declarations. +*/ +class UserOpaqueMesh +{ +public: + virtual ~UserOpaqueMesh() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif diff --git a/APEX_1.4/include/UserRenderBoneBuffer.h b/APEX_1.4/include/UserRenderBoneBuffer.h new file mode 100644 index 00000000..5e1ef3f8 --- /dev/null +++ b/APEX_1.4/include/UserRenderBoneBuffer.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_BONE_BUFFER_H +#define USER_RENDER_BONE_BUFFER_H + +/*! +\file +\brief class UserRenderBoneBuffer +*/ + +#include "RenderBufferData.h" +#include "UserRenderBoneBufferDesc.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief type of the bone buffer data +*/ +class RenderBoneBufferData : public RenderBufferData<RenderBoneSemantic, RenderBoneSemantic::Enum> {}; + +/** +\brief Used for storing skeletal bone information used during skinning. + +Separated out into its own interface as we don't know how the user is going to implement this +it could be in another vertex buffer, a texture or just an array and skinned on CPU depending +on engine and hardware support. +*/ +class UserRenderBoneBuffer +{ +public: + virtual ~UserRenderBoneBuffer() {} + + /** + \brief Called when APEX wants to update the contents of the bone buffer. + + The source data type is assumed to be the same as what was defined in the descriptor. + APEX should call this function and supply data for ALL semantics that were originally + requested during creation every time its called. + + \param [in] data Contains the source data for the bone buffer. + \param [in] firstBone first bone to start writing to. + \param [in] numBones number of bones to write. + */ + virtual void writeBuffer(const nvidia::RenderBoneBufferData& data, uint32_t firstBone, uint32_t numBones) = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif diff --git a/APEX_1.4/include/UserRenderBoneBufferDesc.h b/APEX_1.4/include/UserRenderBoneBufferDesc.h new file mode 100644 index 00000000..ece07d68 --- /dev/null +++ b/APEX_1.4/include/UserRenderBoneBufferDesc.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_BONE_BUFFER_DESC_H +#define USER_RENDER_BONE_BUFFER_DESC_H + +/*! +\file +\brief class UserRenderBoneBufferDesc, structs RenderDataFormat and RenderBoneSemantic +*/ + +#include "RenderDataFormat.h" +#include "UserRenderResourceManager.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief The semantics available for bone buffers +*/ +struct RenderBoneSemantic +{ + /** + \brief Enum of the semantics available for bone buffers + */ + enum Enum + { + POSE = 0, //!< A matrix that transforms from object space into animated object space or even world space + PREVIOUS_POSE, //!< The corresponding poses from the last frame + NUM_SEMANTICS //!< Count of semantics, not a valid semantic. + }; +}; + + + +/** +\brief Descriptor to generate a bone buffer + +This descriptor is filled out by APEX and helps as a guide how the +bone buffer should be generated. +*/ +class UserRenderBoneBufferDesc +{ +public: + UserRenderBoneBufferDesc(void) + { + maxBones = 0; + hint = RenderBufferHint::STATIC; + for (uint32_t i = 0; i < RenderBoneSemantic::NUM_SEMANTICS; i++) + { + buffersRequest[i] = RenderDataFormat::UNSPECIFIED; + } + } + + /** + \brief Check if parameter's values are correct + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + return (numFailed == 0); + } + +public: + /** + \brief The maximum amount of bones this buffer will ever hold. + */ + uint32_t maxBones; + + /** + \brief Hint on how often this buffer is updated. + */ + RenderBufferHint::Enum hint; + + /** + \brief Array of semantics with the corresponding format. + + RenderDataFormat::UNSPECIFIED is used for semantics that are disabled + */ + RenderDataFormat::Enum buffersRequest[RenderBoneSemantic::NUM_SEMANTICS]; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif diff --git a/APEX_1.4/include/UserRenderCallback.h b/APEX_1.4/include/UserRenderCallback.h new file mode 100644 index 00000000..97b55e2a --- /dev/null +++ b/APEX_1.4/include/UserRenderCallback.h @@ -0,0 +1,394 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_CALLBACK_H +#define USER_RENDER_CALLBACK_H + +#include "RenderDataFormat.h" + +/** +\brief Cuda graphics resource +*/ +typedef struct CUgraphicsResource_st* CUgraphicsResource; + + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Render interop flags +*/ +struct RenderInteropFlags +{ + /** + \brief Enum of render interop flags + */ + enum Enum + { + NO_INTEROP = 0, + CUDA_INTEROP, + }; +}; + +/** +\brief Render map type +*/ +struct RenderMapType +{ + /** + \brief Enum of render map type + */ + enum Enum + { + MAP_READ = 1, + MAP_WRITE = 2, + MAP_READ_WRITE = 3, + MAP_WRITE_DISCARD = 4, + MAP_WRITE_NO_OVERWRITE = 5 + }; +}; + +/** +\brief User render data +*/ +class UserRenderData +{ +public: + + /** + \brief Add reference + */ + virtual void addRef() = 0; + + /** + \brief release data + */ + virtual void release() = 0; +}; + +/** +\brief User render data holder +*/ +class UserRenderDataHolder +{ +public: + UserRenderDataHolder() + : userData(NULL) + { + } + + ~UserRenderDataHolder() + { + if (userData) + { + userData->release(); + } + } + + /** + \brief Copy constructor for UserRenderDataHolder + */ + UserRenderDataHolder(const UserRenderDataHolder& other) + : userData(other.userData) + { + if (userData) + { + userData->addRef(); + } + } + + /** + \brief Assignment operator for UserRenderDataHolder + */ + UserRenderDataHolder& operator=(const UserRenderDataHolder& other) + { + setUserData(other.userData); + return *this; + } + + /** + \brief Set user render data + \see UserRenderData + */ + void setUserData(UserRenderData* newUserData) + { + if (userData != newUserData) + { + if (userData) + { + userData->release(); + } + userData = newUserData; + if (userData) + { + userData->addRef(); + } + } + } + + /** + \brief Get user render data + \see UserRenderData + */ + UserRenderData* getUserData() const + { + return userData; + } + +private: + + /** + \brief User render data + \see UserRenderData + */ + UserRenderData* userData; +}; + +/** +\brief User render storage +*/ +class UserRenderStorage +{ +public: + + /** + \brief Release user render storage + */ + virtual void release() = 0; + + /** + \brief Enum of user render storage type + */ + enum Type + { + BUFFER = 0, + SURFACE, + }; + + /** + \brief Returns type of user render storage + */ + virtual Type getType() const = 0; +}; + +/** +\brief User render buffer desc +*/ +struct UserRenderBufferDesc : public UserRenderDataHolder +{ + UserRenderBufferDesc(void) + { + setDefaults(); + } + + /** + \brief Default values + */ + void setDefaults() + { + size = 0; + setUserData(NULL); + userFlags = 0; + interopFlags = RenderInteropFlags::NO_INTEROP; + } + + /** + \brief Check if parameter's values are correct + */ + bool isValid(void) const + { + return (size > 0); + } + + /** + \brief Check if this object is the same as other + */ + bool isTheSameAs(const UserRenderBufferDesc& other) const + { + if (size != other.size) return false; + if (userFlags != other.userFlags) return false; + if (getUserData() != other.getUserData()) return false; + if (interopFlags != other.interopFlags) return false; + return true; + } + + size_t size; ///< Buffer size + uint32_t userFlags; ///< User flags + RenderInteropFlags::Enum interopFlags; ///< Interop flags +}; + +/** +\brief User render buffer +*/ +class UserRenderBuffer : public UserRenderStorage +{ +public: + + /** + \brief Returns BUFFER type + */ + virtual Type getType() const + { + return BUFFER; + } + + /** + \brief Returns CPU memory pointer to buffer content + \note CPU access + */ + virtual void* map(RenderMapType::Enum mapType, size_t offset = 0, size_t size = SIZE_MAX) = 0; + + /** + \brief Flush CPU buffer to GPU + */ + virtual void unmap() = 0; + + /** + \brief Returns graphics resource for CUDA Interop + \note GPU access + */ + virtual bool getCUDAgraphicsResource(CUgraphicsResource &ret) = 0; +}; + +/** +\brief User render surface desc +*/ +struct UserRenderSurfaceDesc : public UserRenderDataHolder +{ + UserRenderSurfaceDesc(void) + { + setDefaults(); + } + + /** + \brief Default values + */ + void setDefaults() + { + width = 0; + height = 0; + depth = 0; + format = RenderDataFormat::UNSPECIFIED; + setUserData(NULL); + userFlags = 0; + interopFlags = RenderInteropFlags::NO_INTEROP; + } + + /** + \brief Check if parameter's values are correct + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + numFailed += (width == 0); + numFailed += (format == RenderDataFormat::UNSPECIFIED); + return (numFailed == 0); + } + + /** + \brief Check if this object is the same as other + */ + bool isTheSameAs(const UserRenderSurfaceDesc& other) const + { + if (width != other.width) return false; + if (height != other.height) return false; + if (depth != other.depth) return false; + if (format != other.format) return false; + if (userFlags != other.userFlags) return false; + if (getUserData() != other.getUserData()) return false; + if (interopFlags != other.interopFlags) return false; + return true; + } + + size_t width; ///< Surface width + size_t height; ///< Surface height + size_t depth; ///< Surface depth + RenderDataFormat::Enum format; ///< Render data format + uint32_t userFlags; ///< User flags + RenderInteropFlags::Enum interopFlags; ///< Interop flags +}; + +/** +\brief User render surface +*/ +class UserRenderSurface : public UserRenderStorage +{ +public: + + /** + \brief Returns SURFACE type + */ + virtual Type getType() const + { + return SURFACE; + } + + /** + \brief Mapped information + */ + struct MappedInfo + { + void* pData; ///< Data pointer + uint32_t rowPitch; ///< Row pitch + uint32_t depthPitch; ///< Depth pitch + }; + + /** + \brief Returns CPU memory pointer to buffer content + \note CPU access + */ + virtual bool map(RenderMapType::Enum mapType, MappedInfo& info) = 0; + + /** + \brief Flush CPU buffer to GPU + */ + virtual void unmap() = 0; + + /** + \brief Returns graphics resource for CUDA Interop + \note GPU access + */ + virtual bool getCUDAgraphicsResource(CUgraphicsResource &ret) = 0; +}; + +/** +\brief User render callback +*/ +class UserRenderCallback +{ +public: + + /** + \brief Creates render buffer with specified UserRenderBufferDesc + */ + virtual UserRenderBuffer* createRenderBuffer(const UserRenderBufferDesc& ) + { + return NULL; + } + /** + \brief Creates render surface with specified UserRenderSurfaceDesc + */ + virtual UserRenderSurface* createRenderSurface(const UserRenderSurfaceDesc& ) + { + return NULL; + } +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif diff --git a/APEX_1.4/include/UserRenderIndexBuffer.h b/APEX_1.4/include/UserRenderIndexBuffer.h new file mode 100644 index 00000000..509082a5 --- /dev/null +++ b/APEX_1.4/include/UserRenderIndexBuffer.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_INDEX_BUFFER_H +#define USER_RENDER_INDEX_BUFFER_H + +/*! +\file +\brief class UserRenderIndexBuffer +*/ + +#include "ApexUsingNamespace.h" + +/** +\brief Cuda graphics resource +*/ +typedef struct CUgraphicsResource_st* CUgraphicsResource; + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Used for storing index data for rendering. +*/ +class UserRenderIndexBuffer +{ +public: + virtual ~UserRenderIndexBuffer() {} + + ///Get the low-level handle of the buffer resource (D3D resource pointer or GL buffer object ID) + ///\return true id succeeded, false otherwise + virtual bool getInteropResourceHandle(CUgraphicsResource& handle) +#if APEX_DEFAULT_NO_INTEROP_IMPLEMENTATION + { + PX_UNUSED(&handle); + return false; + } +#else + = 0; +#endif + + //! write some data into the buffer. + // the source data type is assumed to be the same as what was defined in the descriptor. + virtual void writeBuffer(const void* srcData, uint32_t srcStride, uint32_t firstDestElement, uint32_t numElements) = 0; +}; + +PX_POP_PACK + +} +} // namespace nvidia::apex + +#endif // USER_RENDER_INDEX_BUFFER_H diff --git a/APEX_1.4/include/UserRenderIndexBufferDesc.h b/APEX_1.4/include/UserRenderIndexBufferDesc.h new file mode 100644 index 00000000..e8c1fd92 --- /dev/null +++ b/APEX_1.4/include/UserRenderIndexBufferDesc.h @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_INDEX_BUFFER_DESC_H +#define USER_RENDER_INDEX_BUFFER_DESC_H + +/*! +\file +\brief class UserRenderIndexBufferDesc, structs RenderDataFormat and UserRenderIndexBufferDesc +*/ + +#include "RenderDataFormat.h" +#include "UserRenderResourceManager.h" + +namespace physx +{ + class PxCudaContextManager; +}; + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#if !PX_PS4 + #pragma warning(push) + #pragma warning(disable:4121) +#endif //!PX_PS4 + +/** +\brief describes the semantics and layout of an index buffer +*/ +class UserRenderIndexBufferDesc +{ +public: + UserRenderIndexBufferDesc(void) + { + registerInCUDA = false; + interopContext = 0; + maxIndices = 0; + hint = RenderBufferHint::STATIC; + format = RenderDataFormat::UNSPECIFIED; + primitives = RenderPrimitiveType::TRIANGLES; + } + + /** + \brief Check if parameter's values are correct + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + numFailed += (registerInCUDA && !interopContext) ? 1 : 0; + return (numFailed == 0); + } + +public: + + /** + \brief The maximum amount of indices this buffer will ever hold. + */ + uint32_t maxIndices; + + /** + \brief Hint on how often this buffer is updated + */ + RenderBufferHint::Enum hint; + + /** + \brief The format of this buffer (only one implied semantic) + */ + RenderDataFormat::Enum format; + + /** + \brief Rendering primitive type (triangle, line strip, etc) + */ + RenderPrimitiveType::Enum primitives; + + /** + \brief Declare if the resource must be registered in CUDA upon creation + */ + bool registerInCUDA; + + /** + \brief The CUDA context + + This context must be used to register and unregister the resource every time the + device is lost and recreated. + */ + PxCudaContextManager* interopContext; +}; + +#if !PX_PS4 + #pragma warning(pop) +#endif //!PX_PS4 + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // USER_RENDER_INDEX_BUFFER_DESC_H diff --git a/APEX_1.4/include/UserRenderInstanceBuffer.h b/APEX_1.4/include/UserRenderInstanceBuffer.h new file mode 100644 index 00000000..d879c9f6 --- /dev/null +++ b/APEX_1.4/include/UserRenderInstanceBuffer.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_INSTANCE_BUFFER_H +#define USER_RENDER_INSTANCE_BUFFER_H + +/*! +\file +\brief class UserRenderInstanceBuffer +*/ + +#include "RenderBufferData.h" +#include "UserRenderInstanceBufferDesc.h" + +/** +\brief Cuda graphics resource +*/ +typedef struct CUgraphicsResource_st* CUgraphicsResource; + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT +/** +\brief The instance buffer type (deprecated) +*/ +class PX_DEPRECATED RenderInstanceBufferData : public RenderBufferData<RenderInstanceSemantic, RenderInstanceSemantic::Enum> {}; + +/** +\brief Used for storing per-instance data for rendering. +*/ +class UserRenderInstanceBuffer +{ +public: + virtual ~UserRenderInstanceBuffer() {} + + ///Get the low-level handle of the buffer resource + ///\return true if succeeded, false otherwise + virtual bool getInteropResourceHandle(CUgraphicsResource& handle) +#if APEX_DEFAULT_NO_INTEROP_IMPLEMENTATION + { + PX_UNUSED(&handle); + return false; + } +#else + = 0; +#endif + /** + \brief Called when APEX wants to update the contents of the instance buffer. + + The source data type is assumed to be the same as what was defined in the descriptor. + APEX should call this function and supply data for ALL semantics that were originally + requested during creation every time its called. + + \param [in] data Contains the source data for the instance buffer. + \param [in] firstInstance first instance to start writing to. + \param [in] numInstances number of instance to write. + */ + virtual void writeBuffer(const void* data, uint32_t firstInstance, uint32_t numInstances) + { + PX_UNUSED(data); + PX_UNUSED(firstInstance); + PX_UNUSED(numInstances); + } +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // USER_RENDER_INSTANCE_BUFFER_H diff --git a/APEX_1.4/include/UserRenderInstanceBufferDesc.h b/APEX_1.4/include/UserRenderInstanceBufferDesc.h new file mode 100644 index 00000000..096497ce --- /dev/null +++ b/APEX_1.4/include/UserRenderInstanceBufferDesc.h @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_INSTANCE_BUFFER_DESC_H +#define USER_RENDER_INSTANCE_BUFFER_DESC_H + +/*! +\file +\brief class UserRenderInstanceBufferDesc, structs RenderDataFormat and RenderInstanceSemantic +*/ + +#include "UserRenderResourceManager.h" +#include "RenderDataFormat.h" + +namespace physx +{ + class PxCudaContextManager; +}; + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#if !PX_PS4 + #pragma warning(push) + #pragma warning(disable:4121) +#endif //!PX_PS4 + +/** +\brief Enumerates the potential instance buffer semantics +*/ +struct RenderInstanceSemantic +{ + /** + \brief Enume of the potential instance buffer semantics + */ + enum Enum + { + POSITION = 0, //!< position of instance + ROTATION_SCALE, //!< rotation matrix and scale baked together + VELOCITY_LIFE, //!< velocity and life remain (1.0=new .. 0.0=dead) baked together + DENSITY, //!< particle density at instance location + COLOR, //!< color of instance + UV_OFFSET, //!< an offset to apply to all U,V coordinates + LOCAL_OFFSET, //!< the static initial position offset of the instance + + USER_DATA, //!< User data - 32 bits + + POSE, //!< pose matrix + + NUM_SEMANTICS //!< Count of semantics, not a valid semantic. + }; +}; + +/** +\brief potential semantics of a sprite buffer +*/ +struct RenderInstanceLayoutElement +{ + /** + \brief Enum of sprite buffer semantics types + */ + enum Enum + { + POSITION_FLOAT3, + ROTATION_SCALE_FLOAT3x3, + VELOCITY_LIFE_FLOAT4, + DENSITY_FLOAT1, + COLOR_RGBA8, + COLOR_BGRA8, + COLOR_FLOAT4, + UV_OFFSET_FLOAT2, + LOCAL_OFFSET_FLOAT3, + USER_DATA_UINT1, + POSE_FLOAT3x4, + + NUM_SEMANTICS + }; + + /** + \brief Get semantic format + */ + static PX_INLINE RenderDataFormat::Enum getSemanticFormat(Enum semantic) + { + switch (semantic) + { + case POSITION_FLOAT3: + return RenderDataFormat::FLOAT3; + case ROTATION_SCALE_FLOAT3x3: + return RenderDataFormat::FLOAT3x3; + case VELOCITY_LIFE_FLOAT4: + return RenderDataFormat::FLOAT4; + case DENSITY_FLOAT1: + return RenderDataFormat::FLOAT1; + case COLOR_RGBA8: + return RenderDataFormat::R8G8B8A8; + case COLOR_BGRA8: + return RenderDataFormat::B8G8R8A8; + case COLOR_FLOAT4: + return RenderDataFormat::FLOAT4; + case UV_OFFSET_FLOAT2: + return RenderDataFormat::FLOAT2; + case LOCAL_OFFSET_FLOAT3: + return RenderDataFormat::FLOAT3; + case USER_DATA_UINT1: + return RenderDataFormat::UINT1; + case POSE_FLOAT3x4: + return RenderDataFormat::FLOAT3x4; + default: + PX_ALWAYS_ASSERT(); + return RenderDataFormat::NUM_FORMATS; + } + } +/** + \brief Get semantic from layout element format + */ + static PX_INLINE RenderInstanceSemantic::Enum getSemantic(Enum semantic) + { + switch (semantic) + { + case POSITION_FLOAT3: + return RenderInstanceSemantic::POSITION; + case ROTATION_SCALE_FLOAT3x3: + return RenderInstanceSemantic::ROTATION_SCALE; + case VELOCITY_LIFE_FLOAT4: + return RenderInstanceSemantic::VELOCITY_LIFE; + case DENSITY_FLOAT1: + return RenderInstanceSemantic::DENSITY; + case COLOR_RGBA8: + case COLOR_BGRA8: + case COLOR_FLOAT4: + return RenderInstanceSemantic::COLOR; + case UV_OFFSET_FLOAT2: + return RenderInstanceSemantic::UV_OFFSET; + case LOCAL_OFFSET_FLOAT3: + return RenderInstanceSemantic::LOCAL_OFFSET; + case USER_DATA_UINT1: + return RenderInstanceSemantic::USER_DATA; + case POSE_FLOAT3x4: + return RenderInstanceSemantic::POSE; + default: + PX_ALWAYS_ASSERT(); + return RenderInstanceSemantic::NUM_SEMANTICS; + } + } +}; + +/** +\brief Describes the data and layout of an instance buffer +*/ +class UserRenderInstanceBufferDesc +{ +public: + UserRenderInstanceBufferDesc(void) + { + setDefaults(); + } + + /** + \brief Default values + */ + void setDefaults() + { + registerInCUDA = false; + interopContext = 0; + maxInstances = 0; + hint = RenderBufferHint::STATIC; + for (uint32_t i = 0; i < RenderInstanceLayoutElement::NUM_SEMANTICS; i++) + { + semanticOffsets[i] = uint32_t(-1); + } + stride = 0; + } + + /** + \brief Check if parameter's values are correct + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + + numFailed += (maxInstances == 0); + numFailed += (stride == 0); + numFailed += (semanticOffsets[RenderInstanceLayoutElement::POSITION_FLOAT3] == uint32_t(-1)) + && (semanticOffsets[RenderInstanceLayoutElement::POSE_FLOAT3x4] == uint32_t(-1)); + numFailed += registerInCUDA && (interopContext == 0); + + numFailed += ((stride & 0x03) != 0); + for (uint32_t i = 0; i < RenderInstanceLayoutElement::NUM_SEMANTICS; i++) + { + if (semanticOffsets[i] != static_cast<uint32_t>(-1)) + { + numFailed += (semanticOffsets[i] >= stride); + numFailed += ((semanticOffsets[i] & 0x03) != 0); + } + } + + return (numFailed == 0); + } + + /** + \brief Check if this object is the same as other + */ + bool isTheSameAs(const UserRenderInstanceBufferDesc& other) const + { + if (registerInCUDA != other.registerInCUDA) return false; + if (maxInstances != other.maxInstances) return false; + if (hint != other.hint) return false; + + if (stride != other.stride) return false; + for (uint32_t i = 0; i < RenderInstanceLayoutElement::NUM_SEMANTICS; i++) + { + if (semanticOffsets[i] != other.semanticOffsets[i]) return false; + } + return true; + } + +public: + uint32_t maxInstances; //!< The maximum amount of instances this buffer will ever hold. + RenderBufferHint::Enum hint; //!< Hint on how often this buffer is updated. + + /** + \brief Array of the corresponding offsets (in bytes) for each semantic. + */ + uint32_t semanticOffsets[RenderInstanceLayoutElement::NUM_SEMANTICS]; + + uint32_t stride; //!< The stride between instances of this buffer. Required when CUDA interop is used! + + bool registerInCUDA; //!< Declare if the resource must be registered in CUDA upon creation + + /** + This context must be used to register and unregister the resource every time the + device is lost and recreated. + */ + PxCudaContextManager* interopContext; +}; + +#if !PX_PS4 + #pragma warning(pop) +#endif //!PX_PS4 + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // USER_RENDER_INSTANCE_BUFFER_DESC_H diff --git a/APEX_1.4/include/UserRenderResource.h b/APEX_1.4/include/UserRenderResource.h new file mode 100644 index 00000000..934cf544 --- /dev/null +++ b/APEX_1.4/include/UserRenderResource.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_RESOURCE_H +#define USER_RENDER_RESOURCE_H + +/*! +\file +\brief class UserRenderResource +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +class UserRenderVertexBuffer; +class UserRenderIndexBuffer; +class UserRenderBoneBuffer; +class UserRenderInstanceBuffer; +class UserRenderSpriteBuffer; + + +PX_PUSH_PACK_DEFAULT + +/** +\brief An abstract interface to a renderable resource +*/ +class UserRenderResource +{ +public: + virtual ~UserRenderResource() {} + + /** \brief Set vertex buffer range */ + virtual void setVertexBufferRange(uint32_t firstVertex, uint32_t numVerts) = 0; + /** \brief Set index buffer range */ + virtual void setIndexBufferRange(uint32_t firstIndex, uint32_t numIndices) = 0; + /** \brief Set bone buffer range */ + virtual void setBoneBufferRange(uint32_t firstBone, uint32_t numBones) = 0; + /** \brief Set instance buffer range */ + virtual void setInstanceBufferRange(uint32_t firstInstance, uint32_t numInstances) = 0; + /** \brief Set sprite buffer range */ + virtual void setSpriteBufferRange(uint32_t firstSprite, uint32_t numSprites) = 0; + /** \brief Set sprite visible count */ + virtual void setSpriteVisibleCount(uint32_t visibleCount) { PX_UNUSED(visibleCount); } + /** \brief Set material */ + virtual void setMaterial(void* material) = 0; + + /** \brief Get number of vertex buffers */ + virtual uint32_t getNbVertexBuffers() const = 0; + /** \brief Get vertex buffer */ + virtual UserRenderVertexBuffer* getVertexBuffer(uint32_t index) const = 0; + /** \brief Get index buffer */ + virtual UserRenderIndexBuffer* getIndexBuffer() const = 0; + /** \brief Get bone buffer */ + virtual UserRenderBoneBuffer* getBoneBuffer() const = 0; + /** \brief Get instance buffer */ + virtual UserRenderInstanceBuffer* getInstanceBuffer() const = 0; + /** \brief Get sprite buffer */ + virtual UserRenderSpriteBuffer* getSpriteBuffer() const = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif diff --git a/APEX_1.4/include/UserRenderResourceDesc.h b/APEX_1.4/include/UserRenderResourceDesc.h new file mode 100644 index 00000000..0e481ea0 --- /dev/null +++ b/APEX_1.4/include/UserRenderResourceDesc.h @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_RESOURCE_DESC_H +#define USER_RENDER_RESOURCE_DESC_H + +/*! +\file +\brief class UserRenderResourceDesc +*/ + +#include "UserRenderResourceManager.h" +#include "foundation/PxAssert.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class Renderable; +class UserOpaqueMesh; +class UserRenderVertexBuffer; +class UserRenderIndexBuffer; +class UserRenderBoneBuffer; +class UserRenderInstanceBuffer; +class UserRenderSpriteBuffer; + +/** +\brief Describes all the data that makes up a renderable resource +*/ +class UserRenderResourceDesc +{ +public: + UserRenderResourceDesc(void) + { + firstVertex = 0; + numVerts = 0; + + indexBuffer = 0; + firstIndex = 0; + numIndices = 0; + + boneBuffer = 0; + firstBone = 0; + numBones = 0; + + instanceBuffer = 0; + firstInstance = 0; + numInstances = 0; + + spriteBuffer = 0; + firstSprite = 0; + numSprites = 0; + visibleSpriteCount = 0; + + material = 0; + submeshIndex = 0; + + userRenderData = 0; + + numVertexBuffers = 0; + vertexBuffers = NULL; + + cullMode = RenderCullMode::CLOCKWISE; + primitives = RenderPrimitiveType::UNKNOWN; + + opaqueMesh = NULL; + } + + /** + \brief Checks if the resource is valid + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + if (numVertexBuffers >= 255) + { + numFailed++; + } + if (numIndices && !indexBuffer) + { + numFailed++; + } + if (numBones && !boneBuffer) + { + numFailed++; + } + if (numInstances && !instanceBuffer) + { + numFailed++; + } + if (numSprites && !spriteBuffer) + { + numFailed++; + } + PX_ASSERT(numFailed == 0); + return numFailed == 0; + } + +public: + UserOpaqueMesh* opaqueMesh; //!< A user specified opaque mesh interface. + UserRenderVertexBuffer** vertexBuffers; //!< vertex buffers used when rendering this resource. + //!< there should be no overlap in semantics between any two VBs. + uint32_t numVertexBuffers; //!< number of vertex buffers used when rendering this resource. + + uint32_t firstVertex; //!< First vertex to render + uint32_t numVerts; //!< Number of vertices to render + + UserRenderIndexBuffer* indexBuffer; //!< optional index buffer used when rendering this resource. + uint32_t firstIndex; //!< First index to render + uint32_t numIndices; //!< Number of indices to render + + UserRenderBoneBuffer* boneBuffer; //!< optional bone buffer used for skinned meshes. + uint32_t firstBone; //!< First bone to render + uint32_t numBones; //!< Number of bones to render + + UserRenderInstanceBuffer* instanceBuffer; //!< optional instance buffer if rendering multiple instances of the same resource. + uint32_t firstInstance; //!< First instance to render + uint32_t numInstances; //!< Number of instances to render + + UserRenderSpriteBuffer* spriteBuffer; //!< optional sprite buffer if rendering sprites + uint32_t firstSprite; //!< First sprite to render + uint32_t numSprites; //!< Number of sprites to render + uint32_t visibleSpriteCount; //!< If the sprite buffer is using the view direction modifier; this will represent the number of sprites visible in front of the camera (Not necessarily in the frustum but in front of the camera) + + UserRenderSurfaceBuffer** surfaceBuffers; //!< optional surface buffer for transferring variable to texture + uint32_t numSurfaceBuffers; //!< Number of surface buffers to render + uint32_t widthSurfaceBuffers;//!< The surface buffer width + uint32_t heightSurfaceBuffers;//!< The surface buffer height + + void* material; //!< user defined material used when rendering this resource. + uint32_t submeshIndex; //!< the index of the submesh that render resource belongs to + + //! user defined pointer originally passed in to Renderable::updateRenderResources(..) + void* userRenderData; + + RenderCullMode::Enum cullMode; //!< Triangle culling mode + RenderPrimitiveType::Enum primitives; //!< Rendering primitive type (triangle, line strip, etc) +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif diff --git a/APEX_1.4/include/UserRenderResourceManager.h b/APEX_1.4/include/UserRenderResourceManager.h new file mode 100644 index 00000000..99f7241a --- /dev/null +++ b/APEX_1.4/include/UserRenderResourceManager.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_RESOURCE_MANAGER_H +#define USER_RENDER_RESOURCE_MANAGER_H + +/*! +\file +\brief class UserRenderResourceManager, structs RenderPrimitiveType, RenderBufferHint, and RenderCullMode +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class UserRenderVertexBuffer; +class UserRenderVertexBufferDesc; +class UserRenderIndexBuffer; +class UserRenderIndexBufferDesc; +class UserRenderSurfaceBuffer; +class UserRenderSurfaceBufferDesc; +class UserRenderBoneBuffer; +class UserRenderBoneBufferDesc; +class UserRenderInstanceBuffer; +class UserRenderInstanceBufferDesc; +class UserRenderSpriteBuffer; +class UserRenderSpriteBufferDesc; +class UserRenderResource; +class UserRenderResourceDesc; +class UserOpaqueMesh; +class UserOpaqueMeshDesc; + +class UserRenderSpriteTextureDesc; + +/** +\brief Describe the implied vertex ordering +*/ +struct RenderPrimitiveType +{ + /** + \brief Enum of the implied vertex ordering types + */ + enum Enum + { + UNKNOWN = 0, + + TRIANGLES, + TRIANGLE_STRIP, + + LINES, + LINE_STRIP, + + POINTS, + POINT_SPRITES, + }; +}; + +/** +\brief Possible triangle culling modes +*/ +struct RenderCullMode +{ + /** + \brief Enum of possible triangle culling mode types + */ + enum Enum + { + CLOCKWISE = 0, + COUNTER_CLOCKWISE, + NONE + }; +}; + +/** +\brief Hint of the buffer data lifespan +*/ +struct RenderBufferHint +{ + /** + \brief Enum of hints of the buffer data lifespan + */ + enum Enum + { + STATIC = 0, + DYNAMIC, + STREAMING, + }; +}; + +/** +\brief User defined renderable resource manager + +A render resource manager is an object that creates and manages renderable resources... +This is given to the APEX SDK at creation time via the descriptor and must be persistent through the lifetime +of the SDK. +*/ +class UserRenderResourceManager +{ +public: + virtual ~UserRenderResourceManager() {} + + /** + The create methods in this class will only be called from the context of an Renderable::updateRenderResources() + call, but the release methods can be triggered by any APEX API call that deletes an Actor. It is up to + the end-user to make the release methods thread safe. + */ + + virtual UserRenderVertexBuffer* createVertexBuffer(const UserRenderVertexBufferDesc& desc) = 0; + /** \brief Release vertex buffer */ + virtual void releaseVertexBuffer(UserRenderVertexBuffer& buffer) = 0; + + /** \brief Create index buffer */ + virtual UserRenderIndexBuffer* createIndexBuffer(const UserRenderIndexBufferDesc& desc) = 0; + /** \brief Release index buffer */ + virtual void releaseIndexBuffer(UserRenderIndexBuffer& buffer) = 0; + + /** \brief Create bone buffer */ + virtual UserRenderBoneBuffer* createBoneBuffer(const UserRenderBoneBufferDesc& desc) = 0; + /** \brief Release bone buffer */ + virtual void releaseBoneBuffer(UserRenderBoneBuffer& buffer) = 0; + + /** \brief Create instance buffer */ + virtual UserRenderInstanceBuffer* createInstanceBuffer(const UserRenderInstanceBufferDesc& desc) = 0; + /** \brief Release instance buffer */ + virtual void releaseInstanceBuffer(UserRenderInstanceBuffer& buffer) = 0; + + /** \brief Create sprite buffer */ + virtual UserRenderSpriteBuffer* createSpriteBuffer(const UserRenderSpriteBufferDesc& desc) = 0; + /** \brief Release sprite buffer */ + virtual void releaseSpriteBuffer(UserRenderSpriteBuffer& buffer) = 0; + + /** \brief Create surface buffer */ + virtual UserRenderSurfaceBuffer* createSurfaceBuffer(const UserRenderSurfaceBufferDesc& desc) = 0; + /** \brief Release surface buffer */ + virtual void releaseSurfaceBuffer(UserRenderSurfaceBuffer& buffer) = 0; + + /** \brief Create resource */ + virtual UserRenderResource* createResource(const UserRenderResourceDesc& desc) = 0; + + /** + releaseResource() should not release any of the included buffer pointers. Those free methods will be + called separately by the APEX SDK before (or sometimes after) releasing the UserRenderResource. + */ + virtual void releaseResource(UserRenderResource& resource) = 0; + + /** + Get the maximum number of bones supported by a given material. Return 0 for infinite. + For optimal rendering, do not limit the bone count (return 0 from this function). + */ + virtual uint32_t getMaxBonesForMaterial(void* material) = 0; + + + /** \brief Get the sprite layout data + Returns true in case textureDescArray is set. + In case user is not interested in setting specific layout for sprite PS, + this function should return false. + */ + virtual bool getSpriteLayoutData(uint32_t spriteCount, uint32_t spriteSemanticsBitmap, UserRenderSpriteBufferDesc* textureDescArray) = 0; + + /** \brief Get the instance layout data + Returns true in case textureDescArray is set. + In case user is not interested in setting specific layout for sprite PS, + this function should return false. + */ + virtual bool getInstanceLayoutData(uint32_t spriteCount, uint32_t spriteSemanticsBitmap, UserRenderInstanceBufferDesc* instanceDescArray) = 0; + +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif diff --git a/APEX_1.4/include/UserRenderSpriteBuffer.h b/APEX_1.4/include/UserRenderSpriteBuffer.h new file mode 100644 index 00000000..791ed0ec --- /dev/null +++ b/APEX_1.4/include/UserRenderSpriteBuffer.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_SPRITE_BUFFER_H +#define USER_RENDER_SPRITE_BUFFER_H + +/*! +\file +\brief class UserRenderSpriteBuffer +*/ + +#include "RenderBufferData.h" +#include "UserRenderSpriteBufferDesc.h" + +/** +\brief Cuda graphics resource +*/ +typedef struct CUgraphicsResource_st* CUgraphicsResource; + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Sprite buffer data (deprecated) +*/ +class PX_DEPRECATED RenderSpriteBufferData : public RenderBufferData<RenderSpriteSemantic, RenderSpriteSemantic::Enum>, public ModuleSpecificRenderBufferData +{ +}; + +/** +\brief Used for storing per-sprite instance data for rendering. +*/ +class UserRenderSpriteBuffer +{ +public: + virtual ~UserRenderSpriteBuffer() {} + + /** + \brief Called when APEX wants to update the contents of the sprite buffer. + + The source data type is assumed to be the same as what was defined in the descriptor. + APEX should call this function and supply data for ALL semantics that were originally + requested during creation every time its called. + + \param [in] data Contains the source data for the sprite buffer. + \param [in] firstSprite first sprite to start writing to. + \param [in] numSprites number of vertices to write. + */ + virtual void writeBuffer(const void* data, uint32_t firstSprite, uint32_t numSprites) + { + PX_UNUSED(data); + PX_UNUSED(firstSprite); + PX_UNUSED(numSprites); + } + + ///Get the low-level handle of the buffer resource + ///\return true if succeeded, false otherwise + virtual bool getInteropResourceHandle(CUgraphicsResource& handle) +#if APEX_DEFAULT_NO_INTEROP_IMPLEMENTATION + { + PX_UNUSED(&handle); + return false; + } +#else + = 0; +#endif + + /** + \brief Get interop texture handle list + */ + virtual bool getInteropTextureHandleList(CUgraphicsResource* handleList) + { + PX_UNUSED(handleList); + return false; + } + + /** + \brief Write data to the texture + */ + virtual void writeTexture(uint32_t textureId, uint32_t numSprites, const void* srcData, size_t srcSize) + { + PX_UNUSED(textureId); + PX_UNUSED(numSprites); + PX_UNUSED(srcData); + PX_UNUSED(srcSize); + + PX_ALWAYS_ASSERT(); + } +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // USER_RENDER_SPRITE_BUFFER_H diff --git a/APEX_1.4/include/UserRenderSpriteBufferDesc.h b/APEX_1.4/include/UserRenderSpriteBufferDesc.h new file mode 100644 index 00000000..b734d975 --- /dev/null +++ b/APEX_1.4/include/UserRenderSpriteBufferDesc.h @@ -0,0 +1,364 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_SPRITE_BUFFER_DESC_H +#define USER_RENDER_SPRITE_BUFFER_DESC_H + +/*! +\file +\brief class UserRenderSpriteBufferDesc, structs RenderDataFormat and RenderSpriteSemantic +*/ + +#include "ApexUsingNamespace.h" +#include "RenderDataFormat.h" +#include "UserRenderResourceManager.h" + +namespace physx +{ + class PxCudaContextManager; +}; + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#if !PX_PS4 + #pragma warning(push) + #pragma warning(disable:4121) +#endif //!PX_PS4 + +/** +\brief potential semantics of a sprite buffer +*/ +struct RenderSpriteSemantic +{ + /** + \brief Enum of sprite buffer semantics types + */ + enum Enum + { + POSITION = 0, //!< Position of sprite + COLOR, //!< Color of sprite + VELOCITY, //!< Linear velocity of sprite + SCALE, //!< Scale of sprite + LIFE_REMAIN, //!< 1.0 (new) .. 0.0 (dead) + DENSITY, //!< Particle density at sprite location + SUBTEXTURE, //!< Sub-texture index of sprite + ORIENTATION, //!< 2D sprite orientation (angle in radians, CCW in screen plane) + + USER_DATA, //!< User data - 32 bits (passed from Emitter) + + NUM_SEMANTICS //!< Count of semantics, not a valid semantic. + }; +}; + +/** +\brief potential semantics of a sprite buffer +*/ +struct RenderSpriteLayoutElement +{ + /** + \brief Enum of sprite buffer semantics types + */ + enum Enum + { + POSITION_FLOAT3, + COLOR_RGBA8, + COLOR_BGRA8, + COLOR_FLOAT4, + VELOCITY_FLOAT3, + SCALE_FLOAT2, + LIFE_REMAIN_FLOAT1, + DENSITY_FLOAT1, + SUBTEXTURE_FLOAT1, + ORIENTATION_FLOAT1, + USER_DATA_UINT1, + + NUM_SEMANTICS + }; + + /** + \brief Get semantic format + */ + static PX_INLINE RenderDataFormat::Enum getSemanticFormat(Enum semantic) + { + switch (semantic) + { + case POSITION_FLOAT3: + return RenderDataFormat::FLOAT3; + case COLOR_RGBA8: + return RenderDataFormat::R8G8B8A8; + case COLOR_BGRA8: + return RenderDataFormat::B8G8R8A8; + case COLOR_FLOAT4: + return RenderDataFormat::FLOAT4; + case VELOCITY_FLOAT3: + return RenderDataFormat::FLOAT3; + case SCALE_FLOAT2: + return RenderDataFormat::FLOAT2; + case LIFE_REMAIN_FLOAT1: + return RenderDataFormat::FLOAT1; + case DENSITY_FLOAT1: + return RenderDataFormat::FLOAT1; + case SUBTEXTURE_FLOAT1: + return RenderDataFormat::FLOAT1; + case ORIENTATION_FLOAT1: + return RenderDataFormat::FLOAT1; + case USER_DATA_UINT1: + return RenderDataFormat::UINT1; + default: + PX_ALWAYS_ASSERT(); + return RenderDataFormat::NUM_FORMATS; + } + } +/** + \brief Get semantic from layout element format + */ + static PX_INLINE RenderSpriteSemantic::Enum getSemantic(Enum semantic) + { + switch (semantic) + { + case POSITION_FLOAT3: + return RenderSpriteSemantic::POSITION; + case COLOR_RGBA8: + case COLOR_BGRA8: + case COLOR_FLOAT4: + return RenderSpriteSemantic::COLOR; + case VELOCITY_FLOAT3: + return RenderSpriteSemantic::VELOCITY; + case SCALE_FLOAT2: + return RenderSpriteSemantic::SCALE; + case LIFE_REMAIN_FLOAT1: + return RenderSpriteSemantic::LIFE_REMAIN; + case DENSITY_FLOAT1: + return RenderSpriteSemantic::DENSITY; + case SUBTEXTURE_FLOAT1: + return RenderSpriteSemantic::SUBTEXTURE; + case ORIENTATION_FLOAT1: + return RenderSpriteSemantic::ORIENTATION; + case USER_DATA_UINT1: + return RenderSpriteSemantic::USER_DATA; + default: + PX_ALWAYS_ASSERT(); + return RenderSpriteSemantic::NUM_SEMANTICS; + } + } +}; + +/** +\brief Struct for sprite texture layout info +*/ +struct RenderSpriteTextureLayout +{ + /** + \brief Enum of sprite texture layout info + */ + enum Enum + { + NONE = 0, + POSITION_FLOAT4, //float4(POSITION.x, POSITION.y, POSITION.z, 1) + SCALE_ORIENT_SUBTEX_FLOAT4, //float4(SCALE.x, SCALE.y, ORIENTATION, SUBTEXTURE) + COLOR_RGBA8, + COLOR_BGRA8, + COLOR_FLOAT4, + NUM_LAYOUTS + }; + + /** + \brief Get layout format + */ + static PX_INLINE RenderDataFormat::Enum getLayoutFormat(Enum layout) + { + switch (layout) + { + case NONE: + return RenderDataFormat::UNSPECIFIED; + case POSITION_FLOAT4: + return RenderDataFormat::FLOAT4; + case SCALE_ORIENT_SUBTEX_FLOAT4: + return RenderDataFormat::FLOAT4; + case COLOR_RGBA8: + return RenderDataFormat::R8G8B8A8; + case COLOR_BGRA8: + return RenderDataFormat::B8G8R8A8; + case COLOR_FLOAT4: + return RenderDataFormat::R32G32B32A32_FLOAT; + default: + PX_ALWAYS_ASSERT(); + return RenderDataFormat::NUM_FORMATS; + } + } + +}; + +/** +\brief Class for storing sprite texture render data +*/ +class UserRenderSpriteTextureDesc +{ +public: + RenderSpriteTextureLayout::Enum layout; //!< texture layout + uint32_t width; //!< texture width + uint32_t height; //!< texture height + uint32_t pitchBytes; //!< texture pitch bytes + uint32_t arrayIndex; //!< array index for array textures or cubemap face index + uint32_t mipLevel; //!< mipmap level + +public: + PX_INLINE UserRenderSpriteTextureDesc(void) + { + layout = RenderSpriteTextureLayout::NONE; + width = 0; + height = 0; + pitchBytes = 0; + + arrayIndex = 0; + mipLevel = 0; + } + + /** + \brief Check if this object is the same as other + */ + bool isTheSameAs(const UserRenderSpriteTextureDesc& other) const + { + if (layout != other.layout) return false; + if (width != other.width) return false; + if (height != other.height) return false; + if (pitchBytes != other.pitchBytes) return false; + if (arrayIndex != other.arrayIndex) return false; + if (mipLevel != other.mipLevel) return false; + return true; + } +}; + +/** +\brief describes the semantics and layout of a sprite buffer +*/ +class UserRenderSpriteBufferDesc +{ +public: + /** + \brief Max number of sprite textures + */ + static const uint32_t MAX_SPRITE_TEXTURES = 4; + + UserRenderSpriteBufferDesc(void) + { + setDefaults(); + } + + /** + \brief Default values + */ + void setDefaults() + { + maxSprites = 0; + hint = RenderBufferHint::STATIC; + registerInCUDA = false; + interopContext = 0; + + for (uint32_t i = 0; i < RenderSpriteLayoutElement::NUM_SEMANTICS; i++) + { + semanticOffsets[i] = static_cast<uint32_t>(-1); + } + stride = 0; + + textureCount = 0; + } + + /** + \brief Checks if data is correct + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + + numFailed += (maxSprites == 0); + numFailed += (textureCount == 0) && (stride == 0); + numFailed += (textureCount == 0) && (semanticOffsets[RenderSpriteLayoutElement::POSITION_FLOAT3] == uint32_t(-1)); + numFailed += registerInCUDA && (interopContext == 0); + + numFailed += ((stride & 0x03) != 0); + for (uint32_t i = 0; i < RenderSpriteLayoutElement::NUM_SEMANTICS; i++) + { + if (semanticOffsets[i] != static_cast<uint32_t>(-1)) + { + numFailed += (semanticOffsets[i] >= stride); + numFailed += ((semanticOffsets[i] & 0x03) != 0); + } + } + + return (numFailed == 0); + } + + /** + \brief Check if this object is the same as other + */ + bool isTheSameAs(const UserRenderSpriteBufferDesc& other) const + { + if (registerInCUDA != other.registerInCUDA) return false; + if (maxSprites != other.maxSprites) return false; + if (hint != other.hint) return false; + if (textureCount != other.textureCount) return false; + if (textureCount == 0) + { + if (stride != other.stride) return false; + for (uint32_t i = 0; i < RenderSpriteLayoutElement::NUM_SEMANTICS; i++) + { + if (semanticOffsets[i] != other.semanticOffsets[i]) return false; + } + } + else + { + for (uint32_t i = 0; i < textureCount; i++) + { + if (textureDescs[i].isTheSameAs(other.textureDescs[i]) == false) return false; + } + } + return true; + } + +public: + uint32_t maxSprites; //!< The maximum number of sprites that APEX will store in this buffer + RenderBufferHint::Enum hint; //!< A hint about the update frequency of this buffer + + /** + \brief Array of the corresponding offsets (in bytes) for each semantic. + */ + uint32_t semanticOffsets[RenderSpriteLayoutElement::NUM_SEMANTICS]; + + uint32_t stride; //!< The stride between sprites of this buffer. Required when CUDA interop is used! + + bool registerInCUDA; //!< Declare if the resource must be registered in CUDA upon creation + + /** + This context must be used to register and unregister the resource every time the + device is lost and recreated. + */ + PxCudaContextManager* interopContext; + + uint32_t textureCount; //!< the number of textures + UserRenderSpriteTextureDesc textureDescs[MAX_SPRITE_TEXTURES]; //!< an array of texture descriptors +}; + +#if !PX_PS4 + #pragma warning(pop) +#endif //!PX_PS4 + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // USER_RENDER_SPRITE_BUFFER_DESC_H diff --git a/APEX_1.4/include/UserRenderSurfaceBuffer.h b/APEX_1.4/include/UserRenderSurfaceBuffer.h new file mode 100644 index 00000000..61f7cf3f --- /dev/null +++ b/APEX_1.4/include/UserRenderSurfaceBuffer.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_SURFACE_BUFFER_H +#define USER_RENDER_SURFACE_BUFFER_H + +/*! +\file +\brief classes UserRenderSurfaceBuffer and RenderSurfaceBufferData +*/ + +#include "UserRenderSurfaceBufferDesc.h" + +/** +\brief Cuda graphics resource +*/ +typedef struct CUgraphicsResource_st* CUgraphicsResource; + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief surface buffer data +*/ +class RenderSurfaceBufferData {}; + +/** +\brief Used for storing per-vertex data for rendering. +*/ +class UserRenderSurfaceBuffer +{ +public: + virtual ~UserRenderSurfaceBuffer() {} + + /** + \brief Called when APEX wants to update the contents of the surface buffer. + + The source data type is assumed to be the same as what was defined in the descriptor. + + \param [in] srcData contains the source data for the surface buffer. + \param [in] srcPitch source data pitch (in bytes). + \param [in] srcHeight source data height. + \param [in] dstX first element to start writing in X-dimension. + \param [in] dstY first element to start writing in Y-dimension. + \param [in] dstZ first element to start writing in Z-dimension. + \param [in] width number of elements in X-dimension. + \param [in] height number of elements in Y-dimension. + \param [in] depth number of elements in Z-dimension. + */ + virtual void writeBuffer(const void* srcData, uint32_t srcPitch, uint32_t srcHeight, uint32_t dstX, uint32_t dstY, uint32_t dstZ, uint32_t width, uint32_t height, uint32_t depth) = 0; + + + ///Get the low-level handle of the buffer resource + ///\return true if succeeded, false otherwise + virtual bool getInteropResourceHandle(CUgraphicsResource& handle) +#if APEX_DEFAULT_NO_INTEROP_IMPLEMENTATION + { + PX_UNUSED(&handle); + return false; + } +#else + = 0; +#endif + +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // USER_RENDER_SURFACE_BUFFER_H diff --git a/APEX_1.4/include/UserRenderSurfaceBufferDesc.h b/APEX_1.4/include/UserRenderSurfaceBufferDesc.h new file mode 100644 index 00000000..a37c488f --- /dev/null +++ b/APEX_1.4/include/UserRenderSurfaceBufferDesc.h @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_SURFACE_BUFFER_DESC_H +#define USER_RENDER_SURFACE_BUFFER_DESC_H + +/*! +\file +\brief class UserRenderSurfaceBufferDesc, structs RenderDataFormat and RenderSurfaceSemantic +*/ + +#include "ApexUsingNamespace.h" +#include "UserRenderResourceManager.h" +#include "RenderDataFormat.h" +#include "ApexSDK.h" + +namespace physx +{ + class PxCudaContextManager; +} + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Describes the semantics and layout of a Surface buffer +*/ +class UserRenderSurfaceBufferDesc +{ +public: + UserRenderSurfaceBufferDesc(void) + { + setDefaults(); + } + + /** + \brief Default values + */ + void setDefaults() + { +// hint = RenderBufferHint::STATIC; + format = RenderDataFormat::UNSPECIFIED; + + width = 0; + height = 0; + depth = 1; + + //moduleIdentifier = 0; + + registerInCUDA = false; + interopContext = 0; +// stride = 0; + } + + /** + \brief Checks if the surface buffer descriptor is valid + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + numFailed += (format == RenderDataFormat::UNSPECIFIED); + numFailed += (width == 0) && (height == 0) && (depth == 0); + numFailed += registerInCUDA && (interopContext == 0); +// numFailed += registerInCUDA && (stride == 0); + + return (numFailed == 0); + } + +public: + /** + \brief The size of U-dimension. + */ + uint32_t width; + + /** + \brief The size of V-dimension. + */ + uint32_t height; + + /** + \brief The size of W-dimension. + */ + uint32_t depth; + + /** + \brief Data format of suface buffer. + */ + RenderDataFormat::Enum format; + + bool registerInCUDA; //!< Declare if the resource must be registered in CUDA upon creation + + /** + This context must be used to register and unregister the resource every time the + device is lost and recreated. + */ + PxCudaContextManager* interopContext; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // USER_RENDER_SURFACE_BUFFER_DESC_H diff --git a/APEX_1.4/include/UserRenderVertexBuffer.h b/APEX_1.4/include/UserRenderVertexBuffer.h new file mode 100644 index 00000000..04661f8e --- /dev/null +++ b/APEX_1.4/include/UserRenderVertexBuffer.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_VERTEX_BUFFER_H +#define USER_RENDER_VERTEX_BUFFER_H + +/*! +\file +\brief classes UserRenderVertexBuffer and RenderVertexBufferData +*/ + +#include "RenderBufferData.h" +#include "UserRenderVertexBufferDesc.h" + +#include "ApexUsingNamespace.h" + +/** +\brief Cuda graphics resource +*/ +typedef struct CUgraphicsResource_st* CUgraphicsResource; + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief vertex buffer data +*/ +class RenderVertexBufferData : public RenderBufferData<RenderVertexSemantic, RenderVertexSemantic::Enum>, public ModuleSpecificRenderBufferData +{ +}; + +/** +\brief Used for storing per-vertex data for rendering. +*/ +class UserRenderVertexBuffer +{ +public: + virtual ~UserRenderVertexBuffer() {} + + ///Get the low-level handle of the buffer resource (D3D resource pointer or GL buffer object ID) + ///\return true id succeeded, false otherwise + virtual bool getInteropResourceHandle(CUgraphicsResource& handle) +#if APEX_DEFAULT_NO_INTEROP_IMPLEMENTATION + { + PX_UNUSED(&handle); + return false; + } +#else + = 0; +#endif + + /** + \brief Called when APEX wants to update the contents of the vertex buffer. + + The source data type is assumed to be the same as what was defined in the descriptor. + APEX should call this function and supply data for ALL semantics that were originally + requested during creation every time its called. + + \param [in] data Contains the source data for the vertex buffer. + \param [in] firstVertex first vertex to start writing to. + \param [in] numVertices number of vertices to write. + */ + virtual void writeBuffer(const nvidia::RenderVertexBufferData& data, uint32_t firstVertex, uint32_t numVertices) = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // USER_RENDER_VERTEX_BUFFER_H diff --git a/APEX_1.4/include/UserRenderVertexBufferDesc.h b/APEX_1.4/include/UserRenderVertexBufferDesc.h new file mode 100644 index 00000000..ea72a085 --- /dev/null +++ b/APEX_1.4/include/UserRenderVertexBufferDesc.h @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDER_VERTEX_BUFFER_DESC_H +#define USER_RENDER_VERTEX_BUFFER_DESC_H + +/*! +\file +\brief class UserRenderVertexBufferDesc, structs RenderDataFormat and RenderVertexSemantic +*/ + +#include "ApexUsingNamespace.h" +#include "UserRenderResourceManager.h" +#include "RenderDataFormat.h" +#include "ApexSDK.h" + +namespace physx +{ + class PxCudaContextManager; +}; + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Potential semantics of a vertex buffer +*/ +struct RenderVertexSemantic +{ + /** + \brief Enum of vertex buffer semantics types + */ + enum Enum + { + CUSTOM = -1, //!< User-defined + + POSITION = 0, //!< Position of vertex + NORMAL, //!< Normal at vertex + TANGENT, //!< Tangent at vertex + BINORMAL, //!< Binormal at vertex + COLOR, //!< Color at vertex + TEXCOORD0, //!< Texture coord 0 of vertex + TEXCOORD1, //!< Texture coord 1 of vertex + TEXCOORD2, //!< Texture coord 2 of vertex + TEXCOORD3, //!< Texture coord 3 of vertex + BONE_INDEX, //!< Bone index of vertex + BONE_WEIGHT, //!< Bone weight of vertex + + DISPLACEMENT_TEXCOORD, //!< X Displacement map texture coord of vertex + DISPLACEMENT_FLAGS, //!< Displacement map flags of vertex + + NUM_SEMANTICS //!< Count of standard semantics, not a valid semantic + }; +}; + +/** +\brief Texture UV direction convention +*/ +struct TextureUVOrigin +{ + /** + \brief Enum of texture UV directions types + */ + enum Enum + { + ORIGIN_TOP_LEFT = 0, //!< Origin is at top left + ORIGIN_TOP_RIGHT = 1, //!< Origin is at top right + ORIGIN_BOTTOM_LEFT = 2, //!< Origin is at bottom left + ORIGIN_BOTTOM_RIGHT = 3, //!< Origin is at bottom right + + ORIGIN_UNKNOWN = 0xFFFFFFFF //!< Unknown origin + }; +}; + + +/** +\brief Describes the semantics and layout of a vertex buffer +*/ +class UserRenderVertexBufferDesc +{ +public: + UserRenderVertexBufferDesc(void) + { + interopContext = 0; + registerInCUDA = false; + maxVerts = 0; + hint = RenderBufferHint::STATIC; + for (uint32_t i = 0; i < RenderVertexSemantic::NUM_SEMANTICS; i++) + { + buffersRequest[i] = RenderDataFormat::UNSPECIFIED; + } + moduleIdentifier = 0; + numCustomBuffers = 0; + customBuffersIdents = NULL; + customBuffersRequest = NULL; + uvOrigin = TextureUVOrigin::ORIGIN_TOP_LEFT; + canBeShared = true; + } + + /** + \brief Checks if dsta is correct + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + if (maxVerts == 0) + { + numFailed++; + } + if (!customBuffersRequest) + { + uint32_t vertexSize = 0; + for (uint32_t i = 0; i < RenderVertexSemantic::NUM_SEMANTICS; i++) + { + vertexSize += RenderDataFormat::getFormatDataSize(buffersRequest[i]); + } + if (vertexSize == 0) + { + numFailed++; + } + } + return (numFailed == 0); + } + +public: + /** + \brief The maximum number of vertices that APEX will store in this buffer. + */ + uint32_t maxVerts; + + /** + \brief A hint about the update frequency of this buffer + */ + RenderBufferHint::Enum hint; + + /** + \brief Array of semantics with the corresponding format. + + RenderDataFormat::UNSPECIFIED is used for semantics that are disabled + */ + RenderDataFormat::Enum buffersRequest[RenderVertexSemantic::NUM_SEMANTICS]; + + /** + \brief List of custom semantics that will be provided for this VB. + */ + + /** + \brief The number of custom VB semantics. + */ + uint32_t numCustomBuffers; + + /** + \brief Array of custom buffer identifiers + */ + void** customBuffersIdents; + + /** + \brief Array of custom VB format types + */ + RenderDataFormat::Enum* customBuffersRequest; + + /** + \brief Identifier of module generating this request + */ + AuthObjTypeID moduleIdentifier; + + /** + \brief Texture UV direction convention. + */ + TextureUVOrigin::Enum uvOrigin; + + /** + \brief Buffer can be shared by multiple render resources + */ + bool canBeShared; + + /** + \brief Declare if the resource must be registered in CUDA upon creation + */ + bool registerInCUDA; + + /** + \brief The CUDA context + + This context must be used to register and unregister the resource every time the + device is lost and recreated. + */ + PxCudaContextManager* interopContext; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // USER_RENDER_VERTEX_BUFFER_DESC_H diff --git a/APEX_1.4/include/UserRenderer.h b/APEX_1.4/include/UserRenderer.h new file mode 100644 index 00000000..c289dc38 --- /dev/null +++ b/APEX_1.4/include/UserRenderer.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef USER_RENDERER_H +#define USER_RENDERER_H + +/*! +\file +\brief class UserRenderer +*/ + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderContext; + +/** +\brief User provided renderer interface +*/ +class UserRenderer +{ +public: + virtual ~UserRenderer() {} + /** + \brief Render a resource + + Renderable::dispatchRenderResouces() will call this + function as many times as possible to render all of the actor's + sub-meshes. + */ + virtual void renderResource(const RenderContext& context) = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif diff --git a/APEX_1.4/include/VertexFormat.h b/APEX_1.4/include/VertexFormat.h new file mode 100644 index 00000000..d694c397 --- /dev/null +++ b/APEX_1.4/include/VertexFormat.h @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef VERTEX_FORMAT_H +#define VERTEX_FORMAT_H + +/*! +\file +\brief class VertexFormat and struct VertexFormatFlag +*/ + +#include "ApexUsingNamespace.h" +#include "UserRenderResourceManager.h" +#include "UserRenderVertexBufferDesc.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Color stored in 32 bits +*/ +struct ColorRGBA +{ + ///Constructor + ColorRGBA() : r(0xFF), g(0xFF), b(0xFF), a(0xFF) {} + ///Constructor + ColorRGBA(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a) : r(_r), g(_g), b(_b), a(_a) {} + + ///color + uint8_t r; + ///color + uint8_t g; + ///color + uint8_t b; + ///color + uint8_t a; +}; + +/** +\brief Type of render data +*/ +struct RenderDataAccess +{ + /** + \brief Enum of type of render data + */ + enum Enum + { + STATIC = 0, + DYNAMIC, + STREAMING, + + ACCESS_TYPE_COUNT + }; +}; + +/** +\brief Describes the format of an VertexBuffer. +*/ +class VertexFormat +{ +public: + + enum + { + MAX_UV_COUNT = 4, + MAX_BONE_PER_VERTEX_COUNT = 4, + }; + + /** \brief Buffer ID */ + typedef uint32_t BufferID; + + + /** \brief Resets the format to the initial state */ + virtual void reset() = 0; + + + /** \brief Sets the winding (cull mode) for this format */ + virtual void setWinding(RenderCullMode::Enum winding) = 0; + + /** \brief Sets whether or not a separate bone buffer is used */ + virtual void setHasSeparateBoneBuffer(bool hasSeparateBoneBuffer) = 0; + + /** \brief Accessor to read winding (cull mode) */ + virtual RenderCullMode::Enum getWinding() const = 0; + + /** \brief Accessor to read if a seperate vertex buffer for bone indices and weights is generated */ + virtual bool hasSeparateBoneBuffer() const = 0; + + + /** \brief Returns a buffer name for a semantic. Returns NULL if the semantic is invalid */ + virtual const char* getSemanticName(RenderVertexSemantic::Enum semantic) const = 0; + + /** \brief Returns a buffer ID for a semantic. For custom buffers, use the getID() function. */ + virtual BufferID getSemanticID(RenderVertexSemantic::Enum semantic) const = 0; + + /** \brief Returns a buffer ID for a named buffer. For standard semantics, the getSemanticID( semantic ) function is faster, but + is equivalent to getID( getSemanticName( semantic ) ). Returns 0 if name == NULL */ + virtual BufferID getID(const char* name) const = 0; + + + /** \brief Adds a vertex buffer channel to this format + \param [in] name the name of a new buffer (use getSemanticName for standard semantics) + \return The buffer index. If the buffer for the semantic already exists, the index of the existing buffer is returned. Returns -1 if there is an error (e.g. name == NULL). + */ + virtual int32_t addBuffer(const char* name) = 0; + + /** \brief Removes a buffer + \param [in] index the buffer to remove + \return True if successful, false otherwise (if the buffer index was invalid) + */ + virtual bool bufferReplaceWithLast(uint32_t index) = 0; + + + /** \brief Set the format for a semantic + \return True if successful, false otherwise (if the buffer index was invalid) + */ + virtual bool setBufferFormat(uint32_t index, RenderDataFormat::Enum format) = 0; + + /** \brief Set the access type for a buffer (static, dynamic, etc.) + \return True if successful, false otherwise (if the buffer index was invalid) + */ + virtual bool setBufferAccess(uint32_t index, RenderDataAccess::Enum access) = 0; + + /** \brief Set whether or not the buffer should be serialized + \return True if successful, false otherwise (if the buffer index was invalid) + */ + virtual bool setBufferSerialize(uint32_t index, bool serialize) = 0; + + + /** \brief Accessor to read the name of a given buffer + \return The buffer name if successful, NULL otherwise. + */ + virtual const char* getBufferName(uint32_t index) const = 0; + + /** \brief Accessor to read the semantic of a given buffer + \return The buffer semantic if successful, RenderVertexSemantic::NUM_SEMANTICS otherwise. + */ + virtual RenderVertexSemantic::Enum getBufferSemantic(uint32_t index) const = 0; + + /** \brief Accessor to read the ID of a given buffer + \return The buffer semantic if successful, 0 otherwise. + */ + virtual BufferID getBufferID(uint32_t index) const = 0; + + /** \brief Get the format for a buffer + \return The buffer format if successful, RenderDataFormat::UNSPECIFIED otherwise. + */ + virtual RenderDataFormat::Enum getBufferFormat(uint32_t index) const = 0; + + /** \brief Get the access type for a buffer (static, dynamic, etc.) + \return The buffer access if successful, RenderDataAccess::ACCESS_TYPE_COUNT otherwise. + */ + virtual RenderDataAccess::Enum getBufferAccess(uint32_t index) const = 0; + + /** \brief Get whether or not the buffer should be serialized + \return Whether or not the buffer should be serialized if successful, false otherwise. + */ + virtual bool getBufferSerialize(uint32_t index) const = 0; + + + /** \brief Accessor to read the number of buffers */ + virtual uint32_t getBufferCount() const = 0; + + /** \brief Returns the number of buffers that are user-specified */ + virtual uint32_t getCustomBufferCount() const = 0; + + /** \brief Accessor to get the buffer index + If the buffer is not found, -1 is returned + */ + virtual int32_t getBufferIndexFromID(BufferID id) const = 0; + + +protected: + VertexFormat() {} + virtual ~VertexFormat() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // VERTEX_FORMAT_H diff --git a/APEX_1.4/include/basicfs/AttractorFSActor.h b/APEX_1.4/include/basicfs/AttractorFSActor.h new file mode 100644 index 00000000..89fd57a0 --- /dev/null +++ b/APEX_1.4/include/basicfs/AttractorFSActor.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef ATTRACTOR_FSACTOR_H +#define ATTRACTOR_FSACTOR_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class BasicFSAsset; + + +/** + \brief AttractorFS Actor class + */ +class AttractorFSActor : public Actor, public Renderable +{ +protected: + virtual ~AttractorFSActor() {} + +public: + /** + \brief Returns the asset the instance has been created from. + */ + virtual BasicFSAsset* getAttractorFSAsset() const = 0; + + /** + \brief Gets the current position of the actor + */ + virtual PxVec3 getCurrentPosition() const = 0; + + /** + \brief Sets the current position of the actor + */ + virtual void setCurrentPosition(const PxVec3& pos) = 0; + + /** + \brief Sets the attracting radius of the field + */ + virtual void setFieldRadius(float) = 0; + + /** + \brief Sets strength of the constant part of attracting field + */ + virtual void setConstFieldStrength(float) = 0; + + /** + \brief Sets strength coefficient for variable part of attracting field + */ + virtual void setVariableFieldStrength(float) = 0; + + /** + \brief Enable/Disable the field simulation + */ + virtual void setEnabled(bool isEnabled) = 0; + + /** + \brief Sets the uniform overall object scale + */ + virtual void setCurrentScale(float scale) = 0; + + /** + \brief Retrieves the uniform overall object scale + */ + virtual float getCurrentScale(void) const = 0; + +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // ATTRACTOR_FSACTOR_H diff --git a/APEX_1.4/include/basicfs/AttractorFSPreview.h b/APEX_1.4/include/basicfs/AttractorFSPreview.h new file mode 100644 index 00000000..e982f231 --- /dev/null +++ b/APEX_1.4/include/basicfs/AttractorFSPreview.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef ATTRACTOR_FSPREVIEW_H +#define ATTRACTOR_FSPREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderDebugInterface; + +/** + \brief The APEX_ATTRACT namespace contains the defines for setting the preview detail levels. + + ATTRACT_DRAW_NOTHING - draw nothing<BR> + ATTRACT_DRAW_SHAPE - draw the attractor shape<BR> + ATTRACT_DRAW_ASSET_INFO - draw the asset info in the screen space<BR> + ATTRACT_DRAW_FULL_DETAIL - draw all components of the preview<BR> +*/ +namespace APEX_ATTRACT +{ +/** + \def ATTRACT_DRAW_NOTHING + Draw no preview items. +*/ +static const uint32_t ATTRACT_DRAW_NOTHING = 0x00; +/** + \def ATTRACT_DRAW_SHAPE + Draw the shape. The top of the shape should be above ground and the bottom should be below ground. +*/ +static const uint32_t ATTRACT_DRAW_SHAPE = 0x01; +/** + \def ATTRACT_DRAW_ASSET_INFO + Draw the Asset Info in Screen Space. This displays the various asset members that are relevant to the current asset. + parameters that are not relevant because they are disabled are not displayed. +*/ + +static const uint32_t ATTRACT_DRAW_ASSET_INFO = 0x02; +/** + \def ATTRACT_DRAW_FULL_DETAIL + Draw all of the preview rendering items. +*/ +static const uint32_t ATTRACT_DRAW_FULL_DETAIL = (ATTRACT_DRAW_SHAPE + ATTRACT_DRAW_ASSET_INFO); +} + +/** +\brief This class provides the asset preview for APEX AttractorFS Assets. The class provides multiple levels of prevew +detail that can be selected individually. +*/ +class AttractorFSPreview : public AssetPreview +{ +public: + /** + \brief Set the radius of the attractor. + */ + virtual void setRadius(float radius) = 0; + + /** + Set the detail level of the preview rendering by selecting which features to enable.<BR> + Any, all, or none of the following masks may be added together to select what should be drawn.<BR> + The defines for the individual items are:<br> + ATTRACT_DRAW_NOTHING - draw nothing<BR> + ATTRACT_DRAW_SHAPE - draw the shape<BR> + ATTRACT_DRAW_ASSET_INFO - draw the turbulencefs asset info in the screen space<BR> + ATTRACT_DRAW_FULL_DETAIL - draw all components of the turbulencefs preview<BR> + All items may be drawn using the macro DRAW_FULL_DETAIL. + */ + virtual void setDetailLevel(uint32_t detail) = 0; +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // ATTRACTOR_FS_PREVIEW_H diff --git a/APEX_1.4/include/basicfs/BasicFSAsset.h b/APEX_1.4/include/basicfs/BasicFSAsset.h new file mode 100644 index 00000000..8f1e9693 --- /dev/null +++ b/APEX_1.4/include/basicfs/BasicFSAsset.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef BASIC_FSASSET_H +#define BASIC_FSASSET_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#define JET_FS_AUTHORING_TYPE_NAME "JetFSAsset" +#define ATTRACTOR_FS_AUTHORING_TYPE_NAME "AttractorFSAsset" +#define VORTEX_FS_AUTHORING_TYPE_NAME "VortexFSAsset" +#define NOISE_FS_AUTHORING_TYPE_NAME "NoiseFSAsset" +#define WIND_FS_AUTHORING_TYPE_NAME "WindFSAsset" + +/** + \brief BasicFS Asset class + */ +class BasicFSAsset : public Asset +{ +protected: + virtual ~BasicFSAsset() {} + +public: +}; + +/** + \brief BasicFS Asset Authoring class + */ +class BasicFSAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~BasicFSAssetAuthoring() {} + +public: +}; + + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // BASIC_FSASSET_H diff --git a/APEX_1.4/include/basicfs/JetFSActor.h b/APEX_1.4/include/basicfs/JetFSActor.h new file mode 100644 index 00000000..44de7efa --- /dev/null +++ b/APEX_1.4/include/basicfs/JetFSActor.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef JET_FSACTOR_H +#define JET_FSACTOR_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class BasicFSAsset; + + +/** + \brief JetFS Actor class + */ +class JetFSActor : public Actor, public Renderable +{ +protected: + virtual ~JetFSActor() {} + +public: + + /** + \brief Returns the asset the instance has been created from. + */ + virtual BasicFSAsset* getJetFSAsset() const = 0; + + /** + \brief Gets the current pose of the actor + */ + virtual PxMat44 getCurrentPose() const = 0; + + /** + \brief Sets the current pose of the actor + */ + virtual void setCurrentPose(const PxTransform& pose) = 0; + + /** + \brief Gets the current position of the actor + */ + virtual PxVec3 getCurrentPosition() const = 0; + + /** + \brief Sets the current position of the actor + */ + virtual void setCurrentPosition(const PxVec3& pos) = 0; + + /** + \brief Gets the current scale of the actor + */ + virtual float getCurrentScale() const = 0; + + /** + \brief Sets the current scale of the actor + */ + virtual void setCurrentScale(const float& scale) = 0; + + /** + \brief Sets the field strength + */ + virtual void setFieldStrength(float) = 0; + + /** + \brief Sets the field direction + */ + virtual void setFieldDirection(const PxVec3&) = 0; + + /** + \brief Enable/Disable the field simulation + */ + virtual void setEnabled(bool isEnabled) = 0; + +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // JET_FSACTOR_H diff --git a/APEX_1.4/include/basicfs/JetFSPreview.h b/APEX_1.4/include/basicfs/JetFSPreview.h new file mode 100644 index 00000000..c97607a0 --- /dev/null +++ b/APEX_1.4/include/basicfs/JetFSPreview.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef JET_FSPREVIEW_H +#define JET_FSPREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderDebugInterface; + +/** + \brief The APEX_JET namespace contains the defines for setting the preview detail levels. + + JET_DRAW_NOTHING - draw nothing<BR> + JET_DRAW_SHAPE - draw the shape<BR> + JET_DRAW_ASSET_INFO - draw the asset info in the screen space<BR> + JET_DRAW_FULL_DETAIL - draw all components of the preview<BR> +*/ +namespace APEX_JET +{ +/** + \def JET_DRAW_NOTHING + Draw no preview items. +*/ +static const uint32_t JET_DRAW_NOTHING = 0x00; +/** + \def JET_DRAW_SHAPE + Draw the shape. The top of the shape should be above ground and the bottom should be below ground. +*/ +static const uint32_t JET_DRAW_SHAPE = 0x01; +/** + \def JET_DRAW_ASSET_INFO + Draw the Asset Info in Screen Space. This displays the various asset members that are relevant to the current asset. + parameters that are not relevant because they are disabled are not displayed. +*/ +static const uint32_t JET_DRAW_ASSET_INFO = 0x02; +/** + \def JET_DRAW_FULL_DETAIL + Draw all of the preview rendering items. +*/ +static const uint32_t JET_DRAW_FULL_DETAIL = (JET_DRAW_SHAPE + JET_DRAW_ASSET_INFO); +} + +/** +\brief This class provides the asset preview for APEX TurbulenceFS Assets. The class provides multiple levels of prevew +detail that can be selected individually. +*/ +class JetFSPreview : public AssetPreview +{ +public: + /** + Set the detail level of the preview rendering by selecting which features to enable.<BR> + Any, all, or none of the following masks may be added together to select what should be drawn.<BR> + The defines for the individual items are:<br> + JET_DRAW_NOTHING - draw nothing<BR> + JET_DRAW_SHAPE - draw the shape<BR> + JET_DRAW_ASSET_INFO - draw the turbulencefs asset info in the screen space<BR> + JET_DRAW_FULL_DETAIL - draw all components of the turbulencefs preview<BR> + All items may be drawn using the macro DRAW_FULL_DETAIL. + */ + virtual void setDetailLevel(uint32_t detail) = 0; +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // JET_FSPREVIEW_H diff --git a/APEX_1.4/include/basicfs/ModuleBasicFS.h b/APEX_1.4/include/basicfs/ModuleBasicFS.h new file mode 100644 index 00000000..df6c7dda --- /dev/null +++ b/APEX_1.4/include/basicfs/ModuleBasicFS.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef MODULE_BASIC_FS_H +#define MODULE_BASIC_FS_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class BasicFSAsset; +class BasicFSAssetAuthoring; + + +/** + \brief BasicFS module class + */ +class ModuleBasicFS : public Module +{ +public: + +protected: + virtual ~ModuleBasicFS() {} +}; + + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // MODULE_BASIC_FS_H diff --git a/APEX_1.4/include/basicfs/NoiseFSActor.h b/APEX_1.4/include/basicfs/NoiseFSActor.h new file mode 100644 index 00000000..3c44cff1 --- /dev/null +++ b/APEX_1.4/include/basicfs/NoiseFSActor.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef NOISE_FSACTOR_H +#define NOISE_FSACTOR_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class BasicFSAsset; + + +/** + \brief JetFS Actor class + */ +class NoiseFSActor : public Actor, public Renderable +{ +protected: + virtual ~NoiseFSActor() {} + +public: + + /** + \brief Returns the asset the instance has been created from. + */ + virtual BasicFSAsset* getNoiseFSAsset() const = 0; + + /** + \brief Gets the current pose of the actor + */ + virtual PxMat44 getCurrentPose() const = 0; + + /** + \brief Sets the current pose of the actor + */ + virtual void setCurrentPose(const PxTransform& pose) = 0; + + /** + \brief Gets the current position of the actor + */ + virtual PxVec3 getCurrentPosition() const = 0; + + /** + \brief Sets the current position of the actor + */ + virtual void setCurrentPosition(const PxVec3& pos) = 0; + + /** + \brief Gets the current scale of the actor + */ + virtual float getCurrentScale() const = 0; + + /** + \brief Sets the current scale of the actor + */ + virtual void setCurrentScale(const float& scale) = 0; + + /** + \brief Sets the noise strength + */ + virtual void setNoiseStrength(float) = 0; + + /** + \brief Enable/Disable the field simulation + */ + virtual void setEnabled(bool isEnabled) = 0; + +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // NOISE_FSACTOR_H diff --git a/APEX_1.4/include/basicfs/NoiseFSPreview.h b/APEX_1.4/include/basicfs/NoiseFSPreview.h new file mode 100644 index 00000000..48446aac --- /dev/null +++ b/APEX_1.4/include/basicfs/NoiseFSPreview.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef NOISE_FSPREVIEW_H +#define NOISE_FSPREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderDebugInterface; + +/** + \brief The APEX_NOISE namespace contains the defines for setting the preview detail levels. + + NOISE_DRAW_NOTHING - draw nothing<BR> + NOISE_DRAW_SHAPE - draw the shape<BR> + NOISE_DRAW_ASSET_INFO - draw the asset info in the screen space<BR> + NOISE_DRAW_FULL_DETAIL - draw all components of the preview<BR> +*/ +namespace APEX_NOISE +{ +/** + \def NOISE_DRAW_NOTHING + Draw no preview items. +*/ +static const uint32_t NOISE_DRAW_NOTHING = 0x00; +/** + \def NOISE_DRAW_SHAPE + Draw the shape. The top of the shape should be above ground and the bottom should be below ground. +*/ +static const uint32_t NOISE_DRAW_SHAPE = 0x01; +/** + \def NOISE_DRAW_ASSET_INFO + Draw the Asset Info in Screen Space. This displays the various asset members that are relevant to the current asset. + parameters that are not relevant because they are disabled are not displayed. +*/ +static const uint32_t NOISE_DRAW_ASSET_INFO = 0x02; +/** + \def NOISE_DRAW_FULL_DETAIL + Draw all of the preview rendering items. +*/ +static const uint32_t NOISE_DRAW_FULL_DETAIL = (NOISE_DRAW_SHAPE + NOISE_DRAW_ASSET_INFO); +} + +/** +\brief This class provides the asset preview for APEX NoiseFS Assets. The class provides multiple levels of prevew +detail that can be selected individually. +*/ +class NoiseFSPreview : public AssetPreview +{ +public: + /** + Set the detail level of the preview rendering by selecting which features to enable.<BR> + Any, all, or none of the following masks may be added together to select what should be drawn.<BR> + The defines for the individual items are:<br> + NOISE_DRAW_NOTHING - draw nothing<BR> + NOISE_DRAW_SHAPE - draw the shape<BR> + NOISE_DRAW_ASSET_INFO - draw the asset info in the screen space<BR> + NOISE_DRAW_FULL_DETAIL - draw all components of the asset preview<BR> + All items may be drawn using the macro DRAW_FULL_DETAIL. + */ + virtual void setDetailLevel(uint32_t detail) = 0; +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // NOISE_FSPREVIEW_H diff --git a/APEX_1.4/include/basicfs/VortexFSActor.h b/APEX_1.4/include/basicfs/VortexFSActor.h new file mode 100644 index 00000000..e2ee9b1f --- /dev/null +++ b/APEX_1.4/include/basicfs/VortexFSActor.h @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef VORTEX_FSACTOR_H +#define VORTEX_FSACTOR_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class BasicFSAsset; + + +/** + \brief VortexFS Actor class + */ +class VortexFSActor : public Actor, public Renderable +{ +protected: + virtual ~VortexFSActor() {} + +public: + + /** + \brief Returns the asset the instance has been created from. + */ + virtual BasicFSAsset* getVortexFSAsset() const = 0; + + /** + \brief Gets the current pose of the actor + */ + virtual PxMat44 getCurrentPose() const = 0; + + /** + \brief Sets the current pose of the actor + */ + virtual void setCurrentPose(const PxTransform& pose) = 0; + + /** + \brief Gets the current position of the actor + */ + virtual PxVec3 getCurrentPosition() const = 0; + + /** + \brief Sets the current position of the actor + */ + virtual void setCurrentPosition(const PxVec3& pos) = 0; + + /** + \brief Sets the axis of the capsule in local coordinate system + */ + virtual void setAxis(const PxVec3&) = 0; + + /** + \brief Sets the height of the capsule + */ + virtual void setHeight(float) = 0; + + /** + \brief Sets the bottom radius of the capsule + */ + virtual void setBottomRadius(float) = 0; + + /** + \brief Sets the top radius of the capsule + */ + virtual void setTopRadius(float) = 0; + + /** + \brief Sets the bottom spherical force of the capsule + */ + virtual void setBottomSphericalForce(bool) = 0; + + /** + \brief Sets the top spherical force of the capsule + */ + virtual void setTopSphericalForce(bool) = 0; + + /** + \brief Sets strength of the rotational part of vortex field + */ + virtual void setRotationalStrength(float) = 0; + + /** + \brief Sets strength of the radial part of vortex field + */ + virtual void setRadialStrength(float) = 0; + + /** + \brief Sets strength of the lifting part of vortex field + */ + virtual void setLiftStrength(float) = 0; + + /** + \brief Enable/Disable the field simulation + */ + virtual void setEnabled(bool isEnabled) = 0; + + + /** + \brief Sets the uniform overall object scale + */ + virtual void setCurrentScale(float scale) = 0; + + /** + \brief Retrieves the uniform overall object scale + */ + virtual float getCurrentScale(void) const = 0; + +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // VORTEX_FSACTOR_H diff --git a/APEX_1.4/include/basicfs/VortexFSPreview.h b/APEX_1.4/include/basicfs/VortexFSPreview.h new file mode 100644 index 00000000..8270995d --- /dev/null +++ b/APEX_1.4/include/basicfs/VortexFSPreview.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef VORTEX_FSPREVIEW_H +#define VORTEX_FSPREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderDebugInterface; + +/** + \brief The APEX_VORTEX namespace contains the defines for setting the preview detail levels. + + VORTEX_DRAW_NOTHING - draw nothing<BR> + VORTEX_DRAW_SHAPE - draw the Vortex shape<BR> + VORTEX_DRAW_ASSET_INFO - draw the asset info in the screen space<BR> + VORTEX_DRAW_FULL_DETAIL - draw all components of the preview<BR> +*/ +namespace APEX_VORTEX +{ +/** + \def VORTEX_DRAW_NOTHING + Draw no preview items. +*/ +static const uint32_t VORTEX_DRAW_NOTHING = 0x00; +/** + \def VORTEX_DRAW_SHAPE + Draw the shape. The top of the shape should be above ground and the bottom should be below ground. +*/ +static const uint32_t VORTEX_DRAW_SHAPE = 0x01; +/** + \def VORTEX_DRAW_ASSET_INFO + Draw the Asset Info in Screen Space. This displays the various asset members that are relevant to the current asset. + parameters that are not relevant because they are disabled are not displayed. +*/ + +static const uint32_t VORTEX_DRAW_ASSET_INFO = 0x02; +/** + \def VORTEX_DRAW_FULL_DETAIL + Draw all of the preview rendering items. +*/ +static const uint32_t VORTEX_DRAW_FULL_DETAIL = (VORTEX_DRAW_SHAPE + VORTEX_DRAW_ASSET_INFO); +} + +/** +\brief This class provides the asset preview for APEX VortexFS Assets. The class provides multiple levels of prevew +detail that can be selected individually. +*/ +class VortexFSPreview : public AssetPreview +{ +public: + /** + \brief Set the radius of the vortex. + */ + virtual void setRadius(float radius) = 0; + /** + Set the detail level of the preview rendering by selecting which features to enable.<BR> + Any, all, or none of the following masks may be added together to select what should be drawn.<BR> + The defines for the individual items are:<br> + VORTEX_DRAW_NOTHING - draw nothing<BR> + VORTEX_DRAW_SHAPE - draw the shape<BR> + VORTEX_DRAW_ASSET_INFO - draw the turbulencefs asset info in the screen space<BR> + VORTEX_DRAW_FULL_DETAIL - draw all components of the turbulencefs preview<BR> + All items may be drawn using the macro DRAW_FULL_DETAIL. + */ + virtual void setDetailLevel(uint32_t detail) = 0; +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // VORTEX_FS_PREVIEW_H diff --git a/APEX_1.4/include/basicfs/WindFSActor.h b/APEX_1.4/include/basicfs/WindFSActor.h new file mode 100644 index 00000000..8d5a373c --- /dev/null +++ b/APEX_1.4/include/basicfs/WindFSActor.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef WIND_FSACTOR_H +#define WIND_FSACTOR_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class BasicFSAsset; + + +/** + \brief WindFS Actor class + */ +class WindFSActor : public Actor, public Renderable +{ +protected: + virtual ~WindFSActor() {} + +public: + + /** + \brief Returns the asset the instance has been created from. + */ + virtual BasicFSAsset* getWindFSAsset() const = 0; + + /** + \brief Gets the current pose of the actor + */ + virtual PxMat44 getCurrentPose() const = 0; + + /** + \brief Sets the current pose of the actor + */ + virtual void setCurrentPose(const PxTransform& pose) = 0; + + /** + \brief Gets the current position of the actor + */ + virtual PxVec3 getCurrentPosition() const = 0; + + /** + \brief Sets the current position of the actor + */ + virtual void setCurrentPosition(const PxVec3& pos) = 0; + + /** + \brief Sets the field strength + */ + virtual void setFieldStrength(float) = 0; + + /** + \brief Sets the field direction + */ + virtual void setFieldDirection(const PxVec3&) = 0; + + /** + \brief Enable/Disable the field simulation + */ + virtual void setEnabled(bool isEnabled) = 0; + + /** + \brief Sets the uniform overall object scale + */ + virtual void setCurrentScale(float scale) = 0; + + /** + \brief Retrieves the uniform overall object scale + */ + virtual float getCurrentScale(void) const = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // WIND_FSACTOR_H diff --git a/APEX_1.4/include/basicfs/WindFSPreview.h b/APEX_1.4/include/basicfs/WindFSPreview.h new file mode 100644 index 00000000..04b9ed04 --- /dev/null +++ b/APEX_1.4/include/basicfs/WindFSPreview.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef WIND_FSPREVIEW_H +#define WIND_FSPREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderDebugInterface; + +/** + \brief The APEX_WIND namespace contains the defines for setting the preview detail levels. + + WIND_DRAW_NOTHING - draw nothing<BR> + WIND_DRAW_ASSET_INFO - draw the asset info in the screen space<BR> + WIND_DRAW_FULL_DETAIL - draw all components of the preview<BR> +*/ +namespace APEX_WIND +{ +/** + \def WIND_DRAW_NOTHING + Draw no preview items. +*/ +static const uint32_t WIND_DRAW_NOTHING = 0x00; +/** + \def WIND_DRAW_ASSET_INFO + Draw the Asset Info in Screen Space. This displays the various asset members that are relevant to the current asset. + parameters that are not relevant because they are disabled are not displayed. +*/ +static const uint32_t WIND_DRAW_ASSET_INFO = 0x02; +/** + \def WIND_DRAW_FULL_DETAIL + Draw all of the preview rendering items. +*/ +static const uint32_t WIND_DRAW_FULL_DETAIL = (WIND_DRAW_ASSET_INFO); +} + +/** +\brief This class provides the asset preview for APEX WindFS Assets. The class provides multiple levels of prevew +detail that can be selected individually. +*/ +class WindFSPreview : public AssetPreview +{ +public: + /** + Set the detail level of the preview rendering by selecting which features to enable.<BR> + Any, all, or none of the following masks may be added together to select what should be drawn.<BR> + The defines for the individual items are:<br> + WIND_DRAW_NOTHING - draw nothing<BR> + WIND_DRAW_ASSET_INFO - draw the asset info in the screen space<BR> + WIND_DRAW_FULL_DETAIL - draw all components of the asset preview<BR> + All items may be drawn using the macro DRAW_FULL_DETAIL. + */ + virtual void setDetailLevel(uint32_t detail) = 0; +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // WIND_FSPREVIEW_H diff --git a/APEX_1.4/include/basicios/BasicIosActor.h b/APEX_1.4/include/basicios/BasicIosActor.h new file mode 100644 index 00000000..f352f4b9 --- /dev/null +++ b/APEX_1.4/include/basicios/BasicIosActor.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef BASIC_IOS_ACTOR_H +#define BASIC_IOS_ACTOR_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief BasicIOS Actor. A simple actor that simulates a particle system. + */ +class BasicIosActor : public Actor +{ +public: + + /// Get the particle radius + virtual float getParticleRadius() const = 0; + + /// Get the particle rest density + virtual float getRestDensity() const = 0; + + /// Get the current number of particles + virtual uint32_t getParticleCount() const = 0; + +protected: + + virtual ~BasicIosActor() {} +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // BASIC_IOS_ACTOR_H diff --git a/APEX_1.4/include/basicios/BasicIosAsset.h b/APEX_1.4/include/basicios/BasicIosAsset.h new file mode 100644 index 00000000..c2278967 --- /dev/null +++ b/APEX_1.4/include/basicios/BasicIosAsset.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef BASIC_IOS_ASSET_H +#define BASIC_IOS_ASSET_H + +#include "Apex.h" +#include <limits.h> + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#define BASIC_IOS_AUTHORING_TYPE_NAME "BasicIosAsset" + +/** + \brief APEX Particle System Asset + */ +class BasicIosAsset : public IosAsset +{ +public: + + ///Get the radius of a particle + virtual float getParticleRadius() const = 0; + + ///Get the rest density of a particle + virtual float getRestDensity() const = 0; + + ///Get the maximum number of particles that are allowed to be newly created on each frame + virtual float getMaxInjectedParticleCount() const = 0; + + ///Get the maximum number of particles that this IOS can simulate + virtual uint32_t getMaxParticleCount() const = 0; + + ///Get the mass of a particle + virtual float getParticleMass() const = 0; + +protected: + virtual ~BasicIosAsset() {} +}; + +/** + \brief APEX Particle System Asset Authoring class + */ +class BasicIosAssetAuthoring : public AssetAuthoring +{ +public: + + ///Set the radius of a particle + virtual void setParticleRadius(float) = 0; + + ///Set the rest density of a particle + virtual void setRestDensity(float) = 0; + + ///Set the maximum number of particles that are allowed to be newly created on each frame + virtual void setMaxInjectedParticleCount(float count) = 0; + + ///Set the maximum number of particles that this IOS can simulate + virtual void setMaxParticleCount(uint32_t count) = 0; + + ///Set the mass of a particle + virtual void setParticleMass(float) = 0; + + ///Set the (NRP) name for the collision group. + virtual void setCollisionGroupName(const char* collisionGroupName) = 0; + + ///Set the (NRP) name for the collision group mask. + virtual void setCollisionGroupMaskName(const char* collisionGroupMaskName) = 0; + +protected: + virtual ~BasicIosAssetAuthoring() {} +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // BASIC_IOS_ASSET_H diff --git a/APEX_1.4/include/basicios/ModuleBasicIos.h b/APEX_1.4/include/basicios/ModuleBasicIos.h new file mode 100644 index 00000000..5f9a0176 --- /dev/null +++ b/APEX_1.4/include/basicios/ModuleBasicIos.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_BASIC_IOS_H +#define MODULE_BASIC_IOS_H + +#include "Apex.h" +#include "TestBase.h" +#include <limits.h> + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class Scene; +class BasicIosAsset; +class BasicIosActor; +class BasicIosAssetAuthoring; + +/** +\brief BasicIOS Module +*/ +class ModuleBasicIos : public Module +{ +protected: + virtual ~ModuleBasicIos() {} + +public: + /// Get BasicIOS authoring type name + virtual const char* getBasicIosTypeName() = 0; + + /// Get TestBase implementation of BasicIos scene + virtual const TestBase* getTestBase(Scene* apexScene) const = 0; + +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // MODULE_BASIC_IOS_H diff --git a/APEX_1.4/include/clothing/ClothingActor.h b/APEX_1.4/include/clothing/ClothingActor.h new file mode 100644 index 00000000..15a42f10 --- /dev/null +++ b/APEX_1.4/include/clothing/ClothingActor.h @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CLOTHING_ACTOR_H +#define CLOTHING_ACTOR_H + +#include "Actor.h" +#include "Renderable.h" +#include "ClothingAsset.h" + +namespace NvParameterized +{ +class Interface; +} + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class ClothingVelocityCallback; +class ClothingPlane; +class ClothingConvex; +class ClothingSphere; +class ClothingCapsule; +class ClothingTriangleMesh; +class ClothingRenderProxy; + + +/** +\brief selects the mode the clothing actor will be in the simulation frame +*/ +struct ClothingTeleportMode +{ + /** \brief the enum type */ + enum Enum + { + /** + \brief Simulation continues smoothly. This is the most commonly used mode + */ + Continuous, + + /** + \brief Transforms the current simulation state from the old global pose to the new global pose. + + This will transform positions and velocities and thus keep the simulation state, just translate it to a new pose. + */ + Teleport, + + /** + \brief Forces the cloth to the animated position in the next frame. + + This can be used to reset it from a bad state or by a teleport where the old state is not important anymore. + */ + TeleportAndReset, + }; +}; + + + +/** +\brief Instance of ClothingAsset. Can be positioned, animated, updated and rendered. +*/ +class ClothingActor : public Actor, public Renderable +{ +protected: + virtual ~ClothingActor() {} +public: + + /** + \brief Returns a reference to the actor descriptor as it is held by the ClothingActor. + + This descriptor can be modified at any time, changes will only be read during the first part of the simulation. + */ + virtual ::NvParameterized::Interface* getActorDesc() = 0; + + /** + \brief Updates all internal bone matrices. This should be called with updated information before apex scenes start simulating. + + \param[in] globalPose The new location of the actor + \param[in] newBoneMatrices Pointer to the array of transformations that contain the composite bone transformations for the + current frame + \param[in] boneMatricesByteStride stride of the bone matrices, must be bigger than sizeof(PxMat44) + \param[in] numBoneMatrices number of bone matrices available. This should correspond with the number of bones present in the asset + \param[in] teleportMode Setting this to anything but TM_Continuous will force apply a teleport and optionally a reset. + + \note This must be called before Scene::simulate is called + */ + virtual void updateState(const PxMat44& globalPose, const PxMat44* newBoneMatrices, uint32_t boneMatricesByteStride, uint32_t numBoneMatrices, ClothingTeleportMode::Enum teleportMode) = 0; + + /** + \brief Change the max distance of all active vertices with a scalar parameter + + \param[in] scale Must be in [0,1] range + \param[in] multipliable Setting to define how the scale is applied. True will multiply the scale on top of the max distance, False will subtract the maximum max distance. + */ + virtual void updateMaxDistanceScale(float scale, bool multipliable) = 0; + + /** + \brief returns the globalPose that was set with ClothingActor::updateState() + */ + virtual const PxMat44& getGlobalPose() const = 0; + + /** + \brief Sets the wind strength and direction, can be called any time + + \deprecated Use ClothingActor::getActorDesc() and modify the wind part of it + + \param[in] windAdaption The rate of adaption. The higher this value, the faster the cloth reaches the wind velocity. Set to 0 to turn off wind + \param[in] windVelocity The target velocity each vertex tries to achieve. + + \note It is safe to call this even during simulation, but it will only have an effect after the next call to Scene::simulate() + */ + virtual void setWind(float windAdaption, const PxVec3& windVelocity) = 0; + + /** + \brief \b DEPRECATED Time in seconds how long it takes to go from 0 maxDistance to full maxDistance + + \deprecated Use ClothingActor::getActorDesc() and modify the maxDistanceBlendTime part of it + <b>Default:</b> 1.0 + \note This also influences how quickly different physical LoDs can be switched + \note It is safe to call this even during simulation. + */ + virtual void setMaxDistanceBlendTime(float blendTime) = 0; + + /** + \brief \b DEPRECATED Time in seconds how long it takes to go from 0 maxDistance to full maxDistance + + \deprecated Use ClothingActor::getActorDesc() and read the maxDistanceBlendTime part of it + */ + virtual float getMaxDistanceBlendTime() const = 0; + + /** + \brief Tells the actor if it will be rendered or not. + If an actor is simulated, but not rendered, some computations (skinning, normal and tangent calculation) + doesn't need to be done. + + disabling is set immediately, disabling is buffered for the next frame. + */ + virtual void setVisible(bool enable) = 0; + + /** + \brief Returns the current visibility setting. + The most recently set value is returned (i.e. the buffered value, not the actual value). + */ + virtual bool isVisible() const = 0; + + /** + \brief Stops simulating the actor. + */ + virtual void setFrozen(bool enable) = 0; + + /** + \brief Returns if the simulation is currently stopped for this actor. + */ + virtual bool isFrozen() const = 0; + + /** + \brief Returns whether the actor is simulated using the 2.8.x or the 3.x cloth solver. + */ + virtual ClothSolverMode::Enum getClothSolverMode() const = 0; + + /** + \brief sets the graphical Lod + This chooses the graphical mesh of all the meshes stored in the asset to be rendered. It has to be set + before the simulate call to take effect for the next time the actor is rendered. Otherwise, the + given value will be buffered and used as soon as possible. + + \param [in] lod lod used to render the mesh + + \note It is safe to call this even during simulation + */ + virtual void setGraphicalLOD(uint32_t lod) = 0; + + /** + \brief returns the graphical Lod + This returns the buffered most recently set graphical lod, even if it's not active yet. + */ + virtual uint32_t getGraphicalLod() = 0; + + /** + \brief Raycasts against the ClothingActor + + \param [in] worldOrigin The world ray's origin + \param [in] worldDirection The world ray's direction, needs not to be normalized + \param [out] time Impact time + \param [out] normal Impact normal in world space + \param [out] vertexIndex Vertex index that was hit + + \return true if this actor is hit + */ + virtual bool rayCast(const PxVec3& worldOrigin, const PxVec3& worldDirection, float& time, PxVec3& normal, uint32_t& vertexIndex) = 0; + + /** + \brief Attach a vertex to a global position + */ + virtual void attachVertexToGlobalPosition(uint32_t vertexIndex, const PxVec3& globalPosition) = 0; + + /** + \brief Free a previously attached vertex + */ + virtual void freeVertex(uint32_t vertexIndex) = 0; + + /** + \brief Returns the actively selected material. + */ + virtual uint32_t getClothingMaterial() const = 0; + + /** + \brief Sets which clothing material is used from the assets library + */ + virtual void setClothingMaterial(uint32_t index) = 0; + + /** + \brief Sets the override material for the submesh with the given index. + */ + virtual void setOverrideMaterial(uint32_t submeshIndex, const char* overrideMaterialName) = 0; + + /** + \brief sets the velocity callback for an individual actor, turned off when NULL + */ + virtual void setVelocityCallback(ClothingVelocityCallback* callback) = 0; + + /** + \brief Returns the current position of all physics vertices. + + This method provides the positions of the currently simulated part of the physics mesh + and skins the non-simulated part with the current bone positions. + + \note This should usually not be needed other than for rendering the physics mesh yourself + \note Must be called in between Scene::fetchResults and Scene::simulate. + */ + virtual void getPhysicalMeshPositions(void* buffer, uint32_t byteStride) = 0; + + /** + \brief Returns the current normals of all physics vertices. + + This method provides the normals of the currently simulated part of the physics mesh + and skins the non-simulated part with the current bone positions. + + \note This should usually not be needed other than for rendering the physics mesh yourself + \note Must be called in between Scene::fetchResults and Scene::simulate. + */ + virtual void getPhysicalMeshNormals(void* buffer, uint32_t byteStride) = 0; + + /** + \brief Returns how much an Actor will cost at maximum + */ + virtual float getMaximumSimulationBudget() const = 0; + + /** + \brief Returns the number of currently simulation vertices. + + \note This is not to be used for getPhysicalMeshPositions. + getNumSimulatedVertices returns the number + of actually simulated verts, while getPhysicalMeshPositions returns the complete + physical mesh, regardless of the current physical lod + */ + virtual uint32_t getNumSimulationVertices() const = 0; + + + /** + \brief Returns a pointer to the internal positions array of the simulated physics mesh + Blocks until the simulation and post simulation processing is done + (with asyncFetchResult set to true) + + \return Pointer the simulation mesh positions + */ + virtual const PxVec3* getSimulationPositions() = 0; + + /** + \brief Returns a pointer to the internal normals array of the simulated physics mesh + Blocks until the simulation and post simulation processing is done + (with asyncFetchResult set to true) + + \return Pointer the simulation mesh normals + */ + virtual const PxVec3* getSimulationNormals() = 0; + + /** + \brief Writes the current velocities of the simulated vertices into the provided array. + A buffer of getNumSimulationVertices() PxVec3's needs to be provided. The function cannot be called + during simulation. + Blocks until the simulation and post simulation processing is done + (with asyncFetchResult set to true) + + \return true if a simulation is available and the velocities have been written + */ + virtual bool getSimulationVelocities(PxVec3* velocities) = 0; + + /** + \brief Returns the number of the graphical vertices that need to be skinned to the simulation mesh [0, numGraphicalVerticesActive) + + The rest must be regularly skinned to bones [numGraphicalVerticesActive, numVertices) + + \note Only valid after simulate. + */ + virtual uint32_t getNumGraphicalVerticesActive(uint32_t submeshIndex) const = 0; + + /** + \brief Returns the transform that needs to be applied to the rendered mesh. + + \note Only valid after simulate. + */ + virtual PxMat44 getRenderGlobalPose() const = 0; + + /** + \brief Returns the current skinning matrices. + The skinning matrices already contain the global pose of the actor. + + \note Only valid after simulate. + */ + virtual const PxMat44* getCurrentBoneSkinningMatrices() const = 0; + + + /** + \brief return whether GPU solver can use half precision for storing positions. + + \note If allowed half precision will be activated only when actors cannot be fitted to shared memory with float precision. + */ + virtual bool isHalfPrecisionAllowed() const = 0; + + /** + \brief allow GPU solver to use half precision for storing positions. + + \note This option will be activated only when actors cannot be fitted to shared memory with float precision. + Be aware half precision might be insufficient for some cloth simulation. + Especially simulation with extensive self collisions sensitive to precision. + + \param [in] isAllowed true - allow GPU solver to use half precision, false - don't allow + */ + virtual void setHalfPrecision(bool isAllowed) = 0; + + + /** + \brief Create a collision plane for the actor. + */ + virtual ClothingPlane* createCollisionPlane(const PxPlane& plane) = 0; + + /** + \brief Create a collision convex for the actor, defined by planes. + */ + virtual ClothingConvex* createCollisionConvex(ClothingPlane** planes, uint32_t numPlanes) = 0; + + /** + \brief Create a collision sphere for the actor. + */ + virtual ClothingSphere* createCollisionSphere(const PxVec3& position, float radius) = 0; + + /** + \brief Create a tapered collision capsule for the actor, defined by two spheres. + */ + virtual ClothingCapsule* createCollisionCapsule(ClothingSphere& sphere1, ClothingSphere& sphere2) = 0; + + /** + \brief Create a collision triangle mesh for the actor. + */ + virtual ClothingTriangleMesh* createCollisionTriangleMesh() = 0; + + /** + \brief Returns the Render Proxy for this clothing actor. + + Call this function after fetchResults to get the ClothingRenderProxy object that can be used + to render the simulation reset. The render proxy can be acquired at any time, it contains the result + from the last fetchResults call. It is recommended to acquire the render proxy after fetchResults and + to release it before the next simulate call to prevent the memory overhead of buffering the render data. + The data in the render proxy remains consistent until it is released (release returns the object into a + pool from which it can be reused). + The ClothingRenderProxy object is valid even after the release of the clothing actor. However it becomes + invalid when the corresponding asset is released. + Blocks until the simulation and post simulation processing is done + (with asyncFetchResult set to true) + + \return ClothingRenderProxy object with static render data. Can be acquired only once per frame, otherwise NULL is returned. + */ + virtual ClothingRenderProxy* acquireRenderProxy() = 0; + +#if APEX_UE4 + /** simulates just this actor, not supported for GPU simulation. */ + virtual void simulate(PxF32 dt) = 0; +#endif +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // CLOTHING_ACTOR_H diff --git a/APEX_1.4/include/clothing/ClothingAsset.h b/APEX_1.4/include/clothing/ClothingAsset.h new file mode 100644 index 00000000..c4ee9610 --- /dev/null +++ b/APEX_1.4/include/clothing/ClothingAsset.h @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CLOTHING_ASSET_H +#define CLOTHING_ASSET_H + +#include "Asset.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class ClothingActor; +class ClothingPreview; + +#define CLOTHING_AUTHORING_TYPE_NAME "ClothingAsset" + + +/** +\brief Describes the solver that is used to simulate the clothing actor. +*/ +struct ClothSolverMode +{ + /** \brief the enum type */ + enum Enum + { + /** + \brief The actor is simulated using the 3.x cloth solver. + */ + v3, + }; +}; + + +/** +\brief Maps from a triangle of the simulated mesh to a vertex of the rendered mesh. +The barycentric coordinates describe the position of a point in space relative to a simulated +triangle. The actual z-coordinate is computed by bary.z = 1 - bary.x - bary.y. +The z part of the vector contains the height of the skinned vertex along the normal of the +simulated triangle. + +So, the following computes the new skinned position: + +uint32_t i0 = map[mapId].vertexIndex0; +uint32_t i1 = map[mapId].vertexIndex1; +uint32_t i2 = map[mapId].vertexIndex2; + +PxVec3 bary = map[mapId].positionBary; +float heightOffset = bary.z * actorScale; +bary.z = (1 - bary.x - bary.y); + +PxVec3 posOnTriangle = physPositions[i0] * bary.x + + physPositions[i1] * bary.y + + physPositions[i2] * bary.z; + +offsetFromTriangle = (physNormals[i0] * bary.x + + physNormals[i1] * bary.y + + physNormals[i2] * bary.z) + * heightOffset; + +skinnedPos = posOnTriangle + offsetFromTriangle; +*/ +struct ClothingMeshSkinningMap +{ + /** + \brief Barycentric coordinates of the graphical vertex relative to the simulated triangle. + \note PX_MAX_F32 values represent invalid coordinates. + */ + PxVec3 positionBary; + + /** + \brief First vertex of the simulated triangle. + */ + uint32_t vertexIndex0; + + /** + \brief Barycentric coordinates of a point that represents the normal. + The actual normal can be extracted by subtracting the skinned position from this point. + \note PX_MAX_F32 values represent invalid coordinates. + */ + PxVec3 normalBary; + + /** + \brief Second vertex of the simulated triangle. + */ + uint32_t vertexIndex1; + + /** + \brief Barycentric coordinates of a point that represents the tangent. + The actual tangent can be extracted by subtracting the skinned position from this point. + \note PX_MAX_F32 values represent invalid coordinates. + */ + PxVec3 tangentBary; + + /** + \brief Third vertex of the simulated triangle. + */ + uint32_t vertexIndex2; +}; + +/** +\brief A clothing asset. It contains all the static and shared data for a given piece of clothing. +*/ +class ClothingAsset : public Asset +{ +protected: + // do not manually delete this object + virtual ~ClothingAsset() {} +public: + /** + \brief Returns the number of ClothingActors this asset has created. + */ + virtual uint32_t getNumActors() const = 0; + + /** + \brief Returns the index'th ClothingActor + */ + virtual ClothingActor* getActor(uint32_t index) = 0; + + /** + \brief Returns the bounding box for the asset. + */ + virtual PxBounds3 getBoundingBox() const = 0; + + /** + \brief returns the number of LOD levels present in this asset + */ + virtual uint32_t getNumGraphicalLodLevels() const = 0; + + /** + \brief returns the actual LOD value of any particular level, normally this is just the identity map + */ + virtual uint32_t getGraphicalLodValue(uint32_t lodLevel) const = 0; + + /** + \brief returns the biggest max distance of any vertex in any physical mesh + */ + virtual float getBiggestMaxDistance() const = 0; + + /** + \brief returns for which solver the asset has been cooked for. + */ + virtual ClothSolverMode::Enum getClothSolverMode() const = 0; + + /** + \brief remaps bone with given name to a new index for updateState calls + + This is needed when the order of bones differs from authoring tool to runtime + + \note must be called after asset is deserialized. Changing this any later, especially after the first ClothingActor::updateState call + will lead to ill-defined behavior. + */ + virtual bool remapBoneIndex(const char* name, uint32_t newIndex) = 0; + + /** + \brief Returns the number of bones + */ + virtual uint32_t getNumBones() const = 0; + + /** + \brief Returns the number of bones that are actually used. They are the first ones internally. + */ + virtual uint32_t getNumUsedBones() const = 0; + + /** + \brief Returns the name of the bone at the given internal index. + */ + virtual const char* getBoneName(uint32_t internalIndex) const = 0; + + /** + \brief Returns the bind pose transform for this bone. + */ + virtual bool getBoneBasePose(uint32_t internalIndex, PxMat44& result) const = 0; + + /** + \brief returns the mapping from internal to external indices for a given asset. + + Use this map to transform all the boneIndices returned from the ClothingPhysicalMesh into the order you specified initially + */ + virtual void getBoneMapping(uint32_t* internal2externalMap) const = 0; + + /** + \brief Gets the RenderMeshAsset associated with this asset. + + \param [in] lodLevel The LoD level of the render mesh asset + \return NULL if lodLevel is not valid + \see ClothingAsset::getNumGraphicalLodLevels() + */ + virtual const RenderMeshAsset* getRenderMeshAsset(uint32_t lodLevel) const = 0; + + /** + \brief Prepares the asset for use with morph target. + + When setting morph target displacements, the asset needs to create a mapping of external to internal vertex order. + These positions will be matched with the internal mesh positions with a smallest distance criterion. + + \param [in] originalPositions Array of positions before the morphing is applied. + \param [in] numPositions Length of the Array + \param [in] epsilon Difference two vertices can have before being reported + \return Number of vertices for which the distance to the next originalPosition was larger than epsilon + */ + virtual uint32_t prepareMorphTargetMapping(const PxVec3* originalPositions, uint32_t numPositions, float epsilon) = 0; + + /** + \brief Returns the size of the mesh skinning map. + \note This call has the side effect of merging the immediate map into the mesh skinning map. This might affect skinning performance done by APEX. + + \return Number of entries in the map + */ + virtual uint32_t getMeshSkinningMapSize(uint32_t lod) = 0; + + /** + \brief Provides the mesh to mesh skinning map. + + This map stores for each graphics mesh vertex the corresponding triangle indices of the physics mesh and barycentric coordinates to + skin the vertex position, normal and tangent. + \note This call has the side effect of merging the immediate map into the mesh skinning map. This might affect skinning performance done by APEX. + + \param [in] lod lod for which the map is requested + \param [out] map Skinning map + */ + virtual void getMeshSkinningMap(uint32_t lod, ClothingMeshSkinningMap* map) = 0; + + /** + \brief Releases all data needed to compute render data in apex clothing. + */ + virtual bool releaseGraphicalData() = 0; +}; + +PX_POP_PACK + +} // namespace nvidia +} // namespace nvidia + +#endif // CLOTHING_ASSET_H diff --git a/APEX_1.4/include/clothing/ClothingAssetAuthoring.h b/APEX_1.4/include/clothing/ClothingAssetAuthoring.h new file mode 100644 index 00000000..6b0d5b0c --- /dev/null +++ b/APEX_1.4/include/clothing/ClothingAssetAuthoring.h @@ -0,0 +1,342 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CLOTHING_ASSET_AUTHORING_H +#define CLOTHING_ASSET_AUTHORING_H + +#include "Asset.h" +#include "IProgressListener.h" +#include "ClothingPhysicalMesh.h" + + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + + +class ClothingPhysicalMesh; + + +/** +\brief The clothing authoring asset. This is used to generate streams that can then be deserialized into a regular asset. +*/ +class ClothingAssetAuthoring : public AssetAuthoring +{ +public: + + /** + \brief set the default value for all coefficients if none is available + */ + virtual void setDefaultConstrainCoefficients(const ClothingConstrainCoefficients& coeff) = 0; + + /** + \brief set the value which is considered invalid when painting + */ + virtual void setInvalidConstrainCoefficients(const ClothingConstrainCoefficients& coeff) = 0; + + /** + \brief Sets the graphical and physical mesh for the given graphical lod level. + \param [in] lod Identifier for that lod level. + \param [in] graphicalMesh The graphical mesh to be rendered in that lod level. + \param [in] physicalMesh The physical mesh to be simulated on that lod level. The reference to the same physical mesh can be + given for different graphical lods. It is copied internally. + <br><b>Note:</b> If the same physical mesh is used several time, the paint values are copied from the + graphical mesh the first time the physical mesh is passed in here. + \param [in] normalResemblance This angle (in degrees) specifies how similar the normal from the physical and graphical mesh need to + be in order for them to be accepted as immediate mode skinning pairs. Use 90 or bigger for any + resemblance. Must be in range (0, 90], but it's highly recommended to use more than 5 degrees. + \param [in] ignoreUnusedVertices All Vertices that have the 'usedForPhysics' property set to false will be ignored when transferring + the painted values from the graphical to the physical mesh + \param [in] progress Progress bar callback class. + */ + virtual void setMeshes(uint32_t lod, RenderMeshAssetAuthoring* graphicalMesh, ClothingPhysicalMesh* physicalMesh, + float normalResemblance = 25, bool ignoreUnusedVertices = true, IProgressListener* progress = NULL) = 0; + + + /** + \brief Assigns a platform tag to a graphical lod. + */ + virtual bool addPlatformToGraphicalLod(uint32_t lod, PlatformTag platform) = 0; + + /** + \brief Removes a platform tag from a graphical lod. + */ + virtual bool removePlatform(uint32_t lod, PlatformTag platform) = 0; + + /** + \brief Get number of platform tags for a given lod. + */ + virtual uint32_t getNumPlatforms(uint32_t lod) const = 0; + + /** + \brief Get i-th platform tag of given lod; + */ + virtual PlatformTag getPlatform(uint32_t lod, uint32_t i) const = 0; + + /** + \brief Returns the number of LoDs that have been set in the ClothingAssetAuthoring::setMeshes call + */ + virtual uint32_t getNumLods() const = 0; + + /** + \brief Returns the n-th LoD value from the ClothingAssetAuthoring::setMeshes call. + + \note These values do not have to be a continuous list + */ + virtual int32_t getLodValue(uint32_t lod) const = 0; + + /** + \brief Clears all lods and meshes. + */ + virtual void clearMeshes() = 0; + + /** + \brief Returns a reference to the internal copy of the physical mesh for the given graphical lod. Returned object MUST be destroyed by the user immediately after use. + */ + virtual ClothingPhysicalMesh* getClothingPhysicalMesh(uint32_t graphicalLod) const = 0; + + /** + \brief assigns name and bindpose to a bone. This needs to be called for every bone at least once + + \param [in] boneIndex The bone index the information is provided for. + \param [in] boneName The bone name. An internal copy of this string will be made. + \param [in] bindPose The bind or rest pose of this bone. + \param [in] parentIndex The bone index of the parent bone, -1 for root bones. + */ + virtual void setBoneInfo(uint32_t boneIndex, const char* boneName, const PxMat44& bindPose, int32_t parentIndex) = 0; + + /** + \brief Specifies the root bone. + + \param [in] boneName The bone name. + */ + virtual void setRootBone(const char* boneName) = 0; + + /** + \brief add a convex collision representation to a bone, vertices must be in bone-bind-pose space! + + \param [in] boneName name of the bone this collision info is for. + \param [in] positions array of vertices with the positions. + \param [in] numPositions number of elements in positions array. if set to 0, bone collision will be capsule. + */ + virtual uint32_t addBoneConvex(const char* boneName, const PxVec3* positions, uint32_t numPositions) = 0; + + /** + \brief add a convex collision representation to a bone, vertices must be in bone-bind-pose space! + + \param [in] boneIndex index of the bone this collision info is for. + \param [in] positions array of vertices with the positions. + \param [in] numPositions number of elements in positions array. if set to 0, bone collision will be capsule. + */ + virtual uint32_t addBoneConvex(uint32_t boneIndex, const PxVec3* positions, uint32_t numPositions) = 0; + + /** + \brief add a capsule to the bone's collision. all relative to bone-bind-pose space! + + \param [in] boneName name of the bone this collision info is for. + \param [in] capsuleRadius The radius of the capsule. if set to 0, bone collision will default back to convex + \param [in] capsuleHeight The height of the capsule + \param [in] localPose The frame of the capsule relative to the frame of the bone (not world space) + */ + virtual void addBoneCapsule(const char* boneName, float capsuleRadius, float capsuleHeight, const PxMat44& localPose) = 0; + + /** + \brief add a capsule to the bone's collision. all relative to bone-bind-pose space! + + \param [in] boneIndex index of the bone this collision info is for. + \param [in] capsuleRadius if set to 0, bone collision will default back to convex + \param [in] capsuleHeight The height of the capsule + \param [in] localPose The frame of the capsule relative to the frame of the bone (not world space) + */ + virtual void addBoneCapsule(uint32_t boneIndex, float capsuleRadius, float capsuleHeight, const PxMat44& localPose) = 0; + + /** + \brief clear all collision information for a given bone name + */ + virtual void clearBoneActors(const char* boneName) = 0; + + /** + \brief clear all collision information for a given bone index + */ + virtual void clearBoneActors(uint32_t boneIndex) = 0; + + /** + \brief clear all collision information for any bone + */ + virtual void clearAllBoneActors() = 0; + + /** + \brief Set up the collision volumes for PhysX3. + The boneNames, radii and localPositions array need to be of size numSpheres, each triplet describes a sphere that is attached to a bone. + The pairs array describes connections between pairs of spheres. It defines capsules with 2 radii. + + \param [in] boneNames names of the bones to which a spheres are added + \param [in] radii radii of the spheres + \param [in] localPositions sphere positions relative to the bone + \param [in] numSpheres number of spheres that are being defined + \param [in] pairs pairs of indices that reference 2 spheres to define a capsule with 2 radii + \param [in] numIndices size of the pairs array + */ + virtual void setCollision(const char** boneNames, float* radii, PxVec3* localPositions, uint32_t numSpheres, uint16_t* pairs, uint32_t numIndices) = 0; + + /** + \brief Set up the collision volumes for PhysX3. + */ + virtual void setCollision(uint32_t* boneIndices, float* radii, PxVec3* localPositions, uint32_t numSpheres, uint16_t* pairs, uint32_t numIndices) = 0; + + /** + \brief Clear the collision volumes for PhysX3. + */ + virtual void clearCollision() = 0; + + /** + \brief Number of hierarchical levels. 0 to turn off + + If either the hierarchical solver iterations or the hierarchical levels are set to 0, this feature is turned off + */ + virtual void setSimulationHierarchicalLevels(uint32_t levels) = 0; + + + /** + \brief The radius of the cloth/softbody particles. + */ + virtual void setSimulationThickness(float thickness) = 0; + + /** + \brief The amount of virtual particles created. 0 means none, 1 means 2 or 3 per triangle. + */ + virtual void setSimulationVirtualParticleDensity(float density) = 0; + + /** + \brief The sleep velocity. If all vertices of a cloth/softbody are below this velocity for some time, it falls asleep + */ + virtual void setSimulationSleepLinearVelocity(float sleep) = 0; + + /** + \brief The direction of gravity. Can be used for cooking. + */ + virtual void setSimulationGravityDirection(const PxVec3& gravity) = 0; + + /** + \brief Turn off Continuous collision detection for clothing. + + Fast moving objects can cause massive forces to the cloth, especially when some kinematic actors move large distances within one frame. + Without CCD those collisions are not detected and thus don't influence the cloth. + + \note Whenever the isContinuous parameter in ClothingActor::updateState is set to false, cloth CCD will be temporarily disabled as well + */ + virtual void setSimulationDisableCCD(bool disable) = 0; + + /** + \brief Turns on twoway interaction with rigid body. Only of limited use for clothing + */ + virtual void setSimulationTwowayInteraction(bool enable) = 0; + + /** + \brief EXPERIMENTAL: Turns on local untangling + + \see CLF_UNTANGLING + */ + virtual void setSimulationUntangling(bool enable) = 0; + + /** + \brief The scale of the cloth rest length + */ + virtual void setSimulationRestLengthScale(float scale) = 0; + + /** + \brief Provide a scaling to the serialize functionality. + + This is useful when the game runs in a different scale than the tool this asset was created in + + \deprecated Only works with deprecated serialization, use applyTransformation instead! + */ + virtual void setExportScale(float scale) = 0; + + /** + \brief Apply an arbitrary transformation to either the physical, the graphical mesh or both. + + This is a permanent transformation and it changes the object state. Should only be called immediately before serialization + and without further modifying the object later on. + + \param transformation This matrix is allowed to contain a translation and a rotation. + \param scale Apply a uniform scaling as well + \param applyToGraphics Apply the transformation and scale to the graphical part of the asset + \param applyToPhysics Apply the transformation and scale to the physical part of the asset + + \note if the 3x3 part of the transformation parameter contains mirroring of axis (= negative determinant) some additional processing is done. + This includes flipping of simulation triangles and adaption of the mesh-mesh skinning. + */ + virtual void applyTransformation(const PxMat44& transformation, float scale, bool applyToGraphics, bool applyToPhysics) = 0; + + /** + \brief Move every bone bind pose to a new position. + + \param newBindPoses array of matrices for the new bind poses. This must be in object space (not relative to the parent bone!) + \param newBindPosesCount number of matrices in the specified array + \param isInternalOrder using internal numbering or external numbering? + \param maintainCollisionWorldSpace The collision volumes do not move to the new bone bind pose + */ + virtual void updateBindPoses(const PxMat44* newBindPoses, uint32_t newBindPosesCount, bool isInternalOrder, bool maintainCollisionWorldSpace) = 0; + + /** + \brief If enabled, the normals of the physical mesh are derived + from the directions of the physical vertex to the bind poses of the assigned bones + */ + virtual void setDeriveNormalsFromBones(bool enable) = 0; + + /** + \brief Returns the material interface + */ + virtual NvParameterized::Interface* getMaterialLibrary() = 0; + + /** + \brief Adds a new material library to the asset + + \param [in] materialLibrary User-generated material library object. + \param [in] materialIndex Default value for the Actor to know which material to use in the library + \param [in] transferOwnership Hands ownership to the authoring asset. + */ + virtual bool setMaterialLibrary(NvParameterized::Interface* materialLibrary, uint32_t materialIndex, bool transferOwnership) = 0; + + /** + \brief Gets the parameterized render mesh associated with this asset. + + \param [in] lodLevel The LoD level of the render mesh asset + + \return NULL if lodLevel is not valid + + \see ClothingAssetAuthoring::getNumLods() + + \note Under no circumstances you should modify the positions of the render mesh asset's vertices. This will certainly break clothing + */ + virtual ::NvParameterized::Interface* getRenderMeshAssetAuthoring(uint32_t lodLevel) const = 0; + + /** + \brief Retrieves the bind pose transform of this bone. + */ + virtual bool getBoneBindPose(uint32_t boneIndex, PxMat44& bindPose) const = 0; + + /** + \brief Directly sets the bind pose transform of this bone + */ + virtual bool setBoneBindPose(uint32_t boneIndex, const PxMat44& bindPose) = 0; +}; + +PX_POP_PACK + +} // namespace nvidia +} // namespace nvidia + +#endif // CLOTHING_ASSET_AUTHORING_H diff --git a/APEX_1.4/include/clothing/ClothingCollision.h b/APEX_1.4/include/clothing/ClothingCollision.h new file mode 100644 index 00000000..8dff9550 --- /dev/null +++ b/APEX_1.4/include/clothing/ClothingCollision.h @@ -0,0 +1,301 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CLOTHING_COLLISION_H +#define CLOTHING_COLLISION_H + +/*! +\file +\brief classes ClothingCollision, ClothingPlane, ClothingConvex, ClothingSphere, ClothingCapsule, ClothingTriangleMesh +*/ + +#include "ApexInterface.h" + +namespace nvidia +{ + +namespace apex +{ +PX_PUSH_PACK_DEFAULT + + +/** +\brief Type of the ClothingCollision +*/ +struct ClothingCollisionType +{ + /** + \brief Enum. + */ + enum Enum + { + Plane, + Convex, + Sphere, + Capsule, + TriangleMesh + }; +}; + + + +class ClothingPlane; +class ClothingConvex; +class ClothingSphere; +class ClothingCapsule; +class ClothingTriangleMesh; + +/** +\brief Base class of all clothing collision types. +*/ +class ClothingCollision : public ApexInterface +{ +public: + /** + \brief Returns the Type of this collision object. + */ + virtual ClothingCollisionType::Enum getType() const = 0; + + /** + \brief Returns the pointer to this object if it is a plane, NULL otherwise. + */ + virtual ClothingPlane* isPlane() = 0; + + /** + \brief Returns the pointer to this object if it is a convex, NULL otherwise. + */ + virtual ClothingConvex* isConvex() = 0; + + /** + \brief Returns the pointer to this object if it is a sphere, NULL otherwise. + */ + virtual ClothingSphere* isSphere() = 0; + + /** + \brief Returns the pointer to this object if it is a capsule, NULL otherwise. + */ + virtual ClothingCapsule* isCapsule() = 0; + + /** + \brief Returns the pointer to this object if it is a triangle mesh, NULL otherwise. + */ + virtual ClothingTriangleMesh* isTriangleMesh() = 0; +}; + + + +/** +\brief Plane collision of a clothing actor. +*/ +class ClothingPlane : public ClothingCollision +{ +public: + /** + \brief Sets the plane equation of the plane. + */ + virtual void setPlane(const PxPlane& plane) = 0; + + /** + \brief Returns the plane equation of the plane. + */ + virtual const PxPlane& getPlane() = 0; + + /** + \brief Returns the number of convexes that reference this plane. + */ + virtual uint32_t getRefCount() const = 0; +}; + + + +/** +\brief Convex collision of a clothing actor. + +A convex is represented by a list of ClothingPlanes. +*/ +class ClothingConvex : public ClothingCollision +{ +public: + /** + \brief Returns the number of planes that define this convex. + */ + virtual uint32_t getNumPlanes() = 0; + + /** + \brief Returns pointer to the planes that define this convex. + */ + virtual ClothingPlane** getPlanes() = 0; + + /** + \brief Releases this convex and all its planes. + + \note Only use this if the planes are used exclusively by this convex. Planes referenced by other convexes will not be released. + */ + virtual void releaseWithPlanes() = 0; +}; + + + +/** +\brief Sphere collision of a clothing actor. +*/ +class ClothingSphere : public ClothingCollision +{ +public: + /** + \brief Sets the position of this sphere. + */ + virtual void setPosition(const PxVec3& position) = 0; + + /** + \brief Returns the position of this sphere. + */ + virtual const PxVec3& getPosition() const = 0; + + /** + \brief Sets the radius of this sphere. + */ + + /** + \brief Sets the Radius of this sphere. + */ + virtual void setRadius(float radius) = 0; + + /** + \brief Returns the Radius of this sphere. + */ + virtual float getRadius() const = 0; + + /** + \brief Returns the number of capsules that reference this plane. + */ + virtual uint32_t getRefCount() const = 0; +}; + + + +/** +\brief Capsule collision of a clothing actor. + +A capsule is represented by two ClothingSpheres. +*/ +class ClothingCapsule : public ClothingCollision +{ +public: + /** + \brief Returns the pointers to the two spheres that represent this capsule. + */ + virtual ClothingSphere** getSpheres() = 0; + + /** + \brief Releases this sphere and its two spheres. + + \note Only use releaseWithSpheres if the 2 spheres are used exclusively by this capsule. Spheres referenced by other convexes will not be released. + */ + virtual void releaseWithSpheres() = 0; +}; + + + +/** +\brief Triangle mesh collision of a clothing actor. +*/ +class ClothingTriangleMesh : public ClothingCollision +{ +public: + /** + \brief Read access to the current triangles of the mesh. + unlockTriangles needs to be called when done reading. + \param[out] ids Pointer to the triangle ids. Not written if NULL is provided. + \param[out] triangles Pointer to the triangles. Contains (3*number of triangles) vertex positions. Not written if NULL is provided. + \return Current number of triangles + */ + virtual uint32_t lockTriangles(const uint32_t** ids, const PxVec3** triangles) = 0; + + /** + \brief Write access to the current triangles of the mesh. Changing Ids is not allowed. + unlockTriangles needs to be called when done editing. + \param[out] ids pointer to the triangle ids. not written if NULL is provided. + \param[out] triangles pointer to the triangles. Contains (3*number of triangles) vertex positions. Not written if NULL is provided. + \return Current number of triangles + */ + virtual uint32_t lockTrianglesWrite(const uint32_t** ids, PxVec3** triangles) = 0; + + /** + \brief Unlock the mesh data after editing or reading. + */ + virtual void unlockTriangles() = 0; + + /** + \brief Adds a triangle to the mesh. Clockwise winding. + If a triangle with a given id already exists, it will update that triangle with the new values. + Ids for triangle removal and adding are accumulated and processed during simulate. That means a triangle + will not be added if the same id is removed in the same frame, independent of the order of the remove and add calls. + \param[in] id User provided triangle id that allows identifing and removing the triangle. + \param[in] v0 First vertex of triangle + \param[in] v1 Second vertex of triangle + \param[in] v2 Third vertex of triangle + */ + virtual void addTriangle(uint32_t id, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2) = 0; + + /** + \brief Adds a list of triangles to the mesh. Clockwise winding. + If a triangle with a given id already exists, it will update that triangle with the new values. + Ids for triangle removal and adding are accumulated and processed during simulate. That means a triangle + will not be added if the same id is removed in the same frame, independent of the order of the remove and add calls. + \param[in] ids User provided triangle indices that allows identifing and removing the triangle. + Needs to contain numTriangles indices. + \param[in] triangleVertices Triangle vertices to add. Needs to contain 3*numTriangles vertex positions + \param[in] numTriangles Number of triangles to add + */ + virtual void addTriangles(const uint32_t* ids, const PxVec3* triangleVertices, uint32_t numTriangles) = 0; + + /** + \brief Removes triangle with given id. + Ids for triangle removal and adding are accumulated and processed during simulate. That means a triangle + will not be added if the same id is removed in the same frame, independent of the order of the remove and add calls. + \param[in] id id of the triangle to be removed + */ + virtual void removeTriangle(uint32_t id) = 0; + + /** + \brief Removes triangles. + Ids for triangle removal and adding are accumulated and processed during simulate. That means a triangle + will not be added if the same id is removed in the same frame, independent of the order of the remove and add calls. + \param[in] ids ids of the triangles to be removed. Needs to contain numTriangle indices. + \param[in] numTriangles Number of triangles to remove + */ + virtual void removeTriangles(const uint32_t* ids, uint32_t numTriangles) = 0; + + /** + \brief Clear all triangles to start with an empty mesh. + */ + virtual void clearTriangles() = 0; + + /** + \brief Sets the global pose of the mesh. + */ + virtual void setPose(PxMat44 pose) = 0; + + /** + \brief Returns the global pose of the mesh. + */ + virtual const PxMat44& getPose() const = 0; +}; + + + +PX_POP_PACK +} // namespace nvidia +} // namespace nvidia + + +#endif // CLOTHING_COLLISION_H
\ No newline at end of file diff --git a/APEX_1.4/include/clothing/ClothingPhysicalMesh.h b/APEX_1.4/include/clothing/ClothingPhysicalMesh.h new file mode 100644 index 00000000..21dafe79 --- /dev/null +++ b/APEX_1.4/include/clothing/ClothingPhysicalMesh.h @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CLOTHING_PHYSICAL_MESH_H +#define CLOTHING_PHYSICAL_MESH_H + +#include "ApexInterface.h" +#include "IProgressListener.h" + +namespace nvidia +{ +namespace apex +{ + + +/** +\brief Constrain coefficients of the physical mesh vertices +*/ +struct ClothingConstrainCoefficients +{ + float maxDistance; ///< \brief Maximum distance a vertex is allowed to move + float collisionSphereRadius; ///< \brief Backstop sphere radius + float collisionSphereDistance; ///< \brief Backstop sphere distance +}; + + +PX_PUSH_PACK_DEFAULT + +/** +\brief Contains the data for handing out statistics about a ClothingPhysicalMesh +*/ +struct ClothingPhysicalMeshStats +{ + /// the number of bytes allocated for the physical mesh + uint32_t totalBytes; + /// the number of vertices + uint32_t numVertices; + /// the number of indices + uint32_t numIndices; +}; + + +/** +\brief Holder for a physical mesh, this can be generated through various ways (see single- and multi-layered clothing) or hand crafted +*/ +class ClothingPhysicalMesh : public ApexInterface +{ +public: + /** + \brief returns the number of vertices + */ + virtual uint32_t getNumVertices() const = 0; + + /** + \brief returns the number of simulated vertices + */ + virtual uint32_t getNumSimulatedVertices() const = 0; + + /** + \brief returns the number of vertices with zero max distance + */ + virtual uint32_t getNumMaxDistance0Vertices() const = 0; + + /** + \brief returns the number of indices + */ + virtual uint32_t getNumIndices() const = 0; + + /** + \brief returns the number of simulated indices + */ + virtual uint32_t getNumSimulatedIndices() const = 0; + + /** + \brief writes the indices to a destination buffer + + \param [out] indexDestination destination buffer where to write the indices + \param [in] byteStride stride of the destination buffer + \param [in] numIndices number of indices the buffer can hold. This can be smaller than getNumIndices() + */ + virtual void getIndices(void* indexDestination, uint32_t byteStride, uint32_t numIndices) const = 0; + + /** + \brief returns whether the mesh is built out of tetrahedra or triangles + */ + virtual bool isTetrahedralMesh() const = 0; + + /** + \brief This will simplify the current mesh. + + \param [in] subdivisions used to derive the maximal length a new edge can get.<br> + Divide the bounding box diagonal by this value to get the maximal edge length for newly created edges<br> + Use 0 to not restrict the maximal edge length + \param [in] maxSteps The maximum number of edges to be considered for simplification.<br> + Use 0 to turn off + \param [in] maxError The maximal quadric error an edge can cause to be considered simplifyable.<br> + Use any value < 0 to turn off + \param [in] progress Callback class that will be fired every now and then to update a progress bar in the gui. + \return The number of edges collapsed + */ + virtual void simplify(uint32_t subdivisions, int32_t maxSteps, float maxError, IProgressListener* progress) = 0; + + /** + \brief Create a physical mesh from scratch + + Overwrites all vertices/indices, and invalidates all misc vertex buffers. vertices must be PxVec3 and indices uint32_t. + If driveChannels is NULL, all vertices are assigned to all drive channels (initialized to 0xffffffff) + */ + virtual void setGeometry(bool tetraMesh, uint32_t numVertices, uint32_t vertexByteStride, const void* vertices, const uint32_t* driveChannels, + uint32_t numIndices, uint32_t indexByteStride, const void* indices) = 0; + + // direct access to specific buffers + /** + \brief writes the indices into a user specified buffer. + + Returns false if the buffer doesn't exist. + The buffer must be bigger than sizeof(uint32_t) * getNumIndices() + */ + virtual bool getIndices(uint32_t* indices, uint32_t byteStride) const = 0; + + /** + \brief Writes the vertex positions into a user specified buffer. + + Returns false if the buffer doesn't exist. + The buffer must be bigger than sizeof(PxVec3) * getNumVertices() + */ + virtual bool getVertices(PxVec3* vertices, uint32_t byteStride) const = 0; + + /** + \brief Writes the normals into a user specified buffer. + + Returns false if the buffer doesn't exist. + The buffer must be bigger than sizeof(PxVec3) * getNumVertices() + */ + virtual bool getNormals(PxVec3* normals, uint32_t byteStride) const = 0; + + /** + \brief Returns the number of bones per vertex. + */ + virtual uint32_t getNumBonesPerVertex() const = 0; + + /** + \brief Writes the bone indices into a user specified buffer. + + Returns false if the buffer doesn't exist. + The buffer must be bigger than sizeof(uint16_t) * getNumVertices() * getNumBonesPerVertex(). + (numBonesPerVertex is the same as in the graphical mesh for LOD 0) + + The bytestride is applied only after writing numBonesPerVertex and thus must be >= sizoef(uint16_t) * numBonesPerVertex + */ + virtual bool getBoneIndices(uint16_t* boneIndices, uint32_t byteStride) const = 0; + + /** + \brief Writes the bone weights into a user specified buffer. + + Returns false if the buffer doesn't exist. + The buffer must be bigger than sizeof(float) * getNumVertices() * getNumBonesPerVertex(). + (numBonesPerVertex is the same as in the graphical mesh for LOD 0) + The bytestride is applied only after writing numBonesPerVertex and thus must be >= sizoef(float) * numBonesPerVertex + */ + virtual bool getBoneWeights(float* boneWeights, uint32_t byteStride) const = 0; + + /** + \brief Allocates and initializes the drive channels (master flags) of the physics mesh. + + This allows to set the drive channels directly on the physics mesh. + */ + virtual void allocateMasterFlagsBuffer() = 0; + + /** + \brief Returns the masterFlag buffer pointer in order to edit the values. + + This allows to set values directly on the physics mesh. + */ + virtual uint32_t* getMasterFlagsBuffer() = 0; + + /** + \brief Allocates and initializes the constrain coefficients of the physics mesh. + + This allows to set the constrain coefficients like maxDistance directly on the physics mesh. + If this is not called by the authoring tool, the constrain coefficients are read from the + graphical mesh. + */ + virtual void allocateConstrainCoefficientBuffer() = 0; + + /** + \brief Returns the constrain coefficient buffer pointer in order to edit the values. + + This allows to set the constrain coefficients like maxDistance directly on the physics mesh. + */ + virtual ClothingConstrainCoefficients* getConstrainCoefficientBuffer() const = 0; + + /** + \brief Writes the cloth constrain coefficients into a user specified buffer. + + Returns false if the buffer doesn't exist. The buffer must be bigger than sizeof(ClothingConstrainCoefficients) * getNumVertices(). + */ + virtual bool getConstrainCoefficients(ClothingConstrainCoefficients* coeffs, uint32_t byteStride) const = 0; + + /** + \brief Returns stats (sizes, counts) for the asset. See ClothingPhysicalMeshStats. + */ + virtual void getStats(ClothingPhysicalMeshStats& stats) const = 0; + +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // CLOTHING_PHYSICAL_MESH_H diff --git a/APEX_1.4/include/clothing/ClothingPreview.h b/APEX_1.4/include/clothing/ClothingPreview.h new file mode 100644 index 00000000..456abd9b --- /dev/null +++ b/APEX_1.4/include/clothing/ClothingPreview.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CLOTHING_PREVIEW_H +#define CLOTHING_PREVIEW_H + +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + + + +/** +\brief A lightweight preview of a ClothingActor that will not perform any simulation +*/ +class ClothingPreview : public AssetPreview +{ + +public: + + /** + \brief Updates all internal bone matrices. + \see ClothingActor::updateState + */ + virtual void updateState(const PxMat44& globalPose, const PxMat44* newBoneMatrices, uint32_t boneMatricesByteStride, uint32_t numBoneMatrices) = 0; + +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // CLOTHING_PREVIEW_H diff --git a/APEX_1.4/include/clothing/ClothingRenderProxy.h b/APEX_1.4/include/clothing/ClothingRenderProxy.h new file mode 100644 index 00000000..ef4a884b --- /dev/null +++ b/APEX_1.4/include/clothing/ClothingRenderProxy.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CLOTHING_RENDER_PROXY_H +#define CLOTHING_RENDER_PROXY_H + +#include "Renderable.h" +#include "ApexInterface.h" + +namespace NvParameterized +{ +class Interface; +} + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Instance of ClothingRenderProxy. This is the renderable of a clothing actor. +The data in this object is consistent until it is returned to APEX with the release() +call. +*/ +class ClothingRenderProxy : public ApexInterface, public Renderable +{ +protected: + virtual ~ClothingRenderProxy() {} + +public: + /** + \brief True if the render proxy contains simulated data, false if it is purely animated. + */ + virtual bool hasSimulatedData() const = 0; +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // CLOTHING_RENDER_PROXY_H diff --git a/APEX_1.4/include/clothing/ClothingVelocityCallback.h b/APEX_1.4/include/clothing/ClothingVelocityCallback.h new file mode 100644 index 00000000..ea46f314 --- /dev/null +++ b/APEX_1.4/include/clothing/ClothingVelocityCallback.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef CLOTHING_VELOCITY_CALLBACK_H +#define CLOTHING_VELOCITY_CALLBACK_H + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +/** +\brief container class for the velocity shader callback. +*/ +class ClothingVelocityCallback +{ +public: + /** + \brief This callback will be fired in Apex threads. It must not address any user data, just operate on the data. + \param [in,out] velocities The velocities of the cloth. These can be modified if necessary, but then the method needs to return true! + \param [in] positions The positions of the cloth. Must not be modified, only read. + \param [in] numParticles Size of the velocities and positions array. + + \return return true if the velocities have been altered, false if they just have been read + */ + virtual bool velocityShader(PxVec3* velocities, const PxVec3* positions, uint32_t numParticles) = 0; +}; + +} // namespace nvidia +} // namespace nvidia + +#endif // CLOTHING_VELOCITY_CALLBACK_H diff --git a/APEX_1.4/include/clothing/ModuleClothing.h b/APEX_1.4/include/clothing/ModuleClothing.h new file mode 100644 index 00000000..2e38d16f --- /dev/null +++ b/APEX_1.4/include/clothing/ModuleClothing.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_CLOTHING_H +#define MODULE_CLOTHING_H + +#include "Module.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class ClothingAsset; +class ClothingAssetAuthoring; +class ClothingPhysicalMesh; + +class IProgressListener; +class RenderMeshAssetAuthoring; + +/** +\mainpage APEX Clothing API Documentation + +\section overview Overview + +This document contains a full API documentation for all public classes. +*/ + + + +/** +\brief APEX Clothing Module + +Used to generate simulated clothing on (mostly humanoid) characters. +*/ +class ModuleClothing : public Module +{ +public: + /** + \brief creates an empty physical mesh. A custom mesh can be assigned to it. + */ + virtual ClothingPhysicalMesh* createEmptyPhysicalMesh() = 0; + + /** + \brief creates a physical mesh based on a render mesh asset. This will be a 1 to 1 copy of the render mesh + + \param [in] asset The render mesh that is used as source for the physical mesh + \param [in] subdivision Modify the physical mesh such that all edges that are longer than (bounding box diagonal / subdivision) are split up. Must be <= 200 + \param [in] mergeVertices All vertices with the same position will be welded together. + \param [in] closeHoles Close any hole found in the mesh. + \param [in] progress An optional callback for progress display. + */ + virtual ClothingPhysicalMesh* createSingleLayeredMesh(RenderMeshAssetAuthoring* asset, uint32_t subdivision, bool mergeVertices, bool closeHoles, IProgressListener* progress) = 0; + +protected: + virtual ~ModuleClothing() {} +}; + +#if !defined(_USRDLL) +/** +* If this module is distributed as a static library, the user must call this +* function before calling ApexSDK::createModule("Clothing") +*/ +void instantiateModuleClothing(); +#endif + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // MODULE_CLOTHING_H diff --git a/APEX_1.4/include/destructible/DestructibleActor.h b/APEX_1.4/include/destructible/DestructibleActor.h new file mode 100644 index 00000000..7ad688c5 --- /dev/null +++ b/APEX_1.4/include/destructible/DestructibleActor.h @@ -0,0 +1,721 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef DESTRUCTIBLE_ACTOR_H +#define DESTRUCTIBLE_ACTOR_H + +#include "foundation/Px.h" +#include "Actor.h" +#include "Renderable.h" +#include "ModuleDestructible.h" +#include "PxForceMode.h" + +namespace physx +{ + class PxRigidDynamic; +}; + +#define DESTRUCTIBLE_ACTOR_TYPE_NAME "DestructibleActor" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +struct DestructibleParameters; +class RenderVolume; +class EmitterActor; +class DestructibleRenderable; +class DestructibleBehaviorGroupDesc; + + +/** + Determines which type of emitter to associate with a render volume +*/ +struct DestructibleEmitterType +{ + /** + Enum of destructible emitter types + */ + enum Enum + { + Crumble, + Dust, // Note: this is a placeholder. Its implementation has been removed in 1.2.0, and will be restored in later versions. + Count + }; +}; + +/** + Provides access to specific NvParamterized types provided by the destructible actor +*/ +struct DestructibleParameterizedType +{ + /** + Enum of destructible parameterized types + */ + enum Enum + { + State, // The full state of the actor (including params, chunk data, etc...) + Params, // The parameters used to initialize the actor + }; +}; + +/** + Hit chunk info. Hit chunks are those directly affected by fracture events. See getHitChunkHistory and forceChunkHits. +*/ +struct DestructibleHitChunk +{ + uint32_t chunkIndex; ///< chunk index + uint32_t hitChunkFlags; ///< hit chunk flag +}; + +/** + Flags for managing the sync state of the destructible actor +*/ +struct DestructibleActorSyncFlags +{ + /** + Enum of destructible actor sync flags + */ + enum Enum + { + None = 0, + CopyDamageEvents = (1 << 0), + ReadDamageEvents = (1 << 1), + CopyFractureEvents = (1 << 2), + ReadFractureEvents = (1 << 3), + CopyChunkTransform = (1 << 4), + ReadChunkTransform = (1 << 5), + Last = (1 << 6), + }; +}; + +/** + Flags which control which actors are returned by DestructibleActor::acquirePhysXActorBuffer +*/ +struct DestructiblePhysXActorQueryFlags +{ + /** + Enum of destructible PhysX actor query flags + */ + enum Enum + { + None = 0, + + // Actor states + Static = (1 << 0), /// Destructible-static, which is a kinematic PhysX actor that hasn't been turned dynamic yet + Dynamic = (1 << 1), /// Dynamic, not dormant (not kinematic) + Dormant = (1 << 2), /// Dynamic, but dormant (had been made dynamic, but is now in a dormant, PhysX-kinematic state) + + AllStates = Static | Dynamic | Dormant, + + // Other filters + /** + Whether or not to ensure that PhysX actors are not listed more than once when this NxDestructibleActor is + part of an extended structure. If this is true, then some NxDestructibleActors may not return all PhysX actors associated with + all of their chunks (and in fact may return no PhysX actors), but after querying all NxDestructibleActors in a given structure, + every PhysX actor will be accounted for. + */ + AllowRedundancy = (1 << 3), + + /** + Whether or not to allow actors not yet put into the PxScene (e.g. there has not been a simulation step since the actor was created) are also returned. + */ + AllowActorsNotInScenes = (1 << 4) + }; +}; + +/** + Tweak-able parameters on source-side for controlling the actor sync state. +*/ +struct DestructibleActorSyncState +{ + uint32_t damageEventFilterDepth; ///< dictates the (inclusive) maximum depth at which damage events will be buffered. + uint32_t fractureEventFilterDepth; ///< dictates the (inclusive) maximum depth at which fracture events will be buffered. +}; + +/** + Tweak-able parameters on source-side for controlling the chunk sync state. DestructibleActorSyncFlags::CopyChunkTransform must first be set. +*/ +struct DestructibleChunkSyncState +{ + bool disableTransformBuffering; ///< a handy switch for controlling whether chunk transforms will be buffered this instance. + bool excludeSleepingChunks; ///< dictates whether chunks that are sleeping will be buffered. + uint32_t chunkTransformCopyDepth; ///< dictates the (inclusive) maximum depth at which chunk transforms will be buffered. +}; + +/** + Flags which describe an actor chunk (as opposed to an asset chunk) - takes into account the actor's condition, for example + a chunk may be world supported because of the actor's placement +*/ +struct DestructibleActorChunkFlags +{ + /** + Enum of destructible actor chunk flags + */ + enum Enum + { + /** + "Use world support" is set in the destructible parameters, and this chunk is a support-depth chunk that + overlaps the physx scene's static geometry + */ + ChunkIsWorldSupported = (1<<0), + }; +}; + +/** + Destructible actor API. The destructible actor is instanced from an DestructibleAsset. +*/ +class DestructibleActor : public Actor, public Renderable +#if PX_PHYSICS_VERSION_MAJOR == 3 + , public ActorSource +#endif +{ +public: + /** + Get the render mesh actor for the specified mesh type. + */ + virtual const RenderMeshActor* getRenderMeshActor(DestructibleActorMeshType::Enum type = DestructibleActorMeshType::Skinned) const = 0; + + /** + Gets the destructible's DestructibleParameter block of parameters. These are initially set from the asset. + */ + virtual const DestructibleParameters& getDestructibleParameters() const = 0; + + /** + Sets the destructible's DestructibleParameter block of parameters. These may be set at runtime. + */ + virtual void setDestructibleParameters(const DestructibleParameters& destructibleParameters) = 0; + + /** + Gets the global pose used when the actor is added to the scene, in the DestructibleActorDesc + */ + virtual PxMat44 getInitialGlobalPose() const = 0; + + /** + Resets the initial global pose used for support calculations when the first simulation step is run. + */ + virtual void setInitialGlobalPose(const PxMat44& pose) = 0; + + /** + Gets the destructible actor's 3D (possibly nonuniform) scale + */ + virtual PxVec3 getScale() const = 0; + + /** + Returns true iff the destructible actor starts off life dynamic. + */ + virtual bool isInitiallyDynamic() const = 0; + + /** + Returns an array of visibility data for each chunk. Each byte in the array is 0 if the + corresponding chunkIndex is invisible, 1 if visibile. + + \param visibilityArray a pointer to the byte buffer to hold the visibility values. + \param visibilityArraySize the size of the visibilityArray + */ + virtual void getChunkVisibilities(uint8_t* visibilityArray, uint32_t visibilityArraySize) const = 0; + + /** + Returns the number of visible chunks. This is the number of 1's written to the visibilityArray by getChunkVisibilities. + */ + virtual uint32_t getNumVisibleChunks() const = 0; + + /** + Returns a pointer to an array of visible chunk indices. + */ + virtual const uint16_t* getVisibleChunks() const = 0; + + /** + Locks the chunk event buffer, and (if successful) returns the head of the chunk event buffer in the buffer field and the length + of the buffer (the number of events) in the bufferSize field. To unlock the buffer, use releaseChunkEventBuffer(). + See DestructibleChunkEvent. This buffer is filled with chunk events if the DestructibleActor parameter createChunkEvents is set to true. + This buffer is not automatically cleared by APEX. The user must clear it using releaseChunkEventBuffer(true). + + N.B. This function only works when the user has *not* requested chunk event callbacks via ModuleDestructible::scheduleChunkStateEventCallback. + + \return Returns true if successful, false otherwise. + */ + virtual bool acquireChunkEventBuffer(const nvidia::DestructibleChunkEvent*& buffer, uint32_t& bufferSize) = 0; + + /** + Releases the chunk event buffer, which may have been locked by acquireChunkEventBuffer(). + If clearBuffer is true, the buffer will be erased before it is unlocked. + + \return Returns true if successful, false otherwise. + */ + virtual bool releaseChunkEventBuffer(bool clearBuffer = true) = 0; + + /** + Locks a PhysX actor buffer, and (if successful) returns the head of the buffer in the buffer field and the length + of the buffer (the number of PhysX actors) in the bufferSize field. + To unlock the buffer, use releasePhysXActorBuffer(). + The user must release this buffer before another call to releasePhysXActorBuffer. + + \param buffer returned buffer, if successful + \param bufferSize returned buffer size, if successful + \param flags flags which control which actors are returned. See DestructiblePhysXActorQueryFlags. + + \return Returns true if successful, false otherwise. + */ + virtual bool acquirePhysXActorBuffer(physx::PxRigidDynamic**& buffer, uint32_t& bufferSize, uint32_t flags = DestructiblePhysXActorQueryFlags::AllStates) = 0; + + /** + Releases the PhysX actor buffer, which may have been locked by acquirePhysXActorBuffer(). + The buffer will be erased before it is unlocked. + + \return Returns true if successful, false otherwise. + */ + virtual bool releasePhysXActorBuffer() = 0; + + /** + Returns the PhysX actor associated with the given chunk. Note, more than one chunk may be associated with a given PhysX actor, and + chunks from different DestructibleActors may even be associated with the same PhysX actor. + Caution is recommended when using this function. During APEX scene simulate/fetchResults, this actor may be deleted, replaced, or tampered with. + When the chunk in question is not visible, but an ancestor of a visible chunk, the visible ancestor's shapes are returned. + + \param chunkIndex the chunk index within the actor + */ + virtual physx::PxRigidDynamic* getChunkPhysXActor(uint32_t chunkIndex) = 0; + + /** + Returns the PhysX shapes associated with the given chunk. + Caution is recommended when using this function. During APEX scene simulate/fetchResults, this actor may be deleted, replaced, or tampered with. + It is safe to use the results of this function during the chunk event callback (see ModuleDestructible::setChunkReport). + + \param shapes returned pointer to array of shapes. May be NULL. + \param chunkIndex the chunk index within the actor + + \return size of array pointed to by shapes pointer. 0 if shapes == NULL. + */ + virtual uint32_t getChunkPhysXShapes(physx::PxShape**& shapes, uint32_t chunkIndex) const = 0; + + /** + Returns current pose of a chunk's reference frame, without scaling. This pose can be used to transform the chunk's hull data + from the asset into global space. + + \param chunkIndex the chunk index within the actor + + \note This pose's translation might not be inside the chunk. Use getChunkBounds to get a better representation + of where the chunk is located. + */ + virtual PxTransform getChunkPose(uint32_t chunkIndex) const = 0; + + /** + Returns current pose of a chunk's reference frame, without scaling. This pose can be used to transform the chunk's hull data + from the asset into global space. + + \param chunkIndex the chunk index within the actor + + \note This pose's translation might not be inside the chunk. Use getChunkBounds to get a better representation + of where the chunk is located. + */ + virtual PxTransform getChunkTransform(uint32_t chunkIndex) const = 0; + + /** + Returns a chunk's linear velocity in world space. + + \param chunkIndex the chunk index within the actor + */ + virtual PxVec3 getChunkLinearVelocity(uint32_t chunkIndex) const = 0; + + /** + Returns a chunk's angular velocity in world space. + + \param chunkIndex the chunk index within the actor + */ + virtual PxVec3 getChunkAngularVelocity(uint32_t chunkIndex) const = 0; + + /** + Returns the transform of the chunk's graphical representation. This may have + a scale component. + + \param chunkIndex the chunk index within the actor + */ + virtual const PxMat44 getChunkTM(uint32_t chunkIndex) const = 0; + + /** + Returns the behavior group index associated with the chunk. Use getBehaviorGroup() to access the behavior group data. + The index will either be -1, in which case it is the default behavior group, or in the range [0, getCustomBehaviorGroupCount()-1]. + Any of those values is valid for getBehaviorGroup(). + + \param chunkIndex the chunk index within the actor + */ + virtual int32_t getChunkBehaviorGroupIndex(uint32_t chunkIndex) const = 0; + + /** + Returns the DestructibleActorChunkFlags for a chunk. These are flags that describe + aspects of the chunk that can only be determined at runtime. + + \param chunkIndex the chunk index within the actor + */ + virtual uint32_t getChunkActorFlags(uint32_t chunkIndex) const = 0; + + /** + Set the destructible actor's global pose. This will only be applied to the physx PxActor or PxActor + for the static chunks, and therefore will apply to all static chunks in the structure which contains + the this destructible actor. This pose should not contain scale, as the scale is already contained + in the actor's scale parameter. + */ + virtual void setGlobalPose(const PxMat44& pose) = 0; + + /** + Get the destructible actor's global pose. This will be the pose of the physx PxActor or PxActor + for the static chunks in the structure containing this actor, if there are static chunks. If there + are no static chunks in the structure, pose will not be modified and false will be returned. Otherwise + pose will be filled in with a scale-free transform, and true is returned. + */ + virtual bool getGlobalPose(PxMat44& pose) = 0; + + /** + Sets the linear velocity of every dynamic chunk to the given value. + */ + virtual void setLinearVelocity(const PxVec3& linearVelocity) = 0; + + /** + Sets the angular velocity of every dynamic chunk to the given value. + */ + virtual void setAngularVelocity(const PxVec3& angularVelocity) = 0; + + /** + If the indexed chunk is visible, it is made dynamic (if it is not already). + If ModuleDestructibleConst::INVALID_CHUNK_INDEX is passed in, all visible chunks in the + destructible actor are made dynamic, if they are not already. + */ + virtual void setDynamic(int32_t chunkIndex = ModuleDestructibleConst::INVALID_CHUNK_INDEX) = 0; + + /** + Returns true if the chunkIndex is valid, and the indexed chunk is dynamic. Returns false otherwise. + */ + virtual bool isDynamic(uint32_t chunkIndex) const = 0; + + /** + If "hard sleeping" is enabled, physx actors for chunk islands that go to sleep will be turned kinematic. If a chunk + island has chunks from more than one DestructibleActor, then hard sleeping will be used if ANY of the destructibles + have hard sleeping enabled. + */ + virtual void enableHardSleeping() = 0; + + /** + See the comments for enableHardSleeping() for a description of this feature. The disableHardSleeping function takes + a "wake" parameter, which (if true) will not only turn kinematic-sleeping actors dynamic, but wake them as well. + */ + virtual void disableHardSleeping(bool wake = false)= 0; + + /** + Returns true iff hard sleeping is selected for this DestructibleActor. + */ + virtual bool isHardSleepingEnabled() const = 0; + + /** + Puts the PxActor associated with the given chunk to sleep, or wakes it up, depending upon the value of the 'awake' bool. + + \param chunkIndex the chunk index within the actor + \param awake if true, wakes the actor, otherwise puts the actor to sleep + + Returns true iff successful. + */ + virtual bool setChunkPhysXActorAwakeState(uint32_t chunkIndex, bool awake) = 0; + + /** + Apply force to chunk's actor + + \param chunkIndex the chunk index within the actor + \param force force, impulse, velocity change, or acceleration (depending on value of mode) + \param mode PhysX force mode (PxForceMode::Enum) + \param position if not null, applies force at position. Otherwise applies force at center of mass + \param wakeup if true, the actor is awakened + + Returns true iff successful. + */ + virtual bool addForce(uint32_t chunkIndex, const PxVec3& force, physx::PxForceMode::Enum mode, const PxVec3* position = NULL, bool wakeup = true) = 0; + + /** + Sets the override material. + */ + virtual void setSkinnedOverrideMaterial(uint32_t submeshIndex, const char* overrideMaterialName) = 0; + + /** + Sets the override material. + */ + virtual void setStaticOverrideMaterial(uint32_t submeshIndex, const char* overrideMaterialName) = 0; + + /** + Sets the override fracture pattern. + */ + virtual void setRuntimeFractureOverridePattern(const char* overridePatternName) = 0; + + /** + Damage + */ + + /** + Apply damage at a point. Damage will be propagated into the destructible based + upon its DestructibleParameters. + + \param damage the amount of damage at the damage point + \param momentum the magnitude of the impulse to transfer to the actor + \param position the damage location + \param direction direction of impact. This is valid even if momentum = 0, for use in deformation calculations. + \param chunkIndex which chunk to damage (returned by rayCast and ModuleDestructible::getDestructibleAndChunk). + If chunkIndex = ModuleDestructibleConst::INVALID_CHUNK_INDEX, then the nearest visible chunk hit is found. + \param damageUserData pointer which will be returned in damage and fracture event callbacks + */ + virtual void applyDamage(float damage, float momentum, const PxVec3& position, const PxVec3& direction, int32_t chunkIndex = ModuleDestructibleConst::INVALID_CHUNK_INDEX, void* damageUserData = NULL) = 0; + + /** + Apply damage to all chunks within a radius. Damage will also propagate into the destructible + based upon its DestructibleParameters. + + \param damage the amount of damage at the damage point + \param momentum the magnitude of the impulse to transfer to each chunk + \param position the damage location + \param radius distance from damage location at which chunks will be affected + \param falloff whether or not to decrease damage with distance from the damage location. If true, + damage will decrease linearly from the full damage (at zero distance) to zero damage (at radius). + If false, full damage is applied to all chunks within the radius. + \param damageUserData pointer which will be returned in damage and fracture event callbacks + */ + virtual void applyRadiusDamage(float damage, float momentum, const PxVec3& position, float radius, bool falloff, void* damageUserData = NULL) = 0; + + /** + Register a rigid body impact for impact-based damage. Much like applyDamage, but multplies the input 'force' by the destructible's forceToDamage parameter, and also allows the user + to report the impacting PhysX actor + */ + virtual void takeImpact(const PxVec3& force, const PxVec3& position, uint16_t chunkIndex, PxActor const* damageImpactActor) = 0; + + /** + PhysX SDK 3.X. + Returns the index of the first visible chunk hit in the actor by worldRay, if any. + Otherwise returns ModuleDestructibleConst::INVALID_CHUNK_INDEX. + If a chunk is hit, the time and normal fields are modified. + + \param[out] time (return value) of the time to the hit chunk, if any. + \param[out] normal (return value) the surface normal of the hit chunk's collision volume, if any. + \param worldRayOrig origin of the ray to fire at the actor (the direction need not be normalized) + \param worldRayDir direction of the ray to fire at the actor (the direction need not be normalized) + \param flags raycast control flags (see DestructibleActorRaycastFlags) + \param parentChunkIndex (if not equal to ModuleDestructibleConst::INVALID_CHUNK_INDEX) + the chunk subhierarchy in which to confine the raycast. If parentChunkIndex = + ModuleDestructibleConst::INVALID_CHUNK_INDEX, then the whole actor is searched. + */ + virtual int32_t rayCast(float& time, PxVec3& normal, const PxVec3& worldRayOrig, const PxVec3& worldRayDir, DestructibleActorRaycastFlags::Enum flags, int32_t parentChunkIndex = ModuleDestructibleConst::INVALID_CHUNK_INDEX) const = 0; + + /** + Physx SDK 3.X. + Returns the index of the first visible chunk hit in the actor by swept oriented bounding box, if any. + Otherwise returns ModuleDestructibleConst::INVALID_CHUNK_INDEX. + If a chunk is hit, the time and normal fields are modified. + + \param[out] time (return value) of the time to the hit chunk, if any. + \param[out] normal (return value) the surface normal of the hit chunk's collision volume, if any. + \param worldBoxCenter the center of the obb to sweep against the actor, oriented in world space + \param worldBoxExtents the extents of the obb to sweep against the actor, oriented in world space + \param worldBoxRot the rotation of the obb to sweep against the actor, oriented in world space + \param worldDisplacement the displacement of the center of the worldBox through the sweep, in world space + \param flags raycast control flags (see DestructibleActorRaycastFlags) + */ + virtual int32_t obbSweep(float& time, PxVec3& normal, const PxVec3& worldBoxCenter, const PxVec3& worldBoxExtents, const PxMat33& worldBoxRot, const PxVec3& worldDisplacement, DestructibleActorRaycastFlags::Enum flags) const = 0; + + /** + Enable/disable the crumble emitter + */ + virtual void setCrumbleEmitterState(bool enable) = 0; + + /** + Enable/disable the dust emitter + Note - this is a placeholder API. The dust feature is disabled in 1.2.0. + */ + virtual void setDustEmitterState(bool enable) = 0; + + /** + Sets a preferred render volume for a dust or crumble emitter + Note - only crumble emitters are implemented in 1.2.0 + */ + virtual void setPreferredRenderVolume(RenderVolume* volume, DestructibleEmitterType::Enum type) = 0; + + + /** + Returns the EmitterActor of either a dust or crumble emitter + Note - only crumble emitters are implemented in 1.2.0 + */ + virtual EmitterActor* getApexEmitter(DestructibleEmitterType::Enum type) = 0; + + /** + * Recreates the Apex Emitter, if necessary. Use this method to re-initialize the crumble or dust emitter after a change has been made to a dependent asset + * Note - only crumble emitters are implemented in 1.2.0 + */ + virtual bool recreateApexEmitter(DestructibleEmitterType::Enum type) = 0; + + /** + * \brief Returns the actor's NvParamaterized interface + * This cannot be directly modified! It is read only to the user. + * This handle can be used to directly serialize the complete actor state. + */ + virtual const ::NvParameterized::Interface* getNvParameterized(DestructibleParameterizedType::Enum type = DestructibleParameterizedType::State) const = 0; + + /** + * \brief Sets the actor's state via the NvParameterized object + * This can be used to update the state from deserialized data. + * The actor assumes control of the interface. + */ + virtual void setNvParameterized(::NvParameterized::Interface*) = 0; + + /** + Set the syncing properties of the destructible actor. + + \param userActorID user-defined value used to identify the syncing actor. + This value will be used to identify destructible actors between the server and client. + userActorID = 0 is used for unregistering the actor as a syncing actor, and is the default value. + The other arguments will then be forcibly set to the default (non-participating) values. + userActorID != 0 registers the actor as a participating syncing actor. + userActorID can be overwritten. In this case, the destructible actor which used to hold this userActorID + will behave exactly like a call to set userActorID to 0. + + \param actorSyncFlags describes the kind of actor information that participates in syncing. See struct DestructibleActorSyncFlags + + \param actorSyncState describes information that allows finer control over the actor that participates in syncing. See struct DestructibleActorSyncState + + \param chunkSyncState describes information that allows finer control over the chunk that participates in syncing. See struct DestructibleChunkSyncState + + \return Returns true if arguments are accepted. Any one invalid argument will cause a return false. In such a case, no changes are made. + */ + virtual bool setSyncParams(uint32_t userActorID, uint32_t actorSyncFlags = 0, const DestructibleActorSyncState * actorSyncState = NULL, const DestructibleChunkSyncState * chunkSyncState = NULL) = 0; + + /** + Set the tracking properties of the actor for chunks that are hit. Chunks that are hit are chunks directly affected by fracture events. + + \param flushHistory flushHistory == true indicates that both the cached chunk hit history and the cached damage event core data will be cleared. + To get the chunk hit history of this actor, see getHitChunkHistory() + To get the damage coloring history of this actor, see getDamageColoringHistory() + \param startTracking startTracking == true indicates that chunk hits and damage coloring will begin caching internally. The actor does not cache chunk hits by default. + \param trackingDepth the depth at which hit chunks will be cached. This value should not exceed the maximum depth level. + \param trackAllChunks trackAllChunks == true indicates that all the chunks will be cached, trackAllChunks == false indicates that only static chunks will be cached. + + Returns true if the function executes correctly with the given arguments. + */ + virtual bool setHitChunkTrackingParams(bool flushHistory, bool startTracking, uint32_t trackingDepth, bool trackAllChunks = true) = 0; + + /** + Get the chunk hit history of the actor. To start caching chunk hits, see setHitChunkTrackingParams() + + \return Returns true if the function executes correctly with the given arguments. + */ + virtual bool getHitChunkHistory(const DestructibleHitChunk *& hitChunkContainer, uint32_t & hitChunkCount) const = 0; + + /** + Force the actor to register chunk hits. + + \param hitChunkContainer should take in an argument that was generated from another destructible actor. See getHitChunkHistory() + \param hitChunkCount hit chunk count + \param removeChunks removeChunks == true indicates that the chunks given by hitChunkContainer will be forcibly removed. + \param deferredEvent whether to enable deferred event mode. If true, fracture events won't get processed until the next tick. + \param damagePosition passed through to ApexDamageEventReportData::hitPosition and hitDirection in the damage notify output by APEX. + \param damageDirection passed through to ApexDamageEventReportData::hitPosition and hitDirection in the damage notify output by APEX. + */ + virtual bool forceChunkHits(const DestructibleHitChunk * hitChunkContainer, uint32_t hitChunkCount, bool removeChunks = true, bool deferredEvent = false, PxVec3 damagePosition = PxVec3(0.0f), PxVec3 damageDirection = PxVec3(0.0f)) = 0; + + /** + Get the damage coloring history of the actor. To start caching damage coloring, see setHitChunkTrackingParams() + + \return Returns true if the function executes correctly with the given arguments. + */ + virtual bool getDamageColoringHistory(const DamageEventCoreData *& damageEventCoreDataContainer, uint32_t & damageEventCoreDataCount) const = 0; + + /** + Force the actor to register damage coloring. + + \param damageEventCoreDataContainer should take in an argument that was generated from another destructible actor. See getDamageColoringHistory() + \param damageEventCoreDataCount the count of damageEventCoreDataContainer. + + \return Returns true if the function executes correctly with the given arguments. + */ + virtual bool forceDamageColoring(const DamageEventCoreData * damageEventCoreDataContainer, uint32_t damageEventCoreDataCount) = 0; + + /** + Accessor to get the initial locally-aligned bounding box of a destructible actor. + */ + virtual PxBounds3 getLocalBounds() const = 0; + + /** + Accessor to get the initial world axis-aligned bounding box of a destructible actor. + */ + virtual PxBounds3 getOriginalBounds() const = 0; + + /** + Accessor to query if a chunk is part of a detached island. + */ + virtual bool isChunkSolitary(int32_t chunkIndex) const = 0; + + /** + Accessor to query the axis aligned bounding box of a given chunk in world-space. + */ + virtual PxBounds3 getChunkBounds(uint32_t chunkIndex) const = 0; + + /** + Accessor to query the axis aligned bounding box of a given chunk in chunk local-space. + */ + virtual PxBounds3 getChunkLocalBounds(uint32_t chunkIndex) const = 0; + + /** + Accessor to query if a chunk has been destroyed. + */ + virtual bool isChunkDestroyed(int32_t chunkIndex) const = 0; + + /** + Accessor to get the array of chunk indices at the support depth. + */ + virtual uint32_t getSupportDepthChunkIndices(uint32_t* const OutChunkIndices, uint32_t MaxOutIndices) const = 0; + + /** + Query the actor's support depth. + */ + virtual uint32_t getSupportDepth() const = 0; + + /** + Set the actor to delete its fractured chunks instead of simulating them. + */ + virtual void setDeleteFracturedChunks(bool inDeleteChunkMode) = 0; + + /** + Acquire a pointer to the destructible's renderable proxy and increment its reference count. The DestructibleRenderable will + only be deleted when its reference count is zero. Calls to DestructibleRenderable::release decrement the reference count, as does + a call to DestructibleActor::release(). . + */ + virtual DestructibleRenderable* acquireRenderableReference() = 0; + + /** + Access to behavior groups created for this actor. Each chunk has a behavior group index associated with it. + + \return This returns the number of custom (non-default) behavior groups. + */ + virtual uint32_t getCustomBehaviorGroupCount() const = 0; + + /** + Access to behavior groups created for this actor. Each chunk has a behavior group index associated with it. + + This returns the indexed behavior group. The index must be either -1 (for the default group) or in the range [0, getCustomBehaviorGroupCount()-1]. + If any other index is given, this function returns false. Otherwise it returns true and the behavior descriptor is filled in. + */ + virtual bool getBehaviorGroup(nvidia::DestructibleBehaviorGroupDesc& behaviorGroupDesc, int32_t index = -1) const = 0; + +protected: + virtual ~DestructibleActor() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // DESTRUCTIBLE_ACTOR_H diff --git a/APEX_1.4/include/destructible/DestructibleActorJoint.h b/APEX_1.4/include/destructible/DestructibleActorJoint.h new file mode 100644 index 00000000..e5783e9d --- /dev/null +++ b/APEX_1.4/include/destructible/DestructibleActorJoint.h @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef DESTRUCTIBLE_ACTOR_JOINT_H +#define DESTRUCTIBLE_ACTOR_JOINT_H + +#include "ModuleDestructible.h" + +#include "extensions/PxJoint.h" + + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** + Descriptor used to create the Destructible actor joint. +*/ +class DestructibleActorJointDesc : public ApexDesc +{ +public: + + /** + \brief constructor sets to default. + */ + PX_INLINE DestructibleActorJointDesc(); + + /** + \brief Resets descriptor to default settings. + */ + PX_INLINE void setToDefault(); + + /** + Returns true iff an object can be created using this descriptor. + */ + PX_INLINE bool isValid() const; + + /** + PhysX SDK 3.X only. + */ + physx::PxJointConcreteType::Enum type; + /** + PhysX SDK 3.X only. + */ + PxRigidActor* actor[2]; + /** + PhysX SDK 3.X only. + */ + PxVec3 localAxis[2]; + /** + PhysX SDK 3.X only. + */ + PxVec3 localAnchor[2]; + /** + PhysX SDK 3.X only. + */ + PxVec3 localNormal[2]; + + /** + If destructible[i] is not NULL, it will effectively replace the actor[i] in jointDesc. + At least one must be non-NULL. + */ + DestructibleActor* destructible[2]; + + /** + If destructible[i] is not NULL and attachmentChunkIndex[i] is a valid chunk index within that + destructible, then that chunk will be used for attachment. + If destructible[i] is not NULL and attachmentChunkIndex[i] is NOT a valid chunk index (such as the + default ModuleDestructibleConst::INVALID_CHUNK_INDEX), then the nearest chunk to globalAnchor[i] is used instead. + Once a chunk is determined, the chunk's associated PxActor will be the PxJoint's attachment actor. + */ + int32_t attachmentChunkIndex[2]; + + + /** + Global attachment data. Since destructibles come apart, there is no single referece frame + associated with them. Therefore it makes more sense to use a global reference frame + when describing the attachment positions and axes. + */ + + /** + \brief global attachment positions + */ + PxVec3 globalAnchor[2]; + + /** + \brief global axes + */ + PxVec3 globalAxis[2]; + + /** + \brief global normals + */ + PxVec3 globalNormal[2]; +}; + +// DestructibleActorJointDesc inline functions + +PX_INLINE DestructibleActorJointDesc::DestructibleActorJointDesc() : ApexDesc() +{ + setToDefault(); +} + +PX_INLINE void DestructibleActorJointDesc::setToDefault() +{ + ApexDesc::setToDefault(); + for (int i=0; i<2; i++) + { + actor[i] = 0; + localAxis[i] = PxVec3(0,0,1); + localNormal[i] = PxVec3(1,0,0); + localAnchor[i] = PxVec3(0); + } + for (int i = 0; i < 2; ++i) + { + destructible[i] = NULL; + attachmentChunkIndex[i] = ModuleDestructibleConst::INVALID_CHUNK_INDEX; + globalAnchor[i] = PxVec3(0.0f); + globalAxis[i] = PxVec3(0.0f, 0.0f, 1.0f); + globalNormal[i] = PxVec3(1.0f, 0.0f, 0.0f); + } +} + +PX_INLINE bool DestructibleActorJointDesc::isValid() const +{ + if (destructible[0] == NULL && destructible[1] == NULL) + { + return false; + } + + for (int i = 0; i < 2; ++i) + { + if (PxAbs(globalAxis[i].magnitudeSquared() - 1.0f) > 0.1f) + { + return false; + } + if (PxAbs(globalNormal[i].magnitudeSquared() - 1.0f) > 0.1f) + { + return false; + } + //check orthogonal pairs + if (PxAbs(globalAxis[i].dot(globalNormal[i])) > 0.1f) + { + return false; + } + } + + return ApexDesc::isValid(); +} + + +/** + Destructible actor joint - a wrapper for an PxJoint. This needs to be used because APEX may need to replace an PxJoint + when fracturing occurs. Always use the joint() method to get the currently valid joint. +*/ +class DestructibleActorJoint : public ApexInterface +{ +public: + /** + PhysX SDK 3.X + Access to the {xJoint represented by the DestructibleActorJoint. This is a temporary interface, + and there are some shortcomings and restrictions: + 1) The user will have to upcast the result of joint() to the correct joint type in order + to access the interface for derived joints. + 2) The user must never delete the joint using the PhysX SDK. To release this joint, simply + use the release() method of this object (defined in the ApexInterface base class). + */ + virtual PxJoint* joint() = 0; + +protected: + virtual ~DestructibleActorJoint() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // DESTRUCTIBLE_ACTOR_JOINT_H diff --git a/APEX_1.4/include/destructible/DestructibleAsset.h b/APEX_1.4/include/destructible/DestructibleAsset.h new file mode 100644 index 00000000..732fc046 --- /dev/null +++ b/APEX_1.4/include/destructible/DestructibleAsset.h @@ -0,0 +1,2273 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef DESTRUCTIBLE_ASSET_H +#define DESTRUCTIBLE_ASSET_H + +#define DESTRUCTIBLE_AUTHORING_TYPE_NAME "DestructibleAsset" + +#include "foundation/Px.h" +#include "FractureToolsAPI.h" +// TODO: Remove this include when we remove the APEX_RUNTIME_FRACTURE define +#include "ModuleDestructible.h" + +#if PX_PHYSICS_VERSION_MAJOR == 3 +#include "PxFiltering.h" +#endif + +namespace nvidia +{ +namespace apex +{ + +struct IntPair; +class DestructibleActor; +class DestructiblePreview; + +PX_PUSH_PACK_DEFAULT +#if !PX_PS4 + #pragma warning(push) + #pragma warning(disable:4121) +#endif //!PX_PS4 + +/** + Flags that may be set for all chunks at a particular depth in the fracture hierarchy +*/ +struct DestructibleDepthParametersFlag +{ + /** + Enum of destructible depth parameters flag + */ + enum Enum + { + /** + If true, chunks at this hierarchy depth level will take impact damage iff OVERRIDE_IMPACT_DAMAGE = TRUE, no matter the setting of impactDamageDefaultDepth.. + Note, DestructibleParameters::forceToDamage must also be positive for this + to take effect. + */ + OVERRIDE_IMPACT_DAMAGE = (1 << 0), + + /** + If OVERRIDE_IMPACT_DAMAGE = TRUE, chunks at this hierarchy depth level will take impact damage iff OVERRIDE_IMPACT_DAMAGE = TRUE, no matter the setting of impactDamageDefaultDepth.. + */ + OVERRIDE_IMPACT_DAMAGE_VALUE = (1 << 1), + + /** + Chunks at this depth should have pose updates ignored. + */ + IGNORE_POSE_UPDATES = (1 << 2), + + /** + Chunks at this depth should be ignored in raycast callbacks. + */ + IGNORE_RAYCAST_CALLBACKS = (1 << 3), + + /** + Chunks at this depth should be ignored in contact callbacks. + */ + IGNORE_CONTACT_CALLBACKS = (1 << 4), + + /** + User defined flags. + */ + USER_FLAG_0 = (1 << 24), + USER_FLAG_1 = (1 << 25), + USER_FLAG_2 = (1 << 26), + USER_FLAG_3 = (1 << 27) + }; +}; + + +/** + Parameters that may be set for all chunks at a particular depth in the fracture hierarchy +*/ +struct DestructibleDepthParameters +{ + /** + \brief constructor sets to default. + */ + PX_INLINE DestructibleDepthParameters(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + \brief (re)sets the structure to parameters which are likely to be the most computationally expensive. + */ + PX_INLINE void setToMostExpensive(); + + /** + A convenience function to determine if the OVERRIDE_IMPACT_DAMAGE is set. + */ + PX_INLINE bool overrideImpactDamage() const; + + /** + A convenience function to read OVERRIDE_IMPACT_DAMAGE_VALUE is set. + */ + PX_INLINE bool overrideImpactDamageValue() const; + + /** + A convenience function to determine if the IGNORE_POSE_UPDATES is set. + */ + PX_INLINE bool ignoresPoseUpdates() const; + + /** + A convenience function to determine if the IGNORE_RAYCAST_CALLBACKS is set. + */ + PX_INLINE bool ignoresRaycastCallbacks() const; + + /** + A convenience function to determine if the IGNORE_CONTACT_CALLBACKS is set. + */ + PX_INLINE bool ignoresContactCallbacks() const; + + /** + A convenience function to determine if the USER_FLAG_0, USER_FLAG_1, USER_FLAG_2, or USER_FLAG_3 flag is set. + */ + PX_INLINE bool hasUserFlagSet(uint32_t flagIndex) const; + + /** + A collection of flags defined in DestructibleDepthParametersFlag. + */ + uint32_t flags; +}; + +// DestructibleDepthParameters inline functions + +PX_INLINE DestructibleDepthParameters::DestructibleDepthParameters() +{ + setToDefault(); +} + +PX_INLINE void DestructibleDepthParameters::setToDefault() +{ + flags = 0; +} + +PX_INLINE bool DestructibleDepthParameters::overrideImpactDamage() const +{ + return (flags & DestructibleDepthParametersFlag::OVERRIDE_IMPACT_DAMAGE) != 0; +} + +PX_INLINE bool DestructibleDepthParameters::overrideImpactDamageValue() const +{ + return (flags & DestructibleDepthParametersFlag::OVERRIDE_IMPACT_DAMAGE_VALUE) != 0; +} + +PX_INLINE bool DestructibleDepthParameters::ignoresPoseUpdates() const +{ + return (flags & DestructibleDepthParametersFlag::IGNORE_POSE_UPDATES) != 0; +} + +PX_INLINE bool DestructibleDepthParameters::ignoresRaycastCallbacks() const +{ + return (flags & DestructibleDepthParametersFlag::IGNORE_RAYCAST_CALLBACKS) != 0; +} + +PX_INLINE bool DestructibleDepthParameters::ignoresContactCallbacks() const +{ + return (flags & DestructibleDepthParametersFlag::IGNORE_CONTACT_CALLBACKS) != 0; +} + +PX_INLINE bool DestructibleDepthParameters::hasUserFlagSet(uint32_t flagIndex) const +{ + switch (flagIndex) + { + case 0: + return (flags & DestructibleDepthParametersFlag::USER_FLAG_0) != 0; + case 1: + return (flags & DestructibleDepthParametersFlag::USER_FLAG_1) != 0; + case 2: + return (flags & DestructibleDepthParametersFlag::USER_FLAG_2) != 0; + case 3: + return (flags & DestructibleDepthParametersFlag::USER_FLAG_3) != 0; + default: + return false; + } +} + +/** + Parameters for RT Fracture +*/ +struct DestructibleRTFractureParameters +{ + /** + If true, align fracture pattern to largest face. + If false, the fracture pattern will be aligned to the hit normal with each fracture. + */ + bool sheetFracture; + + /** + Number of times deep a chunk can be fractured. Can help limit the number of chunks produced by + runtime fracture. + */ + uint32_t depthLimit; + + /** + If true, destroy chunks when they hit their depth limit. + If false, then chunks at their depth limit will not fracture but will have a force applied. + */ + bool destroyIfAtDepthLimit; + + /** + Minimum Convex Size. Minimum size of convex produced by a fracture. + */ + float minConvexSize; + + /** + Scales impulse applied by a fracture. + */ + float impulseScale; + + /** + Parameters for glass fracture + */ + struct FractureGlass + { + /** + Number of angular slices in the glass fracture pattern. + */ + uint32_t numSectors; + + /** + Creates variance in the angle of slices. A value of zero results in all angular slices having the same angle. + */ + float sectorRand; + + /** + The minimum shard size. Shards below this size will not be created and thus not visible. + */ + float firstSegmentSize; + + /** + Scales the radial spacing in the glass fracture pattern. A larger value results in radially longer shards. + */ + float segmentScale; + + /** + Creates variance in the radial size of shards. A value of zero results in a low noise circular pattern. + */ + float segmentRand; + }glass; ///< Instance of FractureGlass parameters + + /** + Fracture attachment + */ + struct FractureAttachment + { + /** + If true, make the positive x side of the sheet an attachment point. + */ + bool posX; + + /** + If true, make the negative x side of the sheet an attachment point. + */ + bool negX; + + /** + If true, make the positive y side of the sheet an attachment point. + */ + bool posY; + + /** + If true, make the negative y side of the sheet an attachment point. + */ + bool negY; + + /** + If true, make the positive z side of the sheet an attachment point. + */ + bool posZ; + + /** + If true, make the negative z side of the sheet an attachment point. + */ + bool negZ; + }attachment; ///< Instance of FractureAttachment parameters + + /** + Set default fracture parameters + */ + PX_INLINE void setToDefault(); +}; + +PX_INLINE void DestructibleRTFractureParameters::setToDefault() +{ + sheetFracture = true; + depthLimit = 2; + destroyIfAtDepthLimit = false; + minConvexSize = 0.02f; + impulseScale = 1.0f; + glass.numSectors = 10; + glass.sectorRand = 0.3f; + glass.firstSegmentSize = 0.06f; + glass.segmentScale = 1.4f; + glass.segmentRand = 0.3f; + attachment.posX = false; + attachment.negX = false; + attachment.posY = false; + attachment.negY = false; + attachment.posZ = false; + attachment.negZ = false; +} + +/** + Flags that apply to a destructible actor, settable at runtime +*/ +struct DestructibleParametersFlag +{ + /** + Enum of destructible parameters flag + */ + enum Enum + { + /** + If set, chunks will "remember" damage applied to them, so that many applications of a damage amount + below damageThreshold will eventually fracture the chunk. If not set, a single application of + damage must exceed damageThreshold in order to fracture the chunk. + */ + ACCUMULATE_DAMAGE = (1 << 0), + + /** + Whether or not chunks at or deeper than the "debris" depth (see DestructibleParameters::debrisDepth) + will time out. The lifetime is a value between DestructibleParameters::debrisLifetimeMin and + DestructibleParameters::debrisLifetimeMax, based upon the destructible module's LOD setting. + */ + DEBRIS_TIMEOUT = (1 << 1), + + /** + Whether or not chunks at or deeper than the "debris" depth (see DestructibleParameters::debrisDepth) + will be removed if they separate too far from their origins. The maxSeparation is a value between + DestructibleParameters::debrisMaxSeparationMin and DestructibleParameters::debrisMaxSeparationMax, + based upon the destructible module's LOD setting. + */ + DEBRIS_MAX_SEPARATION = (1 << 2), + + /** + If set, the smallest chunks may be further broken down, either by fluid crumbles (if a crumble particle + system is specified in the DestructibleActorDesc), or by simply removing the chunk if no crumble + particle system is specified. Note: the "smallest chunks" are normally defined to be the deepest level + of the fracture hierarchy. However, they may be taken from higher levels of the hierarchy if + ModuleDestructible::setMaxChunkDepthOffset is called with a non-zero value. + */ + CRUMBLE_SMALLEST_CHUNKS = (1 << 3), + + /** + If set, the DestructibleActor::rayCast function will search within the nearest visible chunk hit + for collisions with child chunks. This is used to get a better raycast position and normal, in + case the parent collision volume does not tightly fit the graphics mesh. The returned chunk index + will always be that of the visible parent that is intersected, however. + */ + ACCURATE_RAYCASTS = (1 << 4), + + /** + If set, the validBounds field of DestructibleParameters will be used. These bounds are translated + (but not scaled or rotated) to the origin of the destructible actor. If a chunk or chunk island moves + outside of those bounds, it is destroyed. + */ + USE_VALID_BOUNDS = (1 << 5), + + /** + If set, chunk crumbling will be handled via the pattern-based runtime fracture pipeline. + If no fracture pattern is specified in the DestructibleActorDesc, or no fracture pattern + has been assigned to the destructible actor, chunks will simply be removed. + */ + CRUMBLE_VIA_RUNTIME_FRACTURE = (1 << 6), + }; +}; + + +/** + Parameters that apply to a destructible actor +*/ +struct DestructibleParameters +{ + /** + \brief constructor sets to default. + */ + PX_INLINE DestructibleParameters(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + Limits the amount of damage applied to a chunk. This is useful for preventing the entire destructible + from getting pulverized by a very large application of damage. This can easily happen when impact damage is + used, and the damage amount is proportional to the impact force (see forceToDamage). + */ + float damageCap; + + /** + If a chunk is at a depth which takes impact damage (see DestructibleDepthParameters), + then when a chunk has a collision in the PxScene, it will take damage equal to forceToDamage mulitplied by + the impact force. + The default value is zero, which effectively disables impact damage. + */ + float forceToDamage; + + /** + Large impact force may be reported if rigid bodies are spawned inside one another. In this case the relative velocity of the two + objects will be low. This variable allows the user to set a minimum velocity threshold for impacts to ensure that the objects are + moving at a min velocity in order for the impact force to be considered. + Default value is zero. + */ + float impactVelocityThreshold; + + /** + The chunks will not be broken free below this depth. + */ + uint32_t minimumFractureDepth; + + /** + The default depth to which chunks will take impact damage. This default may be overridden in the depth settings. + Negative values imply no default impact damage. + Default value = -1. + */ + int32_t impactDamageDefaultDepth; + + /** + The chunk hierarchy depth at which chunks are considered to be "debris." Chunks at this depth or + below will be considered for various debris settings, such as debrisLifetime. + Negative values indicate that no chunk depth is considered debris. + Default value is -1. + */ + int32_t debrisDepth; + + /** + The chunk hierarchy depth up to which chunks will not be eliminated due to LOD considerations. + These chunks are considered to be essential either for gameplay or visually. + The minimum value is 0, meaning the level 0 chunk is always considered essential. + Default value is 0. + */ + uint32_t essentialDepth; + + /** + "Debris chunks" (see debrisDepth, above) will be destroyed after a time (in seconds) + separated from non-debris chunks. The actual lifetime is interpolated between these + two values, based upon the module's LOD setting. To disable lifetime, clear the + DestructibleDepthParametersFlag::DEBRIS_TIMEOUT flag in the flags field. + If debrisLifetimeMax < debrisLifetimeMin, the mean of the two is used for both. + Default debrisLifetimeMin = 1.0, debrisLifetimeMax = 10.0f. + */ + float debrisLifetimeMin; + + /// \see DestructibleAsset::debrisLifetimeMin + float debrisLifetimeMax; + + /** + "Debris chunks" (see debrisDepth, above) will be destroyed if they are separated from + their origin by a distance greater than maxSeparation. The actual maxSeparation is + interpolated between these two values, based upon the module's LOD setting. To disable + maxSeparation, clear the DestructibleDepthParametersFlag::DEBRIS_MAX_SEPARATION flag in the flags field. + If debrisMaxSeparationMax < debrisMaxSeparationMin, the mean of the two is used for both. + Default debrisMaxSeparationMin = 1.0, debrisMaxSeparationMax = 10.0f. + */ + float debrisMaxSeparationMin; + + /// \see DestructibleAsset::debrisMaxSeparationMin + float debrisMaxSeparationMax; + + /** + The probablity that a debris chunk, when fractured, will simply be destroyed instead of becoming + dynamic or breaking down further into child chunks. Valid range = [0.0,1.0]. Default value = 0.0.' + */ + + float debrisDestructionProbability; + + /** + A bounding box around each DestructibleActor created, defining a range of validity for chunks that break free. + These bounds are scaled and translated with the DestructibleActor's scale and position, but they are *not* + rotated with the DestructibleActor. + */ + PxBounds3 validBounds; + + /** + If greater than 0, the chunks' speeds will not be allowed to exceed maxChunkSpeed. Use 0 + to disable this feature (this is the default). + */ + float maxChunkSpeed; + + /** + A collection of flags defined in DestructibleParametersFlag. + */ + uint32_t flags; + + /** + Scale factor used to apply an impulse force along the normal of chunk when fractured. This is used + in order to "push" the pieces out as they fracture. + */ + float fractureImpulseScale; + + /** + How deep in the hierarchy damage will be propagated, relative to the chunk hit. + Default = UINT16_MAX. + */ + uint16_t damageDepthLimit; + + /** + Optional dominance group for dynamic chunks created when fractured. (ignored if > 31) + */ + uint8_t dynamicChunksDominanceGroup; + + /** + Whether or not to use dynamicChunksGroupsMask. If false, NULL will be passed into the DestructibleActor upon + instantiation, through the DestructibleActorDesc. + */ + bool useDynamicChunksGroupsMask; + +#if PX_PHYSICS_VERSION_MAJOR == 3 + /** + Optional groups mask (2.x) or filter data (3.x) for dynamic chunks created when fractured. (Used if useDynamicChunksGroupsMask is true.) + */ + physx::PxFilterData dynamicChunksFilterData; +#endif + + /** + The supportStrength is used for the stress solver. As this value is increased it takes more force to break apart the chunks under the effect of stress solver. + */ + float supportStrength; + + /** + Whether or not to use the old chunk bounds testing for damage, or use the module setting. A value of 0 forces the new method to be used. + A positive value forces the old method to be used. Negative values cause the global (ModuleDestructible) setting to be used. + Default = -1 + */ + int8_t legacyChunkBoundsTestSetting; + + /** + Whether or not to use the old damage spread method, or use the module setting. A value of 0 forces the new method to be used. + A positive value forces the old method to be used. Negative values cause the global (ModuleDestructible) setting to be used. + Default = -1 + */ + int8_t legacyDamageRadiusSpreadSetting; + + /** + The maximum number of DestructibleDepthParameters (see depthParameters). + */ + enum { kDepthParametersCountMax = 16 }; + + /** + The number of DestructibleDepthParameters (see depthParameters). + Must be in the range [0, kDepthParametersCountMax]. + */ + uint32_t depthParametersCount; + + /** + Parameters that apply to every chunk at a given depth level (see DestructibleDepthParameters). + The element [0] of the array applies to the depth 0 (unfractured) chunk, element [1] applies + to the level 1 chunks, etc. + The number of valid depth parameters must be given in depthParametersCount. + */ + DestructibleDepthParameters depthParameters[kDepthParametersCountMax]; + + /** + Parameters for RT Fracture. + */ + DestructibleRTFractureParameters rtFractureParameters; + + /** + This flag forces drawing of scatter mesh on chunks with depth > 1. + By default is false. + */ + bool alwaysDrawScatterMesh; +}; + +// DestructibleParameters inline functions + +PX_INLINE DestructibleParameters::DestructibleParameters() +{ + setToDefault(); +} + +PX_INLINE void DestructibleParameters::setToDefault() +{ + damageCap = 0; + forceToDamage = 0; + impactVelocityThreshold = 0.0f; + minimumFractureDepth = 0; + impactDamageDefaultDepth = -1; + debrisDepth = -1; + essentialDepth = 0; + debrisLifetimeMin = 1.0f; + debrisLifetimeMax = 10.0f; + debrisMaxSeparationMin = 1.0f; + debrisMaxSeparationMax = 10.0f; + debrisDestructionProbability = 0.0f; + validBounds = PxBounds3(PxVec3(-10000.0f), PxVec3(10000.0f)); + maxChunkSpeed = 0.0f; + fractureImpulseScale = 0.0f; + damageDepthLimit = UINT16_MAX; + useDynamicChunksGroupsMask = false; +#if PX_PHYSICS_VERSION_MAJOR == 3 + dynamicChunksFilterData.word0 = dynamicChunksFilterData.word1 = dynamicChunksFilterData.word2 = dynamicChunksFilterData.word3 = 0; +#endif + supportStrength = -1.0; + legacyChunkBoundsTestSetting = -1; + legacyDamageRadiusSpreadSetting = -1; + dynamicChunksDominanceGroup = 0xFF; // Out of range, so it won't be used. + flags = DestructibleParametersFlag::ACCUMULATE_DAMAGE; + depthParametersCount = 0; + rtFractureParameters.setToDefault(); + alwaysDrawScatterMesh = false; +} + +/** + Flags that apply to a destructible actor when it created +*/ +struct DestructibleInitParametersFlag +{ + /** + Enum of destructible init parameters flag + */ + enum Enum + { + /** + If set, then chunks which are tagged as "support" chunks (via DestructibleChunkDesc::isSupportChunk) + will have environmental support in static destructibles. + Note: if both ASSET_DEFINED_SUPPORT and WORLD_SUPPORT are set, then chunks must be tagged as + "support" chunks AND overlap the PxScene's static geometry in order to be environmentally supported. + */ + ASSET_DEFINED_SUPPORT = (1 << 0), + + /** + If set, then chunks which overlap the PxScene's static geometry will have environmental support in + static destructibles. + Note: if both ASSET_DEFINED_SUPPORT and WORLD_SUPPORT are set, then chunks must be tagged as + "support" chunks AND overlap the PxScene's static geometry in order to be environmentally supported. + */ + WORLD_SUPPORT = (1 << 1), + + /** + If this is set and the destructible is initially static, it will become part of an extended support + structure if it is in contact with another static destructible that also has this flag set. + */ + FORM_EXTENDED_STRUCTURES = (1 << 2) + }; +}; + +/** + Parameters that apply to a destructible actor at initialization +*/ +struct DestructibleInitParameters +{ + /** + \brief constructor sets to default. + */ + PX_INLINE DestructibleInitParameters(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + The chunk hierarchy depth at which to create a support graph. Higher depth levels give more detailed support, + but will give a higher computational load. Chunks below the support depth will never be supported. + */ + uint32_t supportDepth; + + /** + A collection of flags defined in DestructibleInitParametersFlag. + */ + uint32_t flags; +}; + + +// DestructibleInitParameters inline functions + +PX_INLINE DestructibleInitParameters::DestructibleInitParameters() +{ + setToDefault(); +} + +PX_INLINE void DestructibleInitParameters::setToDefault() +{ + supportDepth = 0; + flags = 0; +} + +/** + DamageSpreadFunction +*/ +struct DamageSpreadFunction +{ + PX_INLINE DamageSpreadFunction() + { + setToDefault(); + } + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault() + { + minimumRadius = 0.0f; + radiusMultiplier = 1.0f; + falloffExponent = 1.0f; + } + + /** + Returns true iff an object can be created using this descriptor. + */ + PX_INLINE bool isValid() const + { + return + minimumRadius >= 0.0f && + radiusMultiplier >= 0.0f && + falloffExponent >= 0.0f; + } + + float minimumRadius; ///< minimum radius + float radiusMultiplier; ///< radius multiplier + float falloffExponent; ///< falloff exponent +}; + +/** + Destructible authoring structure. + + Descriptor to build one chunk in a fracture hierarchy. +*/ +class DestructibleBehaviorGroupDesc : public ApexDesc +{ +public: + /** + \brief constructor sets to default. + */ + PX_INLINE DestructibleBehaviorGroupDesc(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + Returns true iff an object can be created using this descriptor. + */ + PX_INLINE bool isValid() const; + + /** + Defines the chunk to be environmentally supported, if the appropriate DestructibleParametersFlag flags + are set in DestructibleParameters. + */ + const char* name; ///< name + float damageThreshold; ///< damage threshold + float damageToRadius; ///< damage to radius + DamageSpreadFunction damageSpread; ///< damage spread + DamageSpreadFunction damageColorSpread; ///< damage color spread + PxVec4 damageColorChange; ///< damege color change + float materialStrength; ///< material strength + float density; ///< density + float fadeOut; ///< fade out + float maxDepenetrationVelocity; ///< maximal depenetration velocity + uint64_t userData; ///< user data +}; + +// DestructibleChunkDesc inline functions + +PX_INLINE DestructibleBehaviorGroupDesc::DestructibleBehaviorGroupDesc() +{ + setToDefault(); +} + +PX_INLINE void DestructibleBehaviorGroupDesc::setToDefault() +{ + ApexDesc::setToDefault(); + + // TC_TODO: suitable default values? + name = NULL; + damageThreshold = 1.0f; + damageToRadius = 0.1f; + damageSpread.setToDefault(); + damageColorSpread.setToDefault(); + damageColorChange.setZero(); + materialStrength = 0.0f; + density = 0; + fadeOut = 1; + maxDepenetrationVelocity = PX_MAX_F32; + userData = (uint64_t)0; +} + +PX_INLINE bool DestructibleBehaviorGroupDesc::isValid() const +{ + // TC_TODO: this good enough? + if (damageThreshold < 0 || + damageToRadius < 0 || + !damageSpread.isValid() || + !damageColorSpread.isValid() || + materialStrength < 0 || + density < 0 || + fadeOut < 0 || + !(maxDepenetrationVelocity > 0.f)) + { + return false; + } + + return ApexDesc::isValid(); +} +/** + Destructible authoring structure. + + Descriptor to build one chunk in a fracture hierarchy. +*/ +class DestructibleChunkDesc : public ApexDesc +{ +public: + /** + \brief constructor sets to default. + */ + PX_INLINE DestructibleChunkDesc(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + Returns true iff an object can be created using this descriptor. + */ + PX_INLINE bool isValid() const; + + /** + Defines the chunk to be environmentally supported, if the appropriate DestructibleParametersFlag flags + are set in DestructibleParameters. + */ + bool isSupportChunk; + + /** + Defines the chunk to be unfractureable. If this is true, then none of its children will be fractureable. + */ + bool doNotFracture; + + /** + Defines the chunk to be undamageable. This means this chunk will not fracture, but its children might. + */ + bool doNotDamage; + + /** + Defines the chunk to be uncrumbleable. This means this chunk will not be broken down into fluid mesh particles + no matter how much damage it takes. Note: this only applies to chunks with no children. For a chunk with + children, then: + 1) The chunk may be broken down into its children, and then its children may be crumbled, if the doNotCrumble flag + is not set on them. + 2) If the Destructible module's chunk depth offset LOD may be set such that this chunk effectively has no children. + In this case, the doNotCrumble flag will apply to it. + */ + bool doNotCrumble; + +#if APEX_RUNTIME_FRACTURE + /** + Defines the chunk to use run-time, dynamic fracturing. The chunk will use the fracture pattern provided by the asset + to guide it's fracture. The resulting chunks will follow a similar process for subdivision. + */ + bool runtimeFracture; +#endif + + /** + Whether or not to use instancing when rendering this chunk. If useInstancedRendering = TRUE, this chunk will + share a draw call with all others that instance the mesh indexed by meshIndex. This may extend to other + destructible actors created from this asset. If useInstancedRendering = FALSE, this chunk may share a draw + call only with other chunks in this asset which have useInstancedRendering = FALSE. + Default = FALSE. + */ + bool useInstancedRendering; + + /** + Translation for this chunk mesh within the asset. Normally a chunk needs no translation, but if a chunk is instanced within + the asset, then this translation is needed. + Default = (0,0,0). + */ + PxVec3 instancePositionOffset; + + /** + UV translation for this chunk mesh within the asset. Normally a chunk needs no UV translation, but if a chunk is instanced within + the asset, then this translation is usually needed. + Default = (0,0). + */ + PxVec2 instanceUVOffset; + + /** + If useInstancedRendering = TRUE, this index is the instanced mesh index. If useInstancedRendering = FALSE, + this index is the mesh part index for the skinned or statically rendered mesh. + This must index a valid DestructibleGeometryDesc (see below). + Default = 0xFFFF (invalid). + */ + uint16_t meshIndex; + + /** + The parent index of this chunk. If the index is negative, this is a root chunk. + Default = -1. + */ + int32_t parentIndex; + + /** + A direction used to move the chunk out of the destructible, if an impact kick is applied. + */ + PxVec3 surfaceNormal; + + /** + Referring to the behavior group used of this chunk, please check DestructibleAssetCookingDesc::behaviorGroupDescs for more detail. + */ + int8_t behaviorGroupIndex; + + /** + The number of scatter mesh instances on this chunk. + Default = 0. + */ + uint32_t scatterMeshCount; + + /** + Array of indices corresponding the scatter mesh assets set using DestructibleAssetAuthoring::setScatterMeshAssets(). + The array length must be at least scatterMeshCount. This pointer may be NULL if scatterMeshCount = 0. + Default = NULL. + */ + const uint8_t* scatterMeshIndices; + + /** + Array of chunk-relative transforms corresponding the scatter mesh assets set using + DestructibleAssetAuthoring::setScatterMeshAssets(). + The array length must be at least scatterMeshCount. This pointer may be NULL if scatterMeshCount = 0. + Default = NULL. + */ + const PxMat44* scatterMeshTransforms; +}; + +// DestructibleChunkDesc inline functions + +PX_INLINE DestructibleChunkDesc::DestructibleChunkDesc() +{ + setToDefault(); +} + +PX_INLINE void DestructibleChunkDesc::setToDefault() +{ + ApexDesc::setToDefault(); + isSupportChunk = false; + doNotFracture = false; + doNotDamage = false; + doNotCrumble = false; +#if APEX_RUNTIME_FRACTURE + runtimeFracture = false; +#endif + useInstancedRendering = false; + instancePositionOffset = PxVec3(0.0f); + instanceUVOffset = PxVec2(0.0f); + meshIndex = 0xFFFF; + parentIndex = -1; + surfaceNormal = PxVec3(0.0f); + behaviorGroupIndex = -1; + scatterMeshCount = 0; + scatterMeshIndices = NULL; + scatterMeshTransforms = NULL; +} + +PX_INLINE bool DestructibleChunkDesc::isValid() const +{ + if (meshIndex == 0xFFFF) + { + return false; + } + + return ApexDesc::isValid(); +} + + +/** + Destructible authoring structure. + + Descriptor to build one chunk in a fracture hierarchy. +*/ +class DestructibleGeometryDesc : public ApexDesc +{ +public: + /** + \brief constructor sets to default. + */ + PX_INLINE DestructibleGeometryDesc(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + Returns true iff an object can be created using this descriptor. + */ + PX_INLINE bool isValid() const; + + /** + The convex hulls associated with this chunk. These may be obtained from ExplicitHierarchicalMesh::convexHulls() + if authoring using an ExplicitHierarchicalMesh. The length of the array is given by convexHullCount. + */ + const nvidia::ExplicitHierarchicalMesh::ConvexHull** convexHulls; + + /** + The length of the convexHulls array. If this is positive, then convexHulls must point to a valid array of this size. + If this is zero, then collisionVolumeDesc must not be NULL, and convex hulls will be automatically created for this + geometry using collisionVolumeDesc. + */ + uint32_t convexHullCount; + + /** + If convexHullCount = 0, then collisionVolumeDesc must not be NULL. In this case convex hulls will automatically be + created for this geometry. See CollisionVolumeDesc. + */ + const CollisionVolumeDesc* collisionVolumeDesc; +}; + +// DestructibleGeometryDesc inline functions + +PX_INLINE DestructibleGeometryDesc::DestructibleGeometryDesc() +{ + setToDefault(); +} + +PX_INLINE void DestructibleGeometryDesc::setToDefault() +{ + ApexDesc::setToDefault(); + convexHulls = NULL; + convexHullCount = 0; + collisionVolumeDesc = NULL; +} + +PX_INLINE bool DestructibleGeometryDesc::isValid() const +{ + if (convexHullCount == 0 && collisionVolumeDesc == NULL) + { + return false; + } + + if (convexHullCount > 0 && convexHulls == NULL) + { + return false; + } + + return ApexDesc::isValid(); +} + + +/** + Destructible authoring structure. + + Descriptor for the cookChunk() method of DestructibleAssetAuthoring +*/ +class DestructibleAssetCookingDesc : public ApexDesc +{ +public: + /** + \brief constructor sets to default. + */ + PX_INLINE DestructibleAssetCookingDesc(); + + /** + \brief (re)sets the structure to the default. + */ + PX_INLINE void setToDefault(); + + /** + Returns true iff an object can be created using this descriptor. + */ + PX_INLINE bool isValid() const; + + /** + Beginning of array of descriptors, one for each chunk. + */ + DestructibleChunkDesc* chunkDescs; + + /** + The size of the chunkDescs array. This must be positive. + */ + uint32_t chunkDescCount; + + /** + Default behavior group (corresponds to index of -1). + */ + DestructibleBehaviorGroupDesc defaultBehaviorGroupDesc; + + /** + Beginning of array of descriptors, one for each behavior group. + */ + DestructibleBehaviorGroupDesc* behaviorGroupDescs; + + /** + The size of the behaviorGroupDescs array. This must be positive. + */ + uint32_t behaviorGroupDescCount; + + /** + RT fracture behavior group + */ + int8_t RTFractureBehaviorGroup; + + /** + Beginning of array of descriptors, one for each mesh part. + */ + DestructibleGeometryDesc* geometryDescs; + + /** + The size of the geometryDescs array. This must be positive. + */ + uint32_t geometryDescCount; + + /** + Index pairs that represent chunk connections in the support graph. + The indices refer to the chunkDescs array. Only sibling chunks, + i.e. chunks at equal depth may be connected. + */ + nvidia::IntPair* supportGraphEdges; + + /** + Number of index pairs in supportGraphEdges. + */ + uint32_t supportGraphEdgeCount; +}; + +// DestructibleAssetCookingDesc inline functions + +PX_INLINE DestructibleAssetCookingDesc::DestructibleAssetCookingDesc() +{ + setToDefault(); +} + +PX_INLINE void DestructibleAssetCookingDesc::setToDefault() +{ + ApexDesc::setToDefault(); + chunkDescs = NULL; + chunkDescCount = 0; + geometryDescs = NULL; + geometryDescCount = 0; + behaviorGroupDescs = 0; + behaviorGroupDescCount = 0; + supportGraphEdges = 0; + supportGraphEdgeCount = 0; +} + +PX_INLINE bool DestructibleAssetCookingDesc::isValid() const +{ + if (chunkDescCount == 0 || chunkDescs == NULL) + { + return false; + } + + for (uint32_t i = 0; i < chunkDescCount; ++i ) + { + if (!chunkDescs[i].isValid()) + { + return false; + } + } + + if (chunkDescCount >= 65535) + { + return false; + } + + if (geometryDescCount == 0 || geometryDescs == NULL) + { + return false; + } + + for (uint32_t i = 0; i < geometryDescCount; ++i ) + { + if (!geometryDescs[i].isValid()) + { + return false; + } + } + + if (behaviorGroupDescCount > 127) + { + return false; + } + + for (uint32_t i = 0; i < behaviorGroupDescCount; ++i ) + { + if (!behaviorGroupDescs[i].isValid()) + { + return false; + } + } + + return ApexDesc::isValid(); +} + + +/** + Stats for an DestructibleAsset: memory usage, counts, etc. +*/ +struct DestructibleAssetStats +{ + uint32_t totalBytes; ///< total bytes + uint32_t chunkCount; ///< chunk count + uint32_t chunkBytes; ///< chunk bytes + uint32_t chunkHullDataBytes; ///< chunk hull data bytes + uint32_t collisionCookedHullDataBytes; ///< collision cooked hull data bytes + uint32_t collisionMeshCount; ///< collision mesh count + uint32_t maxHullVertexCount; ///< max hull vertex count + uint32_t maxHullFaceCount; ///< max hull face count + uint32_t chunkWithMaxEdgeCount; ///< chunk with max edge count + uint32_t runtimeCookedConvexCount; ///< runtime cooked convex count + RenderMeshAssetStats renderMeshAssetStats; ///< render mesh asset stats +}; + +/** + Authoring API for a destructible asset. +*/ +class DestructibleAssetAuthoring : public AssetAuthoring +{ +public: + + /** Fracturing API */ + + /** + DestructibleAssetAuthoring contains an instantiation of ExplicitHierarchicalMesh. + This function gives access to it. See ExplicitHierarchicalMesh for details, it is + the object used by the fracturing tool set for mesh fracturing operations and is used + to generate the embedded RenderMesh as well as collision and hierarchy data + for the destructible asset. + */ + virtual ExplicitHierarchicalMesh& getExplicitHierarchicalMesh() = 0; + + /** + DestructibleAssetAuthoring contains a second instantiation of ExplicitHierarchicalMesh + used to describe the core mesh for slice fracturing (see FractureTools::FractureSliceDesc), + done in createHierarchicallySplitMesh(). This function gives access to it. + */ + virtual ExplicitHierarchicalMesh& getCoreExplicitHierarchicalMesh() = 0; + + /** + DestructibleAssetAuthoring contains an instantiation of CutoutSet used to describe the + cutout fracturing shapes (see FractureTools::CutoutSet), done in createChippedMesh(). + This function gives access to it. + */ + virtual FractureTools::CutoutSet& getCutoutSet() = 0; + + /** + Partitions (and possibly re-orders) the mesh array if the triangles form disjoint islands. + + \param mesh pointer to array of ExplicitRenderTriangles which make up the mesh + \param meshTriangleCount the size of the meshTriangles array + \param meshPartition user-allocated array for mesh partition, will be filled with the end elements of contiguous subsets of meshTriangles. + \param meshPartitionMaxCount size of user-allocated meshPartitionArray + \param padding relative value multiplied by the mesh bounding box. padding gets added to the triangle bounds when calculating triangle neighbors. + + \return Returns the number of partitions. The value may be larger than meshPartitionMaxCount. In that case, the partitions beyond meshPartitionMaxCount are not recorded. + */ + virtual uint32_t partitionMeshByIslands + ( + nvidia::ExplicitRenderTriangle* mesh, + uint32_t meshTriangleCount, + uint32_t* meshPartition, + uint32_t meshPartitionMaxCount, + float padding = 0.0001f + ) = 0; + + /** + Builds a new ExplicitHierarchicalMesh from an array of triangles, used as the starting + point for fracturing. It will contain only one chunk, at depth 0. + + \param meshTriangles pointer to array of ExplicitRenderTriangles which make up the mesh + \param meshTriangleCount the size of the meshTriangles array + \param submeshData pointer to array of ExplicitSubmeshData, describing the submeshes + \param submeshCount the size of the submeshData array + \param meshPartition if not NULL, an array of size meshPartitionCount, giving the end elements of contiguous subsets of meshTriangles. + If meshPartition is NULL, one partition is assumed. + When there is one partition, these triangles become the level 0 part. + When there is more than one partition, the behavior is determined by firstPartitionIsDepthZero (see below). + \param meshPartitionCount if meshPartition is not NULL, this is the size of the meshPartition array. + \param parentIndices if not NULL, the parent indices for each chunk (corresponding to a partition in the mesh partition). + \param parentIndexCount the size of the parentIndices array. This does not need to match meshPartitionCount. If a mesh partition has an index beyond the end of parentIndices, + then the parentIndex is considered to be 0. Therefore, if parentIndexCount = 0, all parents are 0 and so all chunks created will be depth 1. This will cause a + depth 0 chunk to be created that is the aggregate of the depth 1 chunks. If parentIndexCount > 0, then the depth-0 chunk must have a parentIndex of -1. + To reproduce the effect of the old parameter 'firstPartitionIsDepthZero' = true, set parentIndices to the address of a int32_t containing the value -1, and set parentIndexCount = 1. + To reproduce the effect of the old parameter 'firstPartitionIsDepthZero' = false, set parentIndexCount = 0. + Note: if parent indices are given, the first one must be -1, and *only* that index may be negative. That is, there may be only one depth-0 mesh and it must be the first mesh. + */ + virtual bool setRootMesh + ( + const ExplicitRenderTriangle* meshTriangles, + uint32_t meshTriangleCount, + const ExplicitSubmeshData* submeshData, + uint32_t submeshCount, + uint32_t* meshPartition = NULL, + uint32_t meshPartitionCount = 0, + int32_t* parentIndices = NULL, + uint32_t parentIndexCount = 0 + ) = 0; + + /** + Builds the root ExplicitHierarchicalMesh from an RenderMeshAsset. + Since an DestructibleAsset contains no hierarchy information, the input mesh must have only one part. + + \param renderMeshAsset the asset to import + \param maxRootDepth cap the root depth at this value. Re-fracturing of the mesh will occur at this depth. Default = UINT32_MAX + */ + virtual bool importRenderMeshAssetToRootMesh(const nvidia::RenderMeshAsset& renderMeshAsset, uint32_t maxRootDepth = UINT32_MAX) = 0; + + /** + Builds the root ExplicitHierarchicalMesh from an DestructibleAsset. + Since an DestructibleAsset contains hierarchy information, the explicit mesh formed + will have this hierarchy structure. + + \param destructibleAsset the asset to import + \param maxRootDepth cap the root depth at this value. Re-fracturing of the mesh will occur at this depth. Default = UINT32_MAX + */ + virtual bool importDestructibleAssetToRootMesh(const nvidia::DestructibleAsset& destructibleAsset, uint32_t maxRootDepth = UINT32_MAX) = 0; + + /** + Builds a new ExplicitHierarchicalMesh from an array of triangles, used as the core mesh + for slice fracture operations (see FractureTools::FractureSliceDesc, passed into + createHierarchicallySplitMesh). + + \param mesh pointer to array of ExplicitRenderTriangles which make up the mesh + \param meshTriangleCount the size of the meshTriangles array + \param submeshData pointer to array of ExplicitSubmeshData, describing the submeshes + \param submeshCount the size of the submeshData array + \param meshPartition meshPartition array + \param meshPartitionCount meshPartition array size + */ + virtual bool setCoreMesh + ( + const ExplicitRenderTriangle* mesh, + uint32_t meshTriangleCount, + const ExplicitSubmeshData* submeshData, + uint32_t submeshCount, + uint32_t* meshPartition = NULL, + uint32_t meshPartitionCount = 0 + ) = 0; + + /** + Builds a new ExplicitHierarchicalMesh from an array of triangles, externally provided by the user. + Note: setRootMesh and setCoreMesh may be implemented as follows: + setRootMesh(x) <-> buildExplicitHierarchicalMesh( getExplicitHierarchicalMesh(), x) + setCoreMesh(x) <-> buildExplicitHierarchicalMesh( getCoreExplicitHierarchicalMesh(), x) + + \param hMesh new ExplicitHierarchicalMesh + \param meshTriangles pointer to array of ExplicitRenderTriangles which make up the mesh + \param meshTriangleCount the size of the meshTriangles array + \param submeshData pointer to array of ExplicitSubmeshData, describing the submeshes + \param submeshCount the size of the submeshData array + \param meshPartition if not NULL, an array of size meshPartitionCount, giving the end elements of contiguous subsets of meshTriangles. + If meshPartition is NULL, one partition is assumed. + When there is one partition, these triangles become the level 0 part. + When there is more than one partition, these triangles become level 1 parts, while the union of the parts will be the level 0 part. + \param meshPartitionCount if meshPartition is not NULL, this is the size of the meshPartition array. + \param parentIndices if not NULL, the parent indices for each chunk (corresponding to a partition in the mesh partition). + \param parentIndexCount the size of the parentIndices array. This does not need to match meshPartitionCount. If a mesh partition has an index beyond the end of parentIndices, + then the parentIndex is considered to be 0. Therefore, if parentIndexCount = 0, all parents are 0 and so all chunks created will be depth 1. This will cause a + depth 0 chunk to be created that is the aggregate of the depth 1 chunks. If parentIndexCount > 0, then the depth-0 chunk must have a parentIndex of -1. + To reproduce the effect of the old parameter 'firstPartitionIsDepthZero' = true, set parentIndices to the address of a int32_t containing the value -1, and set parentIndexCount = 1. + To reproduce the effect of the old parameter 'firstPartitionIsDepthZero' = false, set parentIndexCount = 0. + Note: if parent indices are given, the first one must be -1, and *only* that index may be negative. That is, there may be only one depth-0 mesh and it must be the first mesh. + */ + virtual bool buildExplicitHierarchicalMesh + ( + ExplicitHierarchicalMesh& hMesh, + const ExplicitRenderTriangle* meshTriangles, + uint32_t meshTriangleCount, + const ExplicitSubmeshData* submeshData, + uint32_t submeshCount, + uint32_t* meshPartition = NULL, + uint32_t meshPartitionCount = 0, + int32_t* parentIndices = NULL, + uint32_t parentIndexCount = 0 + ) = 0; + + /** + Splits the chunk in chunk[0], forming a hierarchy of fractured chunks in chunks[1...] using + slice-mode fracturing. + + \param meshProcessingParams describes generic mesh processing directives + \param desc describes the slicing surfaces (see FractureSliceDesc) + \param collisionDesc convex hulls will be generated for each chunk using the method See CollisionDesc. + \param exportCoreMesh if true, the core mesh will be included (at depth 1) in the hierarchically split mesh. Otherwise, it will only be used to create a hollow space. + \param coreMeshImprintSubmeshIndex if this is < 0, use the core mesh materials (was applyCoreMeshMaterialToNeighborChunks). Otherwise, use the given submesh + \param randomSeed seed for the random number generator, to ensure reproducibility. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. Meant to be set from another thread. + + \return returns true if successful. + */ + virtual bool createHierarchicallySplitMesh + ( + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureSliceDesc& desc, + const CollisionDesc& collisionDesc, + bool exportCoreMesh, + int32_t coreMeshImprintSubmeshIndex, + uint32_t randomSeed, + IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Splits the mesh in chunk[0], forming a hierarchy of fractured meshes in chunks[1...] using + cutout-mode (chippable) fracturing. + + \param meshProcessingParams describes generic mesh processing directives + \param desc describes the slicing surfaces (see FractureCutoutDesc) + \param cutoutSet the cutout set to use for fracturing (see CutoutSet) + \param sliceDesc used if desc.chunkFracturingMethod = SliceFractureCutoutChunks + \param voronoiDesc used if desc.chunkFracturingMethod = VoronoiFractureCutoutChunks + \param collisionDesc convex hulls will be generated for each chunk using the method See CollisionDesc. + \param randomSeed seed for the random number generator, to ensure reproducibility. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. Meant to be set from another thread. + + \return returns true if successful. + */ + virtual bool createChippedMesh + ( + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureCutoutDesc& desc, + const FractureTools::CutoutSet& cutoutSet, + const FractureTools::FractureSliceDesc& sliceDesc, + const FractureTools::FractureVoronoiDesc& voronoiDesc, + const CollisionDesc& collisionDesc, + uint32_t randomSeed, + IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Builds an internal cutout set. + + \param pixelBuffer pointer to be beginning of the pixel buffer + \param bufferWidth the width of the buffer in pixels + \param bufferHeight the height of the buffer in pixels + \param snapThreshold the pixel distance at which neighboring cutout vertices and segments may be fudged into alignment. + \param periodic whether or not to use periodic boundary conditions when creating cutouts from the map + */ + virtual void buildCutoutSet + ( + const uint8_t* pixelBuffer, + uint32_t bufferWidth, + uint32_t bufferHeight, + float snapThreshold, + bool periodic + ) = 0; + + /** + Calculate the mapping between a cutout fracture map and a given triangle. + The result is a 3 by 3 matrix M composed by an affine transformation and a rotation, we can get the 3-D projection for a texture coordinate pair (u,v) with such a formula: + (x,y,z) = M*PxVec3(u,v,1) + + \param mapping resulted mapping, composed by an affine transformation and a rotation + \param triangle triangle + **/ + virtual bool calculateCutoutUVMapping + ( + PxMat33& mapping, + const nvidia::ExplicitRenderTriangle& triangle + ) = 0; + + /** + Uses the passed-in target direction to find the best triangle in the root mesh with normal near the given targetDirection. If triangles exist + with normals within one degree of the given target direction, then one with the greatest area of such triangles is used. Otherwise, the triangle + with normal closest to the given target direction is used. The resulting triangle is used to calculate a UV mapping as in the function + calculateCutoutUVMapping (above). + + The assumption is that there exists a single mapping for all triangles on a specified face, for this feature to be useful. + + \param mapping resulted mapping, composed by an affine transformation and a rotation + \param targetDirection: the target face's normal + **/ + virtual bool calculateCutoutUVMapping + ( + PxMat33& mapping, + const PxVec3& targetDirection + ) = 0; + + /** + Splits the mesh in chunk[0], forming fractured pieces chunks[1...] using + Voronoi decomposition fracturing. + + \param meshProcessingParams describes generic mesh processing directives + \param desc describes the voronoi splitting parameters surfaces (see FractureVoronoiDesc) + \param collisionDesc convex hulls will be generated for each chunk using the method See CollisionDesc. + \param exportCoreMesh if true, the core mesh will be included (at depth 1) in the split mesh. Otherwise, it will only be used to create a hollow space. + \param coreMeshImprintSubmeshIndex if this is < 0, use the core mesh materials (was applyCoreMeshMaterialToNeighborChunks). Otherwise, use the given submesh + \param randomSeed seed for the random number generator, to ensure reproducibility. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. Meant to be set from another thread. + + \return returns true if successful. + */ + virtual bool createVoronoiSplitMesh + ( + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureVoronoiDesc& desc, + const CollisionDesc& collisionDesc, + bool exportCoreMesh, + int32_t coreMeshImprintSubmeshIndex, + uint32_t randomSeed, + IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Generates a set of uniformly distributed points in the interior of the root mesh. + + \param siteBuffer An array of PxVec3, at least the size of siteCount. + \param siteChunkIndices If not NULL, it must be at least the size of siteCount. + siteCount indices will be written to this buffer, + associating each site with a chunk that contains it. + \param siteCount The number of points to write into siteBuffer. + \param randomSeed Pointer to a seed for the random number generator, to ensure reproducibility. + If NULL, the random number generator will not be re-seeded. + \param microgridSize Pointer to a grid size used for BSP creation. If NULL, the default settings will be used. + \param meshMode Open mesh handling. Modes: Automatic, Closed, Open (see BSPOpenMode) + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param chunkIndex If this is a valid index, the voronoi sites will only be created within the volume of the indexed chunk. Otherwise, + the sites will be created within each of the root-level chunks. Default value is an invalid index. + + \return Returns the number of sites actually created (written to siteBuffer and siteChunkIndices). + This may be less than the number of sites requested if site placement fails. + */ + virtual uint32_t createVoronoiSitesInsideMesh + ( + PxVec3* siteBuffer, + uint32_t* siteChunkIndices, + uint32_t siteCount, + uint32_t* randomSeed, + uint32_t* microgridSize, + BSPOpenMode::Enum meshMode, + IProgressListener& progressListener, + uint32_t chunkIndex = 0xFFFFFFFF + ) = 0; + + /** + Creates scatter mesh sites randomly distributed on the mesh. + + \param meshIndices user-allocated array of size scatterMeshInstancesBufferSize which will be filled in by this function, giving the scatter mesh index used + \param relativeTransforms user-allocated array of size scatterMeshInstancesBufferSize which will be filled in by this function, giving the chunk-relative transform for each chunk instance + \param chunkMeshStarts user-allocated array which will be filled in with offsets into the meshIndices and relativeTransforms array. + For a chunk indexed by i, the corresponding range [chunkMeshStart[i], chunkMeshStart[i+1]-1] in meshIndices and relativeTransforms is used. + *NOTE*: chunkMeshStart array must be of at least size N+1, where N is the number of chunks in the base explicit hierarchical mesh. + \param scatterMeshInstancesBufferSize the size of meshIndices and relativeTransforms array. + \param targetChunkCount how many chunks are in the array targetChunkIndices + \param targetChunkIndices an array of chunk indices which are candidates for scatter meshes. The elements in the array chunkIndices will come from this array + \param randomSeed pointer to a seed for the random number generator, to ensure reproducibility. If NULL, the random number generator will not be re-seeded. + \param scatterMeshAssetCount the number of different scatter meshes (not instances). Should not exceed 255. If scatterMeshAssetCount > 255, only the first 255 will be used. + \param scatterMeshAssets an array of size scatterMeshAssetCount, of the render mesh assets which will be used for the scatter meshes + \param minCount an array of size scatterMeshAssetCount, giving the minimum number of instances to place for each mesh + \param maxCount an array of size scatterMeshAssetCount, giving the maximum number of instances to place for each mesh + \param minScales an array of size scatterMeshAssetCount, giving the minimum scale to apply to each scatter mesh + \param maxScales an array of size scatterMeshAssetCount, giving the maximum scale to apply to each scatter mesh + \param maxAngles an array of size scatterMeshAssetCount, giving a maximum deviation angle (in degrees) from the surface normal to apply to each scatter mesh + + \return return value: the number of instances placed in indices and relativeTransforms (will not exceed scatterMeshInstancesBufferSize) + */ + virtual uint32_t createScatterMeshSites + ( + uint8_t* meshIndices, + PxMat44* relativeTransforms, + uint32_t* chunkMeshStarts, + uint32_t scatterMeshInstancesBufferSize, + uint32_t targetChunkCount, + const uint16_t* targetChunkIndices, + uint32_t* randomSeed, + uint32_t scatterMeshAssetCount, + nvidia::RenderMeshAsset** scatterMeshAssets, + const uint32_t* minCount, + const uint32_t* maxCount, + const float* minScales, + const float* maxScales, + const float* maxAngles + ) = 0; + + /** + Utility to visualize Voronoi cells for a given set of sites. + + \param debugRender rendering object which will receive the drawing primitives associated with this cell visualization + \param sites an array of Voronoi cell sites, of length siteCount + \param siteCount the number of Voronoi cell sites (length of sites array) + \param cellColors an optional array of colors (see RenderDebug for format) for the cells. If NULL, the white (0xFFFFFFFF) color will be used. + If not NULL, this (of length cellColorCount) is used to color the cell graphics. The number cellColorCount need not match siteCount. If + cellColorCount is less than siteCount, the cell colors will cycle. That is, site N gets cellColor[N%cellColorCount]. + \param cellColorCount the number of cell colors (the length of cellColors array) + \param bounds defines an axis-aligned bounding box which clips the visualization, since some cells extend to infinity + \param cellIndex if this is a valid index (cellIndex < siteCount), then only the cell corresponding to sites[cellIndex] will be drawn. Otherwise, all cells will be drawn. + */ + virtual void visualizeVoronoiCells + ( + nvidia::RenderDebugInterface& debugRender, + const PxVec3* sites, + uint32_t siteCount, + const uint32_t* cellColors, + uint32_t cellColorCount, + const PxBounds3& bounds, + uint32_t cellIndex = 0xFFFFFFFF + ) = 0; + + /** + Splits the chunk in chunk[chunkIndex], forming a hierarchy of fractured chunks using + slice-mode fracturing. The chunks will be rearranged so that they are in breadth-first order. + + \param chunkIndex index of chunk to be split + \param meshProcessingParams describes generic mesh processing directives + \param desc describes the slicing surfaces (see FractureSliceDesc) + \param collisionDesc convex hulls will be generated for each chunk using the method. See CollisionDesc. + \param randomSeed pointer to a seed for the random number generator, to ensure reproducibility. If NULL, the random number generator will not be re-seeded. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. Meant to be set from another thread. + + \return returns true if successful. + */ + virtual bool hierarchicallySplitChunk + ( + uint32_t chunkIndex, + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureSliceDesc& desc, + const CollisionDesc& collisionDesc, + uint32_t* randomSeed, + IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Splits the chunk in chunk[chunkIndex], forming fractured chunks using + Voronoi decomposition fracturing. The chunks will be rearranged so that they are in breadth-first order. + + \param chunkIndex index of chunk to be split + \param meshProcessingParams describes generic mesh processing directives + \param desc describes the voronoi splitting parameters surfaces (see FractureVoronoiDesc) + \param collisionDesc convex hulls will be generated for each chunk using the method. See CollisionDesc. + \param randomSeed pointer to a seed for the random number generator, to ensure reproducibility. If NULL, the random number generator will not be re-seeded. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. Meant to be set from another thread. + + \return returns true if successful. + */ + virtual bool voronoiSplitChunk + ( + uint32_t chunkIndex, + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureVoronoiDesc& desc, + const CollisionDesc& collisionDesc, + uint32_t* randomSeed, + IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Set the tolerances used in CSG calculations. + + \param linearTolerance relative (to mesh size) tolerance used with angularTolerance to determine coplanarity. Default = 1.0e-4. + \param angularTolerance used with linearTolerance to determine coplanarity. Default = 1.0e-3 + \param baseTolerance relative (to mesh size) tolerance used for spatial partitioning + \param clipTolerance relative (to mesh size) tolerance used when clipping triangles for CSG mesh building operations. Default = 1.0e-4. + \param cleaningTolerance relative (to mesh size) tolerance used when cleaning the out put mesh generated from the toMesh() function. Default = 1.0e-7. + */ + virtual void setBSPTolerances + ( + float linearTolerance, + float angularTolerance, + float baseTolerance, + float clipTolerance, + float cleaningTolerance + ) = 0; + + /** + Set the parameters used in BSP building operations. + + \param logAreaSigmaThreshold At each step in the tree building process, the surface with maximum triangle area is compared + to the other surface triangle areas. If the maximum area surface is far from the "typical" set of + surface areas, then that surface is chosen as the next splitting plane. Otherwise, a random + test set is chosen and a winner determined based upon the weightings below. + The value logAreaSigmaThreshold determines how "atypical" the maximum area surface must be to + be chosen in this manner. + Default value = 2.0. + \param testSetSize Larger values of testSetSize may find better BSP trees, but will take more time to create. + testSetSize = 0 is treated as infinity (all surfaces will be tested for each branch). + Default value = 10. + \param splitWeight How much to weigh the relative number of triangle splits when searching for a BSP surface. + Default value = 0.5. + \param imbalanceWeight How much to weigh the relative triangle imbalance when searching for a BSP surface. + Default value = 0.0. + */ + virtual void setBSPBuildParameters + ( + float logAreaSigmaThreshold, + uint32_t testSetSize, + float splitWeight, + float imbalanceWeight + ) = 0; + + + /** + Instantiates an ExplicitHierarchicalMesh::ConvexHull + + See the ConvexHull API for its functionality. Can be used to author chunk hulls in the + cookChunks function. + + Use ConvexHull::release() to delete the object. + */ + virtual ExplicitHierarchicalMesh::ConvexHull* createExplicitHierarchicalMeshConvexHull() = 0; + + /** + Builds a mesh used for slice fracturing, given the noise parameters and random seed. This function is mostly intended + for visualization - to give the user a "typical" slice surface used for fracturing. + + \return Returns the head of an array of ExplicitRenderTriangles, of length given by the return value. + */ + virtual uint32_t buildSliceMesh(const ExplicitRenderTriangle*& mesh, const FractureTools::NoiseParameters& noiseParameters, const PxPlane& slicePlane, uint32_t randomSeed) = 0; + + /** + Serialization of the data associated with the fracture API. This includes + the root mesh, core mesh, and cutout set. + */ + virtual void serializeFractureToolState(PxFileBuf& stream, nvidia::ExplicitHierarchicalMesh::Embedding& embedding) const = 0; + + /** + Deserialization of the data associated with the fracture API. This includes + the root mesh, core mesh, and cutout set. + */ + virtual void deserializeFractureToolState(PxFileBuf& stream, nvidia::ExplicitHierarchicalMesh::Embedding& embedding) = 0; + + /** + Set current depth for chunk overlaps calculations. + */ + virtual void setChunkOverlapsCacheDepth(int32_t depth = -1) = 0; + + /** + Gets the RenderMeshAsset associated with this asset. + */ + virtual const RenderMeshAsset* getRenderMeshAsset() const = 0; + + /** + Set the RenderMeshAsset associated with this asset. + This is the asset used for non-instanced rendering. + NULL is a valid argument, and can be used to clear the internal mesh data. + + \return Returns true if successful. + */ + virtual bool setRenderMeshAsset(RenderMeshAsset*) = 0; + + /** + Set the RenderMeshAssets used for scatter mesh rendering associated with this asset. + These assets will be rendered using instanced rendering. + The array cannot contain NULL elements, if an array size greater than zero is specified. + + \return Returns true if successful. + */ + virtual bool setScatterMeshAssets(RenderMeshAsset** scatterMeshAssetArray, uint32_t scatterMeshAssetArraySize) = 0; + + /** Retrieve the number of scatter mesh assets */ + virtual uint32_t getScatterMeshAssetCount() const = 0; + + /** Retrieve the scatter mesh asset array */ + virtual RenderMeshAsset* const * getScatterMeshAssets() const = 0; + + /** + Get the number of instanced chunk meshes in this asset. + */ + virtual uint32_t getInstancedChunkMeshCount() const = 0; + + /** + Set the parameters used for runtime destruction behavior. See DestructibleParameters. + */ + virtual void setDestructibleParameters(const DestructibleParameters&) = 0; + + /** + The DestructibleParameters which describe the default fracturing behavior for instanced + DestructibleActors. These may be overridden by calling setDestructibleParameters(). + */ + virtual DestructibleParameters getDestructibleParameters() const = 0; + + /** + Set the parameters used for default destructible initialization. See DestructibleInitParameters. + */ + virtual void setDestructibleInitParameters(const DestructibleInitParameters&) = 0; + + /** + The parameters used for default destructible initialization. See DestructibleInitParameters. + */ + virtual DestructibleInitParameters getDestructibleInitParameters() const = 0; + + /** + Set the name of the emitter to use when generating crumble particles. + */ + virtual void setCrumbleEmitterName(const char*) = 0; + + /** + Set the name of the emitter to use when generating fracture-line dust particles. + */ + virtual void setDustEmitterName(const char*) = 0; + + /** + Set the name of the fracture pattern to use when runtime fracture is enabled. + */ + virtual void setFracturePatternName(const char*) = 0; + + /** + Set padding used for chunk neighbor tests. This padding is relative to the largest diagonal + of the asset's local bounding box. + This value must be non-negative. + Default value = 0.001f. + */ + virtual void setNeighborPadding(float neighborPadding) = 0; + + /** + Get padding used for chunk neighbor tests. Set setNeighborPadding(). + */ + virtual float getNeighborPadding() const = 0; + + /** + Once the internal ExplicitHierarchicalMesh is built using the fracture tools functions + and all emitter names and parameters set, this functions builds the destructible asset. + Every chunk (corresponding to a part in the ExplicitHierarchicalMesh) must have + destruction-specific data set through the descriptor passed into this function. See + DestructibleAssetCookingDesc. + + \param cookingDesc cooking setup + \param cacheOverlaps whether the chunk overlaps up to chunkOverlapCacheDepth should be cached in this call + \param chunkIndexMapUser2Apex optional user provided uint32_t array that will contains the mapping from user chunk indices (referring to chunks in cookingDesc) + to Apex internal chunk indices (referring to chunk is internal chunk array) + \param chunkIndexMapApex2User same as chunkIndexMapUser2Apex, but opposite direction + \param chunkIndexMapCount size of the user provided mapping arrays + */ + virtual void cookChunks( const DestructibleAssetCookingDesc& cookingDesc, bool cacheOverlaps = true, + uint32_t* chunkIndexMapUser2Apex = NULL, uint32_t* chunkIndexMapApex2User = NULL, uint32_t chunkIndexMapCount = 0) = 0; + + /** + The scale factor used to apply an impulse force along the normal of chunk when fractured. This is used + in order to "push" the pieces out as they fracture. + */ + virtual float getFractureImpulseScale() const = 0; + + /** + Large impact force may be reported if rigid bodies are spawned inside one another. In this case the realative velocity of the two + objects will be low. This variable allows the user to set a minimum velocity threshold for impacts to ensure that the objects are + moving at a min velocity in order for the impact force to be considered. + */ + virtual float getImpactVelocityThreshold() const = 0; + + /** + The total number of chunks in the cooked asset. + */ + virtual uint32_t getChunkCount() const = 0; + + /** + The total number of fracture hierarchy depth levels in the cooked asset. + */ + virtual uint32_t getDepthCount() const = 0; + + /** + Returns the number of children for the given chunk. + chunkIndex must be less than getChunkCount(). If it is not, this function returns 0. + */ + virtual uint32_t getChunkChildCount(uint32_t chunkIndex) const = 0; + + /** + Returns the index for the given child of the given chunk. + chunkIndex must be less than getChunkCount() and childIndex must be less than getChunkChildCount(chunkIndex). + If either of these conditions is not met, the function returns ModuleDestructibleConst::INVALID_CHUNK_INDEX. + */ + virtual int32_t getChunkChild(uint32_t chunkIndex, uint32_t childIndex) const = 0; + + /** + If this chunk is instanced within the same asset, then this provides the instancing position offset. + Otherwise, this function returns (0,0,0). + */ + virtual PxVec3 getChunkPositionOffset(uint32_t chunkIndex) const = 0; + + /** + If this chunk is instanced within the same asset, then this provides the instancing UV offset. + Otherwise, this function returns (0,0). + */ + virtual PxVec2 getChunkUVOffset(uint32_t chunkIndex) const = 0; + + /** + The render mesh asset part index associated with this chunk. + */ + virtual uint32_t getPartIndex(uint32_t chunkIndex) const = 0; + + /** + Trim collision geometry to prevent explosive behavior. maxTrimFraction is the maximum (relative) distance to trim a hull in the direction + of each trim plane. + + \return Returns true iff successful. + */ + virtual void trimCollisionGeometry(const uint32_t* partIndices, uint32_t partIndexCount, float maxTrimFraction = 0.2f) = 0; + + /** + Returns stats (sizes, counts) for the asset. See DestructibleAssetStats. + */ + virtual void getStats(DestructibleAssetStats& stats) const = 0; + + /** + Ensures that the asset has chunk overlap information cached up to the given depth. + If depth < 0 (as it is by default), the depth will be taken to be the supportDepth + given in the asset's destructibleParameters. + It is ok to pass in a depth greater than any chunk depth in the asset. + */ + virtual void cacheChunkOverlapsUpToDepth(int32_t depth = -1) = 0; + + /** + Clears the chunk overlap cache. + + \param depth Depth to be cleared. -1 for all depths. + \param keepCachedFlag If the flag is set, the depth is considered to be cached even if the overlaps list is empty. + */ + virtual void clearChunkOverlaps(int32_t depth = -1, bool keepCachedFlag = false) = 0; + + /** + Adds edges to the support graph. Edges must connect chunks of equal depth. + The indices refer to the reordered chunk array, a mapping is provided in cookChunks. + */ + virtual void addChunkOverlaps(IntPair* supportGraphEdges, uint32_t numSupportGraphEdges) = 0; + + /** + Removes edges from support graph. + The indices refer to the reordered chunk array, a mapping is provided in cookChunks. + + \param supportGraphEdges Integer pairs representing indices to chunks that are linked + \param numSupportGraphEdges Number of provided integer pairs. + \param keepCachedFlagIfEmpty If the flag is set, the depth is considered to be cached even if the overlaps list is empty. + */ + virtual void removeChunkOverlaps(IntPair* supportGraphEdges, uint32_t numSupportGraphEdges, bool keepCachedFlagIfEmpty) = 0; + + /** + The size of the array returned by getCachedOverlapsAtDepth(depth) (see below). + Note: this function will not trigger overlap caching for the given depth. If no overlaps + have been calculated for the depth given, this function returns NULL. + */ + virtual uint32_t getCachedOverlapCountAtDepth(uint32_t depth) = 0; + + /** + Array of integer pairs, indexing chunk pairs which touch at a given depth in the heirarcy. + The size of the array is given by getCachedOverlapCountAtDepth(depth). + Note: this function will not trigger overlap caching for the given depth. If no overlaps + have been calculated for the depth given, this function returns NULL. + */ + virtual const IntPair* getCachedOverlapsAtDepth(uint32_t depth) = 0; + + /** + \brief Apply a transformation to destructible asset + + This is a permanent transformation and it changes the object state. Should only be called immediately before serialization + and without further modifying the object later on. + + \param transformation This matrix is allowed to contain a translation and a rotation + \param scale Apply a uniform scaling as well + */ + virtual void applyTransformation(const PxMat44& transformation, float scale) = 0; + + /** + \brief Apply an arbitrary affine transformation to destructible asset + + This is a permanent transformation and it changes the object state. Should only be called immediately before serialization + and without further modifying the object later on. + + \param transformation This matrix is allowed to contain translation, rotation, scale and skew + */ + virtual void applyTransformation(const PxMat44& transformation) = 0; + + /** + \brief Set a maximum fracture depth for a given platform string + + Returns true if the supplied maxDepth is lesser than the number of chunk depth levels for this asset + */ + virtual bool setPlatformMaxDepth(PlatformTag platform, uint32_t maxDepth) = 0; + + /** + \brief Removes the maximum fracture depth limit for a given platform string + + Returns true if the platform's maximum fracture depth was previously set and now removed + */ + virtual bool removePlatformMaxDepth(PlatformTag platform) = 0; + + /** + \brief Returns the size of the actor transform array. See getActorTransforms() for a description of this data. + */ + virtual uint32_t getActorTransformCount() const = 0; + + /** + \brief Returns the head of the actor transform array. This list is a convenience for placing actors in a level from poses authored in a level editor. + The transforms may contain scaling. + */ + virtual const PxMat44* getActorTransforms() const = 0; + + /** + \brief Append transforms to the actor transform list. See getActorTransforms() for a description of this data. + + \param transforms Head of an array of transforms + \param transformCount Size of transforms + */ + virtual void appendActorTransforms(const PxMat44* transforms, uint32_t transformCount) = 0; + + /** + \brief Clear the actor transform array. See getActorTransforms() for a description of this data. + */ + virtual void clearActorTransforms() = 0; +}; + +/** + Destructible asset API. Destructible actors are instanced from destructible assets. +*/ +class DestructibleAsset : public Asset +{ +public: + /** + Enum of chunk flags + */ + enum ChunkFlags + { + ChunkEnvironmentallySupported = (1 << 0), + ChunkAndDescendentsDoNotFracture = (1 << 1), + ChunkDoesNotFracture = (1 << 2), + ChunkDoesNotCrumble = (1 << 3), +#if APEX_RUNTIME_FRACTURE + ChunkRuntimeFracture = (1 << 4), +#endif + ChunkIsInstanced = (1 << 16) + }; + + /** Instancing */ + + /** + Instances the DestructibleAsset, creating an DestructibleActor, using the DestructibleActorDesc. + See DestructibleActor and DestructibleActorDesc. This asset will own the DestructibleActor, + so that any DestructibleActor created by it will be released when this asset is released. + You may also call the DestructibleActor's release() method at any time. + */ + virtual void releaseDestructibleActor(DestructibleActor& actor) = 0; + + + /** General */ + + /** + Create a destructible actor representing the destructible asset in a scene. + Unlike a call to createApexActor, here the created actor takes explicit ownership of the provided actorParams. + This can represent either the destructible descriptor or previously serialized destructible state. + Note: The client should not attempt to use the provided actorParams after calling this method. + */ + virtual DestructibleActor* createDestructibleActorFromDeserializedState(::NvParameterized::Interface* actorParams, Scene& apexScene) = 0; + + /** + The DestructibleParameters which describe the default fracturing behavior for instanced + DestructibleActors. + */ + virtual DestructibleParameters getDestructibleParameters() const = 0; + + /** + The parameters used for default destructible initialization. See DestructibleInitParameters. + */ + virtual DestructibleInitParameters getDestructibleInitParameters() const = 0; + + /** + The name of the emitter to use when generating crumble particles. + Returns NULL if no emitter is configured. + */ + virtual const char* getCrumbleEmitterName() const = 0; + + /** + The name of the emitter to use when generating fracture-line dust particles. + Returns NULL if no emitter is configured. + */ + virtual const char* getDustEmitterName() const = 0; + + /** + The total number of chunks in the asset. + */ + virtual uint32_t getChunkCount() const = 0; + + /** + The total number of fracture hierarchy depth levels in the asset. + */ + virtual uint32_t getDepthCount() const = 0; + + /** + Gets the RenderMeshAsset associated with this asset. + */ + virtual const RenderMeshAsset* getRenderMeshAsset() const = 0; + + /** + Set the RenderMeshAsset associated with this asset. + This is the asset used for non-instanced rendering. + NULL is a valid argument, and can be used to clear the internal mesh data. + Returns true if successful. + */ + virtual bool setRenderMeshAsset(RenderMeshAsset*) = 0; + + /** Retrieve the number of scatter mesh assets */ + virtual uint32_t getScatterMeshAssetCount() const = 0; + + /** Retrieve the scatter mesh asset array */ + virtual RenderMeshAsset* const * getScatterMeshAssets() const = 0; + + /** + Get the number of instanced chunk meshes in this asset. + */ + virtual uint32_t getInstancedChunkMeshCount() const = 0; + + /** + Returns stats (sizes, counts) for the asset. See DestructibleAssetStats. + */ + virtual void getStats(DestructibleAssetStats& stats) const = 0; + + /** + Ensures that the asset has chunk overlap information cached up to the given depth. + If depth < 0 (as it is by default), the depth will be taken to be the supportDepth + given in the asset's destructibleParameters. + It is ok to pass in a depth greater than any chunk depth in the asset. + */ + virtual void cacheChunkOverlapsUpToDepth(int32_t depth = -1) = 0; + + /** + Clears the chunk overlap cache. + If depth < 0 (as it is by default), it clears the cache for each depth. + + \param depth Depth to be cleared. -1 for all depths. + \param keepCachedFlag If the flag is set, the depth is considered to be cached even if the overlaps list is empty. + */ + virtual void clearChunkOverlaps(int32_t depth = -1, bool keepCachedFlag = false) = 0; + + /** + Adds edges to the support graph. Edges must connect chunks of equal depth. + The indices refer to the reordered chunk array, a mapping is provided in cookChunks. + + \param supportGraphEdges Integer pairs representing indices to chunks that are linked + \param numSupportGraphEdges Number of provided integer pairs. + */ + virtual void addChunkOverlaps(IntPair* supportGraphEdges, uint32_t numSupportGraphEdges) = 0; + + /** + Removes edges from support graph. + The indices refer to the reordered chunk array, a mapping is provided in cookChunks. + + \param supportGraphEdges Integer pairs representing indices to chunks that are linked + \param numSupportGraphEdges Number of provided integer pairs. + \param keepCachedFlagIfEmpty If the flag is set, the depth is considered to be cached even if the overlaps list is empty. + */ + virtual void removeChunkOverlaps(IntPair* supportGraphEdges, uint32_t numSupportGraphEdges, bool keepCachedFlagIfEmpty) = 0; + + /** + The size of the array returned by getCachedOverlapsAtDepth(depth) (see below). + Note: this function will not trigger overlap caching for the given depth. + */ + virtual uint32_t getCachedOverlapCountAtDepth(uint32_t depth) const = 0; + + /** + Array of integer pairs, indexing chunk pairs which touch at a given depth in the hierarchy. + The size of the array is given by getCachedOverlapCountAtDepth(depth). + Note: this function will not trigger overlap caching for the given depth. If no overlaps + have been calculated for the depth given, this function returns NULL. + */ + virtual const IntPair* getCachedOverlapsAtDepth(uint32_t depth) const = 0; + + /** + If this chunk is instanced within the same asset, then this provides the instancing position offset. + Otherwise, this function returns (0,0,0). + */ + virtual PxVec3 getChunkPositionOffset(uint32_t chunkIndex) const = 0; + + /** + If this chunk is instanced within the same asset, then this provides the instancing UV offset. + Otherwise, this function returns (0,0). + */ + virtual PxVec2 getChunkUVOffset(uint32_t chunkIndex) const = 0; + + /** + Retrieve flags (see ChunkFlags) for the given chunk. + */ + virtual uint32_t getChunkFlags(uint32_t chunkIndex) const = 0; + + /** + Accessor to query the depth of a given chunk. + */ + virtual uint16_t getChunkDepth(uint32_t chunkIndex) const = 0; + + /** + Returns the index of the given chunk's parent. If the chunk has no parent (is the root of the fracture hierarchy), + then -1 is returned. + */ + virtual int32_t getChunkParentIndex(uint32_t chunkIndex) const = 0; + + /** + Returns the chunk bounds in the asset (local) space. + */ + virtual PxBounds3 getChunkActorLocalBounds(uint32_t chunkIndex) const = 0; + + /** + The render mesh asset part index associated with this chunk. + */ + virtual uint32_t getPartIndex(uint32_t chunkIndex) const = 0; + + /** + The number of convex hulls associated with a given part. + */ + virtual uint32_t getPartConvexHullCount(const uint32_t partIndex) const = 0; + + /** + Returns the head of an array to convex hull NvParamterized::Interface* pointers for a given part. + */ + virtual NvParameterized::Interface** getPartConvexHullArray(const uint32_t partIndex) const = 0; + + /** + \brief Returns the size of the actor transform array. See getActorTransforms() for a description of this data. + */ + virtual uint32_t getActorTransformCount() const = 0; + + /** + \brief Returns the head of the actor transform array. This list is a convenience for placing actors in a level from poses authored in a level editor. + The transforms may contain scaling. + */ + virtual const PxMat44* getActorTransforms() const = 0; + + /** + \brief Apply a transformation to destructible asset + + This is a permanent transformation and it changes the object state. Should only be called immediately before serialization + and without further modifying the object later on. + + \param transformation This matrix is allowed to contain a translation and a rotation + \param scale Apply a uniform scaling as well + */ + virtual void applyTransformation(const PxMat44& transformation, float scale) = 0; + + /** + \brief Apply an arbitrary affine transformation to destructible asset + + This is a permanent transformation and it changes the object state. Should only be called immediately before serialization + and without further modifying the object later on. + + \param transformation This matrix is allowed to contain translation, rotation, scale and skew + */ + virtual void applyTransformation(const PxMat44& transformation) = 0; + + /** + Rebuild the collision volumes for the given chunk, using the geometryDesc (see DestructibleGeometryDesc). + Returns true iff successful. + */ + virtual bool rebuildCollisionGeometry(uint32_t partIndex, const DestructibleGeometryDesc& geometryDesc) = 0; + +protected: + /** Hidden destructor. Use release(). */ + virtual ~DestructibleAsset() {} +}; + + +#if !PX_PS4 + #pragma warning(pop) +#endif //!PX_PS4 + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // DESTRUCTIBLE_ASSET_H diff --git a/APEX_1.4/include/destructible/DestructiblePreview.h b/APEX_1.4/include/destructible/DestructiblePreview.h new file mode 100644 index 00000000..46830160 --- /dev/null +++ b/APEX_1.4/include/destructible/DestructiblePreview.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef DESTRUCTIBLE_PREVIEW_H +#define DESTRUCTIBLE_PREVIEW_H + +#include "AssetPreview.h" +#include "RenderMeshActor.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + + +/** +\brief Destructible module's derivation AssetPreview. +*/ + +class DestructiblePreview : public AssetPreview +{ +public: + + /** + \brief Returns render mesh actor + */ + virtual const RenderMeshActor* getRenderMeshActor() const = 0; + + /** + \brief Sets the preview chunk depth and "explode" amount (pushes the chunks out by that relative distance). + \param [in] depth Must be nonnegative. Internally the value will be clamped to the depth range in the asset. + \param [in] explode must be nonnegative. + */ + virtual void setExplodeView(uint32_t depth, float explode) = 0; + +protected: + DestructiblePreview() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // DESTRUCTIBLE_PREVIEW_H diff --git a/APEX_1.4/include/destructible/DestructibleRenderable.h b/APEX_1.4/include/destructible/DestructibleRenderable.h new file mode 100644 index 00000000..fd76bc8b --- /dev/null +++ b/APEX_1.4/include/destructible/DestructibleRenderable.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef DESTRUCTIBLE_RENDERABLE_H +#define DESTRUCTIBLE_RENDERABLE_H + +#include "foundation/Px.h" +#include "ApexInterface.h" +#include "Renderable.h" +#include "ModuleDestructible.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + + +/** + Destructible renderable API. The destructible renderable contains rendering information for an DestructibleActor. +*/ +class DestructibleRenderable : public ApexInterface, public Renderable +{ +public: + /** + Get the render mesh actor for the specified mesh type. + */ + virtual RenderMeshActor* getRenderMeshActor(DestructibleActorMeshType::Enum type = DestructibleActorMeshType::Skinned) const = 0; + +protected: + virtual ~DestructibleRenderable() {} +}; + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // DESTRUCTIBLE_RENDERABLE_H diff --git a/APEX_1.4/include/destructible/ExplicitHierarchicalMesh.h b/APEX_1.4/include/destructible/ExplicitHierarchicalMesh.h new file mode 100644 index 00000000..5d74c51a --- /dev/null +++ b/APEX_1.4/include/destructible/ExplicitHierarchicalMesh.h @@ -0,0 +1,1024 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef EXPLICIT_HIERARCHICAL_MESH_H +#define EXPLICIT_HIERARCHICAL_MESH_H + +#include "foundation/Px.h" +#include "IProgressListener.h" +#include "RenderMeshAsset.h" +#include "ConvexHullMethod.h" +#include "foundation/PxPlane.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** + ExplicitVertexFormat + + This is used when authoring an VertexBuffer, to define which data channels exist. + */ +struct ExplicitVertexFormat +{ + /** This value defines which vertex winding orders will be rendered. See RenderCullMode. */ + uint32_t mWinding; + + /** Whether or not the accompanying vertex data has defined static vertex positions. */ + bool mHasStaticPositions; + + /** Whether or not the accompanying vertex data has defined static vertex normals. */ + bool mHasStaticNormals; + + /** Whether or not the accompanying vertex data has defined static vertex tangents. */ + bool mHasStaticTangents; + + /** Whether or not the accompanying vertex data has defined static vertex binormals. */ + bool mHasStaticBinormals; + + /** Whether or not the accompanying vertex data has defined static vertex colors. */ + bool mHasStaticColors; + + /** Whether or not to create separate render resource for a static bone index buffer. */ + bool mHasStaticSeparateBoneBuffer; + + /** Whether or not the accompanying vertex data has defined dynamic displacement coordinates */ + bool mHasStaticDisplacements; + + /** Whether or not the accompanying vertex data has defined dynamic vertex positions. */ + bool mHasDynamicPositions; + + /** Whether or not the accompanying vertex data has defined dynamic vertex normals. */ + bool mHasDynamicNormals; + + /** Whether or not the accompanying vertex data has defined dynamic vertex tangents. */ + bool mHasDynamicTangents; + + /** Whether or not the accompanying vertex data has defined dynamic vertex binormals. */ + bool mHasDynamicBinormals; + + /** Whether or not the accompanying vertex data has defined dynamic vertex colors. */ + bool mHasDynamicColors; + + /** Whether or not to create separate render resource for a dynamic bone index buffer. */ + bool mHasDynamicSeparateBoneBuffer; + + /** Whether or not the accompanying vertex data has defined dynamic displacement coordinates */ + bool mHasDynamicDisplacements; + + /** How many UV coordinate channels there are (per vertex) */ + uint32_t mUVCount; + + /** How many bones may influence a vertex */ + uint32_t mBonesPerVertex; + + /** Constructor, calls clear() to set formats to default settings */ + ExplicitVertexFormat() + { + clear(); + } + + /** + Set formats to default settings: + + mWinding = RenderCullMode::CLOCKWISE; + mHasStaticPositions = false; + mHasStaticNormals = false; + mHasStaticTangents = false; + mHasStaticBinormals = false; + mHasStaticColors = false; + mHasStaticSeparateBoneBuffer = false; + mHasStaticDisplacements = false; + mHasDynamicPositions = false; + mHasDynamicNormals = false; + mHasDynamicTangents = false; + mHasDynamicBinormals = false; + mHasDynamicColors = false; + mHasDynamicSeparateBoneBuffer = false; + mHasDynamicDisplacements = false; + mUVCount = 0; + mBonesPerVertex = 0; + */ + void clear() + { + mWinding = RenderCullMode::CLOCKWISE; + mHasStaticPositions = false; + mHasStaticNormals = false; + mHasStaticTangents = false; + mHasStaticBinormals = false; + mHasStaticColors = false; + mHasStaticSeparateBoneBuffer = false; + mHasStaticDisplacements = false; + mHasDynamicPositions = false; + mHasDynamicNormals = false; + mHasDynamicTangents = false; + mHasDynamicBinormals = false; + mHasDynamicColors = false; + mHasDynamicSeparateBoneBuffer = false; + mHasDynamicDisplacements = false; + mUVCount = 0; + mBonesPerVertex = 0; + } + + /** + Equality operator. All values are tested for equality except mBonesPerVertex. + */ + bool operator == (const ExplicitVertexFormat& data) const + { + if (mWinding != data.mWinding) + { + return false; + } + if (mHasStaticPositions != data.mHasStaticPositions || + mHasStaticNormals != data.mHasStaticNormals || + mHasStaticTangents != data.mHasStaticTangents || + mHasStaticBinormals != data.mHasStaticBinormals || + mHasStaticColors != data.mHasStaticColors || + mHasStaticSeparateBoneBuffer != data.mHasStaticSeparateBoneBuffer || + mHasStaticDisplacements != data.mHasStaticDisplacements) + { + return false; + } + if (mHasDynamicPositions != data.mHasDynamicPositions || + mHasDynamicNormals != data.mHasDynamicNormals || + mHasDynamicTangents != data.mHasDynamicTangents || + mHasDynamicBinormals != data.mHasDynamicBinormals || + mHasDynamicColors != data.mHasDynamicColors || + mHasDynamicSeparateBoneBuffer != data.mHasDynamicSeparateBoneBuffer || + mHasDynamicDisplacements != data.mHasDynamicDisplacements) + { + return false; + } + if (mUVCount != data.mUVCount) + { + return false; + } + return true; + } + + /** + Returns the logical complement of the == operator. + */ + bool operator != (const ExplicitVertexFormat& data) const + { + return !(*this == data); + } + + /** + Creates a render-ready VertexFormat corresponding to this structure's member values. + */ + void copyToVertexFormat(VertexFormat* format) const + { + format->reset(); + uint32_t bi; + if (mHasStaticPositions) + { + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::POSITION)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT3); + format->setBufferAccess(bi, mHasDynamicPositions ? RenderDataAccess::DYNAMIC : RenderDataAccess::STATIC); + } + if (mHasStaticNormals) + { + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::NORMAL)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT3); + format->setBufferAccess(bi, mHasDynamicNormals ? RenderDataAccess::DYNAMIC : RenderDataAccess::STATIC); + } + if (mHasStaticTangents) + { + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::TANGENT)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT3); + format->setBufferAccess(bi, mHasDynamicTangents ? RenderDataAccess::DYNAMIC : RenderDataAccess::STATIC); + } + if (mHasStaticBinormals) + { + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::BINORMAL)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT3); + format->setBufferAccess(bi, mHasDynamicBinormals ? RenderDataAccess::DYNAMIC : RenderDataAccess::STATIC); + } + if (mHasStaticDisplacements) + { + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::DISPLACEMENT_TEXCOORD)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT3); + format->setBufferAccess(bi, mHasDynamicDisplacements ? RenderDataAccess::DYNAMIC : RenderDataAccess::STATIC); + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::DISPLACEMENT_FLAGS)); + format->setBufferFormat(bi, RenderDataFormat::UINT1); + format->setBufferAccess(bi, mHasDynamicDisplacements ? RenderDataAccess::DYNAMIC : RenderDataAccess::STATIC); + } + if (mUVCount > 0) + { + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::TEXCOORD0)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT2); + } + if (mUVCount > 1) + { + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::TEXCOORD1)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT2); + } + if (mUVCount > 2) + { + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::TEXCOORD2)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT2); + } + if (mUVCount > 3) + { + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::TEXCOORD3)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT2); + } + switch (mBonesPerVertex) + { + case 1: + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::BONE_INDEX)); + format->setBufferFormat(bi, RenderDataFormat::USHORT1); + break; + case 2: + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::BONE_INDEX)); + format->setBufferFormat(bi, RenderDataFormat::USHORT2); + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::BONE_WEIGHT)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT2); + break; + case 3: + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::BONE_INDEX)); + format->setBufferFormat(bi, RenderDataFormat::USHORT3); + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::BONE_WEIGHT)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT3); + break; + case 4: + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::BONE_INDEX)); + format->setBufferFormat(bi, RenderDataFormat::USHORT4); + bi = (uint32_t)format->addBuffer(format->getSemanticName(RenderVertexSemantic::BONE_WEIGHT)); + format->setBufferFormat(bi, RenderDataFormat::FLOAT4); + break; + } + + format->setHasSeparateBoneBuffer(mHasStaticSeparateBoneBuffer); + format->setWinding((RenderCullMode::Enum)mWinding); + } +}; + + +/** + ExplicitSubmeshData + + This is used when authoring an RenderMeshAsset. + + This is the per-submesh data: the material name, and vertex format. + */ +struct ExplicitSubmeshData +{ + /** + Enum for storing material name buffer size + */ + enum + { + MaterialNameBufferSize = 1024 + }; + + /** + Material name char buffer + */ + char mMaterialName[MaterialNameBufferSize]; + + /** + Explicit vertex format + \see ExplicitVertexFormat + */ + ExplicitVertexFormat mVertexFormat; + + /** + Equal operator for ExplicitSubmeshData + */ + bool operator == (const ExplicitSubmeshData& data) const + { + return !::strcmp(mMaterialName, data.mMaterialName) && mVertexFormat == data.mVertexFormat; + } + + /** + Not equal operator for ExplicitSubmeshData + */ + bool operator != (const ExplicitSubmeshData& data) const + { + return !(*this == data); + } +}; + + +/** + Collision volume descriptor for a chunk +*/ +struct CollisionVolumeDesc +{ + CollisionVolumeDesc() + { + setToDefault(); + } + + /** + Set CollisionVolumeDesc to default values + */ + void setToDefault() + { + mHullMethod = ConvexHullMethod::CONVEX_DECOMPOSITION; + mConcavityPercent = 4.0f; + mMergeThreshold = 4.0f; + mRecursionDepth = 0; + mMaxVertexCount = 0; + mMaxEdgeCount = 0; + mMaxFaceCount = 0; + } + + /** + How to generate convex hulls for a chunk. See ConvexHullMethod::Enum. + Default = CONVEX_DECOMPOSITION. + */ + ConvexHullMethod::Enum mHullMethod; + + /** + Allowed concavity if mHullMethod = ConvexHullMethod::CONVEX_DECOMPOSITION. + Default = 4.0. + */ + float mConcavityPercent; + + /** + Merge threshold if mHullMethod = ConvexHullMethod::CONVEX_DECOMPOSITION. + Default = 4.0. + */ + float mMergeThreshold; + + /** + Recursion depth if mHullMethod = ConvexHullMethod::CONVEX_DECOMPOSITION. + Depth = 0 generates a single convex hull. Higher recursion depths may generate + more convex hulls to fit the mesh. + Default = 0. + */ + uint32_t mRecursionDepth; + + /** + The maximum number of vertices each hull may have. If 0, there is no limit. + Default = 0. + */ + uint32_t mMaxVertexCount; + + /** + The maximum number of edges each hull may have. If 0, there is no limit. + Default = 0. + */ + uint32_t mMaxEdgeCount; + + /** + The maximum number of faces each hull may have. If 0, there is no limit. + Default = 0. + */ + uint32_t mMaxFaceCount; +}; + + +/** + Collision descriptor +*/ +struct CollisionDesc +{ + /** + How many collision volume descriptors are in the mVolumeDescs array. + + This count need not match the depth count of the destructible to be created. If it is greater than the depth count of the destructible, + the extra volume descriptors will be ignored. If it is less than the depth count of the destructible, then mVolumeDescs[depthCount-1] will + be used unless depthCount is zero. In that case, the defeult CollisionVolumeDesc() will be used. + + This may be zero, in which case all volume descriptors will be the default values. If it is not zero, mVolumeDescs must be a valid pointer. + */ + unsigned mDepthCount; + + /** + Array of volume descriptors of length depthCount (may be NULL if depthCount is zero). + */ + CollisionVolumeDesc* mVolumeDescs; + + /** + The maximum amount to trim overlapping collision hulls (as a percentage of the hulls' widths) + + Default = 0.2f + */ + float mMaximumTrimming; + + /** Constructor sets default values. */ + CollisionDesc() + { + setToDefault(); + } + + /** + Set CollisionDesc to default values + */ + void setToDefault() + { + mDepthCount = 0; + mVolumeDescs = NULL; + mMaximumTrimming = 0.2f; + } +}; + + +/** + Enumeration of current fracture methods. Used when an authored mesh needs to know how it was created, for + example if we need to re-apply UV mapping information. +*/ +struct FractureMethod +{ + /** + Enum of fracture methods + */ + enum Enum + { + Unknown, + Slice, + Cutout, + Voronoi, + + FractureMethodCount + }; +}; + + +/** + FractureMaterialDesc + + Descriptor for materials applied to interior faces. +*/ +struct FractureMaterialDesc +{ + /** The UV scale (geometric distance/unit texture distance) for interior materials. + Default = (1.0f,1.0f). + */ + PxVec2 uvScale; + + /** A UV origin offset for interior materials. + Default = (0.0f,0.0f). + */ + PxVec2 uvOffset; + + /** World space vector specifying surface tangent direction. If this vector + is (0.0f,0.0f,0.0f), then an arbitrary direction will be chosen. + Default = (0.0f,0.0f,0.0f). + */ + PxVec3 tangent; + + /** Angle from tangent direction for the u coordinate axis. + Default = 0.0f. + */ + float uAngle; + + /** + The submesh index to use for the newly-created triangles. + If an invalid index is given, 0 will be used. + */ + uint32_t interiorSubmeshIndex; + + /** Constructor sets defaults */ + FractureMaterialDesc() + { + setToDefault(); + } + + /** + Set default values: + uvScale = PxVec2(1.0f); + uvOffset = PxVec2(0.0f); + tangent = PxVec3(0.0f); + uAngle = 0.0f; + interiorSubmeshIndex = 0; + */ + void setToDefault() + { + uvScale = PxVec2(1.0f); + uvOffset = PxVec2(0.0f); + tangent = PxVec3(0.0f); + uAngle = 0.0f; + interiorSubmeshIndex = 0; + } +}; + + +/** + A reference frame for applying UV mapping to triangles. Also includes the fracturing method and an index + which is used internally for such operations as re-applying UV mapping information. +*/ +struct MaterialFrame +{ + MaterialFrame() : + mCoordinateSystem(PxVec4(1.0f)), + mUVPlane(PxVec3(0.0f, 0.0f, 1.0f), 0.0f), + mUVScale(1.0f), + mUVOffset(0.0f), + mFractureMethod(FractureMethod::Unknown), + mFractureIndex(-1), + mSliceDepth(0) + { + } + + /** + Builds coordinate system from material desc + */ + void buildCoordinateSystemFromMaterialDesc(const nvidia::FractureMaterialDesc& materialDesc, const PxPlane& plane) + { + PxVec3 zAxis = plane.n; + zAxis.normalize(); + PxVec3 xAxis = materialDesc.tangent; + PxVec3 yAxis = zAxis.cross(xAxis); + const float l2 = yAxis.magnitudeSquared(); + if (l2 > PX_EPS_F32*PX_EPS_F32) + { + yAxis *= PxRecipSqrt(l2); + } + else + { + uint32_t maxDir = PxAbs(plane.n.x) > PxAbs(plane.n.y) ? + (PxAbs(plane.n.x) > PxAbs(plane.n.z) ? 0u : 2u) : + (PxAbs(plane.n.y) > PxAbs(plane.n.z) ? 1u : 2u); + xAxis = PxMat33(PxIdentity)[(maxDir + 1) % 3]; + yAxis = zAxis.cross(xAxis); + yAxis.normalize(); + } + xAxis = yAxis.cross(zAxis); + + const float c = PxCos(materialDesc.uAngle); + const float s = PxSin(materialDesc.uAngle); + + mCoordinateSystem.column0 = PxVec4(c*xAxis + s*yAxis, 0.0f); + mCoordinateSystem.column1 = PxVec4(c*yAxis - s*xAxis, 0.0f); + mCoordinateSystem.column2 = PxVec4(zAxis, 0.0f); + mCoordinateSystem.setPosition(plane.project(PxVec3(0.0f))); + + mUVPlane = plane; + mUVScale = materialDesc.uvScale; + mUVOffset = materialDesc.uvOffset; + } + + PxMat44 mCoordinateSystem; ///< Coordinate system + PxPlane mUVPlane; ///< UV plane + PxVec2 mUVScale; ///< UV scale + PxVec2 mUVOffset; ///< UV offset + uint32_t mFractureMethod; ///< Fracture method + int32_t mFractureIndex; ///< Fracture index + uint32_t mSliceDepth; ///< The depth being created when this split is done. mSliceDepth = 0 means "unknown" +}; + + +/** + Interface to a "displacement map volume," used with tessellated fracturing. + A displacement map volume captures how to displace a particular point in 3D space + along the x, y and z axes. The data is stored as a 3D texture volume, with + corresponding displacement coordinates acting as a look-up into this volume. + X, Y and Z offsets correspond to R, G, and B color channels + + Various approaches can be used to generate the 3D noise field, in this case + Perlin noise is used, with appropriate settings specified by the FractureSliceDesc. +*/ +class DisplacementMapVolume +{ +public: + /** + Fills the specified array and parameters with texture-compatible information. + + The corresponding texture aligns with the displacement UVs generated as fracturing occurs + when displacement maps are enabled, with RGB data corresponding to XYZ offsets, respectively. + */ + virtual void getData(uint32_t& width, uint32_t& height, uint32_t& depth, uint32_t& size, unsigned char const** ppData) const = 0; + + virtual ~DisplacementMapVolume() { } +}; + + +/** + Handling of open meshes. + + BSPMode::Automatic causes the mesh to be analyzed to determine if it's open or closed + BSPOpenMode::Closed means the mesh should be closed and interior faces are created when the mesh is split + BSPOpenMode::Open means the mesh should be open and no interior faces are created when it is split +*/ +struct BSPOpenMode +{ + /** + Enum of BSP open modes + */ + enum Enum + { + Automatic, + Closed, + Open, + + BSPOpenModeCount + }; +}; + + +/** + ExplicitHierarchicalMesh + + An interface to a representation of a render mesh that is used for authoring. + + The "hierarchical" nature of this mesh is represented by extra parent/child relations + among the parts that will become the parts of an RenderMeshAsset. + */ +class ExplicitHierarchicalMesh +{ +public: + /** Used in the visualize method to determine what to draw. */ + enum Enum + { + /** + Draws the convex hulls associated with the BSP regions marked "outside," if a BSP has + been created for this object (see calculateMeshBSP()). + */ + VisualizeMeshBSPOutsideRegions = (1 << 0), + + /** + Draws the convex hulls associated with the BSP regions marked "inside," if a BSP has + been created for this object (see calculateMeshBSP()). + */ + VisualizeMeshBSPInsideRegions = (1 << 1), + + /** + Draws the convex hull associated with a single BSP regions, if a BSP has + been created for this object (see calculateMeshBSP()). The region index must + be passed into the visualize function if this flag is set. + */ + VisualizeMeshBSPSingleRegion = (1 << 8), + + /** Currently unused */ + VisualizeSliceBSPOutsideRegions = (1 << 16), + + /** Currently unused */ + VisualizeSliceBSPInsideRegions = (1 << 17), + + /** Currently unused */ + VisualizeSliceBSPSingleRegion = (1 << 24), + + VisualizeMeshBSPAllRegions = VisualizeMeshBSPOutsideRegions | VisualizeMeshBSPInsideRegions + }; + + /** + Used in the serialize and deserialize methods, to embed extra data. + The user must implement this class to serialize and deserialize + the enumerated data type given. + */ + class Embedding + { + public: + /** + Enum of data types + */ + enum DataType + { + MaterialLibrary + }; + + /** + Serialize the enumerated data type + */ + virtual void serialize(PxFileBuf& stream, Embedding::DataType type) const = 0; + + /** + Deserialize the enumerated data type + */ + virtual void deserialize(PxFileBuf& stream, Embedding::DataType type, uint32_t version) = 0; + }; + + /** + Used to access the collision data for each mesh part + */ + class ConvexHull + { + protected: + ConvexHull() + { + } + + virtual ~ConvexHull() + { + } + + public: + /** + Builds the convex hull of the points given. + */ + virtual void buildFromPoints(const void* points, uint32_t numPoints, uint32_t pointStrideBytes) = 0; + + /** + The hull's axis aligned bounding box. + */ + virtual const PxBounds3& getBounds() const = 0; + + /** + The hull's volume. + */ + virtual float getVolume() const = 0; + + /** + This is the number of vertices in the convex hull. + */ + virtual uint32_t getVertexCount() const = 0; + + /** + This is the vertex indexed by vertexIndex, which must in + the range [0, getVertexCount()-1]. + */ + virtual PxVec3 getVertex(uint32_t vertexIndex) const = 0; + + /** + This is the number of edges in the convex hull. + */ + virtual uint32_t getEdgeCount() const = 0; + + /** + This is an edge endpoint indexed by edgeIndex, which must in + the range [0, getEdgeCount()-1], and + whichEndpoint, which must be 0 or 1. + */ + virtual PxVec3 getEdgeEndpoint(uint32_t edgeIndex, uint32_t whichEndpoint) const = 0; + + /** + This is the number of planes which bound the convex hull. + */ + virtual uint32_t getPlaneCount() const = 0; + + /** + This is the plane indexed by planeIndex, which must in + the range [0, getPlaneCount()-1]. + */ + virtual PxPlane getPlane(uint32_t planeIndex) const = 0; + + /** + Perform a ray cast against the convex hull. + + \param in this MUST be set to the minimum 'time' that you wish to have reported for intersection. + you may consider this an origin offset for the ray. + On exit, if the hull is intersected, this value will contain the time of intersection, + or its original value, which ever is larger. + + \param out this MUST be set to the maximum 'time' that you wish to have reported for intersection. + you may consider this the endpoint of a line segment intersection. + On exit, if the hull is intersected, this value will contain the time that the ray + exits the hull, or its original value, which ever is smaller. + + \param orig describe the ray to intersect with the convex hull. + \param dir describe the ray to intersect with the convex hull. + + \param localToWorldRT the rotation applied to the convex hull. + + \param scale the scale applied to the convex hull. + + \param normal if not NULL, *normal will contain the surface normal of the convex hull at the + point of intersection (at the 'in' time). If the point on the ray at the 'in' time lies + within the volume of the convex hull, then *normal will be set to (0,0,0). + + \return returns true if the line segment described by the user's supplied 'in' and 'out' + parameters along the ray intersects the convex hull, false otherwise. + */ + virtual bool rayCast(float& in, float& out, const PxVec3& orig, const PxVec3& dir, + const PxTransform& localToWorldRT, const PxVec3& scale, PxVec3* normal = NULL) const = 0; + /** + Removes vertices from the hull until the bounds given in the function's parameters are met. + If inflated = true, then the maximum counts given are compared with the cooked hull, which may have higher counts due to beveling. + + \note a value of zero indicates no limit, effectively infinite. + + \return true if successful, i.e. the limits were met. False otherwise. + */ + virtual bool reduceHull(uint32_t maxVertexCount, uint32_t maxEdgeCount, uint32_t maxFaceCount, bool inflated) = 0; + + /** + Releases all memory associated with this object and deletes itself. + */ + virtual void release() = 0; + }; + + /** + "Resets" this object to its initial state, freeing all internal data. + If keepRoot is true, then parts up to the root depth will not be cleared. + (In this case, not all of the submesh data, etc. will be deleted.) + The root depth is set when the ExplicitHierarchicalMesh is first created. + Fracturing methods create pieces beyond the root depth. + */ + virtual void clear(bool keepRoot = false) = 0; + + /** + The maximum child depth in the hierarchy. Depth 0 is the base, depth 1 parts are children of depth 0, etc. + If there are no parts, this function returns -1. + */ + virtual int32_t maxDepth() const = 0; + + /** + The number of parts in this mesh. + */ + virtual uint32_t partCount() const = 0; + + /** + The number of chunks in this mesh. + */ + virtual uint32_t chunkCount() const = 0; + + /** + The parent index of the chunk indexed by chunkIndex. + Depth 0 parts have no parents, and for those parts this function returns -1. + */ + virtual int32_t* parentIndex(uint32_t chunkIndex) = 0; + + /** + A runtime unique identifier for a chunk. During one execution of an application which + contains the fracture tools, this chunk ID will be unique for the chunk. + */ + virtual uint64_t chunkUniqueID(uint32_t chunkIndex) = 0; + + /** + The geometric part index this chunk references + */ + virtual int32_t* partIndex(uint32_t chunkIndex) = 0; + + /** + If instanced, the part instance offset (translation). + */ + virtual PxVec3* instancedPositionOffset(uint32_t chunkIndex) = 0; + + /** + If instanced, the part instance offset (UV). + */ + virtual PxVec2* instancedUVOffset(uint32_t chunkIndex) = 0; + + /** + The number of triangles in the part indexed by partIndex. + This includes all submeshes. + */ + virtual uint32_t meshTriangleCount(uint32_t partIndex) const = 0; + + /** + A pointer into the array of ExplicitRenderTriangles which form the mesh + of the part indexed by partIndex. + */ + virtual ExplicitRenderTriangle* meshTriangles(uint32_t partIndex) = 0; + + /** + The axis aligned bounding box of the triangles for the part index by partIndex. + */ + virtual PxBounds3 meshBounds(uint32_t partIndex) const = 0; + + /** + The axis aligned bounding box of the triangles for the chunk index by chunkIndex. + */ + virtual PxBounds3 chunkBounds(uint32_t chunkIndex) const = 0; + + /** + Flags describing attributes of the part indexed by partIndex. + See DestructibleAsset::ChunkFlags + */ + virtual uint32_t* chunkFlags(uint32_t chunkIndex) const = 0; + + /** + Build collision volumes for the part indexed by partIndex, using (See CollisionVolumeDesc.) + */ + virtual void buildCollisionGeometryForPart(uint32_t partIndex, const CollisionVolumeDesc& desc) = 0; + + /** + Build collision volumes for all parts referenced by chunks at the root depth. + + If aggregateRootChunkParentCollision, then every chunk which is the parent of root chunks + gets all of the collision hulls of its children. Otherwise, all root chunks have their + collision volumes separately calculated. + */ + virtual void buildCollisionGeometryForRootChunkParts(const CollisionDesc& desc, bool aggregateRootChunkParentCollision = true) = 0; + + /** + Calls IConvexMesh::reduceHull on all part convex hulls. See IConvexMesh::reduceHull. + */ + virtual void reduceHulls(const CollisionDesc& desc, bool inflated) = 0; + + /** + The number of convex hulls for the given part. + */ + virtual uint32_t convexHullCount(uint32_t partIndex) const = 0; + + /** + The convex hulls for the given part. + */ + virtual const ConvexHull** convexHulls(uint32_t partIndex) const = 0; + + /** + The outward surface normal associated with the chunk mesh geometry. + */ + virtual PxVec3* surfaceNormal(uint32_t partIndex) = 0; + + /** + The displacement map volume for the mesh. + */ + virtual const DisplacementMapVolume& displacementMapVolume() const = 0; + + /** + The number of submeshes. The explicit mesh representation is just a list + of ExplicitRenderTriangles for each part, and each ExplicitRenderTriangle has + a submesh index. These indices will lie in a contiguous range from 0 to submeshCount()-1. + */ + virtual uint32_t submeshCount() const = 0; + + /** + The submeshData indexed by submeshIndex. See ExplicitSubmeshData. + */ + virtual ExplicitSubmeshData* submeshData(uint32_t submeshIndex) = 0; + + /** + Creates a submesh and adds it to the list of submeshes, and returns the index of + the newly created submesh. + */ + virtual uint32_t addSubmesh(const ExplicitSubmeshData& submeshData) = 0; + + /** + If there are interior submeshes, then triangles belonging + to those submesh will have materials applied to them with a using a coordinate frame. + In the event that materials need to be re-applied (possibly at a different scale), it + is convenient to store the material frames used. This function returns the array of + material frames. The index extraDataIndex stored in each ExplicitRenderTriangle + references this array. + */ + virtual uint32_t getMaterialFrameCount() const = 0; + virtual nvidia::MaterialFrame getMaterialFrame(uint32_t index) const = 0; ///< \see ConvexHull::getMaterialFrameCount + virtual void setMaterialFrame(uint32_t index, const nvidia::MaterialFrame& materialFrame) = 0; ///< \see ConvexHull::getMaterialFrameCount + virtual uint32_t addMaterialFrame() = 0; ///< \see ConvexHull::getMaterialFrameCount + + /** + Serialization. The user must instantiate Embedding in order to successfully + serialize any embedded data. + */ + virtual void serialize(PxFileBuf& stream, Embedding& embedding) const = 0; + + /** + Serialization. The user must instantiate Embedding in order to successfully + serialize any embedded data. + */ + virtual void deserialize(PxFileBuf& stream, Embedding& embedding) = 0; + + /** + Copies the input mesh in to this object. + */ + virtual void set(const ExplicitHierarchicalMesh& mesh) = 0; + + /** + Creates an internal BSP representation of the mesh parts up to the root depth. + This is used by authoring tools to perform CSG operations. If the user instantiates + IProgressListener, they may pass it in to report progress of this operation. + If microgridSize is not NULL, *microgridSize is used in the BSP calculation. Otherwise the + default parameters are used. + meshMode is used to determine if the mesh is open or closed. See NxMeshProcessingParameters::MeshMode + */ + virtual void calculateMeshBSP(uint32_t randomSeed, IProgressListener* progressListener = NULL, const uint32_t* microgridSize = NULL, BSPOpenMode::Enum meshMode = BSPOpenMode::Automatic) = 0; + + /** + Utility to replace the submesh on a set of interior triangles. + */ + virtual void replaceInteriorSubmeshes(uint32_t partIndex, uint32_t frameCount, uint32_t* frameIndices, uint32_t submeshIndex) = 0; + + /** + Draws various components of this object to the debugRenderer, as + defined by the flags (see the visualization Enum above). Some + of the flags require an index be passed in as well. + */ + virtual void visualize(RenderDebugInterface& debugRender, uint32_t flags, uint32_t index = 0) const = 0; + + /** + Releases all memory associated with this object and deletes itself. + */ + virtual void release() = 0; + +protected: + /** + Constructor and destructor are not public + Use createExplicitHierarchicalMesh() to instantiate an ExplicitHierarchicalMesh and + ExplicitHierarchicalMesh::release() to destroy it. + */ + ExplicitHierarchicalMesh() {} + virtual ~ExplicitHierarchicalMesh() {} + +private: + /** The assignment operator is disabled, use set() instead. */ + ExplicitHierarchicalMesh& operator = (const ExplicitHierarchicalMesh&) + { + return *this; + } +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + + +#endif // EXPLICIT_HIERARCHICAL_MESH_H diff --git a/APEX_1.4/include/destructible/FractureToolsAPI.h b/APEX_1.4/include/destructible/FractureToolsAPI.h new file mode 100644 index 00000000..49f01be2 --- /dev/null +++ b/APEX_1.4/include/destructible/FractureToolsAPI.h @@ -0,0 +1,453 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef FRACTURE_TOOLS_API_H +#define FRACTURE_TOOLS_API_H + +#include "foundation/Px.h" +#include "ExplicitHierarchicalMesh.h" +#include "FractureToolsStructs.h" + +PX_PUSH_PACK_DEFAULT + +namespace nvidia +{ +namespace apex +{ + +struct IntersectMesh; +class DestructibleAsset; + +/** Fracture tools API */ +class FractureToolsAPI +{ +public: + + /** Instantiates a blank CutoutSet */ + virtual FractureTools::CutoutSet* createCutoutSet() = 0; + + /** + Builds a cutout set (which must have been initially created by createCutoutSet()). + Uses a bitmap described by pixelBuffer, bufferWidth, and bufferHeight. Each pixel is represented + by one byte in the buffer. + + \param cutoutSet the CutoutSet to build + \param pixelBuffer pointer to be beginning of the pixel buffer + \param bufferWidth the width of the buffer in pixels + \param bufferHeight the height of the buffer in pixels + \param snapThreshold the pixel distance at which neighboring cutout vertices and segments may be fudged into alignment. + \param periodic whether or not to use periodic boundary conditions when creating cutouts from the map + */ + virtual void buildCutoutSet(FractureTools::CutoutSet& cutoutSet, const uint8_t* pixelBuffer, uint32_t bufferWidth, uint32_t bufferHeight, float snapThreshold, bool periodic) = 0; + + /** + Calculate the mapping between a cutout fracture map and a given triangle. + The result is a 3 by 3 matrix M composed by an affine transformation and a rotation, we can get the 3-D projection for a texture coordinate pair (u,v) with such a formula: + (x,y,z) = M*PxVec3(u,v,1) + + \param triangle the target face's normal + \param theMapping resulted mapping, composed by an affine transformation and a rotation + */ + virtual bool calculateCutoutUVMapping(const nvidia::ExplicitRenderTriangle& triangle, PxMat33& theMapping) = 0; + + /** + Uses the passed-in target direction to find the best triangle in the root mesh with normal near the given targetDirection. If triangles exist + with normals within one degree of the given target direction, then one with the greatest area of such triangles is used. Otherwise, the triangle + with normal closest to the given target direction is used. The resulting triangle is used to calculate a UV mapping as in the function + calculateCutoutUVMapping (above). + + The assumption is that there exists a single mapping for all triangles on a specified face, for this feature to be useful. + + \param hMesh the explicit mesh with well rectangle-shaped faces + \param targetDirection the target face's normal + \param theMapping resulted mapping, composed by an affine transformation and a rotation + */ + virtual bool calculateCutoutUVMapping(nvidia::ExplicitHierarchicalMesh& hMesh, const PxVec3& targetDirection, PxMat33& theMapping) = 0; + + /** + Splits the mesh in chunk[0], forming fractured pieces chunks[1...] using + Voronoi decomposition fracturing. + + \param hMesh the mesh to split + \param iHMeshCore if this mesh is not empty, chunk 0 will be used as an indestructible "core" of the fractured + mesh. That is, it will be subtracted from hMesh, and placed at level 1 of the hierarchy. The remainder + of hMesh will be split as usual, creating chunks at level 1 (and possibly deeper). + \param exportCoreMesh if true, a core mesh chunk will be created from iHMeshCore + \param coreMeshImprintSubmeshIndex if this is < 0, use the core mesh materials (was applyCoreMeshMaterialToNeighborChunks). Otherwise, use the given submesh + \param meshProcessingParams describes generic mesh processing directives + \param desc describes the voronoi splitting parameters surfaces (see FractureVoronoiDesc) + \param collisionDesc convex hulls will be generated for each chunk using the method. See CollisionDesc. + \param randomSeed seed for the random number generator, to ensure reproducibility. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. + Meant to be set from another thread. + + \return true if successful. + */ + virtual bool createVoronoiSplitMesh + ( + nvidia::ExplicitHierarchicalMesh& hMesh, + nvidia::ExplicitHierarchicalMesh& iHMeshCore, + bool exportCoreMesh, + int32_t coreMeshImprintSubmeshIndex, + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureVoronoiDesc& desc, + const CollisionDesc& collisionDesc, + uint32_t randomSeed, + nvidia::IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Generates a set of uniformly distributed points in the interior of the root mesh. + + \param hMesh the mesh in which to distribute sites + \param siteBuffer an array of PxVec3, at least the size of siteCount + \param siteChunkIndices if not NULL, then must be at least the size of siteCount. siteCount indices will be written to this buffer, associating each site with a chunk that contains it. + \param siteCount the number of points to write into siteBuffer + \param randomSeed pointer to a seed for the random number generator, to ensure reproducibility. If NULL, the random number generator will not be re-seeded. + \param microgridSize pointer to a grid size used for BSP creation. If NULL, the default settings will be used. + \param meshMode Open mesh handling. Modes: Automatic, Closed, Open (see BSPOpenMode) + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param chunkIndex If this is a valid index, the voronoi sites will only be created within the volume of the indexed chunk. Otherwise, + the sites will be created within each of the root-level chunks. Default value is an invalid index. + + \return returns the number of sites actually created (written to siteBuffer and siteChunkIndices). This may be less than the number of sites requested if site placement fails. + */ + virtual uint32_t createVoronoiSitesInsideMesh + ( + nvidia::ExplicitHierarchicalMesh& hMesh, + PxVec3* siteBuffer, + uint32_t* siteChunkIndices, + uint32_t siteCount, + uint32_t* randomSeed, + uint32_t* microgridSize, + BSPOpenMode::Enum meshMode, + nvidia::IProgressListener& progressListener, + uint32_t chunkIndex = 0xFFFFFFFF + ) = 0; + + /** + Creates scatter mesh sites randomly distributed on the mesh. + + \param meshIndices user-allocated array of size scatterMeshInstancesBufferSize which will be filled in by this function, giving the scatter mesh index used + \param relativeTransforms user-allocated array of size scatterMeshInstancesBufferSize which will be filled in by this function, giving the chunk-relative transform for each chunk instance + \param chunkMeshStarts user-allocated array which will be filled in with offsets into the meshIndices and relativeTransforms array. + For a chunk indexed by i, the corresponding range [chunkMeshStart[i], chunkMeshStart[i+1]-1] in meshIndices and relativeTransforms is used. + *NOTE*: chunkMeshStart array must be of at least size N+1, where N is the number of chunks in the base explicit hierarchical mesh. + \param scatterMeshInstancesBufferSize the size of meshIndices and relativeTransforms array. + \param scatterMeshInstancesBufferSize the size of meshIndices and relativeTransforms array. + \param hMesh the mesh in which to distribute sites + \param targetChunkCount how many chunks are in the array targetChunkIndices + \param targetChunkIndices an array of chunk indices which are candidates for scatter meshes. The elements in the array chunkIndices will come from this array + \param randomSeed pointer to a seed for the random number generator, to ensure reproducibility. If NULL, the random number generator will not be re-seeded. + \param scatterMeshAssetCount the number of different scatter meshes (not instances). Should not exceed 255. If scatterMeshAssetCount > 255, only the first 255 will be used. + \param scatterMeshAssets an array of size scatterMeshAssetCount, of the render mesh assets which will be used for the scatter meshes + \param minCount an array of size scatterMeshAssetCount, giving the minimum number of instances to place for each mesh + \param maxCount an array of size scatterMeshAssetCount, giving the maximum number of instances to place for each mesh + \param minScales an array of size scatterMeshAssetCount, giving the minimum scale to apply to each scatter mesh + \param maxScales an array of size scatterMeshAssetCount, giving the maximum scale to apply to each scatter mesh + \param maxAngles an array of size scatterMeshAssetCount, giving a maximum deviation angle (in degrees) from the surface normal to apply to each scatter mesh + + return value the number of instances placed in indices and relativeTransforms (will not exceed scatterMeshInstancesBufferSize) + */ + virtual uint32_t createScatterMeshSites + ( + uint8_t* meshIndices, + PxMat44* relativeTransforms, + uint32_t* chunkMeshStarts, + uint32_t scatterMeshInstancesBufferSize, + nvidia::ExplicitHierarchicalMesh& hMesh, + uint32_t targetChunkCount, + const uint16_t* targetChunkIndices, + uint32_t* randomSeed, + uint32_t scatterMeshAssetCount, + nvidia::RenderMeshAsset** scatterMeshAssets, + const uint32_t* minCount, + const uint32_t* maxCount, + const float* minScales, + const float* maxScales, + const float* maxAngles + ) = 0; + + /** + Utility to visualize Voronoi cells for a given set of sites. + + debugRender rendering object which will receive the drawing primitives associated with this cell visualization + sites an array of Voronoi cell sites, of length siteCount + siteCount the number of Voronoi cell sites (length of sites array) + cellColors an optional array of colors (see RenderDebug for format) for the cells. If NULL, the white (0xFFFFFFFF) color will be used. + If not NULL, this (of length cellColorCount) is used to color the cell graphics. The number cellColorCount need not match siteCount. If + cellColorCount is less than siteCount, the cell colors will cycle. That is, site N gets cellColor[N%cellColorCount]. + cellColorCount the number of cell colors (the length of cellColors array) + bounds defines an axis-aligned bounding box which clips the visualization, since some cells extend to infinity + cellIndex if this is a valid index (cellIndex < siteCount), then only the cell corresponding to sites[cellIndex] will be drawn. Otherwise, all cells will be drawn. + */ + virtual void visualizeVoronoiCells + ( + nvidia::RenderDebugInterface& debugRender, + const PxVec3* sites, + uint32_t siteCount, + const uint32_t* cellColors, + uint32_t cellColorCount, + const PxBounds3& bounds, + uint32_t cellIndex = 0xFFFFFFFF + ) = 0; + + /** + Builds a new ExplicitHierarchicalMesh from an array of triangles. + + \param iHMesh the ExplicitHierarchicalMesh to build + \param meshTriangles pointer to array of ExplicitRenderTriangles which make up the mesh + \param meshTriangleCount the size of the meshTriangles array + \param submeshData pointer to array of ExplicitSubmeshData, describing the submeshes + \param submeshCount the size of the submeshData array + \param meshPartition if not NULL, an array of size meshPartitionCount, giving the end elements of contiguous subsets of meshTriangles. + If meshPartition is NULL, one partition is assumed. + When there is one partition, these triangles become the level 0 part. + When there is more than one partition, these triangles become level 1 parts, the behavior is determined by firstPartitionIsDepthZero (see below). + \param meshPartitionCount if meshPartition is not NULL, this is the size of the meshPartition array. + \param parentIndices if not NULL, the parent indices for each chunk (corresponding to a partition in the mesh partition). + \param parentIndexCount the size of the parentIndices array. This does not need to match meshPartitionCount. If a mesh partition has an index beyond the end of parentIndices, + then the parentIndex is considered to be 0. Therefore, if parentIndexCount = 0, all parents are 0 and so all chunks created will be depth 1. This will cause a + depth 0 chunk to be created that is the aggregate of the depth 1 chunks. If parentIndexCount > 0, then the depth-0 chunk must have a parentIndex of -1. + To reproduce the effect of the old parameter 'firstPartitionIsDepthZero' = true, set parentIndices to the address of a int32_t containing the value -1, + and set parentIndexCount = 1. + To reproduce the effect of the old parameter 'firstPartitionIsDepthZero' = false, set parentIndexCount = 0. + Note: if parent indices are given, the first one must be -1, and *only* that index may be negative. + That is, there may be only one depth-0 mesh and it must be the first mesh. + */ + virtual bool buildExplicitHierarchicalMesh + ( + nvidia::ExplicitHierarchicalMesh& iHMesh, + const nvidia::ExplicitRenderTriangle* meshTriangles, + uint32_t meshTriangleCount, + const nvidia::ExplicitSubmeshData* submeshData, + uint32_t submeshCount, + uint32_t* meshPartition = NULL, + uint32_t meshPartitionCount = 0, + int32_t* parentIndices = NULL, + uint32_t parentIndexCount = 0 + ) = 0; + + /** + Set the tolerances used in CSG calculations with BSPs. + + \param linearTolerance relative (to mesh size) tolerance used with angularTolerance to determine coplanarity. Default = 1.0e-4. + \param angularTolerance used with linearTolerance to determine coplanarity. Default = 1.0e-3 + \param baseTolerance relative (to mesh size) tolerance used for spatial partitioning + \param clipTolerance relative (to mesh size) tolerance used when clipping triangles for CSG mesh building operations. Default = 1.0e-4. + \param cleaningTolerance relative (to mesh size) tolerance used when cleaning the out put mesh generated from the toMesh() function. Default = 1.0e-7. + */ + virtual void setBSPTolerances + ( + float linearTolerance, + float angularTolerance, + float baseTolerance, + float clipTolerance, + float cleaningTolerance + ) = 0; + + /** + Set the parameters used in BSP building operations. + + \param logAreaSigmaThreshold At each step in the tree building process, the surface with maximum triangle area is compared + to the other surface triangle areas. If the maximum area surface is far from the "typical" set of + surface areas, then that surface is chosen as the next splitting plane. Otherwise, a random + test set is chosen and a winner determined based upon the weightings below. + The value logAreaSigmaThreshold determines how "atypical" the maximum area surface must be to + be chosen in this manner. + Default value = 2.0. + \param testSetSize Larger values of testSetSize may find better BSP trees, but will take more time to create. + testSetSize = 0 is treated as infinity (all surfaces will be tested for each branch). + Default value = 10. + \param splitWeight How much to weigh the relative number of triangle splits when searching for a BSP surface. + Default value = 0.5. + \param imbalanceWeight How much to weigh the relative triangle imbalance when searching for a BSP surface. + Default value = 0.0. + */ + virtual void setBSPBuildParameters + ( + float logAreaSigmaThreshold, + uint32_t testSetSize, + float splitWeight, + float imbalanceWeight + ) = 0; + + + /** + Builds the root ExplicitHierarchicalMesh from an RenderMeshAsset. + Since an DestructibleAsset contains no hierarchy information, the input mesh must have only one part. + + \param iHMesh the ExplicitHierarchicalMesh to build + \param renderMeshAsset input RenderMesh asset + \param maxRootDepth cap the root depth at this value. Re-fracturing of the mesh will occur at this depth. Default = UINT32_MAX + */ + virtual bool buildExplicitHierarchicalMeshFromRenderMeshAsset(nvidia::ExplicitHierarchicalMesh& iHMesh, const nvidia::RenderMeshAsset& renderMeshAsset, uint32_t maxRootDepth = UINT32_MAX) = 0; + + /** + Builds the root ExplicitHierarchicalMesh from an DestructibleAsset. + Since an DestructibleAsset contains hierarchy information, the explicit mesh formed + will have this hierarchy structure. + + \param iHMesh the ExplicitHierarchicalMesh to build + \param destructibleAsset input Destructible asset + \param maxRootDepth cap the root depth at this value. Re-fracturing of the mesh will occur at this depth. Default = UINT32_MAX + */ + virtual bool buildExplicitHierarchicalMeshFromDestructibleAsset(nvidia::ExplicitHierarchicalMesh& iHMesh, const nvidia::DestructibleAsset& destructibleAsset, uint32_t maxRootDepth = UINT32_MAX) = 0; + + /** + Splits the mesh in chunk[0], forming a hierarchy of fractured meshes in chunks[1...] + + \param hMesh the mesh to split + \param iHMeshCore if this mesh is not empty, chunk 0 will be used as an indestructible "core" of the fractured + mesh. That is, it will be subtracted from hMesh, and placed at level 1 of the hierarchy. The remainder + of hMesh will be split as usual, creating chunks at level 1 (and possibly deeper). + \param exportCoreMesh if true, a core mesh chunk will be created from iHMeshCore + \param coreMeshImprintSubmeshIndex if this is < 0, use the core mesh materials (was applyCoreMeshMaterialToNeighborChunks). Otherwise, use the given submesh + \param meshProcessingParams describes generic mesh processing directives + \param desc describes the slicing surfaces (see FractureSliceDesc) + \param collisionDesc convex hulls will be generated for each chunk using the method. See CollisionDesc. + \param randomSeed seed for the random number generator, to ensure reproducibility. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. + Meant to be set from another thread. + + \return returns true if successful. + */ + virtual bool createHierarchicallySplitMesh + ( + nvidia::ExplicitHierarchicalMesh& hMesh, + nvidia::ExplicitHierarchicalMesh& iHMeshCore, + bool exportCoreMesh, + int32_t coreMeshImprintSubmeshIndex, + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureSliceDesc& desc, + const CollisionDesc& collisionDesc, + uint32_t randomSeed, + nvidia::IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Chips the mesh in chunk[0], forming a hierarchy of fractured meshes in chunks[1...] + + \param hMesh the mesh to split + \param meshProcessingParams describes generic mesh processing directives + \param desc describes the slicing surfaces (see FractureCutoutDesc) + \param iCutoutSet the cutout set to use for fracturing (see CutoutSet) + \param sliceDesc used if desc.chunkFracturingMethod = SliceFractureCutoutChunks + \param voronoiDesc used if desc.chunkFracturingMethod = VoronoiFractureCutoutChunks + \param collisionDesc convex hulls will be generated for each chunk using the method. See CollisionDesc. + \param randomSeed seed for the random number generator, to ensure reproducibility. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. + Meant to be set from another thread. + + \return returns true if successful. + */ + virtual bool createChippedMesh + ( + nvidia::ExplicitHierarchicalMesh& hMesh, + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureCutoutDesc& desc, + const FractureTools::CutoutSet& iCutoutSet, + const FractureTools::FractureSliceDesc& sliceDesc, + const FractureTools::FractureVoronoiDesc& voronoiDesc, + const CollisionDesc& collisionDesc, + uint32_t randomSeed, + nvidia::IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Splits the chunk in chunk[chunkIndex], forming a hierarchy of fractured chunks using + slice-mode fracturing. The chunks will be rearranged so that they are in breadth-first order. + + \param hMesh the ExplicitHierarchicalMesh to act upon + \param chunkIndex index of chunk to be split + \param meshProcessingParams used to create a BSP for this chunk + \param desc describes the slicing surfaces (see FractureSliceDesc) + \param collisionDesc convex hulls will be generated for each chunk using the method. See CollisionDesc. + \param randomSeed pointer to a seed for the random number generator, to ensure reproducibility. If NULL, the random number generator will not be re-seeded. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. + Meant to be set from another thread. + + \return returns true if successful. + */ + virtual bool hierarchicallySplitChunk + ( + nvidia::ExplicitHierarchicalMesh& hMesh, + uint32_t chunkIndex, + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureSliceDesc& desc, + const CollisionDesc& collisionDesc, + uint32_t* randomSeed, + nvidia::IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Splits the chunk in chunk[chunkIndex], forming fractured chunks using + Voronoi decomposition fracturing. The chunks will be rearranged so that they are in breadth-first order. + + \param hMesh the ExplicitHierarchicalMesh to act upon + \param chunkIndex index of chunk to be split + \param meshProcessingParams: describes generic mesh processing directives + \param desc describes the voronoi splitting parameters surfaces (see FractureVoronoiDesc) + \param collisionDesc convex hulls will be generated for each chunk using the method. See CollisionDesc. + \param randomSeed pointer to a seed for the random number generator, to ensure reproducibility. If NULL, the random number generator will not be re-seeded. + \param progressListener The user must instantiate an IProgressListener, so that this function may report progress of this operation + \param cancel if not NULL and *cancel is set to true, the root mesh will be restored to its original state, and the function will return at its earliest opportunity. + Meant to be set from another thread. + + \return returns true if successful. + */ + virtual bool voronoiSplitChunk + ( + nvidia::ExplicitHierarchicalMesh& hMesh, + uint32_t chunkIndex, + const FractureTools::MeshProcessingParameters& meshProcessingParams, + const FractureTools::FractureVoronoiDesc& desc, + const CollisionDesc& collisionDesc, + uint32_t* randomSeed, + nvidia::IProgressListener& progressListener, + volatile bool* cancel = NULL + ) = 0; + + /** + Builds a mesh used for slice fracturing, given the noise parameters and random seed. This function is mostly intended + for visualization - to give the user a "typical" slice surface used for fracturing. + */ + virtual bool buildSliceMesh + ( + nvidia::IntersectMesh& intersectMesh, + nvidia::ExplicitHierarchicalMesh& referenceMesh, + const PxPlane& slicePlane, + const FractureTools::NoiseParameters& noiseParameters, + uint32_t randomSeed + ) = 0; + + /** Instantiates an ExplicitHierarchicalMesh */ + virtual nvidia::ExplicitHierarchicalMesh* createExplicitHierarchicalMesh() = 0; + + /** Instantiates an ExplicitHierarchicalMesh::ConvexHull */ + virtual nvidia::ExplicitHierarchicalMesh::ConvexHull* createExplicitHierarchicalMeshConvexHull() = 0; + +}; + +}} // namespaces + + +PX_POP_PACK + +#endif // FRACTURE_TOOLS_API_H diff --git a/APEX_1.4/include/destructible/FractureToolsStructs.h b/APEX_1.4/include/destructible/FractureToolsStructs.h new file mode 100644 index 00000000..1bfecd9c --- /dev/null +++ b/APEX_1.4/include/destructible/FractureToolsStructs.h @@ -0,0 +1,761 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef FRACTURE_TOOLS_STRUCTS_H +#define FRACTURE_TOOLS_STRUCTS_H + +#include "foundation/Px.h" +#include "ExplicitHierarchicalMesh.h" + +PX_PUSH_PACK_DEFAULT + +namespace FractureTools +{ + +/** + These parameters are passed into the fracturing functions to guide mesh processing. +*/ +struct MeshProcessingParameters +{ + /** + If this is true, separate mesh islands will be turned into separate chunks. + Default = false. + */ + bool islandGeneration; + + /** + If this is true, all T-junctions will be removed from the mesh. + Default = false. + */ + bool removeTJunctions; + + /** + The mesh is initially scaled to fit in a unit cube, then (if gridSize is not + zero), the vertices of the scaled mesh are snapped to a grid of size 1/gridSize. + A power of two is recommended. + Default = 65536. + */ + unsigned microgridSize; + + /** + Open mesh handling. Modes: Automatic, Closed, Open (see BSPOpenMode) + Closed mode assumes the mesh is closed and attempts to insert interior faces. + Open mode assumes the mesh is open and does not insert interior faces. + Automatic mode attempts to determine if the mesh is open or closed, and act accordingly. + + Default is Automatic mode. + */ + nvidia::BSPOpenMode::Enum meshMode; + + /** + Debug output verbosity level. The higher the number, the more messages are output. + Default = 0. + */ + int verbosity; + + /** Constructor sets defaults */ + MeshProcessingParameters() + { + setToDefault(); + } + + /** Set default values */ + void setToDefault() + { + islandGeneration = false; + removeTJunctions = false; + microgridSize = 65536; + meshMode = nvidia::BSPOpenMode::Automatic; + verbosity = 0; + } +}; + + +/** + Interface to a "cutout set," used with chippable fracturing. A cutout set is created from a bitmap. The + result is turned into cutouts which are applied to the mesh. For example, a bitmap which looks like a brick + pattern will generate a cutout for each "brick," forming the cutout set. + + Each cutout is a 2D entity, meant to be projected onto various faces of a mesh. They are represented + by a set of 2D vertices, which form closed loops. More than one loop may represent a single cutout, if + the loops are forced to be convex. Otherwise, a cutout is represented by a single loop. +*/ +class CutoutSet +{ +public: + /** Returns the number of cutouts in the set. */ + virtual uint32_t getCutoutCount() const = 0; + + /** + Applies to the cutout indexed by cutoutIndex: + Returns the number of vertices in the cutout. + */ + virtual uint32_t getCutoutVertexCount(uint32_t cutoutIndex) const = 0; + + /** + Applies to the cutout indexed by cutoutIndex: + Returns the number of loops in this cutout. + */ + virtual uint32_t getCutoutLoopCount(uint32_t cutoutIndex) const = 0; + + /** + Applies to the cutout indexed by cutoutIndex: + Returns the vertex indexed by vertexIndex. (Only the X and Y coordinates are used.) + */ + virtual const physx::PxVec3& getCutoutVertex(uint32_t cutoutIndex, uint32_t vertexIndex) const = 0; + + /** + Applies to the cutout indexed by cutoutIndex: + Returns the number of vertices in the loop indexed by loopIndex. + */ + virtual uint32_t getCutoutLoopSize(uint32_t coutoutIndex, uint32_t loopIndex) const = 0; + + /** + Applies to the cutout indexed by cutoutIndex: + Returns the vertex index of the vertex indexed by vertexNum, in the loop + indexed by loopIndex. + */ + virtual uint32_t getCutoutLoopVertexIndex(uint32_t cutoutIndex, uint32_t loopIndex, uint32_t vertexNum) const = 0; + + /** + Applies to the cutout indexed by cutoutIndex: + Returns the flags of the vertex indexed by vertexNum, in the loop + indexed by loopIndex. + */ + virtual uint32_t getCutoutLoopVertexFlags(uint32_t cutoutIndex, uint32_t loopIndex, uint32_t vertexNum) const = 0; + + /** + Whether or not this cutout set is to be tiled. + */ + virtual bool isPeriodic() const = 0; + + /** + The dimensions of the fracture map used to create the cutout set. + */ + virtual const physx::PxVec2& getDimensions() const = 0; + + /** Serialization */ + //virtual void serialize(physx::PxFileBuf& stream) const = 0; + //virtual void deserialize(physx::PxFileBuf& stream) = 0; + + /** Releases all memory and deletes itself. */ + virtual void release() = 0; + +protected: + /** Protected destructor. Use the release() method. */ + virtual ~CutoutSet() {} +}; + + +/** + NoiseParameters + These parameters are used to build a splitting surface. +*/ +struct NoiseParameters +{ + /** + Size of the fluctuations, relative to mesh size + */ + float amplitude; + + /** + Noise frequencey relative to 1/(grid spacing). On scales much smaller than this, the function is smooth. + On scales much large, the function looks uncorrelated + */ + float frequency; + + /** + Suggested number of grid elements across the mesh. The actual number may vary depending + on the mesh's proportions. + */ + int gridSize; + + /** + Noise function to use. This parameter is currently unused. + Noise is generated by superposition of many fourier modes in random directions, + with frequencies randomly chosen in a band around the input frequency, + */ + int type; + + /** Constructor sets defaults */ + NoiseParameters() + { + setToDefault(); + } + + /** + Set default values: + + amplitude = 0.0f; + frequency = 0.25f; + gridSize = 10; + type = 0; + */ + void setToDefault() + { + amplitude = 0.0f; + frequency = 0.25f; + gridSize = 10; + type = 0; + } +}; + + +/** + SliceParameters + + The slicing parameters for X, Y, and Z slicing of a mesh. +*/ +struct SliceParameters +{ + /** + Which axis order to slice the mesh. + This only matters if there is randomness in the slice surface. + */ + enum Order + { + XYZ, + YZX, + ZXY, + ZYX, + YXZ, + XZY, + Through + }; + + /** The slicing order (see the Order enum) */ + unsigned order; + + /** How many times to slice along each axis */ + unsigned splitsPerPass[3]; + + /** + Variation in slice position along each axis. This is a relative quantity. + linearVariation[axis] = 0 means the slicing offsets are evenly spaced across the mesh along the axis. + linearVariation[axis] = 1 means the slicing offsets are randomly chosen in a range of width 1/(splitsPerPass[axis]+1) + times the width of the mesh along the axis. + */ + float linearVariation[3]; + + /** + Variation in the slice surface angle along each axis. + 0 variation means the slice surfaces are axis-aligned. Otherwise, the surface normal will be varied randomly, + with angle to the axis somewhere within the given variation (in radians). + */ + float angularVariation[3]; + + /** The noise for each slicing direction */ + NoiseParameters noise[3]; + + /** Constructor sets defaults */ + SliceParameters() + { + setToDefault(); + } + + /** Sets all NoiseParameters to their defaults: + order = XYZ; + splitsPerPass[0] = splitsPerPass[1] = splitsPerPass[2] = 1; + linearVariation[0] = linearVariation[1] = linearVariation[2] = 0.1f; + angularVariation[0] = angularVariation[1] = angularVariation[2] = 20.0f*3.1415927f/180.0f; + noise[0].setToDefault(); + noise[1].setToDefault(); + noise[2].setToDefault(); + */ + void setToDefault() + { + order = XYZ; + splitsPerPass[0] = splitsPerPass[1] = splitsPerPass[2] = 1; + linearVariation[0] = linearVariation[1] = linearVariation[2] = 0.1f; + angularVariation[0] = angularVariation[1] = angularVariation[2] = 20.0f * 3.1415927f / 180.0f; + noise[0].setToDefault(); + noise[1].setToDefault(); + noise[2].setToDefault(); + } +}; + + +/** + FractureSliceDesc + + Descriptor for slice-mode fracturing. +*/ +struct FractureSliceDesc +{ + /** How many times to recurse the slicing process */ + unsigned maxDepth; + + /** Array of slice parameters; must be of length maxDepth */ + SliceParameters* sliceParameters; + + /** + If this is true, the targetProportions (see below) will be used. + */ + bool useTargetProportions; + + /** + If useTargetProportions is true, the splitsPerPass values will not necessarily be used. + Instead, the closest values will be chosen at each recursion of slicing, in order to make + the pieces match the target proportions as closely as possible. + + Note: the more noise there is in the slicing surfaces, the less accurate these proportions will be. + */ + float targetProportions[3]; + + /** + Smallest size allowed for chunks, as measured by their bounding box widths along the x, y, and z axes. + The sizes are interpreted as fractions of the unfractured mesh's bounding box width. + Chunks created by fracturing which are smaller than this limit will be removed. Note - this will leave holes at the given depth. + Default = (0,0,0), which disables this feature. + */ + float minimumChunkSize[3]; + + /** + Material application descriptor used for each slice axis. + */ + nvidia::FractureMaterialDesc materialDesc[3]; + + /** + If instanceChunks is true, corresponding chunks in different destructible actors will be instanced. + */ + bool instanceChunks; + + /** + If true, slice geometry and noise will be stored in a separate displacement offset buffer. + */ + bool useDisplacementMaps; + + /** Enum describing creation of displacement maps. */ + enum NoiseMode + { + NoiseWavePlane = 0, + NoisePerlin2D, + NoisePerlin3D, + + NoiseModeCount + }; + + /** + The noise mode. If displacement maps are enabled, NoisePerlin3D will be used. + */ + unsigned noiseMode; + + /** Constructor sets defaults */ + FractureSliceDesc() + { + setToDefault(); + } + + /** + Sets the default values: + + maxDepth = 0; + sliceParameters = NULL; + useTargetProportions = false; + targetProportions[0..2] = 1.0f; + minimumChunkSize[0..2] = 0.0f; + materialDesc[0..2].setToDefault(); + instanceChunks = false; + useDisplacementMaps = false; + noiseMode = NoiseWavePlane; + */ + void setToDefault() + { + maxDepth = 0; + sliceParameters = NULL; + useTargetProportions = false; + for (int i = 0; i < 3; ++i) + { + targetProportions[i] = 1.0f; + minimumChunkSize[i] = 0.0f; + materialDesc[i].setToDefault(); + } + instanceChunks = false; + useDisplacementMaps = false; + noiseMode = NoiseWavePlane; + } +}; + + +/** + CutoutParameters + + Parameters for a single cutout direction. +*/ +struct CutoutParameters +{ + /** + The depth to apply cutout fracturing. + 0 has a special value; it means cut all the way through + */ + float depth; + + /** + Material application descriptor used for the cutout direction. + Note: The backface slice will use the U-direction and UV offset specified in each descriptor, however the cutout slices (surrounding + each cutout chunk) will ignore these fields (only using the UV scale). + */ + nvidia::FractureMaterialDesc materialDesc; + + /** + Describes the characteristics of the backface cutting surface (along the various cutout directions). + If the noise is 0, the cutting surface will be a plane. Otherwise, there will be some variation, + or roughness, to the surface. + */ + NoiseParameters backfaceNoise; + + /** + Describes the characteristics of the perimeter cutting surfaces (for the various cutout directions). + If the noise is 0, the cutting surface will smooth. Otherwise, there will be some variation, + or roughness, to the surface. + + Note: this noise is applied only to the graphics of the cutout chunks. The chunks' collision volumes AND the chunks' + children (if fractured further) will NOT be affected by this noise. + */ + NoiseParameters edgeNoise; + + /** Constructor sets defaults */ + CutoutParameters() + { + setToDefault(); + } + + /** + Set default values: + + depth = 1.0f; + backfaceNoise.setToDefault(); + edgeNoise.setToDefault(); + materialDesc.setToDefault(); + */ + void setToDefault() + { + depth = 1.0f; + backfaceNoise.setToDefault(); + materialDesc.setToDefault(); + edgeNoise.setToDefault(); + } +}; + + +/** + FractureCutoutDesc + + Descriptor for cutout-mode (chippable) fracturing. +*/ +struct FractureCutoutDesc +{ + /** Enum describing the directions to apply cutout fracturing. */ + enum Directions + { + UserDefined = 0, // If no flags are set, the cutout direction is taken from userDefinedDirection + + NegativeX = 1 << 0, + PositiveX = 1 << 1, + NegativeY = 1 << 2, + PositiveY = 1 << 3, + NegativeZ = 1 << 4, + PositiveZ = 1 << 5, + + DirectionCount = 6 + }; + + /** The directions to apply cutout fracturing. (See the Directions enum.) */ + unsigned directions; + + /** + The order in which to apply each cutout direction. + The direction in directionOrder[0] is applied first, in directionOrder[1], second, and so on. + */ + unsigned directionOrder[DirectionCount]; + + /** Cutout parameters used for the various pre-defined cutout directions. */ + CutoutParameters cutoutParameters[DirectionCount]; + + /** + The cutout direction if directions = 0. When this is used, it must be have non-zero length (it will be + normalized internally), and userUVMapping must be set (this may be done with AssetAuthoring::calculateCutoutUVMapping). + */ + physx::PxVec3 userDefinedDirection; + + /** The UV mapping used if directons = 0 (along with userDefinedDirection). */ + physx::PxMat33 userUVMapping; + + /** Cutout parameters used if user-defined (UV-based) cutout fracturing is selected by setting directions = 0 */ + CutoutParameters userDefinedCutoutParameters; + + /** Enum describing the instancing mode. */ + enum InstancingMode + { + DoNotInstance, + InstanceCongruentChunks, + InstanceAllChunks, + + InstanceModeCount + }; + + /** + The instancing mode. + */ + unsigned instancingMode; + + /** + If tileFractureMap is true, the map will be tiled across the destructible. + */ + bool tileFractureMap; + + /** + The U,V width of the fracture map when instancing chunks + */ + physx::PxVec2 uvTileSize; + + /** + If true, non-convex cutouts will be split into convex ones. + */ + bool splitNonconvexRegions; + + /** + Fracturing to apply to cutout chunks (if any), to break them down further. + Current options include none, slice fracturing, and voronoi fracturing. + */ + enum CutoutChunkFracturingMethod + { + DoNotFractureCutoutChunks, + SliceFractureCutoutChunks, + VoronoiFractureCutoutChunks, + + CutoutChunkFracturingMethodCount + }; + + /** + If true, slice-mode fracturing will be applied to each cutout piece. + The cutout function must be provided with a FractureSliceDesc as well to describe + the slice parameters. These parameters, however, must be interpreted from the + point of view of the cutout direction. That is, X and Y slice parameters will be + used to slice along the cutout faces. The Z slice parameters will be used to slice + into the cutout faces. + */ + unsigned chunkFracturingMethod; + + /** + If true, the backface and cutouts will be trimmed if (a) backface noise is non-zero or + (b) the collision hull is something other than the mesh convex hull ("Wrap Graphics Mesh"). + Trimming is done by intersecting the face slice plane (without added noise) with the backface + and cutouts. + Default is true. + */ + bool trimFaceCollisionHulls; + + /** Scale to apply to the X coordinates of the cutout set (along the various cutout directions). */ + float cutoutWidthScale[DirectionCount]; + + /** Scale to apply to the Y coordinates of the cutout set (along the various cutout directions). */ + float cutoutHeightScale[DirectionCount]; + + /** Offset to apply to the X coordinates of the cutout set (along the various cutout directions). */ + float cutoutWidthOffset[DirectionCount]; + + /** Offset to apply to the Y coordinates of the cutout set (along the various cutout directions). */ + float cutoutHeightOffset[DirectionCount]; + + /** If true, the cutout map will be flipped in the X direction (along the various cutout directions). */ + bool cutoutWidthInvert[DirectionCount]; + + /** If true, the cutout map will be flipped in the Y direction (along the various cutout directions). */ + bool cutoutHeightInvert[DirectionCount]; + + /** The interpreted size of the cutout map in the X direction */ + float cutoutSizeX; + + /** The interpreted size of the cutout map in the Y direction */ + float cutoutSizeY; + + /** + Threshold angle to merge (smoothe) vertex normals around cutout, in degrees. + If the exterior angle between two facets of a cutout region no more than this, the vertex normals and tangents will be + averaged at the facet interface. A value of 0 effectively disables smoothing. + Default value = 60 degrees. + */ + float facetNormalMergeThresholdAngle; + + /** Constructor sets defaults */ + FractureCutoutDesc() + { + setToDefault(); + } + + /** + Set default values: + + directions = 0; + directionOrder[0..5] = {NegativeX, .., PositiveZ}; + cutoutParameters[0..5].setToDefault(); + userDefinedDirection= physx::PxVec3(0.0f); + userUVMapping = physx::PxMat33(physx::PxIdentity); + userDefinedCutoutParameters.setToDefault(); + instancingMode = DoNotInstance; + tileFractureMap = false; + uvTileSize = (0.0f,0.0f) + cutoutParameters[0..5].setToDefault(); + cutoutWidthScale[0..5] = 1.0f; + cutoutHeightScale[0..5] = 1.0f; + cutoutWidthOffset[0..5] = 0.0f; + cutoutHeightOffset[0..5] = 0.0f; + cutoutWidthInvert[0..5] = false; + cutoutHeightInvert[0..5] = false; + cutoutSizeX = 1.0f; + cutoutSizeY = 1.0f; + facetNormalMergeThresholdAngle = 60.0f; + splitNonconvexRegions = false; + chunkFracturingMethod = DoNotFractureCutoutChunks; + trimFaceCollisionHulls = true; + */ + void setToDefault() + { + directions = 0; + userDefinedDirection= physx::PxVec3(0.0f); + userUVMapping = physx::PxMat33(physx::PxIdentity); + userDefinedCutoutParameters.setToDefault(); + instancingMode = DoNotInstance; + tileFractureMap = false; + uvTileSize = physx::PxVec2(0.0f); + for (uint32_t i = 0; i < DirectionCount; ++i) + { + directionOrder[i] = 1u << i; + cutoutParameters[i].setToDefault(); + cutoutWidthScale[i] = 1.0f; + cutoutHeightScale[i] = 1.0f; + cutoutWidthOffset[i] = 0.0f; + cutoutHeightOffset[i] = 0.0f; + cutoutWidthInvert[i] = false; + cutoutHeightInvert[i] = false; + } + cutoutSizeX = 1.0f; + cutoutSizeY = 1.0f; + facetNormalMergeThresholdAngle = 60.0f; + splitNonconvexRegions = false; + chunkFracturingMethod = DoNotFractureCutoutChunks; + trimFaceCollisionHulls = true; + } +}; + + +/** + FractureVoronoiDesc + + Descriptor for Voronoi decomposition fracturing. +*/ +struct FractureVoronoiDesc +{ + /** + Number of cell sites in the sites array. Must be positive. + */ + unsigned siteCount; + + /** + Array of cell sites. The length of this array is given by siteCount. + */ + const physx::PxVec3* sites; + + /** + Array of chunk indices to associate with each site. If this pointer is NULL, then all sites will be used to split + all chunks relevant to the splitting operation. Otherwise, the chunkIndices array must be of length siteCount. + */ + const uint32_t* chunkIndices; + + /** + Describes the characteristics of the interior surfaces. + If the noise is 0, the cutting surface will smooth. Otherwise, there will be some variation, or roughness, to the surface. + + Note: this noise is applied only to the graphics of the chunks. The chunks' collision volumes AND the chunks' + children (if fractured further) will NOT be affected by this noise. + */ + NoiseParameters faceNoise; + + /** + If instanceChunks is true, corresponding chunks in different destructible actors will be instanced. + */ + bool instanceChunks; + + /** + If true, slice geometry and noise will be stored in a separate displacement offset buffer. + */ + bool useDisplacementMaps; + + /** Enum describing creation of displacement maps. */ + enum NoiseMode + { + NoiseWavePlane = 0, + NoisePerlin2D, + NoisePerlin3D, + + NoiseModeCount + }; + + /** + The noise mode. If displacement maps are enabled, NoisePerlin3D will be used. + */ + unsigned noiseMode; + + /** + Smallest size allowed for chunks, as measured by their bounding sphere diameters. + The sizes are interpreted as fractions of the unfractured mesh's bounding sphere diameter. + Chunks created by fracturing which are smaller than this limit will be removed. Note - this will leave holes at the given depth. + Default = 0, which disables this feature. + */ + float minimumChunkSize; + + /** + Material application descriptor used for each slice. + Note: the U-direction and UV offset in the descriptor will be ignored - UV mapping is done in arbitrary orientation and translation on each chunk face. + */ + nvidia::FractureMaterialDesc materialDesc; + + + /** Constructor sets defaults */ + FractureVoronoiDesc() + { + setToDefault(); + } + + /** + Sets the default values: + + siteCount = 0; + sites = NULL; + chunkIndices = NULL; + faceNoise.setToDefault(); + instanceChunks = false; + useDisplacementMaps = false; + noiseMode = NoiseWavePlane; + minimumChunkSize = 0.0f; + materialDesc.setToDefault(); + */ + void setToDefault() + { + siteCount = 0; + sites = NULL; + chunkIndices = NULL; + faceNoise.setToDefault(); + instanceChunks = false; + useDisplacementMaps = false; + noiseMode = NoiseWavePlane; + minimumChunkSize = 0.0f; + materialDesc.setToDefault(); + } +}; + + +} // namespace FractureTools + + +PX_POP_PACK + +#endif // FRACTURE_TOOLS_H diff --git a/APEX_1.4/include/destructible/ModuleDestructible.h b/APEX_1.4/include/destructible/ModuleDestructible.h new file mode 100644 index 00000000..863d2740 --- /dev/null +++ b/APEX_1.4/include/destructible/ModuleDestructible.h @@ -0,0 +1,880 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_DESTRUCTIBLE_H +#define MODULE_DESTRUCTIBLE_H + +#include "foundation/Px.h" +#include "foundation/PxBounds3.h" +#include "Module.h" + +#ifndef APEX_RUNTIME_FRACTURE +#define APEX_RUNTIME_FRACTURE 1 +#else +#undef APEX_RUNTIME_FRACTURE +#define APEX_RUNTIME_FRACTURE 0 +#endif + +#if PX_ANDROID +#undef APEX_RUNTIME_FRACTURE +#define APEX_RUNTIME_FRACTURE 0 +#endif + +namespace physx +{ +class PxRigidActor; +class PxRigidDynamic; +class PxScene; +} + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class DestructibleAsset; +class DestructibleAssetAuthoring; +class DestructibleActor; +class DestructibleActorJoint; +class DestructibleChunkDesc; +class DestructibleActorDesc; +class DestructibleActorJointDesc; + +/** + Flags returned by an UserChunkReport +*/ +struct ApexChunkFlag +{ + /** + Enum of apex chunk flag + */ + enum Enum + { + /** The chunk is dynamic */ + DYNAMIC = 1 << 0, + + /** The chunk has environmental support, so will remain kinematic until fractured */ + EXTERNALLY_SUPPORTED = 1 << 1, + + /** Only true if EXTERNALLY_SUPPORTED is true. In addition, this means that it gained support via static geometry overlap. */ + WORLD_SUPPORTED = 1 << 2, + + /** The chunk has been fractured */ + FRACTURED = 1 << 3, + + /** The chunk has been destroyed because the PxActor FIFO was full */ + DESTROYED_FIFO_FULL = 1 << 4, + + /** The chunk has been destroyed because it has exceeded the maximum debris lifetime */ + DESTROYED_TIMED_OUT = 1 << 5, + + /** The chunk has been destroyed because it has exceeded the maximum debris distance */ + DESTROYED_EXCEEDED_MAX_DISTANCE = 1 << 6, + + /** The destroyed chunk has generated crumble particles */ + DESTROYED_CRUMBLED = 1 << 7, + + /** The destroyed chunk has moved beyond the destructible actor's valid bounds. */ + DESTROYED_LEFT_VALID_BOUNDS = 1 << 8, + + /** The destroyed chunk has moved beyond the user-defined bounding box. */ + DESTROYED_LEFT_USER_BOUNDS = 1 << 9, + + /** The destroyed chunk has moved into the user-defined bounding box. */ + DESTROYED_ENTERED_USER_BOUNDS = 1 << 10 + }; +}; + +/** + Per-chunk data returned in DamageEventReportData +*/ +struct ChunkData +{ + /** The index of the chunk within the destructible asset */ + uint32_t index; + + /** The hierarchy depth of the chunk */ + uint32_t depth; + + /** + The chunk's axis-aligned bounding box, in world space. + */ + PxBounds3 worldBounds; + + /** + How much damage the chunk has taken + */ + float damage; + + /** + Several flags holding chunk information + \see ApexChunkFlag + */ + uint32_t flags; +}; + +/** + Per-actor damage event data returned by an UserChunkReport +*/ +struct DamageEventReportData +{ + /** + The DestructibleActor instance that these chunks belong to + */ + DestructibleActor* destructible; + + /** + Damage event hitDirection in world space. + */ + PxVec3 hitDirection; + + /** + The axis-aligned bounding box of all chunk fractures caused by this damage event, + which have flags that overlap the module's chunkReportBitMask (see ModuleDestructible::setChunkReportBitMask). + */ + PxBounds3 worldBounds; + + /** + Total number of fracture events caused by this damage event, + which have flags that overlap the module's chunkReportBitMask (see ModuleDestructible::setChunkReportBitMask). + */ + uint32_t totalNumberOfFractureEvents; + + /** + Min depth of chunk fracture events caused by this damage event, + which have flags that overlap the module's chunkReportBitMask (see ModuleDestructible::setChunkReportBitMask). + */ + uint16_t minDepth; + + /** + Max depth of chunk fracture events caused by this damage event, + which have flags that overlap the module's chunkReportBitMask (see ModuleDestructible::setChunkReportBitMask). + */ + uint16_t maxDepth; + + /** + Array of chunk fracture event data for all chunks above a size threshold, which have flags that overlap the + module's chunkReportBitMask (see ModuleDestructible::setChunkReportBitMask). Currently + the size cutoff is determined by the ModuleDestructible's chunkReportMaxFractureEventDepth (See + ModuleDestructible::setChunkReportMaxFractureEventDepth). All chunks up to that depth, but no deeper, + are reported in this list. The size of this array is given by fractureEventListSize. fractureEventList may + be NULL if fractureEventListSize = 0. + */ + const ChunkData* fractureEventList; + + /** + Size of the fractureEventList array. This may be less than totalNumberOfFractureEvents + if some of the fracture events involve chunks which do not meet the size criterion + described in the notes for the fractureEventList array. + */ + uint32_t fractureEventListSize; + + /** + Other PhysX actor that caused damage to DamageEventReportData. + */ + physx::PxActor const* impactDamageActor; + + + /** + Impact damage position in world-space. + */ + PxVec3 hitPosition; + + /** + User data from applyDamage or applyRadiusDamage. + */ + void* appliedDamageUserData; +}; + + +/** + An event structure for an optional chunk event buffer. Contains a chunk index and an event field. + + Note: currently the only chunk state event is for visibility changes, so the VisibilityChanged bit will always be set when this struct is used. +*/ +struct DestructibleChunkEvent +{ + /** + Enum of event mask + */ + enum EventMask + { + VisibilityChanged = (1 << 0), + ChunkVisible = (1 << 1) + }; + + uint16_t chunkIndex; ///< Chunk index + uint16_t event; ///< Event +}; + + +/** + Chunk state event data pushed to the user, if the user requests it via ModuleDestructible::scheduleChunkStateEventCallback. +*/ +struct ChunkStateEventData +{ + /** + The DestructibleActor instance that these chunks belong to + */ + DestructibleActor* destructible; + + /** + Array of chunk state event data collected since the last UserChunkReport::onStateChangeNotify call. + */ + const DestructibleChunkEvent* stateEventList; + + /** + Size of the stateEventList array + */ + uint32_t stateEventListSize; +}; + + +/** + UserChunkReport - API for a user-defined callback to get information about fractured or damaged chunks +*/ +class UserChunkReport +{ +public: + /** + User implementation of UserChunkReport must overload this function. + This function will get called when a chunk is fractured or destroyed. + See the definition of DamageEventReportData for the information provided + to the function. + */ + virtual void onDamageNotify(const DamageEventReportData& damageEvent) = 0; + + /** + User implementation of UserChunkReport must overload this function. + This function gets called when chunk visibility changes occur, if the user has selected + this option via ModuleDestructible::scheduleChunkStateEventCallback. + See the definition of ChunkStateEventData for the information provided + to the function. + + *Please note* the user must also set the NxParameterized actor parameter 'createChunkEvents' to true, + on individual destructible actors, to receive state change events from that actor. + */ + virtual void onStateChangeNotify(const ChunkStateEventData& visibilityEvent) = 0; + + /** + Called when an DestructibleActor contains no visible chunks. If the user returns true, + APEX will release the destructible actor. If the user returns false, they should not + release the destructible actor from within the callback, and instead must wait until + the completion of Scene::fetchResults(). + + Default implementation returns false, which is the legacy behavior. + + If this class (UserChunkReport) is not implemented, APEX will not destroy the DestructibleActor. + */ + virtual bool releaseOnNoChunksVisible(const DestructibleActor* destructible) { PX_UNUSED(destructible); return false; } + + /** + List of destructible actors that have just become awake (any associated PhysX actor has become awake). + **/ + virtual void onDestructibleWake(DestructibleActor** destructibles, uint32_t count) = 0; + + /** + List of destructible actors that have just gone to sleep (all associated PhysX actors have gone to sleep). + **/ + virtual void onDestructibleSleep(DestructibleActor** destructibles, uint32_t count) = 0; + +protected: + virtual ~UserChunkReport() {} +}; + + +/** + Particle buffer data returned with UserChunkParticleReport +*/ +struct ChunkParticleReportData +{ + /** Position buffer. The length of this buffer is given by positionCount. */ + const PxVec3* positions; + + /** The array length of the positions buffer. */ + uint32_t positionCount; + + /** + Velocity buffer. The length of this buffer is given by velocityCount. + N.B.: The velocity buffer might not have the same length as the positions buffer. + It will be one of three lengths: + velocityCount = 0: There is no velocity data with these particles. + velocityCount = 1: All of the particle velocities are the same, given by *velocities. + velocityCount = positionCount: Each particle velocity is given. + */ + const PxVec3* velocities; + + /** The array length of the velocities buffer. (See the description above.)*/ + uint32_t velocityCount; +}; + +/** + UserChunkParticleReport - API for a user-defined callback to get particle buffer data when a chunk crumbles or emits dust particles. + Note - only crumble emitters are implemented in 1.2.0 +*/ +class UserChunkParticleReport +{ +public: + /** + User implementation of UserChunkParticleReport must overload this function. + This function will get called when an DestructibleActor generates crumble particle or + dust particle effect data. Crumble particles are generated whenever a chunk is destroyed completely and + the DestructibleActorFlag CRUMBLE_SMALLEST_CHUNKS is set. Dust line particles are + generated along chunk boundaries whenever they are fractured free from other chunks. + + Note - only crumble emitters are implemented in 1.2.0 + */ + virtual void onParticleEmission(const ChunkParticleReportData& particleData) = 0; + +protected: + virtual ~UserChunkParticleReport() {} +}; + + +/** + UserDestructiblePhysXActorReport - API for user-defined callbacks giving notification of PhysX actor creation and release from the + destruction module. +*/ +class UserDestructiblePhysXActorReport +{ +public: + /** Called immediately after a PxActor is created in the Destruction module. */ + virtual void onPhysXActorCreate(const physx::PxActor& actor) = 0; + + /** Called immediately before a PxActor is released in the Destruction module. */ + virtual void onPhysXActorRelease(const physx::PxActor& actor) = 0; +protected: + virtual ~UserDestructiblePhysXActorReport() {} +}; + + +/** + Destructible module constants +*/ +struct ModuleDestructibleConst +{ + /** + Enum for invalid chunk index (-1) + */ + enum Enum + { + /** + When a function returns a chunk index, or takes a chunk index as a parameter, this + value indicates "no chunk." + */ + INVALID_CHUNK_INDEX = -1 + }; +}; + +/** + Render mesh distinction, skinned vs. static +*/ +struct DestructibleActorMeshType +{ + /** + Enum for destructible actor mesh type. + */ + enum Enum + { + Skinned, + Static, + Count + }; +}; + +/** + The core data of Damage Event. It is used for sync damage coloring. +*/ +struct DamageEventCoreData +{ + int32_t chunkIndexInAsset; ///< Which chunk the damage is being applied to (non-range based damage) + PxVec3 position; ///< The position, in world space, where the damage event is originating from. + float damage; ///< The amount of damage + float radius; ///< The radius of the damage, if this is a range based damage event. +}; + +/** + Extended damage event data, used for impact damage reports +*/ +struct ImpactDamageEventData : public DamageEventCoreData +{ + nvidia::DestructibleActor* destructible; ///< The destructible hit by the impacting actor + PxVec3 direction; ///< The position, in world space, from which the damage is applied + physx::PxActor const* impactDamageActor; ///< Other PhysX actor that caused damage +}; + +/** + UserImpactDamageReport - API for a user-defined callback to get a buffer of impact damage events +*/ +class UserImpactDamageReport +{ +public: + /** + User implementation of UserImpactDamageReport must overload this function. + If an instance of this object is passed to ModuleDestructible::setImpactDamageReportCallback, + this function will get called once during ApexScene::fetchResults, passing back an array of + ImpactDamageEventData reporting all impact damage events. + */ + virtual void onImpactDamageNotify(const ImpactDamageEventData* buffer, uint32_t bufferSize) = 0; +}; + +/** + Sync-able Callback Class. +*/ +template<typename DestructibleSyncHeader> +class UserDestructibleSyncHandler +{ +public: + /** + Called when write begins. + */ + virtual void onWriteBegin(DestructibleSyncHeader *& bufferStart, uint32_t bufferSize) = 0; + + /** + Called when write done. + */ + virtual void onWriteDone(uint32_t headerCount) = 0; + + /** + Called when pre-process read begins. + */ + virtual void onPreProcessReadBegin(DestructibleSyncHeader *& bufferStart, uint32_t & bufferSize, bool & continuePointerSwizzling) = 0; + + /** + Called when pre-process read done. + */ + virtual void onPreProcessReadDone(uint32_t headerCount) = 0; + + /** + Called when read begins. + */ + virtual void onReadBegin(const DestructibleSyncHeader *& bufferStart) = 0; + + /** + Called when read done. + */ + virtual void onReadDone(const char * debugMessage) = 0; +protected: + virtual ~UserDestructibleSyncHandler() {} +}; + +/*** Sync-able Damage Data ***/ + +struct DamageEventUnit; +/** + Damage event header. +*/ +struct DamageEventHeader +{ + uint32_t userActorID; ///< User actor ID + uint32_t damageEventCount; ///< Damage event count + DamageEventUnit * damageEventBufferStart; ///< damage event buffer size + DamageEventHeader * next; ///< Pointer to next DamageEventHeader structure +}; + +/** + Damage event unit. +*/ +struct DamageEventUnit +{ + uint32_t chunkIndex; ///< Chunk index + uint32_t damageEventFlags; ///< Damage event flags + float damage; ///< Damage value + float momentum; ///< Momentum + float radius; ///< Radius + PxVec3 position; ///< Position + PxVec3 direction; ///< Direction +}; + +/*** Sync-able Fracture Data ***/ + +struct FractureEventUnit; + +/** + Fracture event header. +*/ +struct FractureEventHeader +{ + uint32_t userActorID; ///< User actor ID + uint32_t fractureEventCount; ///< Fracture event count + FractureEventUnit * fractureEventBufferStart; ///< Fracture event buffer start + FractureEventHeader * next; ///< Pointer to next FractureEventHeader structure +}; + +/** + Fracture event unit. +*/ +struct FractureEventUnit +{ + uint32_t chunkIndex; ///< Chunk index + uint32_t fractureEventFlags; ///< Fracture event flags + PxVec3 position; ///< Position + PxVec3 direction; ///< Direction + PxVec3 impulse; ///< Impulse +}; + +/*** Sync-able Transform Data ***/ + +struct ChunkTransformUnit; + +/** + Chunk transform header. +*/ +struct ChunkTransformHeader +{ + uint32_t userActorID; ///< User actor ID + uint32_t chunkTransformCount; ///< Chunk transform count + ChunkTransformUnit * chunkTransformBufferStart; ///< Chunk transform buffer start + ChunkTransformHeader * next; ///< Pointer to next ChunkTransformHeader structure +}; + +/** + Chunk transform unit. +*/ +struct ChunkTransformUnit +{ + uint32_t chunkIndex; ///< Chunk index + PxVec3 chunkPosition; ///< Position + PxQuat chunkOrientation; ///< Chunk orientation +}; + + +/** + Flags for DestructibleActor::raycast() +*/ +struct DestructibleActorRaycastFlags +{ + /** + Enum of destructible actor raycast flags. + */ + enum Enum + { + NoChunks = (0), + StaticChunks = (1 << 0), + DynamicChunks = (1 << 1), + + AllChunks = StaticChunks | DynamicChunks, + + SegmentIntersect = (1 << 2), ///< Do not consider intersect times > 1 + + ForceAccurateRaycastsOn = (1 << 3), + ForceAccurateRaycastsOff = (1 << 4), + }; +}; + + +/** + Enum to control when callbacks are fired. +*/ +struct DestructibleCallbackSchedule +{ + /** + Enum of destructible callback schedule + */ + enum Enum + { + Disabled = (0), + BeforeTick, ///< Called by the simulation thread + FetchResults, ///< Called by an application thread + + Count + }; +}; + + +/** + Descriptor used to create the Destructible APEX module. +*/ +class ModuleDestructible : public Module +{ +public: + /** Object creation */ + + /** + Create an DestructibleActorJoint from the descriptor. (See DestructibleActorJoint and + DestructibleActorJointDesc.) + This module will own the DestructibleActorJoint, so that any DestructibleAsset created by it will + be released when this module is released. You may also call the DestructibleActorJoint's release() + method, as long as the DestructibleActorJoint is still valid in the scene. (See isDestructibleActorJointActive()) + */ + virtual DestructibleActorJoint* createDestructibleActorJoint(const DestructibleActorJointDesc& desc, Scene& scene) = 0; + + /** + Query the module on the validity of a created DestructibleActorJoint. + A DestructibleActorJoint will no longer be valid when it is destroyed in the scene, in which case the module calls the DestructibleActorJoint's release(). + Therefore, this DestructibleActorJoint should no longer be referenced if it is not valid. + */ + virtual bool isDestructibleActorJointActive(const DestructibleActorJoint* candidateJoint, Scene& apexScene) const = 0; + + /** LOD */ + + /** + The maximum number of allowed PxActors which represent dynamic groups of chunks. If a fracturing + event would cause more PxActors to be created, then some PxActors are released and the chunks they + represent destroyed. The PxActors released to make room for others depends on the priority mode. + If sorting by benefit (see setSortByBenefit), then chunks with the lowest LOD benefit are released + first. Otherwise, oldest chunks are released first. + */ + virtual void setMaxDynamicChunkIslandCount(uint32_t maxCount) = 0; + + /** + The maximum number of allowed visible chunks in the scene. If a fracturing + event would cause more chunks to be created, then PxActors are released to make room for the + created chunks. The priority for released PxActors is the same as described in + setMaxDynamicChunkIslandCount. + */ + virtual void setMaxChunkCount(uint32_t maxCount) = 0; + + /** + Instead of keeping the youngest PxActors, keep the greatest benefit PxActors if sortByBenefit is true. + By default, this module does not sort by benefit. That is, oldest PxActors are released first. + */ + virtual void setSortByBenefit(bool sortByBenefit) = 0; + + /** + Deprecated + */ + virtual void setValidBoundsPadding(float pad) = 0; + + /** + Effectively eliminates the deeper level (smaller) chunks from DestructibleAssets (see + DestructibleAsset). If maxChunkDepthOffset = 0, all chunks can be fractured. If maxChunkDepthOffset = 1, + the depest level (smallest) chunks are eliminated, etc. This prevents too many chunks from being + formed. In other words, the higher maxChunkDepthOffset, the lower the "level of detail." + */ + virtual void setMaxChunkDepthOffset(uint32_t maxChunkDepthOffset) = 0; + + /** + Every destructible asset defines a min and max lifetime, and maximum separation distance for its chunks. + Chunk islands are destroyed after this time or separation from their origins. This parameter sets the + lifetimes and max separations within their min-max ranges. The valid range is [0,1]. Default is 0.5. + */ + virtual void setMaxChunkSeparationLOD(float separationLOD) = 0; + + + /** General */ + /** + Sets the user chunk fracture/destroy callback. See UserChunkReport. + Set to NULL (the default) to disable. APEX does not take ownership of the report object. + */ + virtual void setChunkReport(UserChunkReport* chunkReport) = 0; + + /** + Sets the user impact damage report callback. See UserImpactDamageReport. + Set to NULL (the default) to disable. APEX does not take ownership of the report object. + */ + virtual void setImpactDamageReportCallback(UserImpactDamageReport* impactDamageReport) = 0; + + /** + Set a bit mask of flags (see ApexChunkFlag) for the fracture/destroy callback (See setChunkReport.) + Fracture events with flags that overlap this mask will contribute to the DamageEventReportData. + */ + virtual void setChunkReportBitMask(uint32_t chunkReportBitMask) = 0; + + /** + Sets the user callback to receive PhysX actor create/release notifications for destruction-associated PhysX actors. + Set to NULL (the default) to disable. + */ + virtual void setDestructiblePhysXActorReport(UserDestructiblePhysXActorReport* destructiblePhysXActorReport) = 0; + + /** + Set the maximum depth at which individual chunk fracture events will be reported in an DamageEventReportData's + fractureEventList through the UserChunkReport. Fracture events deeper than this will still contribute to the + DamageEventReportData's worldBounds and totalNumberOfFractureEvents. + */ + virtual void setChunkReportMaxFractureEventDepth(uint32_t chunkReportMaxFractureEventDepth) = 0; + + /** + Set whether or not the UserChunkReport::onStateChangeNotify interface will be used to deliver visibility + change data to the user. + + Default = DestructibleCallbackSchedule::Disabled. + */ + virtual void scheduleChunkStateEventCallback(DestructibleCallbackSchedule::Enum chunkStateEventCallbackSchedule) = 0; + + /** + Sets the user chunk crumble particle buffer callback. See UserChunkParticleReport. + Set to NULL (the default) to disable. APEX does not take ownership of the report object. + */ + virtual void setChunkCrumbleReport(UserChunkParticleReport* chunkCrumbleReport) = 0; + + /** + Sets the user chunk dust particle buffer callback. See UserChunkParticleReport. + Set to NULL (the default) to disable. APEX does not take ownership of the report object. + + Note - this is a placeholder API. The dust feature is disabled in 1.2.0. + */ + virtual void setChunkDustReport(UserChunkParticleReport* chunkDustReport) = 0; + + /** + PhysX SDK 3.X. + Allows the user to specify an alternative PhysX scene to use for world support calculations. If NULL (the default), + the PhysX scene associated with the Scene will be used. + */ + virtual void setWorldSupportPhysXScene(Scene& apexScene, PxScene* physxScene) = 0; + + /** + PhysX SDK 3.X. + Returns true iff the PxRigidActor was created by the Destructible module. If true, the user must NOT destroy the actor. + */ + virtual bool owns(const PxRigidActor* actor) const = 0; + +#if APEX_RUNTIME_FRACTURE + /** + PhysX SDK 3.X. + Returns true iff the PxShape was created by the runtime fracture system. + */ + virtual bool isRuntimeFractureShape(const PxShape& shape) const = 0; +#endif + + /** + PhysX SDK 3.X. + Given an PxShape, returns the DestructibleActor and chunkIndex which belong to it, + if the shape's PxActor is owned by the Destructible module (see the 'owns' function, above). Otherwise returns NULL. + Useful when a scene query such as a raycast returns a shape. + */ + virtual DestructibleActor* getDestructibleAndChunk(const PxShape* shape, int32_t* chunkIndex = NULL) const = 0; + + /** + Applies damage to all DestructibleActors within the given radius in the apex scene. + damage = the amount of damage at the damage point + momentum = the magnitude of the impulse to transfer to each chunk + position = the damage location + radius = distance from damage location at which chunks will be affected + falloff = whether or not to decrease damage with distance from the damage location. If true, + damage will decrease linearly from the full damage (at zero distance) to zero damage (at radius). + If false, full damage is applied to all chunks within the radius. + */ + virtual void applyRadiusDamage(Scene& scene, float damage, float momentum, + const PxVec3& position, float radius, bool falloff) = 0; + + /** + Lets the user throttle the number of SDK actor creates per frame (per scene) due to destruction, as this can be quite costly. + The default is 0xffffffff (unlimited). + */ + virtual void setMaxActorCreatesPerFrame(uint32_t maxActorsPerFrame) = 0; + + /** + Lets the user throttle the number of fractures processed per frame (per scene) due to destruction, as this can be quite costly. + The default is 0xffffffff (unlimited). + */ + virtual void setMaxFracturesProcessedPerFrame(uint32_t maxFracturesProcessedPerFrame) = 0; + + /** + Set the callback pointers from which APEX will use to return sync-able data. + */ + virtual bool setSyncParams(UserDestructibleSyncHandler<DamageEventHeader> * userDamageEventHandler, UserDestructibleSyncHandler<FractureEventHeader> * userFractureEventHandler, UserDestructibleSyncHandler<ChunkTransformHeader> * userChunkMotionHandler) = 0; + + /** The following functions control the use of legacy behavior. */ + + /** + By default, destruction damage application (either point or radius damage) now use the exact collision bounds + of the chunk to determine damage application. Before, bounding spheres were used on "leaf" chunks (deepest in the + fracture hierarchy) and only the bounding sphere center (effectively radius 0) was used on all chunks higher in the + hierarchy. This led to inconsistent behavior when damaging destructibles at various levels of detail. + + If true is passed into this function, the legacy behavior is restored. + */ + virtual void setUseLegacyChunkBoundsTesting(bool useLegacyChunkBoundsTesting) = 0; + + /** + By default, the BehaviorGroup fields damageSpread.minimumRadius, damageSpread.radiusMultiplier, and + damageSpread.falloffExponent are used for point and radius damage. Impact damage still uses damageToRadius, + but this radius does not scale with the size of the destructible. + + The old, deprecated behavior was to base damage spread upon the damageToRadius field of the BehaviorGroup used + by the chunk. Specifically, damage would spread throughout a damage radius calculated as + radius = damageToRadius * (damage / damageThreshold) * (size of destructible). + + If true is passed into this function, the legacy behavior is restored. + */ + virtual void setUseLegacyDamageRadiusSpread(bool useLegacyDamageRadiusSpread) = 0; + + /** + Sets mass scaling properties in a given apex scene. + + massScale and scaledMassExponent are used for scaling dynamic chunk masses. + The 'real' mass m of a chunk is calculated by the destructible actor's density multiplied by + the total volume of the chunk's (scaled) collision shapes. The mass used in + the simulation is massScale*pow(m/massScale,scaledMassExponent). Values less than 1 have the + effect of reducing the ratio of different masses. The closer scaledMassExponent is to zero, the + more the ratio will be 'flattened.' This helps PhysX converge when there is a very large number + of interacting rigid bodies (such as a pile of destructible chunks). + + massScale valid range: (0,infinity). Default = 1.0. + scaledMassExponent valid range: [0,1]. Default = 0.5. + + Returns true iff the parameters are valid and the apexScene is valid. + */ + virtual bool setMassScaling(float massScale, float scaledMassExponent, Scene& apexScene) = 0; + + /** + If a static PhysX actor is about to be removed, or has just been added, to the scene, then world support may change. + Use this function to notify the destruction module that it may need to reconsider world support in the given volumes. + This may be called multiple times, and the bounds list will accumulate. This list will be processed upon the next APEX + simulate call, and cleared. + */ + virtual void invalidateBounds(const PxBounds3* bounds, uint32_t boundsCount, Scene& apexScene) = 0; + + /** + When applyDamage, or damage from impact, is processed, a rayCast call is used internally to find a more accurate damage position. + This allows the user to specify the rayCast behavior. If no flags are set, no raycasting is done. Raycasting will be peformed against + static or dynamic chunks, or both, depending on the value of flags. The flags are defined by DestructibleActorRaycastFlags::Enum. + + The default flag used is DestructibleActorRaycastFlags::StaticChunks, since static-only raycasts are faster than ones that include + dynamic chunks. + + Note: only the flags DestructibleActorRaycastFlags::NoChunks, StaticChunks, and DynamicChunks are considered. + */ + virtual void setDamageApplicationRaycastFlags(nvidia::DestructibleActorRaycastFlags::Enum flags, Scene& apexScene) = 0; + + /** + In PhysX 3.x, scaling of collision shapes can be done in the shape, not the cooked hull data. As a consequence, each collision hull only needs to be cooked + once. By default, this hull is not scaled from the original data. But if the user desires, the hull can be scaled before cooking. That scale will be removed from + the DestructibleActor's scale before being applied to the shape using the hull. So ideally, this user-set cooking scale does nothing. Numerically, however, + it may have an effect, so we leave it as an option. + + The input scale must be positive in all components. If not, the cooking scale will not be set, and the function returns false. Otherwise, the scale is set and + the function returns true. + */ + virtual bool setChunkCollisionHullCookingScale(const PxVec3& scale) = 0; + + /** + Retrieves the cooking scale used for PhysX3 collision hulls, which can be set by setChunkCollisionHullCookingScale. + */ + virtual PxVec3 getChunkCollisionHullCookingScale() const = 0; + + /** + \brief Get reference to FractureTools object. + */ + virtual class FractureToolsAPI* getFractureTools() const = 0; + +protected: + virtual ~ModuleDestructible() {} +}; + + +#if !defined(_USRDLL) +/** +* If this module is distributed as a static library, the user must call this +* function before calling ApexSDK::createModule("Destructible") +*/ +void instantiateModuleDestructible(); +#endif + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // MODULE_DESTRUCTIBLE_H diff --git a/APEX_1.4/include/emitter/EmitterActor.h b/APEX_1.4/include/emitter/EmitterActor.h new file mode 100644 index 00000000..f6dd83a0 --- /dev/null +++ b/APEX_1.4/include/emitter/EmitterActor.h @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef EMITTER_ACTOR_H +#define EMITTER_ACTOR_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class EmitterAsset; +class EmitterGeomExplicit; +class EmitterLodParamDesc; +class RenderVolume; + +/// Apex emitter actor class. Emits particles within a given shape. +class EmitterActor : public Actor +{ +protected: + virtual ~EmitterActor() {} + +public: + + /// This is an optional user validation callback interface. + /// If the application wants to confirm/verify all emitted particles they can provide + /// this callback interface by using the setApexEmitterValidateCallback method. + class EmitterValidateCallback + { + public: + /** + \brief This application callback is used to verify an emitted particle position. + + If the user returns false, then the particle will not be emitted. If the user returns true + if will be emitted but using the position value which is passed by reference. The application + can choose to leave the emitter position alone, or modify it to a new location. All locations + are in world space. For convenience to the application the world space emitter position is provided. + */ + virtual bool validateEmitterPosition(const PxVec3 &emitterOrigin,PxVec3 &position) = 0; + }; + + /// Returns the asset the instance has been created from. + virtual EmitterAsset* getEmitterAsset() const = 0; + + /// Returns the explicit geometry for THIS ACTOR only + virtual EmitterGeomExplicit* isExplicitGeom() = 0; + + /// Gets the global pose + virtual PxMat44 getGlobalPose() const = 0; + + /// Sets the curent pose of the emitter + virtual void setCurrentPose(const PxTransform& pose) = 0; + + /// Sets the curent position of the emitter + virtual void setCurrentPosition(const PxVec3& pos) = 0; + + /** + \brief PhysX SDK 3.X. Attaches the emitter to an actor + + PxActor pointer can be NULL to detach existing actor + */ + virtual void setAttachActor(PxActor*) = 0; + + /// sets the relative pose of the emitter in the space of the actor to which it is attached + virtual void setAttachRelativePose(const PxTransform& pose) = 0; + + /// PhysX SDK 3.X. Retrieves the actor, to which the emitter is attached. NULL is returned for an unattached emitter. + virtual const PxActor* getAttachActor() const = 0; + + /// Retrieves the relative pose of the emitter in the space of the actor to which it is attached + virtual const PxMat44 getAttachRelativePose() const = 0; + + /// Retrieves the particle radius + virtual float getObjectRadius() const = 0; + + /// Sets collision groups used to reject particles that overlap the geometry + virtual void setOverlapTestCollisionGroups(uint32_t) = 0; + + /** + \brief start emitting particles + + If persistent is true, the emitter will emit every frame until stopEmit() is + called. + */ + virtual void startEmit(bool persistent = true) = 0; + + /// Stop emitting particles + virtual void stopEmit() = 0; + + /// Returns true if the emitter is emitting particles + virtual bool isEmitting() const = 0; + + /// Gets LOD settings + virtual const EmitterLodParamDesc& getLodParamDesc() const = 0; + /// Sets LOD settings + virtual void setLodParamDesc(const EmitterLodParamDesc&) = 0; + + /** Override authored scalable parameters, if necessary */ + /// Sets the range from which the density of particles within the volume is randomly chosen + virtual void setDensity(const float&) = 0; + + /// Sets the range from which the emission rate is randomly chosen + virtual void setRate(const float&) = 0; + + /// Sets the range from which the velocity of a particle is randomly chosen + virtual void setVelocityLow(const PxVec3&) = 0; + + /// Sets the range from which the velocity of a particle is randomly chosen + virtual void setVelocityHigh(const PxVec3&) = 0; + + /// Sets the range from which the lifetime of a particle is randomly chosen + virtual void setLifetimeLow(const float&) = 0; + + /// Sets the range from which the lifetime of a particle is randomly chosen + virtual void setLifetimeHigh(const float&) = 0; + + /// Sets whether or not authored asset particles are emitted + virtual void emitAssetParticles(bool enable) = 0; + + /// Gets whether or not authored asset particles are emitted + virtual bool getEmitAssetParticles() const = 0; + + /** + \brief Emitted particles are injected to specified render volume on initial frame. + + This will work only if you have one renderVolume for each emitter. + Set to NULL to clear the preferred volume. + */ + virtual void setPreferredRenderVolume(RenderVolume* volume) = 0; + + /// Gets the range from which the emission rate is randomly chosen + virtual void getRate(float&) const = 0; + + /// Returns the number of particles in simulation + virtual uint32_t getSimParticlesCount() const = 0; + + /// Returns the number of particles still alive + virtual uint32_t getActiveParticleCount() const = 0; + + /// Sets the origin of the density grid used by this emitter. Important, this density grid may be shared with lots of other emitters as well, it is based on the underlying IOS + virtual void setDensityGridPosition(const PxVec3 &pos) = 0; + + /// Sets the ApexEmitterPosition validation callback interface + virtual void setApexEmitterValidateCallback(EmitterValidateCallback *callback) = 0; + + /// Sets the uniform overall object scale + PX_DEPRECATED virtual void setObjectScale(float scale) = 0; + + /// Retrieves the uniform overall object scale + PX_DEPRECATED virtual float getObjectScale(void) const = 0; + + /// Sets the uniform overall object scale + virtual void setCurrentScale(float scale) = 0; + + /// Retrieves the uniform overall object scale + virtual float getCurrentScale(void) const = 0; + + +}; + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // EMITTER_ACTOR_H diff --git a/APEX_1.4/include/emitter/EmitterAsset.h b/APEX_1.4/include/emitter/EmitterAsset.h new file mode 100644 index 00000000..bda503b1 --- /dev/null +++ b/APEX_1.4/include/emitter/EmitterAsset.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef EMITTER_ASSET_H +#define EMITTER_ASSET_H + +#include "Apex.h" +#include "EmitterGeoms.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#define EMITTER_AUTHORING_TYPE_NAME "ApexEmitterAsset" + +class EmitterActor; +class EmitterPreview; +class EmitterLodParamDesc; + +///APEX Emitter asset. Emits particles within some shape. +class EmitterAsset : public Asset +{ +protected: + virtual ~EmitterAsset() {} + +public: + + /// Returns the explicit geometry for the all actors based on this asset if the asset is explicit, NULL otherwise + virtual EmitterGeomExplicit* isExplicitGeom() = 0; + + /// Returns the geometry used for the all actors based on this asset + virtual const EmitterGeom* getGeom() const = 0; + + /// Gets IOFX asset name that is used to visualize partices of this emitter + virtual const char* getInstancedObjectEffectsAssetName(void) const = 0; + + /// Gets IOS asset name that is used to simulate partices of this emitter + virtual const char* getInstancedObjectSimulatorAssetName(void) const = 0; + + /// Gets IOS asset class name that is used to simulate partices of this emitter + virtual const char* getInstancedObjectSimulatorTypeName(void) const = 0; + + virtual const float & getDensity() const = 0; ///< Gets the range used to choose the density of particles + virtual const float & getRate() const = 0; ///< Gets the range used to choose the emission rate + virtual const PxVec3 & getVelocityLow() const = 0; ///< Gets the range used to choose the velocity of particles + virtual const PxVec3 & getVelocityHigh() const = 0; ///< Gets the range used to choose the velocity of particles + virtual const float & getLifetimeLow() const = 0; ///< Gets the range used to choose the lifetime of particles + virtual const float & getLifetimeHigh() const = 0; ///< Gets the range used to choose the lifetime of particles + + /// For an explicit emitter, Max Samples is ignored. For shaped emitters, it is the maximum number of objects spawned in a step. + virtual uint32_t getMaxSamples() const = 0; + + /** + \brief Gets the emitter duration in seconds + \note If EmitterActor::startEmit() is called with persistent=true, then this duration is ignored. + */ + virtual float getEmitDuration() const = 0; + + /// Gets LOD settings for this asset + virtual const EmitterLodParamDesc& getLodParamDesc() const = 0; + +}; + +///APEX Emitter Asset Authoring. Used to create APEX Emitter assets. +class EmitterAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~EmitterAssetAuthoring() {} +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // EMITTER_ASSET_H diff --git a/APEX_1.4/include/emitter/EmitterGeoms.h b/APEX_1.4/include/emitter/EmitterGeoms.h new file mode 100644 index 00000000..f81f4ab8 --- /dev/null +++ b/APEX_1.4/include/emitter/EmitterGeoms.h @@ -0,0 +1,318 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef EMITTER_GEOMS_H +#define EMITTER_GEOMS_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +///Emitter type +struct EmitterType +{ + ///Enum of emitter types + enum Enum + { + ET_RATE = 0, ///< use emittion rate to calculate the number of particles + ET_DENSITY_ONCE, ///< emit density particles at once + ET_DENSITY_BRUSH, ///< brush behavior: particles are emitted proportionally to the newly occupied vlume + ET_FILL, ///< fill the volume of the emitter with particles + ET_UNDEFINED, + }; +}; + +class EmitterGeomBox; +class EmitterGeomSphere; +class EmitterGeomSphereShell; +class EmitterGeomCylinder; +class EmitterGeomExplicit; + +///Base class for all emitter shapes +class EmitterGeom +{ +public: + ///Sets the type of the emitter + virtual void setEmitterType(EmitterType::Enum) = 0; + + ///Gets the type of the emitter + virtual EmitterType::Enum getEmitterType() const = 0; + + ///If it is a box, cast to box class, return NULL otherwise + virtual const EmitterGeomBox* isBoxGeom() const + { + return NULL; + } + + ///If it is a sphere, cast to sphere class, return NULL otherwise + virtual const EmitterGeomSphere* isSphereGeom() const + { + return NULL; + } + + ///If it is a sphere shell, cast to sphere shell class, return NULL otherwise + virtual const EmitterGeomSphereShell* isSphereShellGeom() const + { + return NULL; + } + + ///If it is a cylinder shell, cast to cylinder class, return NULL otherwise + virtual const EmitterGeomCylinder* isCylinderGeom() const + { + return NULL; + } + + ///If it is an explicit geom, cast to explicit geom class, return NULL otherwise + virtual const EmitterGeomExplicit* isExplicitGeom() const + { + return NULL; + } +}; + +///Sphere shell shape for an emitter. It's a shape formed by the difference of two cocentered spheres. +class EmitterGeomSphereShell : public EmitterGeom +{ +public: + + ///Set sphere shell radius + virtual void setRadius(float radius) = 0; + + ///Get sphere shell radius + virtual float getRadius() const = 0; + + ///Set sphere shell thickness + virtual void setShellThickness(float thickness) = 0; + + ///Get sphere shell thickness + virtual float getShellThickness() const = 0; +}; + +///Spherical shape for an emitter. +class EmitterGeomSphere : public EmitterGeom +{ +public: + + ///Set sphere radius + virtual void setRadius(float radius) = 0; + + ///Get sphere radius + virtual float getRadius() const = 0; +}; + +///Cylindrical shape for an emitter. +class EmitterGeomCylinder : public EmitterGeom +{ +public: + + ///Set cylinder radius + virtual void setRadius(float radius) = 0; + + ///Get cylinder radius + virtual float getRadius() const = 0; + + ///Set cylinder height + virtual void setHeight(float height) = 0; + + ///Get cylinder height + virtual float getHeight() const = 0; +}; + +///Box shape for an emitter. +class EmitterGeomBox : public EmitterGeom +{ +public: + + ///Set box extents + virtual void setExtents(const PxVec3& extents) = 0; + + ///Get box extents + virtual PxVec3 getExtents() const = 0; +}; + +///Explicit geometry. Coordinates of each particle are given explicitly. +class EmitterGeomExplicit : public EmitterGeom +{ +public: + + ///Point parameters + struct PointParams + { + PxVec3 position; ///< Point position + bool doDetectOverlaps; ///< Should detect overlap + }; + + ///Sphere prameters + struct SphereParams + { + PxVec3 center; ///< Sphere center + float radius; ///< Sphere radius + bool doDetectOverlaps; ///< Should detect overlap + }; + + ///Ellipsoid parameters + struct EllipsoidParams + { + PxVec3 center; ///< Ellipsoid center + float radius; ///< Ellipsoid radius + PxVec3 normal; ///< Ellipsoid normal + float polarRadius; ///< Ellipsoid polar radius + bool doDetectOverlaps; ///< Should detect overlap + }; + + ///Remove all shapes + virtual void resetParticleList() = 0; + + /** + \brief Add particles to geometry to be emitted + \param [in] count - number of particles being added by this call + \param [in] params must be specified. When emitted, these relative positions are added to emitter actor position + \param [in] velocities if NULL, the geometry's velocity list will be padded with zero velocities and the asset's velocityRange will be used for velocity + */ + virtual void addParticleList(uint32_t count, + const PointParams* params, + const PxVec3* velocities = 0) = 0; + + /** + \brief Add particles to geometry to be emitted + \param [in] count - number of particles being added by this call + \param [in] positions must be specified. When emitted, these relative positions are added to emitter actor position + \param [in] velocities if NULL, the geometry's velocity list will be padded with zero velocities and the asset's velocityRange will be used for velocity + */ + virtual void addParticleList(uint32_t count, + const PxVec3* positions, + const PxVec3* velocities = 0) = 0; + + ///Structure contains positions, velocities and user data for particles + struct PointListData + { + const void* positionStart; ///< Pointer to first position + uint32_t positionStrideBytes; ///< The stride between position vectors + const void* velocityStart; ///< Pointer to first velocity + uint32_t velocityStrideBytes; ///< The stride between velocity vectors + const void* userDataStart; ///< Pointer to first instance of user data + uint32_t userDataStrideBytes; ///< The stride between instances of user data + }; + + /** + \brief Add particles to geometry to be emitted + \param [in] count - number of particles being added by this call + \param [in] data - particles data + \see EmitterGeomExplicit::PointListData + */ + virtual void addParticleList(uint32_t count, const PointListData& data) = 0; + + /** + \brief Add spheres to geometry to be emitted + \param [in] count - number of spheres being added by this call + \param [in] params - spheres parameters + \param [in] velocities if NULL, the geometry's velocity list will be padded with zero velocities and the asset's velocityRange will be used for velocity + \see EmitterGeomExplicit::SphereParams + */ + virtual void addSphereList(uint32_t count, + const SphereParams* params, + const PxVec3* velocities = 0) = 0; + + /** + \brief Add ellipsoids to geometry to be emitted + \param [in] count - number of ellipsoids being added by this call + \param [in] params - ellipsoids parameters + \param [in] velocities if NULL, the geometry's velocity list will be padded with zero velocities and the asset's velocityRange will be used for velocity + \see EmitterGeomExplicit::EellipsoidParams + */ + virtual void addEllipsoidList(uint32_t count, + const EllipsoidParams* params, + const PxVec3* velocities = 0) = 0; + + /** + \brief Access particles list + \param [out] params - particles coordinates + \param [out] numPoints - number of particles in list + \param [out] velocities - particles velocities + \param [out] numVelocities - number of particles velocities in list + \see EmitterGeomExplicit::PointParams + */ + virtual void getParticleList(const PointParams* ¶ms, + uint32_t& numPoints, + const PxVec3* &velocities, + uint32_t& numVelocities) const = 0; + + /** + \brief Access spheres list + \param [out] params - spheres parameters + \param [out] numSpheres - number of spheres in list + \param [out] velocities - spheres velocities + \param [out] numVelocities - number of spheres velocities in list + \see EmitterGeomExplicit::SphereParams + */ + virtual void getSphereList(const SphereParams* ¶ms, + uint32_t& numSpheres, + const PxVec3* &velocities, + uint32_t& numVelocities) const = 0; + + /** + \brief Access ellipsoids list + \param [out] params - ellipsoids parameters + \param [out] numEllipsoids - number of ellipsoids in list + \param [out] velocities - ellipsoids velocities + \param [out] numVelocities - number of ellipsoids velocities in list + \see EmitterGeomExplicit::EllipsoidParams + */ + virtual void getEllipsoidList(const EllipsoidParams* ¶ms, + uint32_t& numEllipsoids, + const PxVec3* &velocities, + uint32_t& numVelocities) const = 0; + + ///Get the number of points + virtual uint32_t getParticleCount() const = 0; + + ///Get the position of point + virtual PxVec3 getParticlePos(uint32_t index) const = 0; + + ///Get the number of spheres + virtual uint32_t getSphereCount() const = 0; + + ///Get the center of the sphere + virtual PxVec3 getSphereCenter(uint32_t index) const = 0; + + ///Get the radius of the sphere + virtual float getSphereRadius(uint32_t index) const = 0; + + ///Get the number of ellipsoids + virtual uint32_t getEllipsoidCount() const = 0; + + ///Get the center of the ellipsoid + virtual PxVec3 getEllipsoidCenter(uint32_t index) const = 0; + + ///Get the radius of the ellipsoid + virtual float getEllipsoidRadius(uint32_t index) const = 0; + + ///Get the normal of the ellipsoid + virtual PxVec3 getEllipsoidNormal(uint32_t index) const = 0; + + ///Get the polar radius of the ellipsoid + virtual float getEllipsoidPolarRadius(uint32_t index) const = 0; + + ///Get average distance between particles + virtual float getDistance() const = 0; +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // EMITTER_GEOMS_H diff --git a/APEX_1.4/include/emitter/EmitterLodParamDesc.h b/APEX_1.4/include/emitter/EmitterLodParamDesc.h new file mode 100644 index 00000000..96d1e52e --- /dev/null +++ b/APEX_1.4/include/emitter/EmitterLodParamDesc.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef EMITTER_LOD_PARAM_DESC_H +#define EMITTER_LOD_PARAM_DESC_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + + +PX_PUSH_PACK_DEFAULT + +///LOD parameters fro emitters +class EmitterLodParamDesc : public ApexDesc +{ +public: + float maxDistance; ///< Objects greater than this distance from the player will be culled more aggressively + float distanceWeight; ///< Weight given to distance parameter in LOD function + float speedWeight; ///< Weight given to velocity parameter in LOD function + float lifeWeight; ///< Weight given to life remain parameter in LOD function + float separationWeight; ///< Weight given to separation parameter in LOD function + float bias; ///< Bias given to objects spawned by this emitter, relative to other emitters in the same IOS + + /** + \brief constructor sets to default. + */ + PX_INLINE EmitterLodParamDesc() : ApexDesc() + { + init(); + } + + /** + \brief sets members to default values. + */ + PX_INLINE void setToDefault() + { + ApexDesc::setToDefault(); + init(); + } + + /** + \brief checks if this is a valid descriptor. + */ + PX_INLINE bool isValid() const + { + if (distanceWeight < 0.0f || speedWeight < 0.0f || lifeWeight < 0.0f) + { + return false; + } + if (separationWeight < 0.0f || maxDistance < 0.0f || bias < 0.0f) + { + return false; + } + return ApexDesc::isValid(); + } + + /** + \brief enum of manifest versions + */ + enum ManifestVersions + { + initial, + + count, + current = count - 1 + }; + +private: + + PX_INLINE void init() + { + // These defaults give you pure distance based LOD weighting + maxDistance = 0.0f; + distanceWeight = 1.0f; + speedWeight = 0.0f; + lifeWeight = 0.0f; + separationWeight = 0.0f; + bias = 1.0f; + } +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // EMITTER_LOD_PARAM_DESC_H diff --git a/APEX_1.4/include/emitter/EmitterPreview.h b/APEX_1.4/include/emitter/EmitterPreview.h new file mode 100644 index 00000000..616ae43a --- /dev/null +++ b/APEX_1.4/include/emitter/EmitterPreview.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef EMITTER_PREVIEW_H +#define EMITTER_PREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** + Preview class for ApexEmitter. Used for preview rendeing. +*/ +class EmitterPreview : public AssetPreview +{ +public: + ///Draws the emitter + virtual void drawEmitterPreview() = 0; + ///Sets the scaling factor of the renderable + virtual void setScale(float scale) = 0; + +protected: + EmitterPreview() {} +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // EMITTER_PREVIEW_H diff --git a/APEX_1.4/include/emitter/GroundEmitterActor.h b/APEX_1.4/include/emitter/GroundEmitterActor.h new file mode 100644 index 00000000..c0c3c685 --- /dev/null +++ b/APEX_1.4/include/emitter/GroundEmitterActor.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef GROUND_EMITTER_ACTOR_H +#define GROUND_EMITTER_ACTOR_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + + +PX_PUSH_PACK_DEFAULT + +class GroundEmitterAsset; +class RenderVolume; + +/** + \brief a user calback interface used to map raycast hitpoints to material ID + * If an instance of this class is registered with a ground emitter actor, the actor will call + * requestMaterialLookups() in lieu of doing raycasts. The call will occur from within the scope + * of the ApexScene thread, so the callback must be thread safe. + */ +class MaterialLookupCallback +{ +public: + /// Material request structure. + struct MaterialRequest + { + PxVec3 samplePosition; ///< test point position. This is filled by the emitter + uint32_t outMaterialID; ///< ID of the material at the hitpoint. This must be filled by the user + }; + + /** + \brief Submit the meterial lookup request. This method is called by the emitter and implemented by the user + \param requestCount [IN] number of requests + \param reqList [IN/OUT] the pointer to the requests. samplePosition is read and materialID is written to by the user. + */ + virtual void requestMaterialLookups(uint32_t requestCount, MaterialRequest* reqList) = 0; + + virtual ~MaterialLookupCallback() {} +}; + +///Ground Emitter actor. Uses raycasts against ground to spawn particles +class GroundEmitterActor : public Actor +{ +protected: + virtual ~GroundEmitterActor() {} + +public: + /** + \brief Returns the asset the instance has been created from. + */ + virtual GroundEmitterAsset* getEmitterAsset() const = 0; + + /** + \brief Returns the pose of the emitter + */ + virtual const PxMat44 getPose() const = 0; + /** + \brief Sets the pose of the emitter + */ + virtual void setPose(const PxMat44& pos) = 0; + + /** \brief Set the material lookup callback method that replaces raycasts */ + virtual void setMaterialLookupCallback(MaterialLookupCallback*) = 0; + + /** \brief Get the material lookup callback method that replaces raycasts */ + virtual MaterialLookupCallback* getMaterialLookupCallback() const = 0; + + /** + \brief Attaches the emitter to an actor + PxActor pointer can be NULL to detach existing actor + */ + virtual void setAttachActor(PxActor*) = 0; + + /** + \brief sets the relative position of the emitter in the space of the actor to which it is attached + */ + virtual void setAttachRelativePosition(const PxVec3& pos) = 0; + + /**\brief PhysX SDK 3.X. Retrieves the actor, to which the emitter is attached. NULL is returned for an unattached emitter. */ + virtual const PxActor* getAttachActor() const = 0; + + /** \brief Retrieves the relative position of the emitter in the space of the actor to which it is attached. */ + virtual const PxVec3& getAttachRelativePosition() const = 0; + + /* Override some asset settings at run time */ + + ///Sets the range from which the density of particles within the volume is randomly chosen + virtual void setDensity(const float&) = 0; + + ///Sets the radius. The ground emitter actor will create objects within a circle of size 'radius'. + virtual void setRadius(float) = 0; + + ///Sets The maximum raycasts number per frame. + virtual void setMaxRaycastsPerFrame(uint32_t) = 0; + + ///Sets the height from which the ground emitter will cast rays at terrain/objects opposite of the 'upDirection'. + virtual void setRaycastHeight(float) = 0; + + /** + \brief Sets the height above the ground to emit particles. + If greater than 0, the ground emitter will refresh a disc above the player's position rather than + refreshing a circle around the player's position. + + */ + virtual void setSpawnHeight(float) = 0; + + ///Gets the range from which the density of particles within the volume is randomly chosen + virtual const float & getDensity() const = 0; + + ///Gets the radius. The ground emitter actor will create objects within a circle of size 'radius'. + virtual float getRadius() const = 0; + + ///Gets The maximum raycasts number per frame. + virtual uint32_t getMaxRaycastsPerFrame() const = 0; + + ///Gets the height from which the ground emitter will cast rays at terrain/objects opposite of the 'upDirection'. + virtual float getRaycastHeight() const = 0; + + /** + \brief Gets the height above the ground to emit particles. + If greater than 0, the ground emitter will refresh a disc above the player's position rather than + refreshing a circle around the player's position. + */ + virtual float getSpawnHeight() const = 0; + + ///Sets collision groups used to cast rays + virtual void setRaycastCollisionGroups(uint32_t) = 0; + + ///PHYSX SDK 3.X. Sets collision groups mask. + virtual void setRaycastCollisionGroupsMask(physx::PxFilterData*) = 0; + + + ///Gets collision groups used to cast rays + virtual uint32_t getRaycastCollisionGroups() const = 0; + + ///Emitted particles are injected to specified render volume on initial frame. + ///Set to NULL to clear the preferred volume. + virtual void setPreferredRenderVolume(RenderVolume* volume) = 0; +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // GROUND_EMITTER_ACTOR_H diff --git a/APEX_1.4/include/emitter/GroundEmitterAsset.h b/APEX_1.4/include/emitter/GroundEmitterAsset.h new file mode 100644 index 00000000..d604fbe1 --- /dev/null +++ b/APEX_1.4/include/emitter/GroundEmitterAsset.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef GROUND_EMITTER_ASSET_H +#define GROUND_EMITTER_ASSET_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + + +PX_PUSH_PACK_DEFAULT + +#define GROUND_EMITTER_AUTHORING_TYPE_NAME "GroundEmitterAsset" + +///Ground emitter asset. Used to create Ground emitter actors with specific properties. +class GroundEmitterAsset : public Asset +{ +protected: + PX_INLINE GroundEmitterAsset() {} + virtual ~GroundEmitterAsset() {} + +public: + + ///Gets the velocity range. The ground emitter actor will create objects with a random velocity within the velocity range. + virtual const PxVec3 & getVelocityLow() const = 0; + + ///Gets the velocity range. The ground emitter actor will create objects with a random velocity within the velocity range. + virtual const PxVec3 & getVelocityHigh() const = 0; + + ///Gets the lifetime range. The ground emitter actor will create objects with a random lifetime (in seconds) within the lifetime range. + virtual const float & getLifetimeLow() const = 0; + + ///Gets the lifetime range. The ground emitter actor will create objects with a random lifetime (in seconds) within the lifetime range. + virtual const float & getLifetimeHigh() const = 0; + + ///Gets the radius. The ground emitter actor will create objects within a circle of size 'radius'. + virtual float getRadius() const = 0; + + ///Gets The maximum raycasts number per frame. + virtual uint32_t getMaxRaycastsPerFrame() const = 0; + + ///Gets the height from which the ground emitter will cast rays at terrain/objects opposite of the 'upDirection'. + virtual float getRaycastHeight() const = 0; + + /** + \brief Gets the height above the ground to emit particles. + If greater than 0, the ground emitter will refresh a disc above the player's position rather than + refreshing a circle around the player's position. + */ + virtual float getSpawnHeight() const = 0; + + /// Gets collision groups name used to cast rays + virtual const char* getRaycastCollisionGroupMaskName() const = 0; +}; + +///Ground emitter authoring class. Used to create Ground emitter assets. +class GroundEmitterAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~GroundEmitterAssetAuthoring() {} +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // GROUND_EMITTER_ASSET_H diff --git a/APEX_1.4/include/emitter/GroundEmitterPreview.h b/APEX_1.4/include/emitter/GroundEmitterPreview.h new file mode 100644 index 00000000..1cae7931 --- /dev/null +++ b/APEX_1.4/include/emitter/GroundEmitterPreview.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef GROUND_EMITTER_PREVIEW_H +#define GROUND_EMITTER_PREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + + +PX_PUSH_PACK_DEFAULT + +///Ground emitter preview class. Use for preview rendering +class GroundEmitterPreview : public AssetPreview +{ +public: + ///Does the drawing + virtual void drawEmitterPreview() = 0; + ///Sets the scale factor of the preview object + virtual void setScale(float scale) = 0; + +protected: + GroundEmitterPreview() {} +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // GROUND_EMITTER_PREVIEW_H diff --git a/APEX_1.4/include/emitter/ImpactEmitterActor.h b/APEX_1.4/include/emitter/ImpactEmitterActor.h new file mode 100644 index 00000000..31413807 --- /dev/null +++ b/APEX_1.4/include/emitter/ImpactEmitterActor.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef IMPACT_EMITTER_ACTOR_H +#define IMPACT_EMITTER_ACTOR_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + + +PX_PUSH_PACK_DEFAULT + +class ImpactEmitterAsset; +class RenderVolume; + +///Impact emitter actor. Emits particles at impact places +class ImpactEmitterActor : public Actor +{ +protected: + virtual ~ImpactEmitterActor() {} + +public: + ///Gets the pointer to the underlying asset + virtual ImpactEmitterAsset* getEmitterAsset() const = 0; + + /** + \brief Registers an impact in the queue + + \param hitPos impact position + \param hitDir impact direction + \param surfNorm normal of the surface that is hit by the impact + \param setID - id for the event set which should be spawned. Specifies the behavior. \sa ImpactEmitterAsset::querySetID + + */ + virtual void registerImpact(const PxVec3& hitPos, const PxVec3& hitDir, const PxVec3& surfNorm, uint32_t setID) = 0; + + ///Emitted particles are injected to specified render volume on initial frame. + ///Set to NULL to clear the preferred volume. + virtual void setPreferredRenderVolume(RenderVolume* volume) = 0; +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // IMPACT_EMITTER_ACTOR_H diff --git a/APEX_1.4/include/emitter/ImpactEmitterAsset.h b/APEX_1.4/include/emitter/ImpactEmitterAsset.h new file mode 100644 index 00000000..33211dc8 --- /dev/null +++ b/APEX_1.4/include/emitter/ImpactEmitterAsset.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef IMPACT_EMITTER_ASSET_H +#define IMPACT_EMITTER_ASSET_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + + +PX_PUSH_PACK_DEFAULT + +#define IMPACT_EMITTER_AUTHORING_TYPE_NAME "ImpactEmitterAsset" + +class ImpactEmitterActor; + +///Impact emitter asset class +class ImpactEmitterAsset : public Asset +{ +protected: + PX_INLINE ImpactEmitterAsset() {} + virtual ~ImpactEmitterAsset() {} + +public: + /// Get the setID that corresponds to the set name \sa ImpactEmitterActor::registerImpact() + virtual uint32_t querySetID(const char* setName) = 0; + + /** + \brief Get a list of the event set names. The name index in the outSetNames list is the setID. + \param [in,out] inOutSetNames An array of const char * with at least nameCount + \param [in,out] nameCount The size of setNames as input and output, set to -1 if setIDs > nameCount + */ + virtual void getSetNames(const char** inOutSetNames, uint32_t& nameCount) const = 0; +}; + +///Impact emitter asset authoring. Used to create Impact Emitter assets +class ImpactEmitterAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~ImpactEmitterAssetAuthoring() {} + +public: +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // IMPACT_EMITTER_ASSET_H diff --git a/APEX_1.4/include/emitter/ImpactEmitterPreview.h b/APEX_1.4/include/emitter/ImpactEmitterPreview.h new file mode 100644 index 00000000..e3760970 --- /dev/null +++ b/APEX_1.4/include/emitter/ImpactEmitterPreview.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef IMPACT_EMITTER_PREVIEW_H +#define IMPACT_EMITTER_PREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + + +PX_PUSH_PACK_DEFAULT + +///Impact emitter preview. Used for preview rendering of the emitter actors. +class ImpactEmitterPreview : public AssetPreview +{ +public: + /* No need to add any functionality here */ + +protected: + ImpactEmitterPreview() {} +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // IMPACT_EMITTER_PREVIEW_H diff --git a/APEX_1.4/include/emitter/ModuleEmitter.h b/APEX_1.4/include/emitter/ModuleEmitter.h new file mode 100644 index 00000000..e26dd615 --- /dev/null +++ b/APEX_1.4/include/emitter/ModuleEmitter.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_EMITTER_H +#define MODULE_EMITTER_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + + +PX_PUSH_PACK_DEFAULT + +class EmitterAsset; +class EmitterAssetAuthoring; + +class GroundEmitterAsset; +class GroundEmitterAssetAuthoring; + +class ImpactEmitterAsset; +class ImpactEmitterAssetAuthoring; + + +/** +\brief An APEX Module that provides generic Emitter classes +*/ +class ModuleEmitter : public Module +{ +protected: + virtual ~ModuleEmitter() {} + +public: + + /// get rate scale. Rate parameter in all emitters will be multiplied by rate scale. + virtual float getRateScale() const = 0; + + /// get density scale. Density parameter in all emitters except ground emitters will be multiplied by density scale. + virtual float getDensityScale() const = 0; + + /// get ground density scale. Density parameter in all ground emitters will be multiplied by ground density scale. + virtual float getGroundDensityScale() const = 0; + + /// set rate scale. Rate parameter in all module emitters will be multiplied by rate scale. + virtual void setRateScale(float rateScale) = 0; + + /// set density scale. Density parameter in all emitters except ground emitters will be multiplied by density scale. + virtual void setDensityScale(float densityScale) = 0; + + /// set ground density scale. Density parameter in all ground emitters will be multiplied by ground density scale. + virtual void setGroundDensityScale(float groundDensityScale) = 0; +}; + + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // MODULE_EMITTER_H diff --git a/APEX_1.4/include/fieldsampler/ModuleFieldSampler.h b/APEX_1.4/include/fieldsampler/ModuleFieldSampler.h new file mode 100644 index 00000000..1b445a1a --- /dev/null +++ b/APEX_1.4/include/fieldsampler/ModuleFieldSampler.h @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_FIELD_SAMPLER_H +#define MODULE_FIELD_SAMPLER_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief This is an optional callback interface for collision filtering between field samplers and other objects + If this interface is not provided, then collision filtering happens normally through the default scene simulationfiltershader callback + However, if this is provided, then the user can no only return true/false to indicate whether or not the two objects should interact but + can also assign a weighted multiplier value to control how strongly the two objects should interact. +*/ +class FieldSamplerWeightedCollisionFilterCallback +{ +public: + /** + \brief This is an optional callback interface for collision filtering between field samplers and other objects + If this interface is not provided, then collision filtering happens normally through the default scene simulationfiltershader callback + However, if this is provided, then the user can no only return true/false to indicate whether or not the two objects should interact but + can also assign a weighted multiplier value to control how strongly the two objects should interact. + */ + virtual bool fieldSamplerWeightedCollisionFilter(const physx::PxFilterData &objectA,const physx::PxFilterData &objectB,float &multiplierValue) = 0; +}; + + +/** + \brief FieldSampler module class + */ +class ModuleFieldSampler : public Module +{ +protected: + virtual ~ModuleFieldSampler() {} + +public: + + /** + \brief Sets the optional weighted collision filter callback for this scene. If not provided, it will use the default SimulationFilterShader on the current scene + */ + virtual bool setFieldSamplerWeightedCollisionFilterCallback(const Scene& apexScene,FieldSamplerWeightedCollisionFilterCallback *callback) = 0; + + +#if PX_PHYSICS_VERSION_MAJOR == 3 + /** + Set flag to toggle PhysXMonitor for ForceFields. + */ + virtual void enablePhysXMonitor(const Scene& apexScene, bool enable) = 0; + /** + \brief Add filter data (collision group) to PhysXMonitor. + + \param apexScene [in] - Apex scene for which to submit the force sample batch. + \param filterData [in] - PhysX 3.0 collision mask for PhysXMonitor + */ + virtual void setPhysXMonitorFilterData(const Scene& apexScene, physx::PxFilterData filterData) = 0; +#endif + + /** + \brief Initialize a query for a batch of sampling points + + \param apexScene [in] - Apex scene for which to create the force sample batch query. + \param maxCount [in] - Maximum number of indices (active samples) + \param filterData [in] - PhysX 3.0 collision mask for data + \return the ID of created query + */ + virtual uint32_t createForceSampleBatch(const Scene& apexScene, uint32_t maxCount, const physx::PxFilterData filterData) = 0; + + /** + \brief Release a query for a batch of sampling points + + \param apexScene [in] - Apex scene for which to create the force sample batch. + \param batchId [in] - ID of query that should be released + */ + virtual void releaseForceSampleBatch(const Scene& apexScene, uint32_t batchId) = 0; + + /** + \brief Submits a batch of sampling points to be evaluated during the simulation step. + + \param apexScene [in] - Apex scene for which to submit the force sample batch. + \param batchId [in] - ID of query for force sample batch. + \param forces [out] - Buffer to which computed forces are written to. The buffer needs to be persistent between calling this function and the next PxApexScene::fetchResults. + \param forcesStride [in] - Stride between consecutive force vectors within the forces output. + \param positions [in] - Buffer containing the positions of the input samples. + \param positionsStride [in] - Stride between consecutive position vectors within the positions input. + \param velocities [in] - Buffer containing the velocities of the input samples. + \param velocitiesStride [in] - Stride between consecutive velocity vectors within the velocities input. + \param mass [in] - Buffer containing the mass of the input samples. + \param massStride [in] - Stride between consecutive mass values within the mass input. + \param indices [in] - Buffer containing the indices of the active samples that are considered for the input and output buffers. + \param numIndices [in] - Number of indices (active samples). + */ + virtual void submitForceSampleBatch( const Scene& apexScene, uint32_t batchId, + PxVec4* forces, const uint32_t forcesStride, + const PxVec3* positions, const uint32_t positionsStride, + const PxVec3* velocities, const uint32_t velocitiesStride, + const float* mass, const uint32_t massStride, + const uint32_t* indices, const uint32_t numIndices) = 0; + +}; + + + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // MODULE_FIELD_SAMPLER_H diff --git a/APEX_1.4/include/forcefield/ForceFieldActor.h b/APEX_1.4/include/forcefield/ForceFieldActor.h new file mode 100644 index 00000000..06f260fa --- /dev/null +++ b/APEX_1.4/include/forcefield/ForceFieldActor.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef FORCE_FIELD_ACTOR_H +#define FORCE_FIELD_ACTOR_H + +#include "Apex.h" + + +namespace nvidia +{ +namespace apex +{ + + +PX_PUSH_PACK_DEFAULT + +class ForceFieldAsset; +class ForceFieldAssetParams; + +/** + \brief ForceField Actor + */ +class ForceFieldActor : public Actor +{ +protected: + virtual ~ForceFieldActor() {} + +public: + /** + Return true if the force field actor is enabled. + */ + virtual bool isEnable() = 0; + + /** + Disable force field actor. Default status is enable. Can switch it freely. + A disabled explosion actor still exists there, but has no effect to the scene. + */ + virtual bool disable() = 0; + + /** + Enable force field actor. Default status is enable. Can switch it freely. + A disabled explosion actor still exists there, but has no effect to the scene. + */ + virtual bool enable() = 0; + + /** + Gets location and orientation of the force field. + */ + virtual PxMat44 getPose() const = 0; + + /** + Sets location and orientation of the force field. + */ + virtual void setPose(const PxMat44& pose) = 0; + + /** + Gets the force field actor's scale. + */ + PX_DEPRECATED virtual float getScale() const = 0; + + /** + Sets the force field actor's scale. (0.0f, +inf) + */ + PX_DEPRECATED virtual void setScale(float scale) = 0; + + /** + Gets the force field actor's scale. + */ + PX_DEPRECATED virtual float getCurrentScale() const = 0; + + /** + Sets the force field actor's scale. (0.0f, +inf) + */ + PX_DEPRECATED virtual void setCurrentScale(float scale) = 0; + + + + /** + Retrieves the name string for the force field actor. + */ + virtual const char* getName() const = 0; + + /** + Set a name string for the force field actor that can be retrieved with getName(). + */ + virtual void setName(const char* name) = 0; + + /** + Set strength for the force field actor. + */ + virtual void setStrength(const float strength) = 0; + + /** + Set lifetime for the force field actor. + */ + virtual void setLifetime(const float lifetime) = 0; + + /** + Set falloff type (linear, steep, scurve, custom, none) for the force field actor. + Only works for radial force field types. + */ + PX_DEPRECATED virtual void setFalloffType(const char* type) = 0; + + /** + Set falloff multiplier for the force field actor. + Only works for radial force field types. + */ + PX_DEPRECATED virtual void setFalloffMultiplier(const float multiplier) = 0; + + /** + Returns the asset the actor has been created from. + */ + virtual ForceFieldAsset* getForceFieldAsset() const = 0; + +}; + +PX_POP_PACK + +} // namespace apex +} // namespace nvidia + +#endif // FORCE_FIELD_ACTOR_H diff --git a/APEX_1.4/include/forcefield/ForceFieldAsset.h b/APEX_1.4/include/forcefield/ForceFieldAsset.h new file mode 100644 index 00000000..81ee3480 --- /dev/null +++ b/APEX_1.4/include/forcefield/ForceFieldAsset.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef FORCE_FIELD_ASSET_H +#define FORCE_FIELD_ASSET_H + +#include "Apex.h" +#include "ForceFieldPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#define FORCEFIELD_AUTHORING_TYPE_NAME "ForceFieldAsset" + +class ForceFieldActor; + +/** + \brief ForceField Asset + */ +class ForceFieldAsset : public Asset +{ +protected: + /** + \brief force field asset default destructor. + */ + virtual ~ForceFieldAsset() {} + +public: + /** + \brief returns the default scale of the asset. + */ + virtual float getDefaultScale() const = 0; + + /** + \brief release an actor created from this asset. + */ + virtual void releaseForceFieldActor(ForceFieldActor&) = 0; +}; + +/** + \brief ForceField Asset Authoring + */ +class ForceFieldAssetAuthoring : public AssetAuthoring +{ +protected: + /** + \brief force field asset authoring default destructor. + */ + virtual ~ForceFieldAssetAuthoring() {} + +public: +}; + + +PX_POP_PACK + +} // namespace apex +} // namespace nvidia + +#endif // FORCE_FIELD_ASSET_H diff --git a/APEX_1.4/include/forcefield/ForceFieldPreview.h b/APEX_1.4/include/forcefield/ForceFieldPreview.h new file mode 100644 index 00000000..3e37a5d9 --- /dev/null +++ b/APEX_1.4/include/forcefield/ForceFieldPreview.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef FORCE_FIELD_PREVIEW_H +#define FORCE_FIELD_PREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderDebugInterface; + +namespace APEX_FORCEFIELD +{ +/** + \def FORCEFIELD_DRAW_NOTHING + Draw no items. +*/ +static const uint32_t FORCEFIELD_DRAW_NOTHING = (0x00); +/** + \def FORCEFIELD_DRAW_ICON + Draw the icon. +*/ +static const uint32_t FORCEFIELD_DRAW_ICON = (0x01); +/** + \def FORCEFIELD_DRAW_BOUNDARIES + Draw the ForceField include shapes. +*/ +static const uint32_t FORCEFIELD_DRAW_BOUNDARIES = (0x2); +/** + \def FORCEFIELD_DRAW_WITH_CYLINDERS + Draw the explosion field boundaries. +*/ +static const uint32_t FORCEFIELD_DRAW_WITH_CYLINDERS = (0x4); +/** + \def FORCEFIELD_DRAW_FULL_DETAIL + Draw all of the preview rendering items. +*/ +static const uint32_t FORCEFIELD_DRAW_FULL_DETAIL = (FORCEFIELD_DRAW_ICON + FORCEFIELD_DRAW_BOUNDARIES); +/** + \def FORCEFIELD_DRAW_FULL_DETAIL_BOLD + Draw all of the preview rendering items using cylinders instead of lines to make the text and icon look BOLD. +*/ +static const uint32_t FORCEFIELD_DRAW_FULL_DETAIL_BOLD = (FORCEFIELD_DRAW_FULL_DETAIL + FORCEFIELD_DRAW_WITH_CYLINDERS); +} + +/** +\brief APEX asset preview force field asset. +*/ +class ForceFieldPreview : public AssetPreview +{ +public: + /** + Set the scale of the icon. + The unscaled icon has is 1.0x1.0 game units. + By default the scale of the icon is 1.0. (unscaled) + */ + virtual void setIconScale(float scale) = 0; + /** + Set the detail level of the preview rendering by selecting which features to enable. + Any, all, or none of the following masks may be added together to select what should be drawn. + The defines for the individual items are FORCEFIELD_DRAW_NOTHING, FORCEFIELD_DRAW_ICON, FORCEFIELD_DRAW_BOUNDARIES, + FORCEFIELD_DRAW_WITH_CYLINDERS. + All items may be drawn using the macro FORCEFIELD_DRAW_FULL_DETAIL and FORCEFIELD_DRAW_FULL_DETAIL_BOLD. + */ + virtual void setDetailLevel(uint32_t detail) = 0; + +protected: + ForceFieldPreview() {}; +}; + + +PX_POP_PACK + +} // namespace apex +} // namespace nvidia + +#endif // FORCE_FIELD_PREVIEW_H diff --git a/APEX_1.4/include/forcefield/ModuleForceField.h b/APEX_1.4/include/forcefield/ModuleForceField.h new file mode 100644 index 00000000..b8440020 --- /dev/null +++ b/APEX_1.4/include/forcefield/ModuleForceField.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_FORCE_FIELD_H +#define MODULE_FORCE_FIELD_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class ForceFieldAsset; +class ForceFieldAssetAuthoring; + +/** +\brief ForceField Module +*/ +class ModuleForceField : public Module +{ +public: + /** + \brief The module ID value of the force field. + */ + virtual uint32_t getModuleValue() const = 0; + +protected: + /** + \brief Force field module default destructor. + */ + virtual ~ModuleForceField() {} +}; + + + +PX_POP_PACK + +} // namespace apex +} // namespace nvidia + +#endif // MODULE_FORCE_FIELD_H diff --git a/APEX_1.4/include/iofx/IofxActor.h b/APEX_1.4/include/iofx/IofxActor.h new file mode 100644 index 00000000..c40fa910 --- /dev/null +++ b/APEX_1.4/include/iofx/IofxActor.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef IOFX_ACTOR_H +#define IOFX_ACTOR_H + +#include "Apex.h" +#include "IofxAsset.h" +#include "IofxRenderable.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief IOFX actor public interface +*/ +class IofxActor : public Actor +{ +public: + ///get the radius of the partice + virtual float getObjectRadius() const = 0; + + ///get the number of particles + virtual uint32_t getObjectCount() const = 0; + + ///get the number of visible particles (if sprite depth sorting is enabled, returns only number of particles in front of camera) + virtual uint32_t getVisibleCount() const = 0; + + ///get the name of the IOS asset used to feed partices to the IOFX + virtual const char* getIosAssetName() const = 0; + + ///returns AABB covering all objects in this actor, it's updated each frame during Scene::fetchResults(). + virtual physx::PxBounds3 getBounds() const = 0; + + /** + \brief Acquire a pointer to the iofx's renderable proxy and increment its reference count. + + The IofxRenderable will only be deleted when its reference count is zero. + Calls to IofxRenderable::release decrement the reference count, as does a call to IofxActor::release(). + */ + virtual IofxRenderable* acquireRenderableReference() = 0; +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // IOFX_ACTOR_H diff --git a/APEX_1.4/include/iofx/IofxAsset.h b/APEX_1.4/include/iofx/IofxAsset.h new file mode 100644 index 00000000..a9ba3479 --- /dev/null +++ b/APEX_1.4/include/iofx/IofxAsset.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef IOFX_ASSET_H +#define IOFX_ASSET_H + +#include "Apex.h" +#include "ModifierDefs.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#define IOFX_AUTHORING_TYPE_NAME "IOFX" + +class Modifier; +class ApexActor; + +/** + \brief IOFX Asset public interface. Used to define the way the visual parameters are created + from physical parameters of a particle +*/ +class IofxAsset : public Asset, public Context +{ +public: + ///get the name of the material used for sprite-based particles visualization + virtual const char* getSpriteMaterialName() const = 0; + + ///get the number of different mesh assets used for mesh-based particles visualization + virtual uint32_t getMeshAssetCount() const = 0; + + ///get the name of one of the mesh assets used for mesh-based particles visualization + /// \param index mesh asset internal index + virtual const char* getMeshAssetName(uint32_t index = 0) const = 0; + + ///get the weight of one of the mesh assets used for mesh-based particles visualization. Can be any value; not normalized. + /// \param index mesh asset internal index + virtual uint32_t getMeshAssetWeight(uint32_t index = 0) const = 0; + + ///get the list of spawn modifiers + virtual const Modifier* getSpawnModifiers(uint32_t& outCount) const = 0; + + ///get the list of continuous modifiers + virtual const Modifier* getContinuousModifiers(uint32_t& outCount) const = 0; + + ///get the biggest possible scale given the current spawn- and continuous modifiers + ///note that some modifiers depend on velocity, so the scale can get arbitrarily large. + /// \param maxVelocity this value defines what the highest expected velocity is to compute the upper bound + virtual float getScaleUpperBound(float maxVelocity) const = 0; + + ///the IOFX asset needs to inform other actors when it is released + /// \note only for internal use + virtual void addDependentActor(ApexActor* actor) = 0; +}; + +/** + \brief IOFX Asset Authoring public interface. + */ +class IofxAssetAuthoring : public AssetAuthoring +{ +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // IOFX_ASSET_H diff --git a/APEX_1.4/include/iofx/IofxRenderCallback.h b/APEX_1.4/include/iofx/IofxRenderCallback.h new file mode 100644 index 00000000..1b1cc026 --- /dev/null +++ b/APEX_1.4/include/iofx/IofxRenderCallback.h @@ -0,0 +1,459 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef IOFX_RENDER_CALLBACK_H +#define IOFX_RENDER_CALLBACK_H + +#include "foundation/Px.h" +#include "UserRenderCallback.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class IofxRenderable; +class IofxSpriteRenderable; +class IofxMeshRenderable; + +/** +\brief Enumerates the potential IOFX render semantics +*/ +struct IofxRenderSemantic +{ + /** + \brief Enum of IOFX render semantics + */ + enum Enum + { + POSITION = 0, //!< Position of particle + COLOR, //!< Color of particle + VELOCITY, //!< Linear velocity of particle + SCALE, //!< Scale of particle + LIFE_REMAIN, //!< 1.0 (new) .. 0.0 (dead) + DENSITY, //!< Particle density + SUBTEXTURE, //!< Sub-texture index of particle + ORIENTATION, //!< 2D particle orientation (angle in radians, CCW in screen plane) + ROTATION, //!< 3D particle rotation + USER_DATA, //!< User data - 32 bits (passed from Emitter) + + NUM_SEMANTICS //!< Count of semantics, not a valid semantic. + }; +}; + + +/** +\brief Enumerates the potential IOFX mesh render layout elements +*/ +struct IofxSpriteRenderLayoutElement +{ + /** + \brief Enum of IOFX sprite render layout elements + */ + enum Enum + { + POSITION_FLOAT3, + COLOR_RGBA8, + COLOR_BGRA8, + COLOR_FLOAT4, + VELOCITY_FLOAT3, + SCALE_FLOAT2, + LIFE_REMAIN_FLOAT1, + DENSITY_FLOAT1, + SUBTEXTURE_FLOAT1, + ORIENTATION_FLOAT1, + USER_DATA_UINT1, + + MAX_COUNT + }; + + /** + \brief Get layout element format + */ + static PX_INLINE RenderDataFormat::Enum getFormat(Enum element) + { + switch (element) + { + case POSITION_FLOAT3: + return RenderDataFormat::FLOAT3; + case COLOR_RGBA8: + return RenderDataFormat::R8G8B8A8; + case COLOR_BGRA8: + return RenderDataFormat::B8G8R8A8; + case COLOR_FLOAT4: + return RenderDataFormat::FLOAT4; + case VELOCITY_FLOAT3: + return RenderDataFormat::FLOAT3; + case SCALE_FLOAT2: + return RenderDataFormat::FLOAT2; + case LIFE_REMAIN_FLOAT1: + return RenderDataFormat::FLOAT1; + case DENSITY_FLOAT1: + return RenderDataFormat::FLOAT1; + case SUBTEXTURE_FLOAT1: + return RenderDataFormat::FLOAT1; + case ORIENTATION_FLOAT1: + return RenderDataFormat::FLOAT1; + case USER_DATA_UINT1: + return RenderDataFormat::UINT1; + default: + PX_ALWAYS_ASSERT(); + return RenderDataFormat::NUM_FORMATS; + } + } +}; + +/** +\brief Enumerates the potential IOFX sprite render layout surface elements +*/ +struct IofxSpriteRenderLayoutSurfaceElement +{ + /** + \brief Enum of IOFX sprite render layout surface elements + */ + enum Enum + { + POSITION_FLOAT4, //!< float4(POSITION.x, POSITION.y, POSITION.z, 1) + SCALE_ORIENT_SUBTEX_FLOAT4, //!< float4(SCALE.x, SCALE.y, ORIENTATION, SUBTEXTURE) + COLOR_RGBA8, //<! COLOR in RGBA8 format + COLOR_BGRA8, //<! COLOR in BGRA8 format + COLOR_FLOAT4, //<! COLOR in FLOAT4 format + + MAX_COUNT + }; + + /** + \brief Get layout element format + */ + static PX_INLINE RenderDataFormat::Enum getFormat(Enum element) + { + switch (element) + { + case POSITION_FLOAT4: + return RenderDataFormat::FLOAT4; + case SCALE_ORIENT_SUBTEX_FLOAT4: + return RenderDataFormat::FLOAT4; + case COLOR_RGBA8: + return RenderDataFormat::R8G8B8A8; + case COLOR_BGRA8: + return RenderDataFormat::B8G8R8A8; + case COLOR_FLOAT4: + return RenderDataFormat::R32G32B32A32_FLOAT; + default: + PX_ALWAYS_ASSERT(); + return RenderDataFormat::NUM_FORMATS; + } + } +}; + +/** +\brief Describes the layout for sprite rendering +*/ +struct IofxSpriteRenderLayout +{ + IofxSpriteRenderLayout(void) + { + setDefaults(); + } + + /** + \brief Reset to default values + */ + void setDefaults() + { + bufferDesc.setDefaults(); + for (uint32_t i = 0; i < IofxSpriteRenderLayoutElement::MAX_COUNT; i++) + { + offsets[i] = uint32_t(-1); + } + stride = 0; + surfaceCount = 0; + for (uint32_t i = 0; i < MAX_SURFACE_COUNT; i++) + { + surfaceElements[i] = IofxSpriteRenderLayoutSurfaceElement::MAX_COUNT; + } + } + + /** + \brief Check if parameter's values are correct + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + + numFailed += (surfaceCount == 0) && !bufferDesc.isValid(); + numFailed += (surfaceCount == 0) && (stride == 0); + numFailed += (surfaceCount == 0) && (offsets[IofxSpriteRenderLayoutElement::POSITION_FLOAT3] == uint32_t(-1)); + + numFailed += ((stride & 0x03) != 0); + for (uint32_t i = 0; i < IofxSpriteRenderLayoutElement::MAX_COUNT; i++) + { + if (offsets[i] != static_cast<uint32_t>(-1)) + { + numFailed += (offsets[i] >= stride); + numFailed += ((offsets[i] & 0x03) != 0); + } + } + for (uint32_t i= 0; i < surfaceCount; ++i) + { + numFailed += (surfaceElements[i] >= IofxSpriteRenderLayoutSurfaceElement::MAX_COUNT); + numFailed += !surfaceDescs[i].isValid(); + numFailed += (surfaceDescs[i].width == 0) || (surfaceDescs[i].height == 0); + numFailed += (IofxSpriteRenderLayoutSurfaceElement::getFormat(surfaceElements[i]) != surfaceDescs[i].format); + } + + return (numFailed == 0); + } + + /** + \brief Check if this object is the same as other + */ + bool isTheSameAs(const IofxSpriteRenderLayout& other) const + { + if (surfaceCount != other.surfaceCount) return false; + if (surfaceCount == 0) + { + if (!bufferDesc.isTheSameAs(other.bufferDesc)) return false; + if (stride != other.stride) return false; + for (uint32_t i = 0; i < IofxSpriteRenderLayoutElement::MAX_COUNT; i++) + { + if (offsets[i] != other.offsets[i]) return false; + } + } + else + { + for (uint32_t i = 0; i < surfaceCount; ++i) + { + if (surfaceElements[i] != other.surfaceElements[i]) return false; + if (!surfaceDescs[i].isTheSameAs(other.surfaceDescs[i])) return false; + } + } + return true; + } + +public: + UserRenderBufferDesc bufferDesc; //!< Render buffer desc. + + /** + \brief Array of the corresponding offsets (in bytes) for each layout element. + */ + uint32_t offsets[IofxSpriteRenderLayoutElement::MAX_COUNT]; + uint32_t stride; //!< The stride between objects in render buffer. + + uint32_t surfaceCount; //!< Number of render surfaces (if zero render buffer is used) + + /** + \brief Max number of supported render surfaces + */ + static const uint32_t MAX_SURFACE_COUNT = 4; + + /** + \brief Layout element for each render surface (should be valid for all indices < surfaceCount) + */ + IofxSpriteRenderLayoutSurfaceElement::Enum surfaceElements[MAX_SURFACE_COUNT]; + /** + \brief Description for each render surface (should be valid for all indices < surfaceCount) + */ + UserRenderSurfaceDesc surfaceDescs[MAX_SURFACE_COUNT]; +}; + + +/** +\brief Enumerates the potential IOFX mesh render layout elements +*/ +struct IofxMeshRenderLayoutElement +{ + /** + \brief Enum of IOFX mesh render layout elements + */ + enum Enum + { + POSITION_FLOAT3, + ROTATION_SCALE_FLOAT3x3, + POSE_FLOAT3x4, + VELOCITY_LIFE_FLOAT4, + DENSITY_FLOAT1, + COLOR_RGBA8, + COLOR_BGRA8, + COLOR_FLOAT4, + USER_DATA_UINT1, + + MAX_COUNT + }; + + /** + \brief Get layout element format + */ + static PX_INLINE RenderDataFormat::Enum getFormat(Enum element) + { + switch (element) + { + case POSITION_FLOAT3: + return RenderDataFormat::FLOAT3; + case ROTATION_SCALE_FLOAT3x3: + return RenderDataFormat::FLOAT3x3; + case POSE_FLOAT3x4: + return RenderDataFormat::FLOAT3x4; + case VELOCITY_LIFE_FLOAT4: + return RenderDataFormat::FLOAT4; + case DENSITY_FLOAT1: + return RenderDataFormat::FLOAT1; + case COLOR_RGBA8: + return RenderDataFormat::R8G8B8A8; + case COLOR_BGRA8: + return RenderDataFormat::B8G8R8A8; + case COLOR_FLOAT4: + return RenderDataFormat::FLOAT4; + case USER_DATA_UINT1: + return RenderDataFormat::UINT1; + default: + PX_ALWAYS_ASSERT(); + return RenderDataFormat::NUM_FORMATS; + } + } +}; + +/** +\brief Describes the layout for mesh rendering +*/ +struct IofxMeshRenderLayout +{ + IofxMeshRenderLayout(void) + { + setDefaults(); + } + + /** + \brief Reset to default values + */ + void setDefaults() + { + bufferDesc.setDefaults(); + for (uint32_t i = 0; i < IofxMeshRenderLayoutElement::MAX_COUNT; i++) + { + offsets[i] = uint32_t(-1); + } + stride = 0; + } + + /** + \brief Check if parameter's values are correct + */ + bool isValid(void) const + { + uint32_t numFailed = 0; + + numFailed += !bufferDesc.isValid(); + numFailed += (stride == 0); + numFailed += (offsets[IofxMeshRenderLayoutElement::POSITION_FLOAT3] == uint32_t(-1)) + && (offsets[IofxMeshRenderLayoutElement::POSE_FLOAT3x4] == uint32_t(-1)); + + numFailed += ((stride & 0x03) != 0); + for (uint32_t i = 0; i < IofxMeshRenderLayoutElement::MAX_COUNT; i++) + { + if (offsets[i] != static_cast<uint32_t>(-1)) + { + numFailed += (offsets[i] >= stride); + numFailed += ((offsets[i] & 0x03) != 0); + } + } + + return (numFailed == 0); + } + + /** + \brief Check if this object is the same as other + */ + bool isTheSameAs(const IofxMeshRenderLayout& other) const + { + if (!bufferDesc.isTheSameAs(other.bufferDesc)) return false; + if (stride != other.stride) return false; + for (uint32_t i = 0; i < IofxMeshRenderLayoutElement::MAX_COUNT; i++) + { + if (offsets[i] != other.offsets[i]) return false; + } + return true; + } + +public: + UserRenderBufferDesc bufferDesc; //!< Render buffer desc. + + /** + \brief Array of the corresponding offsets (in bytes) for each layout element. + */ + uint32_t offsets[IofxMeshRenderLayoutElement::MAX_COUNT]; + uint32_t stride; //!< The stride between objects in render buffer. +}; + + +/** +\brief User defined callback for IOFX rendering +*/ +class IofxRenderCallback : public UserRenderCallback +{ +public: + /** + \brief Called just after a new IOFX renderable was created + */ + virtual void onCreatedIofxRenderable(IofxRenderable& ) {} + + /** + \brief Called just after an IOFX renderable was updated + */ + virtual void onUpdatedIofxRenderable(IofxRenderable& ) {} + + /** + \brief Called just before an IOFX renderable is going to be released + */ + virtual void onReleasingIofxRenderable(IofxRenderable& ) {} + + /** \brief Called by the IOFX module to query layout for sprite rendering. + Should return true in case IofxSpriteRenderLayout is properly filled, + and then IOFX will pass this layout to createRender[Buffer|Surface] method(s) to create needed render resources. + In case this method is not implemented and returns false the IOFX module will create a layout to hold all input semantics. + Also in case this method is not implemented or/and createRender[Buffer|Surface] method is not implemented, + then the IOFX module will create its own render buffer/surfaces which user can map to access rendering content. + */ + virtual bool getIofxSpriteRenderLayout(IofxSpriteRenderLayout& spriteRenderLayout, uint32_t spriteCount, uint32_t spriteSemanticsBitmap, RenderInteropFlags::Enum interopFlags) + { + PX_UNUSED(spriteRenderLayout); + PX_UNUSED(spriteCount); + PX_UNUSED(spriteSemanticsBitmap); + PX_UNUSED(interopFlags); + return false; + } + + /** \brief Called by the IOFX module to query layout for mesh rendering. + Should return true in case IofxMeshRenderLayout is properly filled, + and then IOFX will pass this layout to createRenderBuffer method to create needed render resources. + In case this method is not implemented and returns false the IOFX module will create a layout to hold all input semantics. + Also in case this method is not implemented or/and createRenderBuffer method is not implemented, + then the IOFX module will create its own render buffer which user can map to access rendering content. + */ + virtual bool getIofxMeshRenderLayout(IofxMeshRenderLayout& meshRenderLayout, uint32_t meshCount, uint32_t meshSemanticsBitmap, RenderInteropFlags::Enum interopFlags) + { + PX_UNUSED(meshRenderLayout); + PX_UNUSED(meshCount); + PX_UNUSED(meshSemanticsBitmap); + PX_UNUSED(interopFlags); + return false; + } + +}; + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // IOFX_RENDER_CALLBACK_H diff --git a/APEX_1.4/include/iofx/IofxRenderable.h b/APEX_1.4/include/iofx/IofxRenderable.h new file mode 100644 index 00000000..8f1214c9 --- /dev/null +++ b/APEX_1.4/include/iofx/IofxRenderable.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef IOFX_RENDERABLE_H +#define IOFX_RENDERABLE_H + +#include "foundation/Px.h" +#include "ApexInterface.h" +#include "Renderable.h" +#include "IofxRenderCallback.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief IofxSharedRenderData stores common render data shared by several IOFX Renderables. +*/ +struct IofxSharedRenderData +{ + uint32_t maxObjectCount; //!< maximum number of particles + uint32_t activeObjectCount; //!< currently active number of particles +}; + +/** +\brief IofxSpriteSharedRenderData stores sprite render data shared by several IOFX Renderables. +*/ +struct IofxSpriteSharedRenderData : IofxSharedRenderData +{ + IofxSpriteRenderLayout spriteRenderLayout; //!< sprite render layout + UserRenderBuffer* spriteRenderBuffer; //!< sprite render buffer + UserRenderSurface* spriteRenderSurfaces[IofxSpriteRenderLayout::MAX_SURFACE_COUNT]; //!< sprite render surfaces +}; + +/** +\brief IofxMeshSharedRenderData stores mesh render data shared by several IOFX Renderables. +*/ +struct IofxMeshSharedRenderData : IofxSharedRenderData +{ + IofxMeshRenderLayout meshRenderLayout; //!< mesh render layout + UserRenderBuffer* meshRenderBuffer; //!< mesh render buffer +}; + +/** +\brief IofxCommonRenderData stores common render data for one IOFX Renderable. +*/ +struct IofxCommonRenderData +{ + uint32_t startIndex; //!< index of the first particle in render buffer + uint32_t objectCount; //!< number of particles in render buffer + + const char* renderResourceNameSpace; //!< render resource name space + const char* renderResourceName; //!< render resource name + void* renderResource; //!< render resource +}; + +/** +\brief IofxSpriteRenderData stores sprite render data for one IOFX Renderable. +*/ +struct IofxSpriteRenderData : IofxCommonRenderData +{ + uint32_t visibleCount; //!< number of visible particles (if sprite depth sorting is enabled, includes only particles in front of the view frustrum) + + const IofxSpriteSharedRenderData* sharedRenderData; //!< reference to Sprite shared render data +}; + +/** +\brief IofxMeshRenderData stores mesh render data for one IOFX Renderable. +*/ +struct IofxMeshRenderData : IofxCommonRenderData +{ + const IofxMeshSharedRenderData* sharedRenderData; //!< reference to Mesh shared render data +}; + +class IofxSpriteRenderable; +class IofxMeshRenderable; + +/** + \brief The IOFX renderable represents a unit of rendering. + It contains complete information to render a batch of particles with the same material/mesh in the same render volume. +*/ +class IofxRenderable : public ApexInterface +{ +public: + /** + \brief Type of IOFX renderable + */ + enum Type + { + SPRITE, //!< Sprite particles type + MESH //!< Mesh particles type + }; + + /** + \brief Return Type of this renderable. + */ + virtual Type getType() const = 0; + + /** + \brief Return Sprite render data for Sprite renderable and NULL for other types. + */ + virtual const IofxSpriteRenderData* getSpriteRenderData() const = 0; + + /** + \brief Return Mesh render data for Mesh renderable and NULL for other types. + */ + virtual const IofxMeshRenderData* getMeshRenderData() const = 0; + + /** + \brief Return AABB of this renderable. + */ + virtual const physx::PxBounds3& getBounds() const = 0; + +protected: + virtual ~IofxRenderable() {} + +}; + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // IOFX_RENDERABLE_H diff --git a/APEX_1.4/include/iofx/Modifier.h b/APEX_1.4/include/iofx/Modifier.h new file mode 100644 index 00000000..4b3665ac --- /dev/null +++ b/APEX_1.4/include/iofx/Modifier.h @@ -0,0 +1,592 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODIFIER_H +#define MODIFIER_H + +#include "Apex.h" +#include "Curve.h" +#include "IofxAsset.h" +#include "IofxRenderCallback.h" + +#include "ModifierDefs.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/// Converts ModifierStage to bitmap +inline uint32_t ModifierUsageFromStage(ModifierStage stage) +{ + return 1u << stage; +} + +// Disable the unused arguments warning for this header. +#pragma warning( disable: 4100 ) + +/** +\brief Modifier contains all of the data necessary to apply a single modifier type to a particle system. + +Generally this combines some physical transformation with parameters specified at authoring time +to modify the look of the final effect. +*/ +class Modifier +{ +public: + + /// getModifierType returns the enumerated type associated with this class. + virtual ModifierTypeEnum getModifierType() const = 0; + + /// getModifierUsage returns the usage scenarios allowed for a particular modifier. + virtual uint32_t getModifierUsage() const = 0; + + /// returns a bitmap that includes every sprite semantic that the modifier updates + virtual uint32_t getModifierSpriteSemantics() + { + return 0; + } + + /// returns a bitmap that includes every mesh(instance) semantic that the modifier updates + virtual uint32_t getModifierMeshSemantics() + { + return 0; + } + + virtual ~Modifier() { } + +}; + +/** +\brief ModifierT is a helper class to handle the mapping of Type->Enum and Enum->Type. + +This imposes some structure on the subclasses--they all now +expect to have a const static field called ModifierType. +*/ +template <typename T> +class ModifierT : public Modifier +{ +public: + + /// Returns ModifierType for typename T + virtual ModifierTypeEnum getModifierType() const + { + return T::ModifierType; + } + + /// Returns ModifierUsage for typename T + virtual uint32_t getModifierUsage() const + { + return T::ModifierUsage; + } +}; + + +/** +\brief RotationModifier applies rotation to the particles using one of several rotation models. +*/ +class RotationModifier : public ModifierT<RotationModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_Rotation; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Spawn | ModifierUsage_Continuous + | ModifierUsage_Mesh; + + + /// get the roll model + virtual ApexMeshParticleRollType::Enum getRollType() const = 0; + + /// set the roll model + virtual void setRollType(ApexMeshParticleRollType::Enum rollType) = 0; + + /// get the maximum allowed settle rate per second + virtual float getMaxSettleRate() const = 0; + + /// set the maximum allowed settle rate per second + virtual void setMaxSettleRate(float settleRate) = 0; + + /// get the maximum allowed rotation rate per second + virtual float getMaxRotationRate() const = 0; + + /// set the maximum allowed rotation rate per second + virtual void setMaxRotationRate(float rotationRate) = 0; + +}; + +/** + \brief SimpleScaleModifier just applies a simple scale factor to each of the X, Y and Z aspects of the model. Each scalefactor can be + applied independently. +*/ +class SimpleScaleModifier : public ModifierT<SimpleScaleModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_SimpleScale; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Spawn | ModifierUsage_Continuous + | ModifierUsage_Sprite | ModifierUsage_Mesh; + + + /// get the vector of scale factors along the three axes + virtual PxVec3 getScaleFactor() const = 0; + + /// set the vector of scale factors along the three axes + virtual void setScaleFactor(const PxVec3& s) = 0; +}; + +/** +\brief ScaleByMassModifier scales by mass of the particle. +*/ +class ScaleByMassModifier : public ModifierT<ScaleByMassModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_ScaleByMass; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Spawn | ModifierUsage_Continuous + | ModifierUsage_Sprite | ModifierUsage_Mesh; +}; + +/** + \brief RandomScaleModifier applies a random scale uniformly to all three dimensions. Currently, the + scale is a uniform in the range specified. +*/ +class RandomScaleModifier : public ModifierT<RandomScaleModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_RandomScale; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Spawn + | ModifierUsage_Sprite | ModifierUsage_Mesh; + + + /// get the range of scale factors along the three axes + virtual Range<float> getScaleFactor() const = 0; + + /// set the range of scale factors along the three axes + virtual void setScaleFactor(const Range<float>& s) = 0; +}; + +/** + \brief ColorVsLifeModifier modifies the color constants associated with a particle + depending on the life remaining of the particle. +*/ +class ColorVsLifeModifier : public ModifierT<ColorVsLifeModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_ColorVsLife; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Spawn | ModifierUsage_Continuous + | ModifierUsage_Sprite | ModifierUsage_Mesh; + + + /// get the affected color channel + virtual ColorChannel getColorChannel() const = 0; + + /// set the affected color channel + virtual void setColorChannel(ColorChannel colorChannel) = 0; + + /// get the curve that sets the dependency between the lifetime and the color + virtual const Curve* getFunction() const = 0; + + /// set the curve that sets the dependency between the lifetime and the color + virtual void setFunction(const Curve* f) = 0; +}; + +/** + \brief ColorVsDensityModifier modifies the color constants associated with a particle + depending on the density of the particle. +*/ +class ColorVsDensityModifier : public ModifierT<ColorVsDensityModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_ColorVsDensity; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Sprite | ModifierUsage_Mesh; + + + /// get the affected color channel + virtual ColorChannel getColorChannel() const = 0; + + /// set the affected color channel + virtual void setColorChannel(ColorChannel colorChannel) = 0; + + /// get the curve that sets the dependency between the density and the color + virtual const Curve* getFunction() const = 0; + + /// set the curve that sets the dependency between the density and the color + virtual void setFunction(const Curve* f) = 0; +}; + +/** + \brief SubtextureVsLifeModifier is a modifier to adjust the subtexture id versus the life remaining of a particular particle. + + Interpretation of the subtexture id over time is up to the application. + */ +class SubtextureVsLifeModifier : public ModifierT<SubtextureVsLifeModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_SubtextureVsLife; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Sprite; + + + /// get the curve that sets the dependency between the life remaining and the subtexture id + virtual const Curve* getFunction() const = 0; + + /// set the curve that sets the dependency between the life remaining and the subtexture id + virtual void setFunction(const Curve* f) = 0; +}; + +/** + \brief OrientAlongVelocity is a modifier to orient a mesh so that a particular axis coincides with the velocity vector. + */ +class OrientAlongVelocityModifier : public ModifierT<OrientAlongVelocityModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_OrientAlongVelocity; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Mesh; + + + /// get the object-space vector that will coincide with the velocity vector + virtual PxVec3 getModelForward() const = 0; + + /// set the object-space vector that will coincide with the velocity vector + virtual void setModelForward(const PxVec3& s) = 0; +}; + + +/** + \brief ScaleAlongVelocityModifier is a modifier to apply a scale factor along the current velocity vector. + + Note that without applying an OrientAlongVelocity modifier first, the results for this will be 'odd.' + */ +class ScaleAlongVelocityModifier : public ModifierT<ScaleAlongVelocityModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_ScaleAlongVelocity; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Mesh; + + + /// get the scale factor + virtual float getScaleFactor() const = 0; + + /// set the scale factor + virtual void setScaleFactor(const float& s) = 0; +}; + +/** + \brief RandomSubtextureModifier generates a random subtexture ID and places it in the subTextureId field. + */ +class RandomSubtextureModifier : public ModifierT<RandomSubtextureModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_RandomSubtexture; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Spawn + | ModifierUsage_Sprite; + + + ///get the range for subtexture values + virtual Range<float> getSubtextureRange() const = 0; + + ///set the range for subtexture values + virtual void setSubtextureRange(const Range<float>& s) = 0; +}; + +/** + \brief RandomRotationModifier will choose a random orientation for a sprite particle within the range as specified below. + + The values in the range are interpreted as radians. Please keep in mind that all the sprites are coplanar to the screen. + */ +class RandomRotationModifier : public ModifierT<RandomRotationModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_RandomRotation; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Spawn + | ModifierUsage_Sprite; + + + ///get the range of orientations, in radians. + virtual Range<float> getRotationRange() const = 0; + + ///set the range of orientations, in radians. + virtual void setRotationRange(const Range<float>& s) = 0; +}; + +/** + \brief ScaleVsLifeModifier applies a scale factor function against a single axis versus the life remaining. + */ +class ScaleVsLifeModifier : public ModifierT<ScaleVsLifeModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_ScaleVsLife; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Sprite | ModifierUsage_Mesh; + + + /// get the axis along which the scale factor will be applied + virtual ScaleAxis getScaleAxis() const = 0; + + /// set the axis along which the scale factor will be applied + virtual void setScaleAxis(ScaleAxis a) = 0; + + /// get the the curve that defines the dependency between the life remaining and the scale factor + virtual const Curve* getFunction() const = 0; + + /// set the the curve that defines the dependency between the life remaining and the scale factor + virtual void setFunction(const Curve* f) = 0; +}; + +/** + \brief ScaleVsDensityModifier applies a scale factor function against a single axis versus the density of the particle. + */ +class ScaleVsDensityModifier : public ModifierT<ScaleVsDensityModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_ScaleVsDensity; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Sprite | ModifierUsage_Mesh; + + + /// get the axis along which the scale factor will be applied + virtual ScaleAxis getScaleAxis() const = 0; + + /// set the axis along which the scale factor will be applied + virtual void setScaleAxis(ScaleAxis a) = 0; + + /// get the the curve that defines the dependency between the density and the scale factor + virtual const Curve* getFunction() const = 0; + + /// set the the curve that defines the dependency between the density and the scale factor + virtual void setFunction(const Curve* f) = 0; +}; + +/** + \brief ScaleVsCameraDistance applies a scale factor against a specific axis based on distance from the camera to the particle. + */ +class ScaleVsCameraDistanceModifier : public ModifierT<ScaleVsCameraDistanceModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_ScaleVsCameraDistance; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Sprite | ModifierUsage_Mesh; + + + /// get the axis along which the scale factor will be applied + virtual ScaleAxis getScaleAxis() const = 0; + + /// set the axis along which the scale factor will be applied + virtual void setScaleAxis(ScaleAxis a) = 0; + + /// get the the curve that defines the dependency between the camera distance and the scale factor + virtual const Curve* getFunction() const = 0; + + /// set the the curve that defines the dependency between the camera distance and the scale factor + virtual void setFunction(const Curve* f) = 0; +}; + +/** + \brief ViewDirectionSortingModifier sorts sprite particles along view direction back to front. + */ +class ViewDirectionSortingModifier : public ModifierT<ViewDirectionSortingModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_ViewDirectionSorting; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Sprite; + +}; + +/** + \brief RotationRateModifier is a modifier to apply a continuous rotation for sprites. + */ +class RotationRateModifier : public ModifierT<RotationRateModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_RotationRate; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Sprite; + + + /// set the rotation rate + virtual float getRotationRate() const = 0; + + /// get the rotation rate + virtual void setRotationRate(const float& rate) = 0; +}; + +/** + \brief RotationRateVsLifeModifier is a modifier to adjust the rotation rate versus the life remaining of a particular particle. + */ +class RotationRateVsLifeModifier : public ModifierT<RotationRateVsLifeModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_RotationRateVsLife; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Sprite; + + + /// get the curve that sets the dependency between the life remaining and the rotation rate + virtual const Curve* getFunction() const = 0; + + /// set the curve that sets the dependency between the life remaining and the rotation rate + virtual void setFunction(const Curve* f) = 0; +}; + +/** + \brief OrientScaleAlongScreenVelocityModifier is a modifier to orient & scale sprites along the current screen velocity vector. + */ +class OrientScaleAlongScreenVelocityModifier : public ModifierT<OrientScaleAlongScreenVelocityModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_OrientScaleAlongScreenVelocity; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Continuous + | ModifierUsage_Sprite; + + + /// get the scale per velocity + virtual float getScalePerVelocity() const = 0; + + /// set the scale per velocity + virtual void setScalePerVelocity(const float& s) = 0; + + /// get the scale change limit + virtual float getScaleChangeLimit() const = 0; + + /// set the scale change limit + virtual void setScaleChangeLimit(const float& s) = 0; + + /// get the scale change delay + virtual float getScaleChangeDelay() const = 0; + + /// set the scale change delay + virtual void setScaleChangeDelay(const float& s) = 0; +}; + +/** + \brief ColorVsVelocityModifier modifies the color constants associated with a particle + depending on the velocity of the particle. +*/ +class ColorVsVelocityModifier : public ModifierT<ColorVsVelocityModifier> +{ +public: + + /// ModifierType + static const ModifierTypeEnum ModifierType = ModifierType_ColorVsVelocity; + + /// ModifierUsage + static const uint32_t ModifierUsage = ModifierUsage_Spawn | ModifierUsage_Continuous + | ModifierUsage_Sprite | ModifierUsage_Mesh; + + + /// get the affected color channel + virtual ColorChannel getColorChannel() const = 0; + + /// set the affected color channel + virtual void setColorChannel(ColorChannel colorChannel) = 0; + + /// get the curve that sets the dependency between the lifetime and the color + virtual const Curve* getFunction() const = 0; + + /// set the curve that sets the dependency between the lifetime and the color + virtual void setFunction(const Curve* f) = 0; + + /// get velocity0 + virtual float getVelocity0() const = 0; + + /// set velocity0 + virtual void setVelocity0(float value) = 0; + + /// get velocity1 + virtual float getVelocity1() const = 0; + + /// set velocity1 + virtual void setVelocity1(float value) = 0; +}; + +#pragma warning( default: 4100 ) + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // MODIFIER_H diff --git a/APEX_1.4/include/iofx/ModifierDefs.h b/APEX_1.4/include/iofx/ModifierDefs.h new file mode 100644 index 00000000..2d39ad6e --- /dev/null +++ b/APEX_1.4/include/iofx/ModifierDefs.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODIFIER_DEFS_H +#define MODIFIER_DEFS_H + +#include "ApexUsingNamespace.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** + \brief Roll type of a particle + */ +struct ApexMeshParticleRollType +{ + /** + \brief Enum of roll type of a particle + */ + enum Enum + { + SPHERICAL = 0, ///< roll as a sphere + CUBIC, ///< as a cubical object + FLAT_X, ///< as a flat object (shortest axis is x) + FLAT_Y, ///< as a flat object (shortest axis is y) + FLAT_Z, ///< as a flat object (shortest axis is z) + LONG_X, ///< as a long object (longest axis is x) + LONG_Y, ///< as a long object (longest axis is y) + LONG_Z, ///< as a long object (longest axis is z) + SPRITE, ///< as a sprite + + COUNT + }; +}; + +/** + \brief Modifiers list + \note These are serialized to disk, so if you reorder them or change existing modifier types, you + will need to version the stream and map the old values to the new values. + If new values are just appended, no other special care needs to be handled. + */ +enum ModifierTypeEnum +{ + ModifierType_Invalid = 0, + ModifierType_Rotation = 1, + ModifierType_SimpleScale = 2, + ModifierType_RandomScale = 3, + ModifierType_ColorVsLife = 4, + ModifierType_ColorVsDensity = 5, + ModifierType_SubtextureVsLife = 6, + ModifierType_OrientAlongVelocity = 7, + ModifierType_ScaleAlongVelocity = 8, + ModifierType_RandomSubtexture = 9, + ModifierType_RandomRotation = 10, + ModifierType_ScaleVsLife = 11, + ModifierType_ScaleVsDensity = 12, + ModifierType_ScaleVsCameraDistance = 13, + ModifierType_ViewDirectionSorting = 14, + ModifierType_RotationRate = 15, + ModifierType_RotationRateVsLife = 16, + ModifierType_OrientScaleAlongScreenVelocity = 17, + ModifierType_ScaleByMass = 18, + ModifierType_ColorVsVelocity = 19, + + ModifierType_Count +}; + +/** + \brief Stage at which the modifier is applied + */ +enum ModifierStage +{ + ModifierStage_Spawn = 0, ///< at the spawn + ModifierStage_Continuous = 1, ///< on every frame + + ModifierStage_Count +}; + +/** + \brief Color channel + */ +enum ColorChannel +{ + ColorChannel_Red = 0, + ColorChannel_Green = 1, + ColorChannel_Blue = 2, + ColorChannel_Alpha = 3 +}; + +/** + \brief Scale axis + */ +enum ScaleAxis +{ + ScaleAxis_X = 0, + ScaleAxis_Y = 1, + ScaleAxis_Z = 2 +}; + +/** + \brief Modifier usage + */ +enum ModifierUsage +{ + ModifierUsage_Spawn = 0x01, + ModifierUsage_Continuous = 0x02, + + ModifierUsage_Sprite = 0x04, + ModifierUsage_Mesh = 0x08, +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // MODIFIER_DEFS_H diff --git a/APEX_1.4/include/iofx/ModuleIofx.h b/APEX_1.4/include/iofx/ModuleIofx.h new file mode 100644 index 00000000..4057ff4f --- /dev/null +++ b/APEX_1.4/include/iofx/ModuleIofx.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_IOFX_H +#define MODULE_IOFX_H + +#include "Apex.h" +#include "TestBase.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class IofxAsset; +class IofxAssetAuthoring; +class RenderVolume; +class IofxRenderCallback; +class IofxRenderable; + + +/** +\brief Iterate over all renderables in IOFX module. IMPORTANT: release() should be called for each returned not-NULL renderable! +*/ +class IofxRenderableIterator : public ApexInterface +{ +public: + + /// Return the first renderable in IOFX module + virtual IofxRenderable* getFirst() = 0; + + /// Return the next renderable IOFX module + virtual IofxRenderable* getNext() = 0; +}; + + +/** + \brief IOFX Module. + + This module is used to convert physical parameters of particles into visual parameters + that can be used to render particles. ApexRenderVolume provide the ability to partition world space + into separate renderables. + */ +class ModuleIofx : public Module +{ +protected: + virtual ~ModuleIofx() {} + +public: + /// Disable use of OGL/D3D Interop. Must be called before emitters are created to have any effect + virtual void disableCudaInterop() = 0; + + /// Disable use of CUDA IOFX modifiers. Must be called before emitters are created to have any effect + virtual void disableCudaModifiers() = 0; + + /** \brief Disables deferred allocation of IOFX actors + * + * By default, IOFX actors and their render resources will not be + * created until it has objects to render. + */ + virtual void disableDeferredRenderableAllocation() = 0; + + /** \brief Create a new render volume + * + * Render volumes may be created at any time, unlike most other APEX + * asset and actor types. Their insertion into the scene is + * deferred if the simulation is active. + */ + virtual RenderVolume* createRenderVolume(const Scene& apexScene, const PxBounds3& b, uint32_t priority, bool allIofx) = 0; + + /** \brief Release a render volume + * + * Render volumes may be released at any time, unlike most other APEX + * asset and actor types. If the simulation is active, their + * resources are released at the end of the simulation step. + */ + virtual void releaseRenderVolume(RenderVolume& volume) = 0; + + /// Get TestBase implementation of Iofx scene + virtual const TestBase* getTestBase(Scene* apexScene) const = 0; + + /** + \brief Set IofxRenderCallback + \see IofxRenderCallback + */ + virtual bool setIofxRenderCallback(const Scene& apexScene, IofxRenderCallback* ) = 0; + + /** + \brief Get IofxRenderCallback + \see IofxRenderCallback + */ + virtual IofxRenderCallback* getIofxRenderCallback(const Scene& apexScene) const = 0; + + /** + \brief Create an iterator for all renderables in IOFX module + */ + virtual IofxRenderableIterator* createIofxRenderableIterator(const Scene&) = 0; + + /** + \brief Prepare renderables for rendering, should be called each frame before using renderables to update them with the most recent data + */ + virtual void prepareRenderables(const Scene&) = 0; +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // MODULE_IOFX_H diff --git a/APEX_1.4/include/iofx/RenderVolume.h b/APEX_1.4/include/iofx/RenderVolume.h new file mode 100644 index 00000000..c44eeb4f --- /dev/null +++ b/APEX_1.4/include/iofx/RenderVolume.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef RENDER_VOLUME_H +#define RENDER_VOLUME_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class IofxAsset; +class IofxActor; + +/** + \brief An object which "owns" a volume of world space. + + Any particles which enter the + owned volume will be migrated to an IOFX actor owned by this object (if the + particle's IOFX asset is affected by this volume). + + When volumes overlap, their relative priorities break the tie. If multiple volumes + have the same priority, the tie breaker goes to the volume that owns the particle. + */ +class RenderVolume : public ApexInterface +{ +public: + /// Returns AABB covering all objects in this render volume, it's updated each frame during Scene::fetchResults(). + virtual physx::PxBounds3 getBounds() const = 0; + + /// Returns true if the volume affects all IOFX assets + virtual bool getAffectsAllIofx() const = 0; + + /// Adds IOFX asset to volume's list of affected IOFX assets, returns false on failure + virtual bool addIofxAsset(IofxAsset& iofx) = 0; + + /// Moves the render volume while maintaining its dimensions + virtual void setPosition(const PxVec3& pos) = 0; + + /// Directly assigns a new AABB ownership volume + virtual void setOwnershipBounds(const PxBounds3& b) = 0; + + /// Retrieves the configured AABB bounds of the volume. Call getBounds() for the "live" bounds. + virtual PxBounds3 getOwnershipBounds() const = 0; + + /** \brief Retrieve list of IOFX actors owned by this volume (one per IOFX Asset per IOS actor) + * + * Returns count of 0 if empty. Returned pointer is undefined when count is 0. + * + * The bounds of each of these IOFX is guaranteed to be within the bounds of the volume itself. + * Calling the updateRenderResources and dispatchRenderResources() methods of the volume will + * implicitly call the same methods of each of these IOFX actors, so there is no need to iterate + * over them for rendering purposes, unless you require special logic per IOFX. + * + * It is not necessary to release these actors, they will be released automatically when their + * volume, their IOFX Asset, or their host IOS actor are released. + * + * This call is not thread-safe. The returned buffer is only valid until the next APEX API + * call that steps the simulation or modifies the number of IOFX actors in a scene. + */ + virtual IofxActor* const* lockIofxActorList(uint32_t& count) = 0; + + /** + \brief Unlock IOFX actors which where locked by calling lockIofxActorList + \see RenderVolume::lockIofxActorList + */ + virtual void unlockIofxActorList() = 0; + + /** \brief Retrieve list of volume's affected IOFX assets. + * + * Returns count of 0 if empty or volume affects all IOFX assets. Returned pointer is + * undefined when count is 0. + * + * The returned buffer not thread-safe, and is only valid until the next APEX API + * call that steps the simulation or modifies the number of IOFX assets in a scene. + */ + virtual IofxAsset* const* getIofxAssetList(uint32_t& count) const = 0; + + virtual PxVec3 getPosition() const = 0; ///< Returns center of ownership bounds + virtual uint32_t getPriority() const = 0; ///< Returns priority of volume + + /** \brief Returns true if this volume affects the specified IOFX asset + * + * Callers must acquire render lock of the volume before calling + * this function, for thread safety. + */ + virtual bool affectsIofxAsset(const IofxAsset& iofx) const = 0; + +protected: + virtual ~RenderVolume() {} +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // RENDER_VOLUME_H diff --git a/APEX_1.4/include/legacy/ModuleIofxLegacy.h b/APEX_1.4/include/legacy/ModuleIofxLegacy.h new file mode 100644 index 00000000..943fc595 --- /dev/null +++ b/APEX_1.4/include/legacy/ModuleIofxLegacy.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_IOFX_LEGACY_H +#define MODULE_IOFX_LEGACY_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +class IofxRenderCallback; + +PX_PUSH_PACK_DEFAULT + +/** +\brief ModuleIofx interface used in APEXSDK before v. 1.4 + +This interface depricated in APEX 1.4 +*/ +class ModuleIofxLegacy : public Module +{ +protected: + virtual ~ModuleIofxLegacy() {} + +public: + + /** + \brief Returns IOFX render callback + */ + virtual IofxRenderCallback* getIofxLegacyRenderCallback(const Scene& apexScene) = 0; +}; + +PX_POP_PACK + +} +} // end namespace nvidia::apex + +#endif // MODULE_IOFX_LEGACY_H diff --git a/APEX_1.4/include/legacy/ModuleLegacy.h b/APEX_1.4/include/legacy/ModuleLegacy.h new file mode 100644 index 00000000..7a174cb0 --- /dev/null +++ b/APEX_1.4/include/legacy/ModuleLegacy.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_LEGACY_H +#define MODULE_LEGACY_H + +#include <ApexUsingNamespace.h> + +namespace nvidia +{ +namespace apex +{ + +#if !defined(_USRDLL) +/** +* If this module is distributed as a static library, the user must call this +* function before calling ApexSDK::createModule("Legacy") +*/ +void instantiateModuleLegacy(); +#endif + +} +} // end namespace physx::apex + +#endif // MODULE_LEGACY_H diff --git a/APEX_1.4/include/loader/ModuleLoader.h b/APEX_1.4/include/loader/ModuleLoader.h new file mode 100644 index 00000000..950533ff --- /dev/null +++ b/APEX_1.4/include/loader/ModuleLoader.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_LOADER_H +#define MODULE_LOADER_H + +#include "Apex.h" +#include "PsHashMap.h" + +namespace nvidia +{ +namespace apex +{ + +/** +\brief The ModuleLoader is a utility class for loading APEX modules + +\note The most useful methods for rapid integration are "loadAllModules()", + "loadAllLegacyModules()", and "releaseLoadedModules()". + +\note If you need to release APEX modules loaded with ModuleLoader you should use one of + the release-methods provided below. Note that you may never need it because SDK automatically + releases all modules when program ends. +*/ +class ModuleLoader : public Module +{ +public: + /// \brief Load and initialize a specific APEX module + virtual Module* loadModule(const char* name) = 0; + + /** + \brief Load and initialize a list of specific APEX modules + \param [in] names The names of modules to load + \param [in] size Number of modules to load + \param [in] modules The modules array must be the same size as the names array to + support storage of every loaded Module pointer. Use NULL if + you do not need the list of created modules. + */ + virtual void loadModules(const char** names, uint32_t size, Module** modules = 0) = 0; + + /// \brief Load and initialize all APEX modules + virtual void loadAllModules() = 0; + + /// \brief Load and initialize all legacy APEX modules (useful for deserializing legacy assets) + virtual void loadAllLegacyModules() = 0; + + /// \brief Returns the number of loaded APEX modules + virtual uint32_t getLoadedModuleCount() const = 0; + + /// \brief Returns the APEX module specified by the index if it was loaded by this ModuleLoader + virtual Module* getLoadedModule(uint32_t idx) const = 0; + + /// \brief Returns the APEX module specified by the name if it was loaded by this ModuleLoader + virtual Module* getLoadedModule(const char* name) const = 0; + + /// \brief Releases the APEX module specified by the index if it was loaded by this ModuleLoader + virtual void releaseModule(uint32_t idx) = 0; + + /// \brief Releases the APEX module specified by the name if it was loaded by this ModuleLoader + virtual void releaseModule(const char* name) = 0; + + /// \brief Releases the APEX module specified by the index if it was loaded by this ModuleLoader + virtual void releaseModules(Module** modules, uint32_t size) = 0; + + /** + \brief Releases the specified APEX module + \note If the ModuleLoader is used to load modules, this method must be used to + release individual modules. + Do not use the Module::release() method. + */ + virtual void releaseModule(Module* module) = 0; + + /** + \brief Releases the APEX modules specified in the names list + \note If the ModuleLoader is used to load modules, this method must be used to + release individual modules. + Do not use the Module::release() method. + */ + virtual void releaseModules(const char** names, uint32_t size) = 0; + + /// Releases all APEX modules loaded by this ModuleLoader + virtual void releaseLoadedModules() = 0; + + /// ModuleNameErrorMap + typedef shdfnd::HashMap<const char*, nvidia::apex::ApexCreateError> ModuleNameErrorMap; + + /// Returns ModuleNameErrorMap + virtual const ModuleNameErrorMap& getLoadedModulesErrors() const = 0; +}; + +#if !defined(_USRDLL) +/** +* If this module is distributed as a static library, the user must call this +* function before calling ApexSDK::createModule("Loader") +*/ +void instantiateModuleLoader(); +#endif + +} +} // end namespace nvidia::apex + +#endif // MODULE_LOADER_H diff --git a/APEX_1.4/include/nvparameterized/NvParamUtils.h b/APEX_1.4/include/nvparameterized/NvParamUtils.h new file mode 100644 index 00000000..1492f925 --- /dev/null +++ b/APEX_1.4/include/nvparameterized/NvParamUtils.h @@ -0,0 +1,335 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. + +#ifndef NV_PARAM_UTILS_H +#define NV_PARAM_UTILS_H + +#include "NvParameterized.h" + +// utility methods to operate on NvParameterized data. + +namespace NvParameterized +{ + +/** +\brief Recursively finds a parameter with the given name + +This method will recursively search through not only this parameterized but all referenced +parameterized objects as well. It sets the handle and returns the NvParameterized::Interface in which the name was found. + +\param i the parameterized object that will be searched + +\param longName contains the name of the parameter to be found +the longName will work with arrays, structs, and included references + +\param outHandle will contain the output handle that provides read-only access to the specified parameter + +\returns the NvParameterized::Interface pointer in which the parameter is contained (this could be different than the top level NvParameterized::Interface if the parameter is contained in an included reference) +*/ +PX_INLINE const Interface * findParam(const Interface &i,const char *longName, Handle &outHandle); + + +/** +\brief Recursively finds a parameter with the given name + +This method will recursively search through not only this parameterized but all referenced +parameterized objects as well. It sets the handle and returns the NvParameterized::Interface in which the name was found. + +\param i the parameterized object that will be searched + +\param longName contains the name of the parameter to be found +the longName will work with arrays, structs, and included references + +\param outHandle will contain the output handle that provides read-write access to the specified parameter + +\returns the NvParameterized::Interface pointer in which the parameter is contained (this could be different than the top level NvParameterized::Interface if the parameter is contained in an included reference) +*/ +PX_INLINE Interface * findParam(Interface &i,const char *longName, Handle &outHandle); + +/** +\brief Container for results of getParamList +*/ +struct ParamResult +{ +public: + /** + \brief Constructor + */ + ParamResult(const char *name, + const char *longName, + const char *className, + const char *instanceName, + const Handle &handle, + int32_t arraySize, + DataType type) + : mArraySize(arraySize), + mInstanceName(instanceName), + mClassName(className), + mName(name), + mLongName(longName), + mHandle(handle), + mDataType(type) + {} + + /** + \brief size of array (if parameter is array) + */ + int32_t mArraySize; + + /** + \brief Name of parameter's parent object + */ + const char *mInstanceName; + + /** + \brief Name of NvParameterized-class of parameter's parent object + */ + const char *mClassName; + + /** + \brief The name of the parameter + */ + const char *mName; + + /** + \brief The fully qualified 'long' name of the parameter + */ + const char *mLongName; + + /** + \brief Use this handle to access the parameter in question + */ + Handle mHandle; + + /** + \brief The type of parameter + */ + DataType mDataType; +}; + +/** +\brief A helper method to retrieve the list of all parameters relative to an interface. + +\param [in] i the input interface +\param [in] className is an optional class name to match to. If this is null, it will return all parameters. +\param [in] paramName is an optional parameter name to match to. If this is null, it will return all parameters. +\param [out] count the number of parameters found +\param [in] recursive if true the search will recurse into every included reference, not just the top parameterized class +\param [in] classesOnly if true the search will only match against class names +\param [in] traits typically the APEX traits class, used to allocate the ParamResult, see ApexSDK::getParameterizedTraits() + +\note The return pointer is allocated by the NvParameterized Traits class and should be freed by calling releaseParamList() + +*/ +PX_INLINE const ParamResult * getParamList(const Interface &i, + const char *className, // name of class to match + const char *paramName, // name of parameter to match + uint32_t &count, + bool recursive, + bool classesOnly, + NvParameterized::Traits *traits); + +/// helper function to free the parameter list returned from getParamList +PX_INLINE void releaseParamList(uint32_t resultCount,const ParamResult *results,NvParameterized::Traits *traits); + +/// helper function to get an NvParameterized array size +PX_INLINE bool getParamArraySize(const Interface &pm, const char *name, int32_t &arraySize); + +/// helper function to resize an NvParameterized array +PX_INLINE bool resizeParamArray(Interface &pm, const char *name, int32_t newSize); + +/** +\brief Callback container for getNamedReferences +*/ +class NamedReferenceInterface +{ +public: + /** + \brief Destructor + */ + virtual ~NamedReferenceInterface() {} + /** + \brief Callback + + Calls back to the user with any named reference (not included references) in the NvParameterized::Interface + If the user returns a NULL pointer, than the original named reference is left alone. + If the user returns a non-NULL pointer, than the named reference is replaced with the 'const char *' returned. + */ + virtual const char * namedReferenceCallback(const char *className,const char *namedReference,Handle &handle) = 0; +}; + +/// Calls back for every non-included named reference. +PX_INLINE uint32_t getNamedReferences(const Interface &i, + NamedReferenceInterface &namedReference, + bool recursive); + +/** +\brief Callback container for getReferences +*/ +class ReferenceInterface +{ +public: + /** + \brief Destructor + */ + virtual ~ReferenceInterface() {} + /** + \brief Callback + + Calls back to the user with any reference (named or included or both) in the NvParameterized::Interface. + */ + virtual void referenceCallback(Handle &handle) = 0; +}; + +/// Calls back for every reference (named or included or both). +PX_INLINE void getReferences(const Interface &iface, + ReferenceInterface &cb, + bool named, + bool included, + bool recursive); + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamBool(const Interface &pm, const char *name, bool &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamBool(Interface &pm, const char *name, bool val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamString(const Interface &pm, const char *name, const char *&val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamString(Interface &pm, const char *name, const char *val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamEnum(const Interface &pm, const char *name, const char *&val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamEnum(Interface &pm, const char *name, const char *val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamRef(const Interface &pm, const char *name, NvParameterized::Interface *&val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamRef(Interface &pm, const char *name, NvParameterized::Interface *val, bool doDestroyOld = false) ; + +/// helper function to init an NvParameterized value +PX_INLINE bool initParamRef(Interface &pm, const char *name, const char *className, bool doDestroyOld = false); +/// helper function to init an NvParameterized value +PX_INLINE bool initParamRef(Interface &pm, const char *name, const char *className, const char *objName, bool doDestroyOld = false); + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamI8(const Interface &pm, const char *name, int8_t &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamI8(Interface &pm, const char *name, int8_t val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamI16(const Interface &pm, const char *name, int16_t &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamI16(Interface &pm, const char *name, int16_t val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamI32(const Interface &pm, const char *name, int32_t &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamI32(Interface &pm, const char *name, int32_t val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamI64(const Interface &pm, const char *name, int64_t &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamI64(Interface &pm, const char *name, int64_t val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamU8(const Interface &pm, const char *name, uint8_t &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamU8(Interface &pm, const char *name, uint8_t val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamU16(const Interface &pm, const char *name, uint16_t &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamU16(Interface &pm, const char *name, uint16_t val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamU32(const Interface &pm, const char *name, uint32_t &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamU32(Interface &pm, const char *name, uint32_t val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamU64(const Interface &pm, const char *name, uint64_t &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamU64(Interface &pm, const char *name, uint64_t val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamF32(const Interface &pm, const char *name, float &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamF32(Interface &pm, const char *name, float val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamF64(const Interface &pm, const char *name, double &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamF64(Interface &pm, const char *name, double val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamVec2(const Interface &pm, const char *name, physx::PxVec2 &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamVec2(Interface &pm, const char *name, const physx::PxVec2 &val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamVec3(const Interface &pm, const char *name, physx::PxVec3 &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamVec3(Interface &pm, const char *name, const physx::PxVec3 &val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamVec4(const Interface &pm, const char *name, physx::PxVec4 &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamVec4(Interface &pm, const char *name, const physx::PxVec4 &val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamQuat(const Interface &pm, const char *name, physx::PxQuat &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamQuat(Interface &pm, const char *name, const physx::PxQuat &val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamMat33(const Interface &pm, const char *name, physx::PxMat33 &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamMat33(Interface &pm, const char *name, const physx::PxMat33 &val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamMat44(const Interface &pm, const char *name, physx::PxMat44 &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamMat44(Interface &pm, const char *name, const physx::PxMat44 &val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamBounds3(const Interface &pm, const char *name, physx::PxBounds3 &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamBounds3(Interface &pm, const char *name, const physx::PxBounds3 &val) ; + +/// helper function to get an NvParameterized value +PX_INLINE bool getParamTransform(const Interface &pm, const char *name, physx::PxTransform &val); +/// helper function to set an NvParameterized value +PX_INLINE bool setParamTransform(Interface &pm, const char *name, const physx::PxTransform &val) ; + +} // namespace NvParameterized + + +#include "NvParamUtils.inl" + +#endif // NV_PARAM_UTILS_H diff --git a/APEX_1.4/include/nvparameterized/NvParamUtils.inl b/APEX_1.4/include/nvparameterized/NvParamUtils.inl new file mode 100644 index 00000000..5583c3c0 --- /dev/null +++ b/APEX_1.4/include/nvparameterized/NvParamUtils.inl @@ -0,0 +1,1367 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. +#include "NvParameterized.h" +#include "NvParameterizedTraits.h" + +namespace NvParameterized +{ + +#if PX_VC && !PX_PS4 + #pragma warning(push) + #pragma warning(disable: 4996) +#endif //!PX_PS4 + +#define MAX_SEARCH_NAME 1024 +#define MAX_SEARCH_NAMES 32 + +/// local_strcmp +int32_t local_strcmp(const char* s1, const char* s2); +/// local_stricmp +int32_t local_stricmp(const char* s1, const char* s2); + +/// Finds parameter in NvParameterized +struct ParameterFind +{ + /// Contructor + ParameterFind(const NvParameterized::Interface &iface) : mNameIndex(0), mNameCount(0), mResult(iface), mInterface(NULL), mError(false) + { + + } + + /// isDigit + bool isDigit(char c) const + { + return (c>='0' && c <='9'); + } + + /// setSearchName + bool setSearchName(const char *str) + { + bool ret = true; + + mNameIndex = 0; + mNameCount = 0; + mInterface = 0; + mError = false; + char *dest = mSearchName; + char *stop = &mSearchName[MAX_SEARCH_NAME-1]; + + char *head = mSearchName; + mArrayIndex[0] = -1; + + while ( *str && dest < stop ) + { + if ( *str == '[' ) + { + *dest++ = 0; + str++; + if ( isDigit(*str) ) + { + int32_t v = 0; + while ( isDigit(*str) ) + { + int32_t iv = *str-'0'; + v = v*10+iv; + str++; + } + if ( *str == ']' ) + { + mArrayIndex[mNameCount] = v; + } + else + { + ret = false; + break; + } + } + else + { + ret = false; + break; + } + } + else + { + if ( *str == '.' ) + { + if ( mNameCount < MAX_SEARCH_NAMES ) + { + mSearchNames[mNameCount] = head; + mNameCount++; + if ( mNameCount < MAX_SEARCH_NAMES ) + { + mArrayIndex[mNameCount] = -1; + } + *dest++ = 0; + str++; + head = dest; + } + else + { + ret = false; + break; + } + } + else + { + *dest++ = *str++; + } + } + } + + *dest = 0; + + if ( head && *head ) + { + if ( mNameCount < MAX_SEARCH_NAMES ) + { + mSearchNames[mNameCount] = head; + mNameCount++; + *dest++ = 0; + str++; + head = dest; + } + else + { + ret = false; + } + } + + return ret; + } + + /// done + bool done(void) const + { + bool ret = false; + if ( mInterface || mError ) ret = true; + return ret; + } + + /// getArrayIndex + int32_t getArrayIndex(void) + { + return mArrayIndex[mNameIndex]; + } + + /// nameMatch + bool nameMatch(const char *longName) const + { + bool ret = true; + + if (longName && strlen(longName)) + { +#if PX_GCC || PX_LINUX || PX_PS4 || PX_ANDROID || PX_OSX + if ( local_stricmp(longName,mSearchNames[mNameIndex]) == 0 ) +#else +#pragma warning(push) +#pragma warning(disable: 4996) + + if ( _stricmp(longName,mSearchNames[mNameIndex]) == 0 ) + +#pragma warning(pop) +#endif + { + ret = true; + } + else + { + ret = false; + } + } + + return ret; + } + + /// isCompleete + bool isComplete(void) const + { + return (mNameIndex+1) == mNameCount; + } + + /// pushNameMatch + bool pushNameMatch(void) + { + bool ret = false; + + if ( (mNameIndex+1) < mNameCount ) + { + mNameIndex++; + ret = true; + } + return ret; + } + + /// popNameMatch + void popNameMatch(void) + { + if ( mNameIndex ) + { + mNameIndex--; + } + } + + uint32_t mNameIndex; ///< mNameIndex + uint32_t mNameCount; ///< mNameCount + Handle mResult; ///< mResult + const NvParameterized::Interface *mInterface; ///< mInterface + bool mError; ///< mError; + char mSearchName[MAX_SEARCH_NAME]; ///< mSearchName + char *mSearchNames[MAX_SEARCH_NAMES]; ///< mSearchNames + int32_t mArrayIndex[MAX_SEARCH_NAMES]; ///< mArrayIndex +}; + +/// findParameter +PX_INLINE void findParameter(const NvParameterized::Interface &obj, + Handle &handle, + ParameterFind &pf, + bool fromArray=false) +{ + if ( pf.done() ) return; + + if ( handle.numIndexes() < 1 ) + { + obj.getParameterHandle("",handle); + } + + const Definition *pd = handle.parameterDefinition(); + const char *name = pd->name(); + DataType t = pd->type(); + + if ( fromArray || pf.nameMatch(name) ) + { + NvParameterized::Interface *paramPtr = 0; + if ( t == TYPE_REF ) + { + handle.getParamRef(paramPtr); + if ( paramPtr ) + { + if ( pf.pushNameMatch() ) + { + Handle newHandle(*paramPtr, ""); + findParameter(*paramPtr,newHandle,pf); + pf.popNameMatch(); + } + } + if ( pf.isComplete() ) + { + pf.mInterface = &obj; + pf.mResult = handle; + } + } + if ( t == TYPE_STRUCT ) + { + bool pushed = false; + if ( strlen(name) ) + { + pf.pushNameMatch(); + pushed = true; + } + int32_t count = pd->numChildren(); + for (int32_t i=0; i<count; i++) + { + handle.set(i); + findParameter(obj,handle,pf); + handle.popIndex(); + if ( pf.done() ) break; + } + if ( pushed ) + { + pf.popNameMatch(); + } + } + else if ( t == TYPE_ARRAY ) + { + int32_t arraySize; + handle.getArraySize(arraySize); + int32_t arrayIndex = pf.getArrayIndex(); + if ( arrayIndex == -1 && pf.isComplete() ) + { + pf.mInterface = &obj; + pf.mResult = handle; + } + else if ( arrayIndex >= 0 && arrayIndex < arraySize ) + { + handle.set(arrayIndex); + if ( pf.isComplete() ) + { + pf.mInterface = &obj; + pf.mResult = handle; + } + else + { + findParameter(obj,handle,pf,true); + } + handle.popIndex(); + } + else + { + + pf.mError = true; + } + } + else if ( pf.isComplete() ) + { + pf.mInterface = &obj; + pf.mResult = handle; + } + } +} + +PX_INLINE const Interface *findParam(const Interface &i,const char *long_name, Handle &result) +{ + const Interface *ret = 0; + result.setInterface((const NvParameterized::Interface *)0); + + ParameterFind pf(i); + if ( pf.setSearchName(long_name) ) + { + Handle handle(i); + findParameter(i,handle,pf); + result = pf.mResult; + ret = pf.mInterface; + } + return ret; +} + +PX_INLINE Interface *findParam(Interface &i,const char *long_name, Handle &result) +{ + Interface *ret = const_cast<Interface *>( + findParam(const_cast<const Interface &>(i),long_name,result)); + result.setInterface(ret); // Give write access to handle + return ret; +} + +/// Parameter list +struct ParameterList +{ + /// Constructor + ParameterList(const NvParameterized::Interface &iface,const char *className,const char *paramName,bool recursive,bool classesOnly,NvParameterized::Traits *traits) + : mNameIndex(0), + mResult(iface), + mInterface(NULL), + mClassName(className), + mParamName(paramName), + mRecursive(recursive), + mClassesOnly(classesOnly), + mTraits(traits), + mResultCount(0), + mMaxResults(0), + mResults(NULL) + { + + } + + ~ParameterList(void) + { + } + + /// nameMatch + bool nameMatch(const Interface *iface,const char * name,int32_t arrayIndex,DataType type,Handle &handle) + { + size_t slen = strlen(name); + + if ( mClassesOnly ) + { + if ( slen > 0 ) return true; + } + else + { + if ( slen == 0 ) return true; + } + + bool match = true; + if ( mClassName ) + { + const char *cname = iface->className(); + if ( local_strcmp(cname,mClassName) != 0 || strlen(name) ) + { + match = false; + } + } + if ( mParamName ) // if we specified a parameter name, than only include exact matches of this parameter name. + { + if (local_strcmp(mParamName,name) != 0 ) + { + match = false; + } + + } + if ( match ) + { + // ok..let's build the long name... + const char *longName = NULL; + char scratch[1024]; + scratch[0] = 0; + + if ( slen > 0 ) + { + + for (uint32_t i=0; i<mNameIndex; i++) + { + local_strcat_s(scratch, sizeof(scratch), mSearchName[i]); + if ( mArrayIndex[i] > 0 ) + { + char arrayIndexStr[32]; + arrayIndexStr[0] = 0; + local_strcat_s(arrayIndexStr, sizeof(arrayIndexStr), "[0]"); + //sprintf_s(arrayIndexStr, sizeof(arrayIndexStr), "[%d]", 0); //mArrayIndex[i]); + local_strcat_s(scratch, sizeof(scratch), arrayIndexStr); + } + local_strcat_s(scratch, sizeof(scratch),"."); + } + + local_strcat_s(scratch, sizeof(scratch),name); + uint32_t len = (uint32_t)strlen(scratch); + char *temp = (char *)mTraits->alloc(len+1); + temp[0] = 0; + local_strcat_s(temp, len+1, scratch); + longName = temp; + if ( type == TYPE_ARRAY ) + { + handle.getArraySize(arrayIndex); + } + } + + ParamResult pr(name,longName,iface->className(),iface->name(), handle, arrayIndex, type ); + + if ( mResultCount >= mMaxResults ) + { + mMaxResults = mMaxResults ? mMaxResults*2 : 32; + ParamResult *results = (ParamResult *)mTraits->alloc(sizeof(ParamResult)*mMaxResults); + if ( mResults ) + { + for (uint32_t i=0; i<mResultCount; i++) + { + results[i] = mResults[i]; + } + } + mResults = results; + } + mResults[mResultCount] = pr; + mResultCount++; + } + + return true; // always matches.... + } + + /// pushName + bool pushName(const char *name,int32_t arrayIndex) + { + mSearchName[mNameIndex] = name; + mArrayIndex[mNameIndex] = arrayIndex; + mNameIndex++; + return true; + } + + /// popNameMatch + void popNameMatch(void) + { + if ( mNameIndex ) + { + mNameIndex--; + } + } + + /// isRecursive + bool isRecursive(void) const { return mRecursive; } + + /// getResultCount + uint32_t getResultCount(void) const { return mResultCount; } + + /// getResults + ParamResult * getResults(void) const { return mResults; } + + uint32_t mNameIndex; ///< mNameIndex + Handle mResult; ///< mResult + const NvParameterized::Interface *mInterface; ///< mInterface + const char * mClassName; ///< mClassName + const char * mParamName; ///< mParamName + bool mRecursive; ///< mRecursive + bool mClassesOnly; ///< mClassesOnly + NvParameterized::Traits *mTraits; ///< mTraits + uint32_t mResultCount; ///< mResultCount + uint32_t mMaxResults; ///< mMaxResults + ParamResult *mResults; ///< mResults + const char *mSearchName[MAX_SEARCH_NAME]; ///< mSearchName + int32_t mArrayIndex[MAX_SEARCH_NAME]; ///< mArrayIndex + +}; + +/// listParameters +PX_INLINE void listParameters(const NvParameterized::Interface &obj, + Handle &handle, + ParameterList &pf, + int32_t parentArraySize) +{ + if ( handle.numIndexes() < 1 ) + { + obj.getParameterHandle("",handle); + } + + const Definition *pd = handle.parameterDefinition(); + const char *name = pd->name(); + DataType t = pd->type(); + + if ( pf.nameMatch(&obj,name,parentArraySize,t,handle) ) + { + NvParameterized::Interface *paramPtr = 0; + if ( t == TYPE_REF ) + { + handle.getParamRef(paramPtr); + } + if ( t == TYPE_STRUCT ) + { + bool pushed=false; + if ( strlen(name) ) + { + pf.pushName(name,parentArraySize); + pushed = true; + } + int32_t count = pd->numChildren(); + for (int32_t i=0; i<count; i++) + { + handle.set(i); + listParameters(obj,handle,pf,0); + handle.popIndex(); + } + if ( pushed ) + { + pf.popNameMatch(); + } + } + else if ( t == TYPE_ARRAY ) + { + int32_t arraySize; + handle.getArraySize(arraySize); + if ( arraySize > 0 ) + { + for (int32_t i=0; i<arraySize; i++) + { + handle.set(i); + listParameters(obj,handle,pf,arraySize); + const Definition *elemPd = handle.parameterDefinition(); + DataType elemType = elemPd->type(); + handle.popIndex(); + if ( !(elemType == TYPE_STRUCT || elemType == TYPE_ARRAY || elemType == TYPE_REF) ) + { + break; + } + } + } + } + else if ( t == TYPE_REF && pf.isRecursive() ) + { + if ( paramPtr && pd->isIncludedRef() ) + { + if ( pf.pushName(name,parentArraySize) ) + { + Handle newHandle(*paramPtr, ""); + listParameters(*paramPtr,newHandle,pf,0); + pf.popNameMatch(); + } + } + } + } +} + + +/** +\brief Gets every parameter in an NvParameterized Interface class +\note The return pointer is allocated by the NvParameterized Traits class and should be freed by calling releaseParamList +*/ +PX_INLINE const ParamResult * getParamList(const Interface &i,const char *className,const char *paramName,uint32_t &count,bool recursive,bool classesOnly,NvParameterized::Traits *traits) +{ + + PX_UNUSED(className); + + ParameterList pl(i,className,paramName,recursive,classesOnly,traits); + + Handle handle(i); + listParameters(i,handle,pl,0); + + count = pl.getResultCount(); + + return pl.getResults(); +} + +PX_INLINE void releaseParamList(uint32_t resultCount,const ParamResult *results,NvParameterized::Traits *traits) +{ + if ( results ) + { + for (uint32_t i=0; i<resultCount; i++) + { + const ParamResult &r = results[i]; + if ( r.mLongName ) + { + traits->free( (void *)r.mLongName ); + } + } + traits->free((void *)results); + } +} + +/// Calls back for every reference. +PX_INLINE void getReferences(const Interface &iface, + Handle &handle, + ReferenceInterface &cb, + bool named, + bool included, + bool recursive) +{ + if ( handle.numIndexes() < 1 ) + iface.getParameterHandle("",handle); + + NvParameterized::Interface *paramPtr = 0; + + const Definition *pd = handle.parameterDefinition(); + switch( pd->type() ) + { + case TYPE_REF: + handle.getParamRef(paramPtr); + if ( !paramPtr ) + break; + + if ( !pd->isIncludedRef() ) + { + if( named ) + cb.referenceCallback(handle); + } + else + { + if( included ) + cb.referenceCallback(handle); + + if ( recursive ) + { + Handle newHandle(*paramPtr, ""); + getReferences(*paramPtr,newHandle,cb,named,included,recursive); + } + } + break; + + case TYPE_STRUCT: + { + int32_t count = pd->numChildren(); + for (int32_t i=0; i<count; i++) + { + handle.set(i); + getReferences(iface,handle,cb,named,included,recursive); + handle.popIndex(); + } + + break; + } + + case TYPE_ARRAY: + { + int32_t arraySize; + handle.getArraySize(arraySize); + if ( arraySize <= 0 ) + break; + + const Definition *elemPd = pd->child(0); + bool scan = elemPd->type() == TYPE_ARRAY || elemPd->type() == TYPE_REF || elemPd->type() == TYPE_STRUCT; + + if ( scan ) + { + for (int32_t i=0; i<arraySize; i++) + { + handle.set(i); + getReferences(iface,handle,cb,named,included,recursive); + handle.popIndex(); + } + } + + break; + } +NV_PARAMETRIZED_NO_AGGREGATE_AND_REF_DATATYPE_LABELS + default: + break; + } +} + +PX_INLINE void getReferences(const Interface &i, + ReferenceInterface &cb, + bool named, + bool included, + bool recursive) +{ + Handle handle(i); + getReferences(i,handle,cb,named,included,recursive); +} + +/// WrappedNamedReference +class WrappedNamedReference: public ReferenceInterface +{ + NamedReferenceInterface &wrappedReference; + + ///Silence warnings on unable to generate assignment operator + template<typename T> void operator =(T) {} + void operator =(WrappedNamedReference) {} +public: + + /// refCount + uint32_t refCount; + + virtual ~WrappedNamedReference() {} + + /// Constructor + WrappedNamedReference(NamedReferenceInterface &wrappedReference_): wrappedReference(wrappedReference_), refCount(0) {} + + /// referenceCallback + void referenceCallback(Handle &handle) + { + Interface *iface; + handle.getParamRef(iface); + const char *name = wrappedReference.namedReferenceCallback(iface->className(), iface->name(), handle); + if( name ) + { + iface->setName(name); + ++refCount; + } + } +}; + +PX_INLINE uint32_t getNamedReferences(const Interface &i, + NamedReferenceInterface &namedReference, + bool recursive) +{ + WrappedNamedReference reference(namedReference); + getReferences(i, reference, true, false, recursive); + return reference.refCount; +} + + +PX_INLINE bool getParamBool(const Interface &pm, const char *name, bool &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamBool(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamBool(Interface &pm, const char *name, bool value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamBool(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// string +PX_INLINE bool getParamString(const Interface &pm, const char *name, const char *&value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamString(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamString(Interface &pm, const char *name, const char *value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamString(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// enum +PX_INLINE bool getParamEnum(const Interface &pm, const char *name, const char *&value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamEnum(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamEnum(Interface &pm, const char *name, const char *value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamEnum(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// reference +PX_INLINE bool getParamRef(const Interface &pm, const char *name, NvParameterized::Interface *&value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamRef(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamRef(Interface &pm, const char *name, NvParameterized::Interface *value, bool doDestroyOld) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamRef(value, doDestroyOld); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool initParamRef(Interface &pm, const char *name, const char *className, bool doDestroyOld) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.initParamRef(className, doDestroyOld); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool initParamRef(Interface &pm, const char *name, const char *className, const char *objName, bool doDestroyOld) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.initParamRef(className, doDestroyOld); + NvParameterized::Interface *ref; + handle.getParamRef(ref); + if (ref) + ref->setName(objName); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// I8 +PX_INLINE bool getParamI8(const Interface &pm, const char *name, int8_t &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamI8(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamI8(Interface &pm, const char *name, int8_t value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamI8(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// I16 +PX_INLINE bool getParamI16(const Interface &pm, const char *name, int16_t &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamI16(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamI16(Interface &pm, const char *name, int16_t value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamI16(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// I32 +PX_INLINE bool getParamI32(const Interface &pm, const char *name, int32_t &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamI32(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamI32(Interface &pm, const char *name, int32_t value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamI32(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// I64 +PX_INLINE bool getParamI64(const Interface &pm, const char *name, int64_t &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamI64(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamI64(Interface &pm, const char *name, int64_t value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamI64(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// U8 +PX_INLINE bool getParamU8(const Interface &pm, const char *name, uint8_t &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamU8(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamU8(Interface &pm, const char *name, uint8_t value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamU8(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// U16 +PX_INLINE bool getParamU16(const Interface &pm, const char *name, uint16_t &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamU16(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamU16(Interface &pm, const char *name, uint16_t value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamU16(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// U32 +PX_INLINE bool getParamU32(const Interface &pm, const char *name, uint32_t &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamU32(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamU32(Interface &pm, const char *name, uint32_t value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamU32(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// U64 +PX_INLINE bool getParamU64(const Interface &pm, const char *name, uint64_t &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamU64(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamU64(Interface &pm, const char *name, uint64_t value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamU64(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// F32 +PX_INLINE bool getParamF32(const Interface &pm, const char *name, float &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamF32(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamF32(Interface &pm, const char *name, float value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamF32(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// F64 +PX_INLINE bool getParamF64(const Interface &pm, const char *name, double &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamF64(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamF64(Interface &pm, const char *name, double value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamF64(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// Vec2 +PX_INLINE bool getParamVec2(const Interface &pm, const char *name, physx::PxVec2 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamVec2(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamVec2(Interface &pm, const char *name, const physx::PxVec2 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamVec2(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// Vec3 +PX_INLINE bool getParamVec3(const Interface &pm, const char *name, physx::PxVec3 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamVec3(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamVec3(Interface &pm, const char *name, const physx::PxVec3 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamVec3(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// Vec4 +PX_INLINE bool getParamVec4(const Interface &pm, const char *name, physx::PxVec4 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamVec4(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamVec4(Interface &pm, const char *name, const physx::PxVec4 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamVec4(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// Quat +PX_INLINE bool getParamQuat(const Interface &pm, const char *name, physx::PxQuat &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamQuat(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamQuat(Interface &pm, const char *name, const physx::PxQuat &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamQuat(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// Bounds3 +PX_INLINE bool getParamBounds3(const Interface &pm, const char *name, physx::PxBounds3 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamBounds3(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamBounds3(Interface &pm, const char *name, const physx::PxBounds3 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamBounds3(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// Mat33 +PX_INLINE bool getParamMat33(const Interface &pm, const char *name, physx::PxMat33 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamMat33(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamMat33(Interface &pm, const char *name, const physx::PxMat33 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamMat33(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// Mat44 +PX_INLINE bool getParamMat44(const Interface &pm, const char *name, physx::PxMat44 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamMat44(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamMat44(Interface &pm, const char *name, const physx::PxMat44 &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.setParamMat44(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +// Transform +PX_INLINE bool getParamTransform(const Interface &pm, const char *name, physx::PxTransform &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getParamTransform(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool setParamTransform(Interface &pm, const char *name, const physx::PxTransform &value) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + handle.setInterface( iface ); // set mIsConst to false + ret = handle.setParamTransform(value); + } + return (ret == NvParameterized::ERROR_NONE); +} + + +PX_INLINE bool getParamArraySize(const Interface &pm, const char *name, int32_t &arraySize) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + const NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.getArraySize(arraySize); + } + return (ret == NvParameterized::ERROR_NONE); +} + +PX_INLINE bool resizeParamArray(Interface &pm, const char *name, int32_t newSize) +{ + ErrorType ret = NvParameterized::ERROR_INVALID_PARAMETER_NAME; + NvParameterized::Handle handle(pm); + NvParameterized::Interface *iface = findParam(pm,name,handle); + if ( iface ) + { + ret = handle.resizeArray(newSize); + } + return (ret == NvParameterized::ERROR_NONE); +} + +#if PX_VC && !PX_PS4 + #pragma warning(pop) +#endif //!PX_PS4 + +} diff --git a/APEX_1.4/include/nvparameterized/NvParameterized.h b/APEX_1.4/include/nvparameterized/NvParameterized.h new file mode 100644 index 00000000..902a52b0 --- /dev/null +++ b/APEX_1.4/include/nvparameterized/NvParameterized.h @@ -0,0 +1,1812 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. + +#ifndef NV_PARAMETERIZED_H +#define NV_PARAMETERIZED_H + +/** + * APEX uses a framework called NvParameterized for storing asset and actor data. + * NvParameterized classes provide reflection on every parameter they include making it + * effective for serialization and auto-generation of user interfaces for tools.<br> + * + * NvParameterized stores data in C++ classes which are auto-generated from their + * descriptions written in a special domain specific language (DSL). Description files + * contain information on internal layout and various high-level metadata of corresponding + * classes and their members. All generated classes implement special interface for + * run time reflection and modification of data. + * */ + +/*! +\file +\brief NvParameterized classes +*/ + +#include "foundation/PxVec2.h" +#include "foundation/PxVec3.h" +#include "foundation/PxVec4.h" +#include "foundation/PxQuat.h" +#include "foundation/PxBounds3.h" +#include "foundation/PxMat44.h" +#include <stdio.h> +#include <stdarg.h> +#include <new> // for placement new + +PX_PUSH_PACK_DEFAULT + +//! \brief NvParameterized namespace +namespace NvParameterized +{ + +class Interface; +class Traits; + +/** +\brief Various errors that may be returned from NvParameterized calls +*/ +enum ErrorType +{ + ERROR_NONE = 0, + ERROR_TYPE_NOT_SUPPORTED, + ERROR_INDEX_OUT_OF_RANGE, + ERROR_INVALID_PARAMETER_NAME, + ERROR_INVALID_PARAMETER_HANDLE, + ERROR_CAST_FAILED, + ERROR_INVALID_ENUM_VAL, + ERROR_SYNTAX_ERROR_IN_NAME, + ERROR_IS_LEAF_NODE, + ERROR_RESULT_BUFFER_OVERFLOW, + ERROR_NAME_DOES_NOT_MATCH_DEFINITION, + ERROR_NOT_AN_ARRAY, + ERROR_ARRAY_SIZE_IS_FIXED, + ERROR_ARRAY_RESIZING_IS_NOT_SUPPORTED, + ERROR_ARRAY_IS_TOO_SMALL, + ERROR_INVALID_ARRAY_DIMENSION, + ERROR_INVALID_ARRAY_SIZE, + ERROR_PARAMETER_HANDLE_DOES_NOT_MATCH_CLASS, + ERROR_MEMORY_ALLOCATION_FAILURE, + ERROR_INVALID_REFERENCE_INCLUDE_HINT, + ERROR_INVALID_REFERENCE_VALUE, + ERROR_PARAMETER_HANDLE_NOT_INITIALIZED, + ERROR_PARAMETER_DEFINITIONS_DO_NOT_MATCH, + ERROR_HANDLE_MISSING_INTERFACE_POINTER, + ERROR_HANDLE_INVALID_INTERFACE_POINTER, + ERROR_INVALID_CALL_ON_NAMED_REFERENCE, + ERROR_NOT_IMPLEMENTED, + ERROR_OBJECT_CONSTRUCTION_FAILED, + ERROR_MODIFY_CONST_HANDLE +}; + +/** +\brief These types are supported in NvParameterized schemas +\warning Do not change values of enums! +*/ +enum DataType +{ + TYPE_UNDEFINED = 0, + + /** + \brief Array type, size may be static or dynamic + \see Definition::arraySizeIsFixed(), Handle::resizeArray(), Handle::getArraySize() + */ + TYPE_ARRAY = 1, + + TYPE_STRUCT = 2, + + TYPE_BOOL = 3, + /** + \brief String type, represented by a const char pointer + \see Handle::getParamString(), Handle::setParamString() + */ + TYPE_STRING = 4, + + /** + \brief Enum type, represented by a const char pointer + \see Definition::numEnumVals(), Definition::enumVal(), Handle::getParamEnum(), Handle::setParamEnum() + */ + TYPE_ENUM = 5, + + /** + \brief Reference type, may be a named or included reference + + References are intended to be used in instances where a class needs either a + named reference (an emitter asset references an IOFX and IOS asset), or an + included reference (a destructible asset that serializes an APEX render mesh). + References may also used to create a unions within a class. Each reference will + contain one or more variants to allow for unions. + + \see Handle::initParamRef(), Definition::numRefVariants(), Definition::refVariantVal(), Handle::initParamRef(), Handle::getParamRef(), Handle::setParamRef() + */ + TYPE_REF = 6, + + TYPE_I8 = 7, + TYPE_I16 = 8, + TYPE_I32 = 9, + TYPE_I64 = 10, + + TYPE_U8 = 11, + TYPE_U16 = 12, + TYPE_U32 = 13, + TYPE_U64 = 14, + + TYPE_F32 = 15, + TYPE_F64 = 16, + + TYPE_VEC2 = 17, + TYPE_VEC3 = 18, + TYPE_VEC4 = 19, + TYPE_QUAT = 20, + TYPE_MAT33 = 21, + TYPE_BOUNDS3 = 23, + TYPE_MAT44 = 24, + + TYPE_POINTER = 25, + + TYPE_TRANSFORM = 26, + + TYPE_MAT34 = 27, + + TYPE_LAST +}; + +/** +\brief Provides hints about the parameter definition + +\see Definition +*/ +class Hint +{ + public: + + /** + \brief Destructor + */ + virtual ~Hint() {} + /** + \brief Returns the name of the hint + */ + virtual const char * name(void) const = 0; + + /** + \brief Returns the type of the hint + */ + virtual DataType type(void) const = 0; + + /** + \brief Returns the unsigned 64-bit value of the hint + \note Undefined results if the type != TYPE_U64 + */ + virtual uint64_t asUInt(void) const = 0; + + /** + \brief Returns the 64-bit floating point value of the hint + \note Undefined results if the type != TYPE_FU64 + */ + virtual double asFloat(void) const = 0; + + /** + \brief Returns the const character pointer for hint + \note Undefined results if the type != TYPE_STRING + */ + virtual const char * asString(void) const = 0; + + /** + \brief Set the value if the hint is a 64bit unsigned type + */ + virtual bool setAsUInt(uint64_t v) = 0; + + private: +}; + +/** +\brief Provides information about a parameter +*/ +class Definition +{ +public: + + /** + \brief Destructor + */ + virtual ~Definition() {} + + /** + \brief Destroys the Definition object and all nested dynamic objects contained within + */ + virtual void destroy() = 0; + + /** + \brief Returns the number of hints in the parameter Definition + */ + virtual int32_t numHints(void) const = 0; + + /** + \brief Returns the Hint located at the index + \returns NULL if index >= Hint::numHints() + */ + virtual const Hint * hint(int32_t index) const = 0; + + /** + \brief Returns the Hint that matches the input name + \returns NULL if name does not match any of the Definition's hints + */ + virtual const Hint * hint(const char *name) const = 0; + + /** + \brief Store parameter hints + \warning Only for internal use + */ + virtual void setHints(const Hint **hints, int32_t n) = 0; + + /** + \brief Add parameter hint + \warning Only for internal use + */ + virtual void addHint(Hint *hint) = 0; + + /** + \brief Returns this Definition's parent Definition + \returns NULL if at the top level + */ + virtual const Definition * parent(void) const = 0; + + /** + \brief Returns this Definition's top most ancestor + */ + virtual const Definition * root(void) const = 0; + + /** + \brief Returns the name of the parameter + */ + virtual const char * name(void) const = 0; + + /** + \brief Returns the long name of the parameter + If the parameter is a member of a struct or an array the long name will contain these + parent names + */ + virtual const char * longName(void) const = 0; + + /** + \brief Returns the name of parameter's struct type + \returns NULL if not struct + */ + virtual const char * structName(void) const = 0; + + /** + \brief Returns the parameter type + */ + virtual DataType type(void) const = 0; + + /** + \brief Return the parameter type in string form + */ + virtual const char* typeString() const = 0; + + /** + \brief Returns the number of variants this parameter could be + A reference is sometimes a union of different types, each different type is referred to as + a "variant". Variants can be used in either included or named references. + */ + virtual int32_t numRefVariants(void) const = 0; + + /** + \brief Given the ref variant name, get its val index + \returns -1 if input ref_val is not found + */ + virtual int32_t refVariantValIndex( const char * ref_val ) const = 0; + + /** + \brief Get the string value of the reference variant + */ + virtual const char * refVariantVal(int32_t index) const = 0; + + /** + \brief Returns the number of enums for the parameter + */ + virtual int32_t numEnumVals(void) const = 0; + + /** + \brief Given the enum string, get the enum val index + \returns -1 if input enum_val is not found + */ + virtual int32_t enumValIndex( const char * enum_val ) const = 0; + + /** + \brief Returns the Enum string located at the index + \returns NULL if index >= Hint::numEnumVals() + */ + virtual const char * enumVal(int32_t index) const = 0; + + /** + \brief Store possible enum values for TYPE_ENUM parameter + \warning Only for internal use + */ + virtual void setEnumVals(const char **enum_vals, int32_t n) = 0; + + /** + \brief Add new enum value to a list of possible enum values for TYPE_ENUM parameter + \warning Only for internal use + */ + virtual void addEnumVal(const char *enum_val) = 0; + + /** + \brief Returns custom alignment if parameter uses it; otherwise returns 0 + */ + virtual uint32_t alignment(void) const = 0; + + /** + \brief Returns custom padding if parameter uses it; otherwise returns 0 + */ + virtual uint32_t padding(void) const = 0; + + /** + \brief Returns the number of dimensions of a static array + */ + virtual int32_t arrayDimension(void) const = 0; + + /** + \brief Returns the array size of a static array + \returns 0 for dynamic arrays + */ + virtual int32_t arraySize(int32_t dimension = 0) const = 0; + + /** + \brief Used to determine if an array is static or dynamic + */ + virtual bool arraySizeIsFixed(void) const = 0; + + /** + \brief Set size of static array + \warning Only for internal use + */ + virtual bool setArraySize(int32_t size) = 0; // -1 if the size is not fixed + + /** + \brief Used to determine if parameter is aggregate (TYPE_STRUCT or TYPE_ARRAY) or not. + */ + virtual bool isLeaf(void) const = 0; + + /** + \brief Used to determine if reference is included or not. + */ + virtual bool isIncludedRef(void) const = 0; + + /** + \brief Returns the number of children (for a struct or static array) + */ + virtual int32_t numChildren(void) const = 0; + + /** + \brief Access definition of i-th child parameter. + */ + virtual const Definition *child(int32_t index) const = 0; + + /** + \brief Access definition of child parameter with given name + \warning Only used with TYPE_STRUCT + */ + virtual const Definition *child(const char *name, int32_t &index) const = 0; + + /** + \brief Store definitions of child parameters + \warning Only for internal use + */ + virtual void setChildren(Definition **children, int32_t n) = 0; + + /** + \brief Add definition of one morechild parameter + \warning Only for internal use + */ + virtual void addChild(Definition *child) = 0; + + /** + \brief Set indices of child handles which must be released when downsizing array + */ + virtual void setDynamicHandleIndicesMap(const uint8_t *indices, uint32_t numIndices) = 0; + + /** + \brief Get indices of child handles which must be released when downsizing array + */ + virtual const uint8_t * getDynamicHandleIndicesMap(uint32_t &outNumIndices) const = 0; + + /** + \brief Used to determine whether type is not an aggregate (array, ref or struct) + \param [in] simpleStructs structure of simple types is also considered simple + \param [in] simpleStrings strings are considered simple + */ + virtual bool isSimpleType(bool simpleStructs = true, bool simpleStrings = true) const = 0; +}; + +/** +\brief Provides access to individual parameters within the NvParameterized object +*/ +class Handle +{ +public: + + enum { MAX_DEPTH = 16 }; + + /** + \brief The constructor takes a pointer (if the user requires an instance before the ::NvParameterized::Interface exists) + */ + PX_INLINE Handle(::NvParameterized::Interface *iface); + + /** + \brief The constructor takes a reference + */ + PX_INLINE Handle(::NvParameterized::Interface &iface); + + /** + \brief The constructor takes a const interface + \note Handles which are constructed from const objects are not allowed to modify them. + */ + PX_INLINE Handle(const ::NvParameterized::Interface &iface); + + /** + \brief Copy constructor + */ + PX_INLINE Handle(const Handle ¶m_handle); + + /** + \brief This constructor allows the user to create a handle that initially points at a particular parameter in the instance + */ + PX_INLINE Handle(::NvParameterized::Interface &instance, const char *longName); + + /** + \brief This constructor allows the user to create a handle that initially points at a particular parameter in the instance + \note Handles which are constructed from const objects are not allowed to modify them. + */ + PX_INLINE Handle(const ::NvParameterized::Interface &instance, const char *longName); + + /** + \brief Get the parameter Definition for the handle's parameter + */ + PX_INLINE const Definition *parameterDefinition(void) const { return(mParameterDefinition); } + + /** + \brief Get the depth of the handle within the NvParameterized object + */ + PX_INLINE int32_t numIndexes(void) const { return(mNumIndexes); } + + /** + \brief Get the index at the specified depth within the NvParameterized object + */ + PX_INLINE int32_t index(int32_t i) const { return(mIndexList[i]); } + + /** + \brief Reduce the handle's depth within the NvParameterized object + */ + PX_INLINE int32_t popIndex(int32_t levels = 1); + + /** + \brief Set the Handle so it references a parameter in the specified instance with the name child_long_name + */ + PX_INLINE ErrorType set(const ::NvParameterized::Interface *instance, const Definition *root, const char *child_long_name); + + /** + \brief Set the Handle so it references a parameter in the specified instance with the name child_long_name + */ + PX_INLINE ErrorType set(const ::NvParameterized::Interface *instance, const char *child_long_name); + + /** + \brief Get the parameter specified by longName and set the Handle to point it + Given a long name like "mystruct.somearray[10].foo", it will return + a handle to that specific parameter. The handle can then be used to + set/get values, as long as it's a handle to a leaf node. + \note this method will not work if an included reference's child is included in the longName + */ + PX_INLINE ErrorType getParameter(const char *longName); + + /** + \brief Set the depth of the handle within the handle's parameter + + The set method is useful for accessing indices within an array of parameters or members + within a struct. + */ + PX_INLINE ErrorType set(int32_t child_index); + + /** + \brief Get a child handle of this handle + Sets handle to point to a child of this handle, with child_long_name being + relative to the current long name. + */ + PX_INLINE ErrorType getChildHandle(const ::NvParameterized::Interface *instance, const char *child_long_name, Handle &outHandle); + + /** + \brief Get a child handle of this handle + Sets handle to point to a direct child of this handle. Works with structs and arrays. + */ + PX_INLINE ErrorType getChildHandle(int32_t index, Handle &outHandle); + + /** + \brief Returns the long name of the parameter, with indexes into str. + \returns false if the long name didn't fit in str. + */ + PX_INLINE bool getLongName(char *str, uint32_t max_str_len) const; + + /** + \brief Reset all of the state data for the handle + */ + PX_INLINE void reset(); + + /** + \brief Does handle correspond to an existing Interface? + */ + PX_INLINE bool isConst(void) const { return(mIsConst); } + + /** + \brief Does handle correspond to a valid parameter? + */ + PX_INLINE bool isValid(void) const { return(mIsValid); } + + /** + \brief Same as isValid + */ + PX_INLINE operator bool() const { return(isValid()); } + + /** + \brief Return user data stored in handle + */ + PX_INLINE const void *userData(void) const { return(mUserData); } + + /** + \brief Return user data stored in handle + */ + PX_INLINE void *userData(void) { return(mUserData); } + + /** + \brief Store user data in handle + */ + PX_INLINE void setUserData(void *user_data) { mUserData = user_data; } + + /** + \brief Get associated NvParameterized object + \note Will return NULL in case of const handle (use getConstInterface instead) + */ + PX_INLINE ::NvParameterized::Interface * getInterface(void) const { return mIsConst ? 0 : mInterface; } + + /** + \brief Get associated NvParameterized object + */ + PX_INLINE const ::NvParameterized::Interface * getConstInterface(void) const { return mInterface; } + + /** + \brief Set associated NvParameterized object + */ + PX_INLINE void setInterface(::NvParameterized::Interface *iface) { mIsConst = false; mInterface = iface; } + + /** + \brief Set associated NvParameterized object + */ + PX_INLINE void setInterface(const ::NvParameterized::Interface *iface) { mIsConst = true; mInterface = (::NvParameterized::Interface *)iface; } + + /** + \brief Initialize a Reference parameter + + \param [in] chosenRefStr This string must be one of the strings returned from + Definition::refVariantVal() + + \param [in] doDestroyOld Sets whether the previous object should be destroyed or not + + \see Interface::initParamRef(), Definition::numRefVariants(), Definition::refVariantVal() + */ + PX_INLINE ErrorType initParamRef(const char *chosenRefStr = 0, bool doDestroyOld = false); + + /** + \brief Store this Handle's parameter to a string + \param [in] buf this buffer is used to store any strings that need to be constructed + \param [in] bufSize size of buf + \param [out] ret this contains a pointer to the value as a string, it may or may not + be equal to buf, depending if the value had to be constructed dynamically or if it already exists as a static string + */ + PX_INLINE ErrorType valueToStr(char *buf, uint32_t bufSize, const char *&ret); + + /** + \brief Store the string to this Handle's parameter + \returns ERROR_TYPE_NOT_SUPPORTED if the Handle's parameter type is an array, struct, or reference + \returns ERROR_NONE if the Handle's parameter type is a simple type (u32, i32, vec3, etc) + */ + PX_INLINE ErrorType strToValue(const char *str, const char **endptr); + + /** + \brief Resize the array that the Handle points to + */ + ErrorType resizeArray(int32_t new_size); + + /** + \brief Get the array size for the given array dimension + */ + PX_INLINE ErrorType getArraySize(int32_t &size, int32_t dimension = 0) const; + + /** + \brief Swap two elements of an array + */ + PX_INLINE ErrorType swapArrayElements(uint32_t firstElement, uint32_t secondElement); + + // These functions wrap the raw(Get|Set)XXXXX() methods. They deal with + // error handling and casting. + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamBool(bool &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamBool(bool val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamBoolArray(bool *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamBoolArray(const bool *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamString(const char *&val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamString(const char *val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamStringArray(char **array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamStringArray(const char **array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamEnum(const char *&val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamEnum(const char *val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamEnumArray(char **array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamEnumArray(const char **array, int32_t n, int32_t offset = 0) ; + + /** + \see Interface::getParamRef() + */ + PX_INLINE ErrorType getParamRef(::NvParameterized::Interface *&val) const ; + + /** + \see Interface::getParamRefArray() + */ + PX_INLINE ErrorType getParamRefArray(::NvParameterized::Interface **array, int32_t n, int32_t offset = 0) const ; + + /** + \see Interface::setParamRef() + */ + PX_INLINE ErrorType setParamRef(::NvParameterized::Interface * val, bool doDestroyOld = false) ; + + /** + \see Interface::setParamRefArray() + */ + PX_INLINE ErrorType setParamRefArray(::NvParameterized::Interface **array, int32_t n, int32_t offset = 0, bool doDestroyOld = false) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamI8(int8_t &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamI8(int8_t val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamI8Array(int8_t *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamI8Array(const int8_t *val, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamI16(int16_t &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamI16(int16_t val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamI16Array(int16_t *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamI16Array(const int16_t *val, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamI32(int32_t &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamI32(int32_t val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamI32Array(int32_t *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamI32Array(const int32_t *val, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamI64(int64_t &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamI64(int64_t val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamI64Array(int64_t *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamI64Array(const int64_t *val, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamU8(uint8_t &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamU8(uint8_t val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamU8Array(uint8_t *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamU8Array(const uint8_t *val, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamU16(uint16_t &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamU16(uint16_t val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamU16Array(uint16_t *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamU16Array(const uint16_t *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamU32(uint32_t &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamU32(uint32_t val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamU32Array(uint32_t *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamU32Array(const uint32_t *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamU64(uint64_t &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamU64(uint64_t val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamU64Array(uint64_t *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamU64Array(const uint64_t *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamF32(float &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamF32(float val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamF32Array(float *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamF32Array(const float *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamF64(double &val) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamF64(double val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamF64Array(double *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamF64Array(const double *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamVec2(const physx::PxVec2 &val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamVec2(physx::PxVec2 &val) const ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamVec2Array(physx::PxVec2 *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamVec2Array(const physx::PxVec2 *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType setParamVec3(const physx::PxVec3 &val) ; + + /** + \brief Set param + */ + PX_INLINE ErrorType getParamVec3(physx::PxVec3 &val) const ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamVec3Array(physx::PxVec3 *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamVec3Array(const physx::PxVec3 *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType setParamVec4(const physx::PxVec4 &val) ; + + /** + \brief Set param + */ + PX_INLINE ErrorType getParamVec4(physx::PxVec4 &val) const ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamVec4Array(physx::PxVec4 *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamVec4Array(const physx::PxVec4 *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType setParamQuat(const physx::PxQuat &val) ; + + /** + \brief Set param + */ + PX_INLINE ErrorType getParamQuat(physx::PxQuat &val) const ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamQuatArray(physx::PxQuat *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamQuatArray(const physx::PxQuat *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType setParamMat33(const physx::PxMat33 &val) ; + + /** + \brief Set param + */ + PX_INLINE ErrorType getParamMat33(physx::PxMat33 &val) const ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamMat33Array(physx::PxMat33 *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamMat33Array(const physx::PxMat33 *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamMat44(const physx::PxMat44 &val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamMat44(physx::PxMat44 &val) const ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamMat44Array(physx::PxMat44 *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamMat44Array(const physx::PxMat44 *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamMat34Legacy(const float (&val)[12]) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamMat34Legacy(float (&val)[12]) const ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamMat34LegacyArray(float* array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamMat34LegacyArray(const float *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamBounds3(const physx::PxBounds3 &val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamBounds3(physx::PxBounds3 &val) const ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamBounds3Array(physx::PxBounds3 *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamBounds3Array(const physx::PxBounds3 *array, int32_t n, int32_t offset = 0) ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamTransform(const physx::PxTransform &val) ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamTransform(physx::PxTransform &val) const ; + + /** + \brief Get param + */ + PX_INLINE ErrorType getParamTransformArray(physx::PxTransform *array, int32_t n, int32_t offset = 0) const ; + + /** + \brief Set param + */ + PX_INLINE ErrorType setParamTransformArray(const physx::PxTransform *array, int32_t n, int32_t offset = 0) ; + + + /// Template version of setParamXxx + template <typename T> PX_INLINE ErrorType setParam(const T &val); + + /// Template version of getParamXxx + template <typename T> PX_INLINE ErrorType getParam(T &val) const; + + /// Template version of getParamXxxArray + template <typename T> PX_INLINE ErrorType getParamArray(T *array, int32_t n, int32_t offset = 0) const; + + /// Template version of setParamXxxArray + template <typename T> PX_INLINE ErrorType setParamArray(const T *array, int32_t n, int32_t offset = 0); + +private: + + PX_INLINE void pushIndex(int32_t index); + + bool mIsValid, mIsConst; + int32_t mNumIndexes; + int32_t mIndexList[MAX_DEPTH]; + const Definition *mParameterDefinition; + void *mUserData; + ::NvParameterized::Interface *mInterface; +}; + +/// A callback class for notification just prior to serialization +class SerializationCallback +{ +public: + virtual ~SerializationCallback() {} + /// Callback method + virtual void preSerialize(void* userData = NULL) = 0; +}; + + +/** +\brief Represents the interface to the NvParameterized object +*/ +class Interface +{ + friend class Handle; +public: + + /** + \brief Destructor + */ + virtual ~Interface() {} + + /** + \brief Destroys the NvParameterized object and all nested dynamic objects contained within + */ + virtual void destroy() = 0; + + /** + \brief Initializes all parameters to their default value + */ + virtual void initDefaults(void) = 0; + + /** + \brief Initializes all parameters with random values + */ + virtual void initRandom(void) = 0; + + /** + \brief Get the class name + */ + virtual const char * className(void) const = 0; + + /** + \brief Sets the class name + + This method is used for named references. The input name should be one of the possible variants. + \see Definition::numRefVariants(), Definition::refVariantVal() + */ + virtual void setClassName(const char *name) = 0; + + /** + \brief Get the name of the NvParameterized object + This method is used for named references. The name will typically specify an asset to be loaded. + */ + virtual const char * name(void) const = 0; + + /** + \brief Set the name of the NvParameterized object + This method is used for named references. The name will typically specify an asset to be loaded. + */ + virtual void setName(const char *name) = 0; + + /** + \brief Get the class version + */ + virtual uint32_t version(void) const = 0; + + /** + \brief Get the major part of class version + */ + virtual uint16_t getMajorVersion(void) const = 0; + + /** + \brief Get the minor part of class version + */ + virtual uint16_t getMinorVersion(void) const = 0; + + /** + \brief Get the class checksum. + \param bits contains the number of bits contained in the checksum + \returns A pointer to a constant array of uint32_t values representing the checksum + */ + virtual const uint32_t * checksum(uint32_t &bits) const = 0; + + /** + \brief Get the number of parameters contained in the NvParameterized object + */ + virtual int32_t numParameters(void) = 0; + + /** + \brief Get the definition of i-th parameter + */ + virtual const Definition *parameterDefinition(int32_t index) = 0; + + /** + \brief Get definition of root structure + */ + virtual const Definition *rootParameterDefinition(void) = 0; + + /** + \brief Get definition of root structure + */ + virtual const Definition *rootParameterDefinition(void) const = 0; + + /** + \brief Set the Handle to point to the parameter specified by longName + Given a long name like "mystruct.somearray[10].foo", it will return + a handle to that specific parameter. The handle can then be used to + set/get values, as long as it's a handle to a leaf node. + \note this method will not work if an included reference's child is included in the longName + */ + virtual ErrorType getParameterHandle(const char *longName, Handle &handle) const = 0; + + /** + \brief Set the Handle to point to the parameter specified by longName + Given a long name like "mystruct.somearray[10].foo", it will return + a handle to that specific parameter. The handle can then be used to + set/get values, as long as it's a handle to a leaf node. + \note this method will not work if an included reference's child is included in the longName + */ + virtual ErrorType getParameterHandle(const char *longName, Handle &handle) = 0; + + /// An application may set a callback function that is called immediately before serialization + virtual void setSerializationCallback(SerializationCallback *cb, void *userData = NULL) = 0; + + /// Called prior by Serializer to serialization + virtual ErrorType callPreSerializeCallback() const = 0; + + + /** + \brief Compares two NvParameterized objects + \param [in] obj The other ::NvParameterized::Interface object (this == obj) + \param [out] handlesOfInequality If the return value is False, these handles will contain the path to where definition or data is not identical + \param [in] numHandlesOfInequality The number of handles that can be written to. + \param [in] doCompareNotSerialized If false differences of parameters with DONOTSERIALIZE-hint are ignored. + \returns true if parameter definition tree is equal as well as parameter values + */ + virtual bool equals(const ::NvParameterized::Interface &obj, Handle* handlesOfInequality = NULL, uint32_t numHandlesOfInequality = 0, bool doCompareNotSerialized = true) const = 0; + + /** + \brief Checks if object satisfies schema constraints + \param [out] invalidHandles If the return value is False, these handles will contain the path to invalid data + \param [in] numInvalidHandles The number of handles that can be written to. + \returns true if all values satisfy constraints + */ + virtual bool areParamsOK(Handle *invalidHandles = NULL, uint32_t numInvalidHandles = 0) = 0; + + /** + \brief Copies an NvParameterized object + \param [in] src the src NvParameterized object will be copied to this object. It must be of the same type (class name). + */ + virtual ErrorType copy(const ::NvParameterized::Interface &src) = 0; + + /** + \brief Clones an NvParameterized object + \param [out] nullDestObject cloned object; note this is a *reference* to a pointer; the destination cloned object will be created and stored in this pointer; should be NULL on entry! + */ + virtual ErrorType clone(Interface *&nullDestObject) const = 0; + + /** + \brief Check that alignments of internal elements match the schema + \warning Only for internal use + */ + virtual bool checkAlignments() const = 0; + +protected: + /** + \brief Initialize a Reference parameter + + \note By default previous value of parameter isn't destroyed (bool doDestroyOld = false) + */ + virtual ErrorType initParamRef(const Handle &handle, const char *chosenRefStr = 0, bool doDestroyOld = false) = 0; + + // These functions wrap the raw(Get|Set)XXXXX() methods. They deal with + // error handling and casting. + + /** + \brief Get param + */ + virtual ErrorType getParamBool(const Handle &handle, bool &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamBool(const Handle &handle, bool val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamBoolArray(const Handle &handle, bool *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamBoolArray(const Handle &handle, const bool *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamString(const Handle &handle, const char *&val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamString(const Handle &handle, const char *val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamStringArray(const Handle &handle, char **array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamStringArray(const Handle &handle, const char **array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamEnum(const Handle &handle, const char *&val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamEnum(const Handle &handle, const char *val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamEnumArray(const Handle &handle, char **array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamEnumArray(const Handle &handle, const char **array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamRef(const Handle &handle, ::NvParameterized::Interface *&val) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamRefArray(const Handle &handle, ::NvParameterized::Interface **array, int32_t n, int32_t offset = 0) const = 0; + + /** + \note By default previous value of parameter is not destroyed (bool doDestroyOld = false) + */ + virtual ErrorType setParamRef(const Handle &handle, ::NvParameterized::Interface * val, bool doDestroyOld = false) = 0; + + /** + \note By default previous values of parameter are not destroyed (bool doDestroyOld = false) + */ + virtual ErrorType setParamRefArray(const Handle &handle, /*const*/ ::NvParameterized::Interface **array, int32_t n, int32_t offset = 0, bool doDestroyOld = false) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamI8(const Handle &handle, int8_t &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamI8(const Handle &handle, int8_t val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamI8Array(const Handle &handle, int8_t *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamI8Array(const Handle &handle, const int8_t *val, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamI16(const Handle &handle, int16_t &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamI16(const Handle &handle, int16_t val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamI16Array(const Handle &handle, int16_t *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamI16Array(const Handle &handle, const int16_t *val, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamI32(const Handle &handle, int32_t &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamI32(const Handle &handle, int32_t val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamI32Array(const Handle &handle, int32_t *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamI32Array(const Handle &handle, const int32_t *val, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamI64(const Handle &handle, int64_t &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamI64(const Handle &handle, int64_t val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamI64Array(const Handle &handle, int64_t *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamI64Array(const Handle &handle, const int64_t *val, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamU8(const Handle &handle, uint8_t &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamU8(const Handle &handle, uint8_t val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamU8Array(const Handle &handle, uint8_t *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamU8Array(const Handle &handle, const uint8_t *val, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamU16(const Handle &handle, uint16_t &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamU16(const Handle &handle, uint16_t val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamU16Array(const Handle &handle, uint16_t *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamU16Array(const Handle &handle, const uint16_t *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamU32(const Handle &handle, uint32_t &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamU32(const Handle &handle, uint32_t val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamU32Array(const Handle &handle, uint32_t *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamU32Array(const Handle &handle, const uint32_t *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamU64(const Handle &handle, uint64_t &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamU64(const Handle &handle, uint64_t val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamU64Array(const Handle &handle, uint64_t *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamU64Array(const Handle &handle, const uint64_t *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamF32(const Handle &handle, float &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamF32(const Handle &handle, float val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamF32Array(const Handle &handle, float *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamF32Array(const Handle &handle, const float *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamF64(const Handle &handle, double &val) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamF64(const Handle &handle, double val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamF64Array(const Handle &handle, double *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamF64Array(const Handle &handle, const double *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamVec2(const Handle &handle, const physx::PxVec2 &val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamVec2(const Handle &handle, physx::PxVec2 &val) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamVec2Array(const Handle &handle, physx::PxVec2 *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamVec2Array(const Handle &handle, const physx::PxVec2 *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamVec3(const Handle &handle, const physx::PxVec3 &val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamVec3(const Handle &handle, physx::PxVec3 &val) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamVec3Array(const Handle &handle, physx::PxVec3 *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamVec3Array(const Handle &handle, const physx::PxVec3 *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamVec4(const Handle &handle, const physx::PxVec4 &val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamVec4(const Handle &handle, physx::PxVec4 &val) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamVec4Array(const Handle &handle, physx::PxVec4 *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamVec4Array(const Handle &handle, const physx::PxVec4 *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamQuat(const Handle &handle, const physx::PxQuat &val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamQuat(const Handle &handle, physx::PxQuat &val) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamQuatArray(const Handle &handle, physx::PxQuat *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamQuatArray(const Handle &handle, const physx::PxQuat *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamMat33(const Handle &handle, const physx::PxMat33 &val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamMat33(const Handle &handle, physx::PxMat33 &val) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamMat33Array(const Handle &handle, physx::PxMat33 *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamMat33Array(const Handle &handle, const physx::PxMat33 *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamMat44(const Handle &handle, const physx::PxMat44 &val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamMat44(const Handle &handle, physx::PxMat44 &val) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamMat44Array(const Handle &handle, physx::PxMat44 *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamMat44Array(const Handle &handle, const physx::PxMat44 *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamMat34Legacy(const Handle &handle, const float (&val)[12]) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamMat34Legacy(const Handle &handle, float (&val)[12]) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamMat34LegacyArray(const Handle &handle, float *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamMat34LegacyArray(const Handle &handle, const float *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamBounds3(const Handle &handle, const physx::PxBounds3 &val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamBounds3(const Handle &handle, physx::PxBounds3 &val) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamBounds3Array(const Handle &handle, physx::PxBounds3 *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamTransform(const Handle &handle, const physx::PxTransform &val) = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamTransform(const Handle &handle, physx::PxTransform &val) const = 0; + + /** + \brief Get param + */ + virtual ErrorType getParamTransformArray(const Handle &handle, physx::PxTransform *array, int32_t n, int32_t offset = 0) const = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamTransformArray(const Handle &handle, const physx::PxTransform *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Set param + */ + virtual ErrorType setParamBounds3Array(const Handle &handle, const physx::PxBounds3 *array, int32_t n, int32_t offset = 0) = 0; + + /** + \brief Store value of parameter into a string + \see Handle::valueToStr + */ + virtual ErrorType valueToStr(const Handle &handle, char *buf, uint32_t bufSize, const char *&ret) = 0; + + /** + \brief Read value of parameter from string + \see Handle::strToValue + */ + virtual ErrorType strToValue(Handle &handle,const char *str, const char **endptr) = 0; // assigns this string to the value + + /** + \brief Resize array parameter + \see Handle::resizeArray + */ + virtual ErrorType resizeArray(const Handle &array_handle, int32_t new_size) = 0; + + /** + \brief Get size of array parameter + \see Handle::getArraySize + */ + virtual ErrorType getArraySize(const Handle &array_handle, int32_t &size, int32_t dimension = 0) const = 0; + + /** + \brief Swap two elements of an array + \see Handle::swapArrayElements + */ + virtual ErrorType swapArrayElements(const Handle &array_handle, uint32_t firstElement, uint32_t secondElement) = 0; +}; + +} // end of namespace + +#include "NvParameterized.inl" // inline the NvParamterHandle methods. + +PX_POP_PACK + +#endif // NV_PARAMETERIZED_H diff --git a/APEX_1.4/include/nvparameterized/NvParameterized.inl b/APEX_1.4/include/nvparameterized/NvParameterized.inl new file mode 100644 index 00000000..b7c2d2ce --- /dev/null +++ b/APEX_1.4/include/nvparameterized/NvParameterized.inl @@ -0,0 +1,1229 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. + + +/*! +\brief NvParameterized inline implementation +*/ + +namespace NvParameterized +{ + +#include "nvparameterized/NvParameterizedMacroses.h" + +#if PX_VC && !PX_PS4 + #pragma warning(push) + #pragma warning(disable: 4996) +#endif //!PX_PS4 + +#define IS_ALPHA(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z')) +#define IS_DIGIT(c) ((c) >= '0' && (c) <= '9') +#define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_DIGIT(c)) +#define IS_IDENTCHAR(c) (IS_ALPHANUM(c) || (c) == ' ' || (c) == '_') + +/** +\brief Enum of tokenizer result types +*/ +enum TokenizerResultType +{ + TOKENIZER_RESULT_NONE, + TOKENIZER_RESULT_BUFFER_OVERFLOW, + TOKENIZER_RESULT_SYNTAX_ERROR, + TOKENIZER_RESULT_STRUCT_MEMBER, + TOKENIZER_RESULT_ARRAY_INDEX +}; + +/** +\brief Get struct member token +*/ +PX_INLINE TokenizerResultType getStructMemberToken(const char *long_name, + char *token, + uint32_t max_token_len, + uint32_t &offset) +{ + PX_ASSERT(long_name != NULL); + PX_ASSERT(token != NULL); + PX_ASSERT(max_token_len > 1); + PX_ASSERT(IS_IDENTCHAR(long_name[0]) || long_name[0] == '.'); + + offset = 0; + + if(long_name[0] == '.') + offset++; + + uint32_t tokenLen = 0; + while(IS_IDENTCHAR(long_name[offset])) + { + if(offset == max_token_len - 1) + return(TOKENIZER_RESULT_BUFFER_OVERFLOW); + + token[tokenLen++] = long_name[offset++]; + } + + token[tokenLen++] = 0; + + if(long_name[offset] != 0 && long_name[offset] != '.' && long_name[offset] != '[') + return(TOKENIZER_RESULT_SYNTAX_ERROR); + + return(TOKENIZER_RESULT_STRUCT_MEMBER); +} + +/** +\brief Get array member token +*/ +PX_INLINE TokenizerResultType getArrayMemberToken(const char *long_name, + char *token, + uint32_t max_token_len, + uint32_t &offset) +{ + PX_ASSERT(long_name != NULL); + PX_ASSERT(token != NULL); + PX_ASSERT(max_token_len > 1); + PX_ASSERT(long_name[0] == '['); + + offset = 1; + + uint32_t tokenLen = 0; + while(long_name[offset] && IS_DIGIT(long_name[offset])) + { + if(tokenLen == max_token_len - 1) + return(TOKENIZER_RESULT_BUFFER_OVERFLOW); + + token[tokenLen++] = long_name[offset++]; + } + + token[tokenLen++] = 0; + + if(long_name[offset] != ']') + return(TOKENIZER_RESULT_SYNTAX_ERROR); + + offset++; + + return(TOKENIZER_RESULT_ARRAY_INDEX); +} + +/** +\brief Get next token +*/ +PX_INLINE TokenizerResultType getNextToken(const char *long_name, + char *token, + uint32_t max_token_len, + uint32_t &offset) +{ + PX_ASSERT(long_name != NULL); + PX_ASSERT(token != NULL); + PX_ASSERT(max_token_len > 1); + + if(long_name[0] == 0) + return(TOKENIZER_RESULT_NONE); + + if(long_name[0] == '.' || IS_IDENTCHAR(long_name[0])) + return(getStructMemberToken(long_name, token, max_token_len, offset)); + + if(long_name[0] == '[') + return(getArrayMemberToken(long_name, token, max_token_len, offset)); + + return(TOKENIZER_RESULT_SYNTAX_ERROR); +} + +#undef IS_ALPHA +#undef IS_DIGIT +#undef IS_ALPHANUM +#undef IS_IDENTCHAR + +/* + The local_strcat_s function appends strSource to strDestination and terminates the resulting string with a null character. + The initial character of strSource overwrites the terminating null character of strDestination. The behavior of strcat_s is + undefined if the source and destination strings overlap. Note that the second parameter is the total size of the buffer, not + the remaining size +*/ + +/** +\brief The local_strcat_s function appends strSource to strDestination and terminates the resulting string with a null character. +*/ +PX_INLINE int local_strcat_s(char* dest, size_t size, const char* src) +{ + size_t d, destStringLen, srcStringLen; + + if ( dest == NULL || + src == NULL || + size == 0 ) + { + return -1; + } + + destStringLen = strlen(dest); + srcStringLen = strlen(src); + d = srcStringLen + destStringLen; + + if ( size <= d ) + { + return -1; + } + + ::memcpy( &dest[destStringLen], src, srcStringLen ); + dest[d] = '\0'; + + return 0; +} + +/** +\brief The local_sprintf_s function wraps the va_list functionality required for PxVxprintf +*/ +int32_t local_sprintf_s( char * _DstBuf, size_t _DstSize, const char * _Format, ...); + +PX_INLINE Handle::Handle(::NvParameterized::Interface *iface) +{ + reset(); + mInterface = iface; + mIsConst = false; + if (mInterface != NULL) + mParameterDefinition = mInterface->rootParameterDefinition(); +} + +PX_INLINE Handle::Handle(::NvParameterized::Interface &iface) +{ + reset(); + mInterface = &iface; + mIsConst = false; + mParameterDefinition = mInterface->rootParameterDefinition(); +} + +PX_INLINE Handle::Handle(const ::NvParameterized::Interface &iface) +{ + reset(); + mInterface = const_cast< ::NvParameterized::Interface * >(&iface); + mIsConst = true; + mParameterDefinition = mInterface->rootParameterDefinition(); +} + +PX_INLINE Handle::Handle(const Handle ¶m_handle) +{ + reset(); + + if(param_handle.isValid()) + { + mNumIndexes = param_handle.mNumIndexes; + memcpy(mIndexList, param_handle.mIndexList, sizeof(int32_t) * mNumIndexes); + mParameterDefinition = param_handle.mParameterDefinition; + mIsValid = param_handle.mIsValid; + mIsConst = param_handle.mIsConst; + mInterface = param_handle.mInterface; + } + else + mIsConst = mIsValid = false; +} + + +PX_INLINE Handle::Handle(::NvParameterized::Interface &instance,const char *longName) +{ + mInterface = &instance; + mIsConst = false; + mInterface->getParameterHandle(longName, *this); +} + +PX_INLINE Handle::Handle(const ::NvParameterized::Interface &instance,const char *longName) +{ + mInterface = const_cast< ::NvParameterized::Interface *>(&instance); + mIsConst = true; + mInterface->getParameterHandle(longName, *this); +} + +PX_INLINE ErrorType Handle::getChildHandle(const ::NvParameterized::Interface *instance,const char *child_long_name, Handle &handle) +{ + handle = *this; + handle.mUserData = NULL; + return(handle.set(instance,child_long_name)); +} + +PX_INLINE ErrorType Handle::getParameter(const char *longName) +{ + if( !mInterface ) + { + return ERROR_HANDLE_MISSING_INTERFACE_POINTER; + } + + return mInterface->getParameterHandle(longName, *this); +} + +PX_INLINE ErrorType Handle::set(const ::NvParameterized::Interface *instance,const Definition *root,const char *child_long_name) +{ + PX_ASSERT(root->parent() == NULL); + + reset(); + mParameterDefinition = root; + mIsValid = true; + + return(set(instance,child_long_name)); +} + +PX_INLINE ErrorType Handle::set(const ::NvParameterized::Interface *instance,const char *child_long_name) +{ + PX_ASSERT(mParameterDefinition != NULL); + PX_ASSERT(child_long_name != NULL); + + if(!isValid()) + return(ERROR_INVALID_PARAMETER_HANDLE); + + mUserData = NULL; + + if(child_long_name[0] == 0) + { + return(ERROR_NONE); + } + + int32_t indexLevel = 0; + + mIsValid = false; + // while(1) causes C4127 warning + for( ; ; ) + { + char token[1024]; + uint32_t offset; + + TokenizerResultType Result = getNextToken(child_long_name, token, sizeof(token), offset); + + switch(Result) + { + case TOKENIZER_RESULT_NONE: + if(indexLevel == 0) + return(ERROR_INVALID_PARAMETER_NAME); + else + goto no_error; + + case TOKENIZER_RESULT_BUFFER_OVERFLOW: + return(ERROR_RESULT_BUFFER_OVERFLOW); + + case TOKENIZER_RESULT_SYNTAX_ERROR: + return(ERROR_SYNTAX_ERROR_IN_NAME); + + case TOKENIZER_RESULT_STRUCT_MEMBER: + { + if(mParameterDefinition->type() != TYPE_STRUCT) + return(ERROR_NAME_DOES_NOT_MATCH_DEFINITION); + + int32_t index; + mParameterDefinition = mParameterDefinition->child(token, index); + if(mParameterDefinition == NULL) + return(ERROR_INVALID_PARAMETER_NAME); + + pushIndex(index); + } + break; + + case TOKENIZER_RESULT_ARRAY_INDEX: + { + if(mParameterDefinition->type() != TYPE_ARRAY) + return(ERROR_NAME_DOES_NOT_MATCH_DEFINITION); + + int32_t index = atoi(token); + PX_ASSERT(index >= 0); + + int32_t arraySize=0; + if ( instance ) + { + Handle handle(*instance); + ErrorType err = instance->getParameterHandle( mParameterDefinition->longName(), handle ); + if(err != ERROR_NONE) + return(err); + handle.getArraySize(arraySize); + } + else + { + arraySize = mParameterDefinition->arraySize(); + } + + if(index >= arraySize ) + return(ERROR_INDEX_OUT_OF_RANGE); + + PX_ASSERT(mParameterDefinition->numChildren() == 1); + mParameterDefinition = mParameterDefinition->child(0); + + pushIndex(index); + } + break; + } + + child_long_name += offset; + indexLevel++; + } + +no_error: + + mIsValid = true; + return(ERROR_NONE); +} + +PX_INLINE ErrorType Handle::set(int32_t child_index) +{ + PX_ASSERT(mParameterDefinition != NULL); + PX_ASSERT(child_index >= 0); + + switch(parameterDefinition()->type()) + { + case TYPE_STRUCT: + if(child_index < 0 || child_index >= parameterDefinition()->numChildren()) + return(ERROR_INDEX_OUT_OF_RANGE); + mParameterDefinition = mParameterDefinition->child(child_index); + pushIndex(child_index); + + break; + + + case TYPE_ARRAY: + if(child_index < 0) + return(ERROR_INDEX_OUT_OF_RANGE); + + // parameterDefinition()->arraySize() does not work on dynamic arrays... + if( parameterDefinition()->arraySizeIsFixed() && + child_index >= parameterDefinition()->arraySize()) + return(ERROR_INDEX_OUT_OF_RANGE); + + mParameterDefinition = mParameterDefinition->child(0); + pushIndex(child_index); + break; + + NV_PARAMETRIZED_NO_AGGREGATE_DATATYPE_LABELS + default: + { + return(ERROR_IS_LEAF_NODE); + } + } + + mIsValid = true; + return(ERROR_NONE); +} + +PX_INLINE ErrorType Handle::getChildHandle(int32_t index, Handle &handle) +{ + if(parameterDefinition()->type() != TYPE_ARRAY && parameterDefinition()->type() != TYPE_STRUCT) + return(ERROR_IS_LEAF_NODE); + + if(!isValid()) + return(ERROR_INVALID_PARAMETER_HANDLE); + + handle = *this; + handle.pushIndex(index); + if(parameterDefinition()->type() == TYPE_STRUCT) + { + PX_ASSERT(parameterDefinition()->child(index) != NULL); + handle.mParameterDefinition = parameterDefinition()->child(index); + } + else + { + PX_ASSERT(parameterDefinition()->child(0) != NULL); + handle.mParameterDefinition = parameterDefinition()->child(0); + } + + return(ERROR_NONE); +} + +PX_INLINE bool Handle::getLongName(char *str, uint32_t max_str_len) const +{ + PX_ASSERT(parameterDefinition() != NULL); + + if(!isValid()) + return(false); + + if(numIndexes() < 1) + return(false); + + const Definition *root = parameterDefinition()->root(); + + *str = 0; + const Definition *node = root->child(index(0)); + char tmpStr[32]; + for(int32_t i=1; i <= numIndexes(); ++i) + { + PX_ASSERT(node != NULL); + PX_ASSERT(node->parent() != NULL); + + switch(node->parent()->type()) + { + case TYPE_STRUCT: + { + if(node->parent()->parent() != NULL) + { + local_strcat_s(str, max_str_len, "."); + } + local_strcat_s(str, max_str_len, node->name()); + break; + } + + case TYPE_ARRAY: + { + local_strcat_s(str, max_str_len, "["); + + local_sprintf_s(tmpStr, sizeof(tmpStr), "%d", index(i-1)); + + local_strcat_s(str, max_str_len, tmpStr); + local_strcat_s(str, max_str_len, "]"); + break; + } + + NV_PARAMETRIZED_NO_AGGREGATE_DATATYPE_LABELS + default: + { + local_strcat_s(str, max_str_len, node->name()); + } + } + + switch(node->type()) + { + case TYPE_STRUCT: + node = node->child(index(i)); + break; + + case TYPE_ARRAY: + node = node->child(0); + break; + + NV_PARAMETRIZED_NO_AGGREGATE_DATATYPE_LABELS + default: + node = NULL; + } + } + + return(true); +} + +PX_INLINE void Handle::reset(void) +{ + mNumIndexes = 0; + mParameterDefinition = NULL; + mUserData = NULL; + mIsValid = false; +} + +PX_INLINE void Handle::pushIndex(int32_t index) +{ + PX_ASSERT(mNumIndexes < MAX_DEPTH); + PX_ASSERT(index >= 0); + + if(mNumIndexes < MAX_DEPTH) + mIndexList[mNumIndexes++] = index; +} + +PX_INLINE int32_t Handle::popIndex(int32_t levels) +{ + PX_ASSERT(levels > 0); + PX_ASSERT(mNumIndexes >= levels); + PX_ASSERT(mParameterDefinition != NULL); + + if(mNumIndexes >= levels ) + { + mNumIndexes -= levels; + + for(; levels > 0; --levels) + mParameterDefinition = mParameterDefinition->parent(); + + return(mIndexList[mNumIndexes]); + } + + return(-1); +} + +PX_INLINE ErrorType Handle::initParamRef(const char *chosenRefStr, bool doDestroyOld) +{ + PX_ASSERT(mInterface); + return mInterface->initParamRef(*this, chosenRefStr, doDestroyOld); +} + +// These functions wrap the raw(Get|Set)XXXXX() methods. They deal with +// error handling and casting. + +#define CHECK_CONST_HANDLE if( mIsConst ) return ERROR_MODIFY_CONST_HANDLE; + +PX_INLINE ErrorType Handle::getParamBool(bool &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamBool(*this,val); +} + +PX_INLINE ErrorType Handle::setParamBool(bool val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamBool(*this,val); +} + +PX_INLINE ErrorType Handle::getParamBoolArray(bool *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamBoolArray(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamBoolArray(const bool *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamBoolArray(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::getParamString(const char *&val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamString(*this,val); +} + +PX_INLINE ErrorType Handle::setParamString(const char *val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamString(*this,val); +} + +PX_INLINE ErrorType Handle::getParamStringArray(char **array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamStringArray(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamStringArray(const char **array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamStringArray(*this,array,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamEnum(const char *&val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamEnum(*this,val); +} + +PX_INLINE ErrorType Handle::setParamEnum(const char *val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamEnum(*this,val); +} + +PX_INLINE ErrorType Handle::getParamEnumArray(char **array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamEnumArray(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamEnumArray(const char **array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamEnumArray(*this,array,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamRef(::NvParameterized::Interface *&val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamRef(*this,val); +} + +PX_INLINE ErrorType Handle::setParamRef(::NvParameterized::Interface *val, bool doDestroyOld) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamRef(*this, val, doDestroyOld); +} + +PX_INLINE ErrorType Handle::getParamRefArray(::NvParameterized::Interface **array, int32_t n, int32_t offset) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamRefArray(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamRefArray(::NvParameterized::Interface **array, int32_t n, int32_t offset, bool doDestroyOld) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamRefArray(*this,array,n,offset,doDestroyOld); +} + +PX_INLINE ErrorType Handle::getParamI8(int8_t &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamI8(*this,val); +} + +PX_INLINE ErrorType Handle::setParamI8(int8_t val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamI8(*this,val); +} + +PX_INLINE ErrorType Handle::getParamI8Array(int8_t *_array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamI8Array(*this,_array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamI8Array(const int8_t *val, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamI8Array(*this,val,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamI16(int16_t &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamI16(*this,val); +} + +PX_INLINE ErrorType Handle::setParamI16(int16_t val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamI16(*this,val); +} + +PX_INLINE ErrorType Handle::getParamI16Array(int16_t *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamI16Array(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamI16Array(const int16_t *val, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamI16Array(*this,val,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamI32(int32_t &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamI32(*this,val); +} + +PX_INLINE ErrorType Handle::setParamI32(int32_t val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamI32(*this,val); +} + +PX_INLINE ErrorType Handle::getParamI32Array(int32_t *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamI32Array(*this,array,n,offset ) ; +} + +PX_INLINE ErrorType Handle::setParamI32Array(const int32_t *val, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamI32Array(*this,val,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamI64(int64_t &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamI64(*this,val) ; +} + +PX_INLINE ErrorType Handle::setParamI64(int64_t val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamI64(*this,val); +} + +PX_INLINE ErrorType Handle::getParamI64Array(int64_t *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamI64Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamI64Array(const int64_t *val, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamI64Array(*this,val,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamU8(uint8_t &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamU8(*this,val); +} + +PX_INLINE ErrorType Handle::setParamU8(uint8_t val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamU8(*this,val); +} + +PX_INLINE ErrorType Handle::getParamU8Array(uint8_t *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamU8Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamU8Array(const uint8_t *val, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamU8Array(*this,val,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamU16(uint16_t &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamU16(*this,val); +} + +PX_INLINE ErrorType Handle::setParamU16(uint16_t val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamU16(*this,val); +} + +PX_INLINE ErrorType Handle::getParamU16Array(uint16_t *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamU16Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamU16Array(const uint16_t *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamU16Array(*this,array,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamU32(uint32_t &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamU32(*this,val); +} + +PX_INLINE ErrorType Handle::setParamU32(uint32_t val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamU32(*this,val); +} + +PX_INLINE ErrorType Handle::getParamU32Array(uint32_t *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamU32Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamU32Array(const uint32_t *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamU32Array(*this,array,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamU64(uint64_t &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamU64(*this,val); +} + +PX_INLINE ErrorType Handle::setParamU64(uint64_t val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamU64(*this,val); +} + +PX_INLINE ErrorType Handle::getParamU64Array(uint64_t *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamU64Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamU64Array(const uint64_t *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamU64Array(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::getParamF32(float &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamF32(*this,val); +} + +PX_INLINE ErrorType Handle::setParamF32(float val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamF32(*this,val); +} + +PX_INLINE ErrorType Handle::getParamF32Array(float *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamF32Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamF32Array(const float *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamF32Array(*this,array,n,offset); +} + + +PX_INLINE ErrorType Handle::getParamF64(double &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamF64(*this,val); +} + +PX_INLINE ErrorType Handle::setParamF64(double val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamF64(*this,val); +} + +PX_INLINE ErrorType Handle::getParamF64Array(double *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamF64Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamF64Array(const double *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamF64Array(*this,array,n,offset); +} + + +PX_INLINE ErrorType Handle::setParamVec2(const physx::PxVec2 &val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamVec2(*this,val); +} + +PX_INLINE ErrorType Handle::getParamVec2(physx::PxVec2 &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamVec2(*this,val); +} + +PX_INLINE ErrorType Handle::getParamVec2Array(physx::PxVec2 *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamVec2Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamVec2Array(const physx::PxVec2 *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamVec2Array(*this,array,n,offset); +} + + +PX_INLINE ErrorType Handle::setParamVec3(const physx::PxVec3 &val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamVec3(*this,val); +} + +PX_INLINE ErrorType Handle::getParamVec3(physx::PxVec3 &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamVec3(*this,val); +} + +PX_INLINE ErrorType Handle::getParamVec3Array(physx::PxVec3 *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamVec3Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamVec3Array(const physx::PxVec3 *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamVec3Array(*this,array,n,offset); +} + + +PX_INLINE ErrorType Handle::setParamVec4(const physx::PxVec4 &val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamVec4(*this,val); +} + +PX_INLINE ErrorType Handle::getParamVec4(physx::PxVec4 &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamVec4(*this,val); +} + +PX_INLINE ErrorType Handle::getParamVec4Array(physx::PxVec4 *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamVec4Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamVec4Array(const physx::PxVec4 *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamVec4Array(*this,array,n,offset); +} + + +PX_INLINE ErrorType Handle::setParamQuat(const physx::PxQuat &val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamQuat(*this,val); +} + +PX_INLINE ErrorType Handle::getParamQuat(physx::PxQuat &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamQuat(*this,val); +} + +PX_INLINE ErrorType Handle::getParamQuatArray(physx::PxQuat *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamQuatArray(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamQuatArray(const physx::PxQuat *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamQuatArray(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamMat33(const physx::PxMat33 &val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamMat33(*this,val); +} + +PX_INLINE ErrorType Handle::getParamMat33(physx::PxMat33 &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamMat33(*this,val); +} + +PX_INLINE ErrorType Handle::getParamMat33Array(physx::PxMat33 *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamMat33Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamMat33Array(const physx::PxMat33 *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamMat33Array(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamMat44(const physx::PxMat44 &val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamMat44(*this,val); +} + +PX_INLINE ErrorType Handle::getParamMat44(physx::PxMat44 &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamMat44(*this,val); +} + +PX_INLINE ErrorType Handle::getParamMat44Array(physx::PxMat44 *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamMat44Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamMat44Array(const physx::PxMat44 *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamMat44Array(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamMat34Legacy(const float (&val)[12]) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamMat34Legacy(*this,val); +} + +PX_INLINE ErrorType Handle::getParamMat34Legacy(float (&val)[12]) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamMat34Legacy(*this,val); +} + +PX_INLINE ErrorType Handle::getParamMat34LegacyArray(float *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamMat34LegacyArray(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamMat34LegacyArray(const float *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamMat34LegacyArray(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamBounds3(const physx::PxBounds3 &val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamBounds3(*this,val); +} + +PX_INLINE ErrorType Handle::getParamBounds3(physx::PxBounds3 &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamBounds3(*this,val); +} + +PX_INLINE ErrorType Handle::getParamBounds3Array(physx::PxBounds3 *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamBounds3Array(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamBounds3Array(const physx::PxBounds3 *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamBounds3Array(*this,array,n,offset); +} + +PX_INLINE ErrorType Handle::setParamTransform(const physx::PxTransform &val) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamTransform(*this,val); +} + +PX_INLINE ErrorType Handle::getParamTransform(physx::PxTransform &val) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamTransform(*this,val); +} + +PX_INLINE ErrorType Handle::getParamTransformArray(physx::PxTransform *array, int32_t n, int32_t offset ) const +{ + PX_ASSERT(mInterface); + return mInterface->getParamTransformArray(*this,array,n,offset ); +} + +PX_INLINE ErrorType Handle::setParamTransformArray(const physx::PxTransform *array, int32_t n, int32_t offset) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->setParamTransformArray(*this,array,n,offset); +} + + + +#define NV_PARAMETERIZED_TYPES_NO_LEGACY_TYPES +#define NV_PARAMETERIZED_TYPES_ONLY_SIMPLE_TYPES +#define NV_PARAMETERIZED_TYPES_NO_STRING_TYPES +#define NV_PARAMETERIZED_TYPE(type_name, enum_name, c_type) \ + template <> PX_INLINE ::NvParameterized::ErrorType Handle::setParam<c_type>(const c_type &val) { return setParam##type_name(val); } \ + template <> PX_INLINE ::NvParameterized::ErrorType Handle::getParam<c_type>(c_type &val) const {return getParam##type_name(val); } \ + template <> PX_INLINE ::NvParameterized::ErrorType Handle::getParamArray<c_type>(c_type *array, int32_t n, int32_t offset) const { return getParam##type_name##Array(array, n, offset); } \ + template <> PX_INLINE ::NvParameterized::ErrorType Handle::setParamArray<c_type>(const c_type *array, int32_t n, int32_t offset) { return setParam##type_name##Array(array, n, offset); } +#include "NvParameterized_types.h" + +PX_INLINE ErrorType Handle::valueToStr(char *buf, uint32_t bufSize, const char *&ret) +{ + PX_ASSERT(mInterface); + return mInterface->valueToStr(*this, buf, bufSize, ret); +} + +PX_INLINE ErrorType Handle::strToValue(const char *str, const char **endptr) // assigns this string to the valu +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->strToValue(*this,str, endptr); // assigns this string to the value +} + + +PX_INLINE ErrorType Handle::resizeArray(int32_t new_size) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->resizeArray(*this,new_size); +} + +PX_INLINE ErrorType Handle::getArraySize(int32_t &size, int32_t dimension ) const +{ + PX_ASSERT(mInterface); + return mInterface->getArraySize(*this,size,dimension ); +} + +PX_INLINE ErrorType Handle::swapArrayElements(uint32_t firstElement, uint32_t secondElement) +{ + PX_ASSERT(mInterface); + CHECK_CONST_HANDLE + return mInterface->swapArrayElements(*this, firstElement, secondElement); +} + +#undef IS_ALPHA +#undef IS_DIGIT +#undef IS_ALPHANUM +#undef IS_IDENTCHAR +#undef CHECK_CONST_HANDLE + +#if PX_VC && !PX_PS4 + #pragma warning(pop) +#endif //!PX_PS4 + +} // end of namespace diff --git a/APEX_1.4/include/nvparameterized/NvParameterizedMacroses.h b/APEX_1.4/include/nvparameterized/NvParameterizedMacroses.h new file mode 100644 index 00000000..c5f46632 --- /dev/null +++ b/APEX_1.4/include/nvparameterized/NvParameterizedMacroses.h @@ -0,0 +1,136 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2015 NVIDIA Corporation. All rights reserved. + +#ifndef NV_PARAMETERIZED_MACROSES_H +#define NV_PARAMETERIZED_MACROSES_H + +/** Case labels for different NvParameterized::DataType's +*/ +#define NV_PARAMETRIZED_AGGREGATE_DATATYPE_LABELS \ +case NvParameterized::TYPE_ARRAY:\ +case NvParameterized::TYPE_STRUCT:\ + +#define NV_PARAMETRIZED_LINAL_DATATYPE_LABELS \ +case NvParameterized::TYPE_VEC2:\ +case NvParameterized::TYPE_VEC3:\ +case NvParameterized::TYPE_VEC4:\ +case NvParameterized::TYPE_QUAT:\ +case NvParameterized::TYPE_MAT33:\ +case NvParameterized::TYPE_BOUNDS3:\ +case NvParameterized::TYPE_MAT44:\ +case NvParameterized::TYPE_TRANSFORM:\ +case NvParameterized::TYPE_MAT34: + +#define NV_PARAMETRIZED_ARITHMETIC_DATATYPE_LABELS \ +case NvParameterized::TYPE_I8:\ +case NvParameterized::TYPE_I16:\ +case NvParameterized::TYPE_I32:\ +case NvParameterized::TYPE_I64:\ +case NvParameterized::TYPE_U8:\ +case NvParameterized::TYPE_U16:\ +case NvParameterized::TYPE_U32:\ +case NvParameterized::TYPE_U64:\ +case NvParameterized::TYPE_F32:\ +case NvParameterized::TYPE_F64:\ +case NvParameterized::TYPE_BOOL: + +#define NV_PARAMETRIZED_STRING_DATATYPE_LABELS \ +case NvParameterized::TYPE_STRING: + +#define NV_PARAMETRIZED_REF_DATATYPE_LABELS \ +case NvParameterized::TYPE_REF: + +#define NV_PARAMETRIZED_ENUM_DATATYPE_LABELS \ +case NvParameterized::TYPE_ENUM: + +#define NV_PARAMETRIZED_SERVICE_DATATYPE_LABELS \ +case NvParameterized::TYPE_POINTER: + +#define NV_PARAMETRIZED_UNDEFINED_AND_LAST_DATATYPE_LABELS \ +case NvParameterized::TYPE_UNDEFINED:\ +case NvParameterized::TYPE_LAST: + +/** Case labels for composite conditions of switch conditions*/ +/***********************************************************************/ +#define NV_PARAMETRIZED_NO_AGGREGATE_DATATYPE_LABELS \ +/* NV_PARAMETRIZED_AGGREGATE_DATATYPE_LABELS*/ \ +NV_PARAMETRIZED_LINAL_DATATYPE_LABELS \ +NV_PARAMETRIZED_ARITHMETIC_DATATYPE_LABELS \ +NV_PARAMETRIZED_STRING_DATATYPE_LABELS \ +NV_PARAMETRIZED_REF_DATATYPE_LABELS \ +NV_PARAMETRIZED_ENUM_DATATYPE_LABELS \ +NV_PARAMETRIZED_SERVICE_DATATYPE_LABELS \ +NV_PARAMETRIZED_UNDEFINED_AND_LAST_DATATYPE_LABELS + +#define NV_PARAMETRIZED_NO_AGGREGATE_AND_ARITHMETIC_DATATYPE_LABELS \ +/* NV_PARAMETRIZED_AGGREGATE_DATATYPE_LABELS*/ \ +NV_PARAMETRIZED_LINAL_DATATYPE_LABELS \ +/*NV_PARAMETRIZED_ARITHMETIC_DATATYPE_LABELS*/ \ +NV_PARAMETRIZED_STRING_DATATYPE_LABELS \ +NV_PARAMETRIZED_REF_DATATYPE_LABELS \ +NV_PARAMETRIZED_ENUM_DATATYPE_LABELS \ +NV_PARAMETRIZED_SERVICE_DATATYPE_LABELS \ +NV_PARAMETRIZED_UNDEFINED_AND_LAST_DATATYPE_LABELS + +#define NV_PARAMETRIZED_NO_AGGREGATE_AND_REF_DATATYPE_LABELS \ +/* NV_PARAMETRIZED_AGGREGATE_DATATYPE_LABELS*/ \ +NV_PARAMETRIZED_LINAL_DATATYPE_LABELS \ +NV_PARAMETRIZED_ARITHMETIC_DATATYPE_LABELS \ +NV_PARAMETRIZED_STRING_DATATYPE_LABELS \ +/*NV_PARAMETRIZED_REF_DATATYPE_LABELS*/ \ +NV_PARAMETRIZED_ENUM_DATATYPE_LABELS \ +NV_PARAMETRIZED_SERVICE_DATATYPE_LABELS \ +NV_PARAMETRIZED_UNDEFINED_AND_LAST_DATATYPE_LABELS + +#define NV_PARAMETRIZED_NO_ARITHMETIC_AND_LINAL_DATATYPE_LABELS \ +NV_PARAMETRIZED_AGGREGATE_DATATYPE_LABELS \ +/*NV_PARAMETRIZED_LINAL_DATATYPE_LABELS*/ \ +/*NV_PARAMETRIZED_ARITHMETIC_DATATYPE_LABELS*/ \ +NV_PARAMETRIZED_STRING_DATATYPE_LABELS \ +NV_PARAMETRIZED_REF_DATATYPE_LABELS \ +NV_PARAMETRIZED_ENUM_DATATYPE_LABELS \ +NV_PARAMETRIZED_SERVICE_DATATYPE_LABELS \ +NV_PARAMETRIZED_UNDEFINED_AND_LAST_DATATYPE_LABELS + +#define NV_PARAMETRIZED_SERVICE_AND_LAST_DATATYPE_LABELS \ +NV_PARAMETRIZED_SERVICE_DATATYPE_LABELS \ +case NvParameterized::TYPE_LAST: + +#define NV_PARAMETRIZED_LEGACY_DATATYPE_LABELS \ +case NvParameterized::TYPE_MAT34: + +#define NV_PARAMETRIZED_NO_MATH_DATATYPE_LABELS \ +NV_PARAMETRIZED_AGGREGATE_DATATYPE_LABELS \ +NV_PARAMETRIZED_STRING_DATATYPE_LABELS \ +NV_PARAMETRIZED_REF_DATATYPE_LABELS \ +NV_PARAMETRIZED_ENUM_DATATYPE_LABELS \ +NV_PARAMETRIZED_SERVICE_DATATYPE_LABELS \ +NV_PARAMETRIZED_UNDEFINED_AND_LAST_DATATYPE_LABELS + +/***********************************************************************/ + +#endif // NV_PARAMETERIZED_MACROSES_H diff --git a/APEX_1.4/include/nvparameterized/NvParameterizedTraits.h b/APEX_1.4/include/nvparameterized/NvParameterizedTraits.h new file mode 100644 index 00000000..68c51d7a --- /dev/null +++ b/APEX_1.4/include/nvparameterized/NvParameterizedTraits.h @@ -0,0 +1,373 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. + +#ifndef NV_PARAMETERIZED_TRAITS_H +#define NV_PARAMETERIZED_TRAITS_H + +/*! +\file +\brief NvParameterized traits class +*/ + +#include <string.h> +#include "foundation/PxAssert.h" + +namespace NvParameterized +{ + +PX_PUSH_PACK_DEFAULT + +class Traits; +class Interface; + +/** +\brief Interface class for NvParameterized factories +*/ +class Factory +{ +public: + + /** + \brief Creates NvParameterized object of class + */ + virtual ::NvParameterized::Interface *create( Traits *paramTraits ) = 0; + + /** + \brief Finishes initialization of inplace-deserialized objects (vptr and stuff) + */ + virtual ::NvParameterized::Interface *finish( Traits *paramTraits, void *obj, void *buf, int32_t *refCount ) = 0; + + /** + \brief Returns name of class whose objects are created by factory + */ + virtual const char * getClassName() = 0; + + /** + \brief Returns version of class whose objects are created by factory + */ + virtual uint32_t getVersion() = 0; + + /** + \brief Returns memory alignment required for objects of class + */ + virtual uint32_t getAlignment() = 0; + + /** + \brief Returns checksum of class whose objects are created by factory + */ + virtual const uint32_t * getChecksum( uint32_t &bits ) = 0; + + /** + \brief Destructor + */ + virtual ~Factory() {} + + /** + \brief Clean reflection definition table. Call it if you don't have any instances of classes. + */ + virtual void freeParameterDefinitionTable(NvParameterized::Traits* traits) = 0; +}; + +/** +\brief Interface class for legacy object conversions +*/ +class Conversion +{ +public: + virtual ~Conversion() {} + + /** + \brief Initialize object using data from legacy object + \param [in] legacyObj legacy object to be converter + \param [in] obj destination object + \return true if conversion succeeded, false otherwise + \warning You may assume that all nested references were already converted. + */ + virtual bool operator()(::NvParameterized::Interface &legacyObj, ::NvParameterized::Interface &obj) = 0; + + /** + \brief Release converter and any memory allocations associated with it + */ + virtual void release() = 0; +}; + +/** +\brief Interface class for user traits + +This class is a collection of loosely-related functions provided by application or framework +and used by NvParameterized library to do memory allocation, object creation, user notification, etc. +*/ +class Traits +{ +public: + virtual ~Traits() {} + + /** + \brief Register NvParameterized class factory + */ + virtual void registerFactory( ::NvParameterized::Factory & factory ) = 0; + + /** + \brief Remove NvParameterized class factory for current version of class + \return Removed factory or NULL if it is not found + */ + virtual ::NvParameterized::Factory *removeFactory( const char * className ) = 0; + + /** + \brief Remove NvParameterized class factory for given version of class + \return Removed factory or NULL if it is not found + */ + virtual ::NvParameterized::Factory *removeFactory( const char * className, uint32_t version ) = 0; + + /** + \brief Checks whether any class factory is registered + */ + virtual bool doesFactoryExist(const char* className) = 0; + + /** + \brief Checks whether class factory for given version is registered + */ + virtual bool doesFactoryExist(const char* className, uint32_t version) = 0; + + /** + \brief Create object of NvParameterized class using its staticClassName() + + \param [in] name static class name of the instance to create + + Most probably this just calls Factory::create on appropriate factory. + */ + virtual ::NvParameterized::Interface * createNvParameterized( const char * name ) = 0; + + /** + \brief Create object of NvParameterized class using its staticClassName() + + \param [in] name static class name of the instance to create + \param [in] ver version of the class + + Most probably this just calls Factory::create on appropriate factory. + */ + virtual ::NvParameterized::Interface * createNvParameterized( const char * name, uint32_t ver ) = 0; + + /** + \brief Finish construction of inplace object of NvParameterized class + + Most probably this just calls Factory::finish using appropriate factory. + */ + virtual ::NvParameterized::Interface * finishNvParameterized( const char * name, void *obj, void *buf, int32_t *refCount ) = 0; + + /** + \brief Finish construction of inplace object of NvParameterized class + + Most probably this just calls Factory::finish using appropriate factory. + */ + virtual ::NvParameterized::Interface * finishNvParameterized( const char * name, uint32_t ver, void *obj, void *buf, int32_t *refCount ) = 0; + + /** + \brief Get version of class which is currently used + */ + virtual uint32_t getCurrentVersion(const char *className) const = 0; + + /** + \brief Get memory alignment required for objects of class + */ + virtual uint32_t getAlignment(const char *className, uint32_t classVersion) const = 0; + + /** + \brief Register converter for legacy version of class + */ + virtual void registerConversion(const char * /*className*/, uint32_t /*from*/, uint32_t /*to*/, Conversion & /*conv*/) {} + + /** + \brief Remove converter for legacy version of class + */ + virtual ::NvParameterized::Conversion *removeConversion(const char * /*className*/, uint32_t /*from*/, uint32_t /*to*/) { return 0; } + + /** + \brief Update legacy object (most probably using appropriate registered converter) + \param [in] legacyObj legacy object to be converted + \param [in] obj destination object + \return True if conversion was successful, false otherwise + \warning Note that update is intrusive - legacyObj may be modified as a result of update + */ + virtual bool updateLegacyNvParameterized(::NvParameterized::Interface &legacyObj, ::NvParameterized::Interface &obj) + { + PX_UNUSED(&legacyObj); + PX_UNUSED(&obj); + + return false; + } + + /** + \brief Get a list of the NvParameterized class type names + + \param [in] names buffer for names + \param [out] outCount minimal required length of buffer + \param [in] inCount length of buffer + \return False if 'inCount' is not large enough to contain all of the names, true otherwise + + \warning The memory for the strings returned is owned by the traits class + and should only be read, not written or freed. + */ + virtual bool getNvParameterizedNames( const char ** names, uint32_t &outCount, uint32_t inCount) const = 0; + + /** + \brief Get a list of versions of particular NvParameterized class + + \param [in] className Name of the class + \param [in] versions buffer for versions + \param [out] outCount minimal required length of buffer + \param [in] inCount length of buffer + \return False if 'inCount' is not large enough to contain all of version names, true otherwise + + \warning The memory for the strings returned is owned by the traits class + and should only be read, not written or freed. + */ + virtual bool getNvParameterizedVersions(const char* className, uint32_t* versions, uint32_t &outCount, uint32_t inCount) const = 0; + + /** + \brief Increment reference counter + */ + virtual int32_t incRefCount(int32_t *refCount) = 0; + + /** + \brief Decrement reference counter + */ + virtual int32_t decRefCount(int32_t *refCount) = 0; + + /** + \brief Called when inplace object is destroyed + */ + virtual void onInplaceObjectDestroyed(void * /*buf*/, ::NvParameterized::Interface * /*obj*/) {} + + /** + \brief Called when all inplace objects are destroyed + */ + virtual void onAllInplaceObjectsDestroyed(void *buf) { free(buf); } + + /** + \brief Allocate memory with default alignment of 8 + */ + virtual void *alloc(uint32_t nbytes) = 0; + + /** + \brief Allocate aligned memory + */ + virtual void *alloc(uint32_t nbytes, uint32_t align) = 0; + + /** + \brief Deallocate memory + */ + virtual void free(void *buf) = 0; + + /** + \brief Copy string + */ + virtual char *strdup(const char *str) + { + if( !str ) + return NULL; + + uint32_t strLen = (uint32_t)strlen(str) + 1; + char *retStr = (char *)this->alloc(strLen, 1); + + PX_ASSERT( retStr ); + + if( NULL != retStr ) +#if PX_WINDOWS_FAMILY + strcpy_s( retStr, strLen, str ); +#else + strncpy(retStr, str, strLen); +#endif + return retStr; + } + + /** + \brief Release copied string + */ + virtual void strfree(char *str) + { + if( NULL != str ) + this->free( str ); + } + + /** + \brief Warns user + */ + virtual void traitsWarn(const char * /*msg*/) const {} + + /** + \brief Release Traits + */ + virtual void release(void) = 0; + + /** + \brief Adapter for allocator classes in PxAlloctor.h + */ + class Allocator + { + ::NvParameterized::Traits *mTraits; + + public: + + /** + \brief Constructor + */ + Allocator(Traits *traits): mTraits(traits) {} + + /** + \brief Allocate memory + */ + void *allocate(size_t size) + { + return allocate(size, __FILE__, __LINE__); + } + + /** + \brief Allocate memory + */ + void *allocate(size_t size, const char * /*filename*/, int /*line*/) + { + PX_ASSERT( static_cast<uint32_t>(size) == size ); + return mTraits->alloc(static_cast<uint32_t>(size)); + } + + /** + \brief Release memory + */ + void deallocate(void *ptr) + { + return mTraits->free(ptr); + } + }; +}; + + +PX_POP_PACK + +} // namespace NvParameterized + +#endif // NV_PARAMETERIZED_TRAITS_H diff --git a/APEX_1.4/include/nvparameterized/NvParameterized_types.h b/APEX_1.4/include/nvparameterized/NvParameterized_types.h new file mode 100644 index 00000000..289595a4 --- /dev/null +++ b/APEX_1.4/include/nvparameterized/NvParameterized_types.h @@ -0,0 +1,107 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. + +/*! +\brief NvParameterized type X-macro template +\note See http://en.wikipedia.org/wiki/C_preprocessor#X-Macros for more details +*/ + + +// NV_PARAMETERIZED_TYPE(type_name, enum_name, c_type) + +#if PX_VC && !PX_PS4 + #pragma warning(push) + #pragma warning(disable:4555) +#endif //!PX_PS4 + +PX_PUSH_PACK_DEFAULT + +#ifndef NV_PARAMETERIZED_TYPES_ONLY_SIMPLE_TYPES +#ifndef NV_PARAMETERIZED_TYPES_ONLY_SCALAR_TYPES +NV_PARAMETERIZED_TYPE(Array, ARRAY, void *) +NV_PARAMETERIZED_TYPE(Struct, STRUCT, void *) +NV_PARAMETERIZED_TYPE(Ref, REF, NvParameterized::Interface *) +#endif +#endif + +#ifndef NV_PARAMETERIZED_TYPES_NO_STRING_TYPES +#ifndef NV_PARAMETERIZED_TYPES_ONLY_SCALAR_TYPES +NV_PARAMETERIZED_TYPE(String, STRING, const char *) +NV_PARAMETERIZED_TYPE(Enum, ENUM, const char *) +#endif +#endif + +NV_PARAMETERIZED_TYPE(Bool, BOOL, bool) + +NV_PARAMETERIZED_TYPE(I8, I8, int8_t) +NV_PARAMETERIZED_TYPE(I16, I16, int16_t) +NV_PARAMETERIZED_TYPE(I32, I32, int32_t) +NV_PARAMETERIZED_TYPE(I64, I64, int64_t) + +NV_PARAMETERIZED_TYPE(U8, U8, uint8_t) +NV_PARAMETERIZED_TYPE(U16, U16, uint16_t) +NV_PARAMETERIZED_TYPE(U32, U32, uint32_t) +NV_PARAMETERIZED_TYPE(U64, U64, uint64_t) + +NV_PARAMETERIZED_TYPE(F32, F32, float) +NV_PARAMETERIZED_TYPE(F64, F64, double) + +#ifndef NV_PARAMETERIZED_TYPES_ONLY_SCALAR_TYPES +NV_PARAMETERIZED_TYPE(Vec2, VEC2, physx::PxVec2) +NV_PARAMETERIZED_TYPE(Vec3, VEC3, physx::PxVec3) +NV_PARAMETERIZED_TYPE(Vec4, VEC4, physx::PxVec4) +NV_PARAMETERIZED_TYPE(Quat, QUAT, physx::PxQuat) +NV_PARAMETERIZED_TYPE(Bounds3, BOUNDS3, physx::PxBounds3) +NV_PARAMETERIZED_TYPE(Mat33, MAT33, physx::PxMat33) +NV_PARAMETERIZED_TYPE(Mat44, MAT44, physx::PxMat44) +NV_PARAMETERIZED_TYPE(Transform, TRANSFORM, physx::PxTransform) +#endif + + +#ifdef NV_PARAMETERIZED_TYPES_ONLY_SIMPLE_TYPES +# undef NV_PARAMETERIZED_TYPES_ONLY_SIMPLE_TYPES +#endif + +#ifdef NV_PARAMETERIZED_TYPES_NO_STRING_TYPES +# undef NV_PARAMETERIZED_TYPES_NO_STRING_TYPES +#endif + +#ifdef NV_PARAMETERIZED_TYPES_ONLY_SCALAR_TYPES +# undef NV_PARAMETERIZED_TYPES_ONLY_SCALAR_TYPES +#endif + +#ifdef NV_PARAMETERIZED_TYPES_NO_LEGACY_TYPES +# undef NV_PARAMETERIZED_TYPES_NO_LEGACY_TYPES +#endif + +#if PX_VC && !PX_PS4 + #pragma warning(pop) +#endif //!PX_PS4 + +PX_POP_PACK + +#undef NV_PARAMETERIZED_TYPE diff --git a/APEX_1.4/include/nvparameterized/NvSerializer.h b/APEX_1.4/include/nvparameterized/NvSerializer.h new file mode 100644 index 00000000..7c182eaf --- /dev/null +++ b/APEX_1.4/include/nvparameterized/NvSerializer.h @@ -0,0 +1,461 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. + +#ifndef NV_SERIALIZER_H +#define NV_SERIALIZER_H + +/*! +\file +\brief NvParameterized serializer class +*/ + + +#include <filebuf/PxFileBuf.h> + + +namespace NvParameterized +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief Platform descriptor + +This class describes target serialization platform which consists of processor architecture, compiler and OS. +*/ +struct SerializePlatform +{ + /** + \brief Processor architectures enumeration + \warning Do not change values of enums! + */ + typedef enum + { + ARCH_GEN = 0, + ARCH_X86 = 1, + ARCH_X86_64 = 2, + ARCH_PPC = 3, + ARCH_CELL = 4, + ARCH_ARM = 5, + ARCH_LAST + } ArchType; + + /** + \brief Platform processor architecture + */ + ArchType archType; + + /** + \brief Compilers enumeration + \warning Do not change values of enums! + */ + typedef enum + { + COMP_GEN = 0, + COMP_GCC = 1, + COMP_VC = 2, + COMP_MW = 3, + COMP_LAST + } CompilerType; + + /** + \brief Platform compiler + */ + CompilerType compilerType; + + /** + \brief Platform compiler version + */ + uint32_t compilerVer; + + /** + \brief OSes enumeration + \warning Do not change values of enums! + */ + typedef enum + { + OS_WINDOWS = 0, + OS_LINUX = 1, + OS_LV2 = 2, // PS3 + OS_MACOSX = 3, + OS_XBOX = 4, + OS_GEN = 5, + OS_ANDROID = 6, + OS_XBOXONE = 7, + OS_PS4 = 8, + OS_LAST + } OsType; + + /** + \brief Platform OS + */ + OsType osType; + + /** + \brief Platform OS version + */ + uint32_t osVer; + + /** + \brief This value identfies that version is unknown + */ + static const uint32_t ANY_VERSION = (uint32_t)-1; + + PX_INLINE SerializePlatform(); + + /** + \brief Constructor of SerializePlatform + */ + PX_INLINE SerializePlatform(ArchType archType, CompilerType compType, uint32_t compVer, OsType osType, uint32_t osVer); + + /** + \brief Checks if platforms are binary-compatible + */ + PX_INLINE bool operator ==(const SerializePlatform &p) const; + + /** + \brief Checks if platforms are binary-incompatible + */ + PX_INLINE bool operator !=(const SerializePlatform &p) const; +}; + +class Interface; +class Definition; +class Traits; +struct SerializePlatform; + +/** +\brief Interface class for serializer-deserializer of NvParameterized objects + +Serializer serializes and deserializes one or more NvParameterized objects to file using various output formats +(see SerializeType). +*/ +class Serializer +{ +public: + + /** + \brief Status enums that the Serializer methods may return + */ + enum ErrorType + { + ERROR_NONE = 0, + + ERROR_UNKNOWN, + ERROR_NOT_IMPLEMENTED, + + // File format related errors + ERROR_INVALID_PLATFORM, + ERROR_INVALID_PLATFORM_NAME, + ERROR_INVALID_FILE_VERSION, + ERROR_INVALID_FILE_FORMAT, + ERROR_INVALID_MAGIC, + ERROR_INVALID_CHAR, + + // External errors + ERROR_STREAM_ERROR, + ERROR_MEMORY_ALLOCATION_FAILURE, + ERROR_UNALIGNED_MEMORY, + ERROR_PRESERIALIZE_FAILED, + ERROR_INTERNAL_BUFFER_OVERFLOW, + ERROR_OBJECT_CREATION_FAILED, + ERROR_CONVERSION_FAILED, + + // Xml-specific errors + ERROR_VAL2STRING_FAILED, + ERROR_STRING2VAL_FAILED, + ERROR_INVALID_TYPE_ATTRIBUTE, + ERROR_UNKNOWN_XML_TAG, + ERROR_MISSING_DOCTYPE, + ERROR_MISSING_ROOT_ELEMENT, + ERROR_INVALID_NESTING, + ERROR_INVALID_ATTR, + + // Other stuff + ERROR_INVALID_ARRAY, + ERROR_ARRAY_INDEX_OUT_OF_RANGE, + ERROR_INVALID_VALUE, + ERROR_INVALID_INTERNAL_PTR, + ERROR_INVALID_PARAM_HANDLE, + ERROR_INVALID_RELOC_TYPE, + ERROR_INVALID_DATA_TYPE, + ERROR_INVALID_REFERENCE + }; + + /** + \brief The supported serialization formats + */ + enum SerializeType + { + /// serialize in XML format. + NST_XML = 0, + + /// serialize in a binary format + NST_BINARY, + + NST_LAST + }; + + /** + \brief Get type of stream (binary or xml) + \param [in] stream stream to be analyzed + */ + static SerializeType peekSerializeType(physx::general_PxIOStream2::PxFileBuf &stream); + + /** + \brief Get stream native platform + \param [in] stream stream to be analyzed + \param [out] platform stream native platform + */ + static ErrorType peekPlatform(physx::general_PxIOStream2::PxFileBuf &stream, SerializePlatform &platform); + + virtual ~Serializer() {} + + /** + \brief Set platform to use in platform-dependent serialization + \param [in] platform target platform + + \warning Currently this is used only in binary serializer + + Application running on target platforms may potentially make use of extremely fast + inplace deserialization (using method deserializeInplace) on files which were serialized + for this platform. + */ + virtual ErrorType setTargetPlatform(const SerializePlatform &platform) = 0; + + /** + \brief Sets whether serializer will automatically update + objects after deserialization + \param [in] doUpdate should automatic update be done? + + \warning Normally you will not need this + \warning This is true by default + */ + virtual void setAutoUpdate(bool doUpdate) = 0; + + /** + \brief Serialize array of NvParameterized-objects to a stream + \param [in] stream the stream to which the object will be serialized + \param [in] objs NvParameterized-objects which will be serialized + \param [in] nobjs number of objects + \param [in] doSerializeMetadata set this to store object metadata in file + + \warning Serialized file may depend on selected target platform + */ + virtual ErrorType serialize( + physx::general_PxIOStream2::PxFileBuf &stream, + const ::NvParameterized::Interface **objs, + uint32_t nobjs, + bool doSerializeMetadata = false) = 0; + + /** + \brief Peek number of NvParameterized-objects in stream with serialized data + \param [in] stream the stream from which the object will be deserialized + \param [out] numObjects number of objects + + \warning Not all streams support peeking + */ + virtual ErrorType peekNumObjects(physx::general_PxIOStream2::PxFileBuf &stream, uint32_t &numObjects) = 0; + + /** + \brief Peek number of NvParameterized-objects in stream with serialized data + \param [in] stream the stream from which objects will be deserialized + \param [in] classNames pointer to buffer for resulting names + \param [in,out] numClassNames limit on number of returned classNames; number of returned names + + \warning User is responsible for releasing every element of classNames via Traits::strfree() + */ + virtual ErrorType peekClassNames(physx::general_PxIOStream2::PxFileBuf &stream, char **classNames, uint32_t &numClassNames) = 0; + + /** + \brief Peek number of NvParameterized-objects in memory buffer with serialized data + \param [in] data pointer to memory buffer + \param [in] dataLen length of memory buffer + \param [out] numObjects number of objects + */ + virtual ErrorType peekNumObjectsInplace(const void *data, uint32_t dataLen, uint32_t &numObjects) = 0; + + /// TODO + template < typename T, int bufSize = 8 > class DeserializedResults + { + T buf[bufSize]; //For small number of objects + + T *objs; + + uint32_t nobjs; + + Traits *traits; + + void clear(); + + public: + + PX_INLINE DeserializedResults(); + + PX_INLINE ~DeserializedResults(); + + /** + \brief Copy constructor + */ + PX_INLINE DeserializedResults(const DeserializedResults &data); + + /** + \brief Assignment operator + */ + PX_INLINE DeserializedResults &operator =(const DeserializedResults &rhs); + + /** + \brief Allocate memory for values + */ + PX_INLINE void init(Traits *traits_, uint32_t nobjs_); + + /** + \brief Allocate memory and set values + */ + PX_INLINE void init(Traits *traits_, T *objs_, uint32_t nobjs_); + + /** + \brief Number of objects in a container + */ + PX_INLINE uint32_t size() const; + + /** + \brief Access individual object in container + */ + PX_INLINE T &operator[](uint32_t i); + + /** + \brief Const-access individual object in container + */ + PX_INLINE const T &operator[](uint32_t i) const; + + /** + \brief Read all NvParameterized objects in container to buffer outObjs + \warning outObjs must be large enough to hold all contained objects + */ + PX_INLINE void getObjects(T *outObjs); + + /** + \brief Release all objects + */ + PX_INLINE void releaseAll(); + }; + + /** + \brief Container for results of deserialization + + DeserializedData holds array of NvParameterized objects obtained during deserialization. + */ + typedef DeserializedResults< ::NvParameterized::Interface *> DeserializedData; + + /// This class keeps metadata of a single NvParameterized class + struct MetadataEntry + { + /// Class name + const char *className; + + /// Class version + uint32_t version; + + /// Class metadata + Definition *def; + }; + + /** + \brief Container for results of metadata deserialization + + DeserializedMetadata holds array of MetadataEntry obtained during metadata deserialization. + */ + typedef DeserializedResults<MetadataEntry> DeserializedMetadata; + + /** + \brief Deserialize metadata from a stream into one or more definitions + \param [in] stream the stream from which metadata will be deserialized + \param [out] desData storage for deserialized metadata + \warning This is a draft implementation! + */ + virtual ErrorType deserializeMetadata(physx::general_PxIOStream2::PxFileBuf &stream, DeserializedMetadata &desData); + + /** + \brief Deserialize a stream into one or more NvParameterized objects + \param [in] stream the stream from which objects will be deserialized + \param [out] desData storage for deserialized data + */ + virtual ErrorType deserialize(physx::general_PxIOStream2::PxFileBuf &stream, DeserializedData &desData); + + /** + \brief Deserialize a stream into one or more NvParameterized objects + \param [in] stream the stream from which objects will be deserialized + \param [out] desData storage for deserialized data + \param [out] isUpdated true if any legacy object was updated, false otherwise + */ + virtual ErrorType deserialize(physx::general_PxIOStream2::PxFileBuf &stream, DeserializedData &desData, bool &isUpdated) = 0; + + /** + \brief Deserialize memory buffer into one or more NvParameterized objects + \param [in] data pointer to serialized data. It should be allocated via Traits. + \param [in] dataLen length of serialized data + \param [out] desData storage for deserialized data + + \warning Currently only binary serializer supports inplace deserialization + \warning Memory must be aligned to 8 byte boundary + */ + virtual ErrorType deserializeInplace(void *data, uint32_t dataLen, DeserializedData &desData); + + /** + \brief Deserialize memory buffer into one or more NvParameterized objects + \param [in] data pointer to serialized data + \param [in] dataLen length of serialized data + \param [out] desData storage for deserialized data + \param [out] isUpdated true if any legacy object was updated, false otherwise + + \warning Currently only binary serializer supports inplace deserialization + \warning Memory must be aligned to the boundary required by the data (see getInplaceAlignment) + */ + virtual ErrorType deserializeInplace(void *data, uint32_t dataLen, DeserializedData &desData, bool &isUpdated) = 0; + + /** + \brief Get minimum alignment required for inplace deserialization of data in stream + \param [in] stream stream which will be inplace deserialized + \param [out] align alignment required for inplace deserialization of stream + \note For most of the objects this will return default alignment of 8 bytes + */ + virtual ErrorType peekInplaceAlignment(physx::general_PxIOStream2::PxFileBuf& stream, uint32_t& align) = 0; + + /** + \brief Release deserializer and any memory allocations associated with it + */ + virtual void release() = 0; +}; + +PX_POP_PACK + +} // namespace NvParameterized + +#include "NvSerializer.inl" + +#endif // NV_SERIALIZER_H diff --git a/APEX_1.4/include/nvparameterized/NvSerializer.inl b/APEX_1.4/include/nvparameterized/NvSerializer.inl new file mode 100644 index 00000000..e9298bbc --- /dev/null +++ b/APEX_1.4/include/nvparameterized/NvSerializer.inl @@ -0,0 +1,177 @@ +// This code contains NVIDIA Confidential Information and is disclosed to you +// under a form of NVIDIA software license agreement provided separately to you. +// +// Notice +// NVIDIA Corporation and its licensors retain all intellectual property and +// proprietary rights in and to this software and related documentation and +// any modifications thereto. Any use, reproduction, disclosure, or +// distribution of this software and related documentation without an express +// license agreement from NVIDIA Corporation is strictly prohibited. +// +// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES +// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO +// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, +// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. +// +// Information and code furnished is believed to be accurate and reliable. +// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such +// information or for any infringement of patents or other rights of third parties that may +// result from its use. No license is granted by implication or otherwise under any patent +// or patent rights of NVIDIA Corporation. Details are subject to change without notice. +// This code supersedes and replaces all information previously supplied. +// NVIDIA Corporation products are not authorized for use as critical +// components in life support devices or systems without express written approval of +// NVIDIA Corporation. +// +// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. + +#include "NvParameterized.h" +#include "NvParameterizedTraits.h" + +namespace NvParameterized +{ + +/*! +\brief Serializer::SerializePlatform and Serializer::DeserializedData inline implementation +*/ + +/** +\brief Check binary compatibility of compiler versions +*/ +PX_INLINE bool DoCompilerVersMatch(SerializePlatform::CompilerType t, uint32_t v1, uint32_t v2) +{ + PX_UNUSED(t); + if( SerializePlatform::ANY_VERSION == v1 || SerializePlatform::ANY_VERSION == v2 ) + return true; + + //In future we should distinguish compiler versions which have different ABI + //but now we are optimistic + + return true; +} + +/** +\brief Check binary compatibility of OS versions +*/ +PX_INLINE bool DoOsVersMatch(SerializePlatform::OsType t, uint32_t v1, uint32_t v2) +{ + PX_UNUSED(t); + if( SerializePlatform::ANY_VERSION == v1 || SerializePlatform::ANY_VERSION == v2 ) + return true; + + return true; //See comment for doCompilerVersMatch +} + +PX_INLINE SerializePlatform::SerializePlatform() + : archType(ARCH_LAST), + compilerType(COMP_LAST), + compilerVer(ANY_VERSION), + osType(OS_LAST), + osVer(ANY_VERSION) +{} + +PX_INLINE SerializePlatform::SerializePlatform(ArchType archType_, CompilerType compType_, uint32_t compVer_, OsType osType_, uint32_t osVer_) + : archType(archType_), + compilerType(compType_), + compilerVer(compVer_), + osType(osType_), + osVer(osVer_) +{} + +PX_INLINE bool SerializePlatform::operator ==(const SerializePlatform &p) const +{ + return archType == p.archType + && compilerType == p.compilerType + && osType == p.osType + && DoCompilerVersMatch(compilerType, compilerVer, p.compilerVer) + && DoOsVersMatch(osType, osVer, p.osVer); +} + +PX_INLINE bool SerializePlatform::operator !=(const SerializePlatform &p) const +{ + return !(*this == p); +} + +template<typename T, int bufSize> PX_INLINE Serializer::DeserializedResults<T, bufSize>::DeserializedResults(): objs(0), nobjs(0), traits(0) {} + +template<typename T, int bufSize> PX_INLINE Serializer::DeserializedResults<T, bufSize>::DeserializedResults(const Serializer::DeserializedResults<T, bufSize> &data) +{ + *this = data; +} + +template<typename T, int bufSize> PX_INLINE Serializer::DeserializedResults<T, bufSize> &Serializer::DeserializedResults<T, bufSize>::operator =(const Serializer::DeserializedResults<T, bufSize> &rhs) +{ + if( this == &rhs ) + return *this; + + init(rhs.traits, rhs.objs, rhs.nobjs); + return *this; +} + +template<typename T, int bufSize> PX_INLINE void Serializer::DeserializedResults<T, bufSize>::clear() +{ + if ( objs && objs != buf ) //Memory was allocated? + { + PX_ASSERT(traits); + traits->free(objs); + } +} + +template<typename T, int bufSize> PX_INLINE Serializer::DeserializedResults<T, bufSize>::~DeserializedResults() +{ + clear(); +} + +template<typename T, int bufSize> PX_INLINE void Serializer::DeserializedResults<T, bufSize>::init(Traits *traits_, T *objs_, uint32_t nobjs_) +{ + init(traits_, nobjs_); + ::memcpy(objs, objs_, nobjs * sizeof(T)); +} + +template<typename T, int bufSize> PX_INLINE void Serializer::DeserializedResults<T, bufSize>::init(Traits *traits_, uint32_t nobjs_) +{ + clear(); + + traits = traits_; + nobjs = nobjs_; + + //Allocate memory if buf is too small + objs = nobjs <= bufSize + ? buf + : (T *)traits->alloc(nobjs * sizeof(T)); +} + +template<typename T, int bufSize> PX_INLINE uint32_t Serializer::DeserializedResults<T, bufSize>::size() const +{ + return nobjs; +} + +template<typename T, int bufSize> PX_INLINE T &Serializer::DeserializedResults<T, bufSize>::operator[](uint32_t i) +{ + PX_ASSERT( i < nobjs ); + return objs[i]; +} + +template<typename T, int bufSize> PX_INLINE const T &Serializer::DeserializedResults<T, bufSize>::operator[](uint32_t i) const +{ + PX_ASSERT( i < nobjs ); + return objs[i]; +} + +template<typename T, int bufSize> PX_INLINE void Serializer::DeserializedResults<T, bufSize>::getObjects(T *outObjs) +{ + ::memcpy(outObjs, objs, nobjs * sizeof(T)); +} + +template<typename T, int bufSize> PX_INLINE void Serializer::DeserializedResults<T, bufSize>::releaseAll() +{ + for(uint32_t i = 0; i < nobjs; ++i) + { + if (objs[i]) + { + objs[i]->destroy(); // FIXME What should we do with buf. And should we delete T* obj? + } + } +} + +} // namespace NvParameterized diff --git a/APEX_1.4/include/particles/EffectPackageActor.h b/APEX_1.4/include/particles/EffectPackageActor.h new file mode 100644 index 00000000..cbe60bc9 --- /dev/null +++ b/APEX_1.4/include/particles/EffectPackageActor.h @@ -0,0 +1,299 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef EFFECT_PACKAGE_ACTOR_H +#define EFFECT_PACKAGE_ACTOR_H + +#include "Actor.h" +#include "EmitterActor.h" + +/*! +\file +\brief An EffectPackageActor represents an instantiation of a collection of related particle actors +The EffectPackage system allows for multiple related particle actors to be instantiated as a single +unit with a single root pose transform. This can be one or more emitters as well as associated +field samplers, heat sources, etc. This single instantiation can be subject to level of detail culling +and otherwise manipulated as a single unit. + +EffectPackages are authored using the 'ParticleEffectTool' which allows the developer to rapidly +prototype a combined 'particle effect'. This is a PhysX 3.x only feature. +*/ + +struct ID3D11ShaderResourceView; +struct ID3D11DeviceContext; + +namespace physx +{ + class PxRigidDynamic; +} + +namespace nvidia +{ + +namespace general_renderdebug4 +{ +///Forward reference the RenderDebugInterface class +class RenderDebugInterface; +}; + +namespace apex +{ + +/** + This enum is used to identity what 'type' of effect +*/ +enum EffectType +{ + ET_EMITTER, + ET_HEAT_SOURCE, + ET_SUBSTANCE_SOURCE, + ET_TURBULENCE_FS, + ET_JET_FS, + ET_ATTRACTOR_FS, + ET_FORCE_FIELD, + ET_NOISE_FS, + ET_VORTEX_FS, + ET_WIND_FS, + ET_RIGID_BODY, + ET_VELOCITY_SOURCE, + ET_FLAME_EMITTER, + ET_LAST +}; + +class Actor; +class RenderVolume; + +/** +\brief Defines the EffectPackageActor API which is instantiated from an EffectPackageAsset +*/ +class EffectPackageActor : public Actor +{ +public: + + /** + \brief Fade out the EffectPackageActor over a period of time. + This method will cause the actors within the EffectPackage to be 'faded out' over a period of time. + The EffectPackageAsset will define how this fadeOut operation is to be applied. Some actors may + simply be turned off over this duration while others are modulated in some way. For example, by default, + emitter actors will have their emitter rate reduced over this duration so they do not appear to + immediately cut off + + \param [in] fadetime : The duration to fade out the associated effects in seconds + */ + virtual void fadeOut(float fadetime) = 0; + + /** + \brief Fade in the EffectPackageActor over a period of time. + This method will cause the associated effects to be faded in over a period of time. + It will begin the linear interpolation fade process relative to the current fade time. + Meaning if you had previously specified a fadeOut duration of 1 second but then execute + a fadeIn just a 1/2 second later, will will begin fading in from a 50% level; not zero. + + \param [in] fadetime : The duration to fade this effect in, in seconds + */ + virtual void fadeIn(float fadetime) = 0; + + /** + \brief Returns the number of effects within this effect package. + */ + virtual uint32_t getEffectCount() const = 0; + + /** + \brief Returns the type of effect at this index location + + \param [in] effectIndex : The effect number to refer to; must be less than the result of getEffectCount + */ + virtual EffectType getEffectType(uint32_t effectIndex) const = 0; + + /** + \brief Returns the name of the effect at this index. + + \param [in] effectIndex : The effect number to refer to; must be less than the result of getEffectCount + */ + virtual const char* getEffectName(uint32_t effectIndex) const = 0; + + /** + \brief Returns true if this sub-effect is currently enabled. + + \param [in] effectIndex : The effect number to refer to; must be less than the result of getEffectCount + */ + virtual bool isEffectEnabled(uint32_t effectIndex) const = 0; + + /** + \brief Sets the enabled state of this sub-effect + + \param [in] effectIndex : The effect number to refer to; must be less than the result of getEffectCount + \param [in] state : Whether the effect should be enabled or not. + */ + virtual bool setEffectEnabled(uint32_t effectIndex, bool state) = 0; + + /** + \brief Sets the over all effect scale, this is a uniform scaling factor. + + \param [in] scale : The uniform scale to apply to all effects in this effect package + */ + virtual void setCurrentScale(float scale) = 0; + + /** + \brief Gets the current overall uniform effect scale + */ + virtual float getCurrentScale(void) const = 0; + + /** + \brief Returns the pose of this sub-effect; returns as a bool the active state of this effect. + + \param [in] effectIndex : The effect number to refer to; must be less than the result of getEffectCount + \param [pose] : Contains the pose requested + \param [worldSpace] : Whether to return the pose in world-space or in parent-relative space. + */ + virtual bool getEffectPose(uint32_t effectIndex, PxTransform& pose, bool worldSpace) = 0; + + /** + \brief Sets the pose of this sub-effect; returns as a bool the active state of this effect. + + \param [in] effectIndex : The effect number to refer to; must be less than the result of getEffectCount + \param [pose] : Contains the pose to be set + \param [worldSpace] : Whether to return the pose in world-space or in parent-relative space. + */ + virtual bool setEffectPose(uint32_t effectIndex, const PxTransform& pose, bool worldSpace) = 0; + + /** + \brief Returns the base Actor pointer for this effect. + Use this method if you need direct access to the base Actor pointer relative to this + effect. You must use 'getEffectType' to know what type of actor this is referring to before + you cast it to either an emitter, or heat source, or turbulence actor, etc. + It is important to note that the application cannot cache this pointer as it may be deleted in + subsequent frames due to level of detail calculations or timing values such as fade out operations. + + \param [in] effectIndex : The effect number to refer to; must be less than the result of getEffectCount + + \return Returns the Actor pointer for this effect. This may be NULL if that effect is not currently active. + */ + virtual Actor* getEffectActor(uint32_t effectIndex) const = 0; + + /** + \brief Returns the base PxRigidDynamic actor pointer for this effect. + Use this method if you need direct access to the base PxRigidDynamic actor pointer relative to this + effect. + + \param [in] effectIndex : The effect number to refer to; must be less than the result of getEffectCount, must be a rigid dynamic effect + + \return Returns the PxRigidDynamic pointer for this effect. This may be NULL if that effect is not currently active. + */ + virtual PxRigidDynamic* getEffectRigidDynamic(uint32_t effectIndex) const = 0; + + /** + \brief Forces the state of all emitters associated with this effect package to be on or off. + This method allows the application to manually force all emitters to be active or inactive + based on an explicit call. + + \param [state] : Determines whether to set all emitters on or off + */ + virtual void setEmitterState(bool state) = 0; + + /** + \brief A helper method to return the active number of particles being simulated by all related effects in this EffectPackageActor + + \return Returns the number of particles active relative to this EffectPackageActor + */ + virtual uint32_t getActiveParticleCount() const = 0; + + /** + \brief This helper method reports if any emitters within this EffectPackageActor are still actively emitting particles. + + This method allows the application to determine whether or not any emitters are actively running + relative to this actor. Typically this would be used to defer deleting an effect while it is still active. + + \return Returns true if any emitters in the actor are still active. + */ + virtual bool isStillEmitting() const = 0; + + /** + Returns true if any portion of the effect is still considered 'alive' based on LOD and duration settings. + */ + virtual bool isAlive(void) const = 0; + + /** + \brief Allows the application to manually enable this EffectPackageActor + + This method is used by the application to manually force the EffectPackageActor to be enabled. + This is generally used based on some kind of game logic where the EffectPackageActor has been + pre-allocated and placed into the world but is initially inactive until some event occurs. + + \param [state] Set the current enabled state to true or false + */ + virtual void setEnabled(bool state) = 0; + + /** + \brief Returns the current enabled state for this actor + */ + virtual bool getEnabled() const = 0; + + /** + \brief Sets the root pose for this EffectPackageActor + It's important to note that child-relative poses for each sub-component in an EffectPackageActor + are authored in the ParticleEffectTool. + + \param [pose] : Sets the current root pose for this EffectPackageActor + */ + virtual void setPose(const PxTransform& pose) = 0; + + /** + \brief Returns the current root pose for this EffectPackageActor + */ + virtual const PxTransform& getPose() const = 0; + + /** + \brief This method is used by the ParticleEffectTool to refresh a currently running effect with real-time property changes + */ + virtual void refresh() = 0; + + /** + \brief Releases this EffectPackageActor and all associated children effects + */ + virtual void release() = 0; + + /** + \brief A convenient helper method to return the name of the asset used to to create this actor. + */ + virtual const char* getName() const = 0; + + /** + \brief returns the duration of the effect; accounting for maximum duration of each sub-effect. A duration of 'zero' means it is an infinite lifetime effect. + */ + virtual float getDuration() const = 0; + + /** + \brief Returns the current lifetime of the particle. + */ + virtual float getCurrentLife() const = 0; + + /** + \brief Sets the preferred render volume for emitters in this effect package + */ + virtual void setPreferredRenderVolume(RenderVolume* volume) = 0; + + /** + \brief Returns true if this effect package contains a turbulence effect that specifies a volume-render material; if so then the application may want to set up volume rendering + */ + virtual const char * hasVolumeRenderMaterial(uint32_t &index) const = 0; + + /** + \brief Sets the emitter validation callback for any newly created emitter actors. + */ + virtual void setApexEmitterValidateCallback(EmitterActor::EmitterValidateCallback *callback) = 0; +}; + + +}; // end of apex namespace +}; // end of physx namespace + +#endif diff --git a/APEX_1.4/include/particles/EffectPackageAsset.h b/APEX_1.4/include/particles/EffectPackageAsset.h new file mode 100644 index 00000000..6e666443 --- /dev/null +++ b/APEX_1.4/include/particles/EffectPackageAsset.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef EFFECT_PACKAGE_ASSET_H +#define EFFECT_PACKAGE_ASSET_H + +#include "Apex.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#define PARTICLES_EFFECT_PACKAGE_AUTHORING_TYPE_NAME "EffectPackageAsset" + +/** +\brief Describes an EffectPackageAsset; a collection of particle related effects (emitters, field samplers, etc.) +*/ +class EffectPackageAsset : public Asset +{ +protected: + + virtual ~EffectPackageAsset() {} + +public: + /** + \brief returns the duration of the effect; accounting for maximum duration of each sub-effect. A duration of 'zero' means it is an infinite lifetime effect. + */ + virtual float getDuration() const = 0; + + /** + \brief This method returns true if the authored asset has the 'hint' set to indicate the actors should be created with a unique render volume. + */ + virtual bool useUniqueRenderVolume() const = 0; + + +}; // + +/** + \brief Describes an EffectPackageAssetAuthoring class; not currently used. The ParticleEffectTool is used to + author EffectPackageAssets + */ +class EffectPackageAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~EffectPackageAssetAuthoring() {} +}; + +PX_POP_PACK + +} // end of apex namespace +} // end of nvidia namespace + +#endif diff --git a/APEX_1.4/include/particles/ModuleParticles.h b/APEX_1.4/include/particles/ModuleParticles.h new file mode 100644 index 00000000..0040f974 --- /dev/null +++ b/APEX_1.4/include/particles/ModuleParticles.h @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_PARTICLES_H +#define MODULE_PARTICLES_H + +#include "Apex.h" + + +namespace nvidia +{ + + +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class Module; +class Scene; +class EffectPackageActor; +/** +\brief Defines the API for the Particles Module + +The particles module combines the features of a number of particle related APEX modules +into one location; with the exception of APEX turbulence. It also provides support for +the EffectPackage actor and asset as well as integration with the ParticleEffectAuthoring +tool. + +Loading the APEX Particles module will now automatically cause the following related modules +to be instantiated. + +APEX_Emitter +APEX_BasicIOS +APEX_IOFX +APEX_FieldSampler +APEX_BasicIOS +APEX_ParticleIOS +APEX_ForceField + +These modules are no longer loaded as separate DLLs and instantiated individually like they were +prior to APEX 1.3. Instead simply loading the APEX_Particles DLL or calling 'instantiateModuleParticles' +will cause the other particle related modules to be loaded. + +The rationale for making this change was to simplify the startup/shutdown sequence for applications +using APEX particle related effects. It also dramatically simplifies the distribution process for +developers as they now only have to deal with a single DLL rather than as many as 8 which were +required before. + +The turbulence module was not folded into the unified APEX_Particles module at this time since +the source code for it is not yet made available to licensees. + +It is important to note that since the APEX_Particles module does not load the Turbulence module, +the application *must* load the Turbulence module first so that it will already be registered. +*/ +class ModuleParticles : public Module +{ +public: + + /** + \brief Return one of the particle related modules, by name, created by the particles module + */ + virtual nvidia::apex::Module* getModule(const char* moduleName) = 0; + + /** + \brief Registers and adds either a single GraphicsMaterial definition or an entire array of them to the particles module. + + The EffectPackage system works with a set of predefined assets which have been authored using + the ParticleEffectTool. This method adds or revises either a single asset or an array of assets. + When an EffectPackageActor is instantiated it may refer to assets which have been previously authored and + registered using this method. + + \return Returns true if during the registration of this asset the contents were modified. + */ + virtual bool setEffectPackageGraphicsMaterialsDatabase(const NvParameterized::Interface* dataBase) = 0; + + /** + \brief Registers and adds either a single IOS definition or an entire array of them to the particles module. + + The EffectPackage system works with a set of predefined assets which have been authored using + the ParticleEffectTool. This method adds or revises either a single asset or an array of assets. + When an EffectPackageActor is instantiated it may refer to assets which have been previously authored and + registered using this method. + + \return Returns true if during the registration of this asset the contents were modified. + */ + virtual bool setEffectPackageIOSDatabase(const NvParameterized::Interface* dataBase) = 0; + + /** + \brief Registers and adds either a single IOFX definition or an entire array of them to the particles module. + + The EffectPackage system works with a set of predefined assets which have been authored using + the ParticleEffectTool. This method adds or revises either a single asset or an array of assets. + When an EffectPackageActor is instantiated it may refer to assets which have been previously authored and + registered using this method. + + \return Returns true if during the registration of this asset the contents were modified. + */ + virtual bool setEffectPackageIOFXDatabase(const NvParameterized::Interface* dataBase) = 0; + + /** + \brief Registers and adds either a single Emitter definition or an entire array of them to the particles module. + + The EffectPackage system works with a set of predefined assets which have been authored using + the ParticleEffectTool. This method adds or revises either a single asset or an array of assets. + When an EffectPackageActor is instantiated it may refer to assets which have been previously authored and + registered using this method. + + \return Returns true if during the registration of this asset the contents were modified. + */ + virtual bool setEffectPackageEmitterDatabase(const NvParameterized::Interface* dataBase) = 0; + + /** + \brief Registers and adds either a single EffectPackage definition or an entire array of them to the particles module. + + The EffectPackage system works with a set of predefined assets which have been authored using + the ParticleEffectTool. This method adds or revises either a single asset or an array of assets. + When an EffectPackageActor is instantiated it may refer to assets which have been previously authored and + registered using this method. + + \return Returns true if during the registration of this asset the contents were modified. + */ + virtual bool setEffectPackageDatabase(const NvParameterized::Interface* dataBase) = 0; + + /** + \brief Registers and adds either a single FieldSampler definition or an entire array of them to the particles module. + + The EffectPackage system works with a set of predefined assets which have been authored using + the ParticleEffectTool. This method adds or revises either a single asset or an array of assets. + When an EffectPackageActor is instantiated it may refer to assets which have been previously authored and + registered using this method. + + \return Returns true if during the registration of this asset the contents were modified. + */ + virtual bool setEffectPackageFieldSamplerDatabase(const NvParameterized::Interface* dataBase) = 0; + + /** + \brief Returns the NvParameterized::Interface representing the array of GraphicsMaterial assets registered by the Paricles modules + */ + virtual const NvParameterized::Interface* getEffectPackageGraphicsMaterialsDatabase() const = 0; + + /** + \brief Returns the NvParameterized::Interface representing the array of IOS assets registered by the Paricles modules + */ + virtual const NvParameterized::Interface* getEffectPackageIOSDatabase() const = 0; + + /** + \brief Returns the NvParameterized::Interface representing the array of IOFX assets registered by the Paricles modules + */ + virtual const NvParameterized::Interface* getEffectPackageIOFXDatabase() const = 0; + + /** + \brief Returns the NvParameterized::Interface representing the array of Emitter assets registered by the Paricles modules + */ + virtual const NvParameterized::Interface* getEffectPackageEmitterDatabase() const = 0; + + /** + \brief Returns the NvParameterized::Interface representing the array of EffectPackage assets registered by the Paricles modules + */ + virtual const NvParameterized::Interface* getEffectPackageDatabase() const = 0; + + /** + \brief Returns the NvParameterized::Interface representing the array of FieldSampler assets registered by the Paricles modules + */ + virtual const NvParameterized::Interface* getEffectPackageFieldSamplerDatabase() const = 0; + + /** + \brief This helper method will return the NvParameterized::Interface for a previously defined 'GraphicsMaterial' + This 'GraphicsMaterial' contains settings which were defined in the ParticleEffectTool. The ParticleEffectTool + will let the user define things like a source texture, a blend mode, user properties, and celled animation settings, + relative to a particular named material. The application can use all of these settings or none of them as they prefer. + These settings are used by the ParticleEffectTool to provide a prototype visualization of a sprite based particle effect. + + \param [in] name : The name of the predefined graphics material + + \return A pointer to the NvParameterized::Interface representing this material or NULL if not found. + */ + virtual const NvParameterized::Interface* locateGraphicsMaterialData(const char* name) const = 0; + + /** + \brief This helper method will return the NvParameterized::Interface data for a predefined asset in one of the registered 'databases' + When an application gets a callback asking for an asset which was authored using the ParticleEffectTool it can use + this method to extract the current parameter data necessary to create that asset. + + \param [in] resourceName : The name of the previously defined/registered asset + \param [in] nameSpace : The namespace of the asset. + + \return Returns the NvParamterized::Interface pointer for that asset or NULL if not found. + */ + virtual NvParameterized::Interface* locateResource(const char* resourceName, + const char* nameSpace) = 0; + + + /** + \brief This is a helper method to return the names of all assets registered relative to a particular namespace. + + \param [in] nameSpace : The namespace of the asset type we are searching for. + \param [in] nameCount : A reference to a counter which will contain the number of assets found matching this namespace + \param [in] variants : A reference to an array of const char pointers which will contain what reference variant each returned asset matches. + + \return Returns an array of const char pointers representing the asset names matching this resource type. + */ + virtual const char** getResourceNames(const char* nameSpace, uint32_t& nameCount, const char** &variants) = 0; + + /** + \brief This method globally enabled or disables the screen-space culling LOD feature for EffectPackageActors + EffectPackageActors can be culled based on whether or not they are on screen. For this to work the application + must provide a valid projection matrix, in addition to a current view matrix, into the SDK. + The projection matrix in some engines define Z positive as being in front of the screen and others Z negative. + + \param [in] state : Whether to enable or disable the screen culling feature + \param [in] znegative : Whether or not Z is positive or negative when a point projected into screen-space is in front or behind the camera. + */ + virtual void setEnableScreenCulling(bool state, bool znegative) = 0; + + /** + \brief Resets the emitter pool; causing all cached emitters to be released. + */ + virtual void resetEmitterPool() = 0; + + /** + \brief Sets the state to determine whether or not the particles module is going to use the emitter pool. + The emitter pool is an optimization which prevents the effect system from constantly creating and the immediately releasing a great deal of APEX related + assets and resources. Take for example the case of a short lived particle effect. Without an emitter pool, triggering this effect would cause a number of + assets and rendering resources to be allocated sufficient to render and simulate this effect. But, in just a very short time, the effect lifespan is over and + all of those assets and rendering resources are deleted. Then the same effect gets fired again causing the assets and render resources to be immediately re-allocated + yet once again. With the emitter pool enabled, the original emitter is not actually released when it times out. Therefore the render resources and associated assets + stay resident in memory. When the same effect gets triggered again, it simply reuses the previously allocated emitter from the emitter pool. + */ + virtual void setUseEmitterPool(bool state) = 0; + + /** + \brief Returns the current state of the emitter pool status. + */ + virtual bool getUseEmitterPool() const = 0; + + /** + \brief Used by the ParticleEffectTool to initialize the default database values for the editor + */ + virtual void initializeDefaultDatabases() = 0; + +protected: + virtual ~ModuleParticles() {} +}; + +#if !defined(_USRDLL) +/** +* If this module is distributed as a static library, the user must call this +* function before calling ApexSDK::createModule("Particles") +*/ +void instantiateModuleParticles(); +#endif + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // MODULE_PARTICLES_H diff --git a/APEX_1.4/include/particles/ParticlesPreview.h b/APEX_1.4/include/particles/ParticlesPreview.h new file mode 100644 index 00000000..a3e60d70 --- /dev/null +++ b/APEX_1.4/include/particles/ParticlesPreview.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef PARTICLES_PREVIEW_H +#define PARTICLES_PREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderDebugInterface; + +namespace APEX_PARTICLES +{ +/** + \def PARTICLES_DRAW_NOTHING + Draw no items. +*/ +static const uint32_t PARTICLES_DRAW_NOTHING = (0x00); +/** + \def PARTICLES_DRAW_ICON + Draw the icon. +*/ +static const uint32_t PARTICLES_DRAW_ICON = (0x01); +/** + \def PARTICLES_DRAW_BOUNDARIES + Draw the Particles include shapes. +*/ +static const uint32_t PARTICLES_DRAW_BOUNDARIES = (0x2); +/** + \def PARTICLES_DRAW_WITH_CYLINDERS + Draw the dynamicsystem field boundaries. +*/ +static const uint32_t PARTICLES_DRAW_WITH_CYLINDERS = (0x4); +/** + \def PARTICLES_DRAW_FULL_DETAIL + Draw all of the preview rendering items. +*/ +static const uint32_t PARTICLES_DRAW_FULL_DETAIL = (PARTICLES_DRAW_ICON + PARTICLES_DRAW_BOUNDARIES); +/** + \def PARTICLES_DRAW_FULL_DETAIL_BOLD + Draw all of the preview rendering items using cylinders instead of lines to make the text and icon look BOLD. +*/ +static const uint32_t PARTICLES_DRAW_FULL_DETAIL_BOLD = (PARTICLES_DRAW_FULL_DETAIL + PARTICLES_DRAW_WITH_CYLINDERS); +} + +/** +\brief APEX asset preview wind asset. +*/ +class ParticlesPreview : public AssetPreview +{ +public: + /** + Set the scale of the icon. + The unscaled icon has is 1.0x1.0 game units. + By default the scale of the icon is 1.0. (unscaled) + */ + virtual void setIconScale(float scale) = 0; + /** + Set the detail level of the preview rendering by selecting which features to enable. + Any, all, or none of the following masks may be added together to select what should be drawn. + The defines for the individual items are PARTICLES_DRAW_NOTHING, PARTICLES_DRAW_ICON, PARTICLES_DRAW_BOUNDARIES, + PARTICLES_DRAW_WITH_CYLINDERS. + All items may be drawn using the macro PARTICLES_DRAW_FULL_DETAIL and PARTICLES_DRAW_FULL_DETAIL_BOLD. + */ + virtual void setDetailLevel(uint32_t detail) = 0; + +protected: + ParticlesPreview() {}; +}; + + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // PARTICLES_PREVIEW_H diff --git a/APEX_1.4/include/pxparticleios/ModuleParticleIos.h b/APEX_1.4/include/pxparticleios/ModuleParticleIos.h new file mode 100644 index 00000000..48c03abb --- /dev/null +++ b/APEX_1.4/include/pxparticleios/ModuleParticleIos.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_PARTICLE_IOS_H +#define MODULE_PARTICLE_IOS_H + +#include "Apex.h" +#include <limits.h> + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class ParticleIosAsset; +class ParticleIosAssetAuthoring; +class CudaTestManager; +class Scene; + +/** +\brief ParticleIOS Module - Manages PhysX 3.0 PxParticleSystem and PxParticleFluid simulations +*/ +class ModuleParticleIos : public Module +{ +protected: + virtual ~ModuleParticleIos() {} + +public: + /// Get ParticleIOS authoring type name + virtual const char* getParticleIosTypeName() = 0; +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // MODULE_PARTICLE_IOS_H diff --git a/APEX_1.4/include/pxparticleios/ParticleIosActor.h b/APEX_1.4/include/pxparticleios/ParticleIosActor.h new file mode 100644 index 00000000..f073284e --- /dev/null +++ b/APEX_1.4/include/pxparticleios/ParticleIosActor.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef PARTICLE_IOS_ACTOR_H +#define PARTICLE_IOS_ACTOR_H + +#include "Apex.h" + +#if PX_PHYSICS_VERSION_MAJOR == 3 +#include "ScopedPhysXLock.h" +#endif + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief ParticleIOS Actor. A simple actor that simulates a particle system. + */ +class ParticleIosActor : public Actor +{ +public: + // This actor is not publically visible + +protected: + virtual ~ParticleIosActor() {} +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // PARTICLE_IOS_ACTOR_H diff --git a/APEX_1.4/include/pxparticleios/ParticleIosAsset.h b/APEX_1.4/include/pxparticleios/ParticleIosAsset.h new file mode 100644 index 00000000..0fa42f9b --- /dev/null +++ b/APEX_1.4/include/pxparticleios/ParticleIosAsset.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef PARTICLE_IOS_ASSET_H +#define PARTICLE_IOS_ASSET_H + +#include "Apex.h" +#include <limits.h> + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +#define PARTICLE_IOS_AUTHORING_TYPE_NAME "ParticleIosAsset" + +/** + \brief APEX Particle System Asset + */ +class ParticleIosAsset : public IosAsset +{ +public: + ///Get the radius of a particle + virtual float getParticleRadius() const = 0; + + ///Get the maximum number of particles that are allowed to be newly created on each frame + virtual float getMaxInjectedParticleCount() const = 0; + + ///Get the maximum number of particles that this IOS can simulate + virtual uint32_t getMaxParticleCount() const = 0; + + ///Get the mass of a particle + virtual float getParticleMass() const = 0; + +protected: + virtual ~ParticleIosAsset() {} +}; + +/** + \brief APEX Particle System Asset Authoring class + */ +class ParticleIosAssetAuthoring : public AssetAuthoring +{ +public: + ///Set the radius of a particle + virtual void setParticleRadius(float) = 0; + + ///Set the maximum number of particles that are allowed to be newly created on each frame + virtual void setMaxInjectedParticleCount(float count) = 0; + + ///Set the maximum number of particles that this IOS can simulate + virtual void setMaxParticleCount(uint32_t count) = 0; + + ///Set the mass of a particle + virtual void setParticleMass(float) = 0; + + ///Set the (NRP) name for the collision group. + virtual void setCollisionGroupName(const char* collisionGroupName) = 0; + + ///Set the (NRP) name for the collision group mask. + virtual void setCollisionGroupMaskName(const char* collisionGroupMaskName) = 0; + +protected: + virtual ~ParticleIosAssetAuthoring() {} +}; + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // PARTICLE_IOS_ASSET_H diff --git a/APEX_1.4/include/turbulencefs/FlameEmitterActor.h b/APEX_1.4/include/turbulencefs/FlameEmitterActor.h new file mode 100644 index 00000000..a6b61273 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/FlameEmitterActor.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef FLAME_EMITTER_ACTOR_H +#define FLAME_EMITTER_ACTOR_H + +#include "Apex.h" +#include "Shape.h" + +namespace nvidia +{ +namespace apex +{ + +class FlameEmitterAsset; + + +/** + \brief Flame Emitter Actor class + */ +class FlameEmitterActor : public Actor +{ +protected: + virtual ~FlameEmitterActor() {} + +public: + ///Returns the asset the instance has been created from. + virtual FlameEmitterAsset* getFlameEmitterAsset() const = 0; + + + ///enable/disable flame emitter + virtual void setEnabled(bool enable) = 0; + + ///Returns true if flame emitter enabled + virtual bool isEnabled() const = 0; + + ///intersect the collision shape against a given AABB + virtual bool intersectAgainstAABB(const PxBounds3&) const = 0; + + ///get the global pose + virtual PxMat44 getPose() const = 0; + + ///set the global pose + virtual void setPose(PxMat44 pose) = 0; + + ///Sets the uniform overall object scale + virtual void setCurrentScale(float scale) = 0; + + ///Retrieves the uniform overall object scale + virtual float getCurrentScale(void) const = 0; + + virtual void release() = 0; +}; + + +} +} // end namespace nvidia + +#endif diff --git a/APEX_1.4/include/turbulencefs/FlameEmitterAsset.h b/APEX_1.4/include/turbulencefs/FlameEmitterAsset.h new file mode 100644 index 00000000..1d865996 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/FlameEmitterAsset.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef FLAME_EMITTER_ASSET_H +#define FLAME_EMITTER_ASSET_H + +#include "Apex.h" +#include "CustomBufferIterator.h" + +#define FLAME_EMITTER_AUTHORING_TYPE_NAME "FlameEmitterAsset" + +namespace nvidia +{ +namespace apex +{ + +/** + \brief Flame Emitter Asset class + */ +class FlameEmitterAsset : public Asset +{ +protected: + virtual ~FlameEmitterAsset() {} +}; + + +/** + \brief Flame Emitter Asset Authoring class + */ +class FlameEmitterAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~FlameEmitterAssetAuthoring() {} +}; + + +} +} // end namespace nvidia + +#endif // FLAME_EMITTER_ASSET_H diff --git a/APEX_1.4/include/turbulencefs/FlameEmitterPreview.h b/APEX_1.4/include/turbulencefs/FlameEmitterPreview.h new file mode 100644 index 00000000..ad129ad0 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/FlameEmitterPreview.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef FLAME_EMITTER_PREVIEW_H +#define FLAME_EMITTER_PREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief This class provides the asset preview for APEX Flame Emitter Assets. +*/ +class FlameEmitterPreview : public AssetPreview +{ +public: + public: + ///Draws the emitter + virtual void drawFlameEmitterPreview() = 0; + ///Sets the scaling factor of the renderable + virtual void setScale(float scale) = 0; + +protected: + FlameEmitterPreview() {} +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // FLAME_EMITTER_PREVIEW_H
\ No newline at end of file diff --git a/APEX_1.4/include/turbulencefs/HeatSourceActor.h b/APEX_1.4/include/turbulencefs/HeatSourceActor.h new file mode 100644 index 00000000..ac9ba919 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/HeatSourceActor.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef HEAT_SOURCE_ACTOR_H +#define HEAT_SOURCE_ACTOR_H + +#include "Apex.h" +#include "Shape.h" + +namespace nvidia +{ +namespace apex +{ + +class HeatSourceAsset; + + +/** + \brief Turbulence HeatSource Actor class + */ +class HeatSourceActor : public Actor +{ +protected: + virtual ~HeatSourceActor() {} + +public: + ///Returns the asset the instance has been created from. + virtual HeatSourceAsset* getHeatSourceAsset() const = 0; + + ///enable/disable the heating + virtual void setEnabled(bool enable) = 0; + + ///Returns true if heating enabled + virtual bool isEnabled() const = 0; + + ///intersect the collision shape against a given AABB + virtual bool intersectAgainstAABB(PxBounds3) = 0; + + ///Returns pointer to Shape of heat source + virtual Shape* getShape() const = 0; + + ///If it is a box, cast to box class, return NULL otherwise + virtual BoxShape* getBoxShape() = 0; + + ///If it is a sphere, cast to sphere class, return NULL otherwise + virtual SphereShape* getSphereShape() = 0; + + ///Return average value of temperature + virtual float getAverageTemperature() const = 0; + + ///Return STD value of temperature + virtual float getStdTemperature() const = 0; + + ///get the pose of a heat source shape + virtual PxMat44 getPose() const = 0; + + ///Set average and STD values for temperature + virtual void setTemperature(float averageTemperature, float stdTemperature) = 0; + + ///set the pose of a heat source shape + virtual void setPose(PxMat44 pose) = 0; + + ///Sets the uniform overall object scale + virtual void setCurrentScale(float scale) = 0; + + ///Retrieves the uniform overall object scale + virtual float getCurrentScale(void) const = 0; + + virtual void release() = 0; +}; + + +} +} // end namespace nvidia + +#endif diff --git a/APEX_1.4/include/turbulencefs/HeatSourceAsset.h b/APEX_1.4/include/turbulencefs/HeatSourceAsset.h new file mode 100644 index 00000000..a3dccaa5 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/HeatSourceAsset.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef HEAT_SOURCE_ASSET_H +#define HEAT_SOURCE_ASSET_H + +#include "Apex.h" +#include "CustomBufferIterator.h" + +#define HEAT_SOURCE_AUTHORING_TYPE_NAME "HeatSourceAsset" + +namespace nvidia +{ +namespace apex +{ + +class TurbulenceFSActorParams; +class TurbulenceFSActor; +class TurbulenceFSPreview; + +/** + \brief Turbulence FieldSampler Asset class + */ +class HeatSourceAsset : public Asset +{ +protected: + virtual ~HeatSourceAsset() {} +}; + + +/** + \brief Turbulence FieldSampler Asset Authoring class + */ +class HeatSourceAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~HeatSourceAssetAuthoring() {} +}; + + +} +} // end namespace nvidia + +#endif // HEAT_SOURCE_ASSET_H diff --git a/APEX_1.4/include/turbulencefs/HeatSourcePreview.h b/APEX_1.4/include/turbulencefs/HeatSourcePreview.h new file mode 100644 index 00000000..2af3beb0 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/HeatSourcePreview.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef HEAT_SOURCE_PREVIEW_H +#define HEAT_SOURCE_PREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief This class provides the asset preview for APEX HeatSource Assets. +*/ +class HeatSourcePreview : public AssetPreview +{ +public: + public: + ///Draws the emitter + virtual void drawHeatSourcePreview() = 0; + ///Sets the scaling factor of the renderable + virtual void setScale(float scale) = 0; + +protected: + HeatSourcePreview() {} +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // HEAT_SOURCE_PREVIEW_H
\ No newline at end of file diff --git a/APEX_1.4/include/turbulencefs/ModuleTurbulenceFS.h b/APEX_1.4/include/turbulencefs/ModuleTurbulenceFS.h new file mode 100644 index 00000000..aedcad7c --- /dev/null +++ b/APEX_1.4/include/turbulencefs/ModuleTurbulenceFS.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef MODULE_TURBULENCE_FS_H +#define MODULE_TURBULENCE_FS_H + +#include "Apex.h" +#include "Shape.h" +#include "VelocitySourceActor.h" +#include "HeatSourceActor.h" +#include "SubstanceSourceActor.h" +#include "FlameEmitterActor.h" +#include "TestBase.h" +#include "PxFiltering.h" + +namespace nvidia +{ +namespace apex +{ + +class TurbulenceFSAsset; +class TurbulenceFSAssetAuthoring; + +class TurbulenceRenderCallback; + +/** +\brief Class for TurbulenceFS module. +*/ +class ModuleTurbulenceFS : public Module +{ +public: + + /// Set custom timestep parameters for the specified scene (only for one simulation call) + virtual bool setCustomTimestep(const Scene& apexScene, float timestep, int numIterations) = 0; + + /// Enable/disable multi-solve feature for the specified scene (disable by default) + virtual bool setMultiSolveEnabled(const Scene& apexScene, bool enabled) = 0; + + /// Enable output velocity field to UserRenderSurfaceBuffer + virtual void enableOutputVelocityField() = 0; + + /// Enable output density field to UserRenderSurfaceBuffer + virtual void enableOutputDensityField() = 0; + + /// Enable output flame field to UserRenderSurfaceBuffer + virtual void enableOutputFlameField() = 0; + + /// Set custum filter shader to filter collision shapes interacting with Turbulence grids + virtual void setCustomFilterShader(physx::PxSimulationFilterShader shader, const void* shaderData, uint32_t shaderDataSize) = 0; + + ///Returns pointer to TestBase. Internal feature, return NULL for distribution builds + virtual const TestBase* getTestBase(Scene* apexScene) const = 0; + + /// get grid size power. Grid size of all actors will be multiplied by 2^(grid size power). But final grid size restricted by defined values + virtual int32_t getGridSizePow() const = 0; + + /// set grid size power. Grid size of all actors will be multiplied by 2^(grid size power). But final grid size restricted by defined values + virtual void setGridSizePow(int32_t power) = 0; + + ///Prepare renderables for rendering, should be called each frame before using renderables to update them with the most recent data + virtual void prepareRenderables(const Scene&) = 0; + + /** + \brief Set TurbulenceRenderCallback + \see TurbulenceRenderCallback + */ + virtual bool setTurbulenceRenderCallback(const Scene& apexScene, TurbulenceRenderCallback* ) = 0; + + /** + \brief Get TurbulenceRenderCallback + \see TurbulenceRenderCallback + */ + virtual TurbulenceRenderCallback* getTurbulenceRenderCallback(const Scene& apexScene) const = 0; + +protected: + virtual ~ModuleTurbulenceFS() {} +}; + +#if !defined(_USRDLL) +/** + \brief If this module is distributed as a static library, the user must call this + function before calling ApexSDK::createModule("Turbulence") + */ +void instantiateModuleTurbulenceFS(); +#endif + +} +} // end namespace nvidia + +#endif // MODULE_TURBULENCE_FS_H diff --git a/APEX_1.4/include/turbulencefs/SubstanceSourceActor.h b/APEX_1.4/include/turbulencefs/SubstanceSourceActor.h new file mode 100644 index 00000000..d70717fb --- /dev/null +++ b/APEX_1.4/include/turbulencefs/SubstanceSourceActor.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef SUBSTANCE_SOURCE_ACTOR_H +#define SUBSTANCE_SOURCE_ACTOR_H + +#include "Apex.h" +#include "Shape.h" + +namespace nvidia +{ +namespace apex +{ + +class SubstanceSourceAsset; + + +/** + \brief Turbulence ScalarSource Actor class + */ +class SubstanceSourceActor : public Actor +{ +protected: + virtual ~SubstanceSourceActor() {} + +public: + ///Returns the asset the instance has been created from. + virtual SubstanceSourceAsset* getSubstanceSourceAsset() const = 0; + + /** + \brief enable whether or not to use density in the simulation (enabling density reduces performance). + + If you are enabling density then you also need to add substance sources (without substance sources you will see no effect of density on the simulation, except a drop in performance) + */ + virtual void setEnabled(bool enable) = 0; + + ///Returns true if substance source enabled + virtual bool isEnabled() const = 0; + + ///intersect the collision shape against a given AABB + virtual bool intersectAgainstAABB(PxBounds3) = 0; + + ///Returns pointer to Shape of substance source + virtual Shape* getShape() const = 0; + + ///If it is a box, cast to box class, return NULL otherwise + virtual BoxShape* getBoxShape() = 0; + + ///If it is a sphere, cast to sphere class, return NULL otherwise + virtual SphereShape* getSphereShape() = 0; + + ///Return average value of density + virtual float getAverageDensity() const = 0; + + ///Return STD value of density + virtual float getStdDensity() const = 0; + + ///Set average and STD values for density + virtual void setDensity(float averageDensity, float stdDensity) = 0; + + ///Sets the uniform overall object scale + virtual void setCurrentScale(float scale) = 0; + + ///Retrieves the uniform overall object scale + virtual float getCurrentScale(void) const = 0; + + virtual void release() = 0; +}; + + +} +} // end namespace nvidia + +#endif diff --git a/APEX_1.4/include/turbulencefs/SubstanceSourceAsset.h b/APEX_1.4/include/turbulencefs/SubstanceSourceAsset.h new file mode 100644 index 00000000..e3deeba7 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/SubstanceSourceAsset.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef SUBSTANCE_SOURCE_ASSET_H +#define SUBSTANCE_SOURCE_ASSET_H + +#include "Apex.h" +#include "CustomBufferIterator.h" + +#define SUBSTANCE_SOURCE_AUTHORING_TYPE_NAME "SubstanceSourceAsset" + +namespace nvidia +{ +namespace apex +{ + +class TurbulenceFSActorParams; +class TurbulenceFSActor; +class TurbulenceFSPreview; + +/** + \brief Turbulence FieldSampler Asset class + */ +class SubstanceSourceAsset : public Asset +{ +protected: + virtual ~SubstanceSourceAsset() {} +}; + + +/** + \brief Turbulence FieldSampler Asset Authoring class + */ +class SubstanceSourceAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~SubstanceSourceAssetAuthoring() {} +}; + + +} +} // end namespace nvidia + +#endif // SUBSTANCE_SOURCE_ASSET_H diff --git a/APEX_1.4/include/turbulencefs/TurbulenceFSActor.h b/APEX_1.4/include/turbulencefs/TurbulenceFSActor.h new file mode 100644 index 00000000..171d239d --- /dev/null +++ b/APEX_1.4/include/turbulencefs/TurbulenceFSActor.h @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef TURBULENCE_FSACTOR_H +#define TURBULENCE_FSACTOR_H + +#include "Apex.h" +#include "Shape.h" + +namespace nvidia +{ +namespace apex +{ + +class TurbulenceFSAsset; +class TurbulenceRenderable; + +/** + \brief Turbulence FieldSampler Actor class + */ +class TurbulenceFSActor : public Actor, public Renderable +{ +protected: + virtual ~TurbulenceFSActor() {} + +public: + + ///Returns the asset the instance has been created from. + virtual TurbulenceFSAsset* getTurbulenceFSAsset() const = 0; + + ///enable/disable the fluid simulation + virtual void setEnabled(bool enable) = 0; + + /** + \brief set the pose of the grid - this includes only the position and rotation. + + the position is that of the center of the grid, as is determined as (pose.column3.x, pose.column3.y, pose.column3.z)<BR> + the rotation is the rotation of the object that the grid is centered on <BR> + (the grid does not rotate, but we use this pose for rotating the collision obstacle, the jets and imparting angular momentum) + */ + virtual void setPose(PxMat44 pose) = 0; + + /** + \brief get the pose of the grid - this includes only the position and rotation. + + the position is that of the center of the grid, as is determined as (pose.column3.x, pose.column3.y, pose.column3.z)<BR> + the rotation is the rotation of the object that the grid is centered on <BR> + (the grid does not rotate, but we use this pose for rotating the collision obstacle, the jets and imparting angular momentum) + */ + virtual PxMat44 getPose() const = 0; + + ///get the grid bounding box min point + virtual PxVec3 getGridBoundingBoxMin() = 0; + ///get the grid bounding box max point + virtual PxVec3 getGridBoundingBoxMax() = 0; + + ///get the grid size vector + virtual PxVec3 getGridSize() = 0; + + ///get the grid dimensions + virtual void getGridDimensions(uint32_t &gridX,uint32_t &gridY,uint32_t &gridZ) = 0; + + ///set the grid dimensions + virtual void setGridDimensions(const uint32_t &gridX, const uint32_t &gridY, const uint32_t &gridZ) = 0; + + /** + \brief force the current updates per frame to a particular value. + + Range is 0-1:<BR> + 1.0f is maximum simulation quality<BR> + 0.0f is minimum simulation quality + */ + virtual void setUpdatesPerFrame(float upd) = 0; + ///get the current value of the updates per frame + virtual float getUpdatesPerFrame() const = 0; + + /** + \brief methods to get the velocity field sampled at grid centers. + + call setSampleVelocityFieldEnabled(true) to enable the sampling and call getVelocityField to get back the sampled results + */ + virtual void getVelocityField(void** x, void** y, void** z, uint32_t& sizeX, uint32_t& sizeY, uint32_t& sizeZ) = 0; + + ///enable/disable sample velocity field + virtual void setSampleVelocityFieldEnabled(bool enabled) = 0; + + ///set a multiplier and a clamp on the total angular velocity induced in the system by the internal collision obstacle or by external collision objects + virtual void setAngularVelocityMultiplierAndClamp(float angularVelocityMultiplier, float angularVelocityClamp) = 0; + + ///set a multiplier and a clamp on the total linear velocity induced in the system by a collision obstacle + virtual void setLinearVelocityMultiplierAndClamp(float linearVelocityMultiplier, float linearVelocityClamp) = 0; + + ///set velocity field fade. All cells in the field multiplies by (1 - fade) on each frame + virtual void setVelocityFieldFade(float fade) = 0; + + ///set fluid viscosity (diffusion) for velocity + virtual void setFluidViscosity(float viscosity) = 0; + + ///set time of velocity field cleaning process [sec] + virtual void setVelocityFieldCleaningTime(float time) = 0; + + ///set time without activity before velocity field cleaning process starts [sec]. + virtual void setVelocityFieldCleaningDelay(float time) = 0; + + /** + set parameter which correspond to 'a' in erf(a*(cleaning_timer/velocityFieldCleaningTime)). + for full cleaning it should be greater then 2. If you want just decrease velocity magitude use smaller value + */ + virtual void setVelocityFieldCleaningIntensity(float a) = 0; + + /** + \brief enable whether or not to use heat in the simulation (enabling heat reduces performance).<BR> + \note If you are enabling heat then you also need to add temperature sources (without temperature sources you will see no effect of heat on the simulation, except a drop in performance) + */ + virtual void setUseHeat(bool enable) = 0; + + ///set heat specific parameters for the simulation + virtual void setHeatBasedParameters(float forceMultiplier, float ambientTemperature, PxVec3 heatForceDirection, float thermalConductivity) = 0; + + /** + \brief enable whether or not to use density in the simulation (enabling density reduces performance).<BR> + \note If you are enabling density then you also need to add substance sources (without substance sources you will see no effect of density on the simulation, except a drop in performance) + */ + virtual void setUseDensity(bool enable) = 0; + + ///Returns true if turbulence actor is in density mode. + virtual bool getUseDensity(void) const = 0; + + ///set density specific parameters for the simulation + virtual void setDensityBasedParameters(float diffusionCoef, float densityFieldFade) = 0; + + ///get the density grid dimensions + virtual void getDensityGridDimensions(uint32_t &gridX,uint32_t &gridY,uint32_t &gridZ) = 0; + + /** + \brief allows external actors like wind or explosion to add a single directional velocity to the grid.<BR> + \note if multiple calls to this function are made only the last call is honored (i.e. the velocities are not accumulated) + */ + virtual void setExternalVelocity(PxVec3 vel) = 0; + + ///set a multiplier for the field velocity + virtual void setFieldVelocityMultiplier(float value) = 0; + + ///set a weight for the field velocity + virtual void setFieldVelocityWeight(float value) = 0; + + ///set noise parameters + virtual void setNoiseParameters(float noiseStrength, PxVec3 noiseSpacePeriod, float noiseTimePeriod, uint32_t noiseOctaves) = 0; + + ///set density texture range + virtual void setDensityTextureRange(float minValue, float maxValue) = 0; + + ///Returns the optional volume render material name specified for this turbulence actor. + virtual const char *getVolumeRenderMaterialName(void) const = 0; + + ///Sets the uniform overall object scale + virtual void setCurrentScale(float scale) = 0; + + ///Retrieves the uniform overall object scale + virtual float getCurrentScale(void) const = 0; + + ///Returns true if turbulence actor is in flame mode. + virtual bool getUseFlame(void) const = 0; + + ///Returns flame grid dimensions. + virtual void getFlameGridDimensions(uint32_t &gridX, uint32_t &gridY, uint32_t &gridZ) const = 0; + + /** + \brief Acquire a pointer to the Turbulence renderable proxy and increment its reference count. + + The TurbulenceRenderable will only be deleted when its reference count is zero. + Calls to TurbulenceRenderable::release decrement the reference count, as does a call to TurbulenceFSActor::release(). + */ + virtual TurbulenceRenderable* acquireRenderableReference() = 0; + +}; + +} +} // end namespace nvidia + +#endif // TURBULENCE_FSACTOR_H diff --git a/APEX_1.4/include/turbulencefs/TurbulenceFSAsset.h b/APEX_1.4/include/turbulencefs/TurbulenceFSAsset.h new file mode 100644 index 00000000..d591fbd4 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/TurbulenceFSAsset.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef TURBULENCE_FSASSET_H +#define TURBULENCE_FSASSET_H + +#include "Apex.h" +#include "CustomBufferIterator.h" + +#define TURBULENCE_FS_AUTHORING_TYPE_NAME "TurbulenceFSAsset" + +namespace nvidia +{ +namespace apex +{ + +class TurbulenceFSActorParams; +class TurbulenceFSActor; +class TurbulenceFSPreview; + +/** + \brief Turbulence FieldSampler Asset class + */ +class TurbulenceFSAsset : public Asset +{ +protected: + virtual ~TurbulenceFSAsset() {} + +}; + +/** + \brief Turbulence FieldSampler Asset Authoring class + */ +class TurbulenceFSAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~TurbulenceFSAssetAuthoring() {} + +}; + +} +} // end namespace nvidia + +#endif // TURBULENCE_FSASSET_H diff --git a/APEX_1.4/include/turbulencefs/TurbulenceFSPreview.h b/APEX_1.4/include/turbulencefs/TurbulenceFSPreview.h new file mode 100644 index 00000000..9bc0c7a6 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/TurbulenceFSPreview.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef TURBULENCE_FSPREVIEW_H +#define TURBULENCE_FSPREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class RenderDebugInterface; + +/** + \brief The APEX_TURBO namespace contains the defines for setting the preview detail levels. + + TURBO_DRAW_NOTHING - draw nothing<BR> + TURBO_DRAW_ICON - draw the APEX TurbulenceFS Icon<BR> + TURBO_DRAW_BOX - draw the box<BR> + TURBO_DRAW_GRIDS - draw the top and bottom grids of the box<BR> + TURBO_DRAW_ASSET_INFO - draw the asset info in the screen space<BR> + TURBO_DRAW_FULL_DETAIL - draw all components of the preview<BR> +*/ +namespace APEX_TURBO +{ +/** + \def TURBO_DRAW_NOTHING + Draw no preview items. +*/ +static const uint32_t TURBO_DRAW_NOTHING = 0x00; +/** + \def TURBO_DRAW_ICON + Draw the icon. +*/ +static const uint32_t TURBO_DRAW_ICON = 0x01; +/** + \def TURBO_DRAW_BOX + Draw the box. The top of the box should be above ground and the bottom should be below ground. +*/ +static const uint32_t TURBO_DRAW_BOX = 0x02; +/** + \def TURBO_DRAW_GRIDS + Draw the box grids. These help to see if the entire top of the box is above ground and the + bottom of the box is below ground. +*/ +static const uint32_t TURBO_DRAW_GRIDS = 0x04; +/** + \def TURBO_DRAW_ASSET_INFO + Draw the Asset Info in Screen Space. This displays the various asset members that are relevant to the current asset. + parameters that are not relevant because they are disabled are not displayed. +*/ +static const uint32_t TURBO_DRAW_ASSET_INFO = 0x20; +/** + \def TURBO_DRAW_FULL_DETAIL + Draw all of the preview rendering items. +*/ +static const uint32_t TURBO_DRAW_FULL_DETAIL = (TURBO_DRAW_ICON + TURBO_DRAW_BOX + TURBO_DRAW_GRIDS + TURBO_DRAW_ASSET_INFO); +} + +/** +\brief This class provides the asset preview for APEX TurbulenceFS Assets. The class provides multiple levels of prevew +detail that can be selected individually. +*/ +class TurbulenceFSPreview : public AssetPreview +{ +public: + /** + \brief Set the half length dimensions of the actor thus resizing the box. + */ + virtual void setHalfLengthDimensions(PxVec3 halfLengthDimensions) = 0; + /** + \brief Set number of grid cells in the box. + */ + virtual void setNumGrids(PxVec3 numGrids) = 0; + /** + \brief Set the scale of the icon. + + The unscaled icon has is 1.0x1.0 game units.<BR> + By default the scale of the icon is 1.0. (unscaled)<BR> + */ + virtual void setIconScale(float scale) = 0; + /** + \brief Set the detail level of the preview rendering by selecting which features to enable. + + Any, all, or none of the following masks may be added together to select what should be drawn.<BR> + The defines for the individual items are:<br> + TURBO_DRAW_NOTHING - draw nothing<BR> + TURBO_DRAW_ICON - draw the APEX TurbulenceFS Icon<BR> + TURBO_DRAW_BOX - draw the box<BR> + TURBO_DRAW_COLLISION_IMPLICIT - draw the collision implicit<BR> + TURBO_DRAW_GRIDS - draw the top and bottom grids of the box<BR> + TURBO_DRAW_ASSET_INFO - draw the turbulencefs asset info in the screen space<BR> + TURBO_DRAW_FULL_DETAIL - draw all components of the turbulencefs preview<BR> + All items may be drawn using the macro DRAW_FULL_DETAIL. + */ + virtual void setDetailLevel(uint32_t detail) = 0; +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // TURBULENCE_FSPREVIEW_H diff --git a/APEX_1.4/include/turbulencefs/TurbulenceRenderCallback.h b/APEX_1.4/include/turbulencefs/TurbulenceRenderCallback.h new file mode 100644 index 00000000..e71e0100 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/TurbulenceRenderCallback.h @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef TURBULENCE_RENDER_CALLBACK_H +#define TURBULENCE_RENDER_CALLBACK_H + +#include "foundation/Px.h" +#include "UserRenderCallback.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +class TurbulenceRenderable; + +/** +\brief Velocity format for Turbulence rendering +*/ +struct TurbulenceVelocityFormat +{ + /** + \brief Enum of velocity format for Turbulence rendering + */ + enum Enum + { + DEFAULT = 0, + HALF4 = RenderDataFormat::HALF4, + FLOAT4 = RenderDataFormat::FLOAT4, + }; +}; + +/** +\brief Density format for Turbulence rendering +*/ +struct TurbulenceDensityFormat +{ + /** + \brief Enum of density format for Turbulence rendering + */ + enum Enum + { + DEFAULT = 0, + UBYTE1 = RenderDataFormat::UBYTE1, + HALF1 = RenderDataFormat::HALF1, + FLOAT1 = RenderDataFormat::FLOAT1, + }; +}; + +/** +\brief Flame format for Turbulence rendering +*/ +struct TurbulenceFlameFormat +{ + /** + \brief Enum of flame format for Turbulence rendering + */ + enum Enum + { + DEFAULT = 0, + HALF4 = RenderDataFormat::HALF4, + FLOAT4 = RenderDataFormat::FLOAT4, + }; +}; + +/** +\brief Render layout for Turbulence rendering +*/ +struct TurbulenceRenderLayout +{ + TurbulenceRenderLayout() + { + setDefaults(); + } + + ///set default formats + void setDefaults() + { + velocityFormat = TurbulenceVelocityFormat::DEFAULT; + densityFormat = TurbulenceDensityFormat::DEFAULT; + flameFormat = TurbulenceFlameFormat::DEFAULT; + } + + ///Velocity format + TurbulenceVelocityFormat::Enum velocityFormat; + + ///Density format + TurbulenceDensityFormat::Enum densityFormat; + + ///Flame format + TurbulenceFlameFormat::Enum flameFormat; +}; + +/** +\brief User defined callback for Turbulence rendering +*/ +class TurbulenceRenderCallback : public UserRenderCallback +{ +public: + ///Called just after a new Turbulence renderable was created + virtual void onCreatedTurbulenceRenderable(TurbulenceRenderable& ) {} + + ///Called just after an Turbulence renderable was updated + virtual void onUpdatedTurbulenceRenderable(TurbulenceRenderable& ) {} + + ///Called just before an Turbulence renderable is going to be released + virtual void onReleasingTurbulenceRenderable(TurbulenceRenderable& ) {} + + ///Returns render layout + virtual bool getTurbulenceRenderLayout(TurbulenceRenderLayout& renderLayout, uint32_t sizeX, uint32_t sizeY, uint32_t sizeZ, uint32_t densitySizeMultiplier, uint32_t flameSizeMultiplier) + { + PX_UNUSED(renderLayout); + PX_UNUSED(sizeX); + PX_UNUSED(sizeY); + PX_UNUSED(sizeZ); + PX_UNUSED(densitySizeMultiplier); + PX_UNUSED(flameSizeMultiplier); + return false; + } +}; + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // TURBULENCE_RENDER_CALLBACK_H diff --git a/APEX_1.4/include/turbulencefs/TurbulenceRenderable.h b/APEX_1.4/include/turbulencefs/TurbulenceRenderable.h new file mode 100644 index 00000000..462a6d49 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/TurbulenceRenderable.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#ifndef TURBULENCE_RENDERABLE_H +#define TURBULENCE_RENDERABLE_H + +#include "foundation/Px.h" +#include "ApexInterface.h" +#include "Renderable.h" +#include "TurbulenceRenderCallback.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** + \brief Render surface field type + */ +struct TurbulenceFieldType +{ + /** + \brief Enum of render surface field types + */ + enum Enum + { + VELOCITY = 0, + DENSITY, + FLAME, + + MAX_COUNT + }; +}; + +/** + \brief TurbulenceRenderData stores render data for one Turbulence Renderable. + */ +struct TurbulenceRenderData +{ + ///UserRenderSurfaceDesc array for all field types + UserRenderSurfaceDesc fieldSurfaceDescs[TurbulenceFieldType::MAX_COUNT]; + + ///UserRenderSurface array for all field types + UserRenderSurface* fieldSurfaces[TurbulenceFieldType::MAX_COUNT]; +}; + +/** + \brief The Turbulence renderable represents a unit of rendering. + + It contains complete information to render one Turbulence Actor. +*/ +class TurbulenceRenderable : public ApexInterface +{ +public: + ///Return render data. + virtual const TurbulenceRenderData* getRenderData() const = 0; + + ///Return AABB of this renderable. + virtual const physx::PxBounds3& getBounds() const = 0; + +protected: + virtual ~TurbulenceRenderable() {} + +}; + +PX_POP_PACK + +} +} // end namespace nvidia + +#endif // TURBULENCE_RENDERABLE_H diff --git a/APEX_1.4/include/turbulencefs/VelocitySourceActor.h b/APEX_1.4/include/turbulencefs/VelocitySourceActor.h new file mode 100644 index 00000000..79d3f151 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/VelocitySourceActor.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef VELOCITY_SOURCE_ACTOR_H +#define VELOCITY_SOURCE_ACTOR_H + +#include "Apex.h" +#include "Shape.h" + +namespace nvidia +{ +namespace apex +{ + +class VelocitySourceAsset; + + +/** + \brief Turbulence VelocitySource Actor class + */ +class VelocitySourceActor : public Actor +{ +protected: + virtual ~VelocitySourceActor() {} + +public: + ///Returns the asset the instance has been created from. + virtual VelocitySourceAsset* getVelocitySourceAsset() const = 0; + + ///enable/disable the velocity source + virtual void setEnabled(bool enable) = 0; + + ///Returns true if velocity source enabled + virtual bool isEnabled() const = 0; + + ///intersect the collision shape against a given AABB + virtual bool intersectAgainstAABB(PxBounds3) = 0; + + ///Returns pointer to Shape of velocity source + virtual Shape* getShape() const = 0; + + ///If it is a box, cast to box class, return NULL otherwise + virtual BoxShape* getBoxShape() = 0; + + ///If it is a sphere, cast to sphere class, return NULL otherwise + virtual SphereShape* getSphereShape() = 0; + + ///Return average value of velocity + virtual float getAverageVelocity() const = 0; + + ///Return STD value of velocity + virtual float getStdVelocity() const = 0; + + ///get the pose of a velocity source shape + virtual PxMat44 getPose() const = 0; + + ///Set average and STD values for velocity + virtual void setVelocity(float averageVelocity, float stdVelocity) = 0; + + ///set the pose of a velocity source shape + virtual void setPose(PxMat44 pose) = 0; + + ///Sets the uniform overall object scale + virtual void setCurrentScale(float scale) = 0; + + ///Retrieves the uniform overall object scale + virtual float getCurrentScale(void) const = 0; + + virtual void release() = 0; +}; + + +} +} // end namespace nvidia + +#endif diff --git a/APEX_1.4/include/turbulencefs/VelocitySourceAsset.h b/APEX_1.4/include/turbulencefs/VelocitySourceAsset.h new file mode 100644 index 00000000..e30185c1 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/VelocitySourceAsset.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef VELOCITY_SOURCE_ASSET_H +#define VELOCITY_SOURCE_ASSET_H + +#include "Apex.h" +#include "CustomBufferIterator.h" + +#define VELOCITY_SOURCE_AUTHORING_TYPE_NAME "VelocitySourceAsset" + +namespace nvidia +{ +namespace apex +{ + +class TurbulenceFSActorParams; +class TurbulenceFSActor; +class TurbulenceFSPreview; + +/** + \brief Turbulence FieldSampler Asset class + */ +class VelocitySourceAsset : public Asset +{ +protected: + virtual ~VelocitySourceAsset() {} +}; + + +/** + \brief Turbulence FieldSampler Asset Authoring class + */ +class VelocitySourceAssetAuthoring : public AssetAuthoring +{ +protected: + virtual ~VelocitySourceAssetAuthoring() {} +}; + + +} +} // end namespace nvidia + +#endif // VELOCITY_SOURCE_ASSET_H diff --git a/APEX_1.4/include/turbulencefs/VelocitySourcePreview.h b/APEX_1.4/include/turbulencefs/VelocitySourcePreview.h new file mode 100644 index 00000000..dfd1ffe4 --- /dev/null +++ b/APEX_1.4/include/turbulencefs/VelocitySourcePreview.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + +#ifndef VELOCITY_SOURCE_PREVIEW_H +#define VELOCITY_SOURCE_PREVIEW_H + +#include "Apex.h" +#include "AssetPreview.h" + +namespace nvidia +{ +namespace apex +{ + +PX_PUSH_PACK_DEFAULT + +/** +\brief This class provides the asset preview for APEX VelocitySource Assets. +*/ +class VelocitySourcePreview : public AssetPreview +{ +public: + public: + ///Draws the emitter + virtual void drawVelocitySourcePreview() = 0; + ///Sets the scaling factor of the renderable + virtual void setScale(float scale) = 0; + +protected: + VelocitySourcePreview() {} +}; + + +PX_POP_PACK + +} +} // namespace nvidia + +#endif // VELOCITY_SOURCE_PREVIEW_H
\ No newline at end of file |