Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#include "Headers/PhysX.h"
#include "Headers/PhysXSceneInterface.h"
#include "Core/Headers/Console.h"
#include "Utility/Headers/Localization.h"
#include "Core/Headers/Application.h"
#include "Core/Math/Headers/Transform.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Geometry/Shapes/Headers/Object3D.h"
#include "Geometry/Shapes/Headers/Mesh.h"
#include "Geometry/Shapes/Headers/SubMesh.h"
#include "Platform/Video/Buffers/VertexBuffer/Headers/VertexBuffer.h"

#include <cstddef>

namespace Divide {

physx::PxDefaultAllocator PhysX::_gDefaultAllocatorCallback;
physx::PxDefaultErrorCallback PhysX::_gDefaultErrorCallback;
hashMapImpl<stringImpl, physx::PxTriangleMesh*> PhysX::_gMeshCache;

physx::PxProfileZone* PhysX::getOrCreateProfileZone(
    physx::PxFoundation& inFoundation) {
#ifdef PHYSX_PROFILE_SDK
    if (_profileZone == nullptr) {
        _profileZone =
            &physx::PxProfileZone::createProfileZone(
                &inFoundation, "SampleProfileZone", gProfileNameProvider);
    }
#endif
    return _profileZone;
}

PhysX::PhysX()
    : _gPhysicsSDK(nullptr),
      _foundation(nullptr),
      _zoneManager(nullptr),
      _cooking(nullptr),
      _profileZone(nullptr),
      _pvdConnection(nullptr),
      _targetScene(nullptr),
      _accumulator(0.0f),
      _timeStepFactor(0),
      _timeStep(0.0f),
      _simulationSpeed(1.0f)
{
}

PhysX::~PhysX()
{
    assert(_gPhysicsSDK == nullptr);
}

ErrorCode PhysX::initPhysicsAPI(U8 targetFrameRate, F32 simSpeed) {
    Console::printfn(Locale::get(_ID("START_PHYSX_API")));

    _simulationSpeed = simSpeed;
    // create foundation object with default error and allocator callbacks.
    _foundation = PxCreateFoundation(PX_PHYSICS_VERSION,
                                     _gDefaultAllocatorCallback,
                                     _gDefaultErrorCallback);
    assert(_foundation != nullptr);

    bool recordMemoryAllocations = false;

    if (Config::Build::IS_DEBUG_BUILD) {
        recordMemoryAllocations = true;
        _zoneManager = 
            &physx::PxProfileZoneManager::createProfileZoneManager(_foundation);
        assert(_zoneManager != nullptr);
    }

    _gPhysicsSDK =
        PxCreatePhysics(PX_PHYSICS_VERSION, 
                        *_foundation, physx::PxTolerancesScale(),
                        recordMemoryAllocations, _zoneManager);

    if (_gPhysicsSDK == nullptr) {
        Console::errorfn(Locale::get(_ID("ERROR_START_PHYSX_API")));
        return ErrorCode::PHYSX_INIT_ERROR;
    }

    if (Config::Build::IS_DEBUG_BUILD) {
        if (getOrCreateProfileZone(*_foundation)) {
            _zoneManager->addProfileZone(*_profileZone);
        }

        _pvdConnection = _gPhysicsSDK->getPvdConnectionManager();
        _gPhysicsSDK->getPvdConnectionManager()->addHandler(*this);

        if (_pvdConnection != nullptr) {
            if (physx::PxVisualDebuggerExt::createConnection(_pvdConnection,
                                                             "localhost",
                                                             5425, 10000) 
                                                             != nullptr) {
                Console::d_printfn(Locale::get(_ID("CONNECT_PVD_OK")));
            }
        }
    }

    if (!PxInitExtensions(*_gPhysicsSDK)) {
        Console::errorfn(Locale::get(_ID("ERROR_EXTENSION_PHYSX_API")));
        return ErrorCode::PHYSX_EXTENSION_ERROR;
    }

    if (!_cooking) {
        physx::PxCookingParams* cookparams =
            MemoryManager_NEW physx::PxCookingParams(physx::PxTolerancesScale());
        cookparams->targetPlatform = physx::PxPlatform::ePC;
        _cooking =
            PxCreateCooking(PX_PHYSICS_VERSION, *_foundation, *cookparams);
        MemoryManager::DELETE(cookparams);
    }

    updateTimeStep(targetFrameRate, _simulationSpeed);
    Console::printfn(Locale::get(_ID("START_PHYSX_API_OK")));

    return ErrorCode::NO_ERR;
}

bool PhysX::closePhysicsAPI() {
    if (!_gPhysicsSDK) {
        return false;
    }

    Console::printfn(Locale::get(_ID("STOP_PHYSX_API")));

    DIVIDE_ASSERT(_targetScene == nullptr,
                  "PhysX error: target scene not destroyed before calling "
                  "closePhysicsAPI."
                  "Call \"setPhysicsScene( nullptr )\" first");

    if (_cooking) {
        _cooking->release();
    }
    PxCloseExtensions();
    if (_zoneManager) {
        //_zoneManager->release();
    }
    _gPhysicsSDK->release();
    _foundation->release();
    _gPhysicsSDK = nullptr;
    _foundation = nullptr;

    return true;
}

inline void PhysX::updateTimeStep(U8 timeStepFactor, F32 simSpeed) {
    CLAMP<U8>(timeStepFactor, 1, timeStepFactor);
    _timeStepFactor = timeStepFactor;
    _timeStep = 1.0f / _timeStepFactor;
    _timeStep *= simSpeed;
}

/// Process results
void PhysX::process(const U64 deltaTime) {
    if (_targetScene && _timeStep > 0.0f) {
        _accumulator +=
            Time::MicrosecondsToMilliseconds<physx::PxReal>(deltaTime);

        if (_accumulator < _timeStep) {
            return;
        }

        _accumulator -= _timeStep;
        _targetScene->process(Time::SecondsToMicroseconds(_timeStep));
    }
}

/// Update actors
void PhysX::update(const U64 deltaTime) {
    if (_targetScene) {
        _targetScene->update(deltaTime);
    }
}

void PhysX::idle() {
    if (_targetScene) {
        _targetScene->idle();
    }
}

PhysicsSceneInterface* PhysX::NewSceneInterface(Scene& scene) {
    return MemoryManager_NEW PhysXSceneInterface(scene);
}

void PhysX::setPhysicsScene(PhysicsSceneInterface* const targetScene) {
    if (_targetScene) {
        if (targetScene) {
            if (_targetScene->getGUID() == targetScene->getGUID()) {
                return;
            }
        }
    }
    _targetScene = targetScene;
}

/*void PhysX::createActor(SceneGraphNode& node, const stringImpl& sceneName,
                        PhysicsActorMask mask, PhysicsCollisionGroup group) {
    assert(_targetScene != nullptr);

    Object3D* sNode = node.getNode<Object3D>();

    // Load cached version from file first
    stringImpl nodeName("XML/Scenes/" + sceneName + "/collisionMeshes/node_[_" + sNode->getName() + "_]");
    nodeName.append(".cm");

    hashMapImpl<stringImpl, physx::PxTriangleMesh*>::iterator it;
    it = _gMeshCache.find(nodeName);

    // -1 = not available
    //  0 = loaded from RAM cache
    //  1 = loaded from file cache
    I8 loadState = -1;
    if (it != std::cend(_gMeshCache)) {
        loadState = 0;
    } else {
        if (fileExists(nodeName) {
            loadState = 1;
        }
    }

    if (group == PhysicsCollisionGroup::GROUP_NON_COLLIDABLE) {
        // return true;
    }

    if (loadState == -1) {
        sNode->computeTriangleList();
        const vectorImpl<vec3<U32> >& triangles = sNode->getTriangles();

        if (sNode->getTriangles().empty()) {
            return;
        }

        VertexBuffer* nodeVB = sNode->getGeometryVB();
        if (sNode->getObjectType() == Object3D::ObjectType::SUBMESH) {
            SceneGraphNode_ptr grandParent = node.getParent().lock();
            nodeVB = grandParent->getNode<Object3D>()->getGeometryVB();
        }

        physx::PxDefaultFileOutputStream stream(nodeName.c_str());

        physx::PxTriangleMeshDesc meshDesc;
        meshDesc.points.count = (physx::PxU32)nodeVB->getVertexCount();
        meshDesc.points.stride = offsetof(VertexBuffer::Vertex, _position);
        meshDesc.points.data = nodeVB->getVertices().data();
        meshDesc.triangles.count = (physx::PxU32)triangles.size();
        meshDesc.triangles.stride = 3 * sizeof(U32);
        meshDesc.triangles.data = triangles.data();
        if (!nodeVB->usesLargeIndices()) {
            // meshDesc.flags = PxMeshFlag::e16_BIT_INDICES;
        }

        if (!_cooking->cookTriangleMesh(meshDesc, stream)) {
            Console::errorfn(Locale::get(_ID("ERROR_COOK_TRIANGLE_MESH")));
            return;
        }
    } else if (loadState == 0) {
        Console::printfn(Locale::get(_ID("COLLISION_MESH_LOADED_FROM_RAM")), nodeName.c_str());
    } else if (loadState == 1) {
        Console::printfn(Locale::get(_ID("COLLISION_MESH_LOADED_FROM_FILE")), nodeName.c_str());
    }

    PhysXSceneInterface* targetScene =  dynamic_cast<PhysXSceneInterface*>(_targetScene);
    PhysicsComponent* nodePhysics = node.get<PhysicsComponent>();

    PhysXActor* tempActor = targetScene->getOrCreateRigidActor(node.getName());
    assert(tempActor != nullptr);
    tempActor->setParent(nodePhysics);

    if (!tempActor->_actor) {
        const vec3<F32>& position = nodePhysics->getPosition();
        const vec4<F32>& orientation = nodePhysics->getOrientation().asVec4();

        physx::PxTransform posePxTransform(
            physx::PxVec3(position.x, position.y, position.z),
            physx::PxQuat(orientation.x,
                          orientation.y,
                          orientation.z,
                          orientation.w).getConjugate());

        if (mask != PhysicsActorMask::MASK_RIGID_DYNAMIC) {
            tempActor->_actor =
                _gPhysicsSDK->createRigidStatic(posePxTransform);
        } else {
            tempActor->_actor =
                _gPhysicsSDK->createRigidDynamic(posePxTransform);
            tempActor->_isDynamic = true;
        }

        if (!tempActor->_actor) {
            MemoryManager::DELETE(tempActor);
            return;
        }

        tempActor->_type = physx::PxGeometryType::eTRIANGLEMESH;
        // If we got here, the new actor was just created (didn't exist
        // previously in the scene), so add it
        targetScene->addRigidActor(tempActor, false);
    }

    assert(tempActor->_actor);

    physx::PxTriangleMesh* triangleMesh = nullptr;
    if (loadState == 0) {
        triangleMesh = it->second;
    } else {
        physx::PxDefaultFileInputData inData(nodeName.c_str());
        triangleMesh = _gPhysicsSDK->createTriangleMesh(inData);
        hashAlg::insert(_gMeshCache, std::make_pair(nodeName, triangleMesh));
    }

    if (!triangleMesh) {
        Console::errorfn(Locale::get(_ID("ERROR_CREATE_TRIANGLE_MESH")));
        return;
    }

    const vec3<F32>& scale = tempActor->getParent()->getScale();
    STUBBED("PhysX implementation only uses one shape per actor for now! -Ionut")
    tempActor->_actor->createShape(physx::PxTriangleMeshGeometry(
                                       triangleMesh,
                                        physx::PxMeshScale(
                                            physx::PxVec3(scale.x, scale.y, scale.z),
                                            physx::PxQuat(physx::PxIdentity))),
                                   *_gPhysicsSDK->createMaterial(0.7f, 0.7f, 1.0f));

    return;
};
*/

PhysicsAsset* PhysX::createRigidActor(const SceneGraphNode& node)
{
    PhysicsComponent* pComp = node.get<PhysicsComponent>();
    assert(pComp != nullptr);

    PhysXActor* newActor = new PhysXActor(*pComp);

    // get node Geometry
    // create Shape from Geometry
    // create Actor
    // attach Shape to Actor
    // register actor

    return newActor;
}

};

Commits for Divide-Framework/trunk/Source Code/Physics/PhysX/PhysX.cpp

Diff revisions: vs.
Revision Author Commited Message
832 Diff Diff IonutCava picture IonutCava Thu 26 Jan, 2017 17:23:11 +0000

[IonutCava]
- More path related work
- Initial code to centralize file I/O (does not compile yet)

831 Diff Diff IonutCava picture IonutCava Wed 25 Jan, 2017 23:52:34 +0000

[IonutCava]
- More path related updates

830 Diff Diff IonutCava picture IonutCava Wed 25 Jan, 2017 17:29:44 +0000

[IonutCava]
- Add a new Platform element: File
— Move all predefined paths to FileManagement System
- Split MathHelper into MathHelper and StringHelper

828 Diff Diff IonutCava picture IonutCava Mon 23 Jan, 2017 17:19:22 +0000

[Ionut]
- XML loading/saving cleanup PART I

804 Diff Diff IonutCava picture IonutCava Thu 01 Dec, 2016 17:20:59 +0000

[IonutCava]
- Singleton elimination update Part I: get it to compile
— The following classes are no longer Singletons: GFXDevice, GL_API, DX_API, SFXWrapper, FmodWrapper, SDLWrapper, ALWrapper, PXDevice, InputInterface, RenderPassManager, SceneManager and ResourceManager;
— Refactor system to a Context / Component based implementation (Pass relevant context to objects: e.g. GFXDevice object to Textures, GUI to GUIElements, etc)
— Make devices and managers components of the kernel
— Allow multiple Resource caches to co-exist. This may prove useful for later when a more fragmented memory model is need (per frame / per scene / global caches / etc)

  • next steps: part II – cleanup/refactor new code, part III – optimise code, part IV – remove remaining Singletons (e.g. Application, ParamHandler, FrameListenerManager, Recast, PostFX and DebugInterface)
760 Diff Diff IonutCava picture IonutCava Tue 09 Aug, 2016 16:30:12 +0000

[IonutCava]
- Complete rewrite of RenderPass system:
— Allow every rendering pass (reflection, environment, etc) to use the same rendering system: occlusion culling, light culling, etc
— Define render passes by a param based token similar to modern API systems (DX12/Vulkan)
— W.I.P.: Depth rendering slightly wrong; Environment Mapping ,reflection and refraction rendering currently disabled
- Add compile time variables for DEBUG/PROFILE/RELEASE builds to validate all code for every build

753 Diff Diff IonutCava picture IonutCava Thu 28 Jul, 2016 14:26:48 +0000

[IonutCava]
- Very small cleanup and renaming changes
- Updated PhysX build as well

728 Diff Diff IonutCava picture IonutCava Wed 15 Jun, 2016 16:04:33 +0000

[IonutCava]
- Updates and fixes to shadow mapping.
- Fixed a race condition in console::output regarding redirection of events to the GUI
- Attempting to fix particle emitter:
— Rewrite GenericVertexData for easier debugging/processing
— Split attributes and buffers into separate classes
— Not finished / buggy / crashes
- Fixed an issue with scene switching regarding PhysicsSceneInterface. Caused race conditions related crashes
- Fixed an issue with scene save data loading. Moved Load system to main thread after loading finishes

713 Diff Diff IonutCava picture IonutCava Wed 25 May, 2016 15:43:38 +0000

[IonutCava]
- Removed all unique_ptr’s from the code with classic new/delete pairs. They were seriously not needed.
- Added the concept of SceneComponent to scene specific classes: aiManager, lightPool, sceneGraph, physicsInterface etc
— This allowed the removal of the global GET_ACTIVE_SCENEGRAPH call;

696 IonutCava picture IonutCava Mon 09 May, 2016 16:14:09 +0000

[IonutCava]
- More physics system preparation:
— Define specific px groups for nodes: static, kinematic, dynamic, ragdoll, etc