Code Monkey home page Code Monkey logo

physx-rs's Introduction

🎳 physx-rs

Rust binding for NVIDIA PhysX, a popular and mature physics engine well-suited for games

Embark Embark Crates.io Docs dependency status Build status

Created and maintained by Embark and not officially supported by NVIDIA.

This repository contains 2 crates:

Name Description Links
physx High-level interface on top of physx-sys 🚧 Crates.io Docs
physx-sys Unsafe bindings to the PhysX C++ API Crates.io Docs

Why use it?

  • You want a feature-rich and performant physics engine to use in your project.

Caveats

  • The high-level physx wrapper is work-in-progress, and only covers a part of PhysX functionality. You can follow our progress and see where contributions are needed in our Tracking Issue for High-Level API Completeness.

  • Any other features have to be accessed through the unsafe physx-sys crate.

  • It's a large C++ codebase which requires a C++ toolchain, and comes with a non-trivial build system.

Alternatives

  • Rapier: a 2D and 3D physics engine for games, animation, and robotics written in Rust. Fully cross-platform, with web support and optional cross-platform determinism on IEEE 754-2008 compliant systems.

  • nphysics: a 2- and 3-dimensional physics engine for games and animations written in Rust. It is a good option for projects which do not require the full feature set of PhysX or prefer a native Rust solution.

Presentation

Tomasz Stachowiak did a presentation at the Stockholm Rust Meetup on October 2019 about this project that goes through the technical details of how C++ to Rust bindings of physx-sys works:

An unholy fusion of Rust and C++ in physx-rs (Stockholm Rust Meetup, October 2019)

Usage

The following code example shows how physx can be initialized.

const PX_PHYSICS_VERSION: u32 = physx::version(4, 1, 1);
let mut foundation = Foundation::new(PX_PHYSICS_VERSION);

let mut physics = PhysicsFoundation::default();

let mut scene = physics.create(
    SceneDescriptor {
        gravity: PxVec3::new(0.0, 0.0, -9.81),
        ..SceneDescriptor::new(MySceneUserData::default())
    }
);

You can run an example with cargo run --example ball, which should show the following output:

Example

Information about all wrapper functionality can be found in the physx crate docs.

If you require functionality not covered by the physx wrapper you can use the low level physx-sys crate, which closely maps to the official PhysX SDK. You can find the PhysX user guide here.

Prerequisites

How to build

git submodule update --init
cargo build --release

Windows Note

It is highly recommended to not enable debug info in release mode when building with MSVC, as the Physx C++ code will take an extremely long time to compile. You can disable this by putting the following in your Cargo.toml

[profile.release.package.physx-sys]
debug = false

How to release (maintainers only)

  1. Install cargo-release
  2. Look at physx/CHANGELOG.md and physx-sys/CHANGELOG.md to determine whether both or only one of the crate needs updating, and what semantic version bump we need
  3. Review the list of changes in the changelogs and compare with the git commit diffs to the previous release and make sure we've captured and described all changes well and that they are semantically correct
  4. Run cargo release --manifest-path <physx|physx-sys>/Cargo.toml <major|minor|patch> to automatically update the CHANGELOG, publish, tag, and push the release. If you are publishing both physx and physx-sys, you can just add the --skip-push flag to avoid pushing each crate individually and then do git push --follow-tags to push both at the same time.

Contributing

Contributor Covenant

We welcome community contributions to this project.

Please read our Contributor Guide for more information on how to get started.

License

Licensed under either of

at your option.

Note that the PhysX C++ SDK has its own BSD 3 license and depends on additional C++ third party libraries.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

physx-rs's People

Contributors

arirawr avatar dineshadepu avatar fornwall avatar forny avatar fredriknoren avatar h3r2tic avatar hentropy avatar hrydgard avatar jake-shadle avatar jasper-bekkers avatar kngwyu avatar lpil avatar maikklein avatar meithecatte avatar nehliin avatar nickcaplinger avatar niklasnummelin avatar r3dp1xl avatar repi avatar rib avatar rlidwka avatar soniasingla avatar tgolsson avatar vzout avatar xampprocky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

physx-rs's Issues

Ensure "global" resources can be deallocated

Currently multiple of the trampoline parts are never deallocated, assuming that they'll live forever. This includes the new ErrorCallback, the ProfilerCallback, and potentially others. Since PhysX takes ownership of these but doesn't delete them, we have to keep the pointers around and delete them manually when the foundation is dropped, or return a collection of pointers for the user to deal with it.

Add #[derive(Debug)] to structs.

Is your feature request related to a problem? Please describe.
Sometimes it is nice to be able to inspect structs without having to print every field.

Describe the solution you'd like
Adding #[derive(Debug)] to all structs.

Describe alternatives you've considered
N/A

Additional context
N/A.

Segfault (double free) on drop(PxShape)

let mut material = physics.create_material(0.5, 0.5, 0.6, ()).unwrap();
let geometry = PxBoxGeometry::new(1., 1., 1.);
let flags = ShapeFlag::SceneQueryShape | ShapeFlag::SimulationShape | ShapeFlag::Visualization;
let mut shape = physics.create_shape(&geometry, &mut [&mut material], false, flags, ()).unwrap();
drop(material);
drop(shape);

This code releases material twice. Material itself is an owned pointer. And then shape releases all its materials (see line 100 below):

impl<U, M: Material> Drop for PxShape<U, M> {
fn drop(&mut self) {
unsafe {
for material in self.get_materials_mut() {
drop_in_place(material as *mut _);
}
drop_in_place(self.get_user_data_mut());
PxShape_release_mut(self.as_mut_ptr());
}
}
}

Either create_shape should consume material (i.e. &mut [Owner<Material>] instead of &mut [&mut Material]) or PxShape shouldn't release its materials on drop. I believe it's latter, but not completely sure.

Add support for aarch64-apple-darwin

We'll need to add support for the new Mac on Apple Silicon target aarch64-apple-darwin.

The target just became Tier 2 in Rust and is part of the nightly builds as of a few days ago (rust-lang/rust#73908 (comment)) so one can test building both on the real DTK preview hardware as well as cross-compile from Mac.

Currently when building one gets this: thread 'main' panicked at 'unknown TARGET triple 'aarch64-apple-darwin''

Fixing release

@MaikKlein and I had a chat about release, and we sort of converged on the following:

  • Release should only ever be implemented for types where we know enough to safely release. That means we should only call it on the types which we can also instantiate, and thus know whether they have UserData.

  • Drop on Physics should be converted to unsafe .release()

  • Releases should if possible be (mut self) so we can enforce the invariants of release. Otherwise, it should be (&mut self) but safeguard against double deletes by removing the pointer.

  • All new and from_ptr and similar functions should be pub(crate) and not pub

@MaikKlein feel free to add more as you remember and feel

how to solve the problem of "cannot borrow `articulation` as mutable more than once at a time" when I use the feature of artilucation.creaet_link(...)

Excuse me, how should I to resolve this problem?
when I use the method 'articulation.create_link()' to create a link, because of the result of this method will as a parameter in next called of 'articulation.create_link()',that cause the lifetime of first value as same as the second called, so occur Multiple variable borrowings。
I try to clone reference and 'root_link_met()' ,but still can not resolve this problem.

run error in msvs target

Describe the bug
in pxbind crate,run cargo run in msvc target,and result a error:"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\xtr1common:21:2: error: cannot mangle this template type parameter type yet
static constexpr _Ty value = _Val;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: cannot mangle this template specialization type yet"

To Reproduce
Steps to reproduce the behavior:

  1. run "cargo run" command in pxbind folder

Expected behavior
gen some *.rs file

Screenshots
image

Device:

  • Windows 11
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Additional context
i test llvm 16 and 15,all failed in this convext,and change version of vc ()vs2019 ,vs2017,vs2022 ),and failed too

MUSL support

Would be nice to be able to support building for and running on x86_64-unknown-linux-musl to use PhysX more easily across linux distributions.

Did a quick test compile and ran into this linking error:

  = note: /usr/bin/ld: /workspaces/ark/target/x86_64-unknown-linux-musl/release/deps/libphysx_sys-6a6d040663f16ba9.rlib(PsUnixFPU.o): undefined reference to symbol 'feenableexcept@@GLIBC_2.2.5'

looks like the fenv.h that physx is using in physx-sys/PhysX/physx/source/foundation/src/unix/PsUnixFPU.cpp uses a couple of GCC-specific extensions to the POSIX fenv.h that does not exist on MUSL:

PX_FOUNDATION_API void physx::shdfnd::enableFPExceptions()
{
#if PX_LINUX && !defined(__EMSCRIPTEN__)
	feclearexcept(FE_ALL_EXCEPT);
	feenableexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW);
#elif PX_OSX

Should be able to disable those fp exception functions similar to how it is disabled on Emscripten, but requires further patching the PhysX code. Don't think MUSL has a global preprocessor define enabled (or does it?) but we could provide one when building for x86_64-unknown-linux-musl target in build.rs

cc @Jake-Shadle

Can't package/publish physx-sys due to generated files

Running cargo package on physx-sys current fails due to:

error: failed to verify package tarball

Caused by:
  Source directory was modified by build.rs during cargo publish. Build scripts should not modify anything outside of OUT_DIR.
Added: C:\git\physx-rs\target\package\physx-sys-0.1.0+4.1\PhysX\physx\include\PxConfig.h
        C:\git\physx-rs\target\package\physx-sys-0.1.0+4.1\structgen.obj

To proceed despite this, pass the `--no-verify` flag.

PxConfig.h seems to be auto-generated in case one doesn't have it, likely so all the includes can just include it. Unfortunately as we use a submodule straight from the PhysX repo we can't add one ourselves. Not sure if there are any settings to not generate or use this file. Or maybe we can fool cargo somehow as this added file is not intrusive.

structgen.obj I have no idea who is generating, it is some binary file and is straight in the package root which is weird and not useful for anyone.

One option can be to try and publish and get this out simply with --no-verify as a first step

Crash in Bevy engine

Describe the bug
When using ESC it will crash. Owner causes segmentation fault

To Reproduce
Steps to reproduce the behavior: this simple rewrite of the ball demo crashes the app

//BEVY PHYSX
pub fn run() {
    App::build()
        .add_plugins(DefaultPlugins)
        .add_plugin(bevy_screen_diags::ScreenDiagsPlugin::default())
        .add_startup_system(setup_physx.system())
        .add_startup_system(light::setup_simple_light.system())
        .add_startup_system(camera::setup_orbit_camera.system())
        .add_system(update_physx.system())
        .run();
}
fn setup_physx(mut commands: Commands) {
    println!("SETTING UP PHYSX");
    let mut physics = PhysicsFoundation::<_, PxShape>::default();
    let mut scene: Owner<PxScene> = physics
        .create(SceneDescriptor {
            gravity: PxVec3::new(0.0, -9.81, 0.0),
            on_advance: Some(OnAdvance),
            ..SceneDescriptor::new(())
        })
        .unwrap();
    let mut material = physics.create_material(0.5, 0.5, 0.6, ()).unwrap();
    let ground_plane = physics
        .create_plane(PxVec3::new(0.0, 1.0, 0.0), 0.0, material.as_mut(), ())
        .unwrap();
    // The scene owns actors that are added to it.  They can be retrieved using the
    // various getters on the scene.
    scene.add_static_actor(ground_plane);

    let sphere_geo = PxSphereGeometry::new(10.0);

    let mut sphere_actor = physics
        .create_rigid_dynamic(
            PxTransform::from_translation(&PxVec3::new(0.0, 40.0, 100.0)),
            &sphere_geo,
            material.as_mut(),
            10.0,
            PxTransform::default(),
            (),
        )
        .unwrap();
    sphere_actor.set_angular_damping(0.5);
    //sphere_actor.set_rigid_body_flag(RigidBodyFlag::EnablePoseIntegrationPreview, true);
    scene.add_dynamic_actor(sphere_actor);
    commands.spawn().insert(scene);
}
fn update_physx(mut commands: Commands, mut sceneq: Query<&mut Owner<PxScene>>) {
    for mut scene in sceneq.iter_mut() {
        println!("STEPPING");
        scene //HERE IT CRASHES
            .step(
                0.1,
                None::<&mut physx_sys::PxBaseTask>,
                Some(unsafe { &mut ScratchBuffer::new(4) }),
                true,
            )
            .expect("error occured during simulation");
    }
}

Expected behavior
It should not crash

Screenshots
If applicable, add screenshots to help explain your problem.

Device:

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Generate `physx-safe` on top of `physx-sys`

Is your feature request related to a problem? Please describe.
As we now have ported pxbind to Rust it would be easier to make another backend to generate a, most likely unergonomic, safe layer around physx-sys. This would let physx-rs focus on the ergonomics while leaving the unsafe code to this generated layer.

Describe the solution you'd like
Build a backend to pxbind that generates code for a physx-safe crate that hides all, or most of the, unsafe interaction with physx-sys.

Related to: #3

Generate type-safe Rust enums from PhysX enums

The code generator for physx-sys currently generates this peculiar construct for C++ enums:

pub mod PxMeshMidPhase{
    pub type Enum = u32;
    pub const eBVH33: Enum = 0u64 as u32;
    pub const eBVH34: Enum = 1u64 as u32;
    pub const eLAST: Enum = 2u64 as u32;
}

This is to match the C++ closely in terms of usage, and allow binary ops on flags.

While workable, the solution doesn't provide type safety, and makes it unwieldy to match on. We should investigate using more proper Rust enums an type-safe flags.

Add trampolines for PxSweepCallback, PxRaycastCallback and PxOverlapCallback

The Problem

Currently, scene queries are not usable because the callback types they need are not instantiable.

The Solution

Add trampolines for PxSweepCallback, PxRaycastCallback and PxOverlapCallback.

Alternatives

I tried passing in the callback viz MaybeUninit, but it crashes with a memory access violation. It's theoretically possible to cobble the vtable together in Rust, but a trampoline is the best solution.

Context

I have written call throughs for sweep, overlap, and raycast but without these types they cannot be called.

Reevaluate structgen

The goal of structgen is to output bit compatible C and Rust structs that can be marshalled over FFI via simple memcopies (which end up as nops). Right now we both check in the pre-generated sources for these for tier 1 platforms and aarch64-linux-android, with the option to regenerate them during compilation if using a compiler/target without pre-generated sources.

However, this is kind of overkill. For example, with #183 here is a diff between the x86_64-unknown-linux and aarch64-apple-darwin generated rust structs

-pub structgen_pad0: [u8; 8],
+pub structgen_pad0: [u8; 1],
-assert_eq!(size_of::<PxSIMDGuard>(), 8);
+assert_eq!(size_of::<PxSIMDGuard>(), 1);

That's...it. One struct, which is the only struct that we emit that has different fields depending on the target

  private:
#if !(PX_LINUX || PX_OSX) || (!PX_EMSCRIPTEN && PX_INTEL_FAMILY)
  PxU32			mControlWord;
  bool			mEnabled;
#endif

The thing is, we don't even need to emit this type at all because it's not part of the public API, which would give us rust and cpp layouts that are the exact same between x86_64 and aarch64, across targets...other than windows, but meh that can still be its own thing.

Cannot run the example on Ubuntu 16.

Describe the bug
Can't run the example ball_physx.

To Reproduce
Running the example in physx-rs folder

cargo run --example ball_physx

Expected behavior
I get the following error

 dinesh@LAPITOP (master *) /home/dinesh/phd/code/rust/physx-rs $  
|  Dell Laptop=> cargo run --example ball_physx
   Compiling physx-sys v0.1.0+4.1
   Compiling ncollide3d v0.20.1
   Compiling nalgebra-glm v0.4.0
error: failed to run custom build command for `physx-sys v0.1.0+4.1`
process didn't exit successfully: `/home/dinesh/phd/code/rust/physx-rs/target/debug/build/physx-sys-8b775e661e3df296/build-script-build` (exit code: 101)
--- stdout
running: "cmake" "/home/dinesh/.cargo/registry/src/github.com-1ecc6299db9ec823/physx-sys-0.1.0+4.1/PhysX/physx/source/compiler/cmake" "-DCMAKE_LIBRARY_ARCHITECTURE=x86_64-unknown-linux-gnu" "-DPX_OUTPUT_LIB_DIR=/home/dinesh/phd/code/rust/physx-rs/target/debug/build/physx-sys-5e327d56aa7c7e67/out" "-DPX_OUTPUT_BIN_DIR=/home/dinesh/phd/code/rust/physx-rs/target/debug/build/physx-sys-5e327d56aa7c7e67/out" "-DPX_OUTPUT_ARCH=x86" "-DPX_BUILDSNIPPETS=False" "-DPX_BUILDSAMPLES=False" "-DPX_GENERATE_STATIC_LIBRARIES=True" "-DPX_GENERATE_GPU_PROJECTS=False" "-DTARGET_BUILD_PLATFORM=linux" "-DCMAKE_C_COMPILER=clang" "-DCMAKE_CXX_COMPILER=clang++" "-DCMAKE_BUILD_TYPE=debug" "-DCMAKE_INSTALL_PREFIX=/home/dinesh/phd/code/rust/physx-rs/target/debug/build/physx-sys-5e327d56aa7c7e67/out" "-DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_CXX_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64"
-- Configuring done
-- Generating done
-- Build files have been written to: /home/dinesh/phd/code/rust/physx-rs/target/debug/build/physx-sys-5e327d56aa7c7e67/out/build
running: "cmake" "--build" "." "--target" "install" "--config" "debug" "--"
[  0%] Built target PhysXTask
[  4%] Built target PhysXFoundation
[  4%] Built target FastXml
[  6%] Built target LowLevelAABB
[ 10%] Built target SceneQuery
[ 12%] Built target PhysXCharacterKinematic
[ 17%] Built target LowLevel
[ 20%] Built target PhysXPvdSDK
[ 27%] Built target LowLevelDynamics
[ 35%] Built target SimulationController
[ 40%] Built target PhysXVehicle
[ 73%] Built target PhysXCommon
[ 78%] Built target PhysXCooking
[ 88%] Built target PhysX
[100%] Built target PhysXExtensions
Install the project...
-- Install configuration: "debug"
-- Up-to-date: /home/dinesh/phd/code/rust/physx-rs/target/debug/build/physx-sys-5e327d56aa7c7e67/out/source/foundation/include/unix/PsUnixAoS.h
...
cargo:root=/home/dinesh/phd/code/rust/physx-rs/target/debug/build/physx-sys-5e327d56aa7c7e67/out
cargo:rustc-link-search=native=/home/dinesh/phd/code/rust/physx-rs/target/debug/build/physx-sys-5e327d56aa7c7e67/out/bin/linux.clang/debug
cargo:rustc-link-lib=static=PhysXVehicle_static_64
cargo:rustc-link-lib=static=PhysX_static_64
cargo:rustc-link-lib=static=PhysXCooking_static_64
cargo:rustc-link-lib=static=PhysXPvdSDK_static_64
cargo:rustc-link-lib=static=PhysXCommon_static_64
cargo:rustc-link-lib=static=PhysXFoundation_static_64
cargo:rustc-link-lib=static=PhysXCharacterKinematic_static_64
cargo:rustc-link-lib=static=PhysXExtensions_static_64
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
CXXFLAGS_x86_64-unknown-linux-gnu = None
CXXFLAGS_x86_64_unknown_linux_gnu = None
HOST_CXXFLAGS = None
CXXFLAGS = None
CRATE_CC_NO_DEFAULTS = None

--- stderr
PHYSX ROOT /home/dinesh/.cargo/registry/src/github.com-1ecc6299db9ec823/physx-sys-0.1.0+4.1/PhysX/physx
PhysX Build Platform: linux
Using CXX Compiler: /usr/bin/clang++
CMake Warning (dev) at linux/CMakeLists.txt:36 (SET):
  implicitly converting 'INTERAL' to 'STRING' type.
Call Stack (most recent call first):
  CMakeLists.txt:133 (INCLUDE)
This warning is for project developers.  Use -Wno-dev to suppress it.

clang: error: unknown argument: '-fno-plt'
thread 'main' panicked at 'failed to compile structgen even though compiler reported no failures', /home/dinesh/.cargo/registry/src/github.com-1ecc6299db9ec823/physx-sys-0.1.0+4.1/build.rs:163:9
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

warning: build failed, waiting for other jobs to finish...
error: build failed

Device:

  • Ubuntu 16.04
  • C++ 7.4
  • cmake 3.15.2

Additional context
This examle runs fine in ubuntu 18. WIth the same prerequiutes (C and C++ version).

Tracking Issue for High-Level API Completeness

Modules

Module Status Description
πŸƒβ€β™‚οΈ Character ❌ Not relevant for us right now. PRs welcome.
🚏 Common 🚧 Minimal coverage exists.
🎳 Physics 🚧 Most core functionality covered.
😴 Extensions ❌ Extensions can be loaded, but access is primarily through the low-level APIs still. PRs welcome.
🏠 Foundation 🚧 Core parts covered
πŸ• Cooking 🚧 Minimal functionality exists
πŸ’§ Serializers ❌ No coverage yet. PRs welcome.
πŸ”² Geomutils ❌ No coverage yet. PRs welcome.
πŸͺ² Pvd 🚧 Basic functionality exists and can be used
❓ Scenequery ❌ No coverage yet. PRs welcome.
⚑ Immediatemode ❌ No coverage yet. PRs welcome.
πŸš— Vehicle ❌ Not relevant for us right now. PRs welcome.

TODO

  • Review coverage of partially covered modules and add listings here.

Convert from nalgebra to glam

We want to convert the physx high-level crate to use glam as a math library instead of nalgebra + nalgebra-glm as that is what we are using internally in the rest of our code for performance and simplicity.

Cleanup C++ source files

See these commits where files needed to be added so that link.exe didn't complain about missing symbols.

However lld was just fine with these on other platforms (including when cross-compiling to windows) which indicates that none of these sources actually need to be compiled, but they are still weakly referenced and thus get these errors. Getting them properly removed to reduce compile times would be nice.

Remove Releaseable trait again

Describe the bug

The Releaseable trait does not work as it's supposed to w.r.t. inheritance and callbacks, which leads to fully correct code, but not necessarily expected behaviors.

Me and @MaikKlein removed the trait to prevent this from causing issues until we find a better solution, in issue #7 and PR #8 (commit 4902bc5). However, it was accidentally diffed the wrong way and added back here when comparing the internal project with this repository, in commit 0f30263.

Add Mac CI build for aarch64 (Mac M1)

We do test building for aarch64 for Android which gives some coverage, but would be good to have Mac aarch64 CI target as that is a primary platform for us, and PhysX codebase can fail specifically on it as showin in #133.

Not sure if the would nicely cross-compile from the existing Mac x86 agents, or if we should wait until GitHub has Mac aarch64 native agents (could take a long time).

(Maybe?) port binding generator to Rust libclang

The current binding generator in C++ is hard to compile and use, which increases friction if we want to upgrade PhysX version of expose more functionality.

I tried using the approximately equivalent Python libclang bindings to regenerate a 1:1 match of the current output but found that some info was missing around inheritance and fields, which would've lead to a complete breakage of physx-sys, which would be a hard sell.

We should investigate whether the Rust libclangd can be used to generate a more similar version of the bindings and struct-tests.

Fix gcc arguments

Apparently the warning flags being passed to gcc are incorrect, but I never noticed when I did the conversion because I was only using clang.

Example output is:

error: unrecognized command line option '-Wall -Werror -Wno-invalid-offsetof -Wno-uninitialized'

Windows compile regression

It appears that compiling physx in release with debug info enabled using MSVC has a strange behavior of compiling for a long time (20m+) in a single process and then failing with an odd error message. This affects only the non-cmake path (probably?) that was added recently, so there is probably some kind of incorrect flag being passed when debug info is enabled...or..something.

Compile error with Xcode 12.5 on Mac M1

The current version we have of the PhysX C++ codebase fails to build with Xcode 12.5 that was released 3 days ago, Xcode 12.4 still works though.

Could be aarch64-specific as looks like error is in Neon-related (but may be more errors):

  cargo:warning=/Users/repi/.cargo/git/checkouts/physx-rs-4169d2249480eec2/52eb263/physx-sys/PhysX/physx/source/foundation/include/unix/neon/PsUnixNeonInlineAoS.h:3582:10: 
  error: argument value 2 is outside the valid range [0, 1]
  cargo:warning=                return vdupq_lane_f32(vget_low_f32(a), index);
  cargo:warning=                       ^                               ~~~~~

No point in filing issues on Nvidia, they haven't even closed this 1.5y old issue on Xcode 11 compile errors: NVIDIAGameWorks/PhysX#183

Emit default values in FFI bindings

One common change in PhysX 5 was to consolidate constructors, providing default values to preserve the behavior of the default constructor.

-PX_INLINE PxCapsuleGeometry() :						PxGeometry(PxGeometryType::eCAPSULE), radius(0), halfHeight(0)		{}
-PX_INLINE PxCapsuleGeometry(PxReal radius_, PxReal halfHeight_) :	PxGeometry(PxGeometryType::eCAPSULE), radius(radius_), halfHeight(halfHeight_)	{}
+PX_INLINE PxCapsuleGeometry(PxReal radius_=0.0f, PxReal halfHeight_=0.0f) :	PxGeometry(PxGeometryType::eCAPSULE), radius(radius_), halfHeight(halfHeight_)	{}

We could generate bindings to preserve the API in these cases, but that honestly feels a bit wasteful, that being said, it's a bit tedious to consult the C++ code to figure out which defaults are being used, so it would be nice to add the defaults as inline comments for each parameter so that the user can see the defaults in an overlay if they are using something like RLS, or at least be present in the physx_generated.rs code that they can inspect manually.

Support `aarch64-pc-windows-msvc`

We should add support for building and running on Windows for ARM with the aarch64-pc-windows-msvc target.

Hopefully should be pretty easy with the bindgen as we already support other aarch64 targets and Windows on x86-64.
Unless there are issues with PhysX C++ library itself on Windows on ARM

Compile errors when building from source

Describe the bug
Compilation fails when attempting to build the project on Windows 10, following the "How to build" instructions in the readme. In the console I get the following messages:

error: could not find native static library `PhysXVehicle_static_64`,` perhaps an -L flag is missing?

error: aborting due to previous error

error: could not compile `physx-sys`.
warning: build failed, waiting for other jobs to finish...
error: attempt to shift right with overflow
   --> physx\src\articulation_reduced_coordinate.rs:494:23
    |
494 |         let (a, b) = ((self.ptr as usize >> 32) as u32, self.ptr as usize as u32);
    |                       ^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = note: `#[deny(exceeding_bitshifts)]` on by default

error: aborting due to previous error

error: could not compile `physx`.

To Reproduce
Run cargo build --release from the cloned physx-rs directory

Additional context
I don't have any rust experience, and only a small amount of C/C++ experience. I would like to use the physx-sys C API to build a standalone DLL that I can use from C#.

Remove ncollide3d usage

Currently the physx crate uses ncollide3d for a couple of things, we should try and remove that usage as it feels unnecessary to bring in a different collision system in addition to physx.

Removing an actor from a scene fails and prints a PhysX warning instead

Describe the bug
Calling physics::remove_body on a BodyHandle returned by scene::add_actor or scene::add_dynamic will fail and print out the following error instead:
C:\physx-rs\physx-sys\PhysX/physx\source/physx/src\NpScene.cpp (79) : invalid operation : PxScene::removeArticulation(): Articulation not assigned to scene or assigned to another scene. Call will be ignored!
This is because physics::remove_body calls scene::remove_articulation internally, regardless of whether or not the BodyHandle argument points to an articulation.

To Reproduce
Steps to reproduce the behavior:

  1. Add an actor to the scene using scene::add_actor or scene::add_dynamic and save the returned BodyHandle.
  2. Given this handle, attempt to remove the actor from the scene by calling physics::remove_body.
  3. Observe that the actor is not removed from the scene and an "invalid operation" is reported.

Expected behavior
The API should expose a mechanism to delete actors and not just articulations. It should be difficult or impossible to call removeArticulation on an actor or call removeActor on an articulation.

Screenshots
n/a

Device:

  • OS: n/a
  • Browser: n/a
  • Version: origin/main

Additional context
First, I want to say thank you for all the effort put into this crate! You all are awesome, and this crate clearly has a lot of effort put into it. The associated talk is great too. :)

I've been toying around with physx-rs for a basic first-person shooter lately and ran into this issue. I actually have a pull request associated with this issue that I'll add here shortly. It's not a perfect solution, but it's a step in the right direction, and I'm hoping that we can refine it where needed. My project focuses on static and dynamic actors rather than articulations, so I could really use some tests that verify that my work does not break articulation API, at least until I start toying with those too.

C bindings for other languages?

Hi,
I'm keeping various C# .net bindings, for example vulkan, d3d12, d3d11 etc.

Would be possible to generate C bindings into dll/so/dylib so I can bridge the API?

Feel free to close the issue if not appropriate for the project.

Thanks in advance

Opaque struct size doesn't match C++

There is a discrepancy between C++ and Rust struct sizes for a few structs (PxRaycastQueryResult, PxSweepQueryResult, PxOverlapQueryResult, etc.). For example:

printf("c++ size: %d\n", sizeof(PxRaycastQueryResult));
c++ size: 80

println!("rust size: {}", std::mem::size_of::<PxRaycastQueryResult>());
rust size: 1

Issue is that this code:

// Decide whether we should use "strugen" to calculate the exact layout of
// this C++ struct.
//
// Ideally we would do this for all types, but we must be able to name them,
// which is not feasible for anonymous types, or types which the generator
// doesn't support yet (their cppTypeName will be empty).
//
// Note that empty types are only refered to by pointers and references in
// PhysX, so we can generate dummy contents for them.
bool shouldCalculateLayout() const {
return hasDefinition && !cppTypeName.empty() &&
"struct" == recordType && !fields.empty();
}
void fixEmptyStruct() {
if (!hasVtable && fields.empty()) {
PodRecordField f;
f.name = "pxbind_dummy";
f.decl = "char pxbind_dummy;";
f.cppType = "char";
f.rustType = "u8";
fields.emplace_back(f);
}
}

Generates this:

#[repr(C)]
pub struct PxRaycastQueryResult{
    pxbind_dummy: u8
}

I believe it should instead generate this:

#[repr(C)]
pub struct PxRaycastQueryResult{
    pxbind_dummy: [u8; 80]
}

... where "80" is sizeof(PxRaycastQueryResult), which may differ on various platforms.

Why it matters:

I'm trying to initialize PxRaycastQueryResult for batch raycast query following a guide for physx 4.1 vehicles sdk.

And I found no way to initialize it in rust (no PxRaycastQueryResult::new(), and no phys_PxRaycastQueryResult_new()). So I'm trying to manually allocate memory, but how would I know how much memory to allocate?

Code I'm trying to port is:

PxRaycastQueryResult sqResults[4];
PxBatchQueryDesc sqDesc(4, 0, 0);
sqDesc.queryMemory.userRaycastResultBuffer = sqResults;
sqDesc.queryMemory.raycastTouchBufferSize = 4;
PxBatchQuery* batchQuery = scene->createBatchQuery(sqDesc);

PxVehicleSuspensionRaycasts(...);

I'm expecting this to be equivalent of the code above, but it will only allocate 4 bytes and segfault trying to access the rest.

// this segfaults on access later:
let mut sq_results: MaybeUninit<[ PxRaycastQueryResult; 4 ]> = MaybeUninit::uninit();

// this works, but is very ugly and platform-dependent:
//let mut sq_results = [0u8; 80 * 4];

let mut sq_desc = unsafe { PxBatchQueryDesc_new(4, 0, 0) };
let mut batch_query = unsafe {
    sq_desc.queryMemory.userRaycastResultBuffer = sq_results.as_mut_ptr() as *mut PxRaycastQueryResult;
    PxScene_createBatchQuery_mut(scene.as_mut_ptr(), &sq_desc as *const _)
};

phys_PxVehicleSuspensionRaycasts(...);

Add a simple memory profiler

I want to know how much memory PhysX is using.

It seems like physx-rs could overload PxAllocatorCallback to add simple tracking of used memory. This could then be queried like scene.bytes_allocated(). I would assume such an overload would have so little overhead that it wouldn't need to be feature-gated, but if it does have overhead then maybe a simple SceneBuilder flag to turn it on could be considered.

PxAllocatorCallback also supplies a typeName for the allocated resource, so in the future one could consider returning a more detailed HashMap<String, usize> describing what is using memory, though I am not sure if such detail would be useful in practice.

Add back vehicles

All of the former vehicle APIs in 4.1 were deprecated in 5.1, this issue just tracks adding the new replacements in the physx::vehicle2 namespace that I didn't want to add in #183

Ball examples fails to link on Windows 10 MSVC

Describe the bug

The ball example fails to link on Windows 10 MSVC.

To Reproduce

$ git clone https://github.com/EmbarkStudios/physx-rs.git --depth 1 --recursive
$ cd physx-rs
$ cargo run --example ball
    Updating crates.io index
   Compiling cc v1.0.47
   Compiling cmake v0.1.42
   Compiling physx-sys v0.2.1+4.1.1 (D:\projects\physx-rs\physx-sys)
error: could not find native static library `PhysXVehicle_static_64`, perhaps an -L flag is missing?

error: aborting due to previous error

error: could not compile `physx-sys`.

Running cargo test also produces a link error:

LINK : fatal error LNK1181: cannot open input file 'PhysXVehicle_static_64.lib'

Device:

$ rustc --version --verbose
rustc 1.39.0 (4560ea788 2019-11-04)
binary: rustc
commit-hash: 4560ea788cb760f0a34127156c78e2552949f734
commit-date: 2019-11-04
host: x86_64-pc-windows-msvc
release: 1.39.0
LLVM version: 9.0

Additional context
I generally use a Cygwin/Git-bash shell on windows, but I also tested with a cmd prompt to rule out any shell/path related issues. The results were the same.

Android cross-compiling from Windows error "cargo:warning=The command line is too long"

When building locally on Windows to Android I've been running into Cargo errors about the cc command-line being too long which fails the build.

Windows has a max of 8192 characters, and got over 10k characters in some of the compile invocations, mostly due to long paths for all the include paths.

Example:

running: "c:\\Users\\repi\\Downloads\\android-ndk-r21d\\toolchains\\llvm\\prebuilt\\windows-x86_64\\bin\\aarch64-linux-android30-clang++.cmd" "-O3" "-DANDROID" "-ffunction-sections" "-fdata-sections" "-fPIC" "--target=aarch64-linux-android" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\common\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/common/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\fastxml\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/fastxml/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/filebuf/include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/foundation/include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/foundation/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/foundation/src/unix" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/ccd" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/common" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/contact" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/convex" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/distance" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/gjk" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/hf" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/intersection" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/mesh" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/pcm" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/geomutils/src/sweep" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/include\\cooking" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/lowlevel\\api/include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/lowlevel\\common/include/collision" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/lowlevel\\common/include/pipeline" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/lowlevel\\common/include/utils" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/lowlevel/common/src/pipeline" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/lowlevel\\software/include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/lowlevel/software/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\lowlevelaabb\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/lowlevelaabb/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\lowleveldynamics\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/lowleveldynamics/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physx/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physx/src/buffering" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\physxcharacterkinematic\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxcharacterkinematic/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxcooking/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxcooking/src/convex" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxcooking/src/mesh" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\physxextensions\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxextensions/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxextensions/src/serialization" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxextensions/src/serialization/Binary" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxextensions/src/serialization\\File" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxextensions/src/serialization/Xml" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\physxmetadata/core/include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxmetadata/core/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxmetadata/extensions\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxmetadata/extensions/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\physxvehicle\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxvehicle/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxvehicle/src/physxmetadata\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/physxvehicle/src/physxmetadata/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\pvd\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/pvd/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\scenequery\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/scenequery/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\simulationcontroller\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/simulationcontroller/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source\\task\\include" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/task/src" "-I" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX\\pxshared\\include" "-Wall" "-Wextra" "--sysroot=c:\\Users\\repi\\Downloads\\android-ndk-r21d\\toolchains/llvm/prebuilt\\windows-x86_64\\sysroot" "-std=c++14" "-ferror-limit=0" "-Wall" "-Wextra" "-Werror" "-Wstrict-aliasing=2" "-Weverything" "-Wno-alloca" "-Wno-anon-enum-enum-conversion" "-Wno-documentation-deprecated-sync" "-Wno-documentation-unknown-command" "-Wno-gnu-anonymous-struct" "-Wno-undef" "-Wno-unused-function" "-Wno-nested-anon-types" "-Wno-float-equal" "-Wno-padded" "-Wno-weak-vtables" "-Wno-cast-align" "-Wno-conversion" "-Wno-missing-noreturn" "-Wno-missing-variable-declarations" "-Wno-shift-sign-overflow" "-Wno-covered-switch-default" "-Wno-exit-time-destructors" "-Wno-global-constructors" "-Wno-missing-prototypes" "-Wno-unreachable-code" "-Wno-unused-macros" "-Wno-unused-member-function" "-Wno-used-but-marked-unused" "-Wno-weak-template-vtables" "-Wno-deprecated" "-Wno-non-virtual-dtor" "-Wno-invalid-noreturn" "-Wno-return-type-c-linkage" "-Wno-reserved-id-macro" "-Wno-c++98-compat-pedantic" "-Wno-unused-local-typedef" "-Wno-old-style-cast" "-Wno-newline-eof" "-Wno-unused-private-field" "-Wno-format-nonliteral" "-Wno-implicit-fallthrough" "-Wno-undefined-reinterpret-cast" "-Wno-disabled-macro-expansion" "-Wno-zero-as-null-pointer-constant" "-Wno-shadow" "-Wno-unknown-warning-option" "-Wno-atomic-implicit-seq-cst" "-Wno-extra-semi-stmt" "-Wno-gcc-compat" "-Wno-gnu-include-next" "-Wno-class-varargs" "-Wno-implicit-exception-spec-mismatch" "-Wno-macro-redefined" "-Wno-zero-length-array" "-Wno-undefined-func-template" "-Wno-c99-extensions" "-DANDROID" "-DPX_PHYSX_STATIC_LIB" "-DDISABLE_CUDA_PHYSX" "-DPX_SUPPORT_PVD=1" "-DNDEBUG=1" "-DPX_COOKING" "-o" "C:\\git\\embark\\ark\\target\\aarch64-linux-android\\release\\build\\physx-sys-b1c2471c131819bb\\out\\TaskManager.o" "-c" "C:\\Users\\repi\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\physx-sys-0.4.6\\PhysX/physx\\source/task/src\\TaskManager.cpp"
cargo:warning=The command line is too long.
exit code: 1

cc @Jasper-Bekkers @VZout

Compile error with Xcode 11

Got a surprise update to Xcode 11 on my Mac today, which broke physx-sys C++ compilation:

PhysX/physx/source/foundation/include/unix/PsUnixIntrinsics.h:59:2: error: implicit use of sequentially-consistent atomic may incur stronger memory barriers than necessary [-Werror,-Watomic-implicit-seq-cst]
        __sync_synchronize();
        ^~~~~~~~~~~~~~~~~~
1 error generated.

This can be fixed by modifying the physx-sys/PhysX/physx/source/compiler/cmake/mac/CMakeLists.txt and adding -Wno-atomic-implicit-seq-cst to the SET(PHYSX_CXX_FLAGS line.

Though as we bring in the PhysX SDK as a submodule we can't do that fix in this repo, and Nvidia doesn't merge PRs as they use Perforce internally so would take a while for that to get in and be able to update the submodule.

So what we would want to do is to add that compile option from our build.rs, tried doing something like this:

        .define("CMAKE_CXX_FLAGS", "-Wno-atomic-implicit-seq-cst")
        .profile(build_mode)
        .build();

But looks like that doesn't work either, likely because the PhysX Mac CMake file just overwrites that setting: SET(CMAKE_CXX_FLAGS ${PHYSX_CXX_FLAGS}).

So seems we have a couple of non-ideal options:

  1. Contribute a fix back to the Nvidia repo and wait half a year for a new PhysX version to be released. Though hopefully they could merge in a fix earlier, but haven't done that before.
  2. Don't submodule PhysX SDK, check in the huge SDK to this repo and modify and fix the specific file (physx-sys/PhysX/physx/source/compiler/cmake/mac/CMakeLists.txt).
  3. Come up with another solution from our build.rs to make CMake add the compiler option. This would be ideal but not sure if there are any ways of doing it.

How to get collision callback to work?

I'm using pure physx (physx-sys). The problem is that my "onConnect" (when bodies collides) never gets called. The filter shader is called though. Here is the scene creation.

pub fn create_scene(physics: PtrPhysics, gravity: f32) -> PtrScene {
    unsafe {
        let mut scene_desc: PS::PxSceneDesc =
            PS::PxSceneDesc_new(PS::PxPhysics_getTolerancesScale(physics));
        scene_desc.gravity = PS::PxVec3 {
            x: 0.0,
            y: gravity,
            z: 0.0,
        };

        unsafe extern "C" fn filterShader(mut s: *mut PS::FilterShaderCallbackInfo) -> u16 {
            use PS::PxPairFlag as F;
            let mut f = PS::PxPairFlags {
                mBits: (F::eCONTACT_DEFAULT | F::eNOTIFY_TOUCH_FOUND) as u16,
            }; //;;
            (*s).pairFlags = &mut f;
            (PS::PxFilterFlag::eDEFAULT) as u16
        }
        unsafe extern "C" fn onConnect(   //<--- This never gets called
            a: *mut std::ffi::c_void,
            b: *const PS::PxContactPairHeader,
            c: *const PS::PxContactPair,
            d: u32,
        ) {
            println!("Connecting!"); //but it doesn't :(
        };
        let info = PS::SimulationEventCallbackInfo {
            collision_callback: Some(onConnect),
            ..Default::default()
        };
        let simulation_event_callback = PS::create_simulation_event_callbacks(&info);
        scene_desc.simulationEventCallback = simulation_event_callback;
        let dispatcher = PS::phys_PxDefaultCpuDispatcherCreate(1, null_mut());
        scene_desc.cpuDispatcher = dispatcher as *mut PS::PxCpuDispatcher;
         PS::enable_custom_filter_shader(&mut scene_desc, shader, 1);
        let scene = PS::PxPhysics_createScene_mut(physics, &scene_desc);
        scene
    }
}

And this is how I set the filter data

pub fn set_filter_data(actor: *mut PS::PxRigidActor) {
    unsafe {
        let data = PS::PxFilterData_new_2(2, 2, 2, 2);
        let capacity = PS::PxRigidActor_getNbShapes(actor);
        let mut buffer: Vec<*mut PS::PxShape> = Vec::with_capacity(capacity as usize);
        let len =
            PS::PxRigidActor_getShapes(actor, buffer.as_mut_ptr() as *mut *mut _, capacity, 0);
        buffer.set_len(len as usize);
         for n in 0..(len as usize) {
            let shape = buffer.get(n);
            match shape {
                None => {}
                Some(ptr) => {
                    PS::PxShape_setSimulationFilterData_mut(*ptr, &data);
                }
            }
        }
    }
}

I saw the PxSimulationFilterCallback_pairFound_mut ? method but that is supposed to be overriden, not called, and how should it be overriden? I'm really at a loss, there is no crashes, it just doesn't work for some reason.

Are there perhaps some examples out there on how it works? Couldn't find any so far.

Utility function gl_to_px_tf_ref is broken for non-unity scale

I'll fix this myself later, just a reminder.

gl_to_px_tf_ref doesn't work if there's any scale, rotation breaks. Something like this works better (still drops scale of course, but rotation works fine)

pub fn mat4_to_pose_px(mat: &Mat4) -> PxTransform {
    let (_scale, rot, pos) = mat.to_scale_rotation_translation();
    vec3_quat_to_px(pos, rot)
}

how to solve the problem of "cannot borrow `articulation` as mutable more than once at a time" when I use the feature of artilucation.creaet_link(...)

Excuse me, how should I to resolve this problem?
when I use the method 'articulation.create_link()' to create a link, because of the result of this method will as a parameter in next called of 'articulation.create_link()',that cause the lifetime of first value as same as the second called, so occur Multiple variable borrowings。
I try to clone reference and 'root_link_met()' ,but still can not resolve this problem.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.