1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
|
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
// ****************************************************************************
// This snippet illustrates kinematic actor updates in a substepped simulation.
//
// It uses chained continuation tasks that call fetchResults and run simulation steps.
// The scene consists of a kinematic platform interacting with a dynamic
// sphere. The kinematic actor's target pose is updated before every substep.
// ****************************************************************************
#include <new>
#include "PxPhysicsAPI.h"
#include "../SnippetCommon/SnippetPrint.h"
#include "../SnippetCommon/SnippetPVD.h"
#include "../SnippetUtils/SnippetUtils.h"
using namespace physx;
using namespace SnippetUtils;
// The usual PhysX resources.
PxDefaultAllocator gAllocator;
PxDefaultErrorCallback gErrorCallback;
PxFoundation* gFoundation = NULL;
PxPhysics* gPhysics = NULL;
PxMaterial* gMaterial = NULL;
PxDefaultCpuDispatcher* gDispatcher = NULL;
PxScene* gScene = NULL;
PxRigidDynamic* gKinematic = NULL;
// A very simple substepping policy: just take 2 60Hz substeps per step.
static const PxReal SUBSTEP_LENGTH = 1.0f/60.0f;
static const PxU32 NUM_STEPS = 1000;
static const PxI32 NUM_SUBSTEPS = 2;
PxPvd* gPvd = NULL;
// Context for keeping track of the stepper state.
struct StepContext
{
class SubstepCompletionTask* taskPool;
Sync* completionSync;
PxI32 nbSubstepsFinished;
volatile PxI32 nbTasksDestroyed;
} gStepContext;
// Completion task for running a substep.
// The following sequencing is guaranteed:
// * the section of the run() method up to the removeReference() in startNextSubstep() will execute prior
// to the run() method of the task submitted by startNextSubstep()
// * the run() method of a task will run before its release() method
//
// Any work done by a task after releasing the next task (via removeReference()) could end up running in
// parallel with that task, if simulate() completes sufficiently quickly or there is a context switch. In order
// to prevent races, it is therefore recommended that a completion task do no work after releasing the next.
class SubstepCompletionTask : public PxLightCpuTask
{
public:
SubstepCompletionTask()
{
mTm = gScene->getTaskManager();
}
void run()
{
void startNextSubstep();
gScene->fetchResults(true);
if(++gStepContext.nbSubstepsFinished < NUM_SUBSTEPS)
startNextSubstep();
}
void release()
{
this->~SubstepCompletionTask();
// If we're done with all the substeps , synchronize with the main thread. In a real application
// we would most likely run dependent tasks instead.
// We can only signal completion once all substepping resources are cleaned up.
// Release() calls may run concurrently or out of order, so we use an atomic counter.
if(atomicIncrement(&gStepContext.nbTasksDestroyed) == NUM_SUBSTEPS)
syncSet(gStepContext.completionSync);
}
const char* getName() const { return "Substep Completion Task"; }
};
// Update the sim inputs and start the next PhysX substep.
void startNextSubstep()
{
// Compute new target pose for the kinematic at the end of the substep.
static PxReal sTotalSeconds = 0.0f;
sTotalSeconds += SUBSTEP_LENGTH;
const PxReal period = 4.0f;
const PxReal amplitude = 10.0f;
const PxReal angVel = PxTwoPi/period;
PxReal yPos = PxSin(angVel * sTotalSeconds) * amplitude;
gKinematic->setKinematicTarget(PxTransform(0.0f, yPos, 0.0f));
// Create a completion task and set its reference count to 1. This way we can safely submit it to simulate()
// and, even if we get context-switched and simulate() completes before we get back, the task's run()
// method will not execute until we're ready.
SubstepCompletionTask* nextCompletion = new (gStepContext.taskPool+gStepContext.nbSubstepsFinished) SubstepCompletionTask();
nextCompletion->addReference();
// Kick off the sim with the new completion task. Once this call returns, worker threads will update the PhysX
// state in parallel with the rest of this function.
gScene->simulate(SUBSTEP_LENGTH, nextCompletion);
// We can do things here that can run in parallel with the simulation, but must happen before the next task's
// run method executes. In this snippet, there's nothing to do...
// Finally, remove the reference that prevents the next completion task running.
nextCompletion->removeReference();
}
void runPhysics()
{
// Initialize the substepping context.
syncReset(gStepContext.completionSync);
gStepContext.nbSubstepsFinished = 0;
gStepContext.nbTasksDestroyed = 0;
// Start the first substep, then wait for the last one to finish.
startNextSubstep();
syncWait(gStepContext.completionSync);
}
void initPhysics()
{
gFoundation = PxCreateFoundation(PX_FOUNDATION_VERSION, gAllocator, gErrorCallback);
gPvd = PxCreatePvd(*gFoundation);
PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10);
gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL);
gPhysics = PxCreateBasePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd);
gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.2f);
PxSceneDesc desc(gPhysics->getTolerancesScale());
desc.filterShader = PxDefaultSimulationFilterShader;
desc.cpuDispatcher = gDispatcher = PxDefaultCpuDispatcherCreate(2);
desc.gravity = PxVec3(0.0f, -9.81f, 0.0f);
gScene = gPhysics->createScene(desc);
PxPvdSceneClient* pvdClient = gScene->getScenePvdClient();
if(pvdClient)
{
pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true);
pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true);
pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true);
}
gKinematic = PxCreateKinematic(*gPhysics, PxTransform(PxIdentity), PxBoxGeometry(5.0f, 1.0f, 5.0f), *gMaterial, 1.0f);
gScene->addActor(*gKinematic);
PxRigidDynamic* sphere = PxCreateDynamic(*gPhysics, PxTransform(0.0f, 5.0f, 0.0f), PxSphereGeometry(1.0f), *gMaterial, 1.0f);
gScene->addActor(*sphere);
}
void cleanupPhysics()
{
gDispatcher->release();
gPhysics->release();
PxPvdTransport* transport = gPvd->getTransport();
gPvd->release();
transport->release();
gFoundation->release();
}
int snippetMain(int, const char*const*)
{
initPhysics();
// Storage and synchronization for substepping.
gStepContext.taskPool = reinterpret_cast<SubstepCompletionTask*>(malloc(NUM_SUBSTEPS * sizeof(SubstepCompletionTask)));
gStepContext.completionSync = syncCreate();
for(PxU32 i=0; i<NUM_STEPS; i++)
runPhysics();
syncRelease(gStepContext.completionSync);
free(gStepContext.taskPool);
cleanupPhysics();
printf("SnippetStepper done.\n");
return 0;
}
|