Skip to content

Commit 01b5581

Browse files
committed
refactor SceneConfig
1 parent 3fcf354 commit 01b5581

File tree

10 files changed

+107
-75
lines changed

10 files changed

+107
-75
lines changed

include/sapien/physx/physx_default.h

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#pragma once
2+
#include "sapien/math/vec3.h"
23
#include <cstdint>
34
#include <memory>
45

@@ -10,6 +11,22 @@ namespace sapien {
1011
namespace physx {
1112
class PhysxMaterial;
1213

14+
struct PhysxSceneConfig {
15+
Vec3 gravity = {0, 0, -9.81}; // default gravity
16+
float bounceThreshold = 2.f; // relative velocity below this will not bounce
17+
float sleepThreshold = 0.005f; // put to sleep if (kinetic energy/(mass) falls below
18+
float contactOffset = 0.01f; // how close should contacts be generated
19+
uint32_t solverIterations = 10; // solver position iterations, helps reduce jittering
20+
uint32_t solverVelocityIterations = 1; // solver velocity iterations
21+
bool enablePCM = true; // Use persistent contact manifold solver for contact
22+
bool enableTGS = true; // use TGS solver
23+
bool enableCCD = false; // use continuous collision detection
24+
bool enableEnhancedDeterminism = false; // improve determinism
25+
bool enableFrictionEveryIteration =
26+
true; // better friction calculation, recommended for robotics
27+
uint32_t cpuWorkers = 0; // CPU workers, 0 for using main thread
28+
};
29+
1330
class PhysxDefault {
1431
public:
1532
static std::shared_ptr<PhysxMaterial> GetDefaultMaterial();
@@ -21,8 +38,13 @@ class PhysxDefault {
2138
uint32_t totalAggregatePairsCapacity);
2239
static ::physx::PxgDynamicsMemoryConfig const &getGpuMemoryConfig();
2340

24-
static void setCpuWorkers(uint32_t count);
25-
static uint32_t getCpuWorkers();
41+
static void setSceneConfig(Vec3 gravity, float bounceThreshold, float sleepThreshold,
42+
float contactOffset, uint32_t solverIterations,
43+
uint32_t solverVelocityIterations, bool enablePCM, bool enableTGS,
44+
bool enableCCD, bool enableEnhancedDeterminism,
45+
bool enableFrictionEveryIteration, uint32_t cpuWorkers);
46+
static void setSceneConfig(PhysxSceneConfig const &);
47+
static PhysxSceneConfig const &getSceneConfig();
2648

2749
// enable GPU simulation, may not be disabled
2850
static void EnableGPU();

include/sapien/physx/physx_system.h

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include "../array.h"
33
#include "../component.h"
44
#include "../system.h"
5+
#include "./physx_default.h"
56
#include "./physx_engine.h"
67
#include "mesh_manager.h"
78
#include "sapien/scene.h"
@@ -24,27 +25,6 @@ class PhysxRigidDynamicComponent;
2425
class PhysxRigidStaticComponent;
2526
class PhysxArticulationLinkComponent;
2627

27-
struct PhysxSceneConfig {
28-
Vec3 gravity = {0, 0, -9.81}; // default gravity
29-
float bounceThreshold = 2.f; // relative velocity below this will not bounce
30-
float sleepThreshold = 0.005f; // put to sleep if (kinetic energy/(mass) falls below
31-
float contactOffset = 0.01f; // how close should contacts be generated
32-
uint32_t solverIterations = 10; // solver position iterations, helps reduce jittering
33-
uint32_t solverVelocityIterations = 1; // solver velocity iterations
34-
bool enablePCM = true; // Use persistent contact manifold solver for contact
35-
bool enableTGS = true; // use TGS solver
36-
bool enableCCD = false; // use continuous collision detection
37-
bool enableEnhancedDeterminism = false; // improve determinism
38-
bool enableFrictionEveryIteration =
39-
true; // better friction calculation, recommended for robotics
40-
41-
template <class Archive> void serialize(Archive &ar) {
42-
ar(gravity, bounceThreshold, sleepThreshold, contactOffset, solverIterations,
43-
solverVelocityIterations, enablePCM, enableTGS, enableCCD, enableEnhancedDeterminism,
44-
enableFrictionEveryIteration);
45-
}
46-
};
47-
4828
class PhysxSystem : public System {
4929

5030
public:
@@ -85,7 +65,7 @@ class PhysxSystem : public System {
8565
int getSceneCollisionId() const { return mSceneCollisionId; }
8666

8767
protected:
88-
PhysxSystem(PhysxSceneConfig const &config);
68+
PhysxSystem();
8969

9070
PhysxSceneConfig mSceneConfig;
9171
std::shared_ptr<PhysxEngine> mEngine;
@@ -100,7 +80,7 @@ class PhysxSystem : public System {
10080

10181
class PhysxSystemCpu : public PhysxSystem {
10282
public:
103-
PhysxSystemCpu(PhysxSceneConfig const &config);
83+
PhysxSystemCpu();
10484

10585
void registerComponent(std::shared_ptr<PhysxRigidDynamicComponent> component) override;
10686
void registerComponent(std::shared_ptr<PhysxRigidStaticComponent> component) override;
@@ -137,7 +117,7 @@ class PhysxSystemCpu : public PhysxSystem {
137117

138118
class PhysxSystemGpu : public PhysxSystem {
139119
public:
140-
PhysxSystemGpu(PhysxSceneConfig const &config);
120+
PhysxSystemGpu();
141121

142122
void registerComponent(std::shared_ptr<PhysxRigidDynamicComponent> component) override;
143123
void registerComponent(std::shared_ptr<PhysxRigidStaticComponent> component) override;

python/py_package/__init__.pyi

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,5 +62,5 @@ def set_cuda_tensor_backend(backend: str) -> None:
6262
"""
6363
def set_log_level(level: str) -> None:
6464
pass
65-
__version__ = '3.0.0.dev20240110+e029ca37'
65+
__version__ = '3.0.0.dev20240110+3fcf354b'
6666
SceneConfig = sapien.pysapien.physx.PhysxSceneConfig

python/py_package/example/load_urdf.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,8 @@
44

55

66
def main(filename, package_dir):
7-
config = sapien.physx.PhysxSceneConfig()
8-
config.gravity = np.array([0, 0, 0])
9-
10-
scene = sapien.Scene(
11-
[sapien.physx.PhysxSystem(config), sapien.render.RenderSystem()]
12-
)
7+
sapien.physx.set_scene_config(gravity=[0, 0, 0])
8+
scene = sapien.Scene()
139
scene.set_timestep(1 / 125)
1410
scene.set_ambient_light([0.4, 0.4, 0.4])
1511
scene.add_directional_light([1, -1, -1], [0.5, 0.5, 0.5])

python/py_package/pysapien/physx/__init__.pyi

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,12 @@ __all__ = [
3636
"PhysxRigidStaticComponent",
3737
"PhysxSceneConfig",
3838
"PhysxSystem",
39-
"get_cpu_workers",
4039
"get_default_material",
40+
"get_scene_config",
4141
"is_gpu_enabled",
42-
"set_cpu_workers",
4342
"set_default_material",
44-
"set_gpu_memory_config"
43+
"set_gpu_memory_config",
44+
"set_scene_config"
4545
]
4646

4747

@@ -597,7 +597,7 @@ class PhysxContactPoint():
597597
"""
598598
pass
599599
class PhysxSystem(sapien.pysapien.System):
600-
def __init__(self, config: PhysxSceneConfig = SceneConfig()) -> None: ...
600+
def __init__(self) -> None: ...
601601
def get_articulation_link_components(self) -> list[PhysxArticulationLinkComponent]: ...
602602
def get_config(self) -> PhysxSceneConfig: ...
603603
def get_rigid_dynamic_components(self) -> list[PhysxRigidDynamicComponent]: ...
@@ -745,7 +745,7 @@ class PhysxGearComponent(PhysxJointComponent, PhysxBaseComponent, sapien.pysapie
745745
"""
746746
pass
747747
class PhysxGpuSystem(PhysxSystem, sapien.pysapien.System):
748-
def __init__(self, config: PhysxSceneConfig = SceneConfig()) -> None: ...
748+
def __init__(self) -> None: ...
749749
def get_scene_offset(self, scene: sapien.pysapien.Scene) -> numpy.ndarray[numpy.float32, _Shape, _Shape[3]]: ...
750750
@typing.overload
751751
def gpu_apply_articulation_qf(self) -> None: ...
@@ -1266,7 +1266,7 @@ class PhysxSceneConfig():
12661266
pass
12671267
pass
12681268
class PhysxCpuSystem(PhysxSystem, sapien.pysapien.System):
1269-
def __init__(self, config: PhysxSceneConfig = SceneConfig()) -> None: ...
1269+
def __init__(self) -> None: ...
12701270
def get_contacts(self) -> list[PhysxContact]: ...
12711271
def pack(self) -> bytes: ...
12721272
def raycast(self, position: numpy.ndarray[numpy.float32, _Shape, _Shape[3]], direction: numpy.ndarray[numpy.float32, _Shape, _Shape[3]], distance: float) -> PhysxRayHit:
@@ -1277,15 +1277,19 @@ class PhysxCpuSystem(PhysxSystem, sapien.pysapien.System):
12771277
pass
12781278
def _enable_gpu() -> None:
12791279
pass
1280-
def get_cpu_workers() -> int:
1281-
pass
12821280
def get_default_material() -> PhysxMaterial:
12831281
pass
1284-
def is_gpu_enabled() -> bool:
1282+
def get_scene_config() -> PhysxSceneConfig:
12851283
pass
1286-
def set_cpu_workers(count: int) -> None:
1284+
def is_gpu_enabled() -> bool:
12871285
pass
12881286
def set_default_material(static_friction: float, dynamic_friction: float, restitution: float) -> None:
12891287
pass
12901288
def set_gpu_memory_config(temp_buffer_capacity: int = 16777216, max_rigid_contact_count: int = 524288, max_rigid_patch_count: int = 81920, heap_capacity: int = 67108864, found_lost_pairs_capacity: int = 262144, found_lost_aggregate_pairs_capacity: int = 1024, total_aggregate_pairs_capacity: int = 1024) -> None:
12911289
pass
1290+
@typing.overload
1291+
def set_scene_config(gravity: numpy.ndarray[numpy.float32, _Shape, _Shape[3]] = array([ 0. , 0. , -9.81], dtype=float32), bounce_threshold: float = 2.0, sleep_threshold: float = 0.004999999888241291, contact_offset: float = 0.009999999776482582, solver_iterations: int = 10, solver_velocity_iterations: int = 1, enable_pcm: bool = True, enable_tgs: bool = True, enable_ccd: bool = False, enable_enhanced_determinism: bool = False, enable_friction_every_iteration: bool = True, cpu_workers: int = 0) -> None:
1292+
pass
1293+
@typing.overload
1294+
def set_scene_config(config: PhysxSceneConfig) -> None:
1295+
pass

python/py_package/wrapper/articulation_builder.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def create_link_builder(self, parent: LinkBuilder = None):
7474

7575
return builder
7676

77-
def build_entities(self):
77+
def build_entities(self, fix_root_link=None):
7878
entities = []
7979
links = []
8080
for b in self.link_builders:
@@ -113,18 +113,17 @@ def build_entities(self):
113113
links.append(link_component)
114114
entities.append(entity)
115115

116-
return entities
117-
118-
def build(self, fix_root_link=None):
119-
assert self.scene is not None
120-
links = self.build_entities()
121-
122116
if fix_root_link is not None:
123-
links[0].components[0].joint.type = (
117+
entities[0].components[0].joint.type = (
124118
"fixed" if fix_root_link else "undefined"
125119
)
120+
entities[0].pose = self.initial_pose
121+
return entities
122+
123+
def build(self, fix_root_link=None) -> sapien.physx.PhysxArticulation:
124+
assert self.scene is not None
125+
links = self.build_entities(fix_root_link=fix_root_link)
126126

127-
links[0].pose = self.initial_pose
128127
for l in links:
129128
self.scene.add_entity(l)
130129
return l.components[0].articulation

python/py_package/wrapper/engine.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,12 @@ def create_mesh_geometry(self, vertices, indices, scale=[1, 1, 1]):
2121
pass
2222

2323
def create_scene(self, config=SceneConfig()):
24+
sapien.physx.set_scene_config(config)
2425
if sapien.physx.is_gpu_enabled():
2526
physx_system = Scene._GpuSystem
2627
if physx_system is None:
27-
Scene._GpuSystem = physx_system = sapien.physx.PhysxGpuSystem(config)
28+
Scene._GpuSystem = physx_system = sapien.physx.PhysxGpuSystem()
2829
else:
29-
physx_system = sapien.physx.PhysxCpuSystem(config)
30+
physx_system = sapien.physx.PhysxCpuSystem()
3031

3132
return Scene([physx_system, RenderSystem()])

python/pybind/physx.cpp

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -314,13 +314,12 @@ Generator<int> init_physx(py::module &sapien) {
314314
});
315315

316316
PyPhysxSystem
317-
.def(py::init([](PhysxSceneConfig const &config) -> std::shared_ptr<PhysxSystem> {
318-
if (PhysxDefault::GetGPUEnabled()) {
319-
return std::make_shared<PhysxSystemGpu>(config);
320-
}
321-
return std::make_shared<PhysxSystemCpu>(config);
322-
}),
323-
py::arg("config") = PhysxSceneConfig())
317+
.def(py::init([]() -> std::shared_ptr<PhysxSystem> {
318+
if (PhysxDefault::GetGPUEnabled()) {
319+
return std::make_shared<PhysxSystemGpu>();
320+
}
321+
return std::make_shared<PhysxSystemCpu>();
322+
}))
324323
.def_property_readonly("config", &PhysxSystem::getSceneConfig)
325324
.def("get_config", &PhysxSystem::getSceneConfig)
326325
.def_property("timestep", &PhysxSystem::getTimestep, &PhysxSystem::setTimestep)
@@ -340,8 +339,7 @@ Generator<int> init_physx(py::module &sapien) {
340339
&PhysxSystem::getArticulationLinkComponents)
341340
.def("get_articulation_link_components", &PhysxSystem::getArticulationLinkComponents);
342341

343-
PyPhysxSystemCpu
344-
.def(py::init<PhysxSceneConfig const &>(), py::arg("config") = PhysxSceneConfig())
342+
PyPhysxSystemCpu.def(py::init<>())
345343
.def("get_contacts", &PhysxSystemCpu::getContacts, py::return_value_policy::reference)
346344
.def("raycast", &PhysxSystemCpu::raycast, py::arg("position"), py::arg("direction"),
347345
py::arg("distance"),
@@ -351,8 +349,7 @@ Generator<int> init_physx(py::module &sapien) {
351349
"unpack", [](PhysxSystemCpu &s, py::bytes data) { s.unpackState(data); },
352350
py::arg("data"));
353351

354-
PyPhysxSystemGpu
355-
.def(py::init<PhysxSceneConfig const &>(), py::arg("config") = PhysxSceneConfig())
352+
PyPhysxSystemGpu.def(py::init<>())
356353
.def("get_scene_offset", &PhysxSystemGpu::getSceneOffset, py::arg("scene"))
357354
.def("set_scene_offset", &PhysxSystemGpu::setSceneOffset, py::arg("scene"),
358355
py::arg("offset"), R"doc(
@@ -1005,8 +1002,20 @@ set some motion axes of the dynamic rigid body to be locked
10051002
py::arg("found_lost_pairs_capacity") = 256 * 1024,
10061003
py::arg("found_lost_aggregate_pairs_capacity") = 1024,
10071004
py::arg("total_aggregate_pairs_capacity") = 1024)
1008-
.def("set_cpu_workers", &PhysxDefault::setCpuWorkers, py::arg("count"))
1009-
.def("get_cpu_workers", &PhysxDefault::getCpuWorkers);
1005+
1006+
.def("set_scene_config",
1007+
py::overload_cast<Vec3, float, float, float, uint32_t, uint32_t, bool, bool, bool, bool,
1008+
bool, uint32_t>(&PhysxDefault::setSceneConfig),
1009+
py::arg("gravity") = Vec3{0, 0, -9.81}, py::arg("bounce_threshold") = 2.f,
1010+
py::arg("sleep_threshold") = 0.005f, py::arg("contact_offset") = 0.01f,
1011+
py::arg("solver_iterations") = 10, py::arg("solver_velocity_iterations") = 1,
1012+
py::arg("enable_pcm") = true, py::arg("enable_tgs") = true,
1013+
py::arg("enable_ccd") = false, py::arg("enable_enhanced_determinism") = false,
1014+
py::arg("enable_friction_every_iteration") = true, py::arg("cpu_workers") = 0)
1015+
.def("set_scene_config",
1016+
py::overload_cast<PhysxSceneConfig const &>(&PhysxDefault::setSceneConfig),
1017+
py::arg("config"))
1018+
.def("get_scene_config", &PhysxDefault::getSceneConfig);
10101019

10111020
////////// end global //////////
10121021

src/physx/physx_default.cpp

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ static float gRestitution{0.1};
1111
static std::weak_ptr<PhysxMaterial> gDefaultMaterial;
1212
static bool gGPUEnabled{false};
1313
static uint32_t gCpuWorkers{0};
14+
static PhysxSceneConfig gSceneConfig{};
1415

1516
static ::physx::PxgDynamicsMemoryConfig gGpuMemoryConfig{};
1617

@@ -50,8 +51,26 @@ ::physx::PxgDynamicsMemoryConfig const &PhysxDefault::getGpuMemoryConfig() {
5051
return gGpuMemoryConfig;
5152
}
5253

53-
void PhysxDefault::setCpuWorkers(uint32_t count) { gCpuWorkers = count; }
54-
uint32_t PhysxDefault::getCpuWorkers() { return gCpuWorkers; }
54+
void PhysxDefault::setSceneConfig(Vec3 gravity, float bounceThreshold, float sleepThreshold,
55+
float contactOffset, uint32_t solverIterations,
56+
uint32_t solverVelocityIterations, bool enablePCM,
57+
bool enableTGS, bool enableCCD, bool enableEnhancedDeterminism,
58+
bool enableFrictionEveryIteration, uint32_t cpuWorkers) {
59+
gSceneConfig.gravity = gravity;
60+
gSceneConfig.bounceThreshold = bounceThreshold;
61+
gSceneConfig.sleepThreshold = sleepThreshold;
62+
gSceneConfig.contactOffset = contactOffset;
63+
gSceneConfig.solverIterations = solverIterations;
64+
gSceneConfig.solverVelocityIterations = solverVelocityIterations;
65+
gSceneConfig.enablePCM = enablePCM;
66+
gSceneConfig.enableTGS = enableTGS;
67+
gSceneConfig.enableCCD = enableCCD;
68+
gSceneConfig.enableEnhancedDeterminism = enableEnhancedDeterminism;
69+
gSceneConfig.enableFrictionEveryIteration = enableFrictionEveryIteration;
70+
gSceneConfig.cpuWorkers = cpuWorkers;
71+
}
72+
void PhysxDefault::setSceneConfig(PhysxSceneConfig const &config) { gSceneConfig = config; }
73+
PhysxSceneConfig const &PhysxDefault::getSceneConfig() { return gSceneConfig; }
5574

5675
void PhysxDefault::EnableGPU() {
5776
if (PhysxEngine::GetIfExists()) {

src/physx/physx_system.cpp

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,11 @@ struct SapienBodyDataTest {
2626

2727
static_assert(sizeof(SapienBodyDataTest) == 52);
2828

29-
PhysxSystem::PhysxSystem(PhysxSceneConfig const &config)
30-
: mSceneConfig(config), mEngine(PhysxEngine::Get()) {}
29+
PhysxSystem::PhysxSystem()
30+
: mSceneConfig(PhysxDefault::getSceneConfig()), mEngine(PhysxEngine::Get()) {}
3131

32-
PhysxSystemCpu::PhysxSystemCpu(PhysxSceneConfig const &config) : PhysxSystem(config) {
32+
PhysxSystemCpu::PhysxSystemCpu() {
33+
auto &config = mSceneConfig;
3334
PxSceneDesc sceneDesc(mEngine->getPxPhysics()->getTolerancesScale());
3435
sceneDesc.gravity = Vec3ToPxVec3(config.gravity);
3536
sceneDesc.filterShader = TypeAffinityIgnoreFilterShader;
@@ -52,7 +53,7 @@ PhysxSystemCpu::PhysxSystemCpu(PhysxSceneConfig const &config) : PhysxSystem(con
5253

5354
sceneDesc.flags = sceneFlags;
5455

55-
mPxCPUDispatcher = PxDefaultCpuDispatcherCreate(PhysxDefault::getCpuWorkers());
56+
mPxCPUDispatcher = PxDefaultCpuDispatcherCreate(config.cpuWorkers);
5657
if (!mPxCPUDispatcher) {
5758
throw std::runtime_error("PhysX system creation failed: failed to create CPU dispatcher");
5859
}
@@ -61,7 +62,8 @@ PhysxSystemCpu::PhysxSystemCpu(PhysxSceneConfig const &config) : PhysxSystem(con
6162
mPxScene->setSimulationEventCallback(&mSimulationCallback);
6263
}
6364

64-
PhysxSystemGpu::PhysxSystemGpu(PhysxSceneConfig const &config) : PhysxSystem(config) {
65+
PhysxSystemGpu::PhysxSystemGpu() {
66+
auto &config = mSceneConfig;
6567
PxSceneDesc sceneDesc(mEngine->getPxPhysics()->getTolerancesScale());
6668
sceneDesc.gravity = Vec3ToPxVec3(config.gravity);
6769
sceneDesc.filterShader = TypeAffinityIgnoreFilterShaderGpu;
@@ -95,7 +97,7 @@ PhysxSystemGpu::PhysxSystemGpu(PhysxSceneConfig const &config) : PhysxSystem(con
9597

9698
sceneDesc.flags = sceneFlags;
9799

98-
mPxCPUDispatcher = PxDefaultCpuDispatcherCreate(PhysxDefault::getCpuWorkers());
100+
mPxCPUDispatcher = PxDefaultCpuDispatcherCreate(config.cpuWorkers);
99101
if (!mPxCPUDispatcher) {
100102
throw std::runtime_error("PhysX system creation failed: failed to create CPU dispatcher");
101103
}

0 commit comments

Comments
 (0)