file_path
stringlengths
21
202
content
stringlengths
13
1.02M
size
int64
13
1.02M
lang
stringclasses
9 values
avg_line_length
float64
5.43
98.5
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.91
NVIDIA-Omniverse/orbit/docs/source/tutorials/05_controllers/run_diff_ik.rst
Using a task-space controller ============================= .. currentmodule:: omni.isaac.orbit In the previous tutorials, we have joint-space controllers to control the robot. However, in many cases, it is more intuitive to control the robot using a task-space controller. For example, if we want to teleoperate the robot, it is easier to specify the desired end-effector pose rather than the desired joint positions. In this tutorial, we will learn how to use a task-space controller to control the robot. We will use the :class:`controllers.DifferentialIKController` class to track a desired end-effector pose command. The Code ~~~~~~~~ The tutorial corresponds to the ``run_diff_ik.py`` script in the ``orbit/source/standalone/tutorials/05_controllers`` directory. .. dropdown:: Code for run_diff_ik.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :emphasize-lines: 100-102, 123-138, 157-159, 163-173 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ While using any task-space controller, it is important to ensure that the provided quantities are in the correct frames. When parallelizing environment instances, they are all existing in the same unique simulation world frame. However, typically, we want each environment itself to have its own local frame. This is accessible through the :attr:`scene.InteractiveScene.env_origins` attribute. In our APIs, we use the following notation for frames: - The simulation world frame (denoted as ``w``), which is the frame of the entire simulation. - The local environment frame (denoted as ``e``), which is the frame of the local environment. - The robot's base frame (denoted as ``b``), which is the frame of the robot's base link. Since the asset instances are not "aware" of the local environment frame, they return their states in the simulation world frame. Thus, we need to convert the obtained quantities to the local environment frame. This is done by subtracting the local environment origin from the obtained quantities. Creating an IK controller ------------------------- The :class:`~controllers.DifferentialIKController` class computes the desired joint positions for a robot to reach a desired end-effector pose. The included implementation performs the computation in a batched format and uses PyTorch operations. It supports different types of inverse kinematics solvers, including the damped least-squares method and the pseudo-inverse method. These solvers can be specified using the :attr:`~controllers.DifferentialIKControllerCfg.ik_method` argument. Additionally, the controller can handle commands as both relative and absolute poses. In this tutorial, we will use the damped least-squares method to compute the desired joint positions. Additionally, since we want to track desired end-effector poses, we will use the absolute pose command mode. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # Create controller :end-at: diff_ik_controller = DifferentialIKController(diff_ik_cfg, num_envs=scene.num_envs, device=sim.device) Obtaining the robot's joint and body indices -------------------------------------------- The IK controller implementation is a computation-only class. Thus, it expects the user to provide the necessary information about the robot. This includes the robot's joint positions, current end-effector pose, and the Jacobian matrix. While the attribute :attr:`assets.ArticulationData.joint_pos` provides the joint positions, we only want the joint positions of the robot's arm, and not the gripper. Similarly, while the attribute :attr:`assets.ArticulationData.body_state_w` provides the state of all the robot's bodies, we only want the state of the robot's end-effector. Thus, we need to index into these arrays to obtain the desired quantities. For this, the articulation class provides the methods :meth:`~assets.Articulation.find_joints` and :meth:`~assets.Articulation.find_bodies`. These methods take in the names of the joints and bodies and return their corresponding indices. While you may directly use these methods to obtain the indices, we recommend using the :attr:`~managers.SceneEntityCfg` class to resolve the indices. This class is used in various places in the APIs to extract certain information from a scene entity. Internally, it calls the above methods to obtain the indices. However, it also performs some additional checks to ensure that the provided names are valid. Thus, it is a safer option to use this class. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # Specify robot-specific parameters :end-before: # Define simulation stepping Computing robot command ----------------------- The IK controller separates the operation of setting the desired command and computing the desired joint positions. This is done to allow for the user to run the IK controller at a different frequency than the robot's control frequency. The :meth:`~controllers.DifferentialIKController.set_command` method takes in the desired end-effector pose as a single batched array. The pose is specified in the robot's base frame. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # reset controller :end-at: diff_ik_controller.set_command(ik_commands) We can then compute the desired joint positions using the :meth:`~controllers.DifferentialIKController.compute` method. The method takes in the current end-effector pose (in base frame), Jacobian, and current joint positions. We read the Jacobian matrix from the robot's data, which uses its value computed from the physics engine. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # obtain quantities from simulation :end-at: joint_pos_des = diff_ik_controller.compute(ee_pos_b, ee_quat_b, jacobian, joint_pos) The computed joint position targets can then be applied on the robot, as done in the previous tutorials. .. literalinclude:: ../../../../source/standalone/tutorials/05_controllers/run_diff_ik.py :language: python :start-at: # apply actions :end-at: scene.write_data_to_sim() The Code Execution ~~~~~~~~~~~~~~~~~~ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash ./orbit.sh -p source/standalone/tutorials/05_controllers/run_diff_ik.py --robot franka_panda --num_envs 128 The script will start a simulation with 128 robots. The robots will be controlled using the IK controller. The current and desired end-effector poses should be displayed using frame markers. When the robot reaches the desired pose, the command should cycle through to the next pose specified in the script. To stop the simulation, you can either close the window, or press the ``STOP`` button in the UI, or press ``Ctrl+C`` in the terminal.
7,092
reStructuredText
44.76129
114
0.758319
NVIDIA-Omniverse/orbit/docs/source/tutorials/05_controllers/index.rst
Using Motion Generators ======================= While the robots in the simulation environment can be controlled at the joint-level, the following tutorials show you how to use motion generators to control the robots at the task-level. .. toctree:: :maxdepth: 1 :titlesonly: run_diff_ik
302
reStructuredText
24.249998
98
0.695364
NVIDIA-Omniverse/orbit/docs/source/tutorials/04_sensors/add_sensors_on_robot.rst
.. _tutorial-add-sensors-on-robot: Adding sensors on a robot ========================= .. currentmodule:: omni.isaac.orbit While the asset classes allow us to create and simulate the physical embodiment of the robot, sensors help in obtaining information about the environment. They typically update at a lower frequency than the simulation and are useful for obtaining different proprioceptive and exteroceptive information. For example, a camera sensor can be used to obtain the visual information of the environment, and a contact sensor can be used to obtain the contact information of the robot with the environment. In this tutorial, we will see how to add different sensors to a robot. We will use the ANYmal-C robot for this tutorial. The ANYmal-C robot is a quadrupedal robot with 12 degrees of freedom. It has 4 legs, each with 3 degrees of freedom. The robot has the following sensors: - A camera sensor on the head of the robot which provides RGB-D images - A height scanner sensor that provides terrain height information - Contact sensors on the feet of the robot that provide contact information We continue this tutorial from the previous tutorial on :ref:`tutorial-interactive-scene`, where we learned about the :class:`scene.InteractiveScene` class. The Code ~~~~~~~~ The tutorial corresponds to the ``add_sensors_on_robot.py`` script in the ``orbit/source/standalone/tutorials/04_sensors`` directory. .. dropdown:: Code for add_sensors_on_robot.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :emphasize-lines: 74-97, 145-155, 169-170 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ Similar to the previous tutorials, where we added assets to the scene, the sensors are also added to the scene using the scene configuration. All sensors inherit from the :class:`sensors.SensorBase` class and are configured through their respective config classes. Each sensor instance can define its own update period, which is the frequency at which the sensor is updated. The update period is specified in seconds through the :attr:`sensors.SensorBaseCfg.update_period` attribute. Depending on the specified path and the sensor type, the sensors are attached to the prims in the scene. They may have an associated prim that is created in the scene or they may be attached to an existing prim. For instance, the camera sensor has a corresponding prim that is created in the scene, whereas for the contact sensor, the activating the contact reporting is a property on a rigid body prim. In the following, we introduce the different sensors we use in this tutorial and how they are configured. For more description about them, please check the :mod:`sensors` module. Camera sensor ------------- A camera is defined using the :class:`sensors.CameraCfg`. It is based on the USD Camera sensor and the different data types are captured using Omniverse Replicator API. Since it has a corresponding prim in the scene, the prims are created in the scene at the specified prim path. The configuration of the camera sensor includes the following parameters: * :attr:`~sensors.CameraCfg.spawn`: The type of USD camera to create. This can be either :class:`~sim.spawners.sensors.PinholeCameraCfg` or :class:`~sim.spawners.sensors.FisheyeCameraCfg`. * :attr:`~sensors.CameraCfg.offset`: The offset of the camera sensor from the parent prim. * :attr:`~sensors.CameraCfg.data_types`: The data types to capture. This can be ``rgb``, ``distance_to_image_plane``, ``normals``, or other types supported by the USD Camera sensor. To attach an RGB-D camera sensor to the head of the robot, we specify an offset relative to the base frame of the robot. The offset is specified as a translation and rotation relative to the base frame, and the :attr:`~sensors.CameraCfg.OffsetCfg.convention` in which the offset is specified. In the following, we show the configuration of the camera sensor used in this tutorial. We set the update period to 0.1s, which means that the camera sensor is updated at 10Hz. The prim path expression is set to ``{ENV_REGEX_NS}/Robot/base/front_cam`` where the ``{ENV_REGEX_NS}`` is the environment namespace, ``"Robot"`` is the name of the robot, ``"base"`` is the name of the prim to which the camera is attached, and ``"front_cam"`` is the name of the prim associated with the camera sensor. .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: camera = CameraCfg( :end-before: height_scanner = RayCasterCfg( Height scanner -------------- The height-scanner is implemented as a virtual sensor using the NVIDIA Warp ray-casting kernels. Through the :class:`sensors.RayCasterCfg`, we can specify the pattern of rays to cast and the meshes against which to cast the rays. Since they are virtual sensors, there is no corresponding prim created in the scene for them. Instead they are attached to a prim in the scene, which is used to specify the location of the sensor. For this tutorial, the ray-cast based height scanner is attached to the base frame of the robot. The pattern of rays is specified using the :attr:`~sensors.RayCasterCfg.pattern` attribute. For a uniform grid pattern, we specify the pattern using :class:`~sensors.patterns.GridPatternCfg`. Since we only care about the height information, we do not need to consider the roll and pitch of the robot. Hence, we set the :attr:`~sensors.RayCasterCfg.attach_yaw_only` to true. For the height-scanner, you can visualize the points where the rays hit the mesh. This is done by setting the :attr:`~sensors.SensorBaseCfg.debug_vis` attribute to true. The entire configuration of the height-scanner is as follows: .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: height_scanner = RayCasterCfg( :end-before: contact_forces = ContactSensorCfg( Contact sensor -------------- Contact sensors wrap around the PhysX contact reporting API to obtain the contact information of the robot with the environment. Since it relies of PhysX, the contact sensor expects the contact reporting API to be enabled on the rigid bodies of the robot. This can be done by setting the :attr:`~sim.spawners.RigidObjectSpawnerCfg.activate_contact_sensors` to true in the asset configuration. Through the :class:`sensors.ContactSensorCfg`, it is possible to specify the prims for which we want to obtain the contact information. Additional flags can be set to obtain more information about the contact, such as the contact air time, contact forces between filtered prims, etc. In this tutorial, we attach the contact sensor to the feet of the robot. The feet of the robot are named ``"LF_FOOT"``, ``"RF_FOOT"``, ``"LH_FOOT"``, and ``"RF_FOOT"``. We pass a Regex expression ``".*_FOOT"`` to simplify the prim path specification. This Regex expression matches all prims that end with ``"_FOOT"``. We set the update period to 0 to update the sensor at the same frequency as the simulation. Additionally, for contact sensors, we can specify the history length of the contact information to store. For this tutorial, we set the history length to 6, which means that the contact information for the last 6 simulation steps is stored. The entire configuration of the contact sensor is as follows: .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: contact_forces = ContactSensorCfg( :lines: 1-3 Running the simulation loop --------------------------- Similar to when using assets, the buffers and physics handles for the sensors are initialized only when the simulation is played, i.e., it is important to call ``sim.reset()`` after creating the scene. .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: # Play the simulator :end-at: sim.reset() Besides that, the simulation loop is similar to the previous tutorials. The sensors are updated as part of the scene update and they internally handle the updating of their buffers based on their update periods. The data from the sensors can be accessed through their ``data`` attribute. As an example, we show how to access the data for the different sensors created in this tutorial: .. literalinclude:: ../../../../source/standalone/tutorials/04_sensors/add_sensors_on_robot.py :language: python :start-at: # print information from the sensors :end-at: print("Received max contact force of: ", torch.max(scene["contact_forces"].data.net_forces_w).item()) The Code Execution ~~~~~~~~~~~~~~~~~~ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash ./orbit.sh -p source/standalone/tutorials/04_sensors/add_sensors_on_robot.py --num_envs 2 This command should open a stage with a ground plane, lights, and two quadrupedal robots. Around the robots, you should see red spheres that indicate the points where the rays hit the mesh. Additionally, you can switch the viewport to the camera view to see the RGB image captured by the camera sensor. Please check `here <https://youtu.be/htPbcKkNMPs?feature=shared>`_ for more information on how to switch the viewport to the camera view. To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. While in this tutorial, we went over creating and using different sensors, there are many more sensors available in the :mod:`sensors` module. We include minimal examples of using these sensors in the ``source/standalone/tutorials/04_sensors`` directory. For completeness, these scripts can be run using the following commands: .. code-block:: bash # Frame Transformer ./orbit.sh -p source/standalone/tutorials/04_sensors/run_frame_transformer.py # Ray Caster ./orbit.sh -p source/standalone/tutorials/04_sensors/run_ray_caster.py # Ray Caster Camera ./orbit.sh -p source/standalone/tutorials/04_sensors/run_ray_caster_camera.py # USD Camera ./orbit.sh -p source/standalone/tutorials/04_sensors/run_usd_camera.py
10,241
reStructuredText
48.960975
113
0.759301
NVIDIA-Omniverse/orbit/docs/source/tutorials/04_sensors/index.rst
Integrating Sensors =================== The following tutorial shows you how to integrate sensors into the simulation environment. The tutorials introduce the :class:`~omni.isaac.orbit.sensors.SensorBase` class and its derivatives such as :class:`~omni.isaac.orbit.sensors.Camera` and :class:`~omni.isaac.orbit.sensors.RayCaster`. .. toctree:: :maxdepth: 1 :titlesonly: add_sensors_on_robot
406
reStructuredText
30.30769
99
0.729064
NVIDIA-Omniverse/orbit/docs/source/tutorials/00_sim/spawn_prims.rst
.. _tutorial-spawn-prims: Spawning prims into the scene ============================= .. currentmodule:: omni.isaac.orbit This tutorial explores how to spawn various objects (or prims) into the scene in Orbit from Python. It builds upon the previous tutorial on running the simulator from a standalone script and demonstrates how to spawn a ground plane, lights, primitive shapes, and meshes from USD files. The Code ~~~~~~~~ The tutorial corresponds to the ``spawn_prims.py`` script in the ``orbit/source/standalone/tutorials/00_sim`` directory. Let's take a look at the Python script: .. dropdown:: Code for spawn_prims.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :emphasize-lines: 40-79, 91-92 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ Scene designing in Omniverse is built around a software system and file format called USD (Universal Scene Description). It allows describing 3D scenes in a hierarchical manner, similar to a file system. Since USD is a comprehensive framework, we recommend reading the `USD documentation`_ to learn more about it. For completeness, we introduce the must know concepts of USD in this tutorial. * **Primitives (Prims)**: These are the basic building blocks of a USD scene. They can be thought of as nodes in a scene graph. Each node can be a mesh, a light, a camera, or a transform. It can also be a group of other prims under it. * **Attributes**: These are the properties of a prim. They can be thought of as key-value pairs. For example, a prim can have an attribute called ``color`` with a value of ``red``. * **Relationships**: These are the connections between prims. They can be thought of as pointers to other prims. For example, a mesh prim can have a relationship to a material prim for shading. A collection of these prims, with their attributes and relationships, is called a **USD stage**. It can be thought of as a container for all prims in a scene. When we say we are designing a scene, we are actually designing a USD stage. While working with direct USD APIs provides a lot of flexibility, it can be cumbersome to learn and use. To make it easier to design scenes, Orbit builds on top of the USD APIs to provide a configuration-drive interface to spawn prims into a scene. These are included in the :mod:`sim.spawners` module. When spawning prims into the scene, each prim requires a configuration class instance that defines the prim's attributes and relationships (through material and shading information). The configuration class is then passed to its respective function where the prim name and transformation are specified. The function then spawns the prim into the scene. At a high-level, this is how it works: .. code-block:: python # Create a configuration class instance cfg = MyPrimCfg() prim_path = "/path/to/prim" # Spawn the prim into the scene using the corresponding spawner function spawn_my_prim(prim_path, cfg, translation=[0, 0, 0], orientation=[1, 0, 0, 0], scale=[1, 1, 1]) # OR # Use the spawner function directly from the configuration class cfg.func(prim_path, cfg, translation=[0, 0, 0], orientation=[1, 0, 0, 0], scale=[1, 1, 1]) In this tutorial, we demonstrate the spawning of various different prims into the scene. For more information on the available spawners, please refer to the :mod:`sim.spawners` module in Orbit. .. attention:: All the scene designing must happen before the simulation starts. Once the simulation starts, we recommend keeping the scene frozen and only altering the properties of the prim. This is particularly important for GPU simulation as adding new prims during simulation may alter the physics simulation buffers on GPU and lead to unexpected behaviors. Spawning a ground plane ----------------------- The :class:`~sim.spawners.from_files.GroundPlaneCfg` configures a grid-like ground plane with modifiable properties such as its appearance and size. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # Ground-plane :end-at: cfg_ground.func("/World/defaultGroundPlane", cfg_ground) Spawning lights --------------- It is possible to spawn `different light prims`_ into the stage. These include distant lights, sphere lights, disk lights, and cylinder lights. In this tutorial, we spawn a distant light which is a light that is infinitely far away from the scene and shines in a single direction. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # spawn distant light :end-at: cfg_light_distant.func("/World/lightDistant", cfg_light_distant, translation=(1, 0, 10)) Spawning primitive shapes ------------------------- Before spawning primitive shapes, we introduce the concept of a transform prim or Xform. A transform prim is a prim that contains only transformation properties. It is used to group other prims under it and to transform them as a group. Here we make an Xform prim to group all the primitive shapes under it. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # create a new xform prim for all objects to be spawned under :end-at: prim_utils.create_prim("/World/Objects", "Xform") Next, we spawn a cone using the :class:`~sim.spawners.shapes.ConeCfg` class. It is possible to specify the radius, height, physics properties, and material properties of the cone. By default, the physics and material properties are disabled. The first two cones we spawn ``Cone1`` and ``Cone2`` are visual elements and do not have physics enabled. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # spawn a red cone :end-at: cfg_cone.func("/World/Objects/Cone2", cfg_cone, translation=(-1.0, -1.0, 1.0)) For the third cone ``ConeRigid``, we add rigid body physics to it by setting the attributes for that in the configuration class. Through these attributes, we can specify the mass, friction, and restitution of the cone. If unspecified, they default to the default values set by USD Physics. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # spawn a green cone with colliders and rigid body :end-before: # spawn a usd file of a table into the scene Spawning from another file -------------------------- Lastly, it is possible to spawn prims from other file formats such as other USD, URDF, or OBJ files. In this tutorial, we spawn a USD file of a table into the scene. The table is a mesh prim and has a material prim associated with it. All of this information is stored in its USD file. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/spawn_prims.py :language: python :start-at: # spawn a usd file of a table into the scene :end-at: cfg.func("/World/Objects/Table", cfg, translation=(0.0, 0.0, 1.05)) The table above is added as a reference to the scene. In layman terms, this means that the table is not actually added to the scene, but a ``pointer`` to the table asset is added. This allows us to modify the table asset and have the changes reflected in the scene in a non-destructive manner. For example, we can change the material of the table without actually modifying the underlying file for the table asset directly. Only the changes are stored in the USD stage. Executing the Script ~~~~~~~~~~~~~~~~~~~~ Similar to the tutorial before, to run the script, execute the following command: .. code-block:: bash ./orbit.sh -p source/standalone/tutorials/00_sim/spawn_prims.py Once the simulation starts, you should see a window with a ground plane, a light, some cones, and a table. The green cone, which has rigid body physics enabled, should fall and collide with the table and the ground plane. The other cones are visual elements and should not move. To stop the simulation, you can close the window, or press ``Ctrl+C`` in the terminal. This tutorial provided a foundation for spawning various prims into the scene in Orbit. Although simple, it demonstrates the basic concepts of scene designing in Orbit and how to use the spawners. In the coming tutorials, we will now look at how to interact with the scene and the simulation. .. _`USD documentation`: https://graphics.pixar.com/usd/docs/index.html .. _`different light prims`: https://youtu.be/c7qyI8pZvF4?feature=shared
8,582
reStructuredText
46.94972
122
0.738989
NVIDIA-Omniverse/orbit/docs/source/tutorials/00_sim/launch_app.rst
Deep-dive into AppLauncher ========================== .. currentmodule:: omni.isaac.orbit In this tutorial, we will dive into the :class:`app.AppLauncher` class to configure the simulator using CLI arguments and environment variables (envars). Particularly, we will demonstrate how to use :class:`~app.AppLauncher` to enable livestreaming and configure the :class:`omni.isaac.kit.SimulationApp` instance it wraps, while also allowing user-provided options. The :class:`~app.AppLauncher` is a wrapper for :class:`~omni.isaac.kit.SimulationApp` to simplify its configuration. The :class:`~omni.isaac.kit.SimulationApp` has many extensions that must be loaded to enable different capabilities, and some of these extensions are order- and inter-dependent. Additionally, there are startup options such as ``headless`` which must be set at instantiation time, and which have an implied relationship with some extensions, e.g. the livestreaming extensions. The :class:`~app.AppLauncher` presents an interface that can handle these extensions and startup options in a portable manner across a variety of use cases. To achieve this, we offer CLI and envar flags which can be merged with user-defined CLI args, while passing forward arguments intended for :class:`~omni.isaac.kit.SimulationApp`. The Code -------- The tutorial corresponds to the ``launch_app.py`` script in the ``orbit/source/standalone/tutorials/00_sim`` directory. .. dropdown:: Code for launch_app.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/launch_app.py :language: python :emphasize-lines: 18-40 :linenos: The Code Explained ------------------ Adding arguments to the argparser ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :class:`~app.AppLauncher` is designed to be compatible with custom CLI args that users need for their own scripts, while still providing a portable CLI interface. In this tutorial, a standard :class:`argparse.ArgumentParser` is instantiated and given the script-specific ``--size`` argument, as well as the arguments ``--height`` and ``--width``. The latter are ingested by :class:`~omni.isaac.kit.SimulationApp`. The argument ``--size`` is not used by :class:`~app.AppLauncher`, but will merge seamlessly with the :class:`~app.AppLauncher` interface. In-script arguments can be merged with the :class:`~app.AppLauncher` interface via the :meth:`~app.AppLauncher.add_app_launcher_args` method, which will return a modified :class:`~argparse.ArgumentParser` with the :class:`~app.AppLauncher` arguments appended. This can then be processed into an :class:`argparse.Namespace` using the standard :meth:`argparse.ArgumentParser.parse_args` method and passed directly to :class:`~app.AppLauncher` for instantiation. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/launch_app.py :language: python :start-at: import argparse :end-at: simulation_app = app_launcher.app The above only illustrates only one of several ways of passing arguments to :class:`~app.AppLauncher`. Please consult its documentation page to see further options. Understanding the output of --help ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ While executing the script, we can pass the ``--help`` argument and see the combined outputs of the custom arguments and those from :class:`~app.AppLauncher`. .. code-block:: console ./orbit.sh -p source/standalone/tutorials/00_sim/launch_app.py --help [INFO] Using python from: /isaac-sim/python.sh [INFO][AppLauncher]: The argument 'width' will be used to configure the SimulationApp. [INFO][AppLauncher]: The argument 'height' will be used to configure the SimulationApp. usage: launch_app.py [-h] [--size SIZE] [--width WIDTH] [--height HEIGHT] [--headless] [--livestream {0,1,2,3}] [--offscreen_render] [--verbose] [--experience EXPERIENCE] Tutorial on running IsaacSim via the AppLauncher. options: -h, --help show this help message and exit --size SIZE Side-length of cuboid --width WIDTH Width of the viewport and generated images. Defaults to 1280 --height HEIGHT Height of the viewport and generated images. Defaults to 720 app_launcher arguments: --headless Force display off at all times. --livestream {0,1,2,3} Force enable livestreaming. Mapping corresponds to that for the "LIVESTREAM" environment variable. --offscreen_render Enable offscreen rendering when running without a GUI. --verbose Enable verbose terminal logging from the SimulationApp. --experience EXPERIENCE The experience file to load when launching the SimulationApp. * If an empty string is provided, the experience file is determined based on the headless flag. * If a relative path is provided, it is resolved relative to the `apps` folder in Isaac Sim and Orbit (in that order). This readout details the ``--size``, ``--height``, and ``--width`` arguments defined in the script directly, as well as the :class:`~app.AppLauncher` arguments. The ``[INFO]`` messages preceding the help output also reads out which of these arguments are going to be interpreted as arguments to the :class:`~omni.isaac.kit.SimulationApp` instance which the :class:`~app.AppLauncher` class wraps. In this case, it is ``--height`` and ``--width``. These are classified as such because they match the name and type of an argument which can be processed by :class:`~omni.isaac.kit.SimulationApp`. Please refer to the `specification`_ for such arguments for more examples. Using environment variables ^^^^^^^^^^^^^^^^^^^^^^^^^^^ As noted in the help message, the :class:`~app.AppLauncher` arguments (``--livestream``, ``--headless``) have corresponding environment variables (envar) as well. These are detailed in :mod:`omni.isaac.orbit.app` documentation. Providing any of these arguments through CLI is equivalent to running the script in a shell environment where the corresponding envar is set. The support for :class:`~app.AppLauncher` envars are simply a convenience to provide session-persistent configurations, and can be set in the user's ``${HOME}/.bashrc`` for persistent settings between sessions. In the case where these arguments are provided from the CLI, they will override their corresponding envar, as we will demonstrate later in this tutorial. These arguments can be used with any script that starts the simulation using :class:`~app.AppLauncher`, with one exception, ``--offscreen_render``. This setting sets the rendering pipeline to use the offscreen renderer. However, this setting is only compatible with the :class:`omni.isaac.orbit.sim.SimulationContext`. It will not work with Isaac Sim's :class:`omni.isaac.core.simulation_context.SimulationContext` class. For more information on this flag, please see the :class:`~app.AppLauncher` API documentation. The Code Execution ------------------ We will now run the example script: .. code-block:: console LIVESTREAM=1 ./orbit.sh -p source/standalone/tutorials/00_sim/launch_app.py --size 0.5 This will spawn a 0.5m\ :sup:`3` volume cuboid in the simulation. No GUI will appear, equivalent to if we had passed the ``--headless`` flag because headlessness is implied by our ``LIVESTREAM`` envar. If a visualization is desired, we could get one via Isaac's `Native Livestreaming`_. Streaming is currently the only supported method of visualization from within the container. The process can be killed by pressing ``Ctrl+C`` in the launching terminal. Now, let's look at how :class:`~app.AppLauncher` handles conflicting commands: .. code-block:: console export LIVESTREAM=0 ./orbit.sh -p source/standalone/tutorials/00_sim/launch_app.py --size 0.5 --livestream 1 This will cause the same behavior as in the previous run, because although we have set ``LIVESTREAM=0`` in our envars, CLI args such as ``--livestream`` take precedence in determining behavior. The process can be killed by pressing ``Ctrl+C`` in the launching terminal. Finally, we will examine passing arguments to :class:`~omni.isaac.kit.SimulationApp` through :class:`~app.AppLauncher`: .. code-block:: console export LIVESTREAM=1 ./orbit.sh -p source/standalone/tutorials/00_sim/launch_app.py --size 0.5 --width 1920 --height 1080 This will cause the same behavior as before, but now the viewport will be rendered at 1920x1080p resolution. This can be useful when we want to gather high-resolution video, or we can specify a lower resolution if we want our simulation to be more performant. The process can be killed by pressing ``Ctrl+C`` in the launching terminal. .. _specification: https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.kit/docs/index.html#omni.isaac.kit.SimulationApp.DEFAULT_LAUNCHER_CONFIG .. _Native Livestreaming: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/manual_livestream_clients.html#omniverse-streaming-client
9,065
reStructuredText
50.805714
166
0.734363
NVIDIA-Omniverse/orbit/docs/source/tutorials/00_sim/create_empty.rst
Creating an empty scene ======================= .. currentmodule:: omni.isaac.orbit This tutorial shows how to launch and control Isaac Sim simulator from a standalone Python script. It sets up an empty scene in Orbit and introduces the two main classes used in the framework, :class:`app.AppLauncher` and :class:`sim.SimulationContext`. Please review `Isaac Sim Interface`_ and `Isaac Sim Workflows`_ prior to beginning this tutorial to get an initial understanding of working with the simulator. The Code ~~~~~~~~ The tutorial corresponds to the ``create_empty.py`` script in the ``orbit/source/standalone/tutorials/00_sim`` directory. .. dropdown:: Code for create_empty.py :icon: code .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :emphasize-lines: 18-30,34,40-44,46-47,51-54,60-61 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ Launching the simulator ----------------------- The first step when working with standalone Python scripts is to launch the simulation application. This is necessary to do at the start since various dependency modules of Isaac Sim are only available after the simulation app is running. This can be done by importing the :class:`app.AppLauncher` class. This utility class wraps around :class:`omni.isaac.kit.SimulationApp` class to launch the simulator. It provides mechanisms to configure the simulator using command-line arguments and environment variables. For this tutorial, we mainly look at adding the command-line options to a user-defined :class:`argparse.ArgumentParser`. This is done by passing the parser instance to the :meth:`app.AppLauncher.add_app_launcher_args` method, which appends different parameters to it. These include launching the app headless, configuring different Livestream options, and enabling off-screen rendering. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: import argparse :end-at: simulation_app = app_launcher.app Importing python modules ------------------------ Once the simulation app is running, it is possible to import different Python modules from Isaac Sim and other libraries. Here we import the following module: * :mod:`omni.isaac.orbit.sim`: A sub-package in Orbit for all the core simulator-related operations. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: from omni.isaac.orbit.sim import SimulationCfg, SimulationContext :end-at: from omni.isaac.orbit.sim import SimulationCfg, SimulationContext Configuring the simulation context ---------------------------------- When launching the simulator from a standalone script, the user has complete control over playing, pausing and stepping the simulator. All these operations are handled through the **simulation context**. It takes care of various timeline events and also configures the `physics scene`_ for simulation. In Orbit, the :class:`sim.SimulationContext` class inherits from Isaac Sim's :class:`omni.isaac.core.simulation_context.SimulationContext` to allow configuring the simulation through Python's ``dataclass`` object and handle certain intricacies of the simulation stepping. For this tutorial, we set the physics and rendering time step to 0.01 seconds. This is done by passing these quantities to the :class:`sim.SimulationCfg`, which is then used to create an instance of the simulation context. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: # Initialize the simulation context :end-at: sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) Following the creation of the simulation context, we have only configured the physics acting on the simulated scene. This includes the device to use for simulation, the gravity vector, and other advanced solver parameters. There are now two main steps remaining to run the simulation: 1. Designing the simulation scene: Adding sensors, robots and other simulated objects 2. Running the simulation loop: Stepping the simulator, and setting and getting data from the simulator In this tutorial, we look at Step 2 first for an empty scene to focus on the simulation control first. In the following tutorials, we will look into Step 1 and working with simulation handles for interacting with the simulator. Running the simulation ---------------------- The first thing, after setting up the simulation scene, is to call the :meth:`sim.SimulationContext.reset` method. This method plays the timeline and initializes the physics handles in the simulator. It must always be called the first time before stepping the simulator. Otherwise, the simulation handles are not initialized properly. .. note:: :meth:`sim.SimulationContext.reset` is different from :meth:`sim.SimulationContext.play` method as the latter only plays the timeline and does not initializes the physics handles. After playing the simulation timeline, we set up a simple simulation loop where the simulator is stepped repeatedly while the simulation app is running. The method :meth:`sim.SimulationContext.step` takes in as argument :attr:`render`, which dictates whether the step includes updating the rendering-related events or not. By default, this flag is set to True. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: # Play the simulator :end-at: sim.step() Exiting the simulation ---------------------- Lastly, the simulation application is stopped and its window is closed by calling :meth:`omni.isaac.kit.SimulationApp.close` method. .. literalinclude:: ../../../../source/standalone/tutorials/00_sim/create_empty.py :language: python :start-at: # close sim app :end-at: simulation_app.close() The Code Execution ~~~~~~~~~~~~~~~~~~ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash ./orbit.sh -p source/standalone/tutorials/00_sim/create_empty.py The simulation should be playing, and the stage should be rendering. To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal. Passing ``--help`` to the above script will show the different command-line arguments added earlier by the :class:`app.AppLauncher` class. To run the script headless, you can execute the following: .. code-block:: bash ./orbit.sh -p source/standalone/tutorials/00_sim/create_empty.py --headless Now that we have a basic understanding of how to run a simulation, let's move on to the following tutorial where we will learn how to add assets to the stage. .. _`Isaac Sim Interface`: https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_interface.html#isaac-sim-app-tutorial-intro-interface .. _`Isaac Sim Workflows`: https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html .. _carb: https://docs.omniverse.nvidia.com/kit/docs/carbonite/latest/index.html .. _`physics scene`: https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_physics.html#physics-scene
7,227
reStructuredText
43.07317
168
0.754117
NVIDIA-Omniverse/orbit/docs/source/tutorials/00_sim/index.rst
Setting up a Simple Simulation ============================== These tutorials show you how to launch the simulation with different settings and spawn objects in the simulated scene. They cover the following APIs: :class:`~omni.isaac.orbit.app.AppLauncher`, :class:`~omni.isaac.orbit.sim.SimulationContext`, and :class:`~omni.isaac.orbit.sim.spawners`. .. toctree:: :maxdepth: 1 :titlesonly: create_empty spawn_prims launch_app
450
reStructuredText
29.066665
102
0.693333
NVIDIA-Omniverse/orbit/docs/source/setup/faq.rst
Frequently Asked Questions ========================== Where does Orbit fit in the Isaac ecosystem? -------------------------------------------- Over the years, NVIDIA has developed a number of tools for robotics and AI. These tools leverage the power of GPUs to accelerate the simulation both in terms of speed and realism. They show great promise in the field of simulation technology and are being used by many researchers and companies worldwide. `Isaac Gym`_ :cite:`makoviychuk2021isaac` provides a high performance GPU-based physics simulation for robot learning. It is built on top of `PhysX`_ which supports GPU-accelerated simulation of rigid bodies and a Python API to directly access physics simulation data. Through an end-to-end GPU pipeline, it is possible to achieve high frame rates compared to CPU-based physics engines. The tool has been used successfully in a number of research projects, including legged locomotion :cite:`rudin2022learning` :cite:`rudin2022advanced`, in-hand manipulation :cite:`handa2022dextreme` :cite:`allshire2022transferring`, and industrial assembly :cite:`narang2022factory`. Despite the success of Isaac Gym, it is not designed to be a general purpose simulator for robotics. For example, it does not include interaction between deformable and rigid objects, high-fidelity rendering, and support for ROS. The tool has been primarily designed as a preview release to showcase the capabilities of the underlying physics engine. With the release of `Isaac Sim`_, NVIDIA is building a general purpose simulator for robotics and has integrated the functionalities of Isaac Gym into Isaac Sim. `Isaac Sim`_ is a robot simulation toolkit built on top of Omniverse, which is a general purpose platform that aims to unite complex 3D workflows. Isaac Sim leverages the latest advances in graphics and physics simulation to provide a high-fidelity simulation environment for robotics. It supports ROS/ROS2, various sensor simulation, tools for domain randomization and synthetic data creation. Overall, it is a powerful tool for roboticists and is a huge step forward in the field of robotics simulation. With the release of above two tools, NVIDIA also released an open-sourced set of environments called `IsaacGymEnvs`_ and `OmniIsaacGymEnvs`_, that have been built on top of Isaac Gym and Isaac Sim respectively. These environments have been designed to display the capabilities of the underlying simulators and provide a starting point to understand what is possible with the simulators for robot learning. These environments can be used for benchmarking but are not designed for developing and testing custom environments and algorithms. This is where Orbit comes in. Orbit :cite:`mittal2023orbit` is built on top of Isaac Sim to provide a unified and flexible framework for robot learning that exploits latest simulation technologies. It is designed to be modular and extensible, and aims to simplify common workflows in robotics research (such as RL, learning from demonstrations, and motion planning). While it includes some pre-built environments, sensors, and tasks, its main goal is to provide an open-sourced, unified, and easy-to-use interface for developing and testing custom environments and robot learning algorithms. It not only inherits the capabilities of Isaac Sim, but also adds a number of new features that pertain to robot learning research. For example, including actuator dynamics in the simulation, procedural terrain generation, and support to collect data from human demonstrations. Where does the name come from? ------------------------------ "Orbit" suggests a sense of movement circling around a central point. For us, this symbolizes bringing together the different components and paradigms centered around robot learning, and making a unified ecosystem for it. The name further connotes modularity and flexibility. Similar to planets in a solar system at different speeds and positions, the framework is designed to not be rigid or inflexible. Rather, it aims to provide the users the ability to adjust and move around the different components to suit their needs. Finally, the name "orbit" also suggests a sense of exploration and discovery. We hope that the framework will provide a platform for researchers to explore and discover new ideas and paradigms in robot learning. Why should I use Orbit? ----------------------- Since Isaac Sim remains closed-sourced, it is difficult for users to contribute to the simulator and build a common framework for research. On its current path, we see the community using the simulator will simply develop their own frameworks that will result in scattered efforts with a lot of duplication of work. This has happened in the past with other simulators, and we believe that it is not the best way to move forward as a community. Orbit provides an open-sourced platform for the community to drive progress with consolidated efforts toward designing benchmarks and robot learning systems as a joint initiative. This allows us to reuse existing components and algorithms, and to build on top of each other's work. Doing so not only saves time and effort, but also allows us to focus on the more important aspects of research. Our hope with Orbit is that it becomes the de-facto platform for robot learning research and an environment *zoo* that leverages Isaac Sim. As the framework matures, we foresee it benefitting hugely from the latest simulation developments (as part of internal developments at NVIDIA and collaborating partners) and research in robotics. We are already working with labs in universities and research institutions to integrate their work into Orbit and hope that others in the community will join us too in this effort. If you are interested in contributing to Orbit, please reach out to us at `email <mailto:mittalma@ethz.ch>`_. .. _PhysX: https://developer.nvidia.com/physx-sdk .. _Isaac Sim: https://developer.nvidia.com/isaac-sim .. _Isaac Gym: https://developer.nvidia.com/isaac-gym .. _IsaacGymEnvs: https://github.com/NVIDIA-Omniverse/IsaacGymEnvs .. _OmniIsaacGymEnvs: https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs
6,180
reStructuredText
64.755318
112
0.795793
NVIDIA-Omniverse/orbit/docs/source/setup/installation.rst
Installation Guide =================== .. image:: https://img.shields.io/badge/IsaacSim-2023.1.1-silver.svg :target: https://developer.nvidia.com/isaac-sim :alt: IsaacSim 2023.1.1 .. image:: https://img.shields.io/badge/python-3.10-blue.svg :target: https://www.python.org/downloads/release/python-31013/ :alt: Python 3.10 .. image:: https://img.shields.io/badge/platform-linux--64-orange.svg :target: https://releases.ubuntu.com/20.04/ :alt: Ubuntu 20.04 Installing Isaac Sim -------------------- .. caution:: We have dropped support for Isaac Sim versions 2022.2 and below. We recommend using the latest Isaac Sim 2023.1 releases (``2023.1.0-hotfix.1`` or ``2023.1.1``). For more information, please refer to the `Isaac Sim release notes <https://docs.omniverse.nvidia.com/isaacsim/latest/release_notes.html>`__. Downloading pre-built binaries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Please follow the Isaac Sim `documentation <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html>`__ to install the latest Isaac Sim release. To check the minimum system requirements,refer to the documentation `here <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/requirements.html>`__. .. note:: We have tested Orbit with Isaac Sim 2023.1.0-hotfix.1 release on Ubuntu 20.04LTS with NVIDIA driver 525.147. Configuring the environment variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Isaac Sim is shipped with its own Python interpreter which bundles in the extensions released with it. To simplify the setup, we recommend using the same Python interpreter. Alternately, it is possible to setup a virtual environment following the instructions `here <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_python.html>`__. Please locate the `Python executable in Isaac Sim <https://docs.omniverse.nvidia.com/isaacsim/latest/manual_standalone_python.html#isaac-sim-python-environment>`__ by navigating to Isaac Sim root folder. In the remaining of the documentation, we will refer to its path as ``ISAACSIM_PYTHON_EXE``. .. note:: On Linux systems, by default, this should be the executable ``python.sh`` in the directory ``${HOME}/.local/share/ov/pkg/isaac_sim-*``, with ``*`` corresponding to the Isaac Sim version. To avoid the overhead of finding and locating the Isaac Sim installation directory every time, we recommend exporting the following environment variables to your terminal for the remaining of the installation instructions: .. code:: bash # Isaac Sim root directory export ISAACSIM_PATH="${HOME}/.local/share/ov/pkg/isaac_sim-2023.1.0-hotfix.1" # Isaac Sim python executable export ISAACSIM_PYTHON_EXE="${ISAACSIM_PATH}/python.sh" For more information on common paths, please check the Isaac Sim `documentation <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_faq.html#common-path-locations>`__. Running the simulator ~~~~~~~~~~~~~~~~~~~~~ Once Isaac Sim is installed successfully, make sure that the simulator runs on your system. For this, we encourage the user to try some of the introductory tutorials on their `website <https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/index.html>`__. For completeness, we specify the commands here to check that everything is configured correctly. On a new terminal (**Ctrl+Alt+T**), run the following: - Check that the simulator runs as expected: .. code:: bash # note: you can pass the argument "--help" to see all arguments possible. ${ISAACSIM_PATH}/isaac-sim.sh - Check that the simulator runs from a standalone python script: .. code:: bash # checks that python path is set correctly ${ISAACSIM_PYTHON_EXE} -c "print('Isaac Sim configuration is now complete.')" # checks that Isaac Sim can be launched from python ${ISAACSIM_PYTHON_EXE} ${ISAACSIM_PATH}/standalone_examples/api/omni.isaac.core/add_cubes.py .. attention:: If you have been using a previous version of Isaac Sim, you need to run the following command for the *first* time after installation to remove all the old user data and cached variables: .. code:: bash ${ISAACSIM_PATH}/isaac-sim.sh --reset-user If the simulator does not run or crashes while following the above instructions, it means that something is incorrectly configured. To debug and troubleshoot, please check Isaac Sim `documentation <https://docs.omniverse.nvidia.com/dev-guide/latest/linux-troubleshooting.html>`__ and the `forums <https://docs.omniverse.nvidia.com/isaacsim/latest/isaac_sim_forums.html>`__. Installing Orbit ---------------- Organizing the workspace ~~~~~~~~~~~~~~~~~~~~~~~~ .. note:: We recommend making a `fork <https://github.com/NVIDIA-Omniverse/Orbit/fork>`_ of the ``orbit`` repository to contribute to the project. This is not mandatory to use the framework. If you make a fork, please replace ``NVIDIA-Omniverse`` with your username in the following instructions. If you are not familiar with git, we recommend following the `git tutorial <https://git-scm.com/book/en/v2/Getting-Started-Git-Basics>`__. - Clone the ``orbit`` repository into your workspace: .. code:: bash # Option 1: With SSH git clone git@github.com:NVIDIA-Omniverse/orbit.git # Option 2: With HTTPS git clone https://github.com/NVIDIA-Omniverse/orbit.git - Set up a symbolic link between the installed Isaac Sim root folder and ``_isaac_sim`` in the ``orbit``` directory. This makes it convenient to index the python modules and look for extensions shipped with Isaac Sim. .. code:: bash # enter the cloned repository cd orbit # create a symbolic link ln -s ${ISAACSIM_PATH} _isaac_sim We provide a helper executable `orbit.sh <https://github.com/NVIDIA-Omniverse/Orbit/blob/main/orbit.sh>`_ that provides utilities to manage extensions: .. code:: text ./orbit.sh --help usage: orbit.sh [-h] [-i] [-e] [-f] [-p] [-s] [-t] [-o] [-v] [-d] [-c] -- Utility to manage Orbit. optional arguments: -h, --help Display the help content. -i, --install Install the extensions inside Orbit. -e, --extra [LIB] Install learning frameworks (rl_games, rsl_rl, sb3) as extra dependencies. Default is 'all'. -f, --format Run pre-commit to format the code and check lints. -p, --python Run the python executable provided by Isaac Sim or virtual environment (if active). -s, --sim Run the simulator executable (isaac-sim.sh) provided by Isaac Sim. -t, --test Run all python unittest tests. -o, --docker Run the docker container helper script (docker/container.sh). -v, --vscode Generate the VSCode settings file from template. -d, --docs Build the documentation from source using sphinx. -c, --conda [NAME] Create the conda environment for Orbit. Default name is 'orbit'. Setting up the environment ~~~~~~~~~~~~~~~~~~~~~~~~~~ The executable ``orbit.sh`` automatically fetches the python bundled with Isaac Sim, using ``./orbit.sh -p`` command (unless inside a virtual environment). This executable behaves like a python executable, and can be used to run any python script or module with the simulator. For more information, please refer to the `documentation <https://docs.omniverse.nvidia.com/isaacsim/latest/manual_standalone_python.html#isaac-sim-python-environment>`__. Although using a virtual environment is optional, we recommend using ``conda``. To install ``conda``, please follow the instructions `here <https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html>`__. In case you want to use ``conda`` to create a virtual environment, you can use the following command: .. code:: bash # Option 1: Default name for conda environment is 'orbit' ./orbit.sh --conda # or "./orbit.sh -c" # Option 2: Custom name for conda environment ./orbit.sh --conda my_env # or "./orbit.sh -c my_env" If you are using ``conda`` to create a virtual environment, make sure to activate the environment before running any scripts. For example: .. code:: bash conda activate orbit # or "conda activate my_env" Once you are in the virtual environment, you do not need to use ``./orbit.sh -p`` to run python scripts. You can use the default python executable in your environment by running ``python`` or ``python3``. However, for the rest of the documentation, we will assume that you are using ``./orbit.sh -p`` to run python scripts. This command is equivalent to running ``python`` or ``python3`` in your virtual environment. Building extensions ~~~~~~~~~~~~~~~~~~~ To build all the extensions, run the following commands: - Install dependencies using ``apt`` (on Ubuntu): .. code:: bash sudo apt install cmake build-essential - Run the install command that iterates over all the extensions in ``source/extensions`` directory and installs them using pip (with ``--editable`` flag): .. code:: bash ./orbit.sh --install # or "./orbit.sh -i" - For installing all other dependencies (such as learning frameworks), execute: .. code:: bash # Option 1: Install all dependencies ./orbit.sh --extra # or "./orbit.sh -e" # Option 2: Install only a subset of dependencies # note: valid options are 'rl_games', 'rsl_rl', 'sb3', 'robomimic', 'all' ./orbit.sh --extra rsl_rl # or "./orbit.sh -e rsl_r" Verifying the installation ~~~~~~~~~~~~~~~~~~~~~~~~~~ To verify that the installation was successful, run the following command from the top of the repository: .. code:: bash # Option 1: Using the orbit.sh executable # note: this works for both the bundled python and the virtual environment ./orbit.sh -p source/standalone/tutorials/00_sim/create_empty.py # Option 2: Using python in your virtual environment python source/standalone/tutorials/00_sim/create_empty.py The above command should launch the simulator and display a window with a black ground plane. You can exit the script by pressing ``Ctrl+C`` on your terminal or by pressing the ``STOP`` button on the simulator window. If you see this, then the installation was successful! |:tada:|
10,318
reStructuredText
38.087121
130
0.705951
NVIDIA-Omniverse/orbit/docs/source/setup/sample.rst
Running Existing Scripts ======================== Showroom -------- The main core interface extension in Orbit ``omni.isaac.orbit`` provides the main modules for actuators, objects, robots and sensors. We provide a list of demo scripts and tutorials. These showcase how to use the provided interfaces within a code in a minimal way. A few quick showroom scripts to run and checkout: - Spawn different quadrupeds and make robots stand using position commands: .. code:: bash ./orbit.sh -p source/standalone/demos/quadrupeds.py - Spawn different arms and apply random joint position commands: .. code:: bash ./orbit.sh -p source/standalone/demos/arms.py - Spawn different hands and command them to open and close: .. code:: bash ./orbit.sh -p source/standalone/demos/hands.py - Spawn procedurally generated terrains with different configurations: .. code:: bash ./orbit.sh -p source/standalone/demos/procedural_terrain.py - Spawn multiple markers that are useful for visualizations: .. code:: bash ./orbit.sh -p source/standalone/demos/markers.py Workflows --------- With Orbit, we also provide a suite of benchmark environments included in the ``omni.isaac.orbit_tasks`` extension. We use the OpenAI Gym registry to register these environments. For each environment, we provide a default configuration file that defines the scene, observations, rewards and action spaces. The list of environments available registered with OpenAI Gym can be found by running: .. code:: bash ./orbit.sh -p source/standalone/environments/list_envs.py Basic agents ~~~~~~~~~~~~ These include basic agents that output zero or random agents. They are useful to ensure that the environments are configured correctly. - Zero-action agent on the Cart-pole example .. code:: bash ./orbit.sh -p source/standalone/environments/zero_agent.py --task Isaac-Cartpole-v0 --num_envs 32 - Random-action agent on the Cart-pole example: .. code:: bash ./orbit.sh -p source/standalone/environments/random_agent.py --task Isaac-Cartpole-v0 --num_envs 32 State machine ~~~~~~~~~~~~~ We include examples on hand-crafted state machines for the environments. These help in understanding the environment and how to use the provided interfaces. The state machines are written in `warp <https://github.com/NVIDIA/warp>`__ which allows efficient execution for large number of environments using CUDA kernels. .. code:: bash ./orbit.sh -p source/standalone/environments/state_machine/lift_cube_sm.py --num_envs 32 Teleoperation ~~~~~~~~~~~~~ We provide interfaces for providing commands in SE(2) and SE(3) space for robot control. In case of SE(2) teleoperation, the returned command is the linear x-y velocity and yaw rate, while in SE(3), the returned command is a 6-D vector representing the change in pose. To play inverse kinematics (IK) control with a keyboard device: .. code:: bash ./orbit.sh -p source/standalone/environments/teleoperation/teleop_se3_agent.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --num_envs 1 --device keyboard The script prints the teleoperation events configured. For keyboard, these are as follows: .. code:: text Keyboard Controller for SE(3): Se3Keyboard Reset all commands: L Toggle gripper (open/close): K Move arm along x-axis: W/S Move arm along y-axis: A/D Move arm along z-axis: Q/E Rotate arm along x-axis: Z/X Rotate arm along y-axis: T/G Rotate arm along z-axis: C/V Imitation Learning ~~~~~~~~~~~~~~~~~~ Using the teleoperation devices, it is also possible to collect data for learning from demonstrations (LfD). For this, we support the learning framework `Robomimic <https://robomimic.github.io/>`__ and allow saving data in `HDF5 <https://robomimic.github.io/docs/tutorials/dataset_contents.html#viewing-hdf5-dataset-structure>`__ format. 1. Collect demonstrations with teleoperation for the environment ``Isaac-Lift-Cube-Franka-IK-Rel-v0``: .. code:: bash # step a: collect data with keyboard ./orbit.sh -p source/standalone/workflows/robomimic/collect_demonstrations.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --num_envs 1 --num_demos 10 --device keyboard # step b: inspect the collected dataset ./orbit.sh -p source/standalone/workflows/robomimic/tools/inspect_demonstrations.py logs/robomimic/Isaac-Lift-Cube-Franka-IK-Rel-v0/hdf_dataset.hdf5 2. Split the dataset into train and validation set: .. code:: bash # install python module (for robomimic) ./orbit.sh -e robomimic # split data ./orbit.sh -p source/standalone//workflows/robomimic/tools/split_train_val.py logs/robomimic/Isaac-Lift-Cube-Franka-IK-Rel-v0/hdf_dataset.hdf5 --ratio 0.2 3. Train a BC agent for ``Isaac-Lift-Cube-Franka-IK-Rel-v0`` with `Robomimic <https://robomimic.github.io/>`__: .. code:: bash ./orbit.sh -p source/standalone/workflows/robomimic/train.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --algo bc --dataset logs/robomimic/Isaac-Lift-Cube-Franka-IK-Rel-v0/hdf_dataset.hdf5 4. Play the learned model to visualize results: .. code:: bash ./orbit.sh -p source/standalone//workflows/robomimic/play.py --task Isaac-Lift-Cube-Franka-IK-Rel-v0 --checkpoint /PATH/TO/model.pth Reinforcement Learning ~~~~~~~~~~~~~~~~~~~~~~ We provide wrappers to different reinforcement libraries. These wrappers convert the data from the environments into the respective libraries function argument and return types. - Training an agent with `Stable-Baselines3 <https://stable-baselines3.readthedocs.io/en/master/index.html>`__ on ``Isaac-Cartpole-v0``: .. code:: bash # install python module (for stable-baselines3) ./orbit.sh -e sb3 # run script for training # note: we enable cpu flag since SB3 doesn't optimize for GPU anyway ./orbit.sh -p source/standalone/workflows/sb3/train.py --task Isaac-Cartpole-v0 --headless --cpu # run script for playing with 32 environments ./orbit.sh -p source/standalone/workflows/sb3/play.py --task Isaac-Cartpole-v0 --num_envs 32 --checkpoint /PATH/TO/model.zip - Training an agent with `SKRL <https://skrl.readthedocs.io>`__ on ``Isaac-Reach-Franka-v0``: .. code:: bash # install python module (for skrl) ./orbit.sh -e skrl # run script for training ./orbit.sh -p source/standalone/workflows/skrl/train.py --task Isaac-Reach-Franka-v0 --headless # run script for playing with 32 environments ./orbit.sh -p source/standalone/workflows/skrl/play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pt - Training an agent with `RL-Games <https://github.com/Denys88/rl_games>`__ on ``Isaac-Ant-v0``: .. code:: bash # install python module (for rl-games) ./orbit.sh -e rl_games # run script for training ./orbit.sh -p source/standalone/workflows/rl_games/train.py --task Isaac-Ant-v0 --headless # run script for playing with 32 environments ./orbit.sh -p source/standalone/workflows/rl_games/play.py --task Isaac-Ant-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth - Training an agent with `RSL-RL <https://github.com/leggedrobotics/rsl_rl>`__ on ``Isaac-Reach-Franka-v0``: .. code:: bash # install python module (for rsl-rl) ./orbit.sh -e rsl_rl # run script for training ./orbit.sh -p source/standalone/workflows/rsl_rl/train.py --task Isaac-Reach-Franka-v0 --headless # run script for playing with 32 environments ./orbit.sh -p source/standalone/workflows/rsl_rl/play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth All the scripts above log the training progress to `Tensorboard`_ in the ``logs`` directory in the root of the repository. The logs directory follows the pattern ``logs/<library>/<task>/<date-time>``, where ``<library>`` is the name of the learning framework, ``<task>`` is the task name, and ``<date-time>`` is the timestamp at which the training script was executed. To view the logs, run: .. code:: bash # execute from the root directory of the repository ./orbit.sh -p -m tensorboard.main --logdir=logs .. _Tensorboard: https://www.tensorflow.org/tensorboard
8,309
reStructuredText
34.974026
191
0.711638
NVIDIA-Omniverse/orbit/docs/source/setup/developer.rst
Developer's Guide ================= For development, we suggest using `Microsoft Visual Studio Code (VSCode) <https://code.visualstudio.com/>`__. This is also suggested by NVIDIA Omniverse and there exists tutorials on how to `debug Omniverse extensions <https://www.youtube.com/watch?v=Vr1bLtF1f4U&ab_channel=NVIDIAOmniverse>`__ using VSCode. Setting up Visual Studio Code ----------------------------- The ``orbit`` repository includes the VSCode settings to easily allow setting up your development environment. These are included in the ``.vscode`` directory and include the following files: .. code-block:: bash .vscode ├── tools │   ├── launch.template.json │   ├── settings.template.json │   └── setup_vscode.py ├── extensions.json ├── launch.json # <- this is generated by setup_vscode.py ├── settings.json # <- this is generated by setup_vscode.py └── tasks.json To setup the IDE, please follow these instructions: 1. Open the ``orbit`` directory on Visual Studio Code IDE 2. Run VSCode `Tasks <https://code.visualstudio.com/docs/editor/tasks>`__, by pressing ``Ctrl+Shift+P``, selecting ``Tasks: Run Task`` and running the ``setup_python_env`` in the drop down menu. .. image:: ../_static/vscode_tasks.png :width: 600px :align: center :alt: VSCode Tasks If everything executes correctly, it should create a file ``.python.env`` in the ``.vscode`` directory. The file contains the python paths to all the extensions provided by Isaac Sim and Omniverse. This helps in indexing all the python modules for intelligent suggestions while writing code. For more information on VSCode support for Omniverse, please refer to the following links: * `Isaac Sim VSCode support <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_standalone_python.html#isaac-sim-python-vscode>`__ * `Debugging with VSCode <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_advanced_python_debugging.html>`__ Configuring the python interpreter ---------------------------------- In the provided configuration, we set the default python interpreter to use the python executable provided by Omniverse. This is specified in the ``.vscode/settings.json`` file: .. code-block:: json { "python.defaultInterpreterPath": "${workspaceFolder}/_isaac_sim/kit/python/bin/python3", "python.envFile": "${workspaceFolder}/.vscode/.python.env", } If you want to use a different python interpreter (for instance, from your conda environment), you need to change the python interpreter used by selecting and activating the python interpreter of your choice in the bottom left corner of VSCode, or opening the command palette (``Ctrl+Shift+P``) and selecting ``Python: Select Interpreter``. For more information on how to set python interpreter for VSCode, please refer to the `VSCode documentation <https://code.visualstudio.com/docs/python/environments#_working-with-python-interpreters>`_. Repository organization ----------------------- The ``orbit`` repository is structured as follows: .. code-block:: bash orbit ├── .vscode ├── .flake8 ├── LICENSE ├── orbit.sh ├── pyproject.toml ├── README.md ├── docs ├── source │   ├── extensions │   │   ├── omni.isaac.orbit │   │   └── omni.isaac.orbit_tasks │   ├── standalone │   │   ├── demos │   │   ├── environments │   │   ├── tools │   │   ├── tutorials │   │   └── workflows └── VERSION The ``source`` directory contains the source code for all ``orbit`` *extensions* and *standalone applications*. The two are the different development workflows supported in `Isaac Sim <https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html>`__. These are described in the following sections. Extensions ~~~~~~~~~~ Extensions are the recommended way to develop applications in Isaac Sim. They are modularized packages that formulate the Omniverse ecosystem. Each extension provides a set of functionalities that can be used by other extensions or standalone applications. A folder is recognized as an extension if it contains an ``extension.toml`` file in the ``config`` directory. More information on extensions can be found in the `Omniverse documentation <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_basic.html>`__. Orbit in itself provides extensions for robot learning. These are written into the ``source/extensions`` directory. Each extension is written as a python package and follows the following structure: .. code:: bash <extension-name> ├── config │   └── extension.toml ├── docs │   ├── CHANGELOG.md │   └── README.md ├── <extension-name> │ ├── __init__.py │ ├── .... │ └── scripts ├── setup.py └── tests The ``config/extension.toml`` file contains the metadata of the extension. This includes the name, version, description, dependencies, etc. This information is used by Omniverse to load the extension. The ``docs`` directory contains the documentation for the extension with more detailed information about the extension and a CHANGELOG file that contains the changes made to the extension in each version. The ``<extension-name>`` directory contains the main python package for the extension. It may also contains the ``scripts`` directory for keeping python-based applications that are loaded into Omniverse when then extension is enabled using the `Extension Manager <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_basic.html>`__. More specifically, when an extension is enabled, the python module specified in the ``config/extension.toml`` file is loaded and scripts that contains children of the :class:`omni.ext.IExt` class are executed. .. code:: python import omni.ext class MyExt(omni.ext.IExt): """My extension application.""" def on_startup(self, ext_id): """Called when the extension is loaded.""" pass def on_shutdown(self): """Called when the extension is unloaded. It releases all references to the extension and cleans up any resources. """ pass While loading extensions into Omniverse happens automatically, using the python package in standalone applications requires additional steps. To simplify the build process and avoiding the need to understand the `premake <https://premake.github.io/>`__ build system used by Omniverse, we directly use the `setuptools <https://setuptools.readthedocs.io/en/latest/>`__ python package to build the python module provided by the extensions. This is done by the ``setup.py`` file in the extension directory. .. note:: The ``setup.py`` file is not required for extensions that are only loaded into Omniverse using the `Extension Manager <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_extension-manager.html>`__. Lastly, the ``tests`` directory contains the unit tests for the extension. These are written using the `unittest <https://docs.python.org/3/library/unittest.html>`__ framework. It is important to note that Omniverse also provides a similar `testing framework <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/104.0/guide/testing_exts_python.html>`__. However, it requires going through the build process and does not support testing of the python module in standalone applications. Standalone applications ~~~~~~~~~~~~~~~~~~~~~~~ In a typical Omniverse workflow, the simulator is launched first, after which the extensions are enabled that load the python module and run the python application. While this is a recommended workflow, it is not always possible to use this workflow. For example, for robot learning, it is essential to have complete control over simulation stepping and all the other functionalities instead of asynchronously waiting for the simulator to step. In such cases, it is necessary to write a standalone application that launches the simulator using :class:`~omni.isaac.orbit.app.AppLauncher` and allows complete control over the simulation through the :class:`~omni.isaac.orbit.sim.SimulationContext` class. .. code:: python """Launch Isaac Sim Simulator first.""" from omni.isaac.orbit.app import AppLauncher # launch omniverse app app_launcher = AppLauncher(headless=False) simulation_app = app_launcher.app """Rest everything follows.""" from omni.isaac.orbit.sim import SimulationContext if __name__ == "__main__": # get simulation context simulation_context = SimulationContext() # reset and play simulation simulation_context.reset() # step simulation simulation_context.step() # stop simulation simulation_context.stop() # close the simulation simulation_app.close() The ``source/standalone`` directory contains various standalone applications designed using the extensions provided by ``orbit``. These applications are written in python and are structured as follows: * **demos**: Contains various demo applications that showcase the core framework ``omni.isaac.orbit``. * **environments**: Contains applications for running environments defined in ``omni.isaac.orbit_tasks`` with different agents. These include a random policy, zero-action policy, teleoperation or scripted state machines. * **tools**: Contains applications for using the tools provided by the framework. These include converting assets, generating datasets, etc. * **tutorials**: Contains step-by-step tutorials for using the APIs provided by the framework. * **workflows**: Contains applications for using environments with various learning-based frameworks. These include different reinforcement learning or imitation learning libraries.
9,810
reStructuredText
39.374485
146
0.729664
NVIDIA-Omniverse/orbit/docs/source/setup/template.rst
Building your Own Project ========================= Traditionally, building new projects that utilize Orbit's features required creating your own extensions within the Orbit repository. However, this approach can obscure project visibility and complicate updates from one version of Orbit to another. To circumvent these challenges, we now provide a pre-configured and customizable `extension template <https://github.com/isaac-orbit/orbit.ext_template>`_ for creating projects in an isolated environment. This template serves three distinct use cases: * **Project Template**: Provides essential access to Isaac Sim and Orbit's features, making it ideal for projects that require a standalone environment. * **Python Package**: Facilitates integration with Isaac Sim's native or virtual Python environment, allowing for the creation of Python packages that can be shared and reused across multiple projects. * **Omniverse Extension**: Supports direct integration into Omniverse extension workflow. .. note:: We recommend using the extension template for new projects, as it provides a more streamlined and efficient workflow. Additionally it ensures that your project remains up-to-date with the latest features and improvements in Orbit. To get started, please follow the instructions in the `extension template repository <https://github.com/isaac-orbit/orbit.ext_template>`_.
1,396
reStructuredText
52.730767
139
0.790831
NVIDIA-Omniverse/orbit/docs/source/api/index.rst
API Reference ============= This page gives an overview of all the modules and classes in the Orbit extensions. omni.isaac.orbit extension -------------------------- The following modules are available in the ``omni.isaac.orbit`` extension: .. currentmodule:: omni.isaac.orbit .. autosummary:: :toctree: orbit app actuators assets controllers devices envs managers markers scene sensors sim terrains utils .. toctree:: :hidden: orbit/omni.isaac.orbit.envs.mdp orbit/omni.isaac.orbit.envs.ui orbit/omni.isaac.orbit.sensors.patterns orbit/omni.isaac.orbit.sim.converters orbit/omni.isaac.orbit.sim.schemas orbit/omni.isaac.orbit.sim.spawners omni.isaac.orbit_tasks extension -------------------------------- The following modules are available in the ``omni.isaac.orbit_tasks`` extension: .. currentmodule:: omni.isaac.orbit_tasks .. autosummary:: :toctree: orbit_tasks utils .. toctree:: :hidden: orbit_tasks/omni.isaac.orbit_tasks.utils.wrappers orbit_tasks/omni.isaac.orbit_tasks.utils.data_collector
1,096
reStructuredText
17.913793
83
0.67792
NVIDIA-Omniverse/orbit/docs/source/api/orbit_tasks/omni.isaac.orbit_tasks.utils.rst
orbit\_tasks.utils ================== .. automodule:: omni.isaac.orbit_tasks.utils :members: :imported-members: .. rubric:: Submodules .. autosummary:: data_collector wrappers
205
reStructuredText
13.714285
44
0.580488
NVIDIA-Omniverse/orbit/docs/source/api/orbit_tasks/omni.isaac.orbit_tasks.utils.data_collector.rst
orbit\_tasks.utils.data\_collector ================================== .. automodule:: omni.isaac.orbit_tasks.utils.data_collector .. Rubric:: Classes .. autosummary:: RobomimicDataCollector Robomimic Data Collector ------------------------ .. autoclass:: RobomimicDataCollector :members: :show-inheritance:
338
reStructuredText
17.833332
59
0.579882
NVIDIA-Omniverse/orbit/docs/source/api/orbit_tasks/omni.isaac.orbit_tasks.utils.wrappers.rst
orbit\_tasks.utils.wrappers =========================== .. automodule:: omni.isaac.orbit_tasks.utils.wrappers RL-Games Wrapper ---------------- .. automodule:: omni.isaac.orbit_tasks.utils.wrappers.rl_games :members: :show-inheritance: RSL-RL Wrapper -------------- .. automodule:: omni.isaac.orbit_tasks.utils.wrappers.rsl_rl :members: :imported-members: :show-inheritance: SKRL Wrapper ------------ .. automodule:: omni.isaac.orbit_tasks.utils.wrappers.skrl :members: :show-inheritance: Stable-Baselines3 Wrapper ------------------------- .. automodule:: omni.isaac.orbit_tasks.utils.wrappers.sb3 :members: :show-inheritance:
665
reStructuredText
18.588235
62
0.62406
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.utils.rst
orbit.utils =========== .. automodule:: omni.isaac.orbit.utils .. Rubric:: Submodules .. autosummary:: io array assets dict math noise string timer warp .. Rubric:: Functions .. autosummary:: configclass Configuration class ~~~~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.configclass :members: :show-inheritance: IO operations ~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.io :members: :imported-members: :show-inheritance: Array operations ~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.array :members: :show-inheritance: Asset operations ~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.assets :members: :show-inheritance: Dictionary operations ~~~~~~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.dict :members: :show-inheritance: Math operations ~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.math :members: :inherited-members: :show-inheritance: Noise operations ~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.noise :members: :imported-members: :inherited-members: :show-inheritance: :exclude-members: __init__, func String operations ~~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.string :members: :show-inheritance: Timer operations ~~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.timer :members: :show-inheritance: Warp operations ~~~~~~~~~~~~~~~ .. automodule:: omni.isaac.orbit.utils.warp :members: :imported-members: :show-inheritance:
1,602
reStructuredText
14.871287
50
0.598627
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.terrains.rst
orbit.terrains ============== .. automodule:: omni.isaac.orbit.terrains .. rubric:: Classes .. autosummary:: TerrainImporter TerrainImporterCfg TerrainGenerator TerrainGeneratorCfg SubTerrainBaseCfg Terrain importer ---------------- .. autoclass:: TerrainImporter :members: :show-inheritance: .. autoclass:: TerrainImporterCfg :members: :exclude-members: __init__, class_type Terrain generator ----------------- .. autoclass:: TerrainGenerator :members: .. autoclass:: TerrainGeneratorCfg :members: :exclude-members: __init__ .. autoclass:: SubTerrainBaseCfg :members: :exclude-members: __init__ Height fields ------------- .. automodule:: omni.isaac.orbit.terrains.height_field All sub-terrains must inherit from the :class:`HfTerrainBaseCfg` class which contains the common parameters for all terrains generated from height fields. .. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfTerrainBaseCfg :members: :show-inheritance: :exclude-members: __init__, function Random Uniform Terrain ^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.random_uniform_terrain .. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfRandomUniformTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Pyramid Sloped Terrain ^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.pyramid_sloped_terrain .. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfPyramidSlopedTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfInvertedPyramidSlopedTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Pyramid Stairs Terrain ^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.pyramid_stairs_terrain .. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfPyramidStairsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfInvertedPyramidStairsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Discrete Obstacles Terrain ^^^^^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.discrete_obstacles_terrain .. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfDiscreteObstaclesTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Wave Terrain ^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.wave_terrain .. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfWaveTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Stepping Stones Terrain ^^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.height_field.hf_terrains.stepping_stones_terrain .. autoclass:: omni.isaac.orbit.terrains.height_field.hf_terrains_cfg.HfSteppingStonesTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Trimesh terrains ---------------- .. automodule:: omni.isaac.orbit.terrains.trimesh Flat terrain ^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.flat_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshPlaneTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Pyramid terrain ^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.pyramid_stairs_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshPyramidStairsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Inverted pyramid terrain ^^^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.inverted_pyramid_stairs_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshInvertedPyramidStairsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Random grid terrain ^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.random_grid_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRandomGridTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Rails terrain ^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.rails_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRailsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Pit terrain ^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.pit_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshPitTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Box terrain ^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.box_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshBoxTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Gap terrain ^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.gap_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshGapTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Floating ring terrain ^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.floating_ring_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshFloatingRingTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Star terrain ^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.star_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshStarTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Repeated Objects Terrain ^^^^^^^^^^^^^^^^^^^^^^^^ .. autofunction:: omni.isaac.orbit.terrains.trimesh.mesh_terrains.repeated_objects_terrain .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedObjectsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedPyramidsTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedBoxesTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function .. autoclass:: omni.isaac.orbit.terrains.trimesh.mesh_terrains_cfg.MeshRepeatedCylindersTerrainCfg :members: :show-inheritance: :exclude-members: __init__, function Utilities --------- .. automodule:: omni.isaac.orbit.terrains.utils :members: :undoc-members:
7,214
reStructuredText
26.538168
103
0.708206
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.rst
orbit.sim ========= .. automodule:: omni.isaac.orbit.sim .. rubric:: Submodules .. autosummary:: converters schemas spawners utils .. rubric:: Classes .. autosummary:: SimulationContext SimulationCfg PhysxCfg .. rubric:: Functions .. autosummary:: simulation_context.build_simulation_context Simulation Context ------------------ .. autoclass:: SimulationContext :members: :show-inheritance: Simulation Configuration ------------------------ .. autoclass:: SimulationCfg :members: :show-inheritance: :exclude-members: __init__ .. autoclass:: PhysxCfg :members: :show-inheritance: :exclude-members: __init__ Simulation Context Builder -------------------------- .. automethod:: simulation_context.build_simulation_context Utilities --------- .. automodule:: omni.isaac.orbit.sim.utils :members: :show-inheritance:
897
reStructuredText
13.966666
59
0.626533
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.markers.rst
orbit.markers ============= .. automodule:: omni.isaac.orbit.markers .. rubric:: Classes .. autosummary:: VisualizationMarkers VisualizationMarkersCfg Visualization Markers --------------------- .. autoclass:: VisualizationMarkers :members: :undoc-members: :show-inheritance: .. autoclass:: VisualizationMarkersCfg :members: :exclude-members: __init__
392
reStructuredText
15.374999
40
0.637755
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.managers.rst
orbit.managers ============== .. automodule:: omni.isaac.orbit.managers .. rubric:: Classes .. autosummary:: SceneEntityCfg ManagerBase ManagerTermBase ManagerTermBaseCfg ObservationManager ObservationGroupCfg ObservationTermCfg ActionManager ActionTerm ActionTermCfg EventManager EventTermCfg CommandManager CommandTerm CommandTermCfg RewardManager RewardTermCfg TerminationManager TerminationTermCfg CurriculumManager CurriculumTermCfg Scene Entity ------------ .. autoclass:: SceneEntityCfg :members: :exclude-members: __init__ Manager Base ------------ .. autoclass:: ManagerBase :members: .. autoclass:: ManagerTermBase :members: .. autoclass:: ManagerTermBaseCfg :members: :exclude-members: __init__ Observation Manager ------------------- .. autoclass:: ObservationManager :members: :inherited-members: :show-inheritance: .. autoclass:: ObservationGroupCfg :members: :exclude-members: __init__ .. autoclass:: ObservationTermCfg :members: :exclude-members: __init__ Action Manager -------------- .. autoclass:: ActionManager :members: :inherited-members: :show-inheritance: .. autoclass:: ActionTerm :members: :inherited-members: :show-inheritance: .. autoclass:: ActionTermCfg :members: :exclude-members: __init__ Event Manager ------------- .. autoclass:: EventManager :members: :inherited-members: :show-inheritance: .. autoclass:: EventTermCfg :members: :exclude-members: __init__ Randomization Manager --------------------- .. deprecated:: v0.3 The Randomization Manager is deprecated and will be removed in v0.4. Please use the :class:`EventManager` class instead. .. autoclass:: RandomizationManager :members: :inherited-members: :show-inheritance: .. autoclass:: RandomizationTermCfg :members: :exclude-members: __init__ Command Manager --------------- .. autoclass:: CommandManager :members: .. autoclass:: CommandTerm :members: :exclude-members: __init__, class_type .. autoclass:: CommandTermCfg :members: :exclude-members: __init__, class_type Reward Manager -------------- .. autoclass:: RewardManager :members: :inherited-members: :show-inheritance: .. autoclass:: RewardTermCfg :exclude-members: __init__ Termination Manager ------------------- .. autoclass:: TerminationManager :members: :inherited-members: :show-inheritance: .. autoclass:: TerminationTermCfg :members: :exclude-members: __init__ Curriculum Manager ------------------ .. autoclass:: CurriculumManager :members: :inherited-members: :show-inheritance: .. autoclass:: CurriculumTermCfg :members: :exclude-members: __init__
2,846
reStructuredText
16.574074
72
0.641251
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sensors.rst
orbit.sensors ============= .. automodule:: omni.isaac.orbit.sensors .. rubric:: Submodules .. autosummary:: patterns .. rubric:: Classes .. autosummary:: SensorBase SensorBaseCfg Camera CameraData CameraCfg ContactSensor ContactSensorData ContactSensorCfg FrameTransformer FrameTransformerData FrameTransformerCfg RayCaster RayCasterData RayCasterCfg RayCasterCamera RayCasterCameraCfg Sensor Base ----------- .. autoclass:: SensorBase :members: .. autoclass:: SensorBaseCfg :members: :exclude-members: __init__, class_type USD Camera ---------- .. autoclass:: Camera :members: :inherited-members: :show-inheritance: .. autoclass:: CameraData :members: :inherited-members: :exclude-members: __init__ .. autoclass:: CameraCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Contact Sensor -------------- .. autoclass:: ContactSensor :members: :inherited-members: :show-inheritance: .. autoclass:: ContactSensorData :members: :inherited-members: :exclude-members: __init__ .. autoclass:: ContactSensorCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Frame Transformer ----------------- .. autoclass:: FrameTransformer :members: :inherited-members: :show-inheritance: .. autoclass:: FrameTransformerData :members: :inherited-members: :exclude-members: __init__ .. autoclass:: FrameTransformerCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type .. autoclass:: OffsetCfg :members: :inherited-members: :exclude-members: __init__ Ray-Cast Sensor --------------- .. autoclass:: RayCaster :members: :inherited-members: :show-inheritance: .. autoclass:: RayCasterData :members: :inherited-members: :exclude-members: __init__ .. autoclass:: RayCasterCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Ray-Cast Camera --------------- .. autoclass:: RayCasterCamera :members: :inherited-members: :show-inheritance: .. autoclass:: RayCasterCameraCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
2,409
reStructuredText
16.463768
42
0.635533
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.actuators.rst
orbit.actuators =============== .. automodule:: omni.isaac.orbit.actuators .. rubric:: Classes .. autosummary:: ActuatorBase ActuatorBaseCfg ImplicitActuator ImplicitActuatorCfg IdealPDActuator IdealPDActuatorCfg DCMotor DCMotorCfg ActuatorNetMLP ActuatorNetMLPCfg ActuatorNetLSTM ActuatorNetLSTMCfg Actuator Base ------------- .. autoclass:: ActuatorBase :members: :inherited-members: .. autoclass:: ActuatorBaseCfg :members: :inherited-members: :exclude-members: __init__, class_type Implicit Actuator ----------------- .. autoclass:: ImplicitActuator :members: :inherited-members: :show-inheritance: .. autoclass:: ImplicitActuatorCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Ideal PD Actuator ----------------- .. autoclass:: IdealPDActuator :members: :inherited-members: :show-inheritance: .. autoclass:: IdealPDActuatorCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type DC Motor Actuator ----------------- .. autoclass:: DCMotor :members: :inherited-members: :show-inheritance: .. autoclass:: DCMotorCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type MLP Network Actuator --------------------- .. autoclass:: ActuatorNetMLP :members: :inherited-members: :show-inheritance: .. autoclass:: ActuatorNetMLPCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type LSTM Network Actuator --------------------- .. autoclass:: ActuatorNetLSTM :members: :inherited-members: :show-inheritance: .. autoclass:: ActuatorNetLSTMCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
1,831
reStructuredText
16.447619
42
0.663026
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.envs.ui.rst
orbit.envs.ui ============= .. automodule:: omni.isaac.orbit.envs.ui .. rubric:: Classes .. autosummary:: BaseEnvWindow RLTaskEnvWindow ViewportCameraController Base Environment UI ------------------- .. autoclass:: BaseEnvWindow :members: RL Task Environment UI ---------------------- .. autoclass:: RLTaskEnvWindow :members: :show-inheritance: Viewport Camera Controller -------------------------- .. autoclass:: ViewportCameraController :members:
509
reStructuredText
14.9375
40
0.573674
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.devices.rst
orbit.devices ============= .. automodule:: omni.isaac.orbit.devices .. rubric:: Classes .. autosummary:: DeviceBase Se2Gamepad Se3Gamepad Se2Keyboard Se3Keyboard Se3SpaceMouse Se3SpaceMouse Device Base ----------- .. autoclass:: DeviceBase :members: Game Pad -------- .. autoclass:: Se2Gamepad :members: :inherited-members: :show-inheritance: .. autoclass:: Se3Gamepad :members: :inherited-members: :show-inheritance: Keyboard -------- .. autoclass:: Se2Keyboard :members: :inherited-members: :show-inheritance: .. autoclass:: Se3Keyboard :members: :inherited-members: :show-inheritance: Space Mouse ----------- .. autoclass:: Se2SpaceMouse :members: :inherited-members: :show-inheritance: .. autoclass:: Se3SpaceMouse :members: :inherited-members: :show-inheritance:
893
reStructuredText
13.419355
40
0.62262
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.app.rst
orbit.app ========= .. automodule:: omni.isaac.orbit.app .. rubric:: Classes .. autosummary:: AppLauncher Environment variables --------------------- The following details the behavior of the class based on the environment variables: * **Headless mode**: If the environment variable ``HEADLESS=1``, then SimulationApp will be started in headless mode. If ``LIVESTREAM={1,2,3}``, then it will supersede the ``HEADLESS`` envvar and force headlessness. * ``HEADLESS=1`` causes the app to run in headless mode. * **Livestreaming**: If the environment variable ``LIVESTREAM={1,2,3}`` , then `livestream`_ is enabled. Any of the livestream modes being true forces the app to run in headless mode. * ``LIVESTREAM=1`` enables streaming via the Isaac `Native Livestream`_ extension. This allows users to connect through the Omniverse Streaming Client. * ``LIVESTREAM=2`` enables streaming via the `Websocket Livestream`_ extension. This allows users to connect in a browser using the WebSocket protocol. * ``LIVESTREAM=3`` enables streaming via the `WebRTC Livestream`_ extension. This allows users to connect in a browser using the WebRTC protocol. * **Offscreen Render**: If the environment variable ``OFFSCREEN_RENDER`` is set to 1, then the offscreen-render pipeline is enabled. This is useful for running the simulator without a GUI but still rendering the viewport and camera images. * ``OFFSCREEN_RENDER=1``: Enables the offscreen-render pipeline which allows users to render the scene without launching a GUI. .. note:: The off-screen rendering pipeline only works when used in conjunction with the :class:`omni.isaac.orbit.sim.SimulationContext` class. This is because the off-screen rendering pipeline enables flags that are internally used by the SimulationContext class. To set the environment variables, one can use the following command in the terminal: .. code:: bash export REMOTE_DEPLOYMENT=3 export OFFSCREEN_RENDER=1 # run the python script ./orbit.sh -p source/standalone/demo/play_quadrupeds.py Alternatively, one can set the environment variables to the python script directly: .. code:: bash REMOTE_DEPLOYMENT=3 OFFSCREEN_RENDER=1 ./orbit.sh -p source/standalone/demo/play_quadrupeds.py Overriding the environment variables ------------------------------------ The environment variables can be overridden in the python script itself using the :class:`AppLauncher`. These can be passed as a dictionary, a :class:`argparse.Namespace` object or as keyword arguments. When the passed arguments are not the default values, then they override the environment variables. The following snippet shows how use the :class:`AppLauncher` in different ways: .. code:: python import argparser from omni.isaac.orbit.app import AppLauncher # add argparse arguments parser = argparse.ArgumentParser() # add your own arguments # .... # add app launcher arguments for cli AppLauncher.add_app_launcher_args(parser) # parse arguments args = parser.parse_args() # launch omniverse isaac-sim app # -- Option 1: Pass the settings as a Namespace object app_launcher = AppLauncher(args).app # -- Option 2: Pass the settings as keywords arguments app_launcher = AppLauncher(headless=args.headless, livestream=args.livestream) # -- Option 3: Pass the settings as a dictionary app_launcher = AppLauncher(vars(args)) # -- Option 4: Pass no settings app_launcher = AppLauncher() # obtain the launched app simulation_app = app_launcher.app Simulation App Launcher ----------------------- .. autoclass:: AppLauncher :members: .. _livestream: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html .. _`Native Livestream`: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html#isaac-sim-setup-kit-remote .. _`Websocket Livestream`: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html#isaac-sim-setup-livestream-webrtc .. _`WebRTC Livestream`: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/manual_livestream_clients.html#isaac-sim-setup-livestream-websocket
4,248
reStructuredText
36.9375
152
0.734228
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.converters.rst
orbit.sim.converters ==================== .. automodule:: omni.isaac.orbit.sim.converters .. rubric:: Classes .. autosummary:: AssetConverterBase AssetConverterBaseCfg MeshConverter MeshConverterCfg UrdfConverter UrdfConverterCfg Asset Converter Base -------------------- .. autoclass:: AssetConverterBase :members: .. autoclass:: AssetConverterBaseCfg :members: :exclude-members: __init__ Mesh Converter -------------- .. autoclass:: MeshConverter :members: :inherited-members: :show-inheritance: .. autoclass:: MeshConverterCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__ URDF Converter -------------- .. autoclass:: UrdfConverter :members: :inherited-members: :show-inheritance: .. autoclass:: UrdfConverterCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__
933
reStructuredText
15.981818
47
0.633441
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.spawners.rst
orbit.sim.spawners ================== .. automodule:: omni.isaac.orbit.sim.spawners .. rubric:: Submodules .. autosummary:: shapes lights sensors from_files materials .. rubric:: Classes .. autosummary:: SpawnerCfg RigidObjectSpawnerCfg Spawners -------- .. autoclass:: SpawnerCfg :members: :exclude-members: __init__ .. autoclass:: RigidObjectSpawnerCfg :members: :show-inheritance: :exclude-members: __init__ Shapes ------ .. automodule:: omni.isaac.orbit.sim.spawners.shapes .. rubric:: Classes .. autosummary:: ShapeCfg CapsuleCfg ConeCfg CuboidCfg CylinderCfg SphereCfg .. autoclass:: ShapeCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_capsule .. autoclass:: CapsuleCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_cone .. autoclass:: ConeCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_cuboid .. autoclass:: CuboidCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_cylinder .. autoclass:: CylinderCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_sphere .. autoclass:: SphereCfg :members: :show-inheritance: :exclude-members: __init__, func Lights ------ .. automodule:: omni.isaac.orbit.sim.spawners.lights .. rubric:: Classes .. autosummary:: LightCfg CylinderLightCfg DiskLightCfg DistantLightCfg DomeLightCfg SphereLightCfg .. autofunction:: spawn_light .. autoclass:: LightCfg :members: :exclude-members: __init__, func .. autoclass:: CylinderLightCfg :members: :exclude-members: __init__, func .. autoclass:: DiskLightCfg :members: :exclude-members: __init__, func .. autoclass:: DistantLightCfg :members: :exclude-members: __init__, func .. autoclass:: DomeLightCfg :members: :exclude-members: __init__, func .. autoclass:: SphereLightCfg :members: :exclude-members: __init__, func Sensors ------- .. automodule:: omni.isaac.orbit.sim.spawners.sensors .. rubric:: Classes .. autosummary:: PinholeCameraCfg FisheyeCameraCfg .. autofunction:: spawn_camera .. autoclass:: PinholeCameraCfg :members: :exclude-members: __init__, func .. autoclass:: FisheyeCameraCfg :members: :exclude-members: __init__, func From Files ---------- .. automodule:: omni.isaac.orbit.sim.spawners.from_files .. rubric:: Classes .. autosummary:: UrdfFileCfg UsdFileCfg GroundPlaneCfg .. autofunction:: spawn_from_urdf .. autoclass:: UrdfFileCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_from_usd .. autoclass:: UsdFileCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_ground_plane .. autoclass:: GroundPlaneCfg :members: :exclude-members: __init__, func Materials --------- .. automodule:: omni.isaac.orbit.sim.spawners.materials .. rubric:: Classes .. autosummary:: VisualMaterialCfg PreviewSurfaceCfg MdlFileCfg GlassMdlCfg PhysicsMaterialCfg RigidBodyMaterialCfg Visual Materials ~~~~~~~~~~~~~~~~ .. autoclass:: VisualMaterialCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_preview_surface .. autoclass:: PreviewSurfaceCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_from_mdl_file .. autoclass:: MdlFileCfg :members: :exclude-members: __init__, func .. autoclass:: GlassMdlCfg :members: :exclude-members: __init__, func Physical Materials ~~~~~~~~~~~~~~~~~~ .. autoclass:: PhysicsMaterialCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_rigid_body_material .. autoclass:: RigidBodyMaterialCfg :members: :exclude-members: __init__, func
3,974
reStructuredText
15.772152
56
0.642929
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.controllers.rst
orbit.controllers ================= .. automodule:: omni.isaac.orbit.controllers .. rubric:: Classes .. autosummary:: DifferentialIKController DifferentialIKControllerCfg Differential Inverse Kinematics ------------------------------- .. autoclass:: DifferentialIKController :members: :inherited-members: :show-inheritance: .. autoclass:: DifferentialIKControllerCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
503
reStructuredText
18.384615
44
0.650099
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.envs.rst
orbit.envs ========== .. automodule:: omni.isaac.orbit.envs .. rubric:: Submodules .. autosummary:: mdp ui .. rubric:: Classes .. autosummary:: BaseEnv BaseEnvCfg ViewerCfg RLTaskEnv RLTaskEnvCfg Base Environment ---------------- .. autoclass:: BaseEnv :members: .. autoclass:: BaseEnvCfg :members: :exclude-members: __init__, class_type .. autoclass:: ViewerCfg :members: :exclude-members: __init__ RL Task Environment ------------------- .. autoclass:: RLTaskEnv :members: :inherited-members: :show-inheritance: .. autoclass:: RLTaskEnvCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
729
reStructuredText
13.6
42
0.593964
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.scene.rst
orbit.scene =========== .. automodule:: omni.isaac.orbit.scene .. rubric:: Classes .. autosummary:: InteractiveScene InteractiveSceneCfg interactive Scene ----------------- .. autoclass:: InteractiveScene :members: :undoc-members: :show-inheritance: .. autoclass:: InteractiveSceneCfg :members: :exclude-members: __init__
362
reStructuredText
14.124999
38
0.624309
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sensors.patterns.rst
orbit.sensors.patterns ====================== .. automodule:: omni.isaac.orbit.sensors.patterns .. rubric:: Classes .. autosummary:: PatternBaseCfg GridPatternCfg PinholeCameraPatternCfg BpearlPatternCfg Pattern Base ------------ .. autoclass:: PatternBaseCfg :members: :inherited-members: :exclude-members: __init__ Grid Pattern ------------ .. autofunction:: omni.isaac.orbit.sensors.patterns.grid_pattern .. autoclass:: GridPatternCfg :members: :inherited-members: :exclude-members: __init__, func Pinhole Camera Pattern ---------------------- .. autofunction:: omni.isaac.orbit.sensors.patterns.pinhole_camera_pattern .. autoclass:: PinholeCameraPatternCfg :members: :inherited-members: :exclude-members: __init__, func RS-Bpearl Pattern ----------------- .. autofunction:: omni.isaac.orbit.sensors.patterns.bpearl_pattern .. autoclass:: BpearlPatternCfg :members: :inherited-members: :exclude-members: __init__, func
1,006
reStructuredText
18.365384
74
0.649105
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.assets.rst
orbit.assets ============ .. automodule:: omni.isaac.orbit.assets .. rubric:: Classes .. autosummary:: AssetBase AssetBaseCfg RigidObject RigidObjectData RigidObjectCfg Articulation ArticulationData ArticulationCfg .. currentmodule:: omni.isaac.orbit.assets Asset Base ---------- .. autoclass:: AssetBase :members: .. autoclass:: AssetBaseCfg :members: :exclude-members: __init__, class_type Rigid Object ------------ .. autoclass:: RigidObject :members: :inherited-members: :show-inheritance: .. autoclass:: RigidObjectData :members: :inherited-members: :show-inheritance: :exclude-members: __init__ .. autoclass:: RigidObjectCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Articulation ------------ .. autoclass:: Articulation :members: :inherited-members: :show-inheritance: .. autoclass:: ArticulationData :members: :inherited-members: :show-inheritance: :exclude-members: __init__ .. autoclass:: ArticulationCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
1,202
reStructuredText
16.185714
42
0.639767
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.envs.mdp.rst
orbit.envs.mdp ============== .. automodule:: omni.isaac.orbit.envs.mdp Observations ------------ .. automodule:: omni.isaac.orbit.envs.mdp.observations :members: Actions ------- .. automodule:: omni.isaac.orbit.envs.mdp.actions .. automodule:: omni.isaac.orbit.envs.mdp.actions.actions_cfg :members: :show-inheritance: :exclude-members: __init__, class_type Events ------ .. automodule:: omni.isaac.orbit.envs.mdp.events :members: Commands -------- .. automodule:: omni.isaac.orbit.envs.mdp.commands .. automodule:: omni.isaac.orbit.envs.mdp.commands.commands_cfg :members: :show-inheritance: :exclude-members: __init__, class_type Rewards ------- .. automodule:: omni.isaac.orbit.envs.mdp.rewards :members: Terminations ------------ .. automodule:: omni.isaac.orbit.envs.mdp.terminations :members: Curriculum ---------- .. automodule:: omni.isaac.orbit.envs.mdp.curriculums :members:
948
reStructuredText
16.254545
63
0.649789
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.schemas.rst
orbit.sim.schemas ================= .. automodule:: omni.isaac.orbit.sim.schemas .. rubric:: Classes .. autosummary:: ArticulationRootPropertiesCfg RigidBodyPropertiesCfg CollisionPropertiesCfg MassPropertiesCfg JointDrivePropertiesCfg FixedTendonPropertiesCfg .. rubric:: Functions .. autosummary:: define_articulation_root_properties modify_articulation_root_properties define_rigid_body_properties modify_rigid_body_properties activate_contact_sensors define_collision_properties modify_collision_properties define_mass_properties modify_mass_properties modify_joint_drive_properties modify_fixed_tendon_properties Articulation Root ----------------- .. autoclass:: ArticulationRootPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_articulation_root_properties .. autofunction:: modify_articulation_root_properties Rigid Body ---------- .. autoclass:: RigidBodyPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_rigid_body_properties .. autofunction:: modify_rigid_body_properties .. autofunction:: activate_contact_sensors Collision --------- .. autoclass:: CollisionPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_collision_properties .. autofunction:: modify_collision_properties Mass ---- .. autoclass:: MassPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_mass_properties .. autofunction:: modify_mass_properties Joint Drive ----------- .. autoclass:: JointDrivePropertiesCfg :members: :exclude-members: __init__ .. autofunction:: modify_joint_drive_properties Fixed Tendon ------------ .. autoclass:: FixedTendonPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: modify_fixed_tendon_properties
1,877
reStructuredText
19.637362
53
0.706446
NVIDIA-Omniverse/orbit/docs/source/features/actuators.rst
.. _feature-actuators: Actuators ========= An articulated system comprises of actuated joints, also called the degrees of freedom (DOF). In a physical system, the actuation typically happens either through active components, such as electric or hydraulic motors, or passive components, such as springs. These components can introduce certain non-linear characteristics which includes delays or maximum producible velocity or torque. In simulation, the joints are either position, velocity, or torque-controlled. For position and velocity control, the physics engine internally implements a spring-damp (PD) controller which computes the torques applied on the actuated joints. In torque-control, the commands are set directly as the joint efforts. While this mimics an ideal behavior of the joint mechanism, it does not truly model how the drives work in the physical world. Thus, we provide a mechanism to inject external models to compute the joint commands that would represent the physical robot's behavior. Actuator models --------------- We name two different types of actuator models: 1. **implicit**: corresponds to the ideal simulation mechanism (provided by physics engine). 2. **explicit**: corresponds to external drive models (implemented by user). The explicit actuator model performs two steps: 1) it computes the desired joint torques for tracking the input commands, and 2) it clips the desired torques based on the motor capabilities. The clipped torques are the desired actuation efforts that are set into the simulation. As an example of an ideal explicit actuator model, we provide the :class:`omni.isaac.orbit.actuators.IdealPDActuator` class, which implements a PD controller with feed-forward effort, and simple clipping based on the configured maximum effort: .. math:: \tau_{j, computed} & = k_p * (q - q_{des}) + k_d * (\dot{q} - \dot{q}_{des}) + \tau_{ff} \\ \tau_{j, applied} & = clip(\tau_{computed}, -\tau_{j, max}, \tau_{j, max}) where, :math:`k_p` and :math:`k_d` are joint stiffness and damping gains, :math:`q` and :math:`\dot{q}` are the current joint positions and velocities, :math:`q_{des}`, :math:`\dot{q}_{des}` and :math:`\tau_{ff}` are the desired joint positions, velocities and torques commands. The parameters :math:`\gamma` and :math:`\tau_{motor, max}` are the gear box ratio and the maximum motor effort possible. Actuator groups --------------- The actuator models by themselves are computational blocks that take as inputs the desired joint commands and output the the joint commands to apply into the simulator. They do not contain any knowledge about the joints they are acting on themselves. These are handled by the :class:`omni.isaac.orbit.assets.Articulation` class, which wraps around the physics engine's articulation class. Actuator are collected as a set of actuated joints on an articulation that are using the same actuator model. For instance, the quadruped, ANYmal-C, uses series elastic actuator, ANYdrive 3.0, for all its joints. This grouping configures the actuator model for those joints, translates the input commands to the joint level commands, and returns the articulation action to set into the simulator. Having an arm with a different actuator model, such as a DC motor, would require configuring a different actuator group. The following figure shows the actuator groups for a legged mobile manipulator: .. image:: ../_static/actuator_groups.svg :width: 600 :align: center :alt: Actuator groups for a legged mobile manipulator .. seealso:: We provide implementations for various explicit actuator models. These are detailed in `omni.isaac.orbit.actuators <../api/orbit.actuators.html>`_ sub-package.
3,727
reStructuredText
51.507042
117
0.763885
NVIDIA-Omniverse/orbit/docs/source/features/motion_generators.rst
Motion Generators ================= Robotic tasks are typically defined in task-space in terms of desired end-effector trajectory, while control actions are executed in the joint-space. This naturally leads to *joint-space* and *task-space* (operational-space) control methods. However, successful execution of interaction tasks using motion control often requires an accurate model of both the robot manipulator as well as its environment. While a sufficiently precise manipulator's model might be known, detailed description of environment is hard to obtain :cite:p:`siciliano2009force`. Planning errors caused by this mismatch can be overcome by introducing a *compliant* behavior during interaction. While compliance is achievable passively through robot's structure (such as elastic actuators, soft robot arms), we are more interested in controller designs that focus on active interaction control. These are broadly categorized into: 1. **impedance control:** indirect control method where motion deviations caused during interaction relates to contact force as a mass-spring-damper system with adjustable parameters (stiffness and damping). A specialized case of this is *stiffness* control where only the static relationship between position error and contact force is considered. 2. **hybrid force/motion control:** active control method which controls motion and force along unconstrained and constrained task directions respectively. Among the various schemes for hybrid motion control, the provided implementation is based on inverse dynamics control in the operational space :cite:p:`khatib1987osc`. .. note:: To provide an even broader set of motion generators, we welcome contributions from the community. If you are interested, please open an issue to start a discussion! Joint-space controllers ----------------------- Torque control ~~~~~~~~~~~~~~ Action dimensions: ``"n"`` (number of joints) In torque control mode, the input actions are directly set as feed-forward joint torque commands, i.e. at every time-step, .. math:: \tau = \tau_{des} Thus, this control mode is achievable by setting the command type for the actuator group, via the :class:`ActuatorControlCfg` class, to ``"t_abs"``. Velocity control ~~~~~~~~~~~~~~~~ Action dimensions: ``"n"`` (number of joints) In velocity control mode, a proportional control law is required to reduce the error between the current and desired joint velocities. Based on input actions, the joint torques commands are computed as: .. math:: \tau = k_d (\dot{q}_{des} - \dot{q}) where :math:`k_d` are the gains parsed from configuration. This control mode is achievable by setting the command type for the actuator group, via the :class:`ActuatorControlCfg` class, to ``"v_abs"`` or ``"v_rel"``. .. attention:: While performing velocity control, in many cases, gravity compensation is required to ensure better tracking of the command. In this case, we suggest disabling gravity for the links in the articulation in simulation. Position control with fixed impedance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"n"`` (number of joints) In position control mode, a proportional-damping (PD) control law is employed to track the desired joint positions and ensuring the articulation remains still at the desired location (i.e., desired joint velocities are zero). Based on the input actions, the joint torque commands are computed as: .. math:: \tau = k_p (q_{des} - q) - k_d \dot{q} where :math:`k_p` and :math:`k_d` are the gains parsed from configuration. In its simplest above form, the control mode is achievable by setting the command type for the actuator group, via the :class:`ActuatorControlCfg` class, to ``"p_abs"`` or ``"p_rel"``. However, a more complete formulation which considers the dynamics of the articulation would be: .. math:: \tau = M \left( k_p (q_{des} - q) - k_d \dot{q} \right) + g where :math:`M` is the joint-space inertia matrix of size :math:`n \times n`, and :math:`g` is the joint-space gravity vector. This implementation is available through the :class:`JointImpedanceController` class by setting the impedance mode to ``"fixed"``. The gains :math:`k_p` are parsed from the input configuration and :math:`k_d` are computed while considering the system as a decoupled point-mass oscillator, i.e., .. math:: k_d = 2 \sqrt{k_p} \times D where :math:`D` is the damping ratio of the system. Critical damping is achieved for :math:`D = 1`, overcritical damping for :math:`D > 1` and undercritical damping for :math:`D < 1`. Additionally, it is possible to disable the inertial or gravity compensation in the controller by setting the flags :attr:`inertial_compensation` and :attr:`gravity_compensation` in the configuration to :obj:`False`, respectively. Position control with variable stiffness ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"2n"`` (number of joints) In stiffness control, the same formulation as above is employed, however, the gains :math:`k_p` are part of the input commands. This implementation is available through the :class:`JointImpedanceController` class by setting the impedance mode to ``"variable_kp"``. Position control with variable impedance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"3n"`` (number of joints) In impedance control, the same formulation as above is employed, however, both :math:`k_p` and :math:`k_d` are part of the input commands. This implementation is available through the :class:`JointImpedanceController` class by setting the impedance mode to ``"variable"``. Task-space controllers ---------------------- Differential inverse kinematics (IK) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"3"`` (relative/absolute position), ``"6"`` (relative pose), or ``"7"`` (absolute pose) Inverse kinematics converts the task-space tracking error to joint-space error. In its most typical implementation, the pose error in the task-sace, :math:`\Delta \chi_e = (\Delta p_e, \Delta \phi_e)`, is computed as the cartesian distance between the desired and current task-space positions, and the shortest distance in :math:`\mathbb{SO}(3)` between the desired and current task-space orientations. Using the geometric Jacobian :math:`J_{eO} \in \mathbb{R}^{6 \times n}`, that relates task-space velocity to joint-space velocities, we design the control law to obtain the desired joint positions as: .. math:: q_{des} = q + \eta J_{eO}^{-} \Delta \chi_e where :math:`\eta` is a scaling parameter and :math:`J_{eO}^{-}` is the pseudo-inverse of the Jacobian. It is possible to compute the pseudo-inverse of the Jacobian using different formulations: * Moore-Penrose pseduo-inverse: :math:`A^{-} = A^T(AA^T)^{-1}`. * Levenberg-Marquardt pseduo-inverse (damped least-squares): :math:`A^{-} = A^T (AA^T + \lambda \mathbb{I})^{-1}`. * Tanspose pseudo-inverse: :math:`A^{-} = A^T`. * Adaptive singular-vale decomposition (SVD) pseduo-inverse from :cite:t:`buss2004ik`. These implementations are available through the :class:`DifferentialInverseKinematics` class. Impedance controller ~~~~~~~~~~~~~~~~~~~~ It uses task-space pose error and Jacobian to compute join torques through mass-spring-damper system with a) fixed stiffness, b) variable stiffness (stiffness control), and c) variable stiffness and damping (impedance control). Operational-space controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Similar to task-space impedance control but uses the Equation of Motion (EoM) for computing the task-space force Closed-loop proportional force controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It uses a proportional term to track the desired wrench command with respect to current wrench at the end-effector. Hybrid force-motion controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It combines closed-loop force control and operational-space motion control to compute the desired wrench at the end-effector. It uses selection matrices that define the unconstrainted and constrained task directions. Reactive planners ----------------- Typical task-space controllers do not account for motion constraints such as joint limits, self-collision and environment collision. Instead they rely on high-level planners (such as RRT) to handle these non-Euclidean constraints and give joint/task-space way-points to the controller. However, these methods are often conservative and have undesirable deceleration when close to an object. More recently, different approaches combine the constraints directly into an optimization problem, thereby providing a holistic solution for motion generation and control. We currently support the following planners: - **RMPFlow (lula):** An acceleration-based policy that composes various Reimannian Motion Policies (RMPs) to solve a hierarchy of tasks :cite:p:`cheng2021rmpflow`. It is capable of performing dynamic collision avoidance while navigating the end-effector to a target. - **MPC (OCS2):** A receding horizon control policy based on sequential linear-quadratic (SLQ) programming. It formulates various constraints into a single optimization problem via soft-penalties and uses automatic differentiation to compute derivatives of the system dynamics, constraints and costs. Currently, we support the MPC formulation for end-effector trajectory tracking in fixed-arm and mobile manipulators. The formulation considers a kinematic system model with joint limits and self-collision avoidance :cite:p:`mittal2021articulated`. .. warning:: We wrap around the python bindings for these reactive planners to perform a batched computing of robot actions. However, their current implementations are CPU-based which may cause certain slowdown for learning.
9,828
reStructuredText
41.734782
132
0.737993
NVIDIA-Omniverse/orbit/docs/source/features/environments.rst
Environments ============ The following lists comprises of all the RL tasks implementations that are available in Orbit. While we try to keep this list up-to-date, you can always get the latest list of environments by running the following command: .. code-block:: bash ./orbit.sh -p source/standalone/environments/list_envs.py We are actively working on adding more environments to the list. If you have any environments that you would like to add to Orbit, please feel free to open a pull request! Classic ------- Classic environments that are based on IsaacGymEnvs implementation of MuJoCo-style environments. .. table:: :widths: 33 37 30 +------------------+-----------------------------+-------------------------------------------------------------------------+ | World | Environment ID | Description | +==================+=============================+=========================================================================+ | |humanoid| | |humanoid-link| | Move towards a direction with the MuJoCo humanoid robot | +------------------+-----------------------------+-------------------------------------------------------------------------+ | |ant| | |ant-link| | Move towards a direction with the MuJoCo ant robot | +------------------+-----------------------------+-------------------------------------------------------------------------+ | |cartpole| | |cartpole-link| | Move the cart to keep the pole upwards in the classic cartpole control | +------------------+-----------------------------+-------------------------------------------------------------------------+ .. |humanoid| image:: ../_static/tasks/classic/humanoid.jpg .. |ant| image:: ../_static/tasks/classic/ant.jpg .. |cartpole| image:: ../_static/tasks/classic/cartpole.jpg .. |humanoid-link| replace:: `Isaac-Humanoid-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/humanoid_env_cfg.py>`__ .. |ant-link| replace:: `Isaac-Ant-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/ant_env_cfg.py>`__ .. |cartpole-link| replace:: `Isaac-Cartpole-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/cartpole_env_cfg.py>`__ Manipulation ------------ Environments based on fixed-arm manipulation tasks. For many of these tasks, we include configurations with different arm action spaces. For example, for the reach environment: * |lift-cube-link|: Franka arm with joint position control * |lift-cube-ik-abs-link|: Franka arm with absolute IK control * |lift-cube-ik-rel-link|: Franka arm with relative IK control .. table:: :widths: 33 37 30 +----------------+---------------------+-----------------------------------------------------------------------------+ | World | Environment ID | Description | +================+=====================+=============================================================================+ | |reach-franka| | |reach-franka-link| | Move the end-effector to a sampled target pose with the Franka robot | +----------------+---------------------+-----------------------------------------------------------------------------+ | |reach-ur10| | |reach-ur10-link| | Move the end-effector to a sampled target pose with the UR10 robot | +----------------+---------------------+-----------------------------------------------------------------------------+ | |lift-cube| | |lift-cube-link| | Pick a cube and bring it to a sampled target position with the Franka robot | +----------------+---------------------+-----------------------------------------------------------------------------+ | |cabi-franka| | |cabi-franka-link| | Grasp the handle of a cabinet's drawer and open it with the Franka robot | +----------------+---------------------+-----------------------------------------------------------------------------+ .. |reach-franka| image:: ../_static/tasks/manipulation/franka_reach.jpg .. |reach-ur10| image:: ../_static/tasks/manipulation/ur10_reach.jpg .. |lift-cube| image:: ../_static/tasks/manipulation/franka_lift.jpg .. |cabi-franka| image:: ../_static/tasks/manipulation/franka_open_drawer.jpg .. |reach-franka-link| replace:: `Isaac-Reach-Franka-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/franka/joint_pos_env_cfg.py>`__ .. |reach-ur10-link| replace:: `Isaac-Reach-UR10-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/ur_10/joint_pos_env_cfg.py>`__ .. |lift-cube-link| replace:: `Isaac-Lift-Cube-Franka-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/joint_pos_env_cfg.py>`__ .. |lift-cube-ik-abs-link| replace:: `Isaac-Lift-Cube-Franka-IK-Abs-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/ik_abs_env_cfg.py>`__ .. |lift-cube-ik-rel-link| replace:: `Isaac-Lift-Cube-Franka-IK-Rel-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/ik_rel_env_cfg.py>`__ .. |cabi-franka-link| replace:: `Isaac-Open-Drawer-Franka-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/cabinet/config/franka/joint_pos_env_cfg.py>`__ Locomotion ---------- Environments based on legged locomotion tasks. .. table:: :widths: 33 37 30 +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | World | Environment ID | Description | +==============================+==============================================+=========================================================================+ | |velocity-flat-anymal-b| | |velocity-flat-anymal-b-link| | Track a velocity command on flat terrain with the Anymal B robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-anymal-b| | |velocity-rough-anymal-b-link| | Track a velocity command on rough terrain with the Anymal B robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-anymal-c| | |velocity-flat-anymal-c-link| | Track a velocity command on flat terrain with the Anymal C robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-anymal-c| | |velocity-rough-anymal-c-link| | Track a velocity command on rough terrain with the Anymal C robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-anymal-d| | |velocity-flat-anymal-d-link| | Track a velocity command on flat terrain with the Anymal D robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-anymal-d| | |velocity-rough-anymal-d-link| | Track a velocity command on rough terrain with the Anymal D robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-unitree-a1| | |velocity-flat-unitree-a1-link| | Track a velocity command on flat terrain with the Unitree A1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-unitree-a1| | |velocity-rough-unitree-a1-link| | Track a velocity command on rough terrain with the Unitree A1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-unitree-go1| | |velocity-flat-unitree-go1-link| | Track a velocity command on flat terrain with the Unitree Go1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-unitree-go1| | |velocity-rough-unitree-go1-link| | Track a velocity command on rough terrain with the Unitree Go1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-unitree-go2| | |velocity-flat-unitree-go2-link| | Track a velocity command on flat terrain with the Unitree Go2 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-unitree-go2| | |velocity-rough-unitree-go2-link| | Track a velocity command on rough terrain with the Unitree Go2 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ .. |velocity-flat-anymal-b-link| replace:: `Isaac-Velocity-Flat-Anymal-B-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_b/flat_env_cfg.py>`__ .. |velocity-rough-anymal-b-link| replace:: `Isaac-Velocity-Rough-Anymal-B-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_b/rough_env_cfg.py>`__ .. |velocity-flat-anymal-c-link| replace:: `Isaac-Velocity-Flat-Anymal-C-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_c/flat_env_cfg.py>`__ .. |velocity-rough-anymal-c-link| replace:: `Isaac-Velocity-Rough-Anymal-C-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_c/rough_env_cfg.py>`__ .. |velocity-flat-anymal-d-link| replace:: `Isaac-Velocity-Flat-Anymal-D-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_d/flat_env_cfg.py>`__ .. |velocity-rough-anymal-d-link| replace:: `Isaac-Velocity-Rough-Anymal-D-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_d/rough_env_cfg.py>`__ .. |velocity-flat-unitree-a1-link| replace:: `Isaac-Velocity-Flat-Unitree-A1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_a1/flat_env_cfg.py>`__ .. |velocity-rough-unitree-a1-link| replace:: `Isaac-Velocity-Rough-Unitree-A1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_a1/rough_env_cfg.py>`__ .. |velocity-flat-unitree-go1-link| replace:: `Isaac-Velocity-Flat-Unitree-Go1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go1/flat_env_cfg.py>`__ .. |velocity-rough-unitree-go1-link| replace:: `Isaac-Velocity-Rough-Unitree-Go1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go1/rough_env_cfg.py>`__ .. |velocity-flat-unitree-go2-link| replace:: `Isaac-Velocity-Flat-Unitree-Go2-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go2/flat_env_cfg.py>`__ .. |velocity-rough-unitree-go2-link| replace:: `Isaac-Velocity-Rough-Unitree-Go2-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go2/rough_env_cfg.py>`__ .. |velocity-flat-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_flat.jpg .. |velocity-rough-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_rough.jpg .. |velocity-flat-anymal-c| image:: ../_static/tasks/locomotion/anymal_c_flat.jpg .. |velocity-rough-anymal-c| image:: ../_static/tasks/locomotion/anymal_c_rough.jpg .. |velocity-flat-anymal-d| image:: ../_static/tasks/locomotion/anymal_d_flat.jpg .. |velocity-rough-anymal-d| image:: ../_static/tasks/locomotion/anymal_d_rough.jpg .. |velocity-flat-unitree-a1| image:: ../_static/tasks/locomotion/a1_flat.jpg .. |velocity-rough-unitree-a1| image:: ../_static/tasks/locomotion/a1_rough.jpg .. |velocity-flat-unitree-go1| image:: ../_static/tasks/locomotion/go1_flat.jpg .. |velocity-rough-unitree-go1| image:: ../_static/tasks/locomotion/go1_rough.jpg .. |velocity-flat-unitree-go2| image:: ../_static/tasks/locomotion/go2_flat.jpg .. |velocity-rough-unitree-go2| image:: ../_static/tasks/locomotion/go2_rough.jpg
14,487
reStructuredText
95.586666
260
0.530752
NVIDIA-Omniverse/orbit/docs/source/deployment/cluster.rst
.. _deployment-cluster: Cluster Guide ============= Clusters are a great way to speed up training and evaluation of learning algorithms. While the Orbit Docker image can be used to run jobs on a cluster, many clusters only support singularity images. This is because `singularity`_ is designed for ease-of-use on shared multi-user systems and high performance computing (HPC) environments. It does not require root privileges to run containers and can be used to run user-defined containers. Singularity is compatible with all Docker images. In this section, we describe how to convert the Orbit Docker image into a singularity image and use it to submit jobs to a cluster. .. attention:: Cluster setup varies across different institutions. The following instructions have been tested on the `ETH Zurich Euler`_ cluster, which uses the SLURM workload manager. The instructions may need to be adapted for other clusters. If you have successfully adapted the instructions for another cluster, please consider contributing to the documentation. Setup Instructions ------------------ In order to export the Docker Image to a singularity image, `apptainer`_ is required. A detailed overview of the installation procedure for ``apptainer`` can be found in its `documentation`_. For convenience, we summarize the steps here for a local installation: .. code:: bash sudo apt update sudo apt install -y software-properties-common sudo add-apt-repository -y ppa:apptainer/ppa sudo apt update sudo apt install -y apptainer For simplicity, we recommend that an SSH connection is set up between the local development machine and the cluster. Such a connection will simplify the file transfer and prevent the user cluster password from being requested multiple times. .. attention:: The workflow has been tested with ``apptainer version 1.2.5-1.el7`` and ``docker version 24.0.7``. - ``apptainer``: There have been reported binding issues with previous versions (such as ``apptainer version 1.1.3-1.el7``). Please ensure that you are using the latest version. - ``Docker``: The latest versions (``25.x``) cannot be used as they are not compatible yet with apptainer/ singularity. We are waiting for an update from the apptainer team. To track this issue, please check the `forum post`_. Configuring the cluster parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ First, you need to configure the cluster-specific parameters in ``docker/.env.base`` file. The following describes the parameters that need to be configured: - ``CLUSTER_ISAAC_SIM_CACHE_DIR``: The directory on the cluster where the Isaac Sim cache is stored. This directory has to end on ``docker-isaac-sim``. This directory will be copied to the compute node and mounted into the singularity container. It should increase the speed of starting the simulation. - ``CLUSTER_ORBIT_DIR``: The directory on the cluster where the orbit code is stored. This directory has to end on ``orbit``. This directory will be copied to the compute node and mounted into the singularity container. When a job is submitted, the latest local changes will be copied to the cluster. - ``CLUSTER_LOGIN``: The login to the cluster. Typically, this is the user and cluster names, e.g., ``your_user@euler.ethz.ch``. - ``CLUSTER_SIF_PATH``: The path on the cluster where the singularity image will be stored. The image will be copied to the compute node but not uploaded again to the cluster when a job is submitted. - ``CLUSTER_PYTHON_EXECUTABLE``: The path within orbit to the Python executable that should be executed in the submitted job. Exporting to singularity image ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Next, we need to export the Docker image to a singularity image and upload it to the cluster. This step is only required once when the first job is submitted or when the Docker image is updated. For instance, due to an upgrade of the Isaac Sim version, or additional requirements for your project. To export to a singularity image, execute the following command: .. code:: bash ./docker/container.sh push [profile] This command will create a singularity image under ``docker/exports`` directory and upload it to the defined location on the cluster. Be aware that creating the singularity image can take a while. ``[profile]`` is an optional argument that specifies the container profile to be used. If no profile is specified, the default profile ``base`` will be used. .. note:: By default, the singularity image is created without root access by providing the ``--fakeroot`` flag to the ``apptainer build`` command. In case the image creation fails, you can try to create it with root access by removing the flag in ``docker/container.sh``. Job Submission and Execution ---------------------------- Defining the job parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The job parameters are defined inside the ``docker/cluster/submit_job.sh``. A typical SLURM operation requires specifying the number of CPUs and GPUs, the memory, and the time limit. For more information, please check the `SLURM documentation`_. The default configuration is as follows: .. literalinclude:: ../../../docker/cluster/submit_job.sh :language: bash :lines: 12-19 :linenos: :lineno-start: 12 An essential requirement for the cluster is that the compute node has access to the internet at all times. This is required to load assets from the Nucleus server. For some cluster architectures, extra modules must be loaded to allow internet access. For instance, on ETH Zurich Euler cluster, the ``eth_proxy`` module needs to be loaded. This can be done by adding the following line to the ``submit_job.sh`` script: .. literalinclude:: ../../../docker/cluster/submit_job.sh :language: bash :lines: 3-5 :linenos: :lineno-start: 3 Submitting a job ~~~~~~~~~~~~~~~~ To submit a job on the cluster, the following command can be used: .. code:: bash ./docker/container.sh job [profile] "argument1" "argument2" ... This command will copy the latest changes in your code to the cluster and submit a job. Please ensure that your Python executable's output is stored under ``orbit/logs`` as this directory will be copied again from the compute node to ``CLUSTER_ORBIT_DIR``. ``[profile]`` is an optional argument that specifies which singularity image corresponding to the container profile will be used. If no profile is specified, the default profile ``base`` will be used. The profile has be defined directlty after the ``job`` command. All other arguments are passed to the Python executable. If no profile is defined, all arguments are passed to the Python executable. The training arguments are passed to the Python executable. As an example, the standard ANYmal rough terrain locomotion training can be executed with the following command: .. code:: bash ./docker/container.sh job --task Isaac-Velocity-Rough-Anymal-C-v0 --headless --video --offscreen_render The above will, in addition, also render videos of the training progress and store them under ``orbit/logs`` directory. .. note:: The ``./docker/container.sh job`` command will copy the latest changes in your code to the cluster. However, it will not delete any files that have been deleted locally. These files will still exist on the cluster which can lead to issues. In this case, we recommend removing the ``CLUSTER_ORBIT_DIR`` directory on the cluster and re-run the command. .. _Singularity: https://docs.sylabs.io/guides/2.6/user-guide/index.html .. _ETH Zurich Euler: https://scicomp.ethz.ch/wiki/Euler .. _apptainer: https://apptainer.org/ .. _documentation: www.apptainer.org/docs/admin/main/installation.html#install-ubuntu-packages .. _SLURM documentation: www.slurm.schedmd.com/sbatch.html .. _forum post: https://forums.docker.com/t/trouble-after-upgrade-to-docker-ce-25-0-1-on-debian-12/139613
7,938
reStructuredText
43.105555
119
0.745528
NVIDIA-Omniverse/orbit/docs/source/deployment/run_docker_example.rst
Running an example with Docker ============================== From the root of the ``orbit`` repository, the ``docker`` directory contains all the Docker relevant files. These include the three files (**Dockerfile**, **docker-compose.yaml**, **.env**) which are used by Docker, and an additional script that we use to interface with them, **container.sh**. In this tutorial, we will learn how to use the Orbit Docker container for development. For a detailed description of the Docker setup, including installation and obtaining access to an Isaac Sim image, please reference the :ref:`deployment-docker`. For a description of Docker in general, please refer to `their official documentation <https://docs.docker.com/get-started/overview/>`_. Building the Container ~~~~~~~~~~~~~~~~~~~~~~ To build the Orbit container from the root of the Orbit repository, we will run the following: .. code-block:: console ./docker/container.sh start The terminal will first pull the base IsaacSim image, build the Orbit image's additional layers on top of it, and run the Orbit container. This should take several minutes upon the first build but will be shorter in subsequent runs as Docker's caching prevents repeated work. If we run the command ``docker container ls`` on the terminal, the output will list the containers that are running on the system. If everything has been set up correctly, a container with the ``NAME`` **orbit** should appear, similar to below: .. code-block:: console CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 483d1d5e2def orbit "bash" 30 seconds ago Up 30 seconds orbit Once the container is up and running, we can enter it from our terminal. .. code-block:: console ./docker/container.sh enter On entering the Orbit container, we are in the terminal as the superuser, ``root``. This environment contains a copy of the Orbit repository, but also has access to the directories and libraries of Isaac Sim. We can run experiments from this environment using a few convenient aliases that have been put into the ``root`` **.bashrc**. For instance, we have made the **orbit.sh** script usable from anywhere by typing its alias ``orbit``. Additionally in the container, we have `bind mounted`_ the ``orbit/source`` directory from the host machine. This means that if we modify files under this directory from an editor on the host machine, the changes are reflected immediately within the container without requiring us to rebuild the Docker image. We will now run a sample script from within the container to demonstrate how to extract artifacts from the Orbit Docker container. The Code ~~~~~~~~ The tutorial corresponds to the ``log_time.py`` script in the ``orbit/source/standalone/tutorials/00_sim`` directory. .. dropdown:: Code for log_time.py :icon: code .. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py :language: python :emphasize-lines: 46-55, 72-79 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ The Orbit Docker container has several `volumes`_ to facilitate persistent storage between the host computer and the container. One such volume is the ``/workspace/orbit/logs`` directory. The ``log_time.py`` script designates this directory as the location to which a ``log.txt`` should be written: .. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py :language: python :start-at: # Specify that the logs must be in logs/docker_tutorial :end-at: print(f"[INFO] Logging experiment to directory: {log_dir_path}") As the comments note, :func:`os.path.abspath()` will prepend ``/workspace/orbit`` because in the Docker container all python execution is done through ``/workspace/orbit/orbit.sh``. The output will be a file, ``log.txt``, with the ``sim_time`` written on a newline at every simulation step: .. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py :language: python :start-at: # Prepare to count sim_time :end-at: sim_time += sim_dt Executing the Script ~~~~~~~~~~~~~~~~~~~~ We will execute the script to produce a log, adding a ``--headless`` flag to our execution to prevent a GUI: .. code-block:: bash orbit -p source/standalone/tutorials/00_sim/log_time.py --headless Now ``log.txt`` will have been produced at ``/workspace/orbit/logs/docker_tutorial``. If we exit the container by typing ``exit``, we will return to ``orbit/docker`` in our host terminal environment. We can then enter the following command to retrieve our logs from the Docker container and put them on our host machine: .. code-block:: console ./container.sh copy We will see a terminal readout reporting the artifacts we have retrieved from the container. If we navigate to ``/orbit/docker/artifacts/logs/docker_tutorial``, we will see a copy of the ``log.txt`` file which was produced by the script above. Each of the directories under ``artifacts`` corresponds to Docker `volumes`_ mapped to directories within the container and the ``container.sh copy`` command copies them from those `volumes`_ to these directories. We could return to the Orbit Docker terminal environment by running ``container.sh enter`` again, but we have retrieved our logs and wish to go inspect them. We can stop the Orbit Docker container with the following command: .. code-block:: console ./container.sh stop This will bring down the Docker Orbit container. The image will persist and remain available for further use, as will the contents of any `volumes`_. If we wish to free up the disk space taken by the image, (~20.1GB), and do not mind repeating the build process when we next run ``./container.sh start``, we may enter the following command to delete the **orbit** image: .. code-block:: console docker image rm orbit A subsequent run of ``docker image ls``` will show that the image tagged **orbit** is now gone. We can repeat the process for the underlying NVIDIA container if we wish to free up more space. If a more powerful method of freeing resources from Docker is desired, please consult the documentation for the `docker prune`_ commands. .. _volumes: https://docs.docker.com/storage/volumes/ .. _bind mounted: https://docs.docker.com/storage/bind-mounts/ .. _docker prune: https://docs.docker.com/config/pruning/
6,373
reStructuredText
43.887324
138
0.73529
NVIDIA-Omniverse/orbit/docs/source/deployment/docker.rst
.. _deployment-docker: Docker Guide ============ .. caution:: Due to the dependency on Isaac Sim docker image, by running this container you are implicitly agreeing to the `NVIDIA Omniverse EULA`_. If you do not agree to the EULA, do not run this container. Setup Instructions ------------------ .. note:: The following steps are taken from the NVIDIA Omniverse Isaac Sim documentation on `container installation`_. They have been added here for the sake of completeness. Docker and Docker Compose ~~~~~~~~~~~~~~~~~~~~~~~~~ We have tested the container using Docker Engine version 26.0.0 and Docker Compose version 2.25.0 We recommend using these versions or newer. * To install Docker, please follow the instructions for your operating system on the `Docker website`_. * To install Docker Compose, please follow the instructions for your operating system on the `docker compose`_ page. * Follow the post-installation steps for Docker on the `post-installation steps`_ page. These steps allow you to run Docker without using ``sudo``. * To build and run GPU-accelerated containers, you also need install the `NVIDIA Container Toolkit`_. Please follow the instructions on the `Container Toolkit website`_ for installation steps. Obtaining the Isaac Sim Container ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Get access to the `Isaac Sim container`_ by joining the NVIDIA Developer Program credentials. * Generate your `NGC API key`_ to access locked container images from NVIDIA GPU Cloud (NGC). * This step requires you to create an NGC account if you do not already have one. * You would also need to install the NGC CLI to perform operations from the command line. * Once you have your generated API key and have installed the NGC CLI, you need to log in to NGC from the terminal. .. code:: bash ngc config set * Use the command line to pull the Isaac Sim container image from NGC. .. code:: bash docker login nvcr.io * For the username, enter ``$oauthtoken`` exactly as shown. It is a special username that is used to authenticate with NGC. .. code:: text Username: $oauthtoken Password: <Your NGC API Key> Directory Organization ---------------------- The root of the Orbit repository contains the ``docker`` directory that has various files and scripts needed to run Orbit inside a Docker container. A subset of these are summarized below: * ``Dockerfile.base``: Defines the orbit image by overlaying Orbit dependencies onto the Isaac Sim Docker image. ``Dockerfiles`` which end with something else, (i.e. ``Dockerfile.ros2``) build an `image_extension <#orbit-image-extensions>`_. * ``docker-compose.yaml``: Creates mounts to allow direct editing of Orbit code from the host machine that runs the container. It also creates several named volumes such as ``isaac-cache-kit`` to store frequently re-used resources compiled by Isaac Sim, such as shaders, and to retain logs, data, and documents. * ``base.env``: Stores environment variables required for the ``base`` build process and the container itself. ``.env`` files which end with something else (i.e. ``.env.ros2``) define these for `image_extension <#orbit-image-extensions>`_. * ``container.sh``: A script that wraps the ``docker compose`` command to build the image and run the container. Running the Container --------------------- .. note:: The docker container copies all the files from the repository into the container at the location ``/workspace/orbit`` at build time. This means that any changes made to the files in the container would not normally be reflected in the repository after the image has been built, i.e. after ``./container.sh start`` is run. For a faster development cycle, we mount the following directories in the Orbit repository into the container so that you can edit their files from the host machine: * ``source``: This is the directory that contains the Orbit source code. * ``docs``: This is the directory that contains the source code for Orbit documentation. This is overlaid except for the ``_build`` subdirectory where build artifacts are stored. The script ``container.sh`` wraps around three basic ``docker compose`` commands. Each can accept an `image_extension argument <#orbit-image-extensions>`_, or else they will default to image_extension ``base``: 1. ``start``: This builds the image and brings up the container in detached mode (i.e. in the background). 2. ``enter``: This begins a new bash process in an existing orbit container, and which can be exited without bringing down the container. 3. ``copy``: This copies the ``logs``, ``data_storage`` and ``docs/_build`` artifacts, from the ``orbit-logs``, ``orbit-data`` and ``orbit-docs`` volumes respectively, to the ``docker/artifacts`` directory. These artifacts persist between docker container instances and are shared between image extensions. 4. ``stop``: This brings down the container and removes it. The following shows how to launch the container in a detached state and enter it: .. code:: bash # Launch the container in detached mode # We don't pass an image extension arg, so it defaults to 'base' ./docker/container.sh start # Enter the container # We pass 'base' explicitly, but if we hadn't it would default to 'base' ./docker/container.sh enter base To copy files from the base container to the host machine, you can use the following command: .. code:: bash # Copy the file /workspace/orbit/logs to the current directory docker cp orbit-base:/workspace/orbit/logs . The script ``container.sh`` provides a wrapper around this command to copy the ``logs`` , ``data_storage`` and ``docs/_build`` directories to the ``docker/artifacts`` directory. This is useful for copying the logs, data and documentation: .. code:: # stop the container ./docker/container.sh stop Python Interpreter ~~~~~~~~~~~~~~~~~~ The container uses the Python interpreter provided by Isaac Sim. This interpreter is located at ``/isaac-sim/python.sh``. We set aliases inside the container to make it easier to run the Python interpreter. You can use the following commands to run the Python interpreter: .. code:: bash # Run the Python interpreter -> points to /isaac-sim/python.sh python Understanding the mounted volumes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``docker-compose.yaml`` file creates several named volumes that are mounted to the container. These are summarized below: * ``isaac-cache-kit``: This volume is used to store cached Kit resources (`/isaac-sim/kit/cache` in container) * ``isaac-cache-ov``: This volume is used to store cached OV resources (`/root/.cache/ov` in container) * ``isaac-cache-pip``: This volume is used to store cached pip resources (`/root/.cache/pip`` in container) * ``isaac-cache-gl``: This volume is used to store cached GLCache resources (`/root/.cache/nvidia/GLCache` in container) * ``isaac-cache-compute``: This volume is used to store cached compute resources (`/root/.nv/ComputeCache` in container) * ``isaac-logs``: This volume is used to store logs generated by Omniverse. (`/root/.nvidia-omniverse/logs` in container) * ``isaac-carb-logs``: This volume is used to store logs generated by carb. (`/isaac-sim/kit/logs/Kit/Isaac-Sim` in container) * ``isaac-data``: This volume is used to store data generated by Omniverse. (`/root/.local/share/ov/data` in container) * ``isaac-docs``: This volume is used to store documents generated by Omniverse. (`/root/Documents` in container) * ``orbit-docs``: This volume is used to store documentation of Orbit when built inside the container. (`/workspace/orbit/docs/_build` in container) * ``orbit-logs``: This volume is used to store logs generated by Orbit workflows when run inside the container. (`/workspace/orbit/logs` in container) * ``orbit-data``: This volume is used to store whatever data users may want to preserve between container runs. (`/workspace/orbit/data_storage` in container) To view the contents of these volumes, you can use the following command: .. code:: bash # list all volumes docker volume ls # inspect a specific volume, e.g. isaac-cache-kit docker volume inspect isaac-cache-kit Orbit Image Extensions ---------------------- The produced image depends upon the arguments passed to ``./container.sh start`` and ``./container.sh stop``. These commands accept an ``image_extension`` as an additional argument. If no argument is passed, then these commands default to ``base``. Currently, the only valid ``image_extension`` arguments are (``base``, ``ros2``). Only one ``image_extension`` can be passed at a time, and the produced container will be named ``orbit``. .. code:: bash # start base by default ./container.sh start # stop base explicitly ./container.sh stop base # start ros2 container ./container.sh start ros2 # stop ros2 container ./container.sh stop ros2 The passed ``image_extension`` argument will build the image defined in ``Dockerfile.${image_extension}``, with the corresponding `profile`_ in the ``docker-compose.yaml`` and the envars from ``.env.${image_extension}`` in addition to the ``.env.base``, if any. ROS2 Image Extension ~~~~~~~~~~~~~~~~~~~~ In ``Dockerfile.ros2``, the container installs ROS2 Humble via an `apt package`_, and it is sourced in the ``.bashrc``. The exact version is specified by the variable ``ROS_APT_PACKAGE`` in the ``.env.ros2`` file, defaulting to ``ros-base``. Other relevant ROS2 variables are also specified in the ``.env.ros2`` file, including variables defining the `various middleware`_ options. The container defaults to ``FastRTPS``, but ``CylconeDDS`` is also supported. Each of these middlewares can be `tuned`_ using their corresponding ``.xml`` files under ``docker/.ros``. Known Issues ------------ Invalid mount config for type "bind" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you see the following error when building the container: .. code:: text ⠋ Container orbit Creating 0.0s Error response from daemon: invalid mount config for type "bind": bind source path does not exist: ${HOME}/.Xauthority This means that the ``.Xauthority`` file is not present in the home directory of the host machine. The portion of the docker-compose.yaml that enables this is commented out by default, so this shouldn't happen unless it has been altered. This file is required for X11 forwarding to work. To fix this, you can create an empty ``.Xauthority`` file in your home directory. .. code:: bash touch ${HOME}/.Xauthority A similar error but requires a different fix: .. code:: text ⠋ Container orbit Creating 0.0s Error response from daemon: invalid mount config for type "bind": bind source path does not exist: /tmp/.X11-unix This means that the folder/files are either not present or not accessible on the host machine. The portion of the docker-compose.yaml that enables this is commented out by default, so this shouldn't happen unless it has been altered. This usually happens when you have multiple docker versions installed on your machine. To fix this, you can try the following: * Remove all docker versions from your machine. .. code:: bash sudo apt remove docker* sudo apt remove docker docker-engine docker.io containerd runc docker-desktop docker-compose-plugin sudo snap remove docker sudo apt clean autoclean && sudo apt autoremove --yes * Install the latest version of docker based on the instructions in the setup section. WebRTC and WebSocket Streaming ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When streaming the GUI from Isaac Sim, there are `several streaming clients`_ available. There is a `known issue`_ when attempting to use WebRTC streaming client on Google Chrome and Safari while running Isaac Sim inside a container. To avoid this problem, we suggest using either the Native Streaming Client or WebSocket options, or using the Mozilla Firefox browser on which WebRTC works. Streaming is the only supported method for visualizing the Isaac GUI from within the container. The Omniverse Streaming Client is freely available from the Omniverse app, and is easy to use. The other streaming methods similarly require only a web browser. If users want to use X11 forwarding in order to have the apps behave as local GUI windows, they can uncomment the relevant portions in docker-compose.yaml. .. _`NVIDIA Omniverse EULA`: https://docs.omniverse.nvidia.com/platform/latest/common/NVIDIA_Omniverse_License_Agreement.html .. _`container installation`: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_container.html .. _`Docker website`: https://docs.docker.com/desktop/install/linux-install/ .. _`docker compose`: https://docs.docker.com/compose/install/linux/#install-using-the-repository .. _`NVIDIA Container Toolkit`: https://github.com/NVIDIA/nvidia-container-toolkit .. _`Container Toolkit website`: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html .. _`post-installation steps`: https://docs.docker.com/engine/install/linux-postinstall/ .. _`Isaac Sim container`: https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim .. _`NGC API key`: https://docs.nvidia.com/ngc/gpu-cloud/ngc-user-guide/index.html#generating-api-key .. _`several streaming clients`: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/manual_livestream_clients.html .. _`known issue`: https://forums.developer.nvidia.com/t/unable-to-use-webrtc-when-i-run-runheadless-webrtc-sh-in-remote-headless-container/222916 .. _`profile`: https://docs.docker.com/compose/compose-file/15-profiles/ .. _`apt package`: https://docs.ros.org/en/humble/Installation/Ubuntu-Install-Debians.html#install-ros-2-packages .. _`various middleware`: https://docs.ros.org/en/humble/How-To-Guides/Working-with-multiple-RMW-implementations.html .. _`tuned`: https://docs.ros.org/en/foxy/How-To-Guides/DDS-tuning.html
14,374
reStructuredText
49.438596
204
0.714693
NVIDIA-Omniverse/orbit/docs/source/deployment/index.rst
Container Deployment ==================== Docker is a tool that allows for the creation of containers, which are isolated environments that can be used to run applications. They are useful for ensuring that an application can run on any machine that has Docker installed, regardless of the host machine's operating system or installed libraries. We include a Dockerfile and docker-compose.yaml file that can be used to build a Docker image that contains Orbit and all of its dependencies. This image can then be used to run Orbit in a container. The Dockerfile is based on the Isaac Sim image provided by NVIDIA, which includes the Omniverse application launcher and the Isaac Sim application. The Dockerfile installs Orbit and its dependencies on top of this image. The following guides provide instructions for building the Docker image and running Orbit in a container. .. toctree:: :maxdepth: 1 docker cluster run_docker_example
946
reStructuredText
40.173911
102
0.788584
NVIDIA-Omniverse/orbit/docs/source/refs/migration.rst
Migration Guide (Isaac Sim) =========================== Moving from Isaac Sim 2022.2.1 to 2023.1.0 brings in a number of changes to the APIs and the way the application is built. This document outlines the changes and how to migrate your code to the new APIs. Many of these changes attribute to the underlying Omniverse Kit upgrade from 104.2 to 105.1. The new upgrade brings the following notable changes: * Update to USD 22.11 * Upgrading the Python from 3.7 to 3.10 .. warning:: This document is a work in progress and will be updated as we move closer to the release of Isaac Sim 2023.1.0. Renaming of PhysX Flatcache to PhysX Fabric ------------------------------------------- The PhysX Flatcache has been renamed to PhysX Fabric. The new name is more descriptive of the functionality and is consistent with the naming convention used by Omniverse called `Fabric`_. Consequently, the Python module name has also been changed from :mod:`omni.physxflatcache` to :mod:`omni.physxfabric`. Following this, on the Isaac Sim side, various renaming have occurred: * The parameter passed to :class:`SimulationContext` constructor via the keyword :obj:`sim_params` now expects the key ``use_fabric`` instead of ``use_flatcache``. * The Python attribute :attr:`SimulationContext.get_physics_context().use_flatcache` is now :attr:`SimulationContext.get_physics_context().use_fabric`. * The Python function :meth:`SimulationContext.get_physics_context().enable_flatcache` is now :meth:`SimulationContext.get_physics_context().enable_fabric`. Renaming of the URDF and MJCF Importers --------------------------------------- Starting from Isaac Sim 2023.1, the URDF and MJCF importers have been renamed to be more consistent with the other asset importers in Omniverse. The importers are now available on NVIDIA-Omniverse GitHub as open source projects. Due to the extension name change, the Python module names have also been changed: * URDF Importer: :mod:`omni.importer.urdf` (previously :mod:`omni.isaac.urdf`) * MJCF Importer: :mod:`omni.importer.mjcf` (previously :mod:`omni.isaac.mjcf`) Deprecation of :class:`UsdLux.Light` API ---------------------------------------- As highlighted in the release notes of `USD 22.11`_, the ``UsdLux.Light`` API has been deprecated in favor of the new ``UsdLuxLightAPI`` API. In the new API the attributes are prefixed with ``inputs:``. For example, the ``intensity`` attribute is now available as ``inputs:intensity``. The following example shows how to create a sphere light using the old API and the new API. .. dropdown:: Code for Isaac Sim 2022.2.1 and below :icon: code .. code-block:: python import omni.isaac.core.utils.prims as prim_utils prim_utils.create_prim( "/World/Light/GreySphere", "SphereLight", translation=(4.5, 3.5, 10.0), attributes={"radius": 2.5, "intensity": 600.0, "color": (0.75, 0.75, 0.75)}, ) .. dropdown:: Code for Isaac Sim 2023.1.0 and above :icon: code .. code-block:: python import omni.isaac.core.utils.prims as prim_utils prim_utils.create_prim( "/World/Light/WhiteSphere", "SphereLight", translation=(-4.5, 3.5, 10.0), attributes={ "inputs:radius": 2.5, "inputs:intensity": 600.0, "inputs:color": (1.0, 1.0, 1.0) }, ) .. _Fabric: https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/usd_fabric_usdrt.html .. _`USD 22.11`: https://github.com/PixarAnimationStudios/OpenUSD/blob/release/CHANGELOG.md
3,578
reStructuredText
36.28125
103
0.686138
NVIDIA-Omniverse/orbit/docs/source/refs/changelog.rst
Extensions Changelog ==================== All notable changes to this project are documented in this file. The format is based on `Keep a Changelog <https://keepachangelog.com/en/1.0.0/>`__ and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`__. Each extension has its own changelog. The changelog for each extension is located in the ``docs`` directory of the extension. The changelog for each extension is also included in this changelog to make it easier to find the changelog for a specific extension. omni.isaac.orbit ----------------- Extension containing the core framework of Orbit. .. include:: ../../../source/extensions/omni.isaac.orbit/docs/CHANGELOG.rst :start-line: 3 omni.isaac.orbit_assets ------------------------ Extension for configurations of various assets and sensors for Orbit. .. include:: ../../../source/extensions/omni.isaac.orbit_assets/docs/CHANGELOG.rst :start-line: 3 omni.isaac.orbit_tasks ---------------------- Extension containing the environments built using Orbit. .. include:: ../../../source/extensions/omni.isaac.orbit_tasks/docs/CHANGELOG.rst :start-line: 3
1,156
reStructuredText
30.270269
89
0.701557
NVIDIA-Omniverse/orbit/docs/source/refs/issues.rst
Known Issues ============ .. attention:: Please also refer to the `Omniverse Isaac Sim documentation`_ for known issues and workarounds. Stale values after resetting the environment -------------------------------------------- When resetting the environment, some of the data fields of assets and sensors are not updated. These include the poses of links in a kinematic chain, the camera images, the contact sensor readings, and the lidar point clouds. This is a known issue which has to do with the way the PhysX and rendering engines work in Omniverse. Many physics engines do a simulation step as a two-level call: ``forward()`` and ``simulate()``, where the kinematic and dynamic states are updated, respectively. Unfortunately, PhysX has only a single ``step()`` call where the two operations are combined. Due to computations through GPU kernels, it is not so straightforward for them to split these operations. Thus, at the moment, it is not possible to set the root and/or joint states and do a forward call to update the kinematic states of links. This affects both initialization as well as episodic resets. Similarly for RTX rendering related sensors (such as cameras), the sensor data is not updated immediately after setting the state of the sensor. The rendering engine update is bundled with the simulator's ``step()`` call which only gets called when the simulation is stepped forward. This means that the sensor data is not updated immediately after a reset and it will hold outdated values. While the above is erroneous, there is currently no direct workaround for it. From our experience in using IsaacGym, the reset values affect the agent learning critically depending on how frequently the environment terminates. Eventually if the agent is learning successfully, this number drops and does not affect the performance that critically. We have made a feature request to the respective Omniverse teams to have complete control over stepping different parts of the simulation app. However, at this point, there is no set timeline for this feature request. Non-determinism in physics simulation ------------------------------------- Due to GPU work scheduling, there's a possibility that runtime changes to simulation parameters may alter the order in which operations take place. This occurs because environment updates can happen while the GPU is occupied with other tasks. Due to the inherent nature of floating-point numeric storage, any modification to the execution ordering can result in minor changes in the least significant bits of output data. These changes may lead to divergent execution over the course of simulating thousands of environments and simulation frames. An illustrative example of this issue is observed with the runtime domain randomization of object's physics materials. This process can introduce both determinancy and simulation issues when executed on the GPU due to the way these parameters are passed from the CPU to the GPU in the lower-level APIs. Consequently, it is strongly advised to perform this operation only at setup time, before the environment stepping commences. For more information, please refer to the `PhysX Determinism documentation`_. Blank initial frames from the camera ------------------------------------ When using the :class:`omni.isaac.orbit.sensors.Camera` sensor in standalone scripts, the first few frames may be blank. This is a known issue with the simulator where it needs a few steps to load the material textures properly and fill up the render targets. A hack to work around this is to add the following after initializing the camera sensor and setting its pose: .. code-block:: python from omni.isaac.orbit.sim import SimulationContext sim = SimulationContext.instance() # note: the number of steps might vary depending on how complicated the scene is. for _ in range(12): sim.render() Using instanceable assets for markers ------------------------------------- When using `instanceable assets`_ for markers, the markers do not work properly, since Omniverse does not support instanceable assets when using the :class:`UsdGeom.PointInstancer` schema. This is a known issue and will hopefully be fixed in a future release. If you use an instanceable assets for markers, the marker class removes all the physics properties of the asset. This is then replicated across other references of the same asset since physics properties of instanceable assets are stored in the instanceable asset's USD file and not in its stage reference's USD file. .. _instanceable assets: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gym_instanceable_assets.html .. _Omniverse Isaac Sim documentation: https://docs.omniverse.nvidia.com/isaacsim/latest/known_issues.html .. _PhysX Determinism documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.3.1/docs/BestPractices.html#determinism
4,937
reStructuredText
52.096774
125
0.774154
NVIDIA-Omniverse/orbit/docs/source/refs/troubleshooting.rst
Tricks and Troubleshooting ========================== .. note:: The following lists some of the common tricks and troubleshooting methods that we use in our common workflows. Please also check the `troubleshooting page on Omniverse <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/linux_troubleshooting.html>`__ for more assistance. Checking the internal logs from the simulator --------------------------------------------- When running the simulator from a standalone script, it logs warnings and errors to the terminal. At the same time, it also logs internal messages to a file. These are useful for debugging and understanding the internal state of the simulator. Depending on your system, the log file can be found in the locations listed `here <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_faq.html#common-path-locations>`_. To obtain the exact location of the log file, you need to check the first few lines of the terminal output when you run the standalone script. The log file location is printed at the start of the terminal output. For example: .. code:: bash [INFO] Using python from: /home/${USER}/git/orbit/_isaac_sim/python.sh ... Passing the following args to the base kit application: [] Loading user config located at: '.../data/Kit/Isaac-Sim/2023.1/user.config.json' [Info] [carb] Logging to file: '.../logs/Kit/Isaac-Sim/2023.1/kit_20240328_183346.log' In the above example, the log file is located at ``.../logs/Kit/Isaac-Sim/2023.1/kit_20240328_183346.log``, ``...`` is the path to the user's log directory. The log file is named ``kit_20240328_183346.log`` You can open this file to check the internal logs from the simulator. Also when reporting issues, please include this log file to help us debug the issue. Using CPU Scaling Governor for performance ------------------------------------------ By default on many systems, the CPU frequency governor is set to “powersave” mode, which sets the CPU to lowest static frequency. To increase the maximum performance, we recommend setting the CPU frequency governor to “performance” mode. For more details, please check the the link `here <https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/power_management_guide/cpufreq_governors>`__. .. warning:: We advice not to set the governor to “performance” mode on a system with poor cooling (such as laptops), since it may cause the system to overheat. - To view existing ``scaling_governor`` value per CPU: .. code:: bash cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor - To change the governor to “performance” mode for each CPU: .. code:: bash echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor Observing long load times at the start of the simulation -------------------------------------------------------- The first time you run the simulator, it will take a long time to load up. This is because the simulator is compiling shaders and loading assets. Subsequent runs should be faster to start up, but may still take some time. Please note that once the Isaac Sim app loads, the environment creation time may scale linearly with the number of environments. Please expect a longer load time if running with thousands of environments or if each environment contains a larger number of assets. We are continually working on improving the time needed for this. When an instance of Isaac Sim is already running, launching another Isaac Sim instance in a different process may appear to hang at startup for the first time. Please be patient and give it some time as the second process will take longer to start up due to slower shader compilation. Receiving a “PhysX error” when running simulation on GPU -------------------------------------------------------- When using the GPU pipeline, the buffers used for the physics simulation are allocated on the GPU only once at the start of the simulation. This means that they do not grow dynamically as the number of collisions or objects in the scene changes. If the number of collisions or objects in the scene exceeds the size of the buffers, the simulation will fail with an error such as the following: .. code:: bash PhysX error: the application need to increase the PxgDynamicsMemoryConfig::foundLostPairsCapacity parameter to 3072, otherwise the simulation will miss interactions In this case, you need to increase the size of the buffers passed to the :class:`~omni.isaac.orbit.sim.SimulationContext` class. The size of the buffers can be increased by setting the :attr:`~omni.isaac.orbit.sim.PhysxCfg.gpu_found_lost_pairs_capacity` parameter in the :class:`~omni.isaac.orbit.sim.PhysxCfg` class. For example, to increase the size of the buffers to 4096, you can use the following code: .. code:: python import omni.isaac.orbit.sim as sim_utils sim_cfg = sim_utils.SimulationConfig() sim_cfg.physx.gpu_found_lost_pairs_capacity = 4096 sim = SimulationContext(sim_params=sim_cfg) Please see the documentation for :class:`~omni.isaac.orbit.sim.SimulationCfg` for more details on the parameters that can be used to configure the simulation. Preventing memory leaks in the simulator ---------------------------------------- Memory leaks in the Isaac Sim simulator can occur when C++ callbacks are registered with Python objects. This happens when callback functions within classes maintain references to the Python objects they are associated with. As a result, Python's garbage collection is unable to reclaim memory associated with these objects, preventing the corresponding C++ objects from being destroyed. Over time, this can lead to memory leaks and increased resource usage. To prevent memory leaks in the Isaac Sim simulator, it is essential to use weak references when registering callbacks with the simulator. This ensures that Python objects can be garbage collected when they are no longer needed, thereby avoiding memory leaks. The `weakref <https://docs.python.org/3/library/weakref.html>`_ module from the Python standard library can be employed for this purpose. For example, consider a class with a callback function ``on_event_callback`` that needs to be registered with the simulator. If you use a strong reference to the ``MyClass`` object when passing the callback, the reference count of the ``MyClass`` object will be incremented. This prevents the ``MyClass`` object from being garbage collected when it is no longer needed, i.e., the ``__del__`` destructor will not be called. .. code:: python import omni.kit class MyClass: def __init__(self): app_interface = omni.kit.app.get_app_interface() self._handle = app_interface.get_post_update_event_stream().create_subscription_to_pop( self.on_event_callback ) def __del__(self): self._handle.unsubscribe() self._handle = None def on_event_callback(self, event): # do something with the message To fix this issue, it's crucial to employ weak references when registering the callback. While this approach adds some verbosity to the code, it ensures that the ``MyClass`` object can be garbage collected when no longer in use. Here's the modified code: .. code:: python import omni.kit import weakref class MyClass: def __init__(self): app_interface = omni.kit.app.get_app_interface() self._handle = app_interface.get_post_update_event_stream().create_subscription_to_pop( lambda event, obj=weakref.proxy(self): obj.on_event_callback(event) ) def __del__(self): self._handle.unsubscribe() self._handle = None def on_event_callback(self, event): # do something with the message In this revised code, the weak reference ``weakref.proxy(self)`` is used when registering the callback, allowing the ``MyClass`` object to be properly garbage collected. By following this pattern, you can prevent memory leaks and maintain a more efficient and stable simulation. Understanding the error logs from crashes ----------------------------------------- Many times the simulator crashes due to a bug in the implementation. This swamps the terminal with exceptions, some of which are coming from the python interpreter calling ``__del__()`` destructor of the simulation application. These typically look like the following: .. code:: bash ... [INFO]: Completed setting up the environment... Traceback (most recent call last): File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 166, in <module> main() File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 126, in main actions = pre_process_actions(delta_pose, gripper_command) File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 57, in pre_process_actions return torch.concat([delta_pose, gripper_vel], dim=1) TypeError: expected Tensor as element 1 in argument 0, but got int Exception ignored in: <function _make_registry.<locals>._Registry.__del__ at 0x7f94ac097f80> Traceback (most recent call last): File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__ File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 98, in destroy TypeError: 'NoneType' object is not callable Exception ignored in: <function _make_registry.<locals>._Registry.__del__ at 0x7f94ac097f80> Traceback (most recent call last): File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__ File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 98, in destroy TypeError: 'NoneType' object is not callable Exception ignored in: <function SettingChangeSubscription.__del__ at 0x7fa2ea173e60> Traceback (most recent call last): File "../orbit/_isaac_sim/kit/kernel/py/omni/kit/app/_impl/__init__.py", line 114, in __del__ AttributeError: 'NoneType' object has no attribute 'get_settings' Exception ignored in: <function RegisteredActions.__del__ at 0x7f935f5cae60> Traceback (most recent call last): File "../orbit/_isaac_sim/extscache/omni.kit.viewport.menubar.lighting-104.0.7/omni/kit/viewport/menubar/lighting/actions.py", line 345, in __del__ File "../orbit/_isaac_sim/extscache/omni.kit.viewport.menubar.lighting-104.0.7/omni/kit/viewport/menubar/lighting/actions.py", line 350, in destroy TypeError: 'NoneType' object is not callable 2022-12-02 15:41:54 [18,514ms] [Warning] [carb.audio.context] 1 contexts were leaked ../orbit/_isaac_sim/python.sh: line 41: 414372 Segmentation fault (core dumped) $python_exe "$@" $args There was an error running python This is a known error with running standalone scripts with the Isaac Sim simulator. Please scroll above the exceptions thrown with ``registry`` to see the actual error log. In the above case, the actual error is: .. code:: bash Traceback (most recent call last): File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 166, in <module> main() File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 126, in main actions = pre_process_actions(delta_pose, gripper_command) File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 57, in pre_process_actions return torch.concat([delta_pose, gripper_vel], dim=1) TypeError: expected Tensor as element 1 in argument 0, but got int
11,894
reStructuredText
47.55102
151
0.724567
NVIDIA-Omniverse/orbit/docs/source/refs/license.rst
.. _license: License ======== NVIDIA Isaac Sim is available freely under `individual license <https://www.nvidia.com/en-us/omniverse/download/>`_. For more information about its license terms, please check `here <https://docs.omniverse.nvidia.com/app_isaacsim/common/NVIDIA_Omniverse_License_Agreement.html#software-support-supplement>`_. The license files for all its dependencies and included assets are available in its `documentation <https://docs.omniverse.nvidia.com/app_isaacsim/common/licenses.html>`_. Orbit framework is open-sourced under the `BSD-3-Clause license <https://opensource.org/licenses/BSD-3-Clause>`_. .. code-block:: text Copyright (c) 2022-2024, The ORBIT Project Developers. All rights reserved. SPDX-License-Identifier: BSD-3-Clause Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 AND CONTRIBUTORS "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 HOLDER 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.
2,281
reStructuredText
46.541666
170
0.772907
NVIDIA-Omniverse/orbit/docs/source/refs/contributing.rst
Contribution Guidelines ======================= We wholeheartedly welcome contributions to the project to make the framework more mature and useful for everyone. These may happen in forms of: * Bug reports: Please report any bugs you find in the `issue tracker <https://github.com/NVIDIA-Omniverse/orbit/issues>`__. * Feature requests: Please suggest new features you would like to see in the `discussions <https://github.com/NVIDIA-Omniverse/Orbit/discussions>`__. * Code contributions: Please submit a `pull request <https://github.com/NVIDIA-Omniverse/orbit/pulls>`__. * Bug fixes * New features * Documentation improvements * Tutorials and tutorial improvements .. attention:: We prefer GitHub `discussions <https://github.com/NVIDIA-Omniverse/Orbit/discussions>`_ for discussing ideas, asking questions, conversations and requests for new features. Please use the `issue tracker <https://github.com/NVIDIA-Omniverse/orbit/issues>`_ only to track executable pieces of work with a definite scope and a clear deliverable. These can be fixing bugs, new features, or general updates. Contributing Code ----------------- We use `GitHub <https://github.com/NVIDIA-Omniverse/orbit>`__ for code hosting. Please follow the following steps to contribute code: 1. Create an issue in the `issue tracker <https://github.com/NVIDIA-Omniverse/orbit/issues>`__ to discuss the changes or additions you would like to make. This helps us to avoid duplicate work and to make sure that the changes are aligned with the roadmap of the project. 2. Fork the repository. 3. Create a new branch for your changes. 4. Make your changes and commit them. 5. Push your changes to your fork. 6. Submit a pull request to the `main branch <https://github.com/NVIDIA-Omniverse/orbit/compare>`__. 7. Ensure all the checks on the pull request template are performed. After sending a pull request, the maintainers will review your code and provide feedback. Please ensure that your code is well-formatted, documented and passes all the tests. .. tip:: It is important to keep the pull request as small as possible. This makes it easier for the maintainers to review your code. If you are making multiple changes, please send multiple pull requests. Large pull requests are difficult to review and may take a long time to merge. Coding Style ------------ We follow the `Google Style Guides <https://google.github.io/styleguide/pyguide.html>`__ for the codebase. For Python code, the PEP guidelines are followed. Most important ones are `PEP-8 <https://www.python.org/dev/peps/pep-0008/>`__ for code comments and layout, `PEP-484 <http://www.python.org/dev/peps/pep-0484>`__ and `PEP-585 <https://www.python.org/dev/peps/pep-0585/>`__ for type-hinting. For documentation, we adopt the `Google Style Guide <https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html>`__ for docstrings. We use `Sphinx <https://www.sphinx-doc.org/en/master/>`__ for generating the documentation. Please make sure that your code is well-documented and follows the guidelines. Circular Imports ^^^^^^^^^^^^^^^^ Circular imports happen when two modules import each other, which is a common issue in Python. You can prevent circular imports by adhering to the best practices outlined in this `StackOverflow post <https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python>`__. In general, it is essential to avoid circular imports as they can lead to unpredictable behavior. However, in our codebase, we encounter circular imports at a sub-package level. This situation arises due to our specific code structure. We organize classes or functions and their corresponding configuration objects into separate files. This separation enhances code readability and maintainability. Nevertheless, it can result in circular imports because, in many configuration objects, we specify classes or functions as default values using the attributes ``class_type`` and ``func`` respectively. To address circular imports, we leverage the `typing.TYPE_CHECKING <https://docs.python.org/3/library/typing.html#typing.TYPE_CHECKING>`_ variable. This special variable is evaluated only during type-checking, allowing us to import classes or functions in the configuration objects without triggering circular imports. It is important to note that this is the sole instance within our codebase where circular imports are used and are acceptable. In all other scenarios, we adhere to best practices and recommend that you do the same. Type-hinting ^^^^^^^^^^^^ To make the code more readable, we use `type hints <https://docs.python.org/3/library/typing.html>`__ for all the functions and classes. This helps in understanding the code and makes it easier to maintain. Following this practice also helps in catching bugs early with static type checkers like `mypy <https://mypy.readthedocs.io/en/stable/>`__. To avoid duplication of efforts, we do not specify type hints for the arguments and return values in the docstrings. However, if your function or class is not self-explanatory, please add a docstring with the type hints. Tools ^^^^^ We use the following tools for maintaining code quality: * `pre-commit <https://pre-commit.com/>`__: Runs a list of formatters and linters over the codebase. * `black <https://black.readthedocs.io/en/stable/>`__: The uncompromising code formatter. * `flake8 <https://flake8.pycqa.org/en/latest/>`__: A wrapper around PyFlakes, pycodestyle and McCabe complexity checker. Please check `here <https://pre-commit.com/#install>`__ for instructions to set these up. To run over the entire repository, please execute the following command in the terminal: .. code:: bash ./orbit.sh --format # or "./orbit.sh -f" Contributing Documentation -------------------------- Contributing to the documentation is as easy as contributing to the codebase. All the source files for the documentation are located in the ``orbit/docs`` directory. The documentation is written in `reStructuredText <https://docutils.sourceforge.io/rst.html>`__ format. We use `Sphinx <https://www.sphinx-doc.org/en/master/>`__ with the `Book Theme <https://sphinx-book-theme.readthedocs.io/en/stable/>`__ for maintaining the documentation. Sending a pull request for the documentation is the same as sending a pull request for the codebase. Please follow the steps mentioned in the `Contributing Code`_ section. .. caution:: To build the documentation, we recommend creating a `virtual environment <https://docs.python.org/3/library/venv.html>`__ to install the dependencies. This can also be a `conda environment <https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html>`__. To build the documentation, run the following command in the terminal which installs the required python packages and builds the documentation using the ``docs/Makefile``: .. code:: bash ./orbit.sh --docs # or "./orbit.sh -d" The documentation is generated in the ``docs/_build`` directory. To view the documentation, open the ``index.html`` file in the ``html`` directory. This can be done by running the following command in the terminal: .. code:: bash xdg-open docs/_build/html/index.html .. hint:: The ``xdg-open`` command is used to open the ``index.html`` file in the default browser. If you are using a different operating system, you can use the appropriate command to open the file in the browser. To do a clean build, run the following command in the terminal: .. code:: bash rm -rf docs/_build && ./orbit.sh --docs Contributing assets ------------------- Currently, we host the assets for the extensions on `NVIDIA Nucleus Server <https://docs.omniverse.nvidia.com/nucleus/latest/index.html>`__. Nucleus is a cloud-based storage service that allows users to store and share large files. It is integrated with the `NVIDIA Omniverse Platform <https://developer.nvidia.com/omniverse>`__. Since all assets are hosted on Nucleus, we do not need to include them in the repository. However, we need to include the links to the assets in the documentation. The included assets are part of the `Isaac Sim Content <https://docs.omniverse.nvidia.com/isaacsim/latest/features/environment_setup/assets/usd_assets_overview.html>`__. To use this content, you need to download the files to a Nucleus server or create an **Isaac** Mount on a Nucleus server. Please check the `Isaac Sim documentation <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_faq.html#assets-and-nucleus>`__ for more information on how to download the assets. .. attention:: We are currently working on a better way to contribute assets. We will update this section once we have a solution. In the meantime, please follow the steps mentioned below. To host your own assets, the current solution is: 1. Create a separate repository for the assets and add it over there 2. Make sure the assets are licensed for use and distribution 3. Include images of the assets in the README file of the repository 4. Send a pull request with a link to the repository We will then verify the assets, its licensing, and include the assets into the Nucleus server for hosting. In case you have any questions, please feel free to reach out to us through e-mail or by opening an issue in the repository. Maintaining a changelog ----------------------- Each extension maintains a changelog in the ``CHANGELOG.rst`` file in the ``docs`` directory. The file is written in `reStructuredText <https://docutils.sourceforge.io/rst.html>`__ format. It contains a curated, chronologically ordered list of notable changes for each version of the extension. The goal of this changelog is to help users and contributors see precisely what notable changes have been made between each release (or version) of the extension. This is a *MUST* for every extension. For updating the changelog, please follow the following guidelines: * Each version should have a section with the version number and the release date. * The version number is updated according to `Semantic Versioning <https://semver.org/>`__. The release date is the date on which the version is released. * Each version is divided into subsections based on the type of changes made. * ``Added``: For new features. * ``Changed``: For changes in existing functionality. * ``Deprecated``: For soon-to-be removed features. * ``Removed``: For now removed features. * ``Fixed``: For any bug fixes. * Each change is described in its corresponding sub-section with a bullet point. * The bullet points are written in the past tense and in imperative mode. For example, the following is a sample changelog: .. code:: rst Changelog --------- 0.1.0 (2021-02-01) ~~~~~~~~~~~~~~~~~~ Added ^^^^^ * Added a new feature. Changed ^^^^^^^ * Changed an existing feature. Deprecated ^^^^^^^^^^ * Deprecated an existing feature. Removed ^^^^^^^ * Removed an existing feature. Fixed ^^^^^ * Fixed a bug. 0.0.1 (2021-01-01) ~~~~~~~~~~~~~~~~~~ Added ^^^^^ * Added a new feature.
11,201
reStructuredText
40.335793
169
0.744933
NVIDIA-Omniverse/PhysX/README.md
# NVIDIA PhysX Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. 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. ## Introduction Welcome to the NVIDIA PhysX source code repository. This repository contains source releases of the PhysX, Flow, and Blast SDKs used in NVIDIA Omniverse. ## Documentation The user guide and API documentation are available on [GitHub Pages](https://nvidia-omniverse.github.io/PhysX). Please create an [Issue](https://github.com/NVIDIA-Omniverse/PhysX/issues/) if you find a documentation issue. ## Instructions Please see instructions specific to each of the libraries in the respective subfolder. ## Community-Maintained Build Configuration Fork Please see [the O3DE Fork](https://github.com/o3de/PhysX) for community-maintained additional build configurations. ## Support * Please use GitHub [Discussions](https://github.com/NVIDIA-Omniverse/PhysX/discussions/) for questions and comments. * GitHub [Issues](https://github.com/NVIDIA-Omniverse/PhysX/issues) should only be used for bug reports or documentation issues. * You can also ask questions in the NVIDIA Omniverse #physics [Discord Channel](https://discord.com/invite/XWQNJDNuaC).
2,570
Markdown
48.442307
222
0.800389
NVIDIA-Omniverse/PhysX/LICENSE.md
BSD 3-Clause License Copyright (c) 2023, NVIDIA Corporation All rights reserved. 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.
1,512
Markdown
46.281249
71
0.803571
NVIDIA-Omniverse/PhysX/physx/dependencies.xml
<project toolsVersion="6.4"> <dependency name="clangMetadata" tags="requiredForDistro requiredForMetaGen"> <package name="clang-physxmetadata" version="4.0.0.32489833_1"/> </dependency> <dependency name="vswhere"> <package name="VsWhere" version="2.7.3111.17308_1.0" platforms="vc15win64 vc16win64 vc17win64 linux-crosscompile linux-aarch64-crosscompile "/> </dependency> <dependency name="PhysXDevice"> <package name="PhysXDevice" version="18.12.7.6" platforms="vc15win64 vc16win64 vc17win64"/> </dependency> <dependency name="freeglut"> <package name="freeglut-windows" version="3.4_1.1" platforms="vc15win64 vc16win64 vc17win64"/> </dependency> <dependency name="PhysXGpu"> <package name="PhysXGpu" version="105.1-5.3.1.6193-f2687f97-windows-public" platforms="vc15win64 vc16win64 vc17win64"/> <package name="PhysXGpu" version="105.1-5.3.1.6193-f2687f97-linux-x86_64-public" platforms="linux"/> <package name="PhysXGpu" version="105.1-5.3.1.6193-f2687f97-linux-aarch64-public" platforms="linux-aarch64"/> </dependency> <dependency name="opengllinux" tags="requiredForDistro"> <package name="opengl-linux" version="2017.5.19.1" platforms="linux"/> </dependency> <dependency name="rapidjson"> <package name="rapidjson" version="1.1.0-67fac85-073453e1" /> </dependency> </project>
1,332
XML
40.656249
147
0.734985
NVIDIA-Omniverse/PhysX/physx/README.md
# NVIDIA PhysX SDK 5 Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. 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. ## Introduction Welcome to the NVIDIA PhysX SDK source code repository. The NVIDIA PhysX SDK is a scalable multi-platform physics solution. PhysX is integrated into [NVIDIA Omniverse](https://developer.nvidia.com/omniverse). See also [PhysX SDK on developer.nvidia.com](https://developer.nvidia.com/physx-sdk). Please see [Release Notes](./CHANGELOG.md) for updates pertaining to the latest version. ## CPU Source and GPU Binaries The source made available in this repository is restricted to CPU code. GPU acceleration is made available through precompiled binaries. ## User Guide and API Documentation The user guide and API documentation are available on [GitHub Pages](https://nvidia-omniverse.github.io/PhysX/physx/index.html). Please create an [Issue](https://github.com/NVIDIA-Omniverse/PhysX/issues/) if you find a documentation issue. ## Quick Start Instructions Platform specific environment and build information can be found in [documentation/platformreadme](./documentation/platformreadme). To begin, clone this repository onto your local drive. Then change directory to physx/, run ./generate_projects.[bat|sh] and follow on-screen prompts. This will let you select a platform specific solution to build. You can then build from the generated solution/make file in the platform- and configuration-specific folders in the ``compiler`` folder. ## Acknowledgements This depot references packages of third party open source software copyright their respective owners. For copyright details, please refer to the license files included in the packages. | Software | Copyright Holder | Package | |---------------------------|-------------------------------------------------------------------------------------|----------------------------------| | CMake | Kitware, Inc. and Contributors | cmake | | LLVM | University of Illinois at Urbana-Champaign | clang-physxmetadata | | Visual Studio Locator | Microsoft Corporation | VsWhere | | Freeglut | Pawel W. Olszta | freeglut-windows<br>opengl-linux | | Mesa 3-D graphics library | Brian Paul | opengl-linux | | RapidJSON | THL A29 Limited, a Tencent company, and Milo Yip<br>Alexander Chemeris (msinttypes) | rapidjson | | OpenGL Ext Wrangler Lib | Nigel Stewart, Milan Ikits, Marcelo E. Magallon, Lev Povalahev | [SDK_ROOT]/snippets/graphics |
4,444
Markdown
66.348484
354
0.655491
NVIDIA-Omniverse/PhysX/physx/documentation/platformreadme/windows/README_WINDOWS.md
# NVIDIA PhysX SDK for Windows ## Location of Binaries: * SDK DLLs/LIBs: bin/ * PhysX Device DLLs: bin/ ## Required packages to generate projects: * Windows OS + headers for at least Win7 (`_WIN32_WINNT = 0x0601`) * CMake, minimum version 3.21 * Python, minimum version 3.5 ## PhysX GPU Acceleration: * Requires CUDA 11.8 compatible display driver. The corresponding driver version can be found [here](https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#cuda-major-component-versions__table-cuda-toolkit-driver-versions). ## Generating solutions for Visual Studio: * Solutions are generated through a script in the physx root directory: generate_projects.bat * The generate_projects.bat script expects a preset name as a parameter; if a parameter is not provided, it lists the available presets. * The generated solutions are in the folder compiler/"preset name". ## Notes: * The PhysXDevice/64.dll must be redistributed with GPU-enabled applications, and must live in the same directory as PhysXGpu.dll. * The nvcuda.dll and PhysXUpdateLoader/64.dll are loaded and checked for the NVIDIA Corporation digital signature. The signature is expected on all NVIDIA Corporation provided dlls. The application will exit if the signature check failed.
1,269
Markdown
44.357141
238
0.78093
NVIDIA-Omniverse/PhysX/physx/documentation/platformreadme/linux/README_LINUX.md
# NVIDIA PhysX SDK for Linux ## Location of Binaries: * SDK libraries: bin/linux.clang ## Required packages to generate projects: * CMake, minimum version 3.14 * Python, minimum version 3.5 * curl Compilers: * For linux x86-64 builds we support Ubuntu LTS releases with their respective default compiler versions: * Ubuntu 20.04 LTS with gcc 9 or clang 10 * Ubuntu 22.04 LTS with gcc 11 or clang 14 * For linux aarch64 builds we support gcc version 9 ## Generating Makefiles: * Makefiles are generated through a script in the physx root directory: generate_projects.sh * The script generate_projects.sh expects a preset name as a parameter, if a parameter is not provided it does list the available presets and you can select one. * Generated solutions are placed in the folders compiler/linux-debug, compiler/linux-checked, compiler/linux-profile, compiler/linux-release. ## Building SDK: * Makefiles are in compiler/linux-debug etc * Clean solution: make clean * Build solution: make * Install solution: make install Note: Compile errors on unsupported compilers or platforms are frequently caused by additional warnings that are treated as errors by default. While we cannot offer support in this case we recommend removing all occurences of the `-Werror` flag in the file `physx/source/compiler/cmake/linux/CMakeLists.txt`. ## PhysX GPU Acceleration: * Running GPU-accelerated simulations requires a CUDA 11.8 compatible display driver. The corresponding driver version can be found [here](https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#cuda-major-component-versions__table-cuda-toolkit-driver-versions). * Note that CUDA is not required for building PhysX, it is only a runtime requirement for GPU-accelerated scenes. ## Required Packages for Building and Running PhysX Snippets: * freeglut3 * libglu1 * libxdamage-dev * libxmu6 ## How to select the PhysX GPU Device: * Set the environment variable PHYSX_GPU_DEVICE to the device ordinal on which GPU PhysX should run. Default is 0. * Example: export PHYSX_GPU_DEVICE="1"
2,079
Markdown
36.142856
273
0.778259
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/generateMetaData.py
## 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-2023 NVIDIA Corporation. All rights reserved. import argparse import os import stat import sys import re import platform import shutil from lib import utils from lib import compare # test mode: create copy of reference files # update mode: try to open file in p4 if necessary def setup_targetdir(metaDataDir, isTestMode): if isTestMode: targetDir = metaDataDir + "_test" if os.path.isdir(targetDir): print("deleting", targetDir) shutil.rmtree(targetDir) def ignore_non_autogen(dir, files): return [f for f in files if not (os.path.isdir(os.path.join(dir, f)) or re.search(r"AutoGenerated", f))] shutil.copytree(metaDataDir, targetDir, ignore=ignore_non_autogen) #set write to new files: for root, dirs, files in os.walk(targetDir): for file in files: os.chmod(os.path.join(root, file) , stat.S_IWRITE|stat.S_IREAD) else: targetDir = metaDataDir if not utils.check_files_writable(utils.list_autogen_files(targetDir)): utils.try_checkout_files(utils.list_autogen_files(targetDir)) if not utils.check_files_writable(utils.list_autogen_files(targetDir)): print("auto generated meta data files not writable:", targetDir) print("aborting") sys.exit(1) utils.clear_files(utils.list_autogen_files(targetDir)) return targetDir # test mode: run perl script to compare reference and generated files def test_targetdir(targetDir, metaDataDir, isTestMode): if isTestMode: print("compare generated meta data files with reference meta data files:") result = compare.compareMetaDataDirectories(targetDir, metaDataDir) if not result: print("failed!") sys.exit(1) else: print("passed.") def get_osx_platform_path(): cmd = "xcodebuild -showsdks" (stdout, stderr) = utils.run_cmd(cmd) if stderr != "": print(stderr) sys.exit(1) match = re.search(r"(-sdk macosx\d+.\d+)", stdout, flags=re.MULTILINE) if not match: print("coundn't parse output of:\n", cmd, "\naborting!") sys.exit(1) sdkparam = match.group(0) cmd = "xcodebuild -version " + sdkparam + " Path" (sdkPath, stderr) = utils.run_cmd(cmd) if stderr != "": print(stderr) sys.exit(1) print("using sdk path:", sdkPath.rstrip()) return sdkPath.rstrip() def includeString(path): return ' -I"' + path + '"' ########################################################################################################### # main ########################################################################################################### parser = argparse.ArgumentParser(description='Generates meta data source files.') parser.add_argument('-test', help='enables testing mode, internal only', action='store_true') args = parser.parse_args() scriptDir = os.path.dirname(os.path.realpath(__file__)) try: os.makedirs("temp") except: None # find SDK_ROOT and PX_SHARED sdkRoot = utils.find_root_path(scriptDir, "source") clangRoot = os.path.normpath(os.environ['PM_clangMetadata_PATH']) print("testmode:", args.test) print("root sdk:", sdkRoot) print("root clang:", clangRoot) boilerPlateFile = os.path.join(sdkRoot, os.path.normpath("tools/physxmetadatagenerator/PxBoilerPlate.h")) includes = '' includes += includeString(sdkRoot + '/include') includes += includeString(sdkRoot + '/tools/physxmetadatagenerator') print("platform:", platform.system()) commonFlags = '-DNDEBUG -DPX_GENERATE_META_DATA -DPX_ENABLE_FEATURES_UNDER_CONSTRUCTION=0 -x c++-header -w -Wno-c++11-narrowing -fms-extensions ' if platform.system() == "Windows": debugFile = open("temp/clangCommandLine_windows.txt", "a") # read INCLUDE variable, set by calling batch script sysIncludes = os.environ['INCLUDE'] sysIncludes = sysIncludes.rstrip(';') sysIncludeList = sysIncludes.split(';') sysIncludeFlags = ' -isystem"' + '" -isystem"'.join(sysIncludeList) + '"' # for some reason -cc1 needs to go first in commonFlags commonFlags = '-cc1 ' + commonFlags platformFlags = '-DPX_VC=14 -D_WIN32 -std=c++14' + sysIncludeFlags clangExe = os.path.join(clangRoot, os.path.normpath('win32/bin/clang.exe')) elif platform.system() == "Linux": debugFile = open("temp/clangCommandLine_linux.txt", "a") platformFlags = '-std=c++0x' clangExe = os.path.join(clangRoot, os.path.normpath('linux32/bin/clang')) elif platform.system() == "Darwin": debugFile = open("temp/clangCommandLine_osx.txt", "a") platformFlags = '-std=c++0x -isysroot' + get_osx_platform_path() clangExe = os.path.join(clangRoot, os.path.normpath('osx/bin/clang')) else: print("unsupported platform, aborting!") sys.exit(1) commonFlags += ' -boilerplate-file ' + boilerPlateFile #some checks if not os.path.isfile(clangExe): print("didn't find,", clangExe, ", aborting!") sys.exit(1) clangExe = '"' + clangExe + '"' # required for execution of clang.exe os.environ["PWD"] = os.path.join(sdkRoot, os.path.normpath("tools/physxmetadatagenerator")) ############################### # PxPhysicsWithExtensions # ############################### print("PxPhysicsWithExtensions:") srcPath = "PxPhysicsWithExtensionsAPI.h" metaDataDir = os.path.join(sdkRoot, os.path.normpath("source/physxmetadata")) targetDir = setup_targetdir(metaDataDir, args.test) cmd = " ".join(["", clangExe, commonFlags, "", platformFlags, includes, srcPath, "-o", '"'+targetDir+'"']) print(cmd, file=debugFile) (stdout, stderr) = utils.run_cmd(cmd) if (stderr != "" or stdout != ""): print(stderr, "\n", stdout) print("wrote meta data files in", targetDir) test_targetdir(targetDir, metaDataDir, args.test) ############################### # PxVehicleExtension # ############################### print("PxVehicleExtension:") srcPath = "PxVehicleExtensionAPI.h" metaDataDir = os.path.join(sdkRoot, os.path.normpath("source/physxvehicle/src/physxmetadata")) includes += includeString(sdkRoot + '/include/vehicle') #TODO, get rid of source include includes += includeString(sdkRoot + '/source/physxvehicle/src') targetDir = setup_targetdir(metaDataDir, args.test) cmd = " ".join(["", clangExe, commonFlags, "", platformFlags, includes, srcPath, "-o", '"'+targetDir+'"']) print(cmd, file=debugFile) (stdout, stderr) = utils.run_cmd(cmd) if (stderr != "" or stdout != ""): print(stderr, "\n", stdout) print("wrote meta data files in", targetDir) test_targetdir(targetDir, metaDataDir, args.test)
7,833
Python
33.511013
145
0.691944
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/PxPhysicsWithExtensionsAPI.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_NXPHYSICSWITHEXTENSIONS_API #define PX_PHYSICS_NXPHYSICSWITHEXTENSIONS_API #include "PxExtensionsCommon.h" //Property overrides will output this exact property name instead of the general //property name that would be used. The properties need to have no template arguments //and exactly the same initialization as the classes they are overriding. static PropertyOverride gPropertyOverrides[] = { PropertyOverride( "PxShape", "Materials", "PxShapeMaterialsProperty" ), PropertyOverride( "PxRigidActor", "Shapes", "PxRigidActorShapeCollection" ), PropertyOverride( "PxArticulationReducedCoordinate", "Links", "PxArticulationLinkCollectionProp" ), }; //The meta data generator ignores properties that are marked as disabled. Note that in the declaration //for properties that are defined via getter and setter methods, the 'get' and 'set' prefix can be dropped. //For protected fields the "m" prefix can be dropped, however for public fields the whole field qualifier is expected. static DisabledPropertyEntry gDisabledProperties[] = { DisabledPropertyEntry( "PxSceneLimits", "IsValid" ), DisabledPropertyEntry( "PxSceneDesc", "TolerancesScale" ), DisabledPropertyEntry( "PxSceneDesc", "IsValid" ), DisabledPropertyEntry( "PxSceneDesc", "SceneQuerySystem" ), DisabledPropertyEntry( "PxShape", "Actor" ), DisabledPropertyEntry( "PxShape", "Geometry" ), DisabledPropertyEntry( "PxArticulationLink", "Articulation" ), DisabledPropertyEntry("PxArticulationJointReducedCoordinate", "ParentArticulationLink"), DisabledPropertyEntry("PxArticulationJointReducedCoordinate", "ChildArticulationLink"), DisabledPropertyEntry("PxArticulationJointReducedCoordinate", "Limit"), DisabledPropertyEntry( "PxArticulationReducedCoordinate", "LoopJoints"), DisabledPropertyEntry("PxArticulationReducedCoordinate", "Dofs"), DisabledPropertyEntry("PxArticulationReducedCoordinate", "CacheDataSize"), DisabledPropertyEntry("PxArticulationReducedCoordinate", "CoefficientMatrixSize"), DisabledPropertyEntry( "PxRigidActor", "IsRigidActor" ), DisabledPropertyEntry( "PxRigidActor", "ClassName" ), DisabledPropertyEntry( "PxRigidActor", "InternalActorIndex" ), DisabledPropertyEntry( "PxRigidStatic", "ClassName" ), DisabledPropertyEntry( "PxRigidDynamic", "ClassName" ), DisabledPropertyEntry( "PxRigidBody", "IsRigidBody" ), DisabledPropertyEntry( "PxRigidBody", "InternalIslandNodeIndex"), DisabledPropertyEntry( "PxRigidBody", "LinearVelocity"), DisabledPropertyEntry("PxRigidBody", "AngularVelocity"), DisabledPropertyEntry( "PxActor", "IsRigidStatic" ), DisabledPropertyEntry( "PxActor", "Type" ), DisabledPropertyEntry( "PxActor", "ClassName" ), DisabledPropertyEntry( "PxActor", "IsRigidDynamic" ), DisabledPropertyEntry( "PxActor", "IsArticulationLink" ), DisabledPropertyEntry( "PxActor", "IsRigidActor" ), DisabledPropertyEntry( "PxActor", "IsRigidBody" ), DisabledPropertyEntry( "PxMeshScale", "Inverse" ), DisabledPropertyEntry( "PxMeshScale", "IsIdentity" ), DisabledPropertyEntry( "PxMeshScale", "IsValidForTriangleMesh" ), DisabledPropertyEntry( "PxMeshScale", "IsValidForConvexMesh" ), DisabledPropertyEntry( "PxGeometry", "Type" ), DisabledPropertyEntry( "PxGeometry", "MTypePadding" ), DisabledPropertyEntry( "PxBoxGeometry", "IsValid" ), DisabledPropertyEntry( "PxSphereGeometry", "IsValid" ), DisabledPropertyEntry( "PxPlaneGeometry", "IsValid" ), DisabledPropertyEntry( "PxCapsuleGeometry", "IsValid" ), DisabledPropertyEntry( "PxConvexMeshGeometry", "IsValid" ), DisabledPropertyEntry( "PxTetrahedronMeshGeometry", "IsValid"), DisabledPropertyEntry( "PxTriangleMeshGeometry", "IsValid" ), DisabledPropertyEntry( "PxHeightFieldGeometry", "IsValid" ), DisabledPropertyEntry( "PxCustomGeometry", "IsValid" ), DisabledPropertyEntry( "PxCustomGeometry", "Callbacks" ), DisabledPropertyEntry( "PxJoint", "ClassName" ), DisabledPropertyEntry( "PxDistanceJoint", "ClassName" ), DisabledPropertyEntry( "PxContactJoint", "ClassName"), DisabledPropertyEntry( "PxGearJoint", "ClassName"), DisabledPropertyEntry( "PxRackAndPinionJoint", "ClassName"), DisabledPropertyEntry( "PxFixedJoint", "ClassName" ), DisabledPropertyEntry( "PxRevoluteJoint", "ClassName" ), DisabledPropertyEntry( "PxPrismaticJoint", "ClassName" ), DisabledPropertyEntry( "PxSphericalJoint", "ClassName" ), DisabledPropertyEntry( "PxD6Joint", "ClassName" ), DisabledPropertyEntry( "PxJointLimitParameters", "IsValid" ), DisabledPropertyEntry( "PxJointLimitParameters", "IsSoft" ), DisabledPropertyEntry( "PxJointLinearLimit", "IsValid" ), DisabledPropertyEntry( "PxJointLinearLimitPair", "IsValid" ), DisabledPropertyEntry( "PxJointAngularLimitPair", "IsValid" ), DisabledPropertyEntry( "PxJointLimitCone", "IsValid" ), DisabledPropertyEntry( "PxJointLimitPyramid", "IsValid" ), DisabledPropertyEntry( "PxD6JointDrive", "IsValid" ), DisabledPropertyEntry( "PxPhysics", "FLIPMaterials" ), DisabledPropertyEntry( "PxPhysics", "MPMMaterials" ), DisabledPropertyEntry( "PxScene", "ParticleSystems"), DisabledPropertyEntry( "PxScene", "FEMCloths"), DisabledPropertyEntry( "PxScene", "HairSystems"), // PT: added this for PVD-315. It's a mystery to me why we don't need to do that here for PxConvexMeshDesc. Maybe because the convex desc is in the cooking lib. DisabledPropertyEntry( "PxHeightFieldDesc", "IsValid" ), // DisabledPropertyEntry( "PxConstraint", "IsValid" ), // DisabledPropertyEntry( "PxTolerancesScale", "IsValid" ), }; //Append these properties to this type. static CustomProperty gCustomProperties[] = { #define DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( propName, propType, fieldName ) CustomProperty("PxSimulationStatistics", #propName, #propType, "PxU32 " #propName "[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];", "PxMemCopy( "#propName ", inSource->"#fieldName", sizeof( "#propName" ) );" ) DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( NbDiscreteContactPairs, NbDiscreteContactPairsProperty, nbDiscreteContactPairs ), DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( NbModifiedContactPairs, NbModifiedContactPairsProperty, nbModifiedContactPairs), DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( NbCCDPairs, NbCCDPairsProperty, nbCCDPairs), DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( NbTriggerPairs, NbTriggerPairsProperty, nbTriggerPairs), #undef DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY CustomProperty( "PxSimulationStatistics", "NbShapes", "NbShapesProperty", "PxU32 NbShapes[PxGeometryType::eGEOMETRY_COUNT];", "PxMemCopy( NbShapes, inSource->nbShapes, sizeof( NbShapes ) );" ), CustomProperty( "PxScene", "SimulationStatistics", "SimulationStatisticsProperty", "PxSimulationStatistics SimulationStatistics;", "inSource->getSimulationStatistics(SimulationStatistics);" ), CustomProperty( "PxShape", "Geom", "PxShapeGeomProperty", "PxGeometryHolder Geom;", "Geom = PxGeometryHolder(inSource->getGeometry());" ), CustomProperty( "PxCustomGeometry", "CustomType", "PxCustomGeometryCustomTypeProperty", "PxU32 CustomType;", "PxCustomGeometry::Type t = inSource->callbacks->getCustomType(); CustomType = *reinterpret_cast<const PxU32*>(&t);" ), }; static const char* gImportantPhysXTypes[] = { "PxRigidStatic", "PxRigidDynamic", "PxShape", "PxArticulationReducedCoordinate", "PxArticulationLink", "PxMaterial", "PxFEMSoftBodyMaterial", "PxPBDMaterial", "PxFLIPMaterial", "PxMPMMaterial", "PxArticulationJointReducedCoordinate", "PxArticulationLimit", "PxArticulationDrive", "PxScene", "PxPhysics", "PxHeightFieldDesc", "PxMeshScale", "PxConstraint", "PxTolerancesScale", "PxSimulationStatistics", "PxSceneDesc", "PxSceneLimits", "PxgDynamicsMemoryConfig", "PxBroadPhaseDesc", "PxGeometry", "PxBoxGeometry", "PxCapsuleGeometry", "PxConvexMeshGeometry", "PxSphereGeometry", "PxPlaneGeometry", "PxTetrahedronMeshGeometry", "PxTriangleMeshGeometry", "PxHeightFieldGeometry", "PxCustomGeometry", "PxAggregate", "PxPruningStructure", //The mesh and heightfield buffers will need to be //handled by hand; they are very unorthodox compared //to the rest of the objects. #if PX_SUPPORT_GPU_PHYSX "PxgDynamicsMemoryConfig", #endif }; static const char* gExtensionPhysXTypes[] = { "PxD6JointDrive", "PxJointLinearLimit", "PxJointLinearLimitPair", "PxJointAngularLimitPair", "PxJointLimitCone", "PxJointLimitPyramid", "PxD6Joint", "PxDistanceJoint", "PxGearJoint", "PxRackAndPinionJoint", "PxContactJoint", "PxFixedJoint", "PxPrismaticJoint", "PxRevoluteJoint", "PxSphericalJoint", }; //We absolutely never generate information about these types, even if types //we do care about are derived from these types. static const char* gAvoidedPhysXTypes[] = { "PxSerializable", "PxObservable", "PxBase", "PxBaseFlag::Enum", "PxFLIPMaterial", "PxMPMMaterial", }; #include "PxPhysicsAPI.h" #include "extensions/PxExtensionsAPI.h" #endif
10,588
C
48.023148
310
0.776445
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/PxVehicleExtensionAPI.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_NXPHYSICSWITHVEHICLEEXTENSIONS_API #define PX_PHYSICS_NXPHYSICSWITHVEHICLEEXTENSIONS_API #include "PxExtensionsCommon.h" //The meta data generator ignores properties that are marked as disabled. Note that in the declaration //for properties that are defined via getter and setter methods, the 'get' and 'set' prefix can be dropped. //For protected fields the "m" prefix can be dropped, however for public fields the whole field qualifier is expected. static DisabledPropertyEntry gDisabledProperties[] = { DisabledPropertyEntry( "PxVehicleWheelsDynData", "MTireForceCalculators" ), DisabledPropertyEntry( "PxVehicleWheelsDynData", "TireForceShaderData" ), DisabledPropertyEntry( "PxVehicleWheelsDynData", "UserData" ), DisabledPropertyEntry( "PxVehicleWheels", "MActor" ), }; //Append these properties to this type. static CustomProperty gCustomProperties[] = { #define DEFINE_VEHICLETIREDATA_INDEXED_PROPERTY( propName, propType, fieldName ) CustomProperty("PxVehicleTireData", #propName, #propType, "PxReal " #propName "[3][2];", "PxMemCopy( "#propName ", inSource->"#fieldName", sizeof( "#propName" ) );" ) DEFINE_VEHICLETIREDATA_INDEXED_PROPERTY( MFrictionVsSlipGraph, MFrictionVsSlipGraphProperty, mFrictionVsSlipGraph), #undef DEFINE_VEHICLETIREDATA_INDEXED_PROPERTY CustomProperty( "PxVehicleEngineData", "MTorqueCurve", "MTorqueCurveProperty", "", "" ), }; static const char* gUserPhysXTypes[] = { "PxVehicleWheels", "PxVehicleWheelsSimData", "PxVehicleWheelsDynData", "PxVehicleDrive4W", "PxVehicleWheels4SimData", "PxVehicleDriveSimData4W", "PxVehicleWheelData", "PxVehicleSuspensionData", "PxVehicleDriveDynData", "PxVehicleDifferential4WData", "PxVehicleDifferentialNWData", "PxVehicleAckermannGeometryData", "PxVehicleTireLoadFilterData", "PxVehicleEngineData", "PxVehicleGearsData", "PxVehicleClutchData", "PxVehicleAutoBoxData", "PxVehicleTireData", "PxVehicleChassisData", "PxTorqueCurvePair", "PxVehicleDriveTank", "PxVehicleNoDrive", "PxVehicleDriveSimDataNW", "PxVehicleDriveNW", "PxVehicleAntiRollBarData", }; //We absolutely never generate information about these types, even if types //we do care about are derived from these types. static const char* gAvoidedPhysXTypes[] = { "PxSerializable", "PxObservable", "PxBase", "PxBaseFlag::Enum", }; #include "PxPhysicsAPI.h" #include "PxVehicleSuspWheelTire4.h" #endif
4,111
C
42.74468
247
0.775724
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/lib/utils.py
## 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-2023 NVIDIA Corporation. All rights reserved. # general utility module import os import sys import re import subprocess def list_autogen_files(dirPath): autogenFiles = [] for (root, subdirs, files) in os.walk(dirPath): files = [f for f in files if re.search(r"AutoGenerated", f)] autogenFiles.extend([os.path.join(root, f) for f in files]) return autogenFiles #checkout files with p4 if available def try_checkout_files(files): print("checking p4 connection parameter...") # checking p4 cmd = "p4" (stdout, stderr) = run_cmd(cmd) if stderr == "": print("p4 available.") else: print("p4 unavailable.") return cmd = "p4 edit " + " " + " ".join(files) (stdout, stderr) = run_cmd(cmd) print(stderr) print(stdout) # check files writability def check_files_writable(files): for file in files: if not os.access(file, os.W_OK): return False return True # find a root directory containing a known directory (as a hint) def find_root_path(startDir, containedDir): currentDir = startDir # search directory tree mergedDir = os.path.join(currentDir, containedDir) while not os.path.isdir(mergedDir): (currentDir, dir) = os.path.split(currentDir) if not dir: return None mergedDir = os.path.join(currentDir, containedDir) return currentDir def run_cmd(cmd, stdin = ""): process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdoutRaw, stderrRaw) = process.communicate(stdin.encode('utf-8')) stdout = stdoutRaw.decode(encoding='utf-8') stderr = stderrRaw.decode(encoding='utf-8') return (stdout, stderr) # clears content of files def clear_files(files): for file in files: open(file, 'w').close() ############################################################################## # internal functions ##############################################################################
3,425
Python
32.588235
115
0.703066
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/lib/compare.py
## 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-2023 NVIDIA Corporation. All rights reserved. # general utility module import os import sys import re from . import utils def compareMetaDataDirectories(candidateDir, referenceDir): print("reference dir:", referenceDir) print("candidate dir:", candidateDir) if not _checkFileExistence(candidateDir, referenceDir): return False referenceFiles = utils.list_autogen_files(referenceDir) #get corresponding candidate files without relying on os.walk order def mapRefToCand(refFile): return os.path.join(candidateDir, os.path.relpath(refFile, referenceDir)) candidateFiles = [mapRefToCand(f) for f in referenceFiles] for (fileCand, fileRef) in zip(candidateFiles, referenceFiles): timeCand = os.path.getmtime(fileCand) timeRef = os.path.getmtime(fileRef) if timeCand <= timeRef: print("last modified time of candidate is not later than last modified time of reference:") print("candidate:", fileCand, "\n", "reference:", fileRef) print("ref:", timeRef) print("cand:", timeCand) return False #_read_file_content will remove line endings(windows/unix), but not ignore empty lines candLines = _read_file_content(fileCand) refLines = _read_file_content(fileRef) if not (candLines and refLines): return False if len(candLines) != len(refLines): print("files got different number of lines:") print("candidate:", fileCand, "\n", "reference:", fileRef) print("ref:", len(refLines)) print("cand:", len(candLines)) return False for (i, (lineCand, lineRef)) in enumerate(zip(candLines, refLines)): if (lineCand != lineRef): print("candidate line is not equal to refence line:") print("candidate:", fileCand, "\n", "reference:", fileRef) print("@line number:", i) print("ref:", lineRef) print("cand:", lineCand) return False return True ############################################################################## # internal functions ############################################################################## #will remove line endings(windows/unix), but not ignore empty lines def _read_file_content(filePath): lines = [] try: with open(filePath, "r") as file: for line in file: lines.append(line.rstrip()) except: print("issue with reading file:", filePath) return lines def _checkFileExistence(candidateDir, referenceDir): candidateSet = set([os.path.relpath(f, candidateDir) for f in utils.list_autogen_files(candidateDir)]) referenceSet = set([os.path.relpath(f, referenceDir) for f in utils.list_autogen_files(referenceDir)]) missingSet = referenceSet - candidateSet if missingSet: print("the following files are missing from the candidates:\n", "\n".join(missingSet)) return False excessSet = candidateSet - referenceSet if excessSet: print("too many candidate files:\n", "\n".join(excessSet)) return False return True
4,397
Python
36.271186
103
0.710257
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometry/VoxelMap.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef VOXEL_MAP_H #define VOXEL_MAP_H #include "PxPhysicsAPI.h" /* VoxelMap inherits physx::PxCustomGeometry::Callbacks interface and provides implementations for 5 callback functions: - getLocalBounds - generateContacts - raycast - overlap - sweep It should be passed to PxCustomGeometry constructor. */ struct VoxelMap : physx::PxCustomGeometry::Callbacks, physx::PxUserAllocated { void setDimensions(int x, int y, int z); int dimX() const; int dimY() const; int dimZ() const; void setVoxelSize(float x, float y, float z); const physx::PxVec3& voxelSize() const; float voxelSizeX() const; float voxelSizeY() const; float voxelSizeZ() const; physx::PxVec3 extents() const; void setVoxel(int x, int y, int z, bool yes = true); bool voxel(int x, int y, int z) const; void clearVoxels(); void setFloorVoxels(int layers); void setWaveVoxels(); void voxelize(const physx::PxGeometry& geom, const physx::PxTransform& pose, bool add = true); physx::PxVec3 voxelPos(int x, int y, int z) const; void pointCoords(const physx::PxVec3& p, int& x, int& y, int& z) const; void getVoxelRegion(const physx::PxBounds3& b, int& sx, int& sy, int& sz, int& ex, int& ey, int& ez) const; // physx::PxCustomGeometry::Callbacks overrides DECLARE_CUSTOM_GEOMETRY_TYPE virtual physx::PxBounds3 getLocalBounds(const physx::PxGeometry&) const; virtual bool generateContacts(const physx::PxGeometry& geom0, const physx::PxGeometry& geom1, const physx::PxTransform& pose0, const physx::PxTransform& pose1, const physx::PxReal contactDistance, const physx::PxReal meshContactMargin, const physx::PxReal toleranceLength, physx::PxContactBuffer& contactBuffer) const; virtual physx::PxU32 raycast(const physx::PxVec3& origin, const physx::PxVec3& unitDir, const physx::PxGeometry& geom, const physx::PxTransform& pose, physx::PxReal maxDist, physx::PxHitFlags hitFlags, physx::PxU32 maxHits, physx::PxGeomRaycastHit* rayHits, physx::PxU32 stride, physx::PxRaycastThreadContext*) const; virtual bool overlap(const physx::PxGeometry& geom0, const physx::PxTransform& pose0, const physx::PxGeometry& geom1, const physx::PxTransform& pose1, physx::PxOverlapThreadContext*) const; virtual bool sweep(const physx::PxVec3& unitDir, const physx::PxReal maxDist, const physx::PxGeometry& geom0, const physx::PxTransform& pose0, const physx::PxGeometry& geom1, const physx::PxTransform& pose1, physx::PxGeomSweepHit& sweepHit, physx::PxHitFlags hitFlags, const physx::PxReal inflation, physx::PxSweepThreadContext*) const; virtual void visualize(const physx::PxGeometry&, physx::PxRenderOutput&, const physx::PxTransform&, const physx::PxBounds3&) const; virtual void computeMassProperties(const physx::PxGeometry&, physx::PxMassProperties&) const {} virtual bool usePersistentContactManifold(const physx::PxGeometry&, physx::PxReal&) const { return true; } private: int pacsX() const; int pacsY() const; int pacsZ() const; int m_dimensions[3]; physx::PxVec3 m_voxelSize; physx::PxArray<physx::PxU64> m_packs; }; #endif
4,745
C
42.541284
190
0.761644
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometry/VoxelMap.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "collision/PxCollisionDefs.h" #include "PxImmediateMode.h" #include "VoxelMap.h" #include "common/PxRenderOutput.h" #include "geomutils/PxContactBuffer.h" using namespace physx; void VoxelMap::setDimensions(int x, int y, int z) { m_dimensions[0] = x; m_dimensions[1] = y; m_dimensions[2] = z; m_packs.resize(size_t(pacsX()) * size_t(pacsY()) * size_t(pacsZ()), 0U); } int VoxelMap::dimX() const { return m_dimensions[0]; } int VoxelMap::dimY() const { return m_dimensions[1]; } int VoxelMap::dimZ() const { return m_dimensions[2]; } int VoxelMap::pacsX() const { return (dimX() + 3) / 4; } int VoxelMap::pacsY() const { return (dimY() + 3) / 4; } int VoxelMap::pacsZ() const { return (dimZ() + 3) / 4; } PxVec3 VoxelMap::extents() const { return PxVec3(dimX() * voxelSizeX(), dimY() * voxelSizeY(), dimZ() * voxelSizeZ()); } void VoxelMap::setVoxelSize(float x, float y, float z) { m_voxelSize = PxVec3(x, y, z); } const PxVec3& VoxelMap::voxelSize() const { return m_voxelSize; } float VoxelMap::voxelSizeX() const { return m_voxelSize.x; } float VoxelMap::voxelSizeY() const { return m_voxelSize.y; } float VoxelMap::voxelSizeZ() const { return m_voxelSize.z; } void VoxelMap::setVoxel(int x, int y, int z, bool yes) { if (x < 0 || x >= int(dimX()) || y < 0 || y >= int(dimY()) || z < 0 || z >= int(dimZ())) return; int px = x / 4, py = y / 4, pz = z / 4; int bx = x & 3, by = y & 3, bz = z & 3; PxU64& p = m_packs[px + py * size_t(pacsX()) + pz * size_t(pacsX()) * size_t(pacsY())]; if (yes) p |= (PxU64(1) << (bx + by * 4 + bz * 16)); else p &= ~(PxU64(1) << (bx + by * 4 + bz * 16)); } bool VoxelMap::voxel(int x, int y, int z) const { if (x < 0 || x >= int(dimX()) || y < 0 || y >= int(dimY()) || z < 0 || z >= int(dimZ())) return false; int px = x / 4, py = y / 4, pz = z / 4; int bx = x & 3, by = y & 3, bz = z & 3; PxU64 p = m_packs[px + py * size_t(pacsX()) + pz * size_t(pacsX()) * size_t(pacsY())]; return (p & (PxU64(1) << (bx + by * 4 + bz * 16))) != 0; } void VoxelMap::clearVoxels() { memset(&m_packs[0], 0, m_packs.size() * sizeof(PxU64)); } void VoxelMap::setFloorVoxels(int layers) { for (int x = 0; x < dimX(); ++x) for (int y = 0; y < layers; ++y) for (int z = 0; z < dimZ(); ++z) setVoxel(x, y, z); } void VoxelMap::setWaveVoxels() { PxVec3 ext = extents(); for (int x = 0; x < dimX(); ++x) for (int y = 0; y < dimY(); ++y) for (int z = 0; z < dimZ(); ++z) { PxVec3 pos = voxelPos(x, y, z); float a = sqrtf((pos.x / ext.x) * (pos.x / ext.x) + (pos.z / ext.z) * (pos.z / ext.z)); if (a * 0.5f > pos.y / ext.y + 0.4f) setVoxel(x, y, z); } } void VoxelMap::voxelize(const PxGeometry& geom, const PxTransform& pose, bool add) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, geom, pose); int sx, sy, sz, ex, ey, ez; getVoxelRegion(bounds, sx, sy, sz, ex, ey, ez); for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (voxel(x, y, z)) { if (!add && PxGeometryQuery::pointDistance(voxelPos(x, y, z), geom, pose) == 0) setVoxel(x, y, z, false); } else { if (add && PxGeometryQuery::pointDistance(voxelPos(x, y, z), geom, pose) == 0) setVoxel(x, y, z); } } PxVec3 VoxelMap::voxelPos(int x, int y, int z) const { return PxVec3((x + 0.5f) * voxelSizeX(), (y + 0.5f) * voxelSizeY(), (z + 0.5f) * voxelSizeZ()) - extents() * 0.5f; } void VoxelMap::pointCoords(const PxVec3& p, int& x, int& y, int& z) const { PxVec3 l = p + extents() * 0.5f, s = voxelSize(); x = int(PxFloor(l.x / s.x)); y = int(PxFloor(l.y / s.y)); z = int(PxFloor(l.z / s.z)); } void VoxelMap::getVoxelRegion(const PxBounds3& b, int& sx, int& sy, int& sz, int& ex, int& ey, int& ez) const { pointCoords(b.minimum, sx, sy, sz); pointCoords(b.maximum, ex, ey, ez); } // physx::PxCustomGeometry::Callbacks overrides IMPLEMENT_CUSTOM_GEOMETRY_TYPE(VoxelMap) PxBounds3 VoxelMap::getLocalBounds(const PxGeometry&) const { return PxBounds3::centerExtents(PxVec3(0), extents()); } bool VoxelMap::generateContacts(const PxGeometry& /*geom0*/, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1, const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength, PxContactBuffer& contactBuffer) const { PxBoxGeometry voxelGeom(voxelSize() * 0.5f); PxGeometry* pGeom0 = &voxelGeom; const PxGeometry* pGeom1 = &geom1; PxTransform pose1in0 = pose0.transformInv(pose1); PxBounds3 bounds1; PxGeometryQuery::computeGeomBounds(bounds1, geom1, pose1in0, contactDistance); struct ContactRecorder : immediate::PxContactRecorder { PxContactBuffer* contactBuffer; ContactRecorder(PxContactBuffer& _contactBuffer) : contactBuffer(&_contactBuffer) {} virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/) { for (PxU32 i = 0; i < nbContacts; ++i) contactBuffer->contact(contactPoints[i]); return true; } } contactRecorder(contactBuffer); PxCache contactCache; struct ContactCacheAllocator : PxCacheAllocator { PxU8 buffer[1024]; ContactCacheAllocator() { memset(buffer, 0, sizeof(buffer)); } virtual PxU8* allocateCacheData(const PxU32 /*byteSize*/) { return reinterpret_cast<PxU8*>(size_t(buffer + 0xf) & ~0xf); } } contactCacheAllocator; int sx, sy, sz, ex, ey, ez; getVoxelRegion(bounds1, sx, sy, sz, ex, ey, ez); for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (voxel(x, y, z)) { PxTransform p0 = pose0.transform(PxTransform(voxelPos(x, y, z))); immediate::PxGenerateContacts(&pGeom0, &pGeom1, &p0, &pose1, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); } return true; } PxU32 VoxelMap::raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& /*geom*/, const PxTransform& pose, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* rayHits, PxU32 stride, PxRaycastThreadContext*) const { PxVec3 p = pose.transformInv(origin); PxVec3 n = pose.rotateInv(unitDir); PxVec3 s = voxelSize() * 0.5f; int x, y, z; pointCoords(p, x, y, z); int hitCount = 0; PxU8* hitBuffer = reinterpret_cast<PxU8*>(rayHits); float currDist = 0; PxVec3 hitN(0); while (currDist < maxDist) { PxVec3 v = voxelPos(x, y, z); if (voxel(x, y, z)) { PxGeomRaycastHit& h = *reinterpret_cast<PxGeomRaycastHit*>(hitBuffer + hitCount * stride); h.distance = currDist; if (hitFlags.isSet(PxHitFlag::ePOSITION)) h.position = origin + unitDir * currDist; if (hitFlags.isSet(PxHitFlag::eNORMAL)) h.normal = hitN; if (hitFlags.isSet(PxHitFlag::eFACE_INDEX)) h.faceIndex = (x) | (y << 10) | (z << 20); hitCount += 1; } if (hitCount == int(maxHits)) break; float step = FLT_MAX; int dx = 0, dy = 0, dz = 0; if (n.x > FLT_EPSILON) { float d = (v.x + s.x - p.x) / n.x; if (d < step) { step = d; dx = 1; dy = 0; dz = 0; } } if (n.x < -FLT_EPSILON) { float d = (v.x - s.x - p.x) / n.x; if (d < step) { step = d; dx = -1; dy = 0; dz = 0; } } if (n.y > FLT_EPSILON) { float d = (v.y + s.y - p.y) / n.y; if (d < step) { step = d; dx = 0; dy = 1; dz = 0; } } if (n.y < -FLT_EPSILON) { float d = (v.y - s.y - p.y) / n.y; if (d < step) { step = d; dx = 0; dy = -1; dz = 0; } } if (n.z > FLT_EPSILON) { float d = (v.z + s.z - p.z) / n.z; if (d < step) { step = d; dx = 0; dy = 0; dz = 1; } } if (n.z < -FLT_EPSILON) { float d = (v.z - s.z - p.z) / n.z; if (d < step) { step = d; dx = 0; dy = 0; dz = -1; } } x += dx; y += dy; z += dz; hitN = PxVec3(float(-dx), float(-dy), float(-dz)); currDist = step; } return hitCount; } bool VoxelMap::overlap(const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext*) const { PxBoxGeometry voxelGeom(voxelSize() * 0.5f); PxTransform pose1in0 = pose0.transformInv(pose1); PxBounds3 bounds1; PxGeometryQuery::computeGeomBounds(bounds1, geom1, pose1in0); int sx, sy, sz, ex, ey, ez; getVoxelRegion(bounds1, sx, sy, sz, ex, ey, ez); for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (voxel(x, y, z)) { PxTransform p0 = pose0.transform(PxTransform(voxelPos(x, y, z))); if (PxGeometryQuery::overlap(voxelGeom, p0, geom1, pose1, PxGeometryQueryFlags(0))) return true; } return false; } bool VoxelMap::sweep(const PxVec3& unitDir, const PxReal maxDist, const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxReal inflation, PxSweepThreadContext*) const { PxBoxGeometry voxelGeom(voxelSize() * 0.5f); PxTransform pose1in0 = pose0.transformInv(pose1); PxBounds3 b; PxGeometryQuery::computeGeomBounds(b, geom1, pose1in0, 0, 1.0f, PxGeometryQueryFlags(0)); PxVec3 n = pose0.rotateInv(unitDir); PxVec3 s = voxelSize(); int sx, sy, sz, ex, ey, ez; getVoxelRegion(b, sx, sy, sz, ex, ey, ez); int sx1, sy1, sz1, ex1, ey1, ez1; sx1 = sy1 = sz1 = -1; ex1 = ey1 = ez1 = 0; float currDist = 0; sweepHit.distance = FLT_MAX; while (currDist < maxDist && currDist < sweepHit.distance) { for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (voxel(x, y, z)) { if (x >= sx1 && x <= ex1 && y >= sy1 && y <= ey1 && z >= sz1 && z <= ez1) continue; PxGeomSweepHit hit; PxTransform p0 = pose0.transform(PxTransform(voxelPos(x, y, z))); if (PxGeometryQuery::sweep(unitDir, maxDist, geom1, pose1, voxelGeom, p0, hit, hitFlags, inflation, PxGeometryQueryFlags(0))) if (hit.distance < sweepHit.distance) sweepHit = hit; } PxVec3 mi = b.minimum, ma = b.maximum; PxVec3 bs = voxelPos(sx, sy, sz) - s, be = voxelPos(ex, ey, ez) + s; float dist = FLT_MAX; if (n.x > FLT_EPSILON) { float d = (be.x - ma.x) / n.x; if (d < dist) dist = d; } if (n.x < -FLT_EPSILON) { float d = (bs.x - mi.x) / n.x; if (d < dist) dist = d; } if (n.y > FLT_EPSILON) { float d = (be.y - ma.y) / n.y; if (d < dist) dist = d; } if (n.y < -FLT_EPSILON) { float d = (bs.y - mi.y) / n.y; if (d < dist) dist = d; } if (n.z > FLT_EPSILON) { float d = (be.z - ma.z) / n.z; if (d < dist) dist = d; } if (n.z < -FLT_EPSILON) { float d = (bs.z - mi.z) / n.z; if (d < dist) dist = d; } sx1 = sx; sy1 = sy; sz1 = sz; ex1 = ex; ey1 = ey; ez1 = ez; PxBounds3 b1 = b; b1.minimum += n * dist; b1.maximum += n * dist; getVoxelRegion(b1, sx, sy, sz, ex, ey, ez); currDist = dist; } return sweepHit.distance < FLT_MAX; } void VoxelMap::visualize(const physx::PxGeometry& /*geom*/, physx::PxRenderOutput& render, const physx::PxTransform& transform, const physx::PxBounds3& /*bound*/) const { PxVec3 extents = voxelSize() * 0.5f; render << transform; for (int x = 0; x < dimX(); ++x) for (int y = 0; y < dimY(); ++y) for (int z = 0; z < dimZ(); ++z) if (voxel(x, y, z)) { if (voxel(x + 1, y, z) && voxel(x - 1, y, z) && voxel(x, y + 1, z) && voxel(x, y - 1, z) && voxel(x, y, z + 1) && voxel(x, y, z - 1)) continue; PxVec3 pos = voxelPos(x, y, z); PxBounds3 bounds(pos - extents, pos + extents); physx::PxDebugBox box(bounds, true); render << box; } }
13,283
C++
28.784753
168
0.621847
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometry/SnippetCustomGeometry.cpp
// 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-2023 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 shows how to use custom geometries in PhysX. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" #include "VoxelMap.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidStatic* gActor = NULL; static const int gVoxelMapDim = 20; static const float gVoxelMapSize = 80.0f; static VoxelMap* gVoxelMap; static PxArray<PxVec3> gVertices; static PxArray<PxU32> gIndices; static PxU32 gVertexCount; static PxU32 gIndexCount; static PxGeometryHolder gVoxelGeometryHolder; static const PxU32 gVertexOrder[12] = { 0, 2, 1, 2, 3, 1, 0, 1, 2, 2, 1, 3 }; PX_INLINE void cookVoxelFace(bool reverseWinding) { for (int i = 0; i < 6; ++i) { gIndices[gIndexCount + i] = gVertexCount + gVertexOrder[i + (reverseWinding ? 6 : 0)]; } gVertexCount += 4; gIndexCount += 6; } void cookVoxelMesh() { int faceCount = 0; gVertexCount = 0; gIndexCount = 0; float vx[2] = {gVoxelMap->voxelSize().x * -0.5f, gVoxelMap->voxelSize().x * 0.5f}; float vy[2] = {gVoxelMap->voxelSize().y * -0.5f, gVoxelMap->voxelSize().y * 0.5f}; float vz[2] = {gVoxelMap->voxelSize().z * -0.5f, gVoxelMap->voxelSize().z * 0.5f}; for (int x = 0; x < gVoxelMap->dimX(); ++x) for (int y = 0; y < gVoxelMap->dimY(); ++y) for (int z = 0; z < gVoxelMap->dimZ(); ++z) if (gVoxelMap->voxel(x, y, z)) { if (!gVoxelMap->voxel(x+1, y, z)) {faceCount++;} if (!gVoxelMap->voxel(x-1, y, z)) {faceCount++;} if (!gVoxelMap->voxel(x, y+1, z)) {faceCount++;} if (!gVoxelMap->voxel(x, y-1, z)) {faceCount++;} if (!gVoxelMap->voxel(x, y, z+1)) {faceCount++;} if (!gVoxelMap->voxel(x, y, z-1)) {faceCount++;} } gVertices.resize(faceCount*4); gIndices.resize(faceCount*6); for (int x = 0; x < gVoxelMap->dimX(); ++x) { for (int y = 0; y < gVoxelMap->dimY(); ++y) { for (int z = 0; z < gVoxelMap->dimZ(); ++z) { PxVec3 voxelPos = gVoxelMap->voxelPos(x, y, z); if (gVoxelMap->voxel(x, y, z)) { if (!gVoxelMap->voxel(x+1, y, z)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[1], vy[0], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[1], vy[0], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[1], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[1], vz[1]); cookVoxelFace(false); } if (!gVoxelMap->voxel(x-1, y, z)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[0], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[0], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[0], vy[1], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[0], vy[1], vz[1]); cookVoxelFace(true); } if (!gVoxelMap->voxel(x, y+1, z)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[1], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[1], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[1], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[1], vz[1]); cookVoxelFace(true); } if (!gVoxelMap->voxel(x, y-1, z)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[0], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[0], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[0], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[0], vz[1]); cookVoxelFace(false); } if (!gVoxelMap->voxel(x, y, z+1)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[0], vz[1]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[1], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[0], vz[1]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[1], vz[1]); cookVoxelFace(false); } if (!gVoxelMap->voxel(x, y, z-1)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[0], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[1], vz[0]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[0], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[1], vz[0]); cookVoxelFace(true); } } } } } const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; PxTriangleMeshDesc triangleMeshDesc; triangleMeshDesc.points.count = gVertexCount; triangleMeshDesc.points.data = gVertices.begin(); triangleMeshDesc.points.stride = sizeof(PxVec3); triangleMeshDesc.triangles.count = gIndexCount / 3; triangleMeshDesc.triangles.data = gIndices.begin(); triangleMeshDesc.triangles.stride = 3 * sizeof(PxU32); PxTriangleMesh* gTriangleMesh = PxCreateTriangleMesh(params, triangleMeshDesc); gVoxelGeometryHolder.storeAny( PxTriangleMeshGeometry(gTriangleMesh) ); } static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0), PxReal density = 1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i < size; i++) { for (PxU32 j = 0; j < size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void initVoxelMap() { gVoxelMap = PX_NEW(VoxelMap); gVoxelMap->setDimensions(gVoxelMapDim, gVoxelMapDim, gVoxelMapDim); gVoxelMap->setVoxelSize(gVoxelMapSize / gVoxelMapDim, gVoxelMapSize / gVoxelMapDim, gVoxelMapSize / gVoxelMapDim); gVoxelMap->setWaveVoxels(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gScene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 1.0f); gScene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.0f); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Create voxel map actor initVoxelMap(); PxRigidStatic* voxelMapActor = gPhysics->createRigidStatic(PxTransform(PxVec3(0, gVoxelMapSize * 0.5f, 0))); PxShape* shape = PxRigidActorExt::createExclusiveShape(*voxelMapActor, PxCustomGeometry(*gVoxelMap), *gMaterial); shape->setFlag(PxShapeFlag::eVISUALIZATION, true); gScene->addActor(*voxelMapActor); gActor = voxelMapActor; gActor->setActorFlag(PxActorFlag::eVISUALIZATION, true); // Ground plane PxRigidStatic* planeActor = gPhysics->createRigidStatic(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 0, 1)))); PxRigidActorExt::createExclusiveShape(*planeActor, PxPlaneGeometry(), *gMaterial); gScene->addActor(*planeActor); gScene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.f); gScene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 1.0f); createStack(PxTransform(PxVec3(0, 22, 0)), 10, 2.0f); cookVoxelMesh(); } void debugRender() { PxTransform pose = gActor->getGlobalPose(); Snippets::renderGeoms(1, &gVoxelGeometryHolder, &pose, false, PxVec3(0.5f)); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_DELETE(gVoxelMap); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); gVertices.reset(); gIndices.reset(); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetCustomGeometry done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch (toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0, 0, -1)) * 200, 3.0f); break; } } int snippetMain(int, const char* const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for (PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char* const*) { return 0; } #endif
11,989
C++
35.554878
145
0.694553
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetCamera.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_SNIPPET_CAMERA_H #define PHYSX_SNIPPET_CAMERA_H #include "foundation/PxTransform.h" namespace Snippets { class Camera { public: Camera(const physx::PxVec3& eye, const physx::PxVec3& dir); void handleMouse(int button, int state, int x, int y); bool handleKey(unsigned char key, int x, int y, float speed = 0.5f); void handleMotion(int x, int y); void handleAnalogMove(float x, float y); physx::PxVec3 getEye() const; physx::PxVec3 getDir() const; physx::PxTransform getTransform() const; void setPose(const physx::PxVec3& eye, const physx::PxVec3& dir); void setSpeed(float speed); private: physx::PxVec3 mEye; physx::PxVec3 mDir; int mMouseX; int mMouseY; float mSpeed; }; } #endif //PHYSX_SNIPPET_CAMERA_H
2,479
C
38.365079
74
0.743445
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetCamera.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "SnippetCamera.h" #include <ctype.h> #include "foundation/PxMat33.h" using namespace physx; namespace Snippets { Camera::Camera(const PxVec3& eye, const PxVec3& dir) : mMouseX(0), mMouseY(0), mSpeed(2.0f) { mEye = eye; mDir = dir.getNormalized(); } void Camera::handleMouse(int button, int state, int x, int y) { PX_UNUSED(state); PX_UNUSED(button); mMouseX = x; mMouseY = y; } bool Camera::handleKey(unsigned char key, int x, int y, float speed) { PX_UNUSED(x); PX_UNUSED(y); const PxVec3 viewY = mDir.cross(PxVec3(0,1,0)).getNormalized(); switch(toupper(key)) { case 'W': mEye += mDir*mSpeed*speed; break; case 'S': mEye -= mDir*mSpeed*speed; break; case 'A': mEye -= viewY*mSpeed*speed; break; case 'D': mEye += viewY*mSpeed*speed; break; default: return false; } return true; } void Camera::handleAnalogMove(float x, float y) { PxVec3 viewY = mDir.cross(PxVec3(0,1,0)).getNormalized(); mEye += mDir*y; mEye += viewY*x; } void Camera::handleMotion(int x, int y) { const int dx = mMouseX - x; const int dy = mMouseY - y; const PxVec3 viewY = mDir.cross(PxVec3(0,1,0)).getNormalized(); const float Sensitivity = PxPi * 0.5f / 180.0f; const PxQuat qx(Sensitivity * dx, PxVec3(0,1,0)); mDir = qx.rotate(mDir); const PxQuat qy(Sensitivity * dy, viewY); mDir = qy.rotate(mDir); mDir.normalize(); mMouseX = x; mMouseY = y; } PxTransform Camera::getTransform() const { PxVec3 viewY = mDir.cross(PxVec3(0,1,0)); if(viewY.normalize()<1e-6f) return PxTransform(mEye); const PxMat33 m(mDir.cross(viewY), viewY, -mDir); return PxTransform(mEye, PxQuat(m)); } PxVec3 Camera::getEye() const { return mEye; } PxVec3 Camera::getDir() const { return mDir; } void Camera::setPose(const PxVec3& eye, const PxVec3& dir) { mEye = eye; mDir = dir; } void Camera::setSpeed(float speed) { mSpeed = speed; } }
3,579
C++
26.538461
91
0.715284
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetRender.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_SNIPPET_RENDER_H #define PHYSX_SNIPPET_RENDER_H #include "PxPhysicsAPI.h" #include "foundation/PxPreprocessor.h" #if PX_WINDOWS #include <windows.h> #pragma warning(disable: 4505) #include <GL/glew.h> #include <GL/freeglut.h> #elif PX_LINUX_FAMILY #if PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-identifier" #endif #include <GL/glew.h> #include <GL/freeglut.h> #if PX_CLANG #pragma clang diagnostic pop #endif #elif PX_OSX #include <GL/glew.h> #include <GLUT/glut.h> #else #error platform not supported. #endif typedef void (*KeyboardCallback) (unsigned char key, const physx::PxTransform& camera); typedef void (*RenderCallback) (); typedef void (*ExitCallback) (); namespace Snippets { class Camera; void setupDefault(const char* name, Camera* camera, KeyboardCallback kbcb, RenderCallback rdcb, ExitCallback excb); Camera* getCamera(); physx::PxVec3 computeWorldRayF(float xs, float ys, const physx::PxVec3& camDir); PX_FORCE_INLINE physx::PxVec3 computeWorldRay(int xs, int ys, const physx::PxVec3& camDir) { return computeWorldRayF(float(xs), float(ys), camDir); } physx::PxU32 getScreenWidth(); physx::PxU32 getScreenHeight(); void enableVSync(bool vsync); void startRender(const Camera* camera, float nearClip = 1.0f, float farClip = 10000.0f, float fov=60.0f, bool setupLighting=true); void finishRender(); void print(const char* text); class TriggerRender { public: virtual bool isTrigger(physx::PxShape*) const = 0; }; #if PX_SUPPORT_GPU_PHYSX class SharedGLBuffer { public: SharedGLBuffer(); ~SharedGLBuffer(); void initialize(physx::PxCudaContextManager* contextManager); void allocate(physx::PxU32 sizeInBytes); void release(); void* map(); void unmap(); private: physx::PxCudaContextManager* cudaContextManager; void* vbo_res; void* devicePointer; public: GLuint vbo; //Opengl vertex buffer object physx::PxU32 size; }; #endif void initFPS(); void showFPS(int updateIntervalMS = 30, const char* info = NULL); void renderSoftBody(physx::PxSoftBody* softBody, const physx::PxVec4* deformedPositionsInvMass, bool shadows, const physx::PxVec3& color = physx::PxVec3(0.0f, 0.75f, 0.0f)); void renderActors(physx::PxRigidActor** actors, const physx::PxU32 numActors, bool shadows = false, const physx::PxVec3& color = physx::PxVec3(0.0f, 0.75f, 0.0f), TriggerRender* cb = NULL, bool changeColorForSleepingActors = true, bool wireframePass=true); // void renderGeoms(const physx::PxU32 nbGeoms, const physx::PxGeometry* geoms, const physx::PxTransform* poses, bool shadows, const physx::PxVec3& color); void renderGeoms(const physx::PxU32 nbGeoms, const physx::PxGeometryHolder* geoms, const physx::PxTransform* poses, bool shadows, const physx::PxVec3& color); void renderMesh(physx::PxU32 nbVerts, const physx::PxVec3* verts, physx::PxU32 nbTris, const physx::PxU32* indices, const physx::PxVec3& color, const physx::PxVec3* normals = NULL, bool flipFaceOrientation = false); void renderMesh(physx::PxU32 nbVerts, const physx::PxVec4* verts, physx::PxU32 nbTris, const physx::PxU32* indices, const physx::PxVec3& color, const physx::PxVec4* normals = NULL, bool flipFaceOrientation = false); void renderMesh(physx::PxU32 nbVerts, const physx::PxVec4* verts, physx::PxU32 nbTris, const void* indices, bool hasSixteenBitIndices, const physx::PxVec3& color, const physx::PxVec4* normals = NULL, bool flipFaceOrientation = false, bool enableBackFaceCulling = true); void renderHairSystem(physx::PxHairSystem* hairSystem, const physx::PxVec4* vertexPositionInvMass, physx::PxU32 numVertices); void DrawLine(const physx::PxVec3& p0, const physx::PxVec3& p1, const physx::PxVec3& color); void DrawPoints(const physx::PxArray<physx::PxVec3>& pts, const physx::PxVec3& color, float scale); void DrawPoints(const physx::PxArray<physx::PxVec3>& pts, const physx::PxArray<physx::PxVec3>& colors, float scale); void DrawPoints(const physx::PxArray<physx::PxVec4>& pts, const physx::PxVec3& color, float scale); void DrawPoints(const physx::PxArray<physx::PxVec4>& pts, const physx::PxArray<physx::PxVec3>& colors, float scale); void DrawPoints(GLuint vbo, physx::PxU32 numPoints, const physx::PxVec3& color, float scale, physx::PxU32 coordinatesPerPoint = 3, physx::PxU32 stride = 4 * sizeof(float), size_t offset = 0); void DrawLines(GLuint vbo, physx::PxU32 numPoints, const physx::PxVec3& color, float scale, physx::PxU32 coordinatesPerPoint = 3, physx::PxU32 stride = 4 * sizeof(float), size_t offset = 0); void DrawIcosahedraPoints(const physx::PxArray<physx::PxVec3>& pts, const physx::PxVec3& color, float radius); void DrawFrame(const physx::PxVec3& pt, float scale=1.0f); void DrawBounds(const physx::PxBounds3& box); void DrawBounds(const physx::PxBounds3& box, const physx::PxVec3& color); void DrawMeshIndexedNoNormals(GLuint vbo, GLuint elementbuffer, GLuint numTriangles, const physx::PxVec3& color, physx::PxU32 stride = 4 * sizeof(float)); void DrawMeshIndexed(GLuint vbo, GLuint elementbuffer, GLuint numTriangles, const physx::PxVec3& color, physx::PxU32 stride = 6 * sizeof(float)); GLuint CreateTexture(physx::PxU32 width, physx::PxU32 height, const GLubyte* buffer, bool createMipmaps); void UpdateTexture(GLuint texId, physx::PxU32 width, physx::PxU32 height, const GLubyte* buffer, bool createMipmaps); void ReleaseTexture(GLuint texId); void DrawRectangle(float x_start, float x_end, float y_start, float y_end, const physx::PxVec3& color_top, const physx::PxVec3& color_bottom, float alpha, physx::PxU32 screen_width, physx::PxU32 screen_height, bool draw_outline, bool texturing); void DisplayTexture(GLuint texId, physx::PxU32 size, physx::PxU32 margin); } #endif //PHYSX_SNIPPET_RENDER_H
7,484
C
50.620689
270
0.757215
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetRender.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #define USE_CUDA_INTEROP (!PX_PUBLIC_RELEASE) #if (PX_SUPPORT_GPU_PHYSX && USE_CUDA_INTEROP) #if PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include "cuda.h" #include "SnippetRender.h" #include "cudaGL.h" #if PX_LINUX && PX_CLANG #pragma clang diagnostic pop #endif #else #include "SnippetRender.h" #endif #include "SnippetFontRenderer.h" #include "SnippetCamera.h" #include "foundation/PxArray.h" #include "foundation/PxMathUtils.h" #include <vector> #define MAX_NUM_ACTOR_SHAPES 128 #define INITIAL_SCREEN_WIDTH 768 #define INITIAL_SCREEN_HEIGHT 768 using namespace physx; static GLFontRenderer gTexter; static float gCylinderData[]={ 1.0f,0.0f,1.0f,1.0f,0.0f,1.0f,1.0f,0.0f,0.0f,1.0f,0.0f,0.0f, 0.866025f,0.500000f,1.0f,0.866025f,0.500000f,1.0f,0.866025f,0.500000f,0.0f,0.866025f,0.500000f,0.0f, 0.500000f,0.866025f,1.0f,0.500000f,0.866025f,1.0f,0.500000f,0.866025f,0.0f,0.500000f,0.866025f,0.0f, -0.0f,1.0f,1.0f,-0.0f,1.0f,1.0f,-0.0f,1.0f,0.0f,-0.0f,1.0f,0.0f, -0.500000f,0.866025f,1.0f,-0.500000f,0.866025f,1.0f,-0.500000f,0.866025f,0.0f,-0.500000f,0.866025f,0.0f, -0.866025f,0.500000f,1.0f,-0.866025f,0.500000f,1.0f,-0.866025f,0.500000f,0.0f,-0.866025f,0.500000f,0.0f, -1.0f,-0.0f,1.0f,-1.0f,-0.0f,1.0f,-1.0f,-0.0f,0.0f,-1.0f,-0.0f,0.0f, -0.866025f,-0.500000f,1.0f,-0.866025f,-0.500000f,1.0f,-0.866025f,-0.500000f,0.0f,-0.866025f,-0.500000f,0.0f, -0.500000f,-0.866025f,1.0f,-0.500000f,-0.866025f,1.0f,-0.500000f,-0.866025f,0.0f,-0.500000f,-0.866025f,0.0f, 0.0f,-1.0f,1.0f,0.0f,-1.0f,1.0f,0.0f,-1.0f,0.0f,0.0f,-1.0f,0.0f, 0.500000f,-0.866025f,1.0f,0.500000f,-0.866025f,1.0f,0.500000f,-0.866025f,0.0f,0.500000f,-0.866025f,0.0f, 0.866026f,-0.500000f,1.0f,0.866026f,-0.500000f,1.0f,0.866026f,-0.500000f,0.0f,0.866026f,-0.500000f,0.0f, 1.0f,0.0f,1.0f,1.0f,0.0f,1.0f,1.0f,0.0f,0.0f,1.0f,0.0f,0.0f }; static std::vector<PxVec3>* gVertexBuffer = NULL; static int gLastTime = 0; static int gFrameCounter = 0; static char gTitle[256]; static bool gWireFrame = false; static PX_FORCE_INLINE void prepareVertexBuffer() { if(!gVertexBuffer) gVertexBuffer = new std::vector<PxVec3>; gVertexBuffer->clear(); } static PX_FORCE_INLINE void pushVertex(const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& n) { PX_ASSERT(gVertexBuffer); gVertexBuffer->push_back(n); gVertexBuffer->push_back(v0); gVertexBuffer->push_back(n); gVertexBuffer->push_back(v1); gVertexBuffer->push_back(n); gVertexBuffer->push_back(v2); } static PX_FORCE_INLINE void pushVertex(const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& n0, const PxVec3& n1, const PxVec3& n2, float normalSign = 1) { PX_ASSERT(gVertexBuffer); gVertexBuffer->push_back(normalSign * n0); gVertexBuffer->push_back(v0); gVertexBuffer->push_back(normalSign * n1); gVertexBuffer->push_back(v1); gVertexBuffer->push_back(normalSign * n2); gVertexBuffer->push_back(v2); } static PX_FORCE_INLINE const PxVec3* getVertexBuffer() { PX_ASSERT(gVertexBuffer); return &(*gVertexBuffer)[0]; } static void releaseVertexBuffer() { if(gVertexBuffer) { delete gVertexBuffer; gVertexBuffer = NULL; } } static void renderSoftBodyGeometry(const PxTetrahedronMesh& mesh, const PxVec4* deformedPositionsInvMass) { const int tetFaces[4][3] = { {0,2,1}, {0,1,3}, {0,3,2}, {1,2,3} }; //Get the deformed vertices //const PxVec3* vertices = mesh.getVertices(); const PxU32 tetCount = mesh.getNbTetrahedrons(); const PxU32 has16BitIndices = mesh.getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES; const void* indexBuffer = mesh.getTetrahedrons(); prepareVertexBuffer(); const PxU32* intIndices = reinterpret_cast<const PxU32*>(indexBuffer); const PxU16* shortIndices = reinterpret_cast<const PxU16*>(indexBuffer); PxU32 numTotalTriangles = 0; for (PxU32 i = 0; i < tetCount; ++i) { PxU32 vref[4]; if (has16BitIndices) { vref[0] = *shortIndices++; vref[1] = *shortIndices++; vref[2] = *shortIndices++; vref[3] = *shortIndices++; } else { vref[0] = *intIndices++; vref[1] = *intIndices++; vref[2] = *intIndices++; vref[3] = *intIndices++; } for (PxU32 j = 0; j < 4; ++j) { const PxVec4& v0 = deformedPositionsInvMass[vref[tetFaces[j][0]]]; const PxVec4& v1 = deformedPositionsInvMass[vref[tetFaces[j][1]]]; const PxVec4& v2 = deformedPositionsInvMass[vref[tetFaces[j][2]]]; PxVec3 fnormal = (v1.getXYZ() - v0.getXYZ()).cross(v2.getXYZ() - v0.getXYZ()); fnormal.normalize(); pushVertex(v0.getXYZ(), v1.getXYZ(), v2.getXYZ(), fnormal); numTotalTriangles++; } } glPushMatrix(); glScalef(1.0f, 1.0f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer + 1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); } static void renderGeometry(const PxGeometry& geom) { if (gWireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); switch(geom.getType()) { case PxGeometryType::eBOX: { const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom); glScalef(boxGeom.halfExtents.x, boxGeom.halfExtents.y, boxGeom.halfExtents.z); glutSolidCube(2); } break; case PxGeometryType::eSPHERE: { const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom); glutSolidSphere(GLdouble(sphereGeom.radius), 10, 10); } break; case PxGeometryType::eCAPSULE: { const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom); const PxF32 radius = capsuleGeom.radius; const PxF32 halfHeight = capsuleGeom.halfHeight; //Sphere glPushMatrix(); glTranslatef(halfHeight, 0.0f, 0.0f); glScalef(radius,radius,radius); glutSolidSphere(1, 10, 10); glPopMatrix(); //Sphere glPushMatrix(); glTranslatef(-halfHeight, 0.0f, 0.0f); glScalef(radius,radius,radius); glutSolidSphere(1, 10, 10); glPopMatrix(); //Cylinder glPushMatrix(); glTranslatef(-halfHeight, 0.0f, 0.0f); glScalef(2.0f*halfHeight, radius,radius); glRotatef(90.0f,0.0f,1.0f,0.0f); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), gCylinderData); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), gCylinderData+3); glDrawArrays(GL_TRIANGLE_STRIP, 0, 13*2); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); } break; case PxGeometryType::eCONVEXMESH: { const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom); //Compute triangles for each polygon. const PxVec3& scale = convexGeom.scale.scale; PxConvexMesh* mesh = convexGeom.convexMesh; const PxU32 nbPolys = mesh->getNbPolygons(); const PxU8* polygons = mesh->getIndexBuffer(); const PxVec3* verts = mesh->getVertices(); PxU32 nbVerts = mesh->getNbVertices(); PX_UNUSED(nbVerts); prepareVertexBuffer(); PxU32 numTotalTriangles = 0; for(PxU32 i = 0; i < nbPolys; i++) { PxHullPolygon data; mesh->getPolygonData(i, data); const PxU32 nbTris = PxU32(data.mNbVerts - 2); const PxU8 vref0 = polygons[data.mIndexBase + 0]; PX_ASSERT(vref0 < nbVerts); for(PxU32 j=0;j<nbTris;j++) { const PxU32 vref1 = polygons[data.mIndexBase + 0 + j + 1]; const PxU32 vref2 = polygons[data.mIndexBase + 0 + j + 2]; //generate face normal: PxVec3 e0 = verts[vref1] - verts[vref0]; PxVec3 e1 = verts[vref2] - verts[vref0]; PX_ASSERT(vref1 < nbVerts); PX_ASSERT(vref2 < nbVerts); PxVec3 fnormal = e0.cross(e1); fnormal.normalize(); pushVertex(verts[vref0], verts[vref1], verts[vref2], fnormal); numTotalTriangles++; } } glPushMatrix(); glScalef(scale.x, scale.y, scale.z); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), vertexBuffer+1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glPopMatrix(); } break; case PxGeometryType::eTRIANGLEMESH: { const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(geom); const PxTriangleMesh& mesh = *triGeom.triangleMesh; const PxVec3 scale = triGeom.scale.scale; const PxU32 triangleCount = mesh.getNbTriangles(); const PxU32 has16BitIndices = mesh.getTriangleMeshFlags() & PxTriangleMeshFlag::e16_BIT_INDICES; const void* indexBuffer = mesh.getTriangles(); const PxVec3* vertices = mesh.getVertices(); prepareVertexBuffer(); const PxU32* intIndices = reinterpret_cast<const PxU32*>(indexBuffer); const PxU16* shortIndices = reinterpret_cast<const PxU16*>(indexBuffer); PxU32 numTotalTriangles = 0; for(PxU32 i=0; i < triangleCount; ++i) { PxU32 vref0, vref1, vref2; if(has16BitIndices) { vref0 = *shortIndices++; vref1 = *shortIndices++; vref2 = *shortIndices++; } else { vref0 = *intIndices++; vref1 = *intIndices++; vref2 = *intIndices++; } const PxVec3& v0 = vertices[vref0]; const PxVec3& v1 = vertices[vref1]; const PxVec3& v2 = vertices[vref2]; PxVec3 fnormal = (v1 - v0).cross(v2 - v0); fnormal.normalize(); pushVertex(v0, v1, v2, fnormal); numTotalTriangles++; } glPushMatrix(); glScalef(scale.x, scale.y, scale.z); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), vertexBuffer+1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); } break; case PxGeometryType::eTETRAHEDRONMESH: { const int tetFaces[4][3] = { {0,2,1}, {0,1,3}, {0,3,2}, {1,2,3} }; const PxTetrahedronMeshGeometry& tetGeom = static_cast<const PxTetrahedronMeshGeometry&>(geom); const PxTetrahedronMesh& mesh = *tetGeom.tetrahedronMesh; //Get the deformed vertices const PxVec3* vertices = mesh.getVertices(); const PxU32 tetCount = mesh.getNbTetrahedrons(); const PxU32 has16BitIndices = mesh.getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES; const void* indexBuffer = mesh.getTetrahedrons(); prepareVertexBuffer(); const PxU32* intIndices = reinterpret_cast<const PxU32*>(indexBuffer); const PxU16* shortIndices = reinterpret_cast<const PxU16*>(indexBuffer); PxU32 numTotalTriangles = 0; for (PxU32 i = 0; i < tetCount; ++i) { PxU32 vref[4]; if (has16BitIndices) { vref[0] = *shortIndices++; vref[1] = *shortIndices++; vref[2] = *shortIndices++; vref[3] = *shortIndices++; } else { vref[0] = *intIndices++; vref[1] = *intIndices++; vref[2] = *intIndices++; vref[3] = *intIndices++; } for (PxU32 j = 0; j < 4; ++j) { const PxVec3& v0 = vertices[vref[tetFaces[j][0]]]; const PxVec3& v1 = vertices[vref[tetFaces[j][1]]]; const PxVec3& v2 = vertices[vref[tetFaces[j][2]]]; PxVec3 fnormal = (v1 - v0).cross(v2 - v0); fnormal.normalize(); pushVertex(v0, v1, v2, fnormal); numTotalTriangles++; } } glPushMatrix(); glScalef(1.0f, 1.0f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer + 1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); } break; default: break; } if (gWireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } static Snippets::Camera* gCamera = NULL; static KeyboardCallback gKbCb = NULL; static PxU32 gScreenWidth = 0; static PxU32 gScreenHeight = 0; static void defaultReshapeCallback(int width, int height) { glViewport(0, 0, width, height); gTexter.setScreenResolution(width, height); gScreenWidth = width; gScreenHeight = height; } static void defaultIdleCallback() { glutPostRedisplay(); } static bool gMoveCamera = false; static void defaultMotionCallback(int x, int y) { if(gCamera && gMoveCamera) gCamera->handleMotion(x, y); } static void defaultMouseCallback(int button, int state, int x, int y) { if(button==0) gMoveCamera = state==0; if(gCamera) gCamera->handleMouse(button, state, x, y); } static void defaultKeyboardCallback(unsigned char key, int x, int y) { if(key==27) glutLeaveMainLoop(); if (key == 110) //n gWireFrame = !gWireFrame; const bool status = gCamera ? gCamera->handleKey(key, x, y) : false; if(!status && gKbCb) gKbCb(key, gCamera ? gCamera->getTransform() : PxTransform(PxIdentity)); } static void defaultSpecialCallback(int key, int x, int y) { switch(key) { case GLUT_KEY_UP: key='W'; break; case GLUT_KEY_DOWN: key='S'; break; case GLUT_KEY_LEFT: key='A'; break; case GLUT_KEY_RIGHT: key='D'; break; } const bool status = gCamera ? gCamera->handleKey((unsigned char)key, x, y) : false; if(!status && gKbCb) gKbCb((unsigned char)key, gCamera ? gCamera->getTransform() : PxTransform(PxIdentity)); } static ExitCallback gUserExitCB = NULL; static void defaultExitCallback() { releaseVertexBuffer(); if(gUserExitCB) (gUserExitCB)(); } static void setupDefaultWindow(const char* name, RenderCallback rdcb) { char* namestr = new char[strlen(name)+1]; strcpy(namestr, name); int argc = 1; char* argv[1] = { namestr }; glutInit(&argc, argv); gScreenWidth = INITIAL_SCREEN_WIDTH; gScreenHeight = INITIAL_SCREEN_HEIGHT; gTexter.init(); gTexter.setScreenResolution(gScreenWidth, gScreenHeight); gTexter.setColor(1.0f, 1.0f, 1.0f, 1.0f); glutInitWindowSize(gScreenWidth, gScreenHeight); glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH); int mainHandle = glutCreateWindow(name); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } glutSetWindow(mainHandle); glutReshapeFunc(defaultReshapeCallback); glutIdleFunc(defaultIdleCallback); glutKeyboardFunc(defaultKeyboardCallback); glutSpecialFunc(defaultSpecialCallback); glutMouseFunc(defaultMouseCallback); glutMotionFunc(defaultMotionCallback); if(rdcb) glutDisplayFunc(rdcb); defaultMotionCallback(0,0); delete[] namestr; } static void setupDefaultRenderState() { // Setup default render states // glClearColor(0.3f, 0.4f, 0.5f, 1.0); glClearColor(0.2f, 0.2f, 0.2f, 1.0); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); // Setup lighting /* glEnable(GL_LIGHTING); PxReal ambientColor[] = { 0.0f, 0.1f, 0.2f, 0.0f }; PxReal diffuseColor[] = { 1.0f, 1.0f, 1.0f, 0.0f }; PxReal specularColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; PxReal position[] = { 100.0f, 100.0f, 400.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, ambientColor); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseColor); glLightfv(GL_LIGHT0, GL_SPECULAR, specularColor); glLightfv(GL_LIGHT0, GL_POSITION, position); glEnable(GL_LIGHT0);*/ } static void InitLighting() { glEnable(GL_COLOR_MATERIAL); glEnable(GL_NORMALIZE); const float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, zero); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, zero); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, zero); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, zero); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, zero); glEnable(GL_LIGHTING); PxVec3 Dir(-1.0f, 1.0f, 0.5f); // PxVec3 Dir(0.0f, 1.0f, 0.0f); Dir.normalize(); const float AmbientValue = 0.3f; const float ambientColor0[] = { AmbientValue, AmbientValue, AmbientValue, 0.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, ambientColor0); const float specularColor0[] = { 0.0f, 0.0f, 0.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_SPECULAR, specularColor0); const float diffuseColor0[] = { 1.0f, 1.0f, 1.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseColor0); const float position0[] = { Dir.x, Dir.y, Dir.z, 0.0f }; glLightfv(GL_LIGHT0, GL_POSITION, position0); glEnable(GL_LIGHT0); // glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // glColor4f(0.0f, 0.0f, 0.0f, 0.0f); /* glEnable(GL_LIGHTING); PxReal ambientColor[] = { 0.0f, 0.1f, 0.2f, 0.0f }; PxReal diffuseColor[] = { 1.0f, 1.0f, 1.0f, 0.0f }; PxReal specularColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; PxReal position[] = { 100.0f, 100.0f, 400.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, ambientColor); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseColor); glLightfv(GL_LIGHT0, GL_SPECULAR, specularColor); glLightfv(GL_LIGHT0, GL_POSITION, position); glEnable(GL_LIGHT0);*/ if(0) { glEnable(GL_FOG); glFogi(GL_FOG_MODE,GL_LINEAR); //glFogi(GL_FOG_MODE,GL_EXP); //glFogi(GL_FOG_MODE,GL_EXP2); glFogf(GL_FOG_START, 0.0f); glFogf(GL_FOG_END, 100.0f); glFogf(GL_FOG_DENSITY, 0.005f); // glClearColor(0.2f, 0.2f, 0.2f, 1.0); // const PxVec3 FogColor(0.2f, 0.2f, 0.2f); const PxVec3 FogColor(0.3f, 0.4f, 0.5f); // const PxVec3 FogColor(1.0f); glFogfv(GL_FOG_COLOR, &FogColor.x); } } namespace Snippets { void initFPS() { gLastTime = glutGet(GLUT_ELAPSED_TIME); } void showFPS(int updateIntervalMS, const char* info) { ++gFrameCounter; int currentTime = glutGet(GLUT_ELAPSED_TIME); if (currentTime - gLastTime > updateIntervalMS) { if (info) sprintf(gTitle, " FPS : %4.0f%s", gFrameCounter * 1000.0 / (currentTime - gLastTime), info); else sprintf(gTitle, " FPS : %4.0f", gFrameCounter * 1000.0 / (currentTime - gLastTime)); glutSetWindowTitle(gTitle); gLastTime = currentTime; gFrameCounter = 0; } } PxU32 getScreenWidth() { return gScreenWidth; } PxU32 getScreenHeight() { return gScreenHeight; } void enableVSync(bool vsync) { #if PX_WIN32 || PX_WIN64 typedef void (APIENTRY * PFNWGLSWAPINTERVALPROC) (GLenum interval); PFNWGLSWAPINTERVALPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALPROC)wglGetProcAddress("wglSwapIntervalEXT"); wglSwapIntervalEXT(vsync); #else PX_UNUSED(vsync); #endif } void setupDefault(const char* name, Camera* camera, KeyboardCallback kbcb, RenderCallback rdcb, ExitCallback excb) { gCamera = camera; gKbCb = kbcb; setupDefaultWindow(name, rdcb); setupDefaultRenderState(); enableVSync(true); glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); gUserExitCB = excb; atexit(defaultExitCallback); } Camera* getCamera() { return gCamera; } static float gNearClip = 0.0f; static float gFarClip = 0.0f; static float gFOV = 60.0f; static float gTextScale = 0.0f; static float gTextY = 0.0f; PxVec3 computeWorldRayF(float xs, float ys, const PxVec3& camDir) { const float Width = float(gScreenWidth); const float Height = float(gScreenHeight); // Recenter coordinates in camera space ([-1, 1]) const float u = ((xs - Width*0.5f)/Width)*2.0f; const float v = -((ys - Height*0.5f)/Height)*2.0f; // Adjust coordinates according to camera aspect ratio const float HTan = tanf(0.25f * fabsf(PxDegToRad(gFOV * 2.0f))); const float VTan = HTan*(Width/Height); // Ray in camera space const PxVec3 CamRay(VTan*u, HTan*v, 1.0f); // Compute ray in world space PxVec3 Right, Up; PxComputeBasisVectors(camDir, Right, Up); const PxMat33 invView(-Right, Up, camDir); return invView.transform(CamRay).getNormalized(); } void startRender(const Camera* camera, float clipNear, float clipFar, float fov, bool setupLighting) { const PxVec3 cameraEye = camera->getEye(); const PxVec3 cameraDir = camera->getDir(); gNearClip = clipNear; gFarClip = clipFar; gFOV = fov; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Setup camera glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(GLdouble(fov), GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)), GLdouble(clipNear), GLdouble(clipFar)); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(GLdouble(cameraEye.x), GLdouble(cameraEye.y), GLdouble(cameraEye.z), GLdouble(cameraEye.x + cameraDir.x), GLdouble(cameraEye.y + cameraDir.y), GLdouble(cameraEye.z + cameraDir.z), 0.0, 1.0, 0.0); glColor4f(0.4f, 0.4f, 0.4f, 1.0f); if(setupLighting) InitLighting(); gTextScale = 0.0175f * float(INITIAL_SCREEN_HEIGHT) / float(gScreenHeight); gTextY = 1.0f - gTextScale; gTexter.setColor(1.0f, 1.0f, 1.0f, 1.0f); } void finishRender() { glutSwapBuffers(); } void print(const char* text) { gTexter.print(0.0f, gTextY, gTextScale, text); gTextY -= gTextScale; } const PxVec3 shadowDir(0.0f, -0.7071067f, -0.7071067f); const PxReal shadowMat[] = { 1,0,0,0, -shadowDir.x / shadowDir.y,0,-shadowDir.z / shadowDir.y,0, 0,0,1,0, 0,0,0,1 }; void renderSoftBody(PxSoftBody* softBody, const PxVec4* deformedPositionsInvMass, bool shadows, const PxVec3& color) { PxShape* shape = softBody->getShape(); const PxMat44 shapePose(PxIdentity); // (PxShapeExt::getGlobalPose(*shapes[j], *actors[i])); const PxGeometry& geom = shape->getGeometry(); const PxTetrahedronMeshGeometry& tetGeom = static_cast<const PxTetrahedronMeshGeometry&>(geom); const PxTetrahedronMesh& mesh = *tetGeom.tetrahedronMesh; glPushMatrix(); glMultMatrixf(&shapePose.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); renderSoftBodyGeometry(mesh, deformedPositionsInvMass); glPopMatrix(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if (shadows) { glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); //glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glColor4f(0.1f, 0.1f, 0.1f, 1.0f); renderSoftBodyGeometry(mesh, deformedPositionsInvMass); glEnable(GL_LIGHTING); glPopMatrix(); } } void renderHairSystem(physx::PxHairSystem* /*hairSystem*/, const physx::PxVec4* vertexPositionInvMass, PxU32 numVertices) { const PxVec3 color{ 1.0f, 0.0f, 0.0f }; const PxSphereGeometry geom(0.05f); // draw the volume glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); for(PxU32 j=0;j<numVertices;j++) { const PxMat44 shapePose(PxTransform(reinterpret_cast<const PxVec3&>(vertexPositionInvMass[j]))); glPushMatrix(); glMultMatrixf(&shapePose.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); renderGeometry(geom); glPopMatrix(); } // draw the cage lines const GLdouble aspect = GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip * 1.005f), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0f, 0.0f, 0.0f, 1.0f); for (PxU32 j = 0; j < numVertices; j++) { const PxMat44 shapePose(PxTransform(reinterpret_cast<const PxVec3&>(vertexPositionInvMass[j]))); glPushMatrix(); glMultMatrixf(&shapePose.column0.x); renderGeometry(geom); glPopMatrix(); } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); } void renderActors(PxRigidActor** actors, const PxU32 numActors, bool shadows, const PxVec3& color, TriggerRender* cb, bool changeColorForSleepingActors, bool wireframePass) { PxShape* shapes[MAX_NUM_ACTOR_SHAPES]; for(PxU32 i=0;i<numActors;i++) { const PxU32 nbShapes = actors[i]->getNbShapes(); PX_ASSERT(nbShapes <= MAX_NUM_ACTOR_SHAPES); actors[i]->getShapes(shapes, nbShapes); bool sleeping; if (changeColorForSleepingActors) sleeping = actors[i]->is<PxRigidDynamic>() ? actors[i]->is<PxRigidDynamic>()->isSleeping() : false; else sleeping = false; for(PxU32 j=0;j<nbShapes;j++) { const PxMat44 shapePose(PxShapeExt::getGlobalPose(*shapes[j], *actors[i])); const PxGeometry& geom = shapes[j]->getGeometry(); const bool isTrigger = cb ? cb->isTrigger(shapes[j]) : shapes[j]->getFlags() & PxShapeFlag::eTRIGGER_SHAPE; if(isTrigger) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render object glPushMatrix(); glMultMatrixf(&shapePose.column0.x); if(sleeping) { const PxVec3 darkColor = color * 0.25f; glColor4f(darkColor.x, darkColor.y, darkColor.z, 1.0f); } else glColor4f(color.x, color.y, color.z, 1.0f); renderGeometry(geom); glPopMatrix(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(shadows) { glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); //glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glColor4f(0.1f, 0.1f, 0.1f, 1.0f); renderGeometry(geom); glEnable(GL_LIGHTING); glPopMatrix(); } } } if(wireframePass) { const GLdouble aspect = GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip*1.005f), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0f, 0.0f, 0.0f, 1.0f); for(PxU32 i=0;i<numActors;i++) { const PxU32 nbShapes = actors[i]->getNbShapes(); PX_ASSERT(nbShapes <= MAX_NUM_ACTOR_SHAPES); actors[i]->getShapes(shapes, nbShapes); for(PxU32 j=0;j<nbShapes;j++) { const PxMat44 shapePose(PxShapeExt::getGlobalPose(*shapes[j], *actors[i])); glPushMatrix(); glMultMatrixf(&shapePose.column0.x); renderGeometry(shapes[j]->getGeometry()); glPopMatrix(); } } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); } } /*static const PxU32 gGeomSizes[] = { sizeof(PxSphereGeometry), sizeof(PxPlaneGeometry), sizeof(PxCapsuleGeometry), sizeof(PxBoxGeometry), sizeof(PxConvexMeshGeometry), sizeof(PxTriangleMeshGeometry), sizeof(PxHeightFieldGeometry), }; void renderGeoms(const PxU32 nbGeoms, const PxGeometry* geoms, const PxTransform* poses, bool shadows, const PxVec3& color) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); const PxVec3 shadowDir(0.0f, -0.7071067f, -0.7071067f); const PxReal shadowMat[]={ 1,0,0,0, -shadowDir.x/shadowDir.y,0,-shadowDir.z/shadowDir.y,0, 0,0,1,0, 0,0,0,1 }; const PxU8* stream = reinterpret_cast<const PxU8*>(geoms); for(PxU32 j=0;j<nbGeoms;j++) { const PxMat44 shapePose(poses[j]); const PxGeometry& geom = *reinterpret_cast<const PxGeometry*>(stream); stream += gGeomSizes[geom.getType()]; // render object glPushMatrix(); glMultMatrixf(&shapePose.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); renderGeometry(geom); glPopMatrix(); if(shadows) { glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); glColor4f(0.1f, 0.2f, 0.3f, 1.0f); renderGeometry(geom); glEnable(GL_LIGHTING); glPopMatrix(); } } }*/ void renderGeoms(const PxU32 nbGeoms, const PxGeometryHolder* geoms, const PxTransform* poses, bool shadows, const PxVec3& color) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); //const PxVec3 shadowDir(0.0f, -0.7071067f, -0.7071067f); //const PxReal shadowMat[]={ 1,0,0,0, -shadowDir.x/shadowDir.y,0,-shadowDir.z/shadowDir.y,0, 0,0,1,0, 0,0,0,1 }; for(PxU32 j=0;j<nbGeoms;j++) { const PxMat44 shapePose(poses[j]); const PxGeometry& geom = geoms[j].any(); // render object glPushMatrix(); glMultMatrixf(&shapePose.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); renderGeometry(geom); glPopMatrix(); if(shadows) { glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); //glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glColor4f(0.1f, 0.1f, 0.1f, 1.0f); renderGeometry(geom); glEnable(GL_LIGHTING); glPopMatrix(); } } if(1) { const GLdouble aspect = GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip*1.005f), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0f, 0.0f, 0.0f, 1.0f); for(PxU32 j=0;j<nbGeoms;j++) { const PxMat44 shapePose(poses[j]); const PxGeometry& geom = geoms[j].any(); // render object glPushMatrix(); glMultMatrixf(&shapePose.column0.x); renderGeometry(geom); glPopMatrix(); } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); } } PX_FORCE_INLINE PxVec3 getVec3(const physx::PxU8* data, const PxU32 index, const PxU32 sStrideInBytes) { return *reinterpret_cast<const PxVec3*>(data + index * sStrideInBytes); } void renderMesh(physx::PxU32 /*nbVerts*/, const physx::PxU8* verts, const PxU32 vertsStrideInBytes, physx::PxU32 nbTris, const void* indices, bool has16bitIndices, const physx::PxVec3& color, const physx::PxU8* normals, const PxU32 normalsStrideInBytes, bool flipFaceOrientation, bool enableBackFaceCulling = true) { if (nbTris == 0) return; glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); const PxMat44 idt(PxIdentity); glPushMatrix(); glMultMatrixf(&idt.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); if (!enableBackFaceCulling) glDisable(GL_CULL_FACE); { prepareVertexBuffer(); PxU32 numTotalTriangles = 0; for(PxU32 i=0; i <nbTris; ++i) { PxU32 vref0, vref1, vref2; if (has16bitIndices) { vref0 = ((const PxU16*)indices)[i * 3 + 0]; vref1 = ((const PxU16*)indices)[i * 3 + 1]; vref2 = ((const PxU16*)indices)[i * 3 + 2]; } else { vref0 = ((const PxU32*)indices)[i * 3 + 0]; vref1 = ((const PxU32*)indices)[i * 3 + 1]; vref2 = ((const PxU32*)indices)[i * 3 + 2]; } const PxVec3& v0 = getVec3(verts, vref0, vertsStrideInBytes); const PxVec3& v1 = flipFaceOrientation ? getVec3(verts, vref2, vertsStrideInBytes) : getVec3(verts, vref1, vertsStrideInBytes); const PxVec3& v2 = flipFaceOrientation ? getVec3(verts, vref1, vertsStrideInBytes) : getVec3(verts, vref2, vertsStrideInBytes); if (normals) { const PxVec3& n0 = getVec3(normals, vref0, normalsStrideInBytes); const PxVec3& n1 = flipFaceOrientation ? getVec3(normals, vref2, normalsStrideInBytes) : getVec3(normals, vref1, normalsStrideInBytes); const PxVec3& n2 = flipFaceOrientation ? getVec3(normals, vref1, normalsStrideInBytes) : getVec3(normals, vref2, normalsStrideInBytes); pushVertex(v0, v1, v2, n0, n1, n2, flipFaceOrientation ? -1.0f : 1.0f); } else { PxVec3 fnormal = (v1 - v0).cross(v2 - v0); fnormal.normalize(); pushVertex(v0, v1, v2, fnormal); } numTotalTriangles++; } glScalef(1.0f, 1.0f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), vertexBuffer+1); glDrawArrays(GL_TRIANGLES, 0, int(nbTris * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); } glPopMatrix(); if (!enableBackFaceCulling) glEnable(GL_CULL_FACE); if(0) { const GLdouble aspect = GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip*1.005f), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0f, 0.0f, 0.0f, 1.0f); glPushMatrix(); glMultMatrixf(&idt.column0.x); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), vertexBuffer+1); glDrawArrays(GL_TRIANGLES, 0, int(nbTris * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); } } void renderMesh(physx::PxU32 nbVerts, const physx::PxVec3* verts, physx::PxU32 nbTris, const physx::PxU32* indices, const physx::PxVec3& color, const physx::PxVec3* normals, bool flipFaceOrientation) { renderMesh(nbVerts, reinterpret_cast<const PxU8*>(verts), sizeof(PxVec3), nbTris, indices, false, color, reinterpret_cast<const PxU8*>(normals), sizeof(PxVec3), flipFaceOrientation); } void renderMesh(physx::PxU32 nbVerts, const physx::PxVec4* verts, physx::PxU32 nbTris, const physx::PxU32* indices, const physx::PxVec3& color, const physx::PxVec4* normals, bool flipFaceOrientation) { renderMesh(nbVerts, reinterpret_cast<const PxU8*>(verts), sizeof(PxVec4), nbTris, indices, false, color, reinterpret_cast<const PxU8*>(normals), sizeof(PxVec4), flipFaceOrientation); } void renderMesh(physx::PxU32 nbVerts, const physx::PxVec4* verts, physx::PxU32 nbTris, const void* indices, bool hasSixteenBitIndices, const physx::PxVec3& color, const physx::PxVec4* normals, bool flipFaceOrientation, bool enableBackFaceCulling) { renderMesh(nbVerts, reinterpret_cast<const PxU8*>(verts), sizeof(PxVec4), nbTris, indices, hasSixteenBitIndices, color, reinterpret_cast<const PxU8*>(normals), sizeof(PxVec4), flipFaceOrientation, enableBackFaceCulling); } void DrawLine(const PxVec3& p0, const PxVec3& p1, const PxVec3& color) { glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); const PxVec3 Pts[] = { p0, p1 }; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec3), &Pts[0].x); glDrawArrays(GL_LINES, 0, 2); glDisableClientState(GL_VERTEX_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } const physx::PxVec3 icosahedronPoints[12] = { PxVec3(0, -0.525731, 0.850651), PxVec3(0.850651, 0, 0.525731), PxVec3(0.850651, 0, -0.525731), PxVec3(-0.850651, 0, -0.525731), PxVec3(-0.850651, 0, 0.525731), PxVec3(-0.525731, 0.850651, 0), PxVec3(0.525731, 0.850651, 0), PxVec3(0.525731, -0.850651, 0), PxVec3(-0.525731, -0.850651, 0), PxVec3(0, -0.525731, -0.850651), PxVec3(0, 0.525731, -0.850651), PxVec3(0, 0.525731, 0.850651) }; const PxU32 icosahedronIndices[3 * 20] = { 1 ,2 ,6 , 1 ,7 ,2 , 3 ,4 ,5 , 4 ,3 ,8 , 6 ,5 ,11 , 5 ,6 ,10 , 9 ,10 ,2 , 10 ,9 ,3 , 7 ,8 ,9 , 8 ,7 ,0 , 11 ,0 ,1 , 0 ,11 ,4 , 6 ,2 ,10 , 1 ,6 ,11 , 3 ,5 ,10 , 5 ,4 ,11 , 2 ,7 ,9 , 7 ,1 ,0 , 3 ,9 ,8 , 4 ,8 ,0 }; void DrawIcosahedraPoints(const PxArray<PxVec3>& pts, const PxVec3& color, float radius) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); const PxMat44 idt(PxIdentity); glPushMatrix(); glMultMatrixf(&idt.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); PxU32 numTotalTriangles = 0; { prepareVertexBuffer(); for (PxU32 i = 0; i < pts.size(); ++i) { PxVec3 center = pts[i]; for (PxU32 j = 0; j < 20; ++j) { const PxVec3& v0 = icosahedronPoints[icosahedronIndices[3 * j + 0]] * radius + center; const PxVec3& v1 = icosahedronPoints[icosahedronIndices[3 * j + 1]] * radius + center; const PxVec3& v2 = icosahedronPoints[icosahedronIndices[3 * j + 2]] * radius + center; { PxVec3 fnormal = (v1 - v0).cross(v2 - v0); fnormal.normalize(); pushVertex(v0, v1, v2, fnormal); } numTotalTriangles++; } } glScalef(1.0f, 1.0f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer + 1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); } glPopMatrix(); } void DrawPoints(const PxArray<PxVec3>& pts, const PxVec3& color, float scale) { glPointSize(scale); glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec3), pts.begin()); glDrawArrays(GL_POINTS, 0, pts.size()); glDisableClientState(GL_VERTEX_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawPoints(const PxArray<PxVec4>& pts, const PxVec3& color, float scale) { glPointSize(scale); glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec4), pts.begin()); glDrawArrays(GL_POINTS, 0, pts.size()); glDisableClientState(GL_VERTEX_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawPoints(const physx::PxArray<physx::PxVec3>& pts, const physx::PxArray<physx::PxVec3>& colors, float scale) { glPointSize(scale); glDisable(GL_LIGHTING); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec3), pts.begin()); glColorPointer(3, GL_FLOAT, sizeof(PxVec3), colors.begin()); glDrawArrays(GL_POINTS, 0, pts.size()); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawPoints(const physx::PxArray<physx::PxVec4>& pts, const physx::PxArray<physx::PxVec3>& colors, float scale) { glPointSize(scale); glDisable(GL_LIGHTING); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec4), pts.begin()); glColorPointer(3, GL_FLOAT, sizeof(PxVec3), colors.begin()); glDrawArrays(GL_POINTS, 0, pts.size()); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } #if PX_SUPPORT_GPU_PHYSX namespace { void createVBO(GLuint* vbo, PxU32 size) { PX_ASSERT(vbo); // create buffer object glGenBuffers(1, vbo); glBindBuffer(GL_ARRAY_BUFFER, *vbo); // initialize buffer object glBufferData(GL_ARRAY_BUFFER, size, 0, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } void deleteVBO(GLuint* vbo) { glBindBuffer(1, *vbo); glDeleteBuffers(1, vbo); *vbo = 0; } #if USE_CUDA_INTEROP //Returns the pointer to the cuda buffer void* mapCudaGraphicsResource(CUgraphicsResource* vbo_resource, size_t& numBytes, CUstream stream = 0) { CUresult result0 = cuGraphicsMapResources(1, vbo_resource, stream); PX_UNUSED(result0); void* dptr; CUresult result1 = cuGraphicsResourceGetMappedPointer((CUdeviceptr*)&dptr, &numBytes, *vbo_resource); PX_UNUSED(result1); return dptr; } void unmapCudaGraphicsResource(CUgraphicsResource* vbo_resource, CUstream stream = 0) { CUresult result2 = cuGraphicsUnmapResources(1, vbo_resource, stream); PX_UNUSED(result2); } #endif } // namespace SharedGLBuffer::SharedGLBuffer() : vbo_res(NULL), devicePointer(NULL), vbo(0), size(0) { } void SharedGLBuffer::initialize(PxCudaContextManager* contextManager) { cudaContextManager = contextManager; } void SharedGLBuffer::allocate(PxU32 sizeInBytes) { release(); createVBO(&vbo, sizeInBytes); #if USE_CUDA_INTEROP physx::PxCudaInteropRegisterFlags flags = physx::PxCudaInteropRegisterFlags(); cudaContextManager->acquireContext(); CUresult result = cuGraphicsGLRegisterBuffer(reinterpret_cast<CUgraphicsResource*>(&vbo_res), vbo, flags); PX_UNUSED(result); cudaContextManager->releaseContext(); #endif size = sizeInBytes; } void SharedGLBuffer::release() { if (vbo) { deleteVBO(&vbo); vbo = 0; } #if USE_CUDA_INTEROP if (vbo_res) { cudaContextManager->acquireContext(); CUresult result = cuGraphicsUnregisterResource(reinterpret_cast<CUgraphicsResource>(vbo_res)); PX_UNUSED(result); cudaContextManager->releaseContext(); vbo_res = NULL; } #endif } SharedGLBuffer::~SharedGLBuffer() { //release(); } void* SharedGLBuffer::map() { if (devicePointer) return devicePointer; #if USE_CUDA_INTEROP size_t numBytes; cudaContextManager->acquireContext(); devicePointer = mapCudaGraphicsResource(reinterpret_cast<CUgraphicsResource*>(&vbo_res), numBytes, 0); cudaContextManager->releaseContext(); #else glBindBuffer(GL_ARRAY_BUFFER, vbo); devicePointer = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); glBindBuffer(GL_ARRAY_BUFFER, 0); #endif return devicePointer; } void SharedGLBuffer::unmap() { if (!devicePointer) return; #if USE_CUDA_INTEROP cudaContextManager->acquireContext(); unmapCudaGraphicsResource(reinterpret_cast<CUgraphicsResource*>(&vbo_res), 0); cudaContextManager->releaseContext(); #else glBindBuffer(GL_ARRAY_BUFFER, vbo); glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); #endif devicePointer = NULL; } #endif // PX_SUPPORT_GPU_PHYSX void DrawPoints(GLuint vbo, PxU32 numPoints, const PxVec3& color, float scale, PxU32 coordinatesPerPoint, PxU32 stride, size_t offset) { glPointSize(scale); glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(coordinatesPerPoint, GL_FLOAT, stride, (void*)offset /*offsetof(Vertex, pos)*/); glDrawArrays(GL_POINTS, 0, numPoints); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawLines(GLuint vbo, PxU32 numPoints, const PxVec3& color, float scale, PxU32 coordinatesPerPoint, PxU32 stride, size_t offset) { PX_ASSERT(numPoints % 2 == 0); glLineWidth(scale); glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(coordinatesPerPoint, GL_FLOAT, stride, (void*)offset /*offsetof(Vertex, pos)*/); glDrawArrays(GL_LINES, 0, numPoints); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawMeshIndexed(GLuint vbo, GLuint elementbuffer, GLuint numTriangles, const physx::PxVec3& color, physx::PxU32 stride) { /*glPushMatrix(); glScalef(1.0f, 1.0f, 1.0f);*/ if(gWireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(color.x, color.y, color.z, 1.0f); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, stride, (void*)0); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, stride, (void*)(3 * sizeof(float))); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glDrawElements(GL_TRIANGLES, int(numTriangles * 3), GL_UNSIGNED_INT, (void*)0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); //glPopMatrix(); if (gWireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } void DrawMeshIndexedNoNormals(GLuint vbo, GLuint elementbuffer, GLuint numTriangles, const physx::PxVec3& color, physx::PxU32 stride) { /*glPushMatrix(); glScalef(1.0f, 1.0f, 1.0f);*/ glColor4f(color.x, color.y, color.z, 1.0f); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, stride, (void*)0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glDrawElements(GL_TRIANGLES, int(numTriangles * 3), GL_UNSIGNED_INT, (void*)0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); //glPopMatrix(); } void DrawFrame(const PxVec3& pt, float scale) { DrawLine(pt, pt + PxVec3(scale, 0.0f, 0.0f), PxVec3(1.0f, 0.0f, 0.0f)); DrawLine(pt, pt + PxVec3(0.0f, scale, 0.0f), PxVec3(0.0f, 1.0f, 0.0f)); DrawLine(pt, pt + PxVec3(0.0f, 0.0f, scale), PxVec3(0.0f, 0.0f, 1.0f)); } void DrawBounds(const physx::PxBounds3& box, const physx::PxVec3& color) { DrawLine(PxVec3(box.minimum.x, box.minimum.y, box.minimum.z), PxVec3(box.maximum.x, box.minimum.y, box.minimum.z), color); DrawLine(PxVec3(box.maximum.x, box.minimum.y, box.minimum.z), PxVec3(box.maximum.x, box.maximum.y, box.minimum.z), color); DrawLine(PxVec3(box.maximum.x, box.maximum.y, box.minimum.z), PxVec3(box.minimum.x, box.maximum.y, box.minimum.z), color); DrawLine(PxVec3(box.minimum.x, box.maximum.y, box.minimum.z), PxVec3(box.minimum.x, box.minimum.y, box.minimum.z), color); DrawLine(PxVec3(box.minimum.x, box.minimum.y, box.minimum.z), PxVec3(box.minimum.x, box.minimum.y, box.maximum.z), color); DrawLine(PxVec3(box.minimum.x, box.minimum.y, box.maximum.z), PxVec3(box.maximum.x, box.minimum.y, box.maximum.z), color); DrawLine(PxVec3(box.maximum.x, box.minimum.y, box.maximum.z), PxVec3(box.maximum.x, box.maximum.y, box.maximum.z), color); DrawLine(PxVec3(box.maximum.x, box.maximum.y, box.maximum.z), PxVec3(box.minimum.x, box.maximum.y, box.maximum.z), color); DrawLine(PxVec3(box.minimum.x, box.maximum.y, box.maximum.z), PxVec3(box.minimum.x, box.minimum.y, box.maximum.z), color); DrawLine(PxVec3(box.minimum.x, box.minimum.y, box.maximum.z), PxVec3(box.minimum.x, box.minimum.y, box.minimum.z), color); DrawLine(PxVec3(box.maximum.x, box.minimum.y, box.minimum.z), PxVec3(box.maximum.x, box.minimum.y, box.maximum.z), color); DrawLine(PxVec3(box.maximum.x, box.maximum.y, box.minimum.z), PxVec3(box.maximum.x, box.maximum.y, box.maximum.z), color); DrawLine(PxVec3(box.minimum.x, box.maximum.y, box.minimum.z), PxVec3(box.minimum.x, box.maximum.y, box.maximum.z), color); } void DrawBounds(const PxBounds3& box) { const PxVec3 color(1.0f, 1.0f, 0.0f); DrawBounds(box, color); } GLuint CreateTexture(PxU32 width, PxU32 height, const GLubyte* buffer, bool createMipmaps) { GLuint texId; glGenTextures(1, &texId); glBindTexture(GL_TEXTURE_2D, texId); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if(buffer) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); if(createMipmaps) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); } } glBindTexture(GL_TEXTURE_2D, 0); return texId; } void UpdateTexture(GLuint texId, physx::PxU32 width, physx::PxU32 height, const GLubyte* buffer, bool createMipmaps) { glBindTexture(GL_TEXTURE_2D, texId); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); if(createMipmaps) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); } glBindTexture( GL_TEXTURE_2D, 0); } void ReleaseTexture(GLuint texId) { glDeleteTextures(1, &texId); } void DrawRectangle(float x_start, float x_end, float y_start, float y_end, const PxVec3& color_top, const PxVec3& color_bottom, float alpha, PxU32 screen_width, PxU32 screen_height, bool draw_outline, bool texturing) { if(alpha!=1.0f) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); } else { glDisable(GL_BLEND); } glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); if(texturing) glEnable(GL_TEXTURE_2D); else glDisable(GL_TEXTURE_2D); { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, screen_width, 0, screen_height, -1, 1); } glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); const float x0 = x_start * float(screen_width); const float x1 = x_end * float(screen_width); const float y0 = y_start * float(screen_height); const float y1 = y_end * float(screen_height); const PxVec3 p0(x0, y0, 0.0f); const PxVec3 p1(x0, y1, 0.0f); const PxVec3 p2(x1, y1, 0.0f); const PxVec3 p3(x1, y0, 0.0f); // const float u = (texture_flags & SQT_FLIP_U) ? 1.0f : 0.0f; // const float v = (texture_flags & SQT_FLIP_V) ? 1.0f : 0.0f; const float u = 0.0f; const float v = 1.0f; const PxVec3 t0(u, v, 0.0f); const PxVec3 t1(u, 1.0f - v, 0.0f); const PxVec3 t2(1.0f - u, 1.0f - v, 0.0f); const PxVec3 t3(1.0f - u, v, 0.0f); glBegin(GL_TRIANGLES); glTexCoord2f(t0.x, t0.y); glColor4f(color_top.x, color_top.y, color_top.z, alpha); glVertex3f(p0.x, p0.y, p0.z); glTexCoord2f(t1.x, t1.y); glColor4f(color_bottom.x, color_bottom.y, color_bottom.z, alpha); glVertex3f(p1.x, p1.y, p1.z); glTexCoord2f(t2.x, t2.y); glColor4f(color_bottom.x, color_bottom.y, color_bottom.z, alpha); glVertex3f(p2.x, p2.y, p2.z); glTexCoord2f(t0.x, t0.y); glColor4f(color_top.x, color_top.y, color_top.z, alpha); glVertex3f(p0.x, p0.y, p0.z); glTexCoord2f(t2.x, t2.y); glColor4f(color_bottom.x, color_bottom.y, color_bottom.z, alpha); glVertex3f(p2.x, p2.y, p2.z); glTexCoord2f(t3.x, t3.y); glColor4f(color_top.x, color_top.y, color_top.z, alpha); glVertex3f(p3.x, p3.y, p3.z); glEnd(); if(draw_outline) { glDisable(GL_TEXTURE_2D); glColor4f(1.0f, 1.0f, 1.0f, alpha); glBegin(GL_LINES); glVertex3f(p0.x, p0.y, p0.z); glVertex3f(p1.x, p1.y, p1.z); glVertex3f(p1.x, p1.y, p1.z); glVertex3f(p2.x, p2.y, p2.z); glVertex3f(p2.x, p2.y, p2.z); glVertex3f(p3.x, p3.y, p3.z); glVertex3f(p3.x, p3.y, p3.z); glVertex3f(p0.x, p0.y, p0.z); glEnd(); } { glMatrixMode(GL_PROJECTION); glPopMatrix(); } glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glDisable(GL_BLEND); } void DisplayTexture(GLuint texId, PxU32 size, PxU32 margin) { const PxU32 screenWidth = gScreenWidth; const PxU32 screenHeight = gScreenHeight; glBindTexture(GL_TEXTURE_2D, texId); // glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); // glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // glDisable(GL_CULL_FACE); const PxVec3 color(1.0f, 1.0f, 1.0f); // const float Alpha = 0.999f; // const float Alpha = 0.5f; const float Alpha = 1.0f; PxU32 PixelSizeX = size; PxU32 PixelSizeY = size; if(!size) { PixelSizeX = gScreenWidth; PixelSizeY = gScreenHeight; margin = 0; } const float x0 = float(screenWidth-PixelSizeX-margin)/float(screenWidth); const float y0 = float(screenHeight-PixelSizeY-margin)/float(screenHeight); const float x1 = float(screenWidth-margin)/float(screenWidth); const float y1 = float(screenHeight-margin)/float(screenHeight); DrawRectangle(x0, x1, y0, y1, color, color, Alpha, screenWidth, screenHeight, false, true); glDisable(GL_TEXTURE_2D); } } //namespace Snippets
53,539
C++
29.734788
216
0.705915
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetFontData.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // auto generated don't touch static const int OGL_FONT_TEXTURE_WIDTH=256; static const int OGL_FONT_TEXTURE_HEIGHT=128; static const int OGL_FONT_CHARS_PER_ROW=16; static const int OGL_FONT_CHARS_PER_COL=8; static const int OGL_FONT_CHAR_BASE=32; int GLFontGlyphWidth[OGL_FONT_CHARS_PER_ROW*OGL_FONT_CHARS_PER_COL] = { 6,7,8,11,10,10,11,7,10,8,10,10,8,9,8,10, 11,11,11,11,11,11,11,11,11,11,8,8,10,10,10,10, 11,10,10,10,11,10,10,10,10,10,9,11,10,10,10,10, 10,11,11,10,10,10,10,10,10,10,10,10,10,7,10,10, 8,10,10,10,9,9,10,9,10,8,8,11,8,10,10,10, 10,9,10,10,9,10,10,10,10,10,9,9,6,9,10,10, 10,10,9,10,10,10,10,10,9,9,9,9,9,8,10,10, 10,11,10,10,10,10,10,10,10,10,10,10,9,10,10,10 }; unsigned char OGLFontData[OGL_FONT_TEXTURE_WIDTH * OGL_FONT_TEXTURE_HEIGHT] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,117,68,0,101,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,85,68,0,0,0,0,0,0,0,0,117,32,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,101,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,101,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,68,117,0,117,85,0,0,0, 0,0,0,0,0,0,0,68,169,254,185,136,48,0,0,0,0,0,0,0,16,152,185,85,0,0,0,117,169,0,0,0, 0,0,0,0,0,0,0,48,221,254,152,16,0,0,0,0,0,0,0,0,0,0,0,0,237,237,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,221,205,68,0,0,0,0,0,0,0,0,152,237,136,16,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,101,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0, 0,0,0,0,0,0,221,101,0,152,152,0,0,0,0,0,0,0,0,0,0,0,0,0,152,101,0,221,32,0,0,0, 0,0,0,0,0,0,85,254,117,254,68,117,101,0,0,0,0,0,0,0,169,117,16,221,48,0,48,221,16,0,0,0, 0,0,0,0,0,0,0,221,169,48,254,117,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,101,0,0,0,0,0,0,0,0,0,0,0,16,205,205,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,101,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0, 0,0,0,0,0,0,185,68,0,117,117,0,0,0,0,0,0,0,0,0,0,0,0,0,221,32,32,221,0,0,0,0, 0,0,0,0,0,0,169,205,0,254,0,0,0,0,0,0,0,0,0,0,254,0,0,117,117,0,205,68,0,0,0,0, 0,0,0,0,0,0,0,254,117,16,254,117,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,237,117,0,0,0,0,0,0,0,0,0,0,0,0,0,16,237,117,0,0,0,0,0,0, 0,0,0,0,0,0,185,117,68,101,101,221,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0, 0,0,0,0,0,0,101,32,0,68,68,0,0,0,0,0,0,0,0,0,0,32,117,117,254,117,169,205,117,32,0,0, 0,0,0,0,0,0,169,221,16,254,0,0,0,0,0,0,0,0,0,0,221,32,0,152,101,136,136,0,0,0,0,0, 0,0,0,0,0,0,0,205,205,117,237,32,0,0,0,0,0,0,0,0,0,0,0,0,117,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,237,0,0,0,0,0,0, 0,0,0,0,0,0,32,85,68,32,101,48,0,0,0,0,0,0,0,0,0,0,0,0,101,32,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,117,185,185,117,221,152,117,0,0,0, 0,0,0,0,0,0,48,237,205,254,0,0,0,0,0,0,0,0,0,0,101,205,136,205,85,205,0,0,0,0,0,0, 0,0,0,0,0,0,16,169,254,221,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,101,205,136,152,0,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,169,85,0,237,16,0,0,0,0, 0,0,0,0,0,0,0,48,221,254,152,16,0,0,0,0,0,0,0,0,0,32,68,16,221,48,0,0,0,0,0,0, 0,0,0,0,0,48,221,169,221,185,0,0,136,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,237,101,32,254,48,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,68,254,68,117,205,68,32,0,0,0, 0,0,0,0,0,0,0,0,0,254,237,237,48,0,0,0,0,0,0,0,0,0,0,169,117,136,205,205,48,0,0,0, 0,0,0,0,0,185,185,0,101,254,68,0,185,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,32,0,0,32,0,0,0,0,0,0,0,0,0,0,68,68,68,205,117,68,68,32,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,48,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,169,205,237,185,237,205,185,85,0,0,0, 0,0,0,0,0,0,0,0,0,254,48,237,152,0,0,0,0,0,0,0,0,0,101,185,85,185,0,68,205,0,0,0, 0,0,0,0,0,254,117,0,0,185,237,16,221,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,237,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,185,237,205,185,185,101,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,117,0,205,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,0,185,185,0,0,0,0,0,0,0,0,32,221,16,117,117,0,0,254,0,0,0, 0,0,0,0,0,221,185,0,0,16,237,205,237,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,169,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,254,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,205,48,16,237,0,0,0,0,0,0, 0,0,0,0,0,0,136,68,0,254,48,254,101,0,0,0,0,0,0,0,0,185,85,0,85,185,0,68,205,0,0,0, 0,0,0,0,0,117,254,117,0,32,185,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,101,254,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,152,221,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,221,0,101,152,0,0,0,0,0,0, 0,0,0,0,0,0,152,221,254,254,237,117,0,0,0,0,0,0,0,0,117,152,0,0,0,136,205,205,48,0,0,0, 0,0,0,0,0,0,117,221,254,221,117,136,254,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,205,169,0,0,0,0,0,0,0,0,0,0,0,0,0,48,254,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,68,16,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,32,237,152,16,0,0,0,0,0,0,0,0,0,0,68,237,136,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,16,254,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,221,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,16,152,254,101,0,0,0,0,0,0,0,0,221,221,85,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,169,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,152,101,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,16,32,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,48,205,254,221,101,0,0,0,0,0,0,0,0,0,0,0,0,48,117,169,117,0,0,0,0,0, 0,0,0,0,0,0,117,205,254,254,169,32,0,0,0,0,0,0,0,0,0,0,185,254,254,237,136,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,136,185,0,0,0,0,0,0,0,0,0,0,0,136,185,185,185,185,48,0,0,0,0, 0,0,0,0,0,0,16,117,237,254,221,101,0,0,0,0,0,0,0,0,0,0,185,185,185,185,185,185,101,0,0,0, 0,0,0,0,0,0,85,221,254,254,169,16,0,0,0,0,0,0,0,0,0,0,101,221,254,205,85,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,169,221,254,254,221,117,16,0,0,0, 0,0,0,0,0,16,237,117,0,68,254,68,0,0,0,0,0,0,0,0,0,0,221,221,152,254,117,0,0,0,0,0, 0,0,0,0,0,0,117,48,0,32,205,221,0,0,0,0,0,0,0,0,0,0,101,32,0,68,254,117,0,0,0,0, 0,0,0,0,0,0,0,0,101,254,254,0,0,0,0,0,0,0,0,0,0,0,185,185,117,117,117,32,0,0,0,0, 0,0,0,0,0,0,185,152,32,0,48,68,0,0,0,0,0,0,0,0,0,0,117,117,117,117,136,254,117,0,0,0, 0,0,0,0,0,32,254,101,0,68,254,152,0,0,0,0,0,0,0,0,0,85,254,68,0,117,254,32,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,32,0,0,101,254,136,0,0,0, 0,0,0,0,0,117,221,0,0,0,152,169,0,0,0,0,0,0,0,0,0,0,32,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,85,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0, 0,0,0,0,0,0,0,32,221,152,254,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,101,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,205,0,0,0,0, 0,0,0,0,0,117,254,0,0,0,185,185,0,0,0,0,0,0,0,0,0,205,152,0,0,0,169,152,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,0,0,0,0,185,185,0,0,0, 0,0,0,0,0,185,152,0,0,0,101,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,85,254,48,0,0,0,0,0,0,0,0,0,0,0,0,16,221,117,0,0,0,0, 0,0,0,0,0,0,0,185,117,117,254,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,169,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,237,68,0,0,0,0, 0,0,0,0,0,101,254,117,0,32,254,101,0,0,0,0,0,0,0,0,0,254,117,0,0,0,117,205,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,32,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,254,85,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,185,205,0,0,0,0,0,0,0,0,0,0,16,68,85,185,169,0,0,0,0,0, 0,0,0,0,0,0,117,185,0,117,254,0,0,0,0,0,0,0,0,0,0,0,185,185,117,32,0,0,0,0,0,0, 0,0,0,0,0,237,85,169,254,237,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,152,152,0,0,0,0,0, 0,0,0,0,0,0,152,254,152,205,117,0,0,0,0,0,0,0,0,0,0,237,152,0,0,0,136,254,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,32,152,237,85,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,185,221,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,237,117,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,152,237,48,0,0,0,0,0,0,0,0,0,0,48,185,205,237,117,0,0,0,0,0, 0,0,0,0,0,48,237,16,0,117,254,0,0,0,0,0,0,0,0,0,0,0,101,117,185,254,101,0,0,0,0,0, 0,0,0,0,0,254,221,68,0,117,254,117,0,0,0,0,0,0,0,0,0,0,0,0,68,254,32,0,0,0,0,0, 0,0,0,0,0,0,101,237,254,237,85,0,0,0,0,0,0,0,0,0,0,152,237,48,0,16,221,254,0,0,0,0, 0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0, 0,0,0,0,0,0,0,32,152,237,117,16,0,0,0,0,0,0,0,0,0,117,117,117,117,117,117,117,101,0,0,0, 0,0,0,0,0,0,68,185,221,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,254,85,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,152,237,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,237,136,0,0,0,0, 0,0,0,0,0,205,85,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,48,0,0,0,0, 0,0,0,0,0,254,152,0,0,0,169,221,0,0,0,0,0,0,0,0,0,0,0,0,185,152,0,0,0,0,0,0, 0,0,0,0,0,85,237,48,32,205,254,101,0,0,0,0,0,0,0,0,0,16,185,254,185,221,117,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,32,152,237,117,16,0,0,0,0,0,0,0,0,0,0,0,117,117,117,117,117,117,117,101,0,0,0, 0,0,0,0,0,0,0,0,68,185,221,101,0,0,0,0,0,0,0,0,0,0,0,0,205,152,0,0,0,0,0,0, 0,0,0,0,0,205,136,0,0,0,101,254,16,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,117,237,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,237,0,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0, 0,0,0,0,0,221,117,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,68,254,32,0,0,0,0,0,0, 0,0,0,0,0,221,152,0,0,0,221,237,0,0,0,0,0,0,0,0,0,0,0,48,68,0,117,185,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,101,221,185,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,16,117,237,152,32,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0,0, 0,0,0,0,0,136,205,0,0,0,136,205,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,254,117,0,0,0,0, 0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0,0,0,0,0,0,0,0,185,152,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0, 0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0, 0,0,0,0,0,0,0,101,221,185,68,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,254,185,0,0,0, 0,0,0,0,0,0,16,117,237,152,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,32,254,68,0,16,237,101,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,221,221,68,68,68,68,16,0,0,0,0,0,0,0,0,0,32,0,0,16,237,152,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,16,0,0,152,254,32,0,0,0,0, 0,0,0,0,0,68,237,48,0,16,237,117,0,0,0,0,0,0,0,0,0,0,48,254,85,0,0,0,0,0,0,0, 0,0,0,0,0,169,221,16,0,16,205,152,0,0,0,0,0,0,0,0,0,32,0,0,0,101,221,16,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,101,221,185,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,117,237,152,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,117,68,0,0,0,0,0,0, 0,0,0,0,0,0,101,237,185,237,136,0,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,254,117,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,68,0,0,0,0,0,0,0,0,0,254,205,185,254,185,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,254,185,205,237,85,0,0,0,0,0, 0,0,0,0,0,0,117,254,185,237,152,0,0,0,0,0,0,0,0,0,0,0,117,254,16,0,0,0,0,0,0,0, 0,0,0,0,0,16,205,237,185,237,185,16,0,0,0,0,0,0,0,0,0,117,237,185,221,185,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,101,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,152,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,68,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,32,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,68,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,48,68,32,0,0,0,0,0,0,0,0,0,0,0,0,32,68,48,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,254,32,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,169,136,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,221,254,221,85,0,0,0,0,0,0,0,0,0,0,0,85,185,85,0,0,0,0,0,0, 0,0,0,0,0,0,185,185,185,185,169,68,0,0,0,0,0,0,0,0,0,0,0,101,185,254,254,221,136,0,0,0, 0,0,0,0,0,0,185,185,185,185,117,32,0,0,0,0,0,0,0,0,0,0,185,185,185,185,185,185,101,0,0,0, 0,0,0,0,0,0,185,185,185,185,185,185,136,0,0,0,0,0,0,0,0,0,0,101,185,254,254,221,136,0,0,0, 0,0,0,0,0,0,185,101,0,0,0,185,101,0,0,0,0,0,0,0,0,0,185,185,185,185,185,185,101,0,0,0, 0,0,0,0,0,0,48,185,185,185,185,48,0,0,0,0,0,0,0,0,0,0,185,101,0,0,16,169,101,0,0,0, 0,0,0,0,0,0,185,101,0,0,0,0,0,0,0,0,0,0,0,0,0,185,169,0,0,0,32,185,136,0,0,0, 0,0,0,0,0,0,185,117,0,0,0,101,136,0,0,0,0,0,0,0,0,0,16,169,254,254,169,16,0,0,0,0, 0,0,0,0,0,0,152,205,32,0,68,237,0,0,0,0,0,0,0,0,0,0,0,169,254,169,0,0,0,0,0,0, 0,0,0,0,0,0,254,152,68,85,205,254,32,0,0,0,0,0,0,0,0,0,152,237,101,0,0,68,117,0,0,0, 0,0,0,0,0,0,254,152,68,101,185,237,48,0,0,0,0,0,0,0,0,0,254,152,68,68,68,68,32,0,0,0, 0,0,0,0,0,0,254,152,68,68,68,68,48,0,0,0,0,0,0,0,0,0,152,237,101,0,0,48,101,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,68,68,152,254,68,68,32,0,0,0, 0,0,0,0,0,0,16,68,68,117,254,68,0,0,0,0,0,0,0,0,0,0,254,117,0,0,152,205,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,48,0,0,117,254,185,0,0,0, 0,0,0,0,0,0,254,254,32,0,0,117,185,0,0,0,0,0,0,0,0,16,205,152,16,16,152,205,16,0,0,0, 0,0,0,0,0,68,221,16,0,117,185,221,68,0,0,0,0,0,0,0,0,0,16,254,205,254,16,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,254,117,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,221,169,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,0,85,237,48,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,205,136,0,0,205,205,185,0,0,0, 0,0,0,0,0,0,254,254,152,0,0,117,185,0,0,0,0,0,0,0,0,117,237,16,0,0,16,237,117,0,0,0, 0,0,0,0,0,152,117,0,136,117,0,205,68,0,0,0,0,0,0,0,0,0,101,237,48,254,101,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,32,254,101,0,0,0,0,0,0,0,0,169,221,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,16,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,169,221,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,32,237,117,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,221,0,32,237,117,185,0,0,0, 0,0,0,0,0,0,254,221,254,32,0,117,185,0,0,0,0,0,0,0,0,185,169,0,0,0,0,169,185,0,0,0, 0,0,0,0,0,221,32,16,221,0,0,205,68,0,0,0,0,0,0,0,0,0,169,136,0,221,169,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,48,205,185,0,0,0,0,0,0,0,0,0,237,152,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,254,152,68,68,68,48,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,237,152,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,185,169,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,16,254,68,117,169,117,185,0,0,0, 0,0,0,0,0,0,254,101,237,152,0,117,185,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,254,0,68,185,0,32,254,68,0,0,0,0,0,0,0,0,32,254,48,0,117,254,32,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,205,16,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,254,221,185,185,185,136,0,0,0,0, 0,0,0,0,0,0,254,221,185,185,185,185,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,221,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,169,152,221,101,117,185,0,0,0, 0,0,0,0,0,0,254,68,117,254,68,117,185,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,254,0,68,205,0,152,221,68,0,0,0,0,0,0,0,0,117,221,0,0,32,254,117,0,0,0,0, 0,0,0,0,0,0,254,117,0,48,185,237,32,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,152,68,68,68,68,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,136,136,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,185,237,48,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,101,237,254,16,117,185,0,0,0, 0,0,0,0,0,0,254,68,16,237,185,117,185,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,205,68,0,237,152,152,185,152,32,0,0,0,0,0,0,0,205,254,254,254,254,254,205,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,237,152,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,185,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,16,237,205,16,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,16,237,169,0,117,185,0,0,0, 0,0,0,0,0,0,254,68,0,117,254,185,185,0,0,0,0,0,0,0,0,205,152,0,0,0,0,152,205,0,0,0, 0,0,0,0,0,117,169,0,48,117,16,101,117,32,0,0,0,0,0,0,32,254,48,0,0,0,117,254,32,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0,0,0,0,0,117,254,48,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,221,169,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,101,254,48,0,0,0,185,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,48,0,0,0,0,0,0,0,0,0,0,254,117,0,68,254,152,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,0,0,0,0,117,185,0,0,0, 0,0,0,0,0,0,254,68,0,16,237,254,185,0,0,0,0,0,0,0,0,136,221,0,0,0,0,221,136,0,0,0, 0,0,0,0,0,16,205,152,16,0,85,32,0,0,0,0,0,0,0,0,117,221,0,0,0,0,32,254,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0,0,0,0,0,0,0,205,237,68,0,0,0,32,0,0,0, 0,0,0,0,0,0,254,117,0,32,169,237,32,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,205,237,68,0,0,185,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,16,0,0,117,237,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,117,254,101,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,0,0,0,0,117,185,0,0,0, 0,0,0,0,0,0,254,68,0,0,117,254,185,0,0,0,0,0,0,0,0,32,237,117,0,0,117,237,32,0,0,0, 0,0,0,0,0,0,16,152,254,254,169,32,0,0,0,0,0,0,0,0,205,117,0,0,0,0,0,185,205,0,0,0, 0,0,0,0,0,0,254,254,254,254,237,117,0,0,0,0,0,0,0,0,0,0,16,152,254,221,185,221,169,0,0,0, 0,0,0,0,0,0,254,254,254,237,152,32,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,152,254,205,185,237,152,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,117,0,0,0, 0,0,0,0,0,0,254,205,205,237,85,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,237,48,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,254,0,0,0,0,0,117,185,0,0,0, 0,0,0,0,0,0,254,68,0,0,0,221,185,0,0,0,0,0,0,0,0,0,48,237,205,205,237,48,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,32,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,32,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,68,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,117,117,101,0,0,0, 0,0,0,0,0,117,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,117,117,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,185,185,185,185,169,101,0,0,0,0,0,0,0,0,0,0,16,169,254,254,169,16,0,0,0,0, 0,0,0,0,0,0,185,185,185,185,152,48,0,0,0,0,0,0,0,0,0,0,16,152,254,254,237,169,0,0,0,0, 0,0,0,0,185,185,185,185,185,185,185,185,101,0,0,0,0,0,0,0,0,0,185,101,0,0,0,136,101,0,0,0, 0,0,0,0,152,117,0,0,0,0,0,85,152,0,0,0,0,0,0,0,185,48,0,0,0,0,0,48,136,0,0,0, 0,0,0,0,85,185,68,0,0,0,48,185,32,0,0,0,0,0,0,0,117,185,16,0,0,0,0,136,117,0,0,0, 0,0,0,0,0,136,185,185,185,185,185,185,101,0,0,0,0,0,0,0,0,0,0,0,254,185,117,117,101,0,0,0, 0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,117,221,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,152,68,68,117,254,136,0,0,0,0,0,0,0,0,16,205,152,16,16,152,205,16,0,0,0, 0,0,0,0,0,0,254,152,68,85,169,237,32,0,0,0,0,0,0,0,0,0,152,169,16,0,48,117,0,0,0,0, 0,0,0,0,68,68,68,152,254,68,68,68,32,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,136,254,16,0,0,0,0,169,136,0,0,0,0,0,0,0,205,117,0,0,0,0,0,117,136,0,0,0, 0,0,0,0,0,221,205,0,0,0,205,169,0,0,0,0,0,0,0,0,32,254,117,0,0,0,68,254,32,0,0,0, 0,0,0,0,0,48,68,68,68,68,152,254,85,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,136,254,0,0,0,0,0,0,0,0,117,237,16,0,0,16,237,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,254,117,0,0,0,0,0,0,0,0,0,254,68,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,48,254,101,0,0,0,32,254,48,0,0,0,0,0,0,0,185,136,0,0,0,0,0,117,117,0,0,0, 0,0,0,0,0,68,254,117,0,117,237,16,0,0,0,0,0,0,0,0,0,136,254,32,0,0,205,136,0,0,0,0, 0,0,0,0,0,0,0,0,0,32,237,169,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,185,237,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,136,254,0,0,0,0,0,0,0,0,185,169,0,0,0,0,169,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,254,117,0,0,0,0,0,0,0,0,0,237,169,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,221,169,0,0,0,117,221,0,0,0,0,0,0,0,0,117,185,0,68,185,48,0,185,68,0,0,0, 0,0,0,0,0,0,169,237,48,237,85,0,0,0,0,0,0,0,0,0,0,16,237,185,0,117,237,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,185,237,16,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,68,221,152,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,221,169,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,117,0,0,152,237,16,0,0,0,0,0,0,0,0,0,101,254,205,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,136,254,16,0,0,205,136,0,0,0,0,0,0,0,0,117,205,0,117,254,117,0,205,48,0,0,0, 0,0,0,0,0,0,32,237,254,185,0,0,0,0,0,0,0,0,0,0,0,0,101,254,85,237,101,0,0,0,0,0, 0,0,0,0,0,0,0,0,117,254,85,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,152,101,32,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,185,117,136,221,205,16,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,221,185,237,185,32,0,0,0,0,0,0,0,0,0,0,0,68,221,254,185,48,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,48,254,101,0,32,254,48,0,0,0,0,0,0,0,0,68,254,0,185,205,152,0,254,0,0,0,0, 0,0,0,0,0,0,0,136,254,85,0,0,0,0,0,0,0,0,0,0,0,0,0,205,254,205,0,0,0,0,0,0, 0,0,0,0,0,0,0,32,237,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,32,221,0,0,152,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,185,117,117,48,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,152,68,237,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,237,237,68,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,0,205,185,0,117,205,0,0,0,0,0,0,0,0,0,32,254,32,221,117,205,32,221,0,0,0,0, 0,0,0,0,0,0,16,237,237,221,0,0,0,0,0,0,0,0,0,0,0,0,0,85,254,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,169,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,152,101,0,0,32,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,205,152,0,0,0,0,152,205,0,0,0, 0,0,0,0,0,0,254,117,0,85,254,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,237,169,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,0,117,254,32,221,117,0,0,0,0,0,0,0,0,0,0,254,85,237,48,254,68,185,0,0,0,0, 0,0,0,0,0,0,169,205,68,254,117,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,85,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,32,221,0,0,0,0,152,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,136,221,0,0,0,0,221,136,0,0,0, 0,0,0,0,0,0,254,117,0,0,185,237,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,237,117,0,0,0,205,117,0,0,0, 0,0,0,0,0,0,32,254,152,254,32,0,0,0,0,0,0,0,0,0,0,205,169,185,0,254,169,136,0,0,0,0, 0,0,0,0,0,68,254,48,0,152,237,32,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0, 0,0,0,0,0,16,237,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,152,117,0,0,0,0,68,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,32,237,117,0,0,117,237,32,0,0,0, 0,0,0,0,0,0,254,117,0,0,32,237,169,0,0,0,0,0,0,0,0,0,101,16,0,0,48,254,101,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,152,221,16,0,48,254,32,0,0,0, 0,0,0,0,0,0,0,205,254,205,0,0,0,0,0,0,0,0,0,0,0,185,254,117,0,185,237,117,0,0,0,0, 0,0,0,0,16,221,117,0,0,16,237,185,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0, 0,0,0,0,0,169,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,237,205,205,237,85,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,85,0,0,0,0,0,0,0,0,221,254,185,185,254,136,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,16,205,237,185,254,101,0,0,0,0, 0,0,0,0,0,0,0,117,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,85,0,136,254,68,0,0,0,0, 0,0,0,0,136,221,16,0,0,0,101,254,85,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,85,237,152,48,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,68,68,16,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,68,16,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,254,254,254,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,185,254,101,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,221,185,185,136,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,185,185,185,237,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,68,68,48,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,16,68,0,0,0,0,0,0,0,0,68,68,68,68,48,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,136,169,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,117,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,101,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,32,117,117,117,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,117,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,185,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,101,185,48,0,0,0,0,0,0,0,0,0,0,0,117,68,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,117,117,117,117,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,205,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,85,254,185,117,117,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,117,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,117,117,117,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,32,117,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,169,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0, 0,0,0,0,0,254,117,85,221,254,185,16,0,0,0,0,0,0,0,0,0,0,0,85,205,254,254,221,101,0,0,0, 0,0,0,0,0,0,117,237,254,136,185,185,0,0,0,0,0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,0,101,237,254,152,136,185,0,0,0,0, 0,0,0,0,0,0,254,117,85,221,254,136,0,0,0,0,0,0,0,0,0,0,254,254,254,254,68,0,0,0,0,0, 0,0,0,0,0,117,254,254,254,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,117,237,48,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,185,237,32,152,254,85,0,0,0, 0,0,0,0,0,0,254,117,85,221,254,136,0,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0, 0,0,0,0,0,254,185,185,85,101,237,185,0,0,0,0,0,0,0,0,0,0,68,254,152,16,0,48,48,0,0,0, 0,0,0,0,0,85,254,101,0,117,254,185,0,0,0,0,0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,85,254,68,0,117,254,185,0,0,0,0, 0,0,0,0,0,0,254,185,185,68,136,254,101,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,101,237,48,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,185,101,221,185,152,169,185,0,0,0, 0,0,0,0,0,0,254,185,185,68,136,254,101,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,254,169,0,0,0,117,254,32,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0, 0,0,0,0,0,185,169,0,0,0,185,185,0,0,0,0,0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,169,169,0,0,0,185,185,0,0,0,0, 0,0,0,0,0,0,254,185,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,85,254,101,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,117,0,185,185,0,117,185,0,0,0, 0,0,0,0,0,0,254,185,0,0,0,254,117,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0,0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,169,237,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0,0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,136,205,237,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,117,237,0,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0, 0,0,0,0,0,221,169,0,0,16,221,185,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,221,169,0,0,16,221,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,16,205,237,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0, 0,0,0,0,0,254,237,85,0,68,237,117,0,0,0,0,0,0,0,0,0,0,68,254,152,32,0,32,68,0,0,0, 0,0,0,0,0,117,254,117,85,185,205,185,0,0,0,0,0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,117,254,117,85,205,185,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,32,237,205,16,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0, 0,0,0,0,0,254,117,169,254,237,117,0,0,0,0,0,0,0,0,0,0,0,0,68,185,254,254,221,136,0,0,0, 0,0,0,0,0,16,152,254,221,48,185,185,0,0,0,0,0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,136,254,237,101,185,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,48,237,205,16,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,221,136,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,0,0,117,254,68,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,85,0,0,169,237,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,185,254,254,205,85,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,185,254,254,205,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,117,117,0,0,0,0, 0,0,0,0,0,0,0,0,117,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,85,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,221,117,117,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,221,136,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,101,237,254,136,0,0,0,0,0,0,0,0,0,0,85,221,254,185,101,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,85,221,254,169,0,0,0,0,0,0,0,0,0,16,152,237,254,254,205,48,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,185,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,205,205,0,0,0,0,136,205,0,0,0,0,0,0,0,237,85,0,0,68,32,0,32,237,0,0,0, 0,0,0,0,0,152,254,48,0,0,85,254,48,0,0,0,0,0,0,0,0,152,221,0,0,0,0,117,221,0,0,0, 0,0,0,0,0,185,254,254,254,254,254,254,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,185,185,85,117,254,117,0,0,0,0,0,0,0,0,85,254,117,0,68,237,254,0,0,0,0, 0,0,0,0,0,0,0,254,185,205,101,117,185,0,0,0,0,0,0,0,0,0,152,221,32,0,0,68,32,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,101,254,48,0,0,0,237,101,0,0,0,0,0,0,0,185,117,0,48,254,136,0,68,185,0,0,0, 0,0,0,0,0,16,205,221,16,16,237,117,0,0,0,0,0,0,0,0,0,68,254,101,0,0,0,221,117,0,0,0, 0,0,0,0,0,0,0,0,0,48,237,152,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,169,0,0,0,169,221,0,0,0,0,0,0,0,0,185,169,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,254,205,16,0,32,101,0,0,0,0,0,0,0,0,0,185,221,32,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,16,237,152,0,0,101,237,16,0,0,0,0,0,0,0,117,169,0,117,185,205,0,117,117,0,0,0, 0,0,0,0,0,0,48,237,169,185,185,0,0,0,0,0,0,0,0,0,0,0,221,185,0,0,85,237,16,0,0,0, 0,0,0,0,0,0,0,0,16,205,152,0,0,0,0,0,0,0,0,0,0,0,0,85,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0, 0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,68,237,254,205,117,16,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,152,237,16,0,185,152,0,0,0,0,0,0,0,0,85,205,0,185,48,254,16,169,85,0,0,0, 0,0,0,0,0,0,0,101,254,237,32,0,0,0,0,0,0,0,0,0,0,0,101,254,32,0,185,152,0,0,0,0, 0,0,0,0,0,0,0,16,205,185,0,0,0,0,0,0,0,0,0,0,0,0,254,254,117,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,254,0,0,0,0, 0,0,0,0,0,117,221,221,185,32,0,48,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,117,205,254,237,32,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,32,254,117,32,254,32,0,0,0,0,0,0,0,0,48,254,16,237,0,205,85,205,48,0,0,0, 0,0,0,0,0,0,0,117,254,237,48,0,0,0,0,0,0,0,0,0,0,0,16,237,136,48,254,32,0,0,0,0, 0,0,0,0,0,0,0,185,205,16,0,0,0,0,0,0,0,0,0,0,0,0,0,85,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0, 0,0,0,0,0,237,16,0,117,237,136,205,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,169,185,0,0,0,0,0,0,0,0,221,169,0,0,0,169,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,254,117,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0, 0,0,0,0,0,0,0,185,221,136,185,0,0,0,0,0,0,0,0,0,0,254,117,169,0,136,136,254,0,0,0,0, 0,0,0,0,0,0,48,254,101,221,205,16,0,0,0,0,0,0,0,0,0,0,0,152,237,169,169,0,0,0,0,0, 0,0,0,0,0,0,152,205,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,32,117,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,237,68,0,117,254,85,0,0,0,0,0,0,0,0,117,254,117,85,185,185,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,117,48,0,0,117,254,68,0,0,0, 0,0,0,0,0,0,0,221,205,32,0,0,0,0,0,0,0,0,0,0,0,0,221,221,85,117,169,254,117,0,0,0, 0,0,0,0,0,0,0,101,254,237,101,0,0,0,0,0,0,0,0,0,0,185,237,101,0,85,254,185,0,0,0,0, 0,0,0,0,0,16,221,136,0,48,254,152,0,0,0,0,0,0,0,0,0,0,0,48,254,254,68,0,0,0,0,0, 0,0,0,0,0,152,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,136,169,254,221,101,0,0,0,0,0,0,0,0,0,0,136,254,221,101,117,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,169,221,254,254,205,85,0,0,0,0, 0,0,0,0,0,0,0,48,205,254,254,254,0,0,0,0,0,0,0,0,0,0,48,221,254,152,16,254,117,0,0,0, 0,0,0,0,0,0,0,0,237,237,0,0,0,0,0,0,0,0,0,0,0,136,254,32,0,32,254,136,0,0,0,0, 0,0,0,0,0,152,205,0,0,0,117,254,101,0,0,0,0,0,0,0,0,0,0,0,205,221,0,0,0,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,254,0,0,0,0,0,0,0,0,0,0,0,0,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,237,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,237,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,237,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,152,221,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,254,185,185,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,254,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,205,48,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,0,0,0,0, 0,0,0,0,0,0,0,0,68,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,185,117,0,185,117,0,0,0,0,0,0,0,0,0,0,0,0,68,117,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,85,185,48,0,0,0,0,0,0,0,0,0,0,0,0,48,117,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,169,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,48,136,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,48,117,85,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,101,185,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,85,117,48,0,0,0,0,0,0,0,0,0,0,0,0,136,169,0,0,0,0,0,0,0, 0,0,0,0,0,0,48,32,0,48,32,0,0,0,0,0,0,0,0,0,0,0,0,117,0,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,101,185,254,254,221,136,0,0,0,0,0,0,0,0,0,0,185,48,0,185,48,0,0,0,0, 0,0,0,0,0,0,0,16,237,101,0,0,0,0,0,0,0,0,0,0,0,0,32,237,117,237,85,0,0,0,0,0, 0,0,0,0,0,0,101,136,0,101,136,0,0,0,0,0,0,0,0,0,0,0,0,16,205,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,16,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,32,237,117,237,85,0,0,0,0,0,0,0,0,0,0,0,48,185,0,48,185,0,0,0,0,0, 0,0,0,0,0,0,0,0,152,185,0,0,0,0,0,0,0,0,0,0,0,0,0,136,101,0,136,101,0,0,0,0, 0,0,0,0,0,0,0,85,237,117,237,32,0,0,0,0,0,0,0,0,0,0,0,16,205,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,85,185,85,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,152,237,101,0,0,68,117,0,0,0,0,0,0,0,0,0,0,117,32,0,117,32,0,0,0,0, 0,0,0,0,0,0,0,85,101,0,0,0,0,0,0,0,0,0,0,0,0,0,85,85,0,48,117,0,0,0,0,0, 0,0,0,0,0,0,68,101,0,68,101,0,0,0,0,0,0,0,0,0,0,0,0,0,32,117,16,0,0,0,0,0, 0,0,0,0,0,0,0,16,117,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,85,85,0,48,117,0,0,0,0,0,0,0,0,0,0,0,32,117,0,32,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,48,0,0,0,0,0,0,0,0,0,0,0,0,101,68,0,101,68,0,0,0,0, 0,0,0,0,0,0,0,117,48,0,85,85,0,0,0,0,0,0,0,0,0,0,0,0,32,117,16,0,0,0,0,0, 0,0,0,0,0,0,0,169,254,169,0,0,0,0,0,0,0,0,0,0,0,0,0,169,254,169,0,0,0,0,0,0, 0,0,0,0,0,68,254,85,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,16,254,205,254,16,0,0,0,0,0,0,0,0,0,0,0,16,254,205,254,16,0,0,0,0,0, 0,0,0,0,0,169,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0,0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0, 0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0,0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0, 0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0,0,0,0,0,0,0,0,85,205,254,254,221,101,0,0,0, 0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0,0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0,0,0,0,0,0,0,254,254,254,254,117,0,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,117,0,0,0,0,0,0,0,0,0,0,0,254,254,254,254,117,0,0,0,0,0, 0,0,0,0,0,0,101,237,48,254,101,0,0,0,0,0,0,0,0,0,0,0,101,237,48,254,101,0,0,0,0,0, 0,0,0,0,0,221,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0,0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0, 0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0,0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0, 0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0,0,0,0,0,0,0,68,254,152,16,0,48,48,0,0,0, 0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0,0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0, 0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,169,136,0,221,169,0,0,0,0,0,0,0,0,0,0,0,169,136,0,221,169,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,185,205,0,0,0,0,0,0,0,0, 0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0,0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0, 0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,32,254,48,0,117,254,32,0,0,0,0,0,0,0,0,0,32,254,48,0,117,254,32,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0,0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0, 0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0,0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0, 0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0,0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0, 0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,117,221,0,0,32,254,117,0,0,0,0,0,0,0,0,0,117,221,0,0,32,254,117,0,0,0,0, 0,0,0,0,0,205,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0,0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0, 0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0,0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0, 0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0,0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0, 0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,205,254,254,254,254,254,205,0,0,0,0,0,0,0,0,0,205,254,254,254,254,254,205,0,0,0,0, 0,0,0,0,0,117,254,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0, 0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0,0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0, 0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,32,254,48,0,0,0,117,254,32,0,0,0,0,0,0,0,32,254,48,0,0,0,117,254,32,0,0,0, 0,0,0,0,0,16,205,237,68,0,0,0,32,0,0,0,0,0,0,0,0,0,221,221,85,117,169,254,117,0,0,0, 0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0,0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0, 0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0,0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0, 0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0,0,0,0,0,0,0,85,254,152,32,0,32,68,0,0,0, 0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0,0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0, 0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,117,221,0,0,0,0,32,254,117,0,0,0,0,0,0,0,117,221,0,0,0,0,32,254,117,0,0,0, 0,0,0,0,0,0,32,185,254,205,185,221,169,0,0,0,0,0,0,0,0,0,48,221,254,152,16,254,117,0,0,0, 0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0,0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0, 0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0,0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0, 0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0,0,0,0,0,0,0,0,85,205,254,254,221,117,0,0,0, 0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0,0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0, 0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,205,117,0,0,0,0,0,185,205,0,0,0,0,0,0,0,205,117,0,0,0,0,0,185,205,0,0,0, 0,0,0,0,0,0,0,0,68,185,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,205,16,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,32,136,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,48,237,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,143,251,198,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,185,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,169,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,0,68,254,0,0,0,0,0, 0,0,0,0,0,0,0,254,68,0,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,117,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,185,32,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,85,117,48,0,0,0,0,0,0,0,0,0,0,0,0,101,185,32,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,0,16,68,0,0,0,0,0, 0,0,0,0,0,0,0,68,16,0,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,185,185,185,185,185,185,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,32,185,185,185,185,101,0,0,0,0,0,0,0,0,0,32,237,117,237,85,0,0,0,0,0, 0,0,0,0,0,0,101,136,0,101,136,0,0,0,0,0,0,0,0,0,0,0,0,0,152,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,85,237,117,237,32,0,0,0,0,0,0,0,0,0,0,0,0,152,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,48,0,185,48,0,0,0,0,0,0,0,0,0,0,16,169,254,254,169,16,0,0,0,0, 0,0,0,0,0,0,185,101,0,0,0,136,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,101,221,254,237,0,0,0,0,0,0,0,0,0,0,32,169,254,254,169,136,185,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,237,254,117,0,0,0, 0,0,0,0,0,0,254,152,68,68,68,68,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,254,68,68,32,0,0,0,0,0,0,0,0,0,85,85,0,48,117,0,0,0,0,0, 0,0,0,0,0,0,68,101,0,68,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,48,0,0,0,0,0, 0,0,0,0,0,0,0,117,48,0,85,85,0,0,0,0,0,0,0,0,0,0,0,0,0,117,48,0,0,0,0,0, 0,0,0,0,0,0,0,117,32,0,117,32,0,0,0,0,0,0,0,0,0,16,205,152,16,16,152,205,16,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,48,254,85,0,48,0,0,0,0,0,0,0,0,0,16,205,152,16,16,152,254,48,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,237,32,0,32,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,205,237,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,237,16,0,0,16,237,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,117,237,16,0,0,185,254,117,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,221,136,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,254,237,136,237,254,136,0,0,0, 0,0,0,0,0,0,48,254,152,254,0,0,0,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,152,221,0,0,0,0,117,221,0,0,0,0,0,0,0,0,185,169,0,0,0,0,169,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,0,85,205,254,254,169,221,48,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,185,169,0,0,85,221,205,185,0,0,0, 0,0,0,0,0,85,16,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,0,48,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,254,152,68,68,68,48,0,0,0,0,0,0,0,0,0,16,32,0,169,254,117,48,254,48,0,0, 0,0,0,0,0,0,136,205,117,254,68,68,16,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,68,254,101,0,0,0,221,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,85,254,117,0,48,254,205,0,0,0,0, 0,0,0,0,0,0,48,152,254,68,32,0,0,0,0,0,0,0,0,0,0,254,117,0,16,221,85,117,254,0,0,0, 0,0,0,0,0,101,205,16,0,0,101,221,48,0,0,0,0,0,0,0,0,0,48,152,254,85,16,0,0,0,0,0, 0,0,0,0,0,0,254,221,185,185,185,136,0,0,0,0,0,0,0,0,0,0,0,48,152,254,68,68,254,117,0,0, 0,0,0,0,0,0,221,101,117,254,185,185,48,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,221,185,0,0,85,237,16,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,205,205,0,0,169,185,254,85,0,0,0, 0,0,0,0,0,0,136,221,254,185,101,0,0,0,0,0,0,0,0,0,0,254,117,0,136,185,0,117,254,0,0,0, 0,0,0,0,0,0,101,205,16,101,237,48,0,0,0,0,0,0,0,0,0,0,136,237,237,185,48,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,48,205,221,221,254,254,254,254,117,0,0, 0,0,0,0,0,85,254,16,117,254,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,101,254,32,0,185,152,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,254,117,0,117,185,0,254,117,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,254,117,48,254,32,0,117,254,0,0,0, 0,0,0,0,0,0,0,101,221,237,48,0,0,0,0,0,0,0,0,0,0,0,0,205,169,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,152,237,185,221,254,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,16,237,136,48,254,32,0,0,0,0,0,0,0,0,0,205,152,0,0,0,0,152,205,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,254,117,68,237,16,0,254,117,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,205,169,185,117,0,0,152,205,0,0,0, 0,0,0,0,0,0,0,48,221,205,16,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,117,254,16,0,0,0,0,0, 0,0,0,0,0,237,117,68,152,254,0,0,0,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0, 0,0,0,0,0,0,0,152,237,169,169,0,0,0,0,0,0,0,0,0,0,136,221,0,0,0,0,221,136,0,0,0, 0,0,0,0,0,0,237,117,0,0,0,205,117,0,0,0,0,0,0,0,0,205,205,237,48,0,85,254,85,0,0,0, 0,0,0,0,0,0,0,152,169,0,0,0,0,0,0,0,0,0,0,0,0,136,254,221,16,0,0,221,136,0,0,0, 0,0,0,0,0,0,48,221,48,101,205,16,0,0,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,221,221,68,205,254,152,0,48,68,0,0, 0,0,0,0,101,237,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,221,221,85,117,169,254,117,0,0,0,0,0,0,0,0,0,221,221,85,117,169,254,117,0,0,0, 0,0,0,0,0,0,0,48,254,254,68,0,0,0,0,0,0,0,0,0,0,32,237,117,0,0,117,237,32,0,0,0, 0,0,0,0,0,0,152,221,16,0,48,254,32,0,0,0,0,0,0,0,0,101,254,169,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,117,237,85,68,68,68,0,0,0,0,0,0,0,0,0,48,254,152,0,0,117,237,32,0,0,0, 0,0,0,0,0,48,221,48,0,0,101,205,16,0,0,0,0,0,0,0,0,0,117,254,32,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,185,0,0,0,0,0,0,0,0,48,221,237,136,136,237,254,205,85,0,0, 0,0,0,0,169,152,0,0,117,254,254,254,185,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,48,221,254,152,16,254,117,0,0,0,0,0,0,0,0,0,48,221,254,152,16,254,117,0,0,0, 0,0,0,0,0,0,0,0,205,221,0,0,0,0,0,0,0,0,0,0,0,0,48,237,205,205,237,48,0,0,0,0, 0,0,0,0,0,0,16,205,237,185,254,101,0,0,0,0,0,0,0,0,0,152,185,221,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,0,0,0,0,0,0,0,0,0,136,205,237,221,205,237,48,0,0,0,0, 0,0,0,0,0,117,48,0,0,0,0,101,85,0,0,0,0,0,0,0,0,0,136,237,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,237,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,48,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,16,0,68,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,152,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,117,254,205,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,32,0,0,0,0,0,0,0,0 };
78,614
C
72.062268
94
0.562114
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetFontRenderer.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "SnippetFontData.h" #include "SnippetFontRenderer.h" #include "SnippetRender.h" bool GLFontRenderer::m_isInit=false; unsigned int GLFontRenderer::m_textureObject=0; int GLFontRenderer::m_screenWidth=640; int GLFontRenderer::m_screenHeight=480; float GLFontRenderer::m_color[4]={1.0f, 1.0f, 1.0f, 1.0f}; namespace { struct RGBAPixel { unsigned char R,G,B,A; }; #define PIXEL_OPAQUE 0xff } bool GLFontRenderer::init() { glGenTextures(1, (GLuint*)&m_textureObject); if(!m_textureObject) return false; glBindTexture(GL_TEXTURE_2D, m_textureObject); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // expand to rgba RGBAPixel* P = new RGBAPixel[OGL_FONT_TEXTURE_WIDTH*OGL_FONT_TEXTURE_HEIGHT]; for(int i=0;i<OGL_FONT_TEXTURE_WIDTH*OGL_FONT_TEXTURE_HEIGHT;i++) { if(1) { P[i].R = PIXEL_OPAQUE; P[i].G = PIXEL_OPAQUE; P[i].B = PIXEL_OPAQUE; P[i].A = OGLFontData[i]; } else { P[i].R = OGLFontData[i]; P[i].G = OGLFontData[i]; P[i].B = OGLFontData[i]; P[i].A = PIXEL_OPAQUE; } } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, OGL_FONT_TEXTURE_WIDTH, OGL_FONT_TEXTURE_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, P); delete [] P; m_isInit = true; return true; } void GLFontRenderer::print(float x, float y, float fontSize, const char* pString, bool forceMonoSpace, int monoSpaceWidth, bool doOrthoProj) { if(1) { const float Saved0 = m_color[0]; const float Saved1 = m_color[1]; const float Saved2 = m_color[2]; m_color[0] = 0.0f; m_color[1] = 0.0f; m_color[2] = 0.0f; // const float Offset = fontSize * 0.05f; // const float Offset = fontSize * 0.075f; const float Offset = fontSize * 0.1f; print_(x+Offset, y-Offset, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); //print_(x-Offset, y-Offset, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); //print_(x+Offset, y+Offset, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); //print_(x-Offset, y+Offset, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); m_color[0] = Saved0; m_color[1] = Saved1; m_color[2] = Saved2; } print_(x, y, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); } void GLFontRenderer::print_(float x, float y, float fontSize, const char* pString, bool forceMonoSpace, int monoSpaceWidth, bool doOrthoProj) { x = x*m_screenWidth; y = y*m_screenHeight; fontSize = fontSize*m_screenHeight; if(!m_isInit) m_isInit = init(); unsigned int num = (unsigned int)(strlen(pString)); if(m_isInit && num > 0) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_textureObject); if(doOrthoProj) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, m_screenWidth, 0, m_screenHeight, -1, 1); } glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glEnable(GL_BLEND); glDisable(GL_CULL_FACE); glColor4f(m_color[0], m_color[1], m_color[2], m_color[3]); const float glyphHeightUV = ((float)OGL_FONT_CHARS_PER_COL)/OGL_FONT_TEXTURE_HEIGHT*2 - 1.0f/128.0f; //const float glyphHeightUV = ((float)OGL_FONT_CHARS_PER_COL)/OGL_FONT_TEXTURE_HEIGHT*2; float translate = 0.0f; float* pVertList = new float[num*3*6]; float* pTextureCoordList = new float[num*2*6]; int vertIndex = 0; int textureCoordIndex = 0; float translateDown = 0.0f; unsigned int count = 0; for(unsigned int i=0;i<num; i++) { const float glyphWidthUV = ((float)OGL_FONT_CHARS_PER_ROW)/OGL_FONT_TEXTURE_WIDTH; if (pString[i] == '\n') { translateDown-=0.005f*m_screenHeight+fontSize; translate = 0.0f; continue; } int c = pString[i]-OGL_FONT_CHAR_BASE; if (c < OGL_FONT_CHARS_PER_ROW*OGL_FONT_CHARS_PER_COL) { count++; float glyphWidth = (float)GLFontGlyphWidth[c]+1; if(forceMonoSpace) glyphWidth = (float)monoSpaceWidth; glyphWidth = glyphWidth*(fontSize/(((float)OGL_FONT_TEXTURE_WIDTH)/OGL_FONT_CHARS_PER_ROW))-0.01f; const float cxUV = float((c)%OGL_FONT_CHARS_PER_ROW)/OGL_FONT_CHARS_PER_ROW+0.008f; const float cyUV = float((c)/OGL_FONT_CHARS_PER_ROW)/OGL_FONT_CHARS_PER_COL+0.008f; pTextureCoordList[textureCoordIndex++] = cxUV; pTextureCoordList[textureCoordIndex++] = cyUV+glyphHeightUV; pVertList[vertIndex++] = x+0+translate; pVertList[vertIndex++] = y+0+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV+glyphWidthUV; pTextureCoordList[textureCoordIndex++] = cyUV; pVertList[vertIndex++] = x+fontSize+translate; pVertList[vertIndex++] = y+fontSize+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV; pTextureCoordList[textureCoordIndex++] = cyUV; pVertList[vertIndex++] = x+0+translate; pVertList[vertIndex++] = y+fontSize+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV; pTextureCoordList[textureCoordIndex++] = cyUV+glyphHeightUV; pVertList[vertIndex++] = x+0+translate; pVertList[vertIndex++] = y+0+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV+glyphWidthUV; pTextureCoordList[textureCoordIndex++] = cyUV+glyphHeightUV; pVertList[vertIndex++] = x+fontSize+translate; pVertList[vertIndex++] = y+0+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV+glyphWidthUV; pTextureCoordList[textureCoordIndex++] = cyUV; pVertList[vertIndex++] = x+fontSize+translate; pVertList[vertIndex++] = y+fontSize+translateDown; pVertList[vertIndex++] = 0; translate+=glyphWidth; } } glEnableClientState(GL_VERTEX_ARRAY); // glVertexPointer(3, GL_FLOAT, num*6, pVertList); glVertexPointer(3, GL_FLOAT, 3*4, pVertList); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // glTexCoordPointer(2, GL_FLOAT, num*6, pTextureCoordList); glTexCoordPointer(2, GL_FLOAT, 2*4, pTextureCoordList); glDrawArrays(GL_TRIANGLES, 0, count*6); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); delete[] pVertList; delete[] pTextureCoordList; // glMatrixMode(GL_MODELVIEW); // glPopMatrix(); if(doOrthoProj) { glMatrixMode(GL_PROJECTION); glPopMatrix(); } glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); glEnable(GL_CULL_FACE); } } void GLFontRenderer::setScreenResolution(int screenWidth, int screenHeight) { m_screenWidth = screenWidth; m_screenHeight = screenHeight; } void GLFontRenderer::setColor(float r, float g, float b, float a) { m_color[0] = r; m_color[1] = g; m_color[2] = b; m_color[3] = a; }
8,678
C++
29.667844
141
0.70673
NVIDIA-Omniverse/PhysX/physx/snippets/snippetloadcollection/SnippetLoadCollection.cpp
// 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-2023 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 loading xml or binary serialized collections and instantiating the objects in a scene. // // It only compiles and runs on authoring platforms (windows, osx and linux). // The snippet supports connecting to PVD in order to display the scene. // // It is a simple command-line tool supporting the following options:: // SnippetLoadCollection [--pvdhost=<ip address> ] [--pvdport=<ip port> ] [--pvdtimeout=<time ms> ] [--generateExampleFiles] <filename>... // // --pvdhost=<ip address> Defines ip address of PVD, default is 127.0.0.1 // --pvdport=<ip port> Defines ip port of PVD, default is 5425 // --pvdtimeout=<time ms> Defines time out of PVD, default is 10 // --generateExampleFiles Generates a set of example files // <filename>... Input files containing serialized collections (either xml or binary) // // Multiple collection files can be specified. The snippet is currently restricted to load a list of collections which obey // the following rule: The first collection needs to be complete. All following collections - if any - may only maintain // dependencies to objects in the first collection. // // The set of example files that can be generated consists of // collection.xml|collection.bin: Can be used individually. // collectionA.xml|collectionA.bin: Can also be used individually but only contain materials and shapes without actors. // collectionB.xml|collectionB.bin: Need to be used together with collectionA files. The actors contained in collectionB // maintain references to objects in the collectionA. // // **************************************************************************** #include "PxPhysicsAPI.h" #include <iostream> #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #define MAX_INPUT_FILES 16 using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxSerializationRegistry* gSerializationRegistry = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxPvd* gPvd = NULL; static PxU8* gMemBlocks[MAX_INPUT_FILES]; static PxU32 gNbMemBlocks = 0; struct CmdLineParameters { const char* pvdhost; PxU32 pvdport; PxU32 pvdtimeout; const char* inputFiles[MAX_INPUT_FILES]; PxU32 nbFiles; bool generateExampleFiles; CmdLineParameters() : pvdhost(PVD_HOST) , pvdport(5425) , pvdtimeout(10) , nbFiles(0) , generateExampleFiles(false) {} } gParameters; static bool match(const char* opt, const char* ref) { std::string s1(opt); std::string s2(ref); return !s1.compare(0, s2.length(), s2); } static void printHelpMsg() { printf("SnippetLoadCollection usage:\n" "SnippetLoadCollection " "[--pvdhost=<ip address> ] " "[--pvdport=<ip port> ]" "[--pvdtimeout=<time ms> ] " "[--generateExampleFiles]" "<filename>...\n\n" "Load binary or xml serialized collections and instatiate the objects in a PhysX scene.\n"); printf("--pvdhost=<ip address> \n"); printf(" Defines ip address of PVD, default is 127.0.0.1 \n"); printf("--pvdport=<ip port> \n"); printf(" Defines ip port of PVD, default is 5425\n"); printf("--pvdtimeout=<time ms> \n"); printf(" Defines timeout of PVD, default is 10\n"); printf("--generateExampleFiles\n"); printf(" Generates a set of example files\n"); printf("<filename>...\n"); printf(" Input files (xml or binary), if a collection contains shared objects, it needs to be provided with the first file. \n\n"); } static bool parseCommandLine(CmdLineParameters& result, int argc, const char *const*argv) { if( argc <= 1 ) { printHelpMsg(); return false; } for(int i = 1; i < argc; ++i) { if(argv[i][0] != '-' || argv[i][1] != '-') { if (result.nbFiles < MAX_INPUT_FILES) { result.inputFiles[result.nbFiles++] = argv[i]; } else printf( "[WARNING] more input files are specified than supported (maximum %d). Ignoring the file %s\n", MAX_INPUT_FILES, argv[i] ); } else if(match(argv[i], "--pvdhost=")) { const char* hostStr = argv[i] + strlen("--pvdhost="); if(hostStr) result.pvdhost = hostStr; } else if(match(argv[i], "--pvdport=")) { const char* portStr = argv[i] + strlen("--pvdport="); if (portStr) result.pvdport = PxU32(atoi(portStr)); } else if(match(argv[i], "--pvdtimeout=")) { const char* timeoutStr = argv[i] + strlen("--pvdtimeout="); if (timeoutStr) result.pvdtimeout = PxU32(atoi(timeoutStr)); } else if(match(argv[i], "--generateExampleFiles")) { result.generateExampleFiles = true; } else { printf( "[ERROR] Unknown command line parameter \"%s\"\n", argv[i] ); printHelpMsg(); return false; } } if(result.nbFiles == 0 && !result.generateExampleFiles) { printf( "[ERROR] parameter missing.\n" ); printHelpMsg(); return false; } return true; } static bool checkFile(bool& isBinary, const char* filename) { PxDefaultFileInputData fileStream(filename); if (fileStream.getLength() == 0) { printf( "[ERROR] input file %s can't be opened!\n", filename); return false; } char testString[17]; fileStream.read(testString, 16); testString[16] = 0; if (strcmp("SEBD", testString) == 0) { isBinary = true; return true; } if (strcmp("<PhysXCollection", testString) == 0) { isBinary = false; return true; } printf( "[ERROR] input file %s seems neither an xml nor a binary serialized collection file!\n", filename); return false; } static PxCollection* deserializeCollection(PxInputData& inputData, bool isBinary, PxCollection* sharedCollection, PxSerializationRegistry& sr) { PxCollection* collection = NULL; if(isBinary) { PxU32 length = inputData.getLength(); PxU8* memBlock = static_cast<PxU8*>(malloc(length+PX_SERIAL_FILE_ALIGN-1)); gMemBlocks[gNbMemBlocks++] = memBlock; void* alignedBlock = reinterpret_cast<void*>((size_t(memBlock)+PX_SERIAL_FILE_ALIGN-1)&~(PX_SERIAL_FILE_ALIGN-1)); inputData.read(alignedBlock, length); collection = PxSerialization::createCollectionFromBinary(alignedBlock, sr, sharedCollection); } else { PxTolerancesScale scale; PxCookingParams params(scale); collection = PxSerialization::createCollectionFromXml(inputData, params, sr, sharedCollection); } return collection; } void initPhysics() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0, -9.81f, 0); gDispatcher = PxDefaultCpuDispatcherCreate(1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gSerializationRegistry = PxSerialization::createSerializationRegistry(*gPhysics); } void cleanupPhysics() { PX_RELEASE(gSerializationRegistry); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); // releases of all objects for(PxU32 i=0; i<gNbMemBlocks; i++) free(gMemBlocks[i]); // now that the objects have been released, it's safe to release the space they occupy if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetLoadCollection done.\n"); } static void serializeCollection(PxCollection& collection, PxCollection* externalRefs, const char* filename, bool toBinary) { PxDefaultFileOutputStream outputStream(filename); if (!outputStream.isValid()) { printf( "[ERROR] Could not open file %s!\n", filename); return; } bool bret; if (toBinary) { bret = PxSerialization::serializeCollectionToBinary(outputStream, collection, *gSerializationRegistry, externalRefs); } else { bret = PxSerialization::serializeCollectionToXml(outputStream, collection, *gSerializationRegistry, NULL, externalRefs); } if(bret) printf( "Generated: \"%s\"\n", filename); else printf( "[ERROR] Failure when generating %s!\n", filename); } static void generateExampleFiles() { PxCollection* collection = PxCreateCollection(); PxCollection* collectionA = PxCreateCollection(); PxCollection* collectionB = PxCreateCollection(); PX_ASSERT( (collection != NULL) && (collectionA != NULL) && (collectionB != NULL) ); PxMaterial *material = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PX_ASSERT( material ); PxShape* planeShape = gPhysics->createShape(PxPlaneGeometry(), *material); PxShape* boxShape = gPhysics->createShape(PxBoxGeometry(2.f, 2.f, 2.f), *material); PxRigidStatic* rigidStatic = PxCreateStatic(*gPhysics, PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxHalfPi, PxVec3(0.f, 0.f, 1.f))), *planeShape); PxRigidDynamic* rigidDynamic = PxCreateDynamic(*gPhysics, PxTransform(PxVec3(0.f, 2.f, 0.f)), *boxShape, 1.f); collection->add(*material); collection->add(*planeShape); collection->add(*boxShape); collection->add(*rigidStatic); collection->add(*rigidDynamic); PxSerialization::complete(*collection, *gSerializationRegistry); PX_ASSERT(PxSerialization::isSerializable(*collection, *gSerializationRegistry)); collectionA->add(*material); collectionA->add(*planeShape); collectionA->add(*boxShape); PxSerialization::complete(*collectionA, *gSerializationRegistry); PxSerialization::createSerialObjectIds(*collectionA, PxSerialObjectId(1)); PX_ASSERT(PxSerialization::isSerializable(*collectionA, *gSerializationRegistry)); collectionB->add(*rigidStatic); collectionB->add(*rigidDynamic); PxSerialization::complete(*collectionB, *gSerializationRegistry, collectionA); PX_ASSERT(PxSerialization::isSerializable(*collectionB, *gSerializationRegistry, collectionA)); serializeCollection(*collection, NULL, "collection.xml", false); serializeCollection(*collectionA, NULL, "collectionA.xml", false); serializeCollection(*collectionB, collectionA, "collectionB.xml", false); serializeCollection(*collection, NULL, "collection.bin", true); serializeCollection(*collectionA, NULL, "collectionA.bin", true); serializeCollection(*collectionB, collectionA, "collectionB.bin", true); collection->release(); collectionA->release(); collectionB->release(); } int snippetMain(int argc, const char *const* argv) { if(!parseCommandLine(gParameters, argc, argv)) return 1; initPhysics(); if(gParameters.generateExampleFiles) generateExampleFiles(); // collection that may have shared objects PxCollection* firstCollection = NULL; for(PxU32 i=0; i<gParameters.nbFiles; i++) { const char* filename = gParameters.inputFiles[i]; bool isBinary; bool validFile = checkFile(isBinary, filename); if (!validFile) break; PxDefaultFileInputData inputStream(filename); PxCollection* collection = deserializeCollection(inputStream, isBinary, firstCollection, *gSerializationRegistry); if (!collection) { printf( "[ERROR] deserialization failure! filename: %s\n", filename); break; } else { printf( "Loaded: \"%s\"\n", filename); } gScene->addCollection(*collection); if (i == 0) { firstCollection = collection; } else { collection->release(); } } if (firstCollection) firstCollection->release(); for (unsigned i = 0; i < 20; i++) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } cleanupPhysics(); return 0; }
13,996
C++
31.779859
146
0.711632
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsoftbodyattachment/SnippetSoftBodyAttachment.cpp
// 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-2023 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 demonstrates how to tie rigid and softbodies together. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetsoftbody/SnippetSoftBody.h" #include "../snippetsoftbody/MeshGenerator.h" #include "extensions/PxTetMakerExt.h" #include "extensions/PxTetrahedronMeshExt.h" #include "extensions/PxSoftBodyExt.h" using namespace physx; using namespace meshgenerator; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxCudaContextManager* gCudaContextManager = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; std::vector<SoftBody> gSoftBodies; static PxFilterFlags softBodyRigidBodyFilter(PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(attributes1); PX_UNUSED(constantBlock); PX_UNUSED(constantBlockSize); if (filterData0.word2 != 0 && filterData0.word2 != filterData1.word2) return PxFilterFlag::eKILL; pairFlags |= PxPairFlag::eCONTACT_DEFAULT; return PxFilterFlag::eDEFAULT; } void addSoftBody(PxSoftBody* softBody, const PxFEMParameters& femParams, PxFEMSoftBodyMaterial* femMaterial, const PxTransform& transform, const PxReal density, const PxReal scale, const PxU32 iterCount/*, PxMaterial* tetMeshMaterial*/) { PxShape* shape = softBody->getShape(); PxVec4* simPositionInvMassPinned; PxVec4* simVelocityPinned; PxVec4* collPositionInvMassPinned; PxVec4* restPositionPinned; PxSoftBodyExt::allocateAndInitializeHostMirror(*softBody, gCudaContextManager, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); const PxReal maxInvMassRatio = 50.f; softBody->setParameter(femParams); shape->setSoftBodyMaterials(&femMaterial, 1); softBody->setSolverIterationCounts(iterCount); PxSoftBodyExt::transform(*softBody, transform, scale, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); PxSoftBodyExt::updateMass(*softBody, density, maxInvMassRatio, simPositionInvMassPinned); PxSoftBodyExt::copyToDevice(*softBody, PxSoftBodyDataFlag::eALL, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); SoftBody sBody(softBody, gCudaContextManager); gSoftBodies.push_back(sBody); PX_PINNED_HOST_FREE(gCudaContextManager, simPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, simVelocityPinned); PX_PINNED_HOST_FREE(gCudaContextManager, collPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, restPositionPinned); } static PxSoftBody* createSoftBody(const PxCookingParams& params, const PxArray<PxVec3>& triVerts, const PxArray<PxU32>& triIndices, bool useCollisionMeshForSimulation = false) { PxFEMSoftBodyMaterial* material = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); material->setDamping(0.005f); PxSoftBodyMesh* softBodyMesh; PxU32 numVoxelsAlongLongestAABBAxis = 8; PxSimpleTriangleMesh surfaceMesh; surfaceMesh.points.count = triVerts.size(); surfaceMesh.points.data = triVerts.begin(); surfaceMesh.triangles.count = triIndices.size() / 3; surfaceMesh.triangles.data = triIndices.begin(); if (useCollisionMeshForSimulation) { softBodyMesh = PxSoftBodyExt::createSoftBodyMeshNoVoxels(params, surfaceMesh, gPhysics->getPhysicsInsertionCallback()); } else { softBodyMesh = PxSoftBodyExt::createSoftBodyMesh(params, surfaceMesh, numVoxelsAlongLongestAABBAxis, gPhysics->getPhysicsInsertionCallback()); } //Alternatively one can cook a softbody mesh in a single step //tetMesh = cooking.createSoftBodyMesh(simulationMeshDesc, collisionMeshDesc, softbodyDesc, physics.getPhysicsInsertionCallback()); PX_ASSERT(softBodyMesh); if (!gCudaContextManager) return NULL; PxSoftBody* softBody = gPhysics->createSoftBody(*gCudaContextManager); if (softBody) { PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE; PxFEMSoftBodyMaterial* materialPtr = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); PxTetrahedronMeshGeometry geometry(softBodyMesh->getCollisionMesh()); PxShape* shape = gPhysics->createShape(geometry, &materialPtr, 1, true, shapeFlags); if (shape) { softBody->attachShape(*shape); shape->setSimulationFilterData(PxFilterData(0, 0, 2, 0)); } softBody->attachSimulationMesh(*softBodyMesh->getSimulationMesh(), *softBodyMesh->getSoftBodyAuxData()); gScene->addActor(*softBody); PxFEMParameters femParams; addSoftBody(softBody, femParams, material, PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxIdentity)), 100.f, 1.0f, 30); softBody->setSoftBodyFlag(PxSoftBodyFlag::eDISABLE_SELF_COLLISION, true); } return softBody; } static PxRigidDynamic* createRigidCube(PxReal halfExtent, const PxVec3& position) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); shape->setSimulationFilterData(PxFilterData(0, 0, 1, 0)); PxTransform localTm(position); PxRigidDynamic* body = gPhysics->createRigidDynamic(localTm); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); shape->release(); return body; } static void connectCubeToSoftBody(PxRigidDynamic* cube, PxReal cubeHalfExtent, const PxVec3& cubePosition, PxSoftBody* softBody, PxU32 pointGridResolution = 10) { float f = 2.0f * cubeHalfExtent / (pointGridResolution - 1); for (PxU32 ix = 0; ix < pointGridResolution; ++ix) { PxReal x = ix * f - cubeHalfExtent; for (PxU32 iy = 0; iy < pointGridResolution; ++iy) { PxReal y = iy * f - cubeHalfExtent; for (PxU32 iz = 0; iz < pointGridResolution; ++iz) { PxReal z = iz * f - cubeHalfExtent; PxVec3 p(x, y, z); PxVec4 bary; PxI32 tet = PxTetrahedronMeshExt::findTetrahedronContainingPoint(softBody->getCollisionMesh(), p + cubePosition, bary); if (tet >= 0) softBody->addTetRigidAttachment(cube, tet, bary, p); } } } } static void createSoftbodies(const PxCookingParams& params) { PxArray<PxVec3> triVerts; PxArray<PxU32> triIndices; PxReal maxEdgeLength = 1; createCube(triVerts, triIndices, PxVec3(0, 9.5, 0), 2.5); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); PxSoftBody* softBodyCube = createSoftBody(params, triVerts, triIndices, true); createSphere(triVerts, triIndices, PxVec3(0,4.5,0), 2.5, maxEdgeLength); PxSoftBody* softBodySphere = createSoftBody(params, triVerts, triIndices); createConeY(triVerts, triIndices, PxVec3(0, 12.5, 0), 2.0f, 3.5); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); PxSoftBody* softBodyCone = createSoftBody(params, triVerts, triIndices); PxReal halfExtent = 1; PxVec3 cubePosA(0, 7.25, 0); PxVec3 cubePosB(0, 11.75, 0); PxRigidDynamic* rigidCubeA = createRigidCube(halfExtent, cubePosA); PxRigidDynamic* rigidCubeB = createRigidCube(halfExtent, cubePosB); connectCubeToSoftBody(rigidCubeA, 2*halfExtent, cubePosA, softBodySphere); connectCubeToSoftBody(rigidCubeA, 2*halfExtent, cubePosA, softBodyCube); connectCubeToSoftBody(rigidCubeB, 2*halfExtent, cubePosB, softBodyCube); connectCubeToSoftBody(rigidCubeB, 2*halfExtent, cubePosB, softBodyCone); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); // initialize cuda PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (gCudaContextManager && !gCudaContextManager->contextIsValid()) { gCudaContextManager->release(); gCudaContextManager = NULL; printf("Failed to initialize cuda context.\n"); } PxTolerancesScale scale; gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, scale, true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxCookingParams params(scale); params.meshWeldTolerance = 0.001f; params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES); params.buildTriangleAdjacencies = false; params.buildGPUData = true; PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); if (!sceneDesc.cudaContextManager) sceneDesc.cudaContextManager = gCudaContextManager; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_ACTIVE_ACTORS; sceneDesc.sceneQueryUpdateMode = PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.gpuMaxNumPartitions = 8; sceneDesc.filterShader = softBodyRigidBodyFilter; sceneDesc.solverType = PxSolverType::ePGS; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createSoftbodies(params); } void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; gScene->simulate(dt); gScene->fetchResults(true); for (PxU32 i = 0; i < gSoftBodies.size(); i++) { SoftBody* sb = &gSoftBodies[i]; sb->copyDeformedVerticesFromGPU(); } } void cleanupPhysics(bool /*interactive*/) { for (PxU32 i = 0; i < gSoftBodies.size(); i++) gSoftBodies[i].release(); gSoftBodies.clear(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); gCudaContextManager->release(); PX_RELEASE(gFoundation); printf("Snippet Softbody-Rigid-Attachments done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,993
C++
36.994152
175
0.766951
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsplitsim/SnippetSplitSim.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // ******************************************************************************************************* // In addition to the simulate() function, which performs both collision detection and dynamics update, // the PhysX SDK provides an api for separate execution of the collision detection and dynamics update steps. // We shall refer to this feature as "split sim". This snippet demonstrates two ways to use the split sim feature // so that application work can be performed concurrently with the collision detection step. // The snippet creates a list of kinematic box actors along with a number of dynamic actors that // interact with the kinematic actors. //The defines OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG and OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG //demonstrate two distinct modes of split sim operation: // (1)Enabling OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG allows the collision detection step to run in parallel // with the renderer and with the update of the kinematic target poses without introducing any lag between // application time and physics time. This is equivalent to calling simulate() and fetchResults() with the key // difference being that the application can schedule work to run concurrently with the collision detection. // A consequence of this approach is that the first frame is more expensive than subsequent frames because it has to // perform blocking collision detection and dynamics update calls. // (2)OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG also allows the collision to run in parallel with // the renderer and the update of the kinematic target poses but this time with a lag between physics time and // application time; that is, the physics is always a single timestep behind the application because the first // frame merely starts the collision detection for the subsequent frame. A consequence of this approach is that // the first frame is cheaper than subsequent frames. // ******************************************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" //This will allow the split sim to overlap collision and render and game logic. #define OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG 1 #define OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG 0 using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; #define NB_KINE_X 16 #define NB_KINE_Y 16 #define KINE_SCALE 3.1f static bool isFirstFrame = true; PxRigidDynamic* gKinematics[NB_KINE_Y][NB_KINE_X]; PxTransform gKinematicTargets[NB_KINE_Y][NB_KINE_X]; void createDynamics() { const PxU32 NbX = 8; const PxU32 NbY = 8; const PxVec3 dims(0.2f, 0.1f, 0.2f); const PxReal sphereRadius = 0.2f; const PxReal capsuleRadius = 0.2f; const PxReal halfHeight = 0.5f; const PxU32 NbLayers = 3; const float YScale = 0.4f; const float YStart = 6.0f; PxShape* boxShape = gPhysics->createShape(PxBoxGeometry(dims), *gMaterial); PxShape* sphereShape = gPhysics->createShape(PxSphereGeometry(sphereRadius), *gMaterial); PxShape* capsuleShape = gPhysics->createShape(PxCapsuleGeometry(capsuleRadius, halfHeight), *gMaterial); PX_UNUSED(boxShape); PX_UNUSED(sphereShape); PX_UNUSED(capsuleShape); for(PxU32 j=0;j<NbLayers;j++) { const float angle = float(j)*0.08f; const PxQuat rot = PxGetRotYQuat(angle); const float ScaleX = 4.0f; const float ScaleY = 4.0f; for(PxU32 y=0;y<NbY;y++) { for(PxU32 x=0;x<NbX;x++) { const float xf = (float(x)-float(NbX)*0.5f)*ScaleX; const float yf = (float(y)-float(NbY)*0.5f)*ScaleY; PxRigidDynamic* dynamic = NULL; PxU32 v = j&3; PxVec3 pos = PxVec3(xf, YStart + float(j)*YScale, yf); switch(v) { case 0: { PxTransform pose(pos, rot); dynamic = gPhysics->createRigidDynamic(pose); dynamic->attachShape(*boxShape); break; } case 1: { PxTransform pose(pos, PxQuat(PxIdentity)); dynamic = gPhysics->createRigidDynamic(pose); dynamic->attachShape(*sphereShape); break; } default: { PxTransform pose(pos, rot); dynamic = gPhysics->createRigidDynamic(pose); dynamic->attachShape(*capsuleShape); break; } }; PxRigidBodyExt::updateMassAndInertia(*dynamic, 10.f); gScene->addActor(*dynamic); } } } } void createGroudPlane() { PxTransform pose = PxTransform(PxVec3(0.0f, 0.0f, 0.0f),PxQuat(PxHalfPi, PxVec3(0.0f, 0.0f, 1.0f))); PxRigidStatic* actor = gPhysics->createRigidStatic(pose); PxShape* shape = PxRigidActorExt::createExclusiveShape(*actor, PxPlaneGeometry(), *gMaterial); PX_UNUSED(shape); gScene->addActor(*actor); } void createKinematics() { const PxU32 NbX = NB_KINE_X; const PxU32 NbY = NB_KINE_Y; const PxVec3 dims(1.5f, 0.2f, 1.5f); const PxQuat rot = PxQuat(PxIdentity); const float YScale = 0.4f; PxShape* shape = gPhysics->createShape(PxBoxGeometry(dims), *gMaterial); const float ScaleX = KINE_SCALE; const float ScaleY = KINE_SCALE; for(PxU32 y=0;y<NbY;y++) { for(PxU32 x=0;x<NbX;x++) { const float xf = (float(x)-float(NbX)*0.5f)*ScaleX; const float yf = (float(y)-float(NbY)*0.5f)*ScaleY; PxTransform pose(PxVec3(xf, 0.2f + YScale, yf), rot); PxRigidDynamic* body = gPhysics->createRigidDynamic(pose); body->attachShape(*shape); gScene->addActor(*body); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gKinematics[y][x] = body; } } } void updateKinematicTargets(PxReal timeStep) { const float YScale = 0.4f; PxTransform motion; motion.q = PxQuat(PxIdentity); static float gTime = 0.0f; gTime += timeStep; const PxU32 NbX = NB_KINE_X; const PxU32 NbY = NB_KINE_Y; const float Coeff = 0.2f; const float ScaleX = KINE_SCALE; const float ScaleY = KINE_SCALE; for(PxU32 y=0;y<NbY;y++) { for(PxU32 x=0;x<NbX;x++) { const float xf = (float(x)-float(NbX)*0.5f)*ScaleX; const float yf = (float(y)-float(NbY)*0.5f)*ScaleY; const float h = sinf(gTime*2.0f + float(x)*Coeff + + float(y)*Coeff)*2.0f; motion.p = PxVec3(xf, h + 2.0f + YScale, yf); gKinematicTargets[y][x] = motion; } } } void applyKinematicTargets() { const PxU32 NbX = NB_KINE_X; const PxU32 NbY = NB_KINE_Y; for(PxU32 y=0;y<NbY;y++) { for(PxU32 x=0;x<NbX;x++) { PxRigidDynamic* kine = gKinematics[y][x]; const PxTransform& target = gKinematicTargets[y][x]; kine->setKinematicTarget(target); } } } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createKinematics(); createDynamics(); } #if OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG void stepPhysics(bool /*interactive*/) { const PxReal timeStep = 1.0f/60.0f; if(isFirstFrame) { //Run the first frame's collision detection gScene->collide(timeStep); isFirstFrame = false; } //update the kinematice target pose in parallel with collision running updateKinematicTargets(timeStep); gScene->fetchCollision(true); //apply the computed and buffered kinematic target poses applyKinematicTargets(); gScene->advance(); gScene->fetchResults(true); //Run the deferred collision detection for the next frame. This will run in parallel with render. gScene->collide(timeStep); } #elif OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG void stepPhysics(bool /*interactive*/) { PxReal timeStep = 1.0/60.0f; //update the kinematice target pose in parallel with collision running updateKinematicTargets(timeStep); if(!isFirstFrame) { gScene->fetchCollision(true); //apply the computed and buffered kinematic target poses applyKinematicTargets(); gScene->advance(); gScene->fetchResults(true); } else applyKinematicTargets(); isFirstFrame = false; //Run the deferred collision detection for the next frame. This will run in parallel with render. gScene->collide(timeStep); } #else void stepPhysics(bool /*interactive*/) { PxReal timeStep = 1.0/60.0f; //update the kinematice target pose in parallel with collision running gScene->collide(timeStep); updateKinematicTargets(timeStep); gScene->fetchCollision(true); //apply the computed and buffered kinematic target poses applyKinematicTargets(); gScene->advance(); gScene->fetchResults(true); } #endif void cleanupPhysics(bool /*interactive*/) { #if OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG || OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG //Close out remainder of previously running scene. If we don't do this, it will be implicitly done //in gScene->release() but a warning will be issued. gScene->fetchCollision(true); gScene->advance(); gScene->fetchResults(true); #endif PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetSplitSim done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,358
C++
31.43832
120
0.717673
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomconvex/SnippetCustomConvexRender.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void debugRender(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if (nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } debugRender(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-20.0f, 20.0f, -20.0f), PxVec3(0.6f, -0.4f, 0.6f)); Snippets::setupDefault("PhysX Snippet CustomConvex", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } struct RenderMesh { std::vector<PxVec3> positions, normals; }; RenderMesh* createRenderCylinder(float height, float radius, float margin) { struct InternalRenderHelper { InternalRenderHelper(float height_, float radius_, float margin_) : height(height_), radius(radius_), margin(margin_) { mesh = new RenderMesh(); halfHeight = height * 0.5f; sides = (int)ceilf(6.2832f / (2 * acosf((radius - err) / radius))); step = 6.2832f / sides; } float height, radius, margin; RenderMesh* mesh; std::vector<PxVec3> positions; std::vector<PxVec3> normals; float halfHeight; float err = 0.001f; int sides; float step; void addVertex(int index) { mesh->positions.push_back(positions[index]); mesh->normals.push_back(normals[index]); } void addTop(const PxVec3& p0, const PxVec3& n0, const PxVec3& p1, const PxVec3& n1, const PxVec3& ax) { int base = int(positions.size()); positions.push_back(p0); normals.push_back(n0); for (int i = 0; i < sides; ++i) { positions.push_back(PxQuat(i * step, ax).rotate(p1)); normals.push_back(PxQuat(i * step, ax).rotate(n1)); } for (int i = 0; i < sides; ++i) { addVertex(base); addVertex(base + 1 + i); addVertex(base + 1 + (i + 1) % sides); } } void addRing(const PxVec3& p0, const PxVec3& n0, const PxVec3& ax) { int base = int(positions.size()); for (int i = 0; i < sides; ++i) { positions.push_back(PxQuat(i * step, ax).rotate(p0)); normals.push_back(PxQuat(i * step, ax).rotate(n0)); } for (int i = 0; i < sides; ++i) { addVertex(base - sides + i); addVertex(base + i); addVertex(base - sides + (i + 1) % sides); addVertex(base - sides + (i + 1) % sides); addVertex(base + i); addVertex(base + (i + 1) % sides); } } void addBottom(const PxVec3& p0, const PxVec3& n0, const PxVec3& /*ax*/) { int base = int(positions.size()); positions.push_back(p0); normals.push_back(n0); for (int i = 0; i < sides; ++i) { addVertex(base - sides + i); addVertex(base); addVertex(base - sides + (i + 1) % sides); } } void run() { int sides2 = margin > 0 ? (int)ceilf(1.5708f / (2 * acosf((margin - err) / margin))) : 1; float step2 = 1.5708f / sides2; addTop(PxVec3(halfHeight + margin, 0, 0), PxVec3(1, 0, 0), PxVec3(halfHeight + margin, radius, 0), PxVec3(1, 0, 0), PxVec3(1, 0, 0)); for (int i = 1; i <= sides2; ++i) { PxVec3 n = PxQuat(i * step2, PxVec3(0, 0, 1)).rotate(PxVec3(1, 0, 0)); addRing(PxVec3(halfHeight, radius, 0) + n * margin, n, PxVec3(1, 0, 0)); } for (int i = 0; i <= sides2; ++i) { PxVec3 n = PxQuat(i * step2, PxVec3(0, 0, 1)).rotate(PxVec3(0, 1, 0)); addRing(PxVec3(-halfHeight, radius, 0) + n * margin, n, PxVec3(1, 0, 0)); } addBottom(PxVec3(-halfHeight - margin, 0, 0), PxVec3(-1, 0, 0), PxVec3(1, 0, 0)); } }; InternalRenderHelper renderHelper(height, radius, margin); renderHelper.run(); return renderHelper.mesh; } RenderMesh* createRenderCone(float height, float radius, float margin) { struct InternalRenderHelper { InternalRenderHelper(float height_, float radius_, float margin_) : height(height_), radius(radius_), margin(margin_) { mesh = new RenderMesh(); halfHeight = height * 0.5f; sides = (int)ceilf(6.2832f / (2 * acosf(((radius + margin) - err) / (radius + margin)))); step = 6.2832f / sides; } float height, radius, margin; RenderMesh* mesh; std::vector<PxVec3> positions; std::vector<PxVec3> normals; float halfHeight; float err = 0.001f; int sides; float step; void addVertex(int index) { mesh->positions.push_back(positions[index]); mesh->normals.push_back(normals[index]); } void addTop(const PxVec3& p0, const PxVec3& n0, const PxVec3& p1, const PxVec3& n1, const PxVec3& ax) { int base = int(positions.size()); positions.push_back(p0); normals.push_back(n0); for (int i = 0; i < sides; ++i) { positions.push_back(PxQuat(i * step, ax).rotate(p1)); normals.push_back(PxQuat(i * step, ax).rotate(n1)); } for (int i = 0; i < sides; ++i) { addVertex(base); addVertex(base + 1 + i); addVertex(base + 1 + (i + 1) % sides); } } void addRing(const PxVec3& p0, const PxVec3& n0, const PxVec3& ax) { int base = int(positions.size()); for (int i = 0; i < sides; ++i) { positions.push_back(PxQuat(i * step, ax).rotate(p0)); normals.push_back(PxQuat(i * step, ax).rotate(n0)); } for (int i = 0; i < sides; ++i) { addVertex(base - sides + i); addVertex(base + i); addVertex(base - sides + (i + 1) % sides); addVertex(base - sides + (i + 1) % sides); addVertex(base + i); addVertex(base + (i + 1) % sides); } } void addBottom(const PxVec3& p0, const PxVec3& n0, const PxVec3& /*ax*/) { int base = int(positions.size()); positions.push_back(p0); normals.push_back(n0); for (int i = 0; i < sides; ++i) { addVertex(base - sides + i); addVertex(base); addVertex(base - sides + (i + 1) % sides); } } void run() { addTop(PxVec3(halfHeight + margin, 0, 0), PxVec3(1, 0, 0), PxVec3(halfHeight + margin, 0, 0), PxVec3(1, 0, 0), PxVec3(1, 0, 0)); float cosAlph = radius / sqrtf(height * height + radius * radius); float alph = acosf(cosAlph); int sides2 = margin > 0 ? (int)ceilf(alph / (2 * acosf((margin - err) / margin))) : 1; float step2 = alph / sides2; for (int i = 1; i <= sides2; ++i) { PxVec3 n = PxQuat(i * step2, PxVec3(0, 0, 1)).rotate(PxVec3(1, 0, 0)); addRing(PxVec3(halfHeight, 0, 0) + n * margin, n, PxVec3(1, 0, 0)); } sides2 = margin > 0 ? (int)ceilf((3.1416f - alph) / (2 * acosf((margin - err) / margin))) : 1; step2 = (3.1416f - alph) / sides2; for (int i = 0; i <= sides2; ++i) { PxVec3 n = PxQuat(alph + i * step2, PxVec3(0, 0, 1)).rotate(PxVec3(1, 0, 0)); addRing(PxVec3(-halfHeight, radius, 0) + n * margin, n, PxVec3(1, 0, 0)); } addBottom(PxVec3(-halfHeight - margin, 0, 0), PxVec3(-1, 0, 0), PxVec3(1, 0, 0)); } }; InternalRenderHelper renderHelper(height, radius, margin); renderHelper.run(); return renderHelper.mesh; } void destroyRenderMesh(RenderMesh* mesh) { delete mesh; } void renderMesh(const RenderMesh& mesh, const PxTransform& pose, bool sleeping) { const PxVec3 color(1.0f, 0.5f, 0.25f); const PxMat44 shapePose(pose); glPushMatrix(); glMultMatrixf(&shapePose.column0.x); if (sleeping) { const PxVec3 darkColor = color * 0.25f; glColor4f(darkColor.x, darkColor.y, darkColor.z, 1.0f); } else { glColor4f(color.x, color.y, color.z, 1.0f); } glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 3 * sizeof(float), mesh.positions.data()); glNormalPointer(GL_FLOAT, 3 * sizeof(float), mesh.normals.data()); glDrawArrays(GL_TRIANGLES, 0, int(mesh.positions.size())); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); bool shadows = true; if (shadows) { const PxVec3 shadowDir(0.0f, -0.7071067f, -0.7071067f); const PxReal shadowMat[] = { 1,0,0,0, -shadowDir.x / shadowDir.y,0,-shadowDir.z / shadowDir.y,0, 0,0,1,0, 0,0,0,1 }; glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); //glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glColor4f(0.1f, 0.1f, 0.1f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 3 * sizeof(float), mesh.positions.data()); glNormalPointer(GL_FLOAT, 3 * sizeof(float), mesh.normals.data()); glDrawArrays(GL_TRIANGLES, 0, int(mesh.positions.size())); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glEnable(GL_LIGHTING); glPopMatrix(); } } static void PxVertex3f(const PxVec3& v) { ::glVertex3f(v.x, v.y, v.z); }; static void PxScalef(const PxVec3& v) { ::glScalef(v.x, v.y, v.z); }; void renderRaycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxRaycastHit* hit) { glDisable(GL_LIGHTING); if (hit) { glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * hit->distance); PxVertex3f(hit->position); PxVertex3f(hit->position + hit->normal); glEnd(); } else { glColor4f(0.6f, 0.0f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * maxDist); glEnd(); } glEnable(GL_LIGHTING); } void renderSweepBox(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxVec3& halfExtents, const PxSweepHit* hit) { glDisable(GL_LIGHTING); if (hit) { glColor4f(0.0f, 0.6f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * hit->distance); PxVertex3f(hit->position); PxVertex3f(hit->position + hit->normal); glEnd(); PxTransform boxPose(origin + unitDir * hit->distance); PxMat44 boxMat(boxPose); glPushMatrix(); glMultMatrixf(&boxMat.column0.x); PxScalef(halfExtents * 2); glutWireCube(1); glPopMatrix(); } else { glColor4f(0.0f, 0.3f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * maxDist); glEnd(); } glEnable(GL_LIGHTING); } void renderOverlapBox(const PxVec3& origin, const PxVec3& halfExtents, bool hit) { glDisable(GL_LIGHTING); if (hit) { glColor4f(0.0f, 0.0f, 1.0f, 1.0f); PxTransform boxPose(origin); PxMat44 boxMat(boxPose); glPushMatrix(); glMultMatrixf(&boxMat.column0.x); PxScalef(halfExtents * 2); glutWireCube(1); glPopMatrix(); } else { glColor4f(0.0f, 0.0f, 0.6f, 1.0f); PxTransform boxPose(origin); PxMat44 boxMat(boxPose); glPushMatrix(); glMultMatrixf(&boxMat.column0.x); PxScalef(halfExtents * 2); glutWireCube(1); glPopMatrix(); } glEnable(GL_LIGHTING); } #endif
13,057
C++
26.548523
137
0.660259
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomconvex/CustomConvex.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef CUSTOM_CONVEX_H #define CUSTOM_CONVEX_H #include "PxPhysicsAPI.h" struct CustomConvex : physx::PxCustomGeometry::Callbacks, physx::PxGjkQuery::Support { float margin; CustomConvex(float margin); // override PxCustomGeometry::Callbacks virtual physx::PxBounds3 getLocalBounds(const physx::PxGeometry&) const; virtual bool generateContacts(const physx::PxGeometry& geom0, const physx::PxGeometry& geom1, const physx::PxTransform& pose0, const physx::PxTransform& pose1, const physx::PxReal contactDistance, const physx::PxReal meshContactMargin, const physx::PxReal toleranceLength, physx::PxContactBuffer& contactBuffer) const; virtual physx::PxU32 raycast(const physx::PxVec3& origin, const physx::PxVec3& unitDir, const physx::PxGeometry& geom, const physx::PxTransform& pose, physx::PxReal maxDist, physx::PxHitFlags hitFlags, physx::PxU32 maxHits, physx::PxGeomRaycastHit* rayHits, physx::PxU32 stride, physx::PxRaycastThreadContext*) const; virtual bool overlap(const physx::PxGeometry& geom0, const physx::PxTransform& pose0, const physx::PxGeometry& geom1, const physx::PxTransform& pose1, physx::PxOverlapThreadContext*) const; virtual bool sweep(const physx::PxVec3& unitDir, const physx::PxReal maxDist, const physx::PxGeometry& geom0, const physx::PxTransform& pose0, const physx::PxGeometry& geom1, const physx::PxTransform& pose1, physx::PxGeomSweepHit& sweepHit, physx::PxHitFlags hitFlags, const physx::PxReal inflation, physx::PxSweepThreadContext*) const; virtual void visualize(const physx::PxGeometry&, physx::PxRenderOutput&, const physx::PxTransform&, const physx::PxBounds3&) const {} virtual bool usePersistentContactManifold(const physx::PxGeometry&, physx::PxReal&) const { return true; } // override PxGjkQuery::Support virtual physx::PxReal getMargin() const; }; struct CustomCylinder : CustomConvex { float height, radius; CustomCylinder(float _height, float _radius, float _margin) : CustomConvex(_margin), height(_height), radius(_radius) {} // override PxCustomGeometry::Callbacks DECLARE_CUSTOM_GEOMETRY_TYPE virtual void computeMassProperties(const physx::PxGeometry& geometry, physx::PxMassProperties& massProperties) const; // override PxGjkQuery::Support virtual physx::PxVec3 supportLocal(const physx::PxVec3& dir) const; }; struct CustomCone : CustomConvex { float height, radius; CustomCone(float _height, float _radius, float _margin) : CustomConvex(_margin), height(_height), radius(_radius) {} // override PxCustomGeometry::Callbacks DECLARE_CUSTOM_GEOMETRY_TYPE virtual void computeMassProperties(const physx::PxGeometry& geometry, physx::PxMassProperties& massProperties) const; // override PxGjkQuery::Support virtual physx::PxVec3 supportLocal(const physx::PxVec3& dir) const; }; #endif
4,494
C
47.333333
190
0.775256
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomconvex/CustomConvex.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "collision/PxCollisionDefs.h" #include "PxImmediateMode.h" #include "geometry/PxGjkQuery.h" #include "extensions/PxGjkQueryExt.h" #include "geometry/PxCustomGeometry.h" #include "CustomConvex.h" #include "geomutils/PxContactBuffer.h" using namespace physx; CustomConvex::CustomConvex(float _margin) : margin(_margin) {} PxBounds3 CustomConvex::getLocalBounds(const PxGeometry&) const { const PxVec3 min(supportLocal(PxVec3(-1, 0, 0)).x, supportLocal(PxVec3(0, -1, 0)).y, supportLocal(PxVec3(0, 0, -1)).z); const PxVec3 max(supportLocal(PxVec3(1, 0, 0)).x, supportLocal(PxVec3(0, 1, 0)).y, supportLocal(PxVec3(0, 0, 1)).z); PxBounds3 bounds(min, max); bounds.fattenSafe(getMargin()); return bounds; } bool CustomConvex::generateContacts(const PxGeometry& geom0, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1, const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength, PxContactBuffer& contactBuffer) const { switch (int(geom1.getType())) { case PxGeometryType::eSPHERE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eCONVEXMESH: { PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1); if (PxGjkQueryExt::generateContacts(*this, geomSupport, pose0, pose1, contactDistance, toleranceLength, contactBuffer)) return true; break; } case PxGeometryType::ePLANE: { const PxPlane plane = PxPlane(1.0f, 0.0f, 0.0f, 0.0f).transform(pose1); const PxPlane localPlane = plane.inverseTransform(pose0); const PxVec3 point = supportLocal(-localPlane.n); const float dist = localPlane.distance(point); const float radius = getMargin(); if (dist < radius) { const PxVec3 n = localPlane.n; const PxVec3 p = point + n * (radius - dist) * 0.5f; PxContactPoint contact; contact.point = pose0.transform(p); contact.normal = pose0.rotate(n); contact.separation = dist - radius; contactBuffer.contact(contact); return true; } break; } case PxGeometryType::eCUSTOM: { const PxCustomGeometry& customGeom1 = static_cast<const PxCustomGeometry&>(geom1); if (customGeom1.getCustomType() == CustomCylinder::TYPE() || customGeom1.getCustomType() == CustomCone::TYPE()) // It's a CustomConvex { CustomConvex* custom1 = static_cast<CustomConvex*>(customGeom1.callbacks); if (PxGjkQueryExt::generateContacts(*this, *custom1, pose0, pose1, contactDistance, toleranceLength, contactBuffer)) return true; } else { struct ContactRecorder : immediate::PxContactRecorder { PxContactBuffer* contactBuffer; ContactRecorder(PxContactBuffer& _contactBuffer) : contactBuffer(&_contactBuffer) {} virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/) { for (PxU32 i = 0; i < nbContacts; ++i) contactBuffer->contact(contactPoints[i]); return true; } } contactRecorder(contactBuffer); PxCache contactCache; struct ContactCacheAllocator : PxCacheAllocator { PxU8 buffer[1024]; ContactCacheAllocator() { memset(buffer, 0, sizeof(buffer)); } virtual PxU8* allocateCacheData(const PxU32 /*byteSize*/) { return reinterpret_cast<PxU8*>(size_t(buffer + 0xf) & ~0xf); } } contactCacheAllocator; const PxGeometry* pGeom0 = &geom0; const PxGeometry* pGeom1 = &geom1; immediate::PxGenerateContacts(&pGeom1, &pGeom0, &pose1, &pose0, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); for (int i = 0; i < int(contactBuffer.count); ++i) contactBuffer.contacts[i].normal = -contactBuffer.contacts[i].normal; } break; } default: break; } return false; } PxU32 CustomConvex::raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& /*geom*/, const PxTransform& pose, PxReal maxDist, PxHitFlags /*hitFlags*/, PxU32 /*maxHits*/, PxGeomRaycastHit* rayHits, PxU32 /*stride*/, PxRaycastThreadContext*) const { PxReal t; PxVec3 n, p; if (PxGjkQuery::raycast(*this, pose, origin, unitDir, maxDist, t, n, p)) { PxGeomRaycastHit& hit = *rayHits; hit.distance = t; hit.position = p; hit.normal = n; return 1; } return 0; } bool CustomConvex::overlap(const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext*) const { switch (int(geom1.getType())) { case PxGeometryType::eSPHERE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eCONVEXMESH: { PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1); if (PxGjkQuery::overlap(*this, geomSupport, pose0, pose1)) return true; break; } default: break; } return false; } bool CustomConvex::sweep(const PxVec3& unitDir, const PxReal maxDist, const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxGeomSweepHit& sweepHit, PxHitFlags /*hitFlags*/, const PxReal inflation, PxSweepThreadContext*) const { switch (int(geom1.getType())) { case PxGeometryType::eSPHERE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eCONVEXMESH: { PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1, inflation); PxReal t; PxVec3 n, p; if (PxGjkQuery::sweep(*this, geomSupport, pose0, pose1, unitDir, maxDist, t, n, p)) { PxGeomSweepHit& hit = sweepHit; hit.distance = t; hit.position = p; hit.normal = n; return true; } break; } default: break; } return false; } PxReal CustomConvex::getMargin() const { return margin; } IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CustomCylinder) //PxU32 CustomCylinder::getCustomType() const //{ // return 1; //} void CustomCylinder::computeMassProperties(const physx::PxGeometry& /*geometry*/, physx::PxMassProperties& massProperties) const { float H = height + 2.0f * margin, R = radius + margin; massProperties.mass = PxPi * R * R * H; massProperties.inertiaTensor = PxMat33(PxZero); massProperties.centerOfMass = PxVec3(PxZero); massProperties.inertiaTensor[0][0] = massProperties.mass * R * R / 2.0f; massProperties.inertiaTensor[1][1] = massProperties.inertiaTensor[2][2] = massProperties.mass * (3 * R * R + H * H) / 12.0f; } PxVec3 CustomCylinder::supportLocal(const PxVec3& dir) const { float halfHeight = height * 0.5f; PxVec3 d = dir.getNormalized(); if (PxSign2(d.x) != 0 && PxSign2(d.y) == 0 && PxSign2(d.z) == 0) return PxVec3(PxSign2(d.x) * halfHeight, 0, 0); return PxVec3(PxSign2(d.x) * halfHeight, 0, 0) + PxVec3(0, d.y, d.z).getNormalized() * radius; } IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CustomCone) void CustomCone::computeMassProperties(const physx::PxGeometry&, physx::PxMassProperties& massProperties) const { float H = height + 2.0f * margin, R = radius + margin; massProperties.mass = PxPi * R * R * H / 3.0f; massProperties.inertiaTensor = PxMat33(PxZero); massProperties.centerOfMass = PxVec3(PxZero); massProperties.inertiaTensor[0][0] = massProperties.mass * R * R * 3.0f / 10.0f; massProperties.inertiaTensor[1][1] = massProperties.inertiaTensor[2][2] = massProperties.mass * (R * R * 3.0f / 20.0f + H * H * 3.0f / 80.0f); massProperties.centerOfMass[0] = -height / 4.0f; } PxVec3 CustomCone::supportLocal(const PxVec3& dir) const { float halfHeight = height * 0.5f; float cosAlph = radius / sqrtf(height * height + radius * radius); PxVec3 d = dir.getNormalized(); if (d.x > cosAlph || (PxSign2(d.x) != 0 && PxSign2(d.y) == 0 && PxSign2(d.z) == 0)) return PxVec3(PxSign2(d.x) * halfHeight, 0, 0); return PxVec3(-halfHeight, 0, 0) + PxVec3(0, d.y, d.z).getNormalized() * radius; }
9,310
C++
34.811538
163
0.726208
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomconvex/SnippetCustomConvex.cpp
// 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-2023 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 shows how to use GJK queries to create custom convex geometry. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "geometry/PxGjkQuery.h" #include "CustomConvex.h" #include "extensions/PxCustomGeometryExt.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; //static std::vector<CustomConvex*> gConvexes; static std::vector<PxCustomGeometryExt::BaseConvexCallbacks*> gConvexes; static std::vector<PxRigidActor*> gActors; struct RenderMesh; static std::vector<RenderMesh*> gMeshes; RenderMesh* createRenderCylinder(float radius, float height, float margin); RenderMesh* createRenderCone(float height, float radius, float margin); void destroyRenderMesh(RenderMesh* mesh); void renderMesh(const RenderMesh& mesh, const PxTransform& pose, bool sleeping); void renderRaycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxRaycastHit* hit); void renderSweepBox(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxVec3& halfExtents, const PxSweepHit* hit); void renderOverlapBox(const PxVec3& origin, const PxVec3& halfExtents, bool hit); static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0), PxReal density = 1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createCylinderActor(float height, float radius, float margin, const PxTransform& pose) { //CustomCylinder* cylinder = new CustomCylinder(height, radius, margin); PxCustomGeometryExt::CylinderCallbacks* cylinder = new PxCustomGeometryExt::CylinderCallbacks(height, radius, 0, margin); gConvexes.push_back(cylinder); PxRigidDynamic* actor = gPhysics->createRigidDynamic(pose); actor->setActorFlag(PxActorFlag::eVISUALIZATION, true); PxShape* shape = PxRigidActorExt::createExclusiveShape(*actor, PxCustomGeometry(*cylinder), *gMaterial); shape->setFlag(PxShapeFlag::eVISUALIZATION, true); PxRigidBodyExt::updateMassAndInertia(*actor, 100); gScene->addActor(*actor); gActors.push_back(actor); RenderMesh* mesh = createRenderCylinder(height, radius, margin); gMeshes.push_back(mesh); } static void createConeActor(float height, float radius, float margin, const PxTransform& pose) { //CustomCone* cone = new CustomCone(height, radius, margin); PxCustomGeometryExt::ConeCallbacks* cone = new PxCustomGeometryExt::ConeCallbacks(height, radius, 0, margin); gConvexes.push_back(cone); PxRigidDynamic* actor = gPhysics->createRigidDynamic(pose); actor->setActorFlag(PxActorFlag::eVISUALIZATION, true); PxShape* shape = PxRigidActorExt::createExclusiveShape(*actor, PxCustomGeometry(*cone), *gMaterial); shape->setFlag(PxShapeFlag::eVISUALIZATION, true); PxRigidBodyExt::updateMassAndInertia(*actor, 100); gScene->addActor(*actor); gActors.push_back(actor); RenderMesh* mesh = createRenderCone(height, radius, margin); gMeshes.push_back(mesh); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gScene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 1.0f); gScene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.0f); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Some custom convexes float heights[] = { 1.0f, 1.25f, 1.5f, 1.75f }; float radiuss[] = { 0.3f, 0.35f, 0.4f, 0.45f }; float margins[] = { 0.0f, 0.05f, 0.1f, 0.15f }; for (int i = 0; i < 50; ++i) { float height = heights[rand() % (sizeof(heights) / sizeof(heights[0]))]; float raduis = radiuss[rand() % (sizeof(radiuss) / sizeof(radiuss[0]))]; float margin = margins[rand() % (sizeof(margins) / sizeof(margins[0]))]; float angle = PX_PIDIV2; createCylinderActor(height, raduis, margin, (PxTransform(PxVec3(-2.0f, 2.0f + i * 2, 2.0f), PxQuat(angle, PxVec3(0.0f, 0.0f, 1.0f))))); } for (int i = 0; i < 50; ++i) { float height = heights[rand() % (sizeof(heights) / sizeof(heights[0]))]; float raduis = radiuss[rand() % (sizeof(radiuss) / sizeof(radiuss[0]))]; float margin = margins[rand() % (sizeof(margins) / sizeof(margins[0]))]; float angle = PX_PIDIV2; createConeActor(height, raduis, margin, (PxTransform(PxVec3(2.0f, 2.0f + i * 2, -2.0f), PxQuat(angle, PxVec3(0, 0, 1))))); } // Ground plane PxRigidStatic* planeActor = gPhysics->createRigidStatic(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0.0f, 0.0f, 1.0f)))); PxRigidActorExt::createExclusiveShape(*planeActor, PxPlaneGeometry(), *gMaterial); gScene->addActor(*planeActor); } void debugRender() { for (int i = 0; i < int(gConvexes.size()); ++i) { PxRigidActor* actor = gActors[i]; RenderMesh* mesh = gMeshes[i]; renderMesh(*mesh, actor->getGlobalPose(), !actor->is<PxRigidDynamic>() || actor->is<PxRigidDynamic>()->isSleeping()); } int count = 20; for (int i = 0; i < count; ++i) { float x = -count / 2.0f; PxVec3 origin(x + i, 0.5f, x); PxVec3 unitDir(0, 0, 1); float maxDist = (float)count; PxRaycastBuffer buffer; gScene->raycast(origin, unitDir, maxDist, buffer); renderRaycast(origin, unitDir, maxDist, buffer.hasBlock ? &buffer.block : nullptr); } for (int i = 0; i < count; ++i) { float x = -count / 2.0f; PxVec3 origin(x, 0.5f, x + i); PxVec3 unitDir(1, 0, 0); float maxDist = (float)count; PxVec3 halfExtents(0.2f, 0.1f, 0.4f); PxSweepBuffer buffer; gScene->sweep(PxBoxGeometry(halfExtents), PxTransform(origin), unitDir, maxDist, buffer); renderSweepBox(origin, unitDir, maxDist, halfExtents, buffer.hasBlock ? &buffer.block : nullptr); } for (int i = 0; i < count; ++i) { float x = -count / 2.0f; for (int j = 0; j < count; ++j) { PxVec3 origin(x + i, 0.0f, x + j); PxVec3 halfExtents(0.4f, 0.1f, 0.4f); PxOverlapBuffer buffer; gScene->overlap(PxBoxGeometry(halfExtents), PxTransform(origin), buffer, PxQueryFilterData(PxQueryFlag::eANY_HIT | PxQueryFlag::eDYNAMIC)); renderOverlapBox(origin, halfExtents, buffer.hasAnyHits()); } } } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { while (!gConvexes.empty()) { delete gConvexes.back(); gConvexes.pop_back(); } while (!gMeshes.empty()) { destroyRenderMesh(gMeshes.back()); gMeshes.pop_back(); } while (!gActors.empty()) { PX_RELEASE(gActors.back()); gActors.pop_back(); } PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetCustomConvex done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch (toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(1.0f), camera.rotate(PxVec3(0, 0, -1)) * 100, 3.0f); break; } } int snippetMain(int, const char* const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for (PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char* const*) { return 0; } #endif
10,611
C++
35.342466
145
0.725851
NVIDIA-Omniverse/PhysX/physx/snippets/snippetfrustumquery/SnippetFrustumQuery.cpp
// 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-2023 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 how to use a PxBVH to implement view-frustum culling. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif //#define BENCHMARK_MODE using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; namespace { class CustomScene { public: CustomScene(); ~CustomScene(); void release(); void addGeom(const PxGeometry& geom, const PxTransform& pose); void createBVH(); void render() const; struct Object { PxGeometryHolder mGeom; PxTransform mPose; }; PxArray<Object> mObjects; PxBVH* mBVH; }; CustomScene::CustomScene() : mBVH(NULL) { } CustomScene::~CustomScene() { } void CustomScene::release() { PX_RELEASE(mBVH); mObjects.reset(); PX_DELETE_THIS; } void CustomScene::addGeom(const PxGeometry& geom, const PxTransform& pose) { Object obj; obj.mGeom.storeAny(geom); obj.mPose = pose; mObjects.pushBack(obj); } void CustomScene::createBVH() { const PxU32 nbObjects = mObjects.size(); PxBounds3* bounds = new PxBounds3[nbObjects]; for(PxU32 i=0;i<nbObjects;i++) { Object& obj = mObjects[i]; PxGeometryQuery::computeGeomBounds(bounds[i], obj.mGeom.any(), obj.mPose); } PxBVHDesc bvhDesc; bvhDesc.bounds.count = nbObjects; bvhDesc.bounds.data = bounds; bvhDesc.bounds.stride = sizeof(PxBounds3); bvhDesc.enlargement = 0.0f; mBVH = PxCreateBVH(bvhDesc); delete [] bounds; } enum FrustumPlaneIndex { FRUSTUM_PLANE_LEFT = 0, FRUSTUM_PLANE_RIGHT = 1, FRUSTUM_PLANE_TOP = 2, FRUSTUM_PLANE_BOTTOM = 3, FRUSTUM_PLANE_NEAR = 4, FRUSTUM_PLANE_FAR = 5, }; void CustomScene::render() const { #ifdef RENDER_SNIPPET if(0) { // This codepath to draw all objects without culling const PxVec3 color(1.0f, 0.5f, 0.25f); for(PxU32 i=0;i<mObjects.size();i++) { const CustomScene::Object& obj = mObjects[i]; Snippets::renderGeoms(1, &obj.mGeom, &obj.mPose, false, color); } return; } // Extract planes from the view/proj matrices. You could also build them from the frustum's vertices. PxPlane planes[6]; { float VM[16]; glGetFloatv(GL_MODELVIEW_MATRIX, VM); const PxMat44 ViewMatrix(VM); float PM[16]; glGetFloatv(GL_PROJECTION_MATRIX, PM); const PxMat44 ProjMatrix(PM); const PxMat44 combo = ProjMatrix * ViewMatrix; planes[FRUSTUM_PLANE_LEFT].n.x = -(combo.column0[3] + combo.column0[0]); planes[FRUSTUM_PLANE_LEFT].n.y = -(combo.column1[3] + combo.column1[0]); planes[FRUSTUM_PLANE_LEFT].n.z = -(combo.column2[3] + combo.column2[0]); planes[FRUSTUM_PLANE_LEFT].d = -(combo.column3[3] + combo.column3[0]); planes[FRUSTUM_PLANE_RIGHT].n.x = -(combo.column0[3] - combo.column0[0]); planes[FRUSTUM_PLANE_RIGHT].n.y = -(combo.column1[3] - combo.column1[0]); planes[FRUSTUM_PLANE_RIGHT].n.z = -(combo.column2[3] - combo.column2[0]); planes[FRUSTUM_PLANE_RIGHT].d = -(combo.column3[3] - combo.column3[0]); planes[FRUSTUM_PLANE_TOP].n.x = -(combo.column0[3] - combo.column0[1]); planes[FRUSTUM_PLANE_TOP].n.y = -(combo.column1[3] - combo.column1[1]); planes[FRUSTUM_PLANE_TOP].n.z = -(combo.column2[3] - combo.column2[1]); planes[FRUSTUM_PLANE_TOP].d = -(combo.column3[3] - combo.column3[1]); planes[FRUSTUM_PLANE_BOTTOM].n.x = -(combo.column0[3] + combo.column0[1]); planes[FRUSTUM_PLANE_BOTTOM].n.y = -(combo.column1[3] + combo.column1[1]); planes[FRUSTUM_PLANE_BOTTOM].n.z = -(combo.column2[3] + combo.column2[1]); planes[FRUSTUM_PLANE_BOTTOM].d = -(combo.column3[3] + combo.column3[1]); planes[FRUSTUM_PLANE_NEAR].n.x = -(combo.column0[3] + combo.column0[2]); planes[FRUSTUM_PLANE_NEAR].n.y = -(combo.column1[3] + combo.column1[2]); planes[FRUSTUM_PLANE_NEAR].n.z = -(combo.column2[3] + combo.column2[2]); planes[FRUSTUM_PLANE_NEAR].d = -(combo.column3[3] + combo.column3[2]); planes[FRUSTUM_PLANE_FAR].n.x = -(combo.column0[3] - combo.column0[2]); planes[FRUSTUM_PLANE_FAR].n.y = -(combo.column1[3] - combo.column1[2]); planes[FRUSTUM_PLANE_FAR].n.z = -(combo.column2[3] - combo.column2[2]); planes[FRUSTUM_PLANE_FAR].d = -(combo.column3[3] - combo.column3[2]); for(PxU32 i=0;i<6;i++) planes[i].normalize(); } if(mBVH) { struct LocalCB : PxBVH::OverlapCallback { LocalCB(const CustomScene& scene) : mScene(scene) { mVisibles.reserve(10000); } virtual bool reportHit(PxU32 boundsIndex) { mVisibles.pushBack(boundsIndex); return true; } const CustomScene& mScene; PxArray<PxU32> mVisibles; LocalCB& operator=(const LocalCB&){return *this;} }; LocalCB cb(*this); #ifdef BENCHMARK_MODE unsigned long long time = __rdtsc(); #endif mBVH->cull(6, planes, cb); char buffer[256]; #ifdef BENCHMARK_MODE time = __rdtsc() - time; sprintf(buffer, "%d visible objects (%d)\n", cb.mVisibles.size(), int(time/1024)); #else sprintf(buffer, "%d visible objects\n", cb.mVisibles.size()); #endif const PxVec3 color(1.0f, 0.5f, 0.25f); for(PxU32 i=0;i<cb.mVisibles.size();i++) { const CustomScene::Object& obj = mObjects[cb.mVisibles[i]]; Snippets::renderGeoms(1, &obj.mGeom, &obj.mPose, false, color); } if(1) { const PxU32 nbObjects = mBVH->getNbBounds(); for(PxU32 i=0;i<nbObjects;i++) Snippets::DrawBounds(mBVH->getBounds()[i]); } Snippets::print(buffer); } #endif } } static PxConvexMesh* createConvexMesh(const PxVec3* verts, const PxU32 numVerts, const PxCookingParams& params) { PxConvexMeshDesc convexDesc; convexDesc.points.count = numVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; return PxCreateConvexMesh(params, convexDesc); } static PxConvexMesh* createCylinderMesh(const PxF32 width, const PxF32 radius, const PxCookingParams& params) { PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } return createConvexMesh(points, 32, params); } static void initScene() { } static void releaseScene() { } static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static CustomScene* gScene = NULL; void renderScene() { if(gScene) gScene->render(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; gConvexMesh = createCylinderMesh(3.0f, 1.0f, params); { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } gScene = new CustomScene; #ifdef BENCHMARK_MODE { SnippetUtils::BasicRandom rnd(42); PxVec3 v; const float coeff = 30.0f; for(int i=0;i<1000;i++) { rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxBoxGeometry(PxVec3(1.0f, 2.0f, 0.5f)), PxTransform(v+PxVec3(0.0f, 0.0f, 0.0f))); rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxSphereGeometry(1.5f), PxTransform(v+PxVec3(4.0f, 0.0f, 0.0f))); rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(v+PxVec3(-4.0f, 0.0f, 0.0f))); rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxConvexMeshGeometry(gConvexMesh), PxTransform(v+PxVec3(0.0f, 0.0f, 4.0f))); rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxTriangleMeshGeometry(gTriangleMesh), PxTransform(v+PxVec3(0.0f, 0.0f, -4.0f))); } } #else { gScene->addGeom(PxBoxGeometry(PxVec3(1.0f, 2.0f, 0.5f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f))); gScene->addGeom(PxSphereGeometry(1.5f), PxTransform(PxVec3(4.0f, 0.0f, 0.0f))); gScene->addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(PxVec3(-4.0f, 0.0f, 0.0f))); gScene->addGeom(PxConvexMeshGeometry(gConvexMesh), PxTransform(PxVec3(0.0f, 0.0f, 4.0f))); gScene->addGeom(PxTriangleMeshGeometry(gTriangleMesh), PxTransform(PxVec3(0.0f, 0.0f, -4.0f))); } #endif gScene->createBVH(); initScene(); } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gScene); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetFrustumQuery done.\n"); } void keyPress(unsigned char /*key*/, const PxTransform& /*camera*/) { /* if(key >= 1 && key <= gScenarioCount) { gScenario = key - 1; releaseScene(); initScene(); } if(key == 'r' || key == 'R') { releaseScene(); initScene(); }*/ } int snippetMain(int, const char*const*) { printf("Frustum query snippet.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
11,648
C++
27.905707
111
0.696085
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometrycollision/SnippetCustomGeometryCollision.cpp
// 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-2023 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 shows how to implement custom geometries generateContacts // callback, using PhysX Immediate Mode contacts generation. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "PxImmediateMode.h" #include "geomutils/PxContactBuffer.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" using namespace physx; /* 10x10 grid of boxes with even boxes removed. */ struct CheckerBoard : PxCustomGeometry::Callbacks { int boardSize; float boxExtent; DECLARE_CUSTOM_GEOMETRY_TYPE CheckerBoard() : boardSize(10), boxExtent(10.0f) {} struct ContactRecorder : immediate::PxContactRecorder { PxContactBuffer* contactBuffer; ContactRecorder(PxContactBuffer& _contactBuffer) : contactBuffer(&_contactBuffer) {} virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/) { for (PxU32 i = 0; i < nbContacts; ++i) if (!contactBuffer->contact(contactPoints[i])) return false; return true; } }; struct ContactCacheAllocator : PxCacheAllocator { PxU8 buffer[1024]; ContactCacheAllocator() { memset(buffer, 0, sizeof(buffer)); } virtual PxU8* allocateCacheData(const PxU32 /*byteSize*/) { return (PxU8*)(size_t(buffer + 0xf) & ~0xf); } }; PxBounds3 getBoardLocalBounds() const { return PxBounds3(-PxVec3(boardSize * boxExtent * 0.5f, boxExtent * 0.5f, boardSize * boxExtent * 0.5f), PxVec3(boardSize * boxExtent * 0.5f, boxExtent * 0.5f, boardSize * boxExtent * 0.5f)); } virtual PxBounds3 getLocalBounds(const PxGeometry&) const { return getBoardLocalBounds(); } virtual bool generateContacts(const PxGeometry&, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1, const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength, PxContactBuffer& contactBuffer) const { PxBoxGeometry boxGeom(PxVec3(boxExtent * 0.5f)); PxGeometry* pGeom0 = &boxGeom; const PxGeometry* pGeom1 = &geom1; PxTransform pose1in0 = pose0.transformInv(pose1); PxBounds3 bounds1; PxGeometryQuery::computeGeomBounds(bounds1, geom1, pose1in0, contactDistance); ContactRecorder contactRecorder(contactBuffer); PxCache contactCache; ContactCacheAllocator contactCacheAllocator; PxBounds3 bounds0 = getBoardLocalBounds(); PxVec3 s = bounds1.minimum + bounds0.getExtents(); PxVec3 e = bounds1.maximum + bounds0.getExtents(); int sx = int(PxFloor(s.x / boxExtent)); int sy = int(PxFloor(s.y / boxExtent)); int sz = int(PxFloor(s.z / boxExtent)); int ex = int(PxFloor(e.x / boxExtent)); int ey = int(PxFloor(e.y / boxExtent)); int ez = int(PxFloor(e.z / boxExtent)); for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (x >= 0 && x < boardSize && y >= 0 && y < boardSize && z >= 0 && z < boardSize && (x + z) & 1 && y == 0) { PxVec3 boxPos = PxVec3((x + 0.5f) * boxExtent, (y + 0.5f) * boxExtent, (z + 0.5f) * boxExtent) - bounds0.getExtents(); PxTransform p0 = pose0.transform(PxTransform(boxPos)); immediate::PxGenerateContacts(&pGeom0, &pGeom1, &p0, &pose1, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); } return true; } virtual PxU32 raycast(const PxVec3&, const PxVec3&, const PxGeometry&, const PxTransform&, PxReal, PxHitFlags, PxU32, PxGeomRaycastHit*, PxU32, PxRaycastThreadContext*) const { return 0; } virtual bool overlap(const PxGeometry&, const PxTransform&, const PxGeometry&, const PxTransform&, PxOverlapThreadContext*) const { return false; } virtual bool sweep(const PxVec3&, const PxReal, const PxGeometry&, const PxTransform&, const PxGeometry&, const PxTransform&, PxGeomSweepHit&, PxHitFlags, const PxReal, PxSweepThreadContext*) const { return false; } virtual void visualize(const PxGeometry&, PxRenderOutput&, const PxTransform&, const PxBounds3&) const {} virtual void computeMassProperties(const physx::PxGeometry&, physx::PxMassProperties&) const {} virtual bool usePersistentContactManifold(const PxGeometry&, PxReal&) const { return false; } }; IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CheckerBoard) static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidStatic* gActor = NULL; static CheckerBoard gCheckerBoard; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0), PxReal density = 1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i < size; i++) { for (PxU32 j = 0; j < size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f * 3, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Create checker board actor PxRigidStatic* checkerBoardActor = gPhysics->createRigidStatic(PxTransform(PxVec3(0, gCheckerBoard.boxExtent * 0.5f, 0))); PxRigidActorExt::createExclusiveShape(*checkerBoardActor, PxCustomGeometry(gCheckerBoard), *gMaterial); gScene->addActor(*checkerBoardActor); gActor = checkerBoardActor; // Ground plane PxRigidStatic* planeActor = gPhysics->createRigidStatic(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 0, 1)))); PxRigidActorExt::createExclusiveShape(*planeActor, PxPlaneGeometry(), *gMaterial); gScene->addActor(*planeActor); createStack(PxTransform(PxVec3(0, 22, 0)), 10, 2.0f); } void debugRender() { float boxExtent = gCheckerBoard.boxExtent; PxBounds3 boardBounds = gCheckerBoard.getBoardLocalBounds(); PxGeometryHolder geom; geom.storeAny(PxBoxGeometry(PxVec3(boxExtent * 0.5f))); for (int x = 0; x < gCheckerBoard.boardSize; ++x) for (int y = 0; y < 1; ++y) for (int z = 0; z < gCheckerBoard.boardSize; ++z) if ((x + z) & 1) { PxVec3 boxPos = PxVec3((x + 0.5f) * boxExtent, (y + 0.5f) * boxExtent, (z + 0.5f) * boxExtent) - boardBounds.getExtents(); PxTransform pose = gActor->getGlobalPose().transform(PxTransform(boxPos)); Snippets::renderGeoms(1, &geom, &pose, false, PxVec3(0.5f)); } } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetGeometryCollision done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch (toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0, 0, -1)) * 200, 3.0f); break; } } int snippetMain(int, const char* const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for (PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char* const*) { return 0; } #endif
10,932
C++
34.381877
145
0.722558
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmultithreading/SnippetMultiThreading.cpp
// 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-2023 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 shows how to coordinate threads performing asynchronous // work during the scene simulation. After simulate() is called, user threads // are started that perform ray-casts against the scene. The call to // fetchResults() is delayed until all ray-casts have completed. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; struct RaycastThread { SnippetUtils::Sync* mWorkReadySyncHandle; SnippetUtils::Thread* mThreadHandle; }; const PxU32 gNumThreads = 1; RaycastThread gThreads[gNumThreads]; SnippetUtils::Sync* gWorkDoneSyncHandle; const PxI32 gRayCount = 1024; volatile PxI32 gRaysAvailable; volatile PxI32 gRaysCompleted; static PxVec3 randVec3() { return (PxVec3(float(rand())/float(RAND_MAX), float(rand())/float(RAND_MAX), float(rand())/float(RAND_MAX))*2.0f - PxVec3(1.0f)).getNormalized(); } static void threadExecute(void* data) { RaycastThread* raycastThread = static_cast<RaycastThread*>(data); // Perform random raycasts against the scene until stop. for(;;) { // Wait here for the sync to be set then reset the sync // to ensure that we only perform raycast work after the // sync has been set again. SnippetUtils::syncWait(raycastThread->mWorkReadySyncHandle); SnippetUtils::syncReset(raycastThread->mWorkReadySyncHandle); // If the thread has been signaled to quit then exit this function. if (SnippetUtils::threadQuitIsSignalled(raycastThread->mThreadHandle)) break; // Perform a fixed number of random raycasts against the scene // and share the work between multiple threads. while (SnippetUtils::atomicDecrement(&gRaysAvailable) >= 0) { PxVec3 dir = randVec3(); PxRaycastBuffer buf; gScene->raycast(PxVec3(0.0f), dir.getNormalized(), 1000.0f, buf, PxHitFlag::eDEFAULT); // If this is the last raycast then signal this to the main thread. if (SnippetUtils::atomicIncrement(&gRaysCompleted) == gRayCount) { SnippetUtils::syncSet(gWorkDoneSyncHandle); } } } // Quit the current thread. SnippetUtils::threadQuit(raycastThread->mThreadHandle); } void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void createPhysicsAndScene() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); for(PxU32 i=0;i<5;i++) createStack(PxTransform(PxVec3(0,0,i*10.0f)), 10, 2.0f); } void createRaycastThreads() { // Create and start threads that will perform raycasts. // Create a sync for each thread so that a signal may be sent // from the main thread to the raycast thread that it can start // performing raycasts. for (PxU32 i=0; i < gNumThreads; ++i) { //Create a sync. gThreads[i].mWorkReadySyncHandle = SnippetUtils::syncCreate(); //Create and start a thread. gThreads[i].mThreadHandle = SnippetUtils::threadCreate(threadExecute, &gThreads[i]); } // Create another sync so that the raycast threads can signal to the main // thread that they have finished performing their raycasts. gWorkDoneSyncHandle = SnippetUtils::syncCreate(); } void initPhysics() { createPhysicsAndScene(); createRaycastThreads(); } void stepPhysics() { // Start simulation gScene->simulate(1.0f/60.0f); // Start ray-cast threads gRaysAvailable = gRayCount; gRaysCompleted = 0; // Signal to each raycast thread that they can start performing raycasts. for (PxU32 i=0; i < gNumThreads; ++i) { SnippetUtils::syncSet(gThreads[i].mWorkReadySyncHandle); } // Wait for raycast threads to finish. SnippetUtils::syncWait(gWorkDoneSyncHandle); SnippetUtils::syncReset(gWorkDoneSyncHandle); // Fetch simulation results gScene->fetchResults(true); } void cleanupPhysics() { // Signal threads to quit. for (PxU32 i=0; i < gNumThreads; ++i) { SnippetUtils::threadSignalQuit(gThreads[i].mThreadHandle); SnippetUtils::syncSet(gThreads[i].mWorkReadySyncHandle); } // Clean up raycast threads and syncs. for (PxU32 i=0; i < gNumThreads; ++i) { SnippetUtils::threadWaitForQuit(gThreads[i].mThreadHandle); SnippetUtils::threadRelease(gThreads[i].mThreadHandle); SnippetUtils::syncRelease(gThreads[i].mWorkReadySyncHandle); } // Clean up the sync for the main thread. SnippetUtils::syncRelease(gWorkDoneSyncHandle); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetMultiThreading done.\n"); } int snippetMain(int, const char*const*) { initPhysics(); for(PxU32 i=0; i<100; ++i) stepPhysics(); cleanupPhysics(); return 0; }
8,278
C++
31.339844
103
0.729041
NVIDIA-Omniverse/PhysX/physx/snippets/snippetjoint/SnippetJoint.cpp
// 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-2023 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 simple use of joints in physx // // It creates a chain of objects joined by limited spherical joints, a chain // joined by fixed joints which is breakable, and a chain of damped D6 joints // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } // spherical joint limited to an angle of at most pi/4 radians (45 degrees) static PxJoint* createLimitedSpherical(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1) { PxSphericalJoint* j = PxSphericalJointCreate(*gPhysics, a0, t0, a1, t1); j->setLimitCone(PxJointLimitCone(PxPi/4, PxPi/4)); j->setSphericalJointFlag(PxSphericalJointFlag::eLIMIT_ENABLED, true); return j; } // fixed, breakable joint static PxJoint* createBreakableFixed(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1) { PxFixedJoint* j = PxFixedJointCreate(*gPhysics, a0, t0, a1, t1); j->setBreakForce(1000, 100000); j->setConstraintFlag(PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES, true); j->setConstraintFlag(PxConstraintFlag::eDISABLE_PREPROCESSING, true); return j; } // D6 joint with a spring maintaining its position static PxJoint* createDampedD6(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1) { PxD6Joint* j = PxD6JointCreate(*gPhysics, a0, t0, a1, t1); j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); j->setDrive(PxD6Drive::eSLERP, PxD6JointDrive(0, 1000, FLT_MAX, true)); return j; } typedef PxJoint* (*JointCreateFunction)(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1); // create a chain rooted at the origin and extending along the x-axis, all transformed by the argument t. static void createChain(const PxTransform& t, PxU32 length, const PxGeometry& g, PxReal separation, JointCreateFunction createJoint) { PxVec3 offset(separation/2, 0, 0); PxTransform localTm(offset); PxRigidDynamic* prev = NULL; for(PxU32 i=0;i<length;i++) { PxRigidDynamic* current = PxCreateDynamic(*gPhysics, t*localTm, g, *gMaterial, 1.0f); (*createJoint)(prev, prev ? PxTransform(offset) : t, current, PxTransform(-offset)); gScene->addActor(*current); prev = current; localTm.p.x += separation; } } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createChain(PxTransform(PxVec3(0.0f, 20.0f, 0.0f)), 5, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createLimitedSpherical); createChain(PxTransform(PxVec3(0.0f, 20.0f, -10.0f)), 5, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createBreakableFixed); createChain(PxTransform(PxVec3(0.0f, 20.0f, -20.0f)), 5, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createDampedD6); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetJoint done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0,0,-1))*200); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
7,443
C++
37.569948
132
0.738412
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbfmultimat/SnippetPBFMultiMat.cpp
// 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-2023 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 fluid simulation using multiple materials. It // creates a container and drops a body of water. The dynamics of the fluid // is computed using Position-based Fluid (PBF) which is a purely // particle-based algorithm. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "extensions/PxParticleExt.h" using namespace physx; using namespace ExtGpu; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxPBDParticleSystem* gParticleSystem = NULL; static PxParticleBuffer* gParticleBuffer = NULL; static bool gIsRunning = true; static void initScene() { PxCudaContextManager* cudaContextManager = NULL; if (PxGetSuggestedCudaDeviceOrdinal(gFoundation->getErrorCallback()) >= 0) { // initialize CUDA PxCudaContextManagerDesc cudaContextManagerDesc; cudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (cudaContextManager && !cudaContextManager->contextIsValid()) { cudaContextManager->release(); cudaContextManager = NULL; } } if (cudaContextManager == NULL) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Failed to initialize CUDA!\n"); } PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.cudaContextManager = cudaContextManager; sceneDesc.staticStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; gScene = gPhysics->createScene(sceneDesc); } static void initParticles(const PxU32 numX, const PxU32 numY, const PxU32 numZ, const PxVec3& position = PxVec3(0, 0, 0), const PxReal particleSpacing = 0.2f, const PxReal fluidDensity = 1000.f) { PxCudaContextManager* cudaContextManager = gScene->getCudaContextManager(); if (cudaContextManager == NULL) return; const PxU32 maxParticles = numX * numY * numZ; gParticleSystem = gPhysics->createPBDParticleSystem(*cudaContextManager, 96); // General particle system setting const PxReal restOffset = 0.5f * particleSpacing / 0.6f; const PxReal solidRestOffset = restOffset; const PxReal fluidRestOffset = restOffset * 0.6f; const PxReal particleMass = fluidDensity * 1.333f * 3.14159f * particleSpacing * particleSpacing * particleSpacing; gParticleSystem->setRestOffset(restOffset); gParticleSystem->setContactOffset(restOffset + 0.01f); gParticleSystem->setParticleContactOffset(PxMax(solidRestOffset + 0.01f, fluidRestOffset / 0.6f)); gParticleSystem->setSolidRestOffset(solidRestOffset); gParticleSystem->setFluidRestOffset(fluidRestOffset); gParticleSystem->enableCCD(false); gScene->addActor(*gParticleSystem); // Create particles and add them to the particle system PxU32* phase = cudaContextManager->allocPinnedHostBuffer<PxU32>(maxParticles); PxVec4* positionInvMass = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); PxVec4* velocity = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); // We are applying different material parameters for each section const PxU32 maxMaterials = 3; PxU32 phases[maxMaterials]; for (PxU32 i = 0; i < maxMaterials; ++i) { PxPBDMaterial* mat = gPhysics->createPBDMaterial(0.05f, i / (maxMaterials - 1.0f), 0.f, 10.002f* (i + 1), 0.5f, 0.005f * i, 0.01f, 0.f, 0.f); phases[i] = gParticleSystem->createPhase(mat, PxParticlePhaseFlags(PxParticlePhaseFlag::eParticlePhaseFluid | PxParticlePhaseFlag::eParticlePhaseSelfCollide)); } PxReal x = position.x; PxReal y = position.y; PxReal z = position.z; for (PxU32 i = 0; i < numX; ++i) { for (PxU32 j = 0; j < numY; ++j) { for (PxU32 k = 0; k < numZ; ++k) { const PxU32 index = i * (numY * numZ) + j * numZ + k; const PxU16 matIndex = (PxU16)(i * maxMaterials / numX); const PxVec4 pos(x, y, z, 1.0f / particleMass); phase[index] = phases[matIndex]; positionInvMass[index] = pos; velocity[index] = PxVec4(0.0f); z += particleSpacing; } z = position.z; y += particleSpacing; } y = position.y; x += particleSpacing; } ExtGpu::PxParticleBufferDesc bufferDesc; bufferDesc.maxParticles = maxParticles; bufferDesc.numActiveParticles = maxParticles; bufferDesc.positions = positionInvMass; bufferDesc.velocities = velocity; bufferDesc.phases = phase; gParticleBuffer = physx::ExtGpu::PxCreateAndPopulateParticleBuffer(bufferDesc, cudaContextManager); gParticleSystem->addParticleBuffer(gParticleBuffer); cudaContextManager->freePinnedHostBuffer(positionInvMass); cudaContextManager->freePinnedHostBuffer(velocity); cudaContextManager->freePinnedHostBuffer(phase); } PxParticleSystem* getParticleSystem() { return gParticleSystem; } PxParticleBuffer* getParticleBuffer() { return gParticleBuffer; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); initScene(); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Setup PBF const PxReal fluidDensity = 1000.0f; initParticles(60, 80, 30, PxVec3(-2.5f, 3.f, -2.5f), 0.1f, fluidDensity); // Setup container gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 1.f, 0.f, 0.f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(1.f, 0.f, 0.f, 6.f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(-1.f, 0.f, 0.f, 6.f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, 1.f, 6.f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, -1.f, 6.f), *gMaterial)); // Setup rigid bodies const PxReal dynamicsDensity = fluidDensity * 0.2f; const PxReal boxSize = 1.0f; const PxReal boxMass = boxSize * boxSize * boxSize * dynamicsDensity; PxShape* shape = gPhysics->createShape(PxBoxGeometry(0.5f * boxSize, 0.5f * boxSize, 0.5f * boxSize), *gMaterial); for (int i = 0; i < 5; ++i) { PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(i - 3.0f, 10, 1))); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, boxMass); gScene->addActor(*body); } shape->release(); } void stepPhysics(bool /*interactive*/) { if (gIsRunning) { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); gScene->fetchResultsParticleSystem(); } } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetPBFFluid done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { switch(toupper(key)) { case 'P': gIsRunning = !gIsRunning; break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
10,081
C++
35.528985
194
0.736832
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbfmultimat/SnippetPBFMultiMatRender.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "cudamanager/PxCudaContext.h" #include "cudamanager/PxCudaContextManager.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #define CUDA_SUCCESS 0 using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern PxParticleSystem* getParticleSystem(); extern PxParticleBuffer* getParticleBuffer(); namespace { Snippets::Camera* sCamera; PxArray<PxVec4>* sPosBufferH; PxArray<PxVec3>* sPosBuffer3H; PxArray<PxVec4>* sVelBufferH; PxArray<PxU32>* sPhasesH; PxArray<PxVec3>* sColorBuffer3H; void copyVec4ToVec3(PxArray<PxVec3>& vec3s, const PxArray<PxVec4>& vec4s) { for (PxU32 i = 0; i < vec4s.size(); ++i) vec3s[i] = vec4s[i].getXYZ(); } PxU32 getGroup(PxU32 phase) { return phase & PxParticlePhaseFlag::eParticlePhaseGroupMask; } void mapVec4ToColor3(PxArray<PxVec3>& colors, const PxArray<PxVec4>& vec4s, const PxArray<PxU32>& phases) { for (PxU32 i = 0; i < vec4s.size(); ++i) { float mag = vec4s[i].getXYZ().magnitude(); float c = PxMin(0.1f * mag, 1.0f); switch (getGroup(phases[i]) % 6) { case 0: colors[i] = PxVec3(1.0f, c, c); break; case 1: colors[i] = PxVec3(c, 1.0f, c); break; case 2: colors[i] = PxVec3(c, c, 1.0f); break; case 3: colors[i] = PxVec3(c, 1.0f, 1.0f); break; case 4: colors[i] = PxVec3(1.0f, c, 1.0f); break; case 5: colors[i] = PxVec3(1.0f, 1.0f, c); break; default: colors[i] = PxVec3(c, c, c); } } } void onBeforeRenderParticles() { PxParticleSystem* particleSystem = getParticleSystem(); if (particleSystem) { PxParticleBuffer* userBuffer = getParticleBuffer(); PxVec4* positions = userBuffer->getPositionInvMasses(); PxVec4* vels = userBuffer->getVelocities(); PxU32* phases = userBuffer->getPhases(); const PxU32 numParticles = userBuffer->getNbActiveParticles(); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxCudaContextManager* cudaContextManager = scene->getCudaContextManager(); cudaContextManager->acquireContext(); PxCudaContext* cudaContext = cudaContextManager->getCudaContext(); cudaContext->memcpyDtoH(sPosBufferH->begin(), CUdeviceptr(positions), sizeof(PxVec4) * numParticles); cudaContext->memcpyDtoH(sVelBufferH->begin(), CUdeviceptr(vels), sizeof(PxVec4) * numParticles); cudaContext->memcpyDtoH(sPhasesH->begin(), CUdeviceptr(phases), sizeof(PxU32) * numParticles); copyVec4ToVec3(*sPosBuffer3H, *sPosBufferH); mapVec4ToColor3(*sColorBuffer3H, *sVelBufferH, *sPhasesH); cudaContextManager->releaseContext(); } } void renderParticles() { Snippets::DrawPoints(*sPosBuffer3H, *sColorBuffer3H, 2.0f); } void allocParticleBuffers() { PxParticleSystem* particleSystem = getParticleSystem(); //const PxU32 maxParticles = particleSystem->getMaxParticles(); if (particleSystem) { PxParticleBuffer* userBuffer = getParticleBuffer(); const PxU32 maxParticles = userBuffer->getMaxParticles(); sPosBufferH = new PxArray<PxVec4>(maxParticles); sPosBuffer3H = new PxArray<PxVec3>(maxParticles); sVelBufferH = new PxArray<PxVec4>(maxParticles); sColorBuffer3H = new PxArray<PxVec3>(maxParticles); sPhasesH = new PxArray<PxU32>(maxParticles); } } void clearupParticleBuffers() { delete sPosBuffer3H; delete sPosBufferH; delete sVelBufferH; delete sColorBuffer3H; delete sPhasesH; } void renderCallback() { onBeforeRenderParticles(); stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } renderParticles(); Snippets::finishRender(); } void cleanup() { delete sCamera; clearupParticleBuffers(); cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(15.0f, 10.0f, 15.0f), PxVec3(-0.6f,-0.2f,-0.6f)); Snippets::setupDefault("PhysX Snippet PBFFluid", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); allocParticleBuffers(); glutMainLoop(); cleanup(); } #endif
6,276
C++
27.531818
136
0.739962
NVIDIA-Omniverse/PhysX/physx/snippets/snippetquerysystemcustomcompound/SnippetQuerySystemCustomCompound.cpp
// 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-2023 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 demonstrates how to re-implement a 'compound pruner' in // Gu::QuerySystem using PxCustomGeometry objects. // // Please get yourself familiar with SnippetQuerySystemAllQueries first. // // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "GuQuerySystem.h" #include "GuFactory.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; using namespace Gu; #ifdef RENDER_SNIPPET using namespace Snippets; #endif #define MAX_SHAPES_PER_COMPOUND 8 static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static const bool gManualBoundsComputation = false; static const bool gUseDelayedUpdates = true; static const float gBoundsInflation = 0.001f; static bool gPause = false; static bool gOneFrame = false; enum QueryScenario { RAYCAST_CLOSEST, RAYCAST_ANY, RAYCAST_MULTIPLE, SWEEP_CLOSEST, SWEEP_ANY, SWEEP_MULTIPLE, OVERLAP_ANY, OVERLAP_MULTIPLE, NB_SCENES }; static QueryScenario gSceneIndex = RAYCAST_CLOSEST; // Tweak number of created objects per scene static const PxU32 gFactor[NB_SCENES] = { 2, 1, 2, 2, 1, 2, 1, 2 }; // Tweak amplitude of created objects per scene static const float gAmplitude[NB_SCENES] = { 4.0f, 4.0f, 4.0f, 4.0f, 8.0f, 4.0f, 4.0f, 4.0f }; static const PxVec3 gCamPos[NB_SCENES] = { PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-3.404853f, 4.865191f, 17.692263f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), }; static const PxVec3 gCamDir[NB_SCENES] = { PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), }; #define MAX_NB_OBJECTS 32 static void fromLocalToGlobalSpace(PxLocationHit& hit, const PxTransform& pose) { hit.position = pose.transform(hit.position); hit.normal = pose.rotate(hit.normal); } /////////////////////////////////////////////////////////////////////////////// // The following functions determine how we use the pruner payloads in this snippet static PX_FORCE_INLINE void setupPayload(PrunerPayload& payload, PxU32 objectIndex, const PxGeometry* geom) { payload.data[0] = objectIndex; payload.data[1] = size_t(geom); } static PX_FORCE_INLINE PxU32 getObjectIndexFromPayload(const PrunerPayload& payload) { return PxU32(payload.data[0]); } static PX_FORCE_INLINE const PxGeometry& getGeometryFromPayload(const PrunerPayload& payload) { return *reinterpret_cast<const PxGeometry*>(payload.data[1]); } /////////////////////////////////////////////////////////////////////////////// static CachedFuncs gCachedFuncs; namespace { struct CustomRaycastHit : PxGeomRaycastHit { PxU32 mObjectIndex; }; struct CustomSweepHit : PxGeomSweepHit { PxU32 mObjectIndex; }; // We now derive CustomScene from PxCustomGeometry::Callbacks. class CustomScene : public Adapter, public PxCustomGeometry::Callbacks { public: CustomScene(); ~CustomScene() {} // Adapter virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const; //~Adapter void release(); void addCompound(const PxTransform& pose, bool isDynamic); void render(); void updateObjects(); void runQueries(); bool raycastClosest(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomRaycastHit& hit) const; bool raycastAny(const PxVec3& origin, const PxVec3& unitDir, float maxDist) const; bool raycastMultiple(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxArray<CustomRaycastHit>& hits) const; bool sweepClosest(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, CustomSweepHit& hit) const; bool sweepAny(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) const; bool sweepMultiple(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, PxArray<CustomSweepHit>& hits) const; bool overlapAny(const PxGeometry& geom, const PxTransform& pose) const; bool overlapMultiple(const PxGeometry& geom, const PxTransform& pose, PxArray<PxU32>& hits) const; // We derive our objects from PxCustomGeometry, to get easy access to the data in the PxCustomGeometry::Callbacks // functions. This generally wouldn't work in the regular PxScene / PhysX code since the geometries are copied around and the // system doesn't know about potential user-data surrounding the PxCustomGeometry objects. But the Gu::QuerySystem only // passes PxGeometry pointers around so it works here. // A more traditional usage of PxCustomGeometry would be to derive our Object from PxCustomGeometry::Callbacks (see e.g. // SnippetCustomConvex). Both approaches would work here. struct Object : public PxCustomGeometry { // Shape-related data // In this simple snippet we just keep all shapes in linear C-style arrays. A more efficient version could use a PxBVH here. PxBounds3 mCompoundLocalBounds; PxGeometryHolder mShapeGeoms[MAX_SHAPES_PER_COMPOUND]; PxTransform mLocalPoses[MAX_SHAPES_PER_COMPOUND]; PxU32 mNbShapes; // Compound/actor data. Note how mData is Gu::QuerySystem handle for the compound. We don't have // ActorShapeData values for each sub-shape, the Gu::QuerySystem doesn't know about these. ActorShapeData mData; PxVec3 mTouchedColor; bool mTouched; }; PxU32 mNbObjects; Object mObjects[MAX_NB_OBJECTS]; QuerySystem* mQuerySystem; PxU32 mPrunerIndex; DECLARE_CUSTOM_GEOMETRY_TYPE // PxCustomGeometry::Callbacks virtual PxBounds3 getLocalBounds(const PxGeometry& geom) const { // In this snippet we only fill the QuerySystem with our PxCustomGeometry-based objects. In a more complex app // we could have to test the type and cast to the appropriate type if needed. PX_ASSERT(geom.getType()==PxGeometryType::eCUSTOM); // Because our internal Objects are derived from custom geometries we have easy access to mCompoundLocalBounds: const Object& obj = static_cast<const Object&>(geom); return obj.mCompoundLocalBounds; } virtual bool generateContacts(const PxGeometry&, const PxGeometry&, const PxTransform&, const PxTransform&, const PxReal, const PxReal, const PxReal, PxContactBuffer&) const { // This is for contact generation, we don't use that here. return false; } virtual PxU32 raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& geom, const PxTransform& pose, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* rayHits, PxU32 stride, PxRaycastThreadContext* context) const { // There are many ways to implement this callback. This is just one example. // We retrieve our object, same as in "getLocalBounds" above. PX_ASSERT(geom.getType()==PxGeometryType::eCUSTOM); const Object& obj = static_cast<const Object&>(geom); // From the point-of-view of the QuerySystem a custom geometry is a single object, but from the point-of-view // of the user it can be anything, including a sub-scene (or as in this snippet, a compound). // The old API flags must be adapted to this new scenario, and we need to re-interpret what they all mean. // As discussed in SnippetQuerySystemAllQueries we don't use PxHitFlag::eMESH_MULTIPLE in the snippets, i.e. // from the point-of-view of the Gu::QuerySystem this raycast function against a unique (custom) geometry // should not return multiple hits. And indeed, "maxHits" is always 1 here. PX_UNUSED(stride); PX_UNUSED(maxHits); PX_ASSERT(maxHits==1); // The new flag PxHitFlag::eANY_HIT tells the system to report any hit from any geometry that contains more // than one primitive. This is equivalent to the old PxHitFlag::eMESH_ANY flag, but this is now also applicable // to PxCustomGeometry objects, not just triangle meshes. const bool anyHit = hitFlags & PxHitFlag::eANY_HIT; // We derive the object's index from the object's pointer. This is the counterpart of 'getObjectIndexFromPayload' // for regular geometries. We don't have a payload here since our sub-shapes are part of our compound // and hidden from the Gu::QuerySystem. Note that this is only used to highlight touched objects in the // render code, so this is all custom for this snippet and not mandatory in any way. const PxU32 objectIndex = PxU32(&obj - mObjects); // The ray is in world space, but the compound's shapes are in local space. We transform the ray from world space // to the compound's local space to do the raycast queries against these sub-shapes. const PxVec3 localOrigin = pose.transformInv(origin); const PxVec3 localDir = pose.q.rotateInv(unitDir); PxGeomRaycastHit localHit; PxGeomRaycastHit bestLocalHit; bestLocalHit.distance = maxDist; bool hasLocalHit = false; for(PxU32 i=0;i<obj.mNbShapes;i++) { // We need to replicate for our compound/sub-scene what was done in the calling code for a regular leaf node. // In particular that leaf code called 'validatePayload' (implemented later in the snippet) to retrieve the // geometry from a payload. We don't need to do that here since we have direct access to the geometries. // However we would still need to implement a preFilter function if needed, to replicate the second part of // 'validatePayload'. We aren't using a preFilter in this snippet though so this is missing here. const PxGeometry& currentGeom = obj.mShapeGeoms[i].any(); const PxTransform& currentPose = obj.mLocalPoses[i]; // We now raycast() against a sub-shape. Note how we only ask for one hit here, because eMESH_MULTIPLE was // not used in the snippet. We could call PxGeometryQuery::raycast here but it is more efficient to go through // the Gu-level function pointers directly, since it bypasses the PX_SIMD_GUARD entirely. We added one of these // when the query started (in CustomScene::runQueries()) so we can ignore them all in subsequent raycast calls. const RaycastFunc func = gCachedFuncs.mCachedRaycastFuncs[currentGeom.getType()]; const PxU32 nbHits = func(currentGeom, currentPose, localOrigin, localDir, bestLocalHit.distance, hitFlags, 1, &localHit, sizeof(PxGeomRaycastHit), context); if(nbHits && localHit.distance<bestLocalHit.distance) { // We detected a valid hit. To simplify the code we decided to reuse the 'reportHits' function from our // own pruner raycast callback, which are passed to us by the query system as the context parameter. These // are the callbacks passed to 'mQuerySystem->raycast' later in this snippet. Specifically they will be // either DefaultPrunerRaycastClosestCallback, DefaultPrunerRaycastAnyCallback, or our own // CustomRaycastMultipleCallback objects. All of them are DefaultPrunerRaycastCallback. PX_ASSERT(context); DefaultPrunerRaycastCallback* raycastCB = static_cast<DefaultPrunerRaycastCallback*>(context); // We moved the ray to the compound's local space so the hit is in this local compound space. We // need to transform the data back into world space. We cannot immediately tell in which raycast mode we are so // we do this conversion immediately. This is a bit less efficient than what we did in SnippetQuerySystemAllQueries, // where that conversion was delayed in the raycastClosest / raycastAny modes. We could be more efficient here // as well but it would make the code more complicated. fromLocalToGlobalSpace(localHit, pose); // We need a payload to call the 'reportHits' function so we create an artificial one here: PrunerPayload payload; setupPayload(payload, objectIndex, &currentGeom); // Reusing the reportHits function is mainly an easy way for us to report multiple hits from here. As // we mentioned above 'maxHits' is 1 and we cannot write out multiple hits to the 'rayHits' buffer, so // this is one alternative. In the 'multiple hits' codepath our own reportHits function will return false. // In that case we don't touch 'hasLocalHit' and we don't update 'bestLocalHit', so the code will use the same // (non shrunk) distance for next raycast calls in this loop, and we will return 0 from the query in // the end. The calling code doesn't need to know that we kept all the hits: we tell it that we // didn't find hits and it doesn't have to do any further processing. if(raycastCB->reportHits(payload, 1, &localHit)) { // This is the single-hit codepath. We still need to know if we're coming from 'raycastAny' or from // 'raycastClosest'. if(anyHit) { // In 'raycastAny' mode we just write out the current hit and early exit. *rayHits = localHit; return 1; } // Otherwise in 'raycastClosest' mode we update the best hit, which will shrink the current distance, // and go on. We delay writing out the best hit (we don't have it yet). bestLocalHit = localHit; hasLocalHit = true; } } } // Last part of 'raycastClosest' mode, process best hit. if(hasLocalHit) { // In SnippetQuerySystemAllQueries this is where we'd convert the best hit back to world-space. In this // snippet we already did that above, so we only need to write out the best hit. *rayHits = bestLocalHit; } return hasLocalHit ? 1 : 0; } virtual bool overlap(const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext* context) const { // Bits similar to what we covered in the raycast callback above are not commented anymore here. PX_ASSERT(geom0.getType()==PxGeometryType::eCUSTOM); const Object& obj = static_cast<const Object&>(geom0); const PxU32 objectIndex = PxU32(&obj - mObjects); // This is the geom we passed to the OVERLAP_ANY / OVERLAP_MULTIPLE codepaths later in this snippet, i.e. // this is our own query volume. const PxGeometry& queryGeom = geom1; // Similar to what we did for the ray in the raycast callback, we need to convert the world-space query volume to our // compound's local space. Note our we convert the whole PxTransform here, not just the position (contrary to what we // did for raycasts). const PxTransform queryLocalPose(pose0.transformInv(pose1)); for(PxU32 i=0;i<obj.mNbShapes;i++) { const PxGeometry& currentGeom = obj.mShapeGeoms[i].any(); const PxTransform& currentPose = obj.mLocalPoses[i]; if(Gu::overlap(queryGeom, queryLocalPose, currentGeom, currentPose, gCachedFuncs.mCachedOverlapFuncs, context)) { PrunerPayload payload; setupPayload(payload, objectIndex, &currentGeom); // We use the same approach as for the raycast callback above. This time the context will be // either CustomOverlapAnyCallback or CustomOverlapMultipleCallback. Either way they are // DefaultPrunerOverlapCallback objects. PX_ASSERT(context); DefaultPrunerOverlapCallback* overlapCB = static_cast<DefaultPrunerOverlapCallback*>(context); // The 'overlapAny' case will return false, in which case we don't need to go through the // remaining sub-shapes. if(!overlapCB->reportHit(payload)) return true; } } return false; } virtual bool sweep(const PxVec3& unitDir, const PxReal maxDist, const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxReal inflation, PxSweepThreadContext* context) const { // Sweeps are a combination of raycast (for the unitDir / maxDist parameters) and overlaps (for the // query-volume-related parameters). Bits already covered in the raycast and overlap callbacks above // will not be commented again here. PX_UNUSED(inflation); PX_ASSERT(geom0.getType()==PxGeometryType::eCUSTOM); const Object& obj = static_cast<const Object&>(geom0); const PxU32 objectIndex = PxU32(&obj - mObjects); const bool anyHit = hitFlags & PxHitFlag::eANY_HIT; // Bit subtle here: the internal system converts swept spheres to swept capsules (there is no internal // codepath for spheres to make the code smaller). So if we use a PxSphereGeometry in the SWEEP_CLOSEST // SWEEP_ANY / SWEEP_MULTIPLE codepaths later in this snippet, we actually receive it as a PxCapsuleGeometry // whose halfHeight = 0 here. This is not important in this snippet because we will use PxGeometryQuery::sweep // below, but it would be important if we'd decide to use the cached Gu-level functions (like we did for raycasts // and overlaps). const PxGeometry& queryGeom = geom1; // Convert both the query volume & ray to local space. const PxTransform queryLocalPose(pose0.transformInv(pose1)); const PxVec3 localDir = pose0.q.rotateInv(unitDir); PxGeomSweepHit localHit; PxGeomSweepHit bestLocalHit; bestLocalHit.distance = maxDist; bool hasLocalHit = false; for(PxU32 i=0;i<obj.mNbShapes;i++) { const PxGeometry& currentGeom = obj.mShapeGeoms[i].any(); const PxTransform& currentPose = obj.mLocalPoses[i]; // Bit subtle here: we don't want to replicate the whole PxGeometryQuery::sweep() function directly // here so contrary to what we previously did, we do not use the gCachedFuncs sweep pointers directly. // We can still pass PxGeometryQueryFlag::Enum(0) to the system to tell it we already took care of the // SIMD guards. This optimization is not as important for sweeps as it was for raycasts, because the // sweeps themselves are generally much more expensive than raycasts, so the relative cost of the SIMD // guard is not as high. const PxU32 retVal = PxGeometryQuery::sweep(localDir, bestLocalHit.distance, queryGeom, queryLocalPose, currentGeom, currentPose, localHit, hitFlags, 0.0f, PxGeometryQueryFlag::Enum(0), context); if(retVal && localHit.distance<bestLocalHit.distance) { fromLocalToGlobalSpace(localHit, pose0); PrunerPayload payload; setupPayload(payload, objectIndex, &currentGeom); // Same approach as before, this time involving our own sweep callbacks. PX_ASSERT(context); DefaultPrunerSweepCallback* sweepCB = static_cast<DefaultPrunerSweepCallback*>(context); if(sweepCB->reportHit(payload, localHit)) { if(anyHit) { sweepHit = localHit; return 1; } bestLocalHit = localHit; hasLocalHit = true; } } } if(hasLocalHit) { sweepHit = bestLocalHit; } return hasLocalHit ? 1 : 0; } virtual void visualize(const PxGeometry&, PxRenderOutput&, const PxTransform&, const PxBounds3&) const { } virtual void computeMassProperties(const PxGeometry&, PxMassProperties&) const { } virtual bool usePersistentContactManifold(const PxGeometry&, PxReal&) const { return false; } //~PxCustomGeometry::Callbacks }; IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CustomScene) const PxGeometry& CustomScene::getGeometry(const PrunerPayload& payload) const { PX_ASSERT(!gManualBoundsComputation); return getGeometryFromPayload(payload); } void CustomScene::release() { PX_DELETE(mQuerySystem); PX_DELETE_THIS; } CustomScene::CustomScene() : mNbObjects(0) { const PxU64 contextID = PxU64(this); mQuerySystem = PX_NEW(QuerySystem)(contextID, gBoundsInflation, *this); Pruner* pruner = createAABBPruner(contextID, true, COMPANION_PRUNER_INCREMENTAL, BVH_SPLATTER_POINTS, 4); mPrunerIndex = mQuerySystem->addPruner(pruner, 0); const PxU32 nb = gFactor[gSceneIndex]; for(PxU32 i=0;i<nb;i++) { addCompound(PxTransform(PxVec3(0.0f, 0.0f, 0.0f)), true); } #ifdef RENDER_SNIPPET Camera* camera = getCamera(); camera->setPose(gCamPos[gSceneIndex], gCamDir[gSceneIndex]); #endif } void CustomScene::addCompound(const PxTransform& pose, bool isDynamic) { PX_ASSERT(mQuerySystem); Object& obj = mObjects[mNbObjects]; obj.callbacks = this; PrunerPayload payload; setupPayload(payload, mNbObjects, static_cast<const PxCustomGeometry*>(&obj)); { const PxBoxGeometry boxGeom(PxVec3(1.0f, 2.0f, 0.5f)); const PxTransform boxGeomPose(PxVec3(0.0f, 0.0f, 0.0f)); const PxSphereGeometry sphereGeom(1.5f); const PxTransform sphereGeomPose(PxVec3(3.0f, 0.0f, 0.0f)); const PxCapsuleGeometry capsuleGeom(1.0f, 1.0f); const PxTransform capsuleGeomPose(PxVec3(-3.0f, 0.0f, 0.0f)); const PxConvexMeshGeometry convexGeom(gConvexMesh); const PxTransform convexGeomPose(PxVec3(0.0f, 0.0f, 3.0f)); const PxTriangleMeshGeometry meshGeom(gTriangleMesh); const PxTransform meshGeomPose(PxVec3(0.0f, 0.0f, -3.0f)); obj.mShapeGeoms[0].storeAny(boxGeom); obj.mShapeGeoms[1].storeAny(sphereGeom); obj.mShapeGeoms[2].storeAny(capsuleGeom); obj.mShapeGeoms[3].storeAny(convexGeom); obj.mShapeGeoms[4].storeAny(meshGeom); obj.mLocalPoses[0] = boxGeomPose; obj.mLocalPoses[1] = sphereGeomPose; obj.mLocalPoses[2] = capsuleGeomPose; obj.mLocalPoses[3] = convexGeomPose; obj.mLocalPoses[4] = meshGeomPose; obj.mNbShapes = 5; // Precompute local bounds for our compound PxBounds3 localCompoundBounds = PxBounds3::empty(); for(PxU32 i=0;i<obj.mNbShapes;i++) { PxBounds3 localShapeBounds; PxGeometryQuery::computeGeomBounds(localShapeBounds, obj.mShapeGeoms[i].any(), obj.mLocalPoses[i]); localCompoundBounds.include(localShapeBounds); } obj.mCompoundLocalBounds = localCompoundBounds; } if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, obj, pose, 0.0f, 1.0f + gBoundsInflation); obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, &bounds); } else { obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, NULL); } mNbObjects++; } void CustomScene::updateObjects() { if(!mQuerySystem) return; if(gPause && !gOneFrame) { mQuerySystem->update(true, true); return; } gOneFrame = false; static float time = 0.0f; time += 0.005f; const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; if(!getDynamic(getPrunerInfo(obj.mData))) continue; // const float coeff = float(i)/float(nbObjects); const float coeff = float(i); const float amplitude = gAmplitude[gSceneIndex]; // Compute an arbitrary new pose for this object PxTransform pose; { const float phase = PxPi * 2.0f * float(i)/float(nbObjects); pose.p.z = 0.0f; pose.p.y = sinf(phase+time*1.17f)*amplitude; pose.p.x = cosf(phase+time*1.17f)*amplitude; PxMat33 rotX; PxSetRotX(rotX, time+coeff); PxMat33 rotY; PxSetRotY(rotY, time*1.17f+coeff); PxMat33 rotZ; PxSetRotZ(rotZ, time*0.33f+coeff); PxMat33 rot = rotX * rotY * rotZ; pose.q = PxQuat(rot); pose.q.normalize(); } if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, obj, pose, 0.0f, 1.0f + gBoundsInflation); mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, &bounds); } else { mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, NULL); } } mQuerySystem->update(true, true); } namespace { struct CustomPrunerFilterCallback : public PrunerFilterCallback { virtual const PxGeometry* validatePayload(const PrunerPayload& payload, PxHitFlags& /*hitFlags*/) { return &getGeometryFromPayload(payload); } }; } static CustomPrunerFilterCallback gFilterCallback; /////////////////////////////////////////////////////////////////////////////// bool CustomScene::raycastClosest(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomRaycastHit& hit) const { DefaultPrunerRaycastClosestCallback CB(gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist, PxHitFlag::eDEFAULT); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); if(CB.mFoundHit) { static_cast<PxGeomRaycastHit&>(hit) = CB.mClosestHit; hit.mObjectIndex = getObjectIndexFromPayload(CB.mClosestPayload); } return CB.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// bool CustomScene::raycastAny(const PxVec3& origin, const PxVec3& unitDir, float maxDist) const { DefaultPrunerRaycastAnyCallback CB(gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); return CB.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomRaycastMultipleCallback : public DefaultPrunerRaycastCallback { PxGeomRaycastHit mLocalHit; PxArray<CustomRaycastHit>& mHits; CustomRaycastMultipleCallback(PxArray<CustomRaycastHit>& hits, PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance) : DefaultPrunerRaycastCallback(filterCB, funcs, origin, dir, distance, 1, &mLocalHit, PxHitFlag::eDEFAULT, false), mHits (hits) {} virtual bool reportHits(const PrunerPayload& payload, PxU32 nbHits, PxGeomRaycastHit* hits) { PX_ASSERT(nbHits==1); PX_UNUSED(nbHits); CustomRaycastHit customHit; static_cast<PxGeomRaycastHit&>(customHit) = hits[0]; customHit.mObjectIndex = getObjectIndexFromPayload(payload); mHits.pushBack(customHit); return false; } PX_NOCOPY(CustomRaycastMultipleCallback) }; } bool CustomScene::raycastMultiple(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxArray<CustomRaycastHit>& hits) const { CustomRaycastMultipleCallback CB(hits, gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); return hits.size()!=0; } /////////////////////////////////////////////////////////////////////////////// namespace { template<class CallbackT> static bool _sweepClosestT(CustomSweepHit& hit, const CustomScene& cs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CallbackT pcb(gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist, PxHitFlag::eDEFAULT | PxHitFlag::ePRECISE_SWEEP, false); cs.mQuerySystem->sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); if(pcb.mFoundHit) { static_cast<PxGeomSweepHit&>(hit) = pcb.mClosestHit; hit.mObjectIndex = getObjectIndexFromPayload(pcb.mClosestPayload); } return pcb.mFoundHit; } } bool CustomScene::sweepClosest(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, CustomSweepHit& hit) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepClosestT<DefaultPrunerSphereSweepCallback>(hit, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepClosestT<DefaultPrunerCapsuleSweepCallback>(hit, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepClosestT<DefaultPrunerBoxSweepCallback>(hit, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepClosestT<DefaultPrunerConvexSweepCallback>(hit, *this, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { template<class CallbackT> static bool _sweepAnyT(const CustomScene& cs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CallbackT pcb(gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist, PxHitFlag::eANY_HIT | PxHitFlag::ePRECISE_SWEEP, true); cs.mQuerySystem->sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); return pcb.mFoundHit; } } bool CustomScene::sweepAny(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepAnyT<DefaultPrunerSphereSweepCallback>(*this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepAnyT<DefaultPrunerCapsuleSweepCallback>(*this, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepAnyT<DefaultPrunerBoxSweepCallback>(*this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepAnyT<DefaultPrunerConvexSweepCallback>(*this, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { template<class BaseCallbackT> struct CustomSweepMultipleCallback : public BaseCallbackT { PxArray<CustomSweepHit>& mHits; CustomSweepMultipleCallback(PxArray<CustomSweepHit>& hits, PrunerFilterCallback& filterCB, const GeomSweepFuncs& funcs, const PxGeometry& geom, const PxTransform& pose, const ShapeData& queryVolume, const PxVec3& dir, float distance) : BaseCallbackT (filterCB, funcs, geom, pose, queryVolume, dir, distance, PxHitFlag::eDEFAULT|PxHitFlag::ePRECISE_SWEEP, false), mHits (hits) {} virtual bool reportHit(const PrunerPayload& payload, PxGeomSweepHit& hit) { CustomSweepHit customHit; static_cast<PxGeomSweepHit&>(customHit) = hit; customHit.mObjectIndex = getObjectIndexFromPayload(payload); mHits.pushBack(customHit); return false; } PX_NOCOPY(CustomSweepMultipleCallback) }; template<class CallbackT> static bool _sweepMultipleT(PxArray<CustomSweepHit>& hits, const CustomScene& cs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CustomSweepMultipleCallback<CallbackT> pcb(hits, gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist); cs.mQuerySystem->sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); return hits.size()!=0; } } bool CustomScene::sweepMultiple(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, PxArray<CustomSweepHit>& hits) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepMultipleT<DefaultPrunerSphereSweepCallback>(hits, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepMultipleT<DefaultPrunerCapsuleSweepCallback>(hits, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepMultipleT<DefaultPrunerBoxSweepCallback>(hits, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepMultipleT<DefaultPrunerConvexSweepCallback>(hits, *this, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomOverlapAnyCallback : public DefaultPrunerOverlapCallback { bool mFoundHit; CustomOverlapAnyCallback(PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose) : DefaultPrunerOverlapCallback(filterCB, funcs, geometry, pose), mFoundHit(false) {} virtual bool reportHit(const PrunerPayload& /*payload*/) { mFoundHit = true; return false; } }; } bool CustomScene::overlapAny(const PxGeometry& geom, const PxTransform& pose) const { CustomOverlapAnyCallback pcb(gFilterCallback, gCachedFuncs.mCachedOverlapFuncs, geom, pose); const ShapeData queryVolume(geom, pose, 0.0f); mQuerySystem->overlap(queryVolume, pcb, NULL); return pcb.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomOverlapMultipleCallback : public DefaultPrunerOverlapCallback { PxArray<PxU32>& mHits; CustomOverlapMultipleCallback(PxArray<PxU32>& hits, PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose) : DefaultPrunerOverlapCallback(filterCB, funcs, geometry, pose), mHits(hits) {} virtual bool reportHit(const PrunerPayload& payload) { mHits.pushBack(getObjectIndexFromPayload(payload)); return true; } PX_NOCOPY(CustomOverlapMultipleCallback) }; } bool CustomScene::overlapMultiple(const PxGeometry& geom, const PxTransform& pose, PxArray<PxU32>& hits) const { CustomOverlapMultipleCallback pcb(hits, gFilterCallback, gCachedFuncs.mCachedOverlapFuncs, geom, pose); const ShapeData queryVolume(geom, pose, 0.0f); mQuerySystem->overlap(queryVolume, pcb, NULL); return hits.size()!=0; } /////////////////////////////////////////////////////////////////////////////// void CustomScene::runQueries() { if(!mQuerySystem) return; const PxVec3 touchedColor(0.25f, 0.5f, 1.0f); for(PxU32 i=0;i<mNbObjects;i++) { mObjects[i].mTouched = false; mObjects[i].mTouchedColor = touchedColor; } PX_SIMD_GUARD if(0) mQuerySystem->commitUpdates(); switch(gSceneIndex) { case RAYCAST_CLOSEST: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; CustomRaycastHit hit; const bool hasHit = raycastClosest(origin, unitDir, maxDist, hit); #ifdef RENDER_SNIPPET if(hasHit) { DrawLine(origin, hit.position, PxVec3(1.0f)); DrawLine(hit.position, hit.position + hit.normal, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 0.5f); mObjects[hit.mObjectIndex].mTouched = true; } else { DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case RAYCAST_ANY: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const bool hasHit = raycastAny(origin, unitDir, maxDist); #ifdef RENDER_SNIPPET if(hasHit) DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f, 0.0f, 0.0f)); else DrawLine(origin, origin + unitDir * maxDist, PxVec3(0.0f, 1.0f, 0.0f)); #else PX_UNUSED(hasHit); #endif } break; case RAYCAST_MULTIPLE: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; PxArray<CustomRaycastHit> hits; const bool hasHit = raycastMultiple(origin, unitDir, maxDist, hits); #ifdef RENDER_SNIPPET if(hasHit) { DrawLine(origin, origin + unitDir * maxDist, PxVec3(0.5f)); const PxU32 nbHits = hits.size(); for(PxU32 i=0;i<nbHits;i++) { const CustomRaycastHit& hit = hits[i]; DrawLine(hit.position, hit.position + hit.normal, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 0.5f); mObjects[hit.mObjectIndex].mTouched = true; } } else { DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_CLOSEST: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; //const PxSphereGeometry sweptGeom(0.5f); const PxCapsuleGeometry sweptGeom(0.5f, 0.5f); const PxTransform pose(origin); CustomSweepHit hit; const bool hasHit = sweepClosest(sweptGeom, pose, unitDir, maxDist, hit); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); if(hasHit) { const PxVec3 sweptPos = origin + unitDir * hit.distance; DrawLine(origin, sweptPos, PxVec3(1.0f)); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, PxVec3(1.0f, 0.0f, 0.0f)); DrawLine(hit.position, hit.position + hit.normal*2.0f, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 2.0f); mObjects[hit.mObjectIndex].mTouched = true; } else { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(1.0f)); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, PxVec3(0.0f, 1.0f, 0.0f)); } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_ANY: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const PxBoxGeometry sweptGeom(PxVec3(0.5f)); //const PxSphereGeometry sweptGeom(0.5f); PxQuat q(1.1f, 0.1f, 0.8f, 1.4f); q.normalize(); const PxTransform pose(origin, q); const bool hasHit = sweepAny(sweptGeom, pose, unitDir, maxDist); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); const PxU32 nb = 20; for(PxU32 i=0;i<nb;i++) { const float coeff = float(i)/float(nb-1); const PxVec3 sweptPos = origin + unitDir * coeff * maxDist; const PxTransform impactPose(sweptPos, q); renderGeoms(1, &gh, &impactPose, false, color); } } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_MULTIPLE: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; // const PxCapsuleGeometry sweptGeom(0.5f, 0.5f); const PxSphereGeometry sweptGeom(0.5f); const PxTransform pose(origin); PxArray<CustomSweepHit> hits; const bool hasHit = sweepMultiple(sweptGeom, pose, unitDir, maxDist, hits); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); if(hasHit) { { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(0.5f)); } const PxVec3 touchedColors[] = { PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f), PxVec3(1.0f, 0.0f, 1.0f), PxVec3(0.0f, 1.0f, 1.0f), PxVec3(1.0f, 1.0f, 0.0f), PxVec3(1.0f, 1.0f, 1.0f), PxVec3(0.5f, 0.5f, 0.5f), }; const PxU32 nbHits = hits.size(); for(PxU32 i=0;i<nbHits;i++) { const PxVec3& shapeTouchedColor = touchedColors[i]; const CustomSweepHit& hit = hits[i]; const PxVec3 sweptPos = origin + unitDir * hit.distance; const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, shapeTouchedColor); DrawLine(hit.position, hit.position + hit.normal*2.0f, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 2.0f); mObjects[hit.mObjectIndex].mTouched = true; mObjects[hit.mObjectIndex].mTouchedColor = shapeTouchedColor; } } else { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case OVERLAP_ANY: { const PxVec3 origin(0.0f, 4.0f, 0.0f); //const PxSphereGeometry queryGeom(0.5f); //const PxCapsuleGeometry queryGeom(0.5f, 0.5f); const PxBoxGeometry queryGeom(1.0f, 0.25f, 0.5f); const PxTransform pose(origin); const bool hasHit = overlapAny(queryGeom, pose); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(queryGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); renderGeoms(1, &gh, &pose, false, color); } #else PX_UNUSED(hasHit); #endif } break; case OVERLAP_MULTIPLE: { const PxVec3 origin(0.0f, 4.0f, 0.0f); // const PxSphereGeometry queryGeom(0.5f); const PxCapsuleGeometry queryGeom(0.5f, 0.5f); const PxTransform pose(origin); PxArray<PxU32> hits; const bool hasHit = overlapMultiple(queryGeom, pose, hits); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(queryGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); renderGeoms(1, &gh, &pose, false, color); for(PxU32 i=0;i<hits.size();i++) mObjects[hits[i]].mTouched = true; } #else PX_UNUSED(hasHit); #endif } break; case NB_SCENES: // Blame pedantic compilers { } break; } } void CustomScene::render() { updateObjects(); runQueries(); #ifdef RENDER_SNIPPET const PxVec3 color(1.0f, 0.5f, 0.25f); const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; PrunerPayloadData ppd; mQuerySystem->getPayloadData(obj.mData, &ppd); //DrawBounds(*ppd.mBounds); const PxVec3& objectColor = obj.mTouched ? obj.mTouchedColor : color; // renderGeoms doesn't support PxCustomGeometry so we deal with this here: PxTransform shapeGlobalPoses[MAX_SHAPES_PER_COMPOUND]; for(PxU32 j=0;j<obj.mNbShapes;j++) { // This is basically PxShapeExt::getGlobalPose with the actor's global pose == *ppd.mTransform shapeGlobalPoses[j] = (*ppd.mTransform) * obj.mLocalPoses[j]; } renderGeoms(obj.mNbShapes, obj.mShapeGeoms, shapeGlobalPoses, false, objectColor); } //mQuerySystem->visualize(true, true, PxRenderOutput) #endif } } static CustomScene* gScene = NULL; void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; { { const PxF32 width = 3.0f; const PxF32 radius = 1.0f; PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } PxConvexMeshDesc convexDesc; convexDesc.points.count = 32; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = points; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; gConvexMesh = PxCreateConvexMesh(params, convexDesc); } { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } } gScene = new CustomScene; } void renderScene() { if(gScene) gScene->render(); #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F8 to select a scenario."); switch(PxU32(gSceneIndex)) { case RAYCAST_CLOSEST: { Snippets::print("Current scenario: raycast closest"); }break; case RAYCAST_ANY: { Snippets::print("Current scenario: raycast any"); }break; case RAYCAST_MULTIPLE: { Snippets::print("Current scenario: raycast multiple"); }break; case SWEEP_CLOSEST: { Snippets::print("Current scenario: sweep closest"); }break; case SWEEP_ANY: { Snippets::print("Current scenario: sweep any"); }break; case SWEEP_MULTIPLE: { Snippets::print("Current scenario: sweep multiple"); }break; case OVERLAP_ANY: { Snippets::print("Current scenario: overlap any"); }break; case OVERLAP_MULTIPLE: { Snippets::print("Current scenario: overlap multiple"); }break; } #endif } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetQuerySystemCustomCompound done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(gScene) { if(key=='p' || key=='P') { gPause = !gPause; } else if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } else { if(key>=1 && key<=NB_SCENES) { gSceneIndex = QueryScenario(key-1); PX_RELEASE(gScene); gScene = new CustomScene; } } } } int snippetMain(int, const char*const*) { printf("Query System Custom Compound snippet.\n"); printf("Press F1 to F8 to select a scene:\n"); printf(" F1......raycast closest\n"); printf(" F2..........raycast any\n"); printf(" F3.....raycast multiple\n"); printf(" F4........sweep closest\n"); printf(" F5............sweep any\n"); printf(" F6.......sweep multiple\n"); printf(" F7..........overlap any\n"); printf(" F8.....overlap multiple\n"); printf("\n"); printf("Press P to Pause.\n"); printf("Press O to step the simulation One frame.\n"); printf("Press the cursor keys to move the camera.\n"); printf("Use the mouse/left mouse button to rotate the camera.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
47,950
C++
33.822803
200
0.702086
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/SnippetVehicleHelpers.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include <ctype.h> #include "../snippetvehicle2common/SnippetVehicleHelpers.h" using namespace physx; namespace snippetvehicle2 { PxFilterFlags VehicleFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(filterData0); PX_UNUSED(attributes1); PX_UNUSED(filterData1); PX_UNUSED(pairFlags); PX_UNUSED(constantBlock); PX_UNUSED(constantBlockSize); return PxFilterFlag::eSUPPRESS; } bool parseVehicleDataPath(int argc, const char *const* argv, const char* snippetName, const char*& vehicleDataPath) { if (argc != 2 || 0 != strncmp(argv[1], "--vehicleDataPath", strlen("--vehicleDataPath"))) { printf("%s usage:\n" "%s " "--vehicleDataPath=<path to the [PHYSX_ROOT]/snippets/media/vehicledata folder containing the vehiclejson files to be loaded> \n", snippetName, snippetName); return false; } vehicleDataPath = argv[1] + strlen("--vehicleDataPath="); return true; } }//namespace snippetvehicle2
2,827
C++
37.739726
133
0.763707
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/base/Base.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "Base.h" namespace snippetvehicle2 { BaseVehicleParams BaseVehicleParams::transformAndScale (const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const { BaseVehicleParams r = *this; r.axleDescription = axleDescription; r.frame = trgFrame; r.scale = trgScale; r.suspensionStateCalculationParams = suspensionStateCalculationParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.brakeResponseParams[0] = brakeResponseParams[0].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.brakeResponseParams[1] = brakeResponseParams[1].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.steerResponseParams = steerResponseParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.ackermannParams[0] = ackermannParams[0].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); for (PxU32 i = 0; i < r.axleDescription.nbWheels; i++) { const PxU32 wheelId = r.axleDescription.wheelIdsInAxleOrder[i]; r.suspensionParams[wheelId] = suspensionParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.suspensionComplianceParams[wheelId] = suspensionComplianceParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.suspensionForceParams[wheelId] = suspensionForceParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.tireForceParams[wheelId] = tireForceParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.wheelParams[wheelId] = wheelParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); } r.rigidBodyParams = rigidBodyParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); return r; } bool BaseVehicle::initialize() { if (!mBaseParams.isValid()) return false; //Set the base state to default. mBaseState.setToDefault(); return true; } void BaseVehicle::step(const PxReal dt, const PxVehicleSimulationContext& context) { mComponentSequence.update(dt, context); } }//namespace snippetvehicle2
3,771
C++
43.37647
136
0.784673
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/base/Base.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct BaseVehicleParams { PxVehicleAxleDescription axleDescription; PxVehicleFrame frame; PxVehicleScale scale; PxVehicleSuspensionStateCalculationParams suspensionStateCalculationParams; //Command response PxVehicleBrakeCommandResponseParams brakeResponseParams[2]; PxVehicleSteerCommandResponseParams steerResponseParams; PxVehicleAckermannParams ackermannParams[1]; //Suspension PxVehicleSuspensionParams suspensionParams[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleSuspensionComplianceParams suspensionComplianceParams[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleSuspensionForceParams suspensionForceParams[PxVehicleLimits::eMAX_NB_WHEELS]; //Tires PxVehicleTireForceParams tireForceParams[PxVehicleLimits::eMAX_NB_WHEELS]; //Wheels PxVehicleWheelParams wheelParams[PxVehicleLimits::eMAX_NB_WHEELS]; //Rigid body PxVehicleRigidBodyParams rigidBodyParams; BaseVehicleParams transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const; PX_FORCE_INLINE bool isValid() const { if (!axleDescription.isValid()) return false; if (!frame.isValid()) return true; if (!scale.isValid()) return false; if (!suspensionStateCalculationParams.isValid()) return false; if (!brakeResponseParams[0].isValid(axleDescription)) return false; if (!brakeResponseParams[1].isValid(axleDescription)) return false; if (!steerResponseParams.isValid(axleDescription)) return false; if (!ackermannParams[0].isValid(axleDescription)) return false; for (PxU32 i = 0; i < axleDescription.nbWheels; i++) { const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i]; if (!suspensionParams[wheelId].isValid()) return false; if (!suspensionComplianceParams[wheelId].isValid()) return false; if (!suspensionForceParams[wheelId].isValid()) return false; if (!tireForceParams[wheelId].isValid()) return false; if (!wheelParams[wheelId].isValid()) return false; } if (!rigidBodyParams.isValid()) return false; return true; } }; struct BaseVehicleState { //Command responses PxReal brakeCommandResponseStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxReal steerCommandResponseStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleWheelActuationState actuationStates[PxVehicleLimits::eMAX_NB_WHEELS]; //Road geometry PxVehicleRoadGeometryState roadGeomStates[PxVehicleLimits::eMAX_NB_WHEELS]; //Suspensions PxVehicleSuspensionState suspensionStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleSuspensionComplianceState suspensionComplianceStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleSuspensionForce suspensionForces[PxVehicleLimits::eMAX_NB_WHEELS]; //Tires PxVehicleTireGripState tireGripStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireDirectionState tireDirectionStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireSpeedState tireSpeedStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireSlipState tireSlipStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireCamberAngleState tireCamberAngleStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireStickyState tireStickyStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireForce tireForces[PxVehicleLimits::eMAX_NB_WHEELS]; //Wheels PxVehicleWheelRigidBody1dState wheelRigidBody1dStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleWheelLocalPose wheelLocalPoses[PxVehicleLimits::eMAX_NB_WHEELS]; //Rigid body PxVehicleRigidBodyState rigidBodyState; PX_FORCE_INLINE void setToDefault() { for (unsigned int i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++) { brakeCommandResponseStates[i] = 0.0; steerCommandResponseStates[i] = 0.0f; actuationStates[i].setToDefault(); roadGeomStates[i].setToDefault(); suspensionStates[i].setToDefault(); suspensionComplianceStates[i].setToDefault(); suspensionForces[i].setToDefault(); tireGripStates[i].setToDefault(); tireDirectionStates[i].setToDefault(); tireSpeedStates[i].setToDefault(); tireSlipStates[i].setToDefault(); tireCamberAngleStates[i].setToDefault(); tireStickyStates[i].setToDefault(); tireForces[i].setToDefault(); wheelRigidBody1dStates[i].setToDefault(); wheelLocalPoses[i].setToDefault(); } rigidBodyState.setToDefault(); } }; // //The PhysX Vehicle SDK was designed to offer flexibility on how to combine data and logic //to implement a vehicle. For the purpose of the snippets, different vehicle types are //represented using a class hierarchy to share base functionality and data. The vehicle //classes implement the component interfaces directly such that no separate component //objects are needed. If the goal was to focus more on modularity, each component //could be defined as its own class but those classes would need to reference all the //data necessary to run the component logic. //This specific class deals with the mechanical base of a vehicle (suspension, tire, //wheel, vehicle body etc.). // class BaseVehicle : public PxVehicleRigidBodyComponent , public PxVehicleSuspensionComponent , public PxVehicleTireComponent , public PxVehicleWheelComponent { public: bool initialize(); virtual void destroy() {} //To be implemented by specific vehicle types that are built on top of this class. //The specific vehicle type defines what components to run and in what order. virtual void initComponentSequence(bool addPhysXBeginEndComponents) = 0; //Run a simulation step void step(const PxReal dt, const PxVehicleSimulationContext& context); virtual void getDataForRigidBodyComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyParams*& rigidBodyParams, PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces, PxVehicleArrayData<const PxVehicleTireForce>& tireForces, const PxVehicleAntiRollTorque*& antiRollTorque, PxVehicleRigidBodyState*& rigidBodyState) { axleDescription = &mBaseParams.axleDescription; rigidBodyParams = &mBaseParams.rigidBodyParams; suspensionForces.setData(mBaseState.suspensionForces); tireForces.setData(mBaseState.tireForces); antiRollTorque = NULL; rigidBodyState = &mBaseState.rigidBodyState; } virtual void getDataForSuspensionComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyParams*& rigidBodyParams, const PxVehicleSuspensionStateCalculationParams*& suspensionStateCalculationParams, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspensionComplianceParams, PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspensionForceParams, PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams, PxVehicleArrayData<const PxVehicleRoadGeometryState>& wheelRoadGeomStates, PxVehicleArrayData<PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<PxVehicleSuspensionForce>& suspensionForces, PxVehicleAntiRollTorque*& antiRollTorque) { axleDescription = &mBaseParams.axleDescription; rigidBodyParams = &mBaseParams.rigidBodyParams; suspensionStateCalculationParams = &mBaseParams.suspensionStateCalculationParams; steerResponseStates.setData(mBaseState.steerCommandResponseStates); rigidBodyState = &mBaseState.rigidBodyState; wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); suspensionComplianceParams.setData(mBaseParams.suspensionComplianceParams); suspensionForceParams.setData(mBaseParams.suspensionForceParams); antiRollForceParams.setEmpty(); wheelRoadGeomStates.setData(mBaseState.roadGeomStates); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); suspensionForces.setData(mBaseState.suspensionForces); antiRollTorque = NULL; } virtual void getDataForTireComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams, PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeomStates, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1DStates, PxVehicleArrayData<PxVehicleTireGripState>& tireGripStates, PxVehicleArrayData<PxVehicleTireDirectionState>& tireDirectionStates, PxVehicleArrayData<PxVehicleTireSpeedState>& tireSpeedStates, PxVehicleArrayData<PxVehicleTireSlipState>& tireSlipStates, PxVehicleArrayData<PxVehicleTireCamberAngleState>& tireCamberAngleStates, PxVehicleArrayData<PxVehicleTireStickyState>& tireStickyStates, PxVehicleArrayData<PxVehicleTireForce>& tireForces) { axleDescription = &mBaseParams.axleDescription; steerResponseStates.setData(mBaseState.steerCommandResponseStates); rigidBodyState = &mBaseState.rigidBodyState; actuationStates.setData(mBaseState.actuationStates); wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); tireForceParams.setData(mBaseParams.tireForceParams); roadGeomStates.setData(mBaseState.roadGeomStates); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); suspensionForces.setData(mBaseState.suspensionForces); wheelRigidBody1DStates.setData(mBaseState.wheelRigidBody1dStates); tireGripStates.setData(mBaseState.tireGripStates); tireDirectionStates.setData(mBaseState.tireDirectionStates); tireSpeedStates.setData(mBaseState.tireSpeedStates); tireSlipStates.setData(mBaseState.tireSlipStates); tireCamberAngleStates.setData(mBaseState.tireCamberAngleStates); tireStickyStates.setData(mBaseState.tireStickyStates); tireForces.setData(mBaseState.tireForces); } virtual void getDataForWheelComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& steerResponseStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleArrayData<PxVehicleWheelLocalPose>& wheelLocalPoses) { axleDescription = &mBaseParams.axleDescription; steerResponseStates.setData(mBaseState.steerCommandResponseStates); wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); actuationStates.setData(mBaseState.actuationStates); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); tireSpeedStates.setData(mBaseState.tireSpeedStates); wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); wheelLocalPoses.setData(mBaseState.wheelLocalPoses); } //Parameters and statess of the vehicle's mechanical base. BaseVehicleParams mBaseParams; BaseVehicleState mBaseState; //The sequence of components that will simulate the vehicle. //To be assembled by specific vehicle types that are built //on top of this class PxVehicleComponentSequence mComponentSequence; //A sub-group of components can be simulated with multiple substeps //to improve simulation fidelity without running the full sequence //at a lower timestep. PxU8 mComponentSequenceSubstepGroupHandle; }; }//namespace snippetvehicle2
14,320
C
41.495549
136
0.820321
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/enginedrivetrain/EngineDrivetrain.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../physxintegration/PhysXIntegration.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct EngineDrivetrainParams { PxVehicleAutoboxParams autoboxParams; PxVehicleClutchCommandResponseParams clutchCommandResponseParams; PxVehicleEngineParams engineParams; PxVehicleGearboxParams gearBoxParams; PxVehicleMultiWheelDriveDifferentialParams multiWheelDifferentialParams; PxVehicleFourWheelDriveDifferentialParams fourWheelDifferentialParams; PxVehicleTankDriveDifferentialParams tankDifferentialParams; PxVehicleClutchParams clutchParams; EngineDrivetrainParams transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const; PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const { if (!autoboxParams.isValid(gearBoxParams)) return false; if (!clutchCommandResponseParams.isValid()) return false; if (!engineParams.isValid()) return false; if (!gearBoxParams.isValid()) return false; if (!multiWheelDifferentialParams.isValid(axleDesc)) return false; if (!fourWheelDifferentialParams.isValid(axleDesc)) return false; if (!tankDifferentialParams.isValid(axleDesc)) return false; if (!clutchParams.isValid()) return false; return true; } }; struct EngineDrivetrainState { PxVehicleEngineDriveThrottleCommandResponseState throttleCommandResponseState; PxVehicleAutoboxState autoboxState; PxVehicleClutchCommandResponseState clutchCommandResponseState; PxVehicleDifferentialState differentialState; PxVehicleWheelConstraintGroupState wheelConstraintGroupState; PxVehicleEngineState engineState; PxVehicleGearboxState gearboxState; PxVehicleClutchSlipState clutchState; PX_FORCE_INLINE void setToDefault() { throttleCommandResponseState.setToDefault(); autoboxState.setToDefault(); clutchCommandResponseState.setToDefault(); differentialState.setToDefault(); wheelConstraintGroupState.setToDefault(); engineState.setToDefault(); gearboxState.setToDefault(); clutchState.setToDefault(); } }; // //This class holds the parameters, state and logic needed to implement a vehicle that //is using an engine drivetrain with gears, clutch etc. // //See BaseVehicle for more details on the snippet code design. // class EngineDriveVehicle : public PhysXActorVehicle , public PxVehicleEngineDriveCommandResponseComponent , public PxVehicleFourWheelDriveDifferentialStateComponent , public PxVehicleMultiWheelDriveDifferentialStateComponent , public PxVehicleTankDriveDifferentialStateComponent , public PxVehicleEngineDriveActuationStateComponent , public PxVehicleEngineDrivetrainComponent { public: enum Enum { eDIFFTYPE_FOURWHEELDRIVE, eDIFFTYPE_MULTIWHEELDRIVE, eDIFFTYPE_TANKDRIVE }; bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, Enum differentialType, bool addPhysXBeginEndComponents=true); virtual void destroy(); virtual void initComponentSequence(bool addPhysXBeginEndComponents); virtual void getDataForPhysXActorBeginComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleCommandState*& commands, const PxVehicleEngineDriveTransmissionCommandState*& transmissionCommands, const PxVehicleGearboxParams*& gearParams, const PxVehicleGearboxState*& gearState, const PxVehicleEngineParams*& engineParams, PxVehiclePhysXActor*& physxActor, PxVehiclePhysXSteerState*& physxSteerState, PxVehiclePhysXConstraints*& physxConstraints, PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleEngineState*& engineState) { axleDescription = &mBaseParams.axleDescription; commands = &mCommandState; physxActor = &mPhysXState.physxActor; physxSteerState = &mPhysXState.physxSteerState; physxConstraints = &mPhysXState.physxConstraints; rigidBodyState = &mBaseState.rigidBodyState; wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); transmissionCommands = &mTransmissionCommandState; gearParams = &mEngineDriveParams.gearBoxParams; gearState = &mEngineDriveState.gearboxState; engineParams = &mEngineDriveParams.engineParams; engineState = &mEngineDriveState.engineState; } virtual void getDataForPhysXActorEndComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxTransform>& wheelShapeLocalPoses, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses, const PxVehicleGearboxState*& gearState, const PxReal*& throttle, PxVehiclePhysXActor*& physxActor) { axleDescription = &mBaseParams.axleDescription; rigidBodyState = &mBaseState.rigidBodyState; wheelParams.setData(mBaseParams.wheelParams); wheelShapeLocalPoses.setData(mPhysXParams.physxWheelShapeLocalPoses); wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); wheelLocalPoses.setData(mBaseState.wheelLocalPoses); physxActor = &mPhysXState.physxActor; gearState = &mEngineDriveState.gearboxState; throttle = &mCommandState.throttle; } virtual void getDataForEngineDriveCommandResponseComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams, const PxVehicleSteerCommandResponseParams*& steerResponseParams, PxVehicleSizedArrayData<const PxVehicleAckermannParams>& ackermannParams, const PxVehicleGearboxParams*& gearboxParams, const PxVehicleClutchCommandResponseParams*& clutchResponseParams, const PxVehicleEngineParams*& engineParams, const PxVehicleRigidBodyState*& rigidBodyState, const PxVehicleEngineState*& engineState, const PxVehicleAutoboxParams*& autoboxParams, const PxVehicleCommandState*& commands, const PxVehicleEngineDriveTransmissionCommandState*& transmissionCommands, PxVehicleArrayData<PxReal>& brakeResponseStates, PxVehicleEngineDriveThrottleCommandResponseState*& throttleResponseState, PxVehicleArrayData<PxReal>& steerResponseStates, PxVehicleGearboxState*& gearboxResponseState, PxVehicleClutchCommandResponseState*& clutchResponseState, PxVehicleAutoboxState*& autoboxState) { axleDescription = &mBaseParams.axleDescription; brakeResponseParams.setDataAndCount(mBaseParams.brakeResponseParams, sizeof(mBaseParams.brakeResponseParams) / sizeof(PxVehicleBrakeCommandResponseParams)); steerResponseParams = &mBaseParams.steerResponseParams; ackermannParams.setDataAndCount(mBaseParams.ackermannParams, sizeof(mBaseParams.ackermannParams)/sizeof(PxVehicleAckermannParams)); gearboxParams = &mEngineDriveParams.gearBoxParams; clutchResponseParams = &mEngineDriveParams.clutchCommandResponseParams; engineParams = &mEngineDriveParams.engineParams; rigidBodyState = &mBaseState.rigidBodyState; engineState = &mEngineDriveState.engineState; autoboxParams = &mEngineDriveParams.autoboxParams; commands = &mCommandState; transmissionCommands = (Enum::eDIFFTYPE_TANKDRIVE == mDifferentialType) ? &mTankDriveTransmissionCommandState : &mTransmissionCommandState; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseState = &mEngineDriveState.throttleCommandResponseState; steerResponseStates.setData(mBaseState.steerCommandResponseStates); gearboxResponseState = &mEngineDriveState.gearboxState; clutchResponseState = &mEngineDriveState.clutchCommandResponseState; autoboxState = &mEngineDriveState.autoboxState; } virtual void getDataForFourWheelDriveDifferentialStateComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleFourWheelDriveDifferentialParams*& differentialParams, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidbody1dStates, PxVehicleDifferentialState*& differentialState, PxVehicleWheelConstraintGroupState*& wheelConstraintGroups) { axleDescription = &mBaseParams.axleDescription; differentialParams = &mEngineDriveParams.fourWheelDifferentialParams; wheelRigidbody1dStates.setData(mBaseState.wheelRigidBody1dStates); differentialState = &mEngineDriveState.differentialState; wheelConstraintGroups = &mEngineDriveState.wheelConstraintGroupState; } virtual void getDataForMultiWheelDriveDifferentialStateComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleMultiWheelDriveDifferentialParams*& differentialParams, PxVehicleDifferentialState*& differentialState) { axleDescription = &mBaseParams.axleDescription; differentialParams = &mEngineDriveParams.multiWheelDifferentialParams; differentialState = &mEngineDriveState.differentialState; } virtual void getDataForTankDriveDifferentialStateComponent( const PxVehicleAxleDescription *&axleDescription, const PxVehicleTankDriveTransmissionCommandState*& tankDriveTransmissionCommands, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, const PxVehicleTankDriveDifferentialParams *& differentialParams, PxVehicleDifferentialState *& differentialState, PxVehicleWheelConstraintGroupState*& wheelConstraintGroups) { axleDescription = &mBaseParams.axleDescription; tankDriveTransmissionCommands = &mTankDriveTransmissionCommandState; wheelParams.setData(mBaseParams.wheelParams); differentialParams = &mEngineDriveParams.tankDifferentialParams; differentialState = &mEngineDriveState.differentialState; wheelConstraintGroups = &mEngineDriveState.wheelConstraintGroupState; } virtual void getDataForEngineDriveActuationStateComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleGearboxParams*& gearboxParams, PxVehicleArrayData<const PxReal>& brakeResponseStates, const PxVehicleEngineDriveThrottleCommandResponseState*& throttleResponseState, const PxVehicleGearboxState*& gearboxState, const PxVehicleDifferentialState*& differentialState, const PxVehicleClutchCommandResponseState*& clutchResponseState, PxVehicleArrayData<PxVehicleWheelActuationState>& actuationStates) { axleDescription = &mBaseParams.axleDescription; gearboxParams = &mEngineDriveParams.gearBoxParams; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseState = &mEngineDriveState.throttleCommandResponseState; gearboxState = &mEngineDriveState.gearboxState; differentialState = &mEngineDriveState.differentialState; clutchResponseState = &mEngineDriveState.clutchCommandResponseState; actuationStates.setData(mBaseState.actuationStates); } virtual void getDataForEngineDrivetrainComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, const PxVehicleEngineParams*& engineParams, const PxVehicleClutchParams*& clutchParams, const PxVehicleGearboxParams*& gearboxParams, PxVehicleArrayData<const PxReal>& brakeResponseStates, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleTireForce>& tireForces, const PxVehicleEngineDriveThrottleCommandResponseState*& throttleResponseState, const PxVehicleClutchCommandResponseState*& clutchResponseState, const PxVehicleDifferentialState*& differentialState, const PxVehicleWheelConstraintGroupState*& constraintGroupState, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleEngineState*& engineState, PxVehicleGearboxState*& gearboxState, PxVehicleClutchSlipState*& clutchState) { axleDescription = &mBaseParams.axleDescription; wheelParams.setData(mBaseParams.wheelParams); engineParams = &mEngineDriveParams.engineParams; clutchParams = &mEngineDriveParams.clutchParams; gearboxParams = &mEngineDriveParams.gearBoxParams; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); actuationStates.setData(mBaseState.actuationStates); tireForces.setData(mBaseState.tireForces); throttleResponseState = &mEngineDriveState.throttleCommandResponseState; clutchResponseState = &mEngineDriveState.clutchCommandResponseState; differentialState = &mEngineDriveState.differentialState; constraintGroupState = Enum::eDIFFTYPE_TANKDRIVE == mDifferentialType ? &mEngineDriveState.wheelConstraintGroupState : NULL; wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); engineState = &mEngineDriveState.engineState; gearboxState = &mEngineDriveState.gearboxState; clutchState = &mEngineDriveState.clutchState; } //Parameters and states of the vehicle's engine drivetrain. EngineDrivetrainParams mEngineDriveParams; EngineDrivetrainState mEngineDriveState; //The commands that will control the vehicle's transmission PxVehicleEngineDriveTransmissionCommandState mTransmissionCommandState; PxVehicleTankDriveTransmissionCommandState mTankDriveTransmissionCommandState; //The type of differential that will be used. //If eDIFFTYPE_TANKDRIVE is chosen then the vehicle's transmission //commands are stored in mTankDriveTransmissionCommandState. //If eDIFFTYPE_FOURWHEELDRIVE or eDIFFTYPE_MULTIWHEELDRIVE is chosen //then the vehicle's transmission commands are stored in //mTransmissionCommandState Enum mDifferentialType; }; }//namespace snippetvehicle2
15,193
C
44.086053
158
0.836701
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/enginedrivetrain/EngineDrivetrain.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "EngineDrivetrain.h" #include "../base/Base.h" namespace snippetvehicle2 { EngineDrivetrainParams EngineDrivetrainParams::transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const { EngineDrivetrainParams r = *this; r.autoboxParams = autoboxParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.clutchCommandResponseParams = clutchCommandResponseParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.engineParams = engineParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.gearBoxParams = gearBoxParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.fourWheelDifferentialParams = fourWheelDifferentialParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.multiWheelDifferentialParams = multiWheelDifferentialParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.tankDifferentialParams = tankDifferentialParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.clutchParams = clutchParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); return r; } bool EngineDriveVehicle::initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, Enum differentialTye, bool addPhysXBeginEndComponents) { mDifferentialType = differentialTye; mTransmissionCommandState.setToDefault(); mTankDriveTransmissionCommandState.setToDefault(); if (!PhysXActorVehicle::initialize(physics, params, defaultMaterial)) return false; if (!mEngineDriveParams.isValid(mBaseParams.axleDescription)) return false; //Set the drivetrain state to default. mEngineDriveState.setToDefault(); //Add all the components in sequence that will simulate a vehicle with an engine drive drivetrain. initComponentSequence(addPhysXBeginEndComponents); return true; } void EngineDriveVehicle::destroy() { PhysXActorVehicle::destroy(); } void EngineDriveVehicle::initComponentSequence(bool addPhysXBeginEndComponents) { //Wake up the associated PxRigidBody if it is asleep and the vehicle commands signal an //intent to change state. //Read from the physx actor and write the state (position, velocity etc) to the vehicle. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorBeginComponent*>(this)); //Read the input commands (throttle, brake, steer, clutch etc) and forward them to the drivetrain and steering mechanism. //When using automatic transmission, the autobox determines if it wants to begin a gear change. If it does, it will overwrite //the target gear command and set throttle to 0 internally. mComponentSequence.add(static_cast<PxVehicleEngineDriveCommandResponseComponent*>(this)); //The differential determines the fraction of available drive torque that will be delivered to each wheel. switch (mDifferentialType) { case eDIFFTYPE_FOURWHEELDRIVE: mComponentSequence.add(static_cast<PxVehicleFourWheelDriveDifferentialStateComponent*>(this)); break; case eDIFFTYPE_MULTIWHEELDRIVE: mComponentSequence.add(static_cast<PxVehicleMultiWheelDriveDifferentialStateComponent*>(this)); break; case eDIFFTYPE_TANKDRIVE: mComponentSequence.add(static_cast<PxVehicleTankDriveDifferentialStateComponent*>(this)); break; default: PX_ASSERT(false); break; } //Work out which wheels have a non-zero drive torque and non-zero brake torque. //This is used to determine if any tire is to enter the "sticky" regime that will bring the //vehicle to rest. mComponentSequence.add(static_cast<PxVehicleEngineDriveActuationStateComponent*>(this)); //Perform a scene query against the physx scene to determine the plane and friction under each wheel. mComponentSequence.add(static_cast<PxVehiclePhysXRoadGeometrySceneQueryComponent*>(this)); //Start a substep group that can be ticked multiple times per update. //Record the handle returned by PxVehicleComponentSequence::beginSubstepGroup() because this //is used later to set the number of substeps for this substep group. //In this example, we allow the update of the suspensions, tires and wheels multiple times without recalculating //the plane underneath the wheel. This is useful for stability at low forward speeds and is much cheaper //than setting a smaller timestep for the whole vehicle. mComponentSequenceSubstepGroupHandle = mComponentSequence.beginSubstepGroup(3); //Update the suspension compression given the plane under each wheel. //Update the kinematic compliance from the compression state of each suspension. //Convert suspension state to suspension force and torque. mComponentSequence.add(static_cast<PxVehicleSuspensionComponent*>(this)); //Compute the load on the tire, the friction experienced by the tire //and the lateral/longitudinal slip angles. //Convert load/friction/slip to tire force and torque. //If the vehicle is to come rest then compute the "sticky" velocity constraints to apply to the //vehicle. mComponentSequence.add(static_cast<PxVehicleTireComponent*>(this)); //Apply any "sticky" velocity constraints to a data buffer that will be consumed by the physx scene //during the next physx scene update. mComponentSequence.add(static_cast<PxVehiclePhysXConstraintComponent*>(this)); //Update the rotational speed of the engine and wheels by applying the available drive torque //to the wheels through the clutch, differential and gears and accounting for the longitudinal //tire force that is applied to the wheel's angular momentum. mComponentSequence.add(static_cast<PxVehicleEngineDrivetrainComponent*>(this)); //Apply the suspension and tire forces to the vehicle's rigid body and forward //integrate the state of the rigid body. mComponentSequence.add(static_cast<PxVehicleRigidBodyComponent*>(this)); //Mark the end of the substep group. mComponentSequence.endSubstepGroup(); //Update the rotation angle of the wheel by forwarding integrating the rotational //speed of each wheel. //Compute the local pose of the wheel in the rigid body frame after accounting //suspension compression and compliance. mComponentSequence.add(static_cast<PxVehicleWheelComponent*>(this)); //Write the local poses of each wheel to the corresponding shapes on the physx actor. //Write the momentum change applied to the vehicle's rigid body to the physx actor. //The physx scene can now try to apply that change to the physx actor. //The physx scene will account for collisions and constraints to be applied to the vehicle //that occur by applying the change. if (addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorEndComponent*>(this)); } }//namespace snippetvehicle2
8,456
C++
48.747059
134
0.796239
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/physxintegration/PhysXIntegration.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "PxScene.h" #include "vehicle2/PxVehicleAPI.h" #include "../base/Base.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct PhysXIntegrationParams { PxVehiclePhysXRoadGeometryQueryParams physxRoadGeometryQueryParams; PxVehiclePhysXMaterialFrictionParams physxMaterialFrictionParams[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehiclePhysXSuspensionLimitConstraintParams physxSuspensionLimitConstraintParams[PxVehicleLimits::eMAX_NB_WHEELS]; PxTransform physxActorCMassLocalPose; PxVec3 physxActorBoxShapeHalfExtents; PxTransform physxActorBoxShapeLocalPose; PxTransform physxWheelShapeLocalPoses[PxVehicleLimits::eMAX_NB_WHEELS]; void create (const PxVehicleAxleDescription& axleDescription, const PxQueryFilterData& queryFilterData, PxQueryFilterCallback* queryFilterCallback, PxVehiclePhysXMaterialFriction* materialFrictions, const PxU32 nbMaterialFrictions, const PxReal defaultFriction, const PxTransform& physXActorCMassLocalPose, const PxVec3& physXActorBoxShapeHalfExtents, const PxTransform& physxActorBoxShapeLocalPose); PhysXIntegrationParams transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const; PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const { if (!physxRoadGeometryQueryParams.isValid()) return false; for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; if (!physxMaterialFrictionParams[wheelId].isValid()) return false; if (!physxSuspensionLimitConstraintParams[wheelId].isValid()) return false; } return true; } }; struct PhysXIntegrationState { PxVehiclePhysXActor physxActor; //physx actor PxVehiclePhysXSteerState physxSteerState; PxVehiclePhysXConstraints physxConstraints; //susp limit and sticky tire constraints PX_FORCE_INLINE void setToDefault() { physxActor.setToDefault(); physxSteerState.setToDefault(); physxConstraints.setToDefault(); } void create (const BaseVehicleParams& baseParams, const PhysXIntegrationParams& physxParams, PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial); void destroy(); }; void setPhysXIntegrationParams(const PxVehicleAxleDescription&, PxVehiclePhysXMaterialFriction*, PxU32 nbPhysXMaterialFrictions, PxReal physXDefaultMaterialFriction, PhysXIntegrationParams&); // //This class holds the parameters, state and logic needed to implement a vehicle that //is using a PhysX actor to potentially interact with other objects in a PhysX scene. // //See BaseVehicle for more details on the snippet code design. // class PhysXActorVehicle : public BaseVehicle , public PxVehiclePhysXActorBeginComponent , public PxVehiclePhysXActorEndComponent , public PxVehiclePhysXConstraintComponent , public PxVehiclePhysXRoadGeometrySceneQueryComponent { public: bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial); virtual void destroy(); void setUpActor(PxScene& scene, const PxTransform& pose, const char* vehicleName); virtual void getDataForPhysXActorBeginComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleCommandState*& commands, const PxVehicleEngineDriveTransmissionCommandState*& transmissionCommands, const PxVehicleGearboxParams*& gearParams, const PxVehicleGearboxState*& gearState, const PxVehicleEngineParams*& engineParams, PxVehiclePhysXActor*& physxActor, PxVehiclePhysXSteerState*& physxSteerState, PxVehiclePhysXConstraints*& physxConstraints, PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleEngineState*& engineState) { axleDescription = &mBaseParams.axleDescription; commands = &mCommandState; physxActor = &mPhysXState.physxActor; physxSteerState = &mPhysXState.physxSteerState; physxConstraints = &mPhysXState.physxConstraints; rigidBodyState = &mBaseState.rigidBodyState; wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); transmissionCommands = NULL; gearParams = NULL; gearState = NULL; engineParams = NULL; engineState = NULL; } virtual void getDataForPhysXActorEndComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxTransform>& wheelShapeLocalPoses, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses, const PxVehicleGearboxState*& gearState, const PxReal*& throttle, PxVehiclePhysXActor*& physxActor) { axleDescription = &mBaseParams.axleDescription; rigidBodyState = &mBaseState.rigidBodyState; wheelParams.setData(mBaseParams.wheelParams); wheelShapeLocalPoses.setData(mPhysXParams.physxWheelShapeLocalPoses); wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); wheelLocalPoses.setData(mBaseState.wheelLocalPoses); physxActor = &mPhysXState.physxActor; gearState = NULL; throttle = &mCommandState.throttle; } virtual void getDataForPhysXConstraintComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& suspensionLimitParams, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleRoadGeometryState>& wheelRoadGeomStates, PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates, PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates, PxVehiclePhysXConstraints*& constraints) { axleDescription = &mBaseParams.axleDescription; rigidBodyState = &mBaseState.rigidBodyState; suspensionParams.setData(mBaseParams.suspensionParams); suspensionLimitParams.setData(mPhysXParams.physxSuspensionLimitConstraintParams); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); wheelRoadGeomStates.setData(mBaseState.roadGeomStates); tireDirectionStates.setData(mBaseState.tireDirectionStates); tireStickyStates.setData(mBaseState.tireStickyStates); constraints = &mPhysXState.physxConstraints; } virtual void getDataForPhysXRoadGeometrySceneQueryComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehiclePhysXRoadGeometryQueryParams*& roadGeomParams, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& materialFrictionParams, PxVehicleArrayData<PxVehicleRoadGeometryState>& roadGeometryStates, PxVehicleArrayData<PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeometryStates) { axleDescription = &mBaseParams.axleDescription; roadGeomParams = &mPhysXParams.physxRoadGeometryQueryParams; steerResponseStates.setData(mBaseState.steerCommandResponseStates); rigidBodyState = &mBaseState.rigidBodyState; wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); materialFrictionParams.setData(mPhysXParams.physxMaterialFrictionParams); roadGeometryStates.setData(mBaseState.roadGeomStates); physxRoadGeometryStates.setEmpty(); } //Parameters and states of the vehicle's physx integration. PhysXIntegrationParams mPhysXParams; PhysXIntegrationState mPhysXState; //The commands that will control the vehicle // // Note that this is not related to a PhysX actor based vehicle as such but // put in here to be shared by all vehicle types that will be based on this // class. It keeps the code simpler for the purpose of the snippets. // PxVehicleCommandState mCommandState; }; }//namespace snippetvehicle2
10,000
C
41.377118
136
0.8204
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/physxintegration/PhysXIntegration.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PhysXIntegration.h" namespace snippetvehicle2 { void PhysXIntegrationParams::create (const PxVehicleAxleDescription& axleDescription, const PxQueryFilterData& queryFilterData, PxQueryFilterCallback* queryFilterCallback, PxVehiclePhysXMaterialFriction* materialFrictions, const PxU32 nbMaterialFrictions, const PxReal defaultFriction, const PxTransform& actorCMassLocalPose, const PxVec3& actorBoxShapeHalfExtents, const PxTransform& actorBoxShapeLocalPose) { physxRoadGeometryQueryParams.roadGeometryQueryType = PxVehiclePhysXRoadGeometryQueryType::eRAYCAST; physxRoadGeometryQueryParams.defaultFilterData = queryFilterData; physxRoadGeometryQueryParams.filterCallback = queryFilterCallback; physxRoadGeometryQueryParams.filterDataEntries = NULL; for(PxU32 i = 0; i < axleDescription.nbWheels; i++) { const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i]; physxMaterialFrictionParams[wheelId].defaultFriction = defaultFriction; physxMaterialFrictionParams[wheelId].materialFrictions = materialFrictions; physxMaterialFrictionParams[wheelId].nbMaterialFrictions = nbMaterialFrictions; physxSuspensionLimitConstraintParams[wheelId].restitution = 0.0f; physxSuspensionLimitConstraintParams[wheelId].directionForSuspensionLimitConstraint = PxVehiclePhysXSuspensionLimitConstraintParams::eROAD_GEOMETRY_NORMAL; physxWheelShapeLocalPoses[wheelId] = PxTransform(PxIdentity); } physxActorCMassLocalPose = actorCMassLocalPose; physxActorBoxShapeHalfExtents = actorBoxShapeHalfExtents; physxActorBoxShapeLocalPose = actorBoxShapeLocalPose; } PhysXIntegrationParams PhysXIntegrationParams::transformAndScale (const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const { PhysXIntegrationParams r = *this; r.physxRoadGeometryQueryParams = physxRoadGeometryQueryParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); for (PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++) { r.physxSuspensionLimitConstraintParams[i] = physxSuspensionLimitConstraintParams[i].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); } r.physxActorCMassLocalPose = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, srcScale, trgScale, physxActorCMassLocalPose); r.physxActorBoxShapeHalfExtents = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, srcScale, trgScale, physxActorBoxShapeHalfExtents); r.physxActorBoxShapeLocalPose = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, srcScale, trgScale, physxActorBoxShapeLocalPose); return r; } void PhysXIntegrationState::create (const BaseVehicleParams& baseParams, const PhysXIntegrationParams& physxParams, PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial) { setToDefault(); //physxActor needs to be populated with an actor and its shapes. { const PxVehiclePhysXRigidActorParams physxActorParams(baseParams.rigidBodyParams, NULL); const PxBoxGeometry boxGeom(physxParams.physxActorBoxShapeHalfExtents); const PxVehiclePhysXRigidActorShapeParams physxActorShapeParams(boxGeom, physxParams.physxActorBoxShapeLocalPose, defaultMaterial, PxShapeFlags(0), PxFilterData(), PxFilterData()); const PxVehiclePhysXWheelParams physxWheelParams(baseParams.axleDescription, baseParams.wheelParams); const PxVehiclePhysXWheelShapeParams physxWheelShapeParams(defaultMaterial, PxShapeFlags(0), PxFilterData(), PxFilterData()); PxVehiclePhysXActorCreate( baseParams.frame, physxActorParams, physxParams.physxActorCMassLocalPose, physxActorShapeParams, physxWheelParams, physxWheelShapeParams, physics, params, physxActor); } //physxConstraints needs to be populated with constraints. PxVehicleConstraintsCreate(baseParams.axleDescription, physics, *physxActor.rigidBody, physxConstraints); } void PhysXIntegrationState::destroy() { PxVehicleConstraintsDestroy(physxConstraints); PxVehiclePhysXActorDestroy(physxActor); } void setPhysXIntegrationParams(const PxVehicleAxleDescription& axleDescription, PxVehiclePhysXMaterialFriction* physXMaterialFrictions, PxU32 nbPhysXMaterialFrictions, PxReal physXDefaultMaterialFriction, PhysXIntegrationParams& physXParams) { //The physx integration params are hardcoded rather than loaded from file. const PxQueryFilterData queryFilterData(PxFilterData(0, 0, 0, 0), PxQueryFlag::eSTATIC); PxQueryFilterCallback* queryFilterCallback = NULL; const PxTransform physxActorCMassLocalPose(PxVec3(0.0f, 0.55f, 1.594f), PxQuat(PxIdentity)); const PxVec3 physxActorBoxShapeHalfExtents(0.84097f, 0.65458f, 2.46971f); const PxTransform physxActorBoxShapeLocalPose(PxVec3(0.0f, 0.830066f, 1.37003f), PxQuat(PxIdentity)); physXParams.create( axleDescription, queryFilterData, queryFilterCallback, physXMaterialFrictions, nbPhysXMaterialFrictions, physXDefaultMaterialFriction, physxActorCMassLocalPose, physxActorBoxShapeHalfExtents, physxActorBoxShapeLocalPose); } bool PhysXActorVehicle::initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial) { mCommandState.setToDefault(); if (!BaseVehicle::initialize()) return false; if (!mPhysXParams.isValid(mBaseParams.axleDescription)) return false; mPhysXState.create(mBaseParams, mPhysXParams, physics, params, defaultMaterial); return true; } void PhysXActorVehicle::destroy() { mPhysXState.destroy(); BaseVehicle::destroy(); } void PhysXActorVehicle::setUpActor(PxScene& scene, const PxTransform& pose, const char* vehicleName) { //Give the vehicle a start pose by appylying a pose to the PxRigidDynamic associated with the vehicle. //This vehicle has components that are configured to read the pose from the PxRigidDynamic //at the start of the vehicle simulation update and to write back an updated pose at the end of the //vehicle simulation update. This allows PhysX to manage any collisions that might happen in-between //each vehicle update. This is not essential but it is anticipated that this will be a typical component //configuration. mPhysXState.physxActor.rigidBody->setGlobalPose(pose); //Add the physx actor to the physx scene. //As described above, a vehicle may be coupled to a physx scene or it can be simulated without any reference to //to a PxRigidDynamic or PxScene. This snippet vehicle employs a configuration that includes coupling to a PxScene and a //PxRigidDynamic. This being the case, the PxRigidDynamic associated with the vehicle needs to be added to the //PxScene instance. scene.addActor(*mPhysXState.physxActor.rigidBody); //Give the physx actor a name to help identification in PVD mPhysXState.physxActor.rigidBody->setName(vehicleName); } }//namespace snippetvehicle2
8,417
C++
46.829545
182
0.816443
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/directdrivetrain/DirectDrivetrain.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "DirectDrivetrain.h" #include "../base/Base.h" namespace snippetvehicle2 { DirectDrivetrainParams DirectDrivetrainParams::transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const { DirectDrivetrainParams r = *this; r.directDriveThrottleResponseParams = directDriveThrottleResponseParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); return r; } bool DirectDriveVehicle::initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents) { mTransmissionCommandState.setToDefault(); if (!PhysXActorVehicle::initialize(physics, params, defaultMaterial)) return false; if (!mDirectDriveParams.isValid(mBaseParams.axleDescription)) return false; //Set the drivetrain state to default. mDirectDriveState.setToDefault(); //Add all the components in sequence that will simulate a vehicle with a direct drive drivetrain. initComponentSequence(addPhysXBeginEndComponents); return true; } void DirectDriveVehicle::destroy() { PhysXActorVehicle::destroy(); } void DirectDriveVehicle::initComponentSequence(bool addPhysXBeginEndComponents) { //Wake up the associated PxRigidBody if it is asleep and the vehicle commands signal an //intent to change state. //Read from the physx actor and write the state (position, velocity etc) to the vehicle. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorBeginComponent*>(this)); //Read the input commands (throttle, brake etc) and forward them as torques and angles to the wheels on each axle. mComponentSequence.add(static_cast<PxVehicleDirectDriveCommandResponseComponent*>(this)); //Work out which wheels have a non-zero drive torque and non-zero brake torque. //This is used to determine if any tire is to enter the "sticky" regime that will bring the //vehicle to rest. mComponentSequence.add(static_cast<PxVehicleDirectDriveActuationStateComponent*>(this)); //Perform a scene query against the physx scene to determine the plane and friction under each wheel. mComponentSequence.add(static_cast<PxVehiclePhysXRoadGeometrySceneQueryComponent*>(this)); //Start a substep group that can be ticked multiple times per update. //In this example, we update the suspensions, tires and wheels 3 times without recalculating //the plane underneath the wheel. This is useful for stability at low forward speeds and is //computationally cheaper than simulating the whole pipeline at a smaller timestep. mComponentSequenceSubstepGroupHandle = mComponentSequence.beginSubstepGroup(3); //Update the suspension compression given the plane under each wheel. //Update the kinematic compliance from the compression state of each suspension. //Convert suspension state to suspension force and torque. mComponentSequence.add(static_cast<PxVehicleSuspensionComponent*>(this)); //Compute the load on the tire, the friction experienced by the tire //and the lateral/longitudinal slip angles. //Convert load/friction/slip to tire force and torque. //If the vehicle is to come rest then compute the "sticky" velocity constraints to apply to the //vehicle. mComponentSequence.add(static_cast<PxVehicleTireComponent*>(this)); //Apply any velocity constraints to a data buffer that will be consumed by the physx scene //during the next physx scene update. mComponentSequence.add(static_cast<PxVehiclePhysXConstraintComponent*>(this)); //Apply the tire force, brake force and drive force to each wheel and //forward integrate the rotation speed of each wheel. mComponentSequence.add(static_cast<PxVehicleDirectDrivetrainComponent*>(this)); //Apply the suspension and tire forces to the vehicle's rigid body and forward //integrate the state of the rigid body. mComponentSequence.add(static_cast<PxVehicleRigidBodyComponent*>(this)); //Mark the end of the substep group. mComponentSequence.endSubstepGroup(); //Update the rotation angle of the wheel by forwarding integrating the rotational //speed of each wheel. //Compute the local pose of the wheel in the rigid body frame after accounting //suspension compression and compliance. mComponentSequence.add(static_cast<PxVehicleWheelComponent*>(this)); //Write the local poses of each wheel to the corresponding shapes on the physx actor. //Write the momentum change applied to the vehicle's rigid body to the physx actor. //The physx scene can now try to apply that change to the physx actor. //The physx scene will account for collisions and constraints to be applied to the vehicle //that occur by applying the change. if (addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorEndComponent*>(this)); } }//namespace snippetvehicle2
6,541
C++
47.102941
148
0.789635
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/directdrivetrain/DirectDrivetrain.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../physxintegration/PhysXIntegration.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct DirectDrivetrainParams { PxVehicleDirectDriveThrottleCommandResponseParams directDriveThrottleResponseParams; DirectDrivetrainParams transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const; PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const { if (!directDriveThrottleResponseParams.isValid(axleDesc)) return false; return true; } }; struct DirectDrivetrainState { PxReal directDriveThrottleResponseStates[PxVehicleLimits::eMAX_NB_WHEELS]; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(DirectDrivetrainState)); } }; // //This class holds the parameters, state and logic needed to implement a vehicle that //is using a direct drivetrain. // //See BaseVehicle for more details on the snippet code design. // class DirectDriveVehicle : public PhysXActorVehicle , public PxVehicleDirectDriveCommandResponseComponent , public PxVehicleDirectDriveActuationStateComponent , public PxVehicleDirectDrivetrainComponent { public: bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents = true); virtual void destroy(); virtual void initComponentSequence(bool addPhysXBeginEndComponents); void getDataForDirectDriveCommandResponseComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams, const PxVehicleDirectDriveThrottleCommandResponseParams*& throttleResponseParams, const PxVehicleSteerCommandResponseParams*& steerResponseParams, PxVehicleSizedArrayData<const PxVehicleAckermannParams>& ackermannParams, const PxVehicleCommandState*& commands, const PxVehicleDirectDriveTransmissionCommandState*& transmissionCommands, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<PxReal>& brakeResponseStates, PxVehicleArrayData<PxReal>& throttleResponseStates, PxVehicleArrayData<PxReal>& steerResponseStates) { axleDescription = &mBaseParams.axleDescription; brakeResponseParams.setDataAndCount(mBaseParams.brakeResponseParams, sizeof(mBaseParams.brakeResponseParams) / sizeof(PxVehicleBrakeCommandResponseParams)); throttleResponseParams = &mDirectDriveParams.directDriveThrottleResponseParams; steerResponseParams = &mBaseParams.steerResponseParams; ackermannParams.setDataAndCount(mBaseParams.ackermannParams, sizeof(mBaseParams.ackermannParams)/sizeof(PxVehicleAckermannParams)); commands = &mCommandState; transmissionCommands = &mTransmissionCommandState; rigidBodyState = &mBaseState.rigidBodyState; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseStates.setData(mDirectDriveState.directDriveThrottleResponseStates); steerResponseStates.setData(mBaseState.steerCommandResponseStates); } virtual void getDataForDirectDriveActuationStateComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& brakeResponseStates, PxVehicleArrayData<const PxReal>& throttleResponseStates, PxVehicleArrayData<PxVehicleWheelActuationState>& actuationStates) { axleDescription = &mBaseParams.axleDescription; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseStates.setData(mDirectDriveState.directDriveThrottleResponseStates); actuationStates.setData(mBaseState.actuationStates); } virtual void getDataForDirectDrivetrainComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& brakeResponseStates, PxVehicleArrayData<const PxReal>& throttleResponseStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleTireForce>& tireForces, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates) { axleDescription = &mBaseParams.axleDescription; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseStates.setData(mDirectDriveState.directDriveThrottleResponseStates); wheelParams.setData(mBaseParams.wheelParams); actuationStates.setData(mBaseState.actuationStates); tireForces.setData(mBaseState.tireForces); wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); } //Parameters and states of the vehicle's direct drivetrain. DirectDrivetrainParams mDirectDriveParams; DirectDrivetrainState mDirectDriveState; //The commands that will control the vehicle's transmission PxVehicleDirectDriveTransmissionCommandState mTransmissionCommandState; }; }//namespace snippetvehicle2
6,614
C
43.395973
158
0.82779
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/DirectDrivetrainSerialization.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../directdrivetrain/DirectDrivetrain.h" #if PX_SWITCH #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #elif PX_OSX #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #elif PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #if (PX_LINUX && PX_CLANG) || PX_SWITCH #pragma clang diagnostic pop #endif namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; bool readThrottleResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams); bool writeThrottleResponseParams (const PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readDirectDrivetrainParamsFromJsonFile(const char* directory, const char* filename, const PxVehicleAxleDescription& axleDescription, DirectDrivetrainParams&); bool writeDirectDrivetrainParamsToJsonFile(const char* directory, const char* filename, const PxVehicleAxleDescription& axleDescription, const DirectDrivetrainParams&); }//namespace snippetvehicle2
3,230
C
42.079999
123
0.795975
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/SerializationCommon.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "SerializationCommon.h" #include <fstream> #include <sstream> namespace snippetvehicle2 { bool openDocument(const char* directory, const char* filename, rapidjson::Document& document) { // Check the json file exists. std::string fileWithPath(directory); fileWithPath.push_back('/'); fileWithPath.append(filename); std::ifstream inputFile(fileWithPath); if (!inputFile.is_open()) { printf("Opening file \"%s\" failed.\n", fileWithPath.c_str()); return false; } // Check the json file can be loaded by rapidjson. // Failures might be missing commas or braces. std::string inputData{ std::istreambuf_iterator<char>(inputFile), std::istreambuf_iterator<char>() }; document.Parse(inputData.c_str()); inputFile.close(); if (!document.IsObject()) { printf("Parsing file \"%s\" failed.\n", fileWithPath.c_str()); return false; } return true; } bool readCommandResponseParams (const rapidjson::Value& value, const PxVehicleAxleDescription& axleDesc, PxVehicleCommandResponseParams& responseParams) { if (!value.HasMember("MaxResponse")) return false; responseParams.maxResponse = static_cast<PxReal>(value["MaxResponse"].GetDouble()); if (!value.HasMember("WheelResponseMultipliers")) return false; const rapidjson::Value& responseMultipliers = value["WheelResponseMultipliers"]; if (responseMultipliers.Size() < axleDesc.nbWheels) return false; if (responseMultipliers.Size() > PxVehicleLimits::eMAX_NB_WHEELS) return false; for (PxU32 i = 0; i < responseMultipliers.Size(); i++) { responseParams.wheelResponseMultipliers[i] = static_cast<PxReal>(responseMultipliers[i].GetDouble()); } //Nonlinear response is not mandatory. responseParams.nonlinearResponse.clear(); if(!value.HasMember("NonLinearResponse")) return true; const rapidjson::Value& nonlinearResponse = value["NonLinearResponse"]; const int nbCommandValues = nonlinearResponse.Size(); for (int i = 0; i < nbCommandValues; i++) { PxVehicleCommandValueResponseTable commandValueResponse; //Read the throttle value and set it. const rapidjson::Value& commandAndResponse = nonlinearResponse[i]; if (!commandAndResponse.HasMember("Throttle")) return false; const PxReal commandValue = static_cast<PxReal>(commandAndResponse["Throttle"].GetDouble()); commandValueResponse.commandValue = commandValue; //Read the array of (speed, torque) entries. if (!commandAndResponse.HasMember("ResponseCurve")) return false; const rapidjson::Value& torqueCurve = commandAndResponse["ResponseCurve"]; const PxU32 nbItems = torqueCurve.Size(); for (PxU32 j = 0; j < nbItems; j++) { const rapidjson::Value& torqueCurveItem = torqueCurve[j]; if (torqueCurveItem.Size() != 2) return false; const PxReal speed = static_cast<PxReal>(torqueCurveItem[0].GetDouble()); const PxReal normalisedResponse = static_cast<PxReal>(torqueCurveItem[1].GetDouble()); commandValueResponse.speedResponses.addPair(speed, normalisedResponse); } responseParams.nonlinearResponse.addResponse(commandValueResponse); } return true; } bool writeCommandResponseParams (const PxVehicleCommandResponseParams& responseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("MaxResponse"); writer.Double(static_cast<double>(responseParams.maxResponse)); writer.Key("WheelResponseMultipliers"); writer.StartArray(); for(PxU32 i = 0; i < axleDesc.nbWheels; i++) { const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Double(static_cast<double>(responseParams.wheelResponseMultipliers[wheelId])); } writer.EndArray(); writer.Key("ResponseCurve"); writer.StartArray(); for (PxU32 i = 0; i < responseParams.nonlinearResponse.nbCommandValues; i++) { writer.Key("Throttle"); writer.Double(static_cast<double>(responseParams.nonlinearResponse.commandValues[i])); writer.Key("ResponseCurve"); writer.StartArray(); const PxReal* speeds = responseParams.nonlinearResponse.speedResponses + responseParams.nonlinearResponse.speedResponsesPerCommandValue[i]; const PxReal* responses = speeds + responseParams.nonlinearResponse.nbSpeedResponsesPerCommandValue[i]; for (PxU32 j = 0; j < responseParams.nonlinearResponse.nbSpeedResponsesPerCommandValue[i]; j++) { writer.StartArray(); writer.Double(static_cast<double>(speeds[j])); writer.Double(static_cast<double>(responses[j])); writer.EndArray(); } writer.EndArray(); } writer.EndArray(); return true; } void writeCommandResponseParams (const PxVehicleAxleDescription& axleDesc, const PxVehicleCommandResponseParams& throttleResponseParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartObject(); writer.Key("MaxResponse"); writer.Double(static_cast<double>(throttleResponseParams.maxResponse)); writer.Key("WheelResponseMultipliers"); writer.StartArray(); for(PxU32 i = 0; i < axleDesc.nbWheels; i++) { const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Double(static_cast<double>(throttleResponseParams.wheelResponseMultipliers[wheelId])); } writer.EndArray(); writer.EndObject(); } bool readVec3(const rapidjson::Value& values, PxVec3& r) { if (values.Size() != 3) return false; r.x = static_cast<PxReal>(values[0].GetDouble()); r.y = static_cast<PxReal>(values[1].GetDouble()); r.z = static_cast<PxReal>(values[2].GetDouble()); return true; } bool writeVec3(const PxVec3& r, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartArray(); writer.Double(static_cast<double>(r.x)); writer.Double(static_cast<double>(r.y)); writer.Double(static_cast<double>(r.z)); writer.EndArray(); return true; } bool readQuat(const rapidjson::Value& values, PxQuat& r) { if (values.Size() != 4) return false; r.x = static_cast<PxReal>(values[0].GetDouble()); r.y = static_cast<PxReal>(values[1].GetDouble()); r.z = static_cast<PxReal>(values[2].GetDouble()); r.w = static_cast<PxReal>(values[3].GetDouble()); return true; } bool writeQuat(const PxQuat& r, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartArray(); writer.Double(static_cast<double>(r.x)); writer.Double(static_cast<double>(r.y)); writer.Double(static_cast<double>(r.z)); writer.Double(static_cast<double>(r.w)); writer.EndArray(); return true; } bool readTransform(const rapidjson::Value& values, PxTransform& r) { if (!values.HasMember("Pos")) return false; if (!values.HasMember("Quat")) return false; if (!readVec3(values["Pos"], r.p)) return false; if (!readQuat(values["Quat"], r.q)) return false; return true; } bool writeTransform(const PxTransform& r, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartObject(); writer.Key("Pos"); writeVec3(r.p, writer); writer.Key("Quat"); writeQuat(r.q, writer); writer.EndObject(); return true; } template<const PxU32 N> bool readFloatLookupTableN(const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxReal, N>& lookupTable) { lookupTable.clear(); if (values.Size() > N) return false; for (PxU32 i = 0; i < values.Size(); i++) { const rapidjson::Value& element = values[i]; if (element.Size() != 2) return false; const PxReal x = static_cast<PxReal>(values[i][0].GetDouble()); const PxReal y = static_cast<PxReal>(values[i][1].GetDouble()); lookupTable.addPair(x, y); } return true; } bool readFloatLookupTable (const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxReal, 3>& lookupTable) { return readFloatLookupTableN<3>(values, lookupTable); } bool readFloatLookupTable (const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxReal, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>& lookupTable) { return readFloatLookupTableN<PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>(values, lookupTable); } template<const PxU32 N> bool writeFloatLookupTable(const PxVehicleFixedSizeLookupTable<PxReal, N>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartArray(); for (PxU32 i = 0; i < lookupTable.nbDataPairs; i++) { writer.StartArray(); writer.Double(static_cast<double>(lookupTable.xVals[i])); writer.Double(static_cast<double>(lookupTable.yVals[i])); writer.EndArray(); } writer.EndArray(); return true; } bool writeFloatLookupTable(const PxVehicleFixedSizeLookupTable<PxReal, 3>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { return writeFloatLookupTable<3>(lookupTable, writer); } bool writeFloatLookupTable(const PxVehicleFixedSizeLookupTable<PxReal, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { return writeFloatLookupTable<PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>(lookupTable, writer); } bool readVec3LookupTable(const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxVec3, 3>& lookupTable) { lookupTable.clear(); if (values.Size() > 3) return false; for (PxU32 i = 0; i < values.Size(); i++) { const rapidjson::Value& element = values[i]; if (element.Size() != 4) return false; const PxReal x = static_cast<PxReal>(values[i][0].GetDouble()); const PxVec3 y(static_cast<PxReal>( values[i][1].GetDouble()), static_cast<PxReal>(values[i][2].GetDouble()), static_cast<PxReal>(values[i][3].GetDouble())); lookupTable.addPair(x, y); } return true; } bool writeVec3LookupTable(const PxVehicleFixedSizeLookupTable<PxVec3, 3>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartArray(); for (PxU32 i = 0; i < lookupTable.nbDataPairs; i++) { writer.StartArray(); writer.Double(static_cast<double>(lookupTable.xVals[i])); writer.Double(static_cast<double>(lookupTable.yVals[i].x)); writer.Double(static_cast<double>(lookupTable.yVals[i].y)); writer.Double(static_cast<double>(lookupTable.yVals[i].z)); writer.EndArray(); } writer.EndArray(); return true; } }//namespace snippetvehicle2
11,729
C++
31.31405
202
0.74627
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/DirectDrivetrainSerialization.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "DirectDrivetrainSerialization.h" #include "SerializationCommon.h" #include <fstream> #include <sstream> namespace snippetvehicle2 { bool readThrottleResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams) { if (!config.HasMember("ThrottleCommandResponseParams")) return false; if (!readCommandResponseParams(config["ThrottleCommandResponseParams"], axleDesc, throttleResponseParams)) return false; return true; } bool writeThrottleResponseParams (const PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("ThrottleCommandResponseParams"); writer.StartObject(); writeCommandResponseParams(throttleResponseParams, axleDesc, writer); writer.EndObject(); return true; } bool readDirectDrivetrainParamsFromJsonFile(const char* directory, const char* filename, const PxVehicleAxleDescription& axleDescription, DirectDrivetrainParams& directDrivetrainParams) { rapidjson::Document config; if (!openDocument(directory, filename, config)) return false; if(!readThrottleResponseParams(config, axleDescription, directDrivetrainParams.directDriveThrottleResponseParams)) return false; return true; } bool writeDirectDrivetrainParamsToJsonFile(const char* directory, const char* filename, const PxVehicleAxleDescription& axleDescription, const DirectDrivetrainParams& directDrivetrainParams) { rapidjson::StringBuffer strbuf; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf); writer.StartObject(); writeThrottleResponseParams(directDrivetrainParams.directDriveThrottleResponseParams, axleDescription, writer); writer.EndObject(); std::ofstream myfile; myfile.open(std::string(directory) + "/" + filename); myfile << strbuf.GetString() << std::endl; myfile.close(); return true; } }//namespace snippetvehicle2
3,715
C++
38.531914
123
0.796501
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/BaseSerialization.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../base/Base.h" #if PX_SWITCH #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #elif PX_OSX #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #elif PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #if (PX_LINUX && PX_CLANG) || PX_SWITCH #pragma clang diagnostic pop #endif namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; bool readAxleDescription(const rapidjson::Document& config, PxVehicleAxleDescription& axleDesc); bool writeAxleDescription(const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readFrame(const rapidjson::Document& config, PxVehicleFrame& frame); bool writeFrame(const PxVehicleFrame& frame, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readScale(const rapidjson::Document& config, PxVehicleScale& scale); bool writeScale(const PxVehicleScale& scale, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readBrakeResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleBrakeCommandResponseParams& brakeResponseParams); bool writeBrakeResponseParams (const PxVehicleBrakeCommandResponseParams& brakeResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readHandbrakeResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleBrakeCommandResponseParams& handbrakeResponseParams); bool writeHandbrakeResponseParams (const PxVehicleBrakeCommandResponseParams& handrakeResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSteerResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSteerCommandResponseParams& steerResponseParams); bool writeSteerResponseParams (const PxVehicleSteerCommandResponseParams& steerResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readAckermannParams (const rapidjson::Document& config, PxVehicleAckermannParams& ackermannParams); bool writeAckermannParams (const PxVehicleAckermannParams& ackermannParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readRigidBodyParams (const rapidjson::Document& config, PxVehicleRigidBodyParams& rigidBodyParams); bool writeRigidBodyParams (const PxVehicleRigidBodyParams& rigidBodyParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionParams* suspParams); bool writeSuspensionParams (const PxVehicleSuspensionParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionStateCalculationParams (const rapidjson::Document& config, PxVehicleSuspensionStateCalculationParams& suspParams); bool writeSuspensionStateCalculationParams (const PxVehicleSuspensionStateCalculationParams& suspParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionComplianceParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionComplianceParams* suspParams); bool writeSuspensionComplianceParams (const PxVehicleSuspensionComplianceParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionForceParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionForceParams* suspParams); bool writeSuspensionForceParams (const PxVehicleSuspensionForceParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionForceLegacyParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionForceLegacyParams* suspParams); bool writeSuspensionForceLegacyParams (const PxVehicleSuspensionForceLegacyParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readTireSlipParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleTireSlipParams* tireParams); bool writeTireSlipParams (const PxVehicleTireSlipParams* tireParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readTireStickyParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleTireStickyParams* tireParams); bool writeTireStickyParams (const PxVehicleTireStickyParams* tireParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readTireForceParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleTireForceParams* tireParams); bool writeTireForceParams (const PxVehicleTireForceParams* tireParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readWheelParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleWheelParams* wheelParams); bool writeWheelParams (const PxVehicleWheelParams* wheelParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readBaseParamsFromJsonFile(const char* directory, const char* filename, BaseVehicleParams&); bool writeBaseParamsToJsonFile(const char* directory, const char* filename, const BaseVehicleParams&); }//namespace snippetvehicle2
7,851
C
42.622222
126
0.82308
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/EngineDrivetrainSerialization.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "EngineDrivetrainSerialization.h" #include "SerializationCommon.h" #include <fstream> #include <sstream> namespace snippetvehicle2 { bool readAutoboxParams(const rapidjson::Document& config, PxVehicleAutoboxParams& autoboxParams) { if(!config.HasMember("AutoboxParams")) return false; if(!config["AutoboxParams"].HasMember("UpRatios")) return false; if (!config["AutoboxParams"].HasMember("DownRatios")) return false; if (!config["AutoboxParams"].HasMember("Latency")) return false; const rapidjson::Value& upRatios = config["AutoboxParams"]["UpRatios"]; for(PxU32 i = 0; i < upRatios.Size(); i++) { autoboxParams.upRatios[i] = static_cast<PxReal>(upRatios[i].GetDouble()); } const rapidjson::Value& downRatios = config["AutoboxParams"]["DownRatios"]; for (PxU32 i = 0; i < downRatios.Size(); i++) { autoboxParams.downRatios[i] = static_cast<PxReal>(downRatios[i].GetDouble()); } autoboxParams.latency = static_cast<PxReal>(config["AutoboxParams"]["Latency"].GetDouble()); return true; } bool writeAutoboxParams(const PxVehicleAutoboxParams& autoboxParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("AutoboxParams"); writer.StartObject(); writer.Key("UpRatios"); writer.StartArray(); for(PxU32 i = 0; i < PxVehicleGearboxParams::eMAX_NB_GEARS; i++) { writer.Double(static_cast<double>(autoboxParams.upRatios[i])); } writer.EndArray(); writer.Key("DownRatios"); writer.StartArray(); for (PxU32 i = 0; i < PxVehicleGearboxParams::eMAX_NB_GEARS; i++) { writer.Double(static_cast<double>(autoboxParams.downRatios[i])); } writer.EndArray(); writer.Key("Latency"); writer.Double(static_cast<double>(autoboxParams.latency)); writer.EndObject(); return true; } bool readClutchCommandResponseParams(const rapidjson::Document& config, PxVehicleClutchCommandResponseParams& clutchCommandResponseParams) { if(!config.HasMember("ClutchCommandResponseParams")) return false; if(!config["ClutchCommandResponseParams"].HasMember("MaxResponse")) return false; clutchCommandResponseParams.maxResponse = static_cast<PxReal>(config["ClutchCommandResponseParams"]["MaxResponse"].GetDouble()); return true; } bool writeClutchCommandResponseParams(const PxVehicleClutchCommandResponseParams& clutchCommandResponseParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("ClutchCommandResponseParams"); writer.StartObject(); writer.Key("MaxResponse"); writer.Double(static_cast<double>(clutchCommandResponseParams.maxResponse)); writer.EndObject(); return true; } bool readEngineParams(const rapidjson::Document& config, PxVehicleEngineParams& engineParams) { if(!config.HasMember("EngineParams")) return false; if(!config["EngineParams"].HasMember("TorqueCurve")) return false; if (!config["EngineParams"].HasMember("MOI")) return false; if (!config["EngineParams"].HasMember("PeakTorque")) return false; if (!config["EngineParams"].HasMember("IdleOmega")) return false; if (!config["EngineParams"].HasMember("MaxOmega")) return false; if (!config["EngineParams"].HasMember("DampingRateFullThrottle")) return false; if (!config["EngineParams"].HasMember("DampingRateZeroThrottleClutchEngaged")) return false; if (!config["EngineParams"].HasMember("DampingRateZeroThrottleClutchDisengaged")) return false; if(!readFloatLookupTable(config["EngineParams"]["TorqueCurve"], engineParams.torqueCurve)) return false; engineParams.moi = static_cast<PxReal>(config["EngineParams"]["MOI"].GetDouble()); engineParams.peakTorque = static_cast<PxReal>(config["EngineParams"]["PeakTorque"].GetDouble()); engineParams.idleOmega = static_cast<PxReal>(config["EngineParams"]["IdleOmega"].GetDouble()); engineParams.maxOmega = static_cast<PxReal>(config["EngineParams"]["MaxOmega"].GetDouble()); engineParams.dampingRateFullThrottle = static_cast<PxReal>(config["EngineParams"]["DampingRateFullThrottle"].GetDouble()); engineParams.dampingRateZeroThrottleClutchEngaged = static_cast<PxReal>(config["EngineParams"]["DampingRateZeroThrottleClutchEngaged"].GetDouble()); engineParams.dampingRateZeroThrottleClutchDisengaged = static_cast<PxReal>(config["EngineParams"]["DampingRateZeroThrottleClutchDisengaged"].GetDouble()); return true; } bool writeEngineParams(const PxVehicleEngineParams& engineParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("EngineParams"); writer.StartObject(); writer.Key("TorqueCurve"); writeFloatLookupTable(engineParams.torqueCurve, writer); writer.Key("MOI"); writer.Double(static_cast<double>(engineParams.moi)); writer.Key("PeakTorque"); writer.Double(static_cast<double>(engineParams.peakTorque)); writer.Key("IdleOmega"); writer.Double(static_cast<double>(engineParams.idleOmega)); writer.Key("MaxOmega"); writer.Double(static_cast<double>(engineParams.maxOmega)); writer.Key("DampingRateFullThrottle"); writer.Double(static_cast<double>(engineParams.dampingRateFullThrottle)); writer.Key("DampingRateZeroThrottleClutchEngaged"); writer.Double(double(engineParams.dampingRateZeroThrottleClutchEngaged)); writer.Key("DampingRateZeroThrottleClutchDisengaged"); writer.Double(double(engineParams.dampingRateZeroThrottleClutchDisengaged)); writer.EndObject(); return true; } bool readGearboxParams(const rapidjson::Document& config, PxVehicleGearboxParams& gearboxParams) { if (!config.HasMember("GearboxParams")) return false; if (!config["GearboxParams"].HasMember("NeutralGear")) return false; if (!config["GearboxParams"].HasMember("Ratios")) return false; if (!config["GearboxParams"].HasMember("FinalRatio")) return false; if (!config["GearboxParams"].HasMember("SwitchTime")) return false; gearboxParams.neutralGear = config["GearboxParams"]["NeutralGear"].GetInt(); gearboxParams.finalRatio = static_cast<PxReal>(config["GearboxParams"]["FinalRatio"].GetDouble()); gearboxParams.switchTime = static_cast<PxReal>(config["GearboxParams"]["SwitchTime"].GetDouble()); const rapidjson::Value& ratios = config["GearboxParams"]["Ratios"]; for(PxU32 i = 0; i < ratios.Size(); i++) { gearboxParams.ratios[i] = static_cast<PxReal>(ratios[i].GetDouble()); } gearboxParams.nbRatios = ratios.Size(); return true; } bool writeGearboxParams(const PxVehicleGearboxParams& gearboxParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("GearboxParams"); writer.StartObject(); writer.Key("NeutralGear"); writer.Int(gearboxParams.neutralGear); writer.Key("FinalRatio"); writer.Double(static_cast<double>(gearboxParams.finalRatio)); writer.Key("SwitchTime"); writer.Double(static_cast<double>(gearboxParams.switchTime)); writer.Key("Ratios"); writer.StartArray(); for(PxU32 i = 0; i < gearboxParams.nbRatios; i++) { writer.Double(static_cast<double>(gearboxParams.ratios[i])); } writer.EndArray(); writer.EndObject(); return true; } bool readMultiWheelDiffParams(const rapidjson::Value& config, PxVehicleMultiWheelDriveDifferentialParams& multiWheelDiffParams) { if (!config.HasMember("TorqueRatios")) return false; if (!config.HasMember("AveWheelSpeedRatios")) return false; const rapidjson::Value& aveWheelSpeedRatios = config["AveWheelSpeedRatios"]; const rapidjson::Value& torqueRatios = config["TorqueRatios"]; if (aveWheelSpeedRatios.Size() != torqueRatios.Size()) return false; for (PxU32 i = 0; i < aveWheelSpeedRatios.Size(); i++) { multiWheelDiffParams.aveWheelSpeedRatios[i] = static_cast<PxReal>(aveWheelSpeedRatios[i].GetDouble()); multiWheelDiffParams.torqueRatios[i] = static_cast<PxReal>(torqueRatios[i].GetDouble()); } return true; } void writeMultiWheelDiffParams (const PxVehicleMultiWheelDriveDifferentialParams& multiWheelDiffParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("TorqueRatios"); writer.StartArray(); for (PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++) { writer.Double(static_cast<double>(multiWheelDiffParams.torqueRatios[i])); } writer.EndArray(); writer.Key("AveWheelSpeedRatios"); writer.StartArray(); for (PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++) { writer.Double(static_cast<double>(multiWheelDiffParams.aveWheelSpeedRatios[i])); } writer.EndArray(); } bool readMultiWheelDifferentialParams(const rapidjson::Document& config, PxVehicleMultiWheelDriveDifferentialParams& multiWheelDifferentialParams) { multiWheelDifferentialParams.setToDefault(); if (!config.HasMember("MultiWheelDifferentialParams")) return false; if (!readMultiWheelDiffParams(config["MultiWheelDifferentialParams"], multiWheelDifferentialParams)) return false; return true; } bool writeMultiWheelDifferentialParams (const PxVehicleMultiWheelDriveDifferentialParams& multiWheelDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("MultiWheelDifferentialParams"); writer.StartObject(); writeMultiWheelDiffParams(multiWheelDifferentialParams, writer); writer.EndObject(); return true; } bool readFourWheelDifferentialParams(const rapidjson::Document& config, PxVehicleFourWheelDriveDifferentialParams& fourWheelDifferentialParams) { fourWheelDifferentialParams.setToDefault(); if (!config.HasMember("FourWheelDifferentialParams")) return false; if (!readMultiWheelDiffParams(config["FourWheelDifferentialParams"], static_cast<PxVehicleMultiWheelDriveDifferentialParams&>(fourWheelDifferentialParams))) return false; if (!config["FourWheelDifferentialParams"].HasMember("FrontWheelIds")) return false; if (!config["FourWheelDifferentialParams"].HasMember("RearWheelIds")) return false; if (!config["FourWheelDifferentialParams"].HasMember("CenterBias")) return false; if (!config["FourWheelDifferentialParams"].HasMember("CenterTarget")) return false; if (!config["FourWheelDifferentialParams"].HasMember("FrontBias")) return false; if (!config["FourWheelDifferentialParams"].HasMember("FrontTarget")) return false; if (!config["FourWheelDifferentialParams"].HasMember("RearBias")) return false; if (!config["FourWheelDifferentialParams"].HasMember("RearTarget")) return false; if (!config["FourWheelDifferentialParams"].HasMember("Rate")) return false; const rapidjson::Value& frontWheelIds = config["FourWheelDifferentialParams"]["FrontWheelIds"]; if(frontWheelIds.Size() != 2) return false; fourWheelDifferentialParams.frontWheelIds[0] = frontWheelIds[0].GetInt(); fourWheelDifferentialParams.frontWheelIds[1] = frontWheelIds[1].GetInt(); const rapidjson::Value& rearWheelIds = config["FourWheelDifferentialParams"]["RearWheelIds"]; if (rearWheelIds.Size() != 2) return false; fourWheelDifferentialParams.rearWheelIds[0] = rearWheelIds[0].GetInt(); fourWheelDifferentialParams.rearWheelIds[1] = rearWheelIds[1].GetInt(); fourWheelDifferentialParams.centerBias = static_cast<PxReal>(config["FourWheelDifferentialParams"]["CenterBias"].GetDouble()); fourWheelDifferentialParams.centerTarget = static_cast<PxReal>(config["FourWheelDifferentialParams"]["CenterTarget"].GetDouble()); fourWheelDifferentialParams.frontBias = static_cast<PxReal>(config["FourWheelDifferentialParams"]["FrontBias"].GetDouble()); fourWheelDifferentialParams.frontTarget = static_cast<PxReal>(config["FourWheelDifferentialParams"]["FrontTarget"].GetDouble()); fourWheelDifferentialParams.rearBias = static_cast<PxReal>(config["FourWheelDifferentialParams"]["RearBias"].GetDouble()); fourWheelDifferentialParams.rearTarget = static_cast<PxReal>(config["FourWheelDifferentialParams"]["RearTarget"].GetDouble()); fourWheelDifferentialParams.rate = static_cast<PxReal>(config["FourWheelDifferentialParams"]["Rate"].GetDouble()); return true; } bool writeFourWheelDifferentialParams(const PxVehicleFourWheelDriveDifferentialParams& fourWheelDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("FourWheelDifferentialParams"); writer.StartObject(); writeMultiWheelDiffParams(static_cast<const PxVehicleMultiWheelDriveDifferentialParams&>(fourWheelDifferentialParams), writer); writer.Key("FrontWheelIds"); writer.StartArray(); writer.Int(fourWheelDifferentialParams.frontWheelIds[0]); writer.Int(fourWheelDifferentialParams.frontWheelIds[1]); writer.EndArray(); writer.Key("RearWheelIds"); writer.StartArray(); writer.Int(fourWheelDifferentialParams.rearWheelIds[0]); writer.Int(fourWheelDifferentialParams.rearWheelIds[1]); writer.EndArray(); writer.Key("CenterBias"); writer.Double(static_cast<double>(fourWheelDifferentialParams.centerBias)); writer.Key("CenterTarget"); writer.Double(static_cast<double>(fourWheelDifferentialParams.centerTarget)); writer.Key("FrontBias"); writer.Double(static_cast<double>(fourWheelDifferentialParams.frontBias)); writer.Key("FrontTarget"); writer.Double(static_cast<double>(fourWheelDifferentialParams.frontTarget)); writer.Key("RearBias"); writer.Double(static_cast<double>(fourWheelDifferentialParams.rearBias)); writer.Key("RearTarget"); writer.Double(static_cast<double>(fourWheelDifferentialParams.rearTarget)); writer.Key("Rate"); writer.Double(static_cast<double>(fourWheelDifferentialParams.rate)); writer.EndObject(); return true; } bool readTankDifferentialParams(const rapidjson::Document& config, PxVehicleTankDriveDifferentialParams& tankDifferentialParams) { tankDifferentialParams.setToDefault(); if (!config.HasMember("TankDifferentialParams")) return false; if(!readMultiWheelDiffParams(config["TankDifferentialParams"], static_cast<PxVehicleMultiWheelDriveDifferentialParams&>(tankDifferentialParams))) return false; if (!config["TankDifferentialParams"].HasMember("TankTracks")) return false; const rapidjson::Value& tankTracks = config["TankDifferentialParams"]["TankTracks"]; for (PxU32 i = 0; i < tankTracks.Size(); i++) { const rapidjson::Value& tankTrack = tankTracks[i]; PxU32 wheelIds[PxVehicleLimits::eMAX_NB_WHEELS]; PxU32 nbWheels = 0; for (PxU32 j = 0; j < tankTrack.Size(); j++) { wheelIds[nbWheels] = static_cast<PxU32>(tankTrack[j].GetInt()); nbWheels++; } tankDifferentialParams.addTankTrack(nbWheels, wheelIds, i); } return true; } bool writeTankDifferentialParams(const PxVehicleTankDriveDifferentialParams& tankDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("TankDifferentialParams"); writer.StartObject(); writeMultiWheelDiffParams(static_cast<const PxVehicleMultiWheelDriveDifferentialParams&>(tankDifferentialParams), writer); writer.Key("TankTracks"); writer.StartArray(); for (PxU32 i = 0; i < tankDifferentialParams.nbTracks; i++) { writer.StartArray(); for (PxU32 j = 0; j < tankDifferentialParams.getNbWheelsInTrack(i); j++) { writer.Int(static_cast<int>(tankDifferentialParams.getWheelInTrack(j, i))); } writer.EndArray(); } writer.EndArray(); writer.EndObject(); return true; } bool reaClutchParams(const rapidjson::Document& config, PxVehicleClutchParams& clutchParams) { if (!config.HasMember("ClutchParams")) return false; if (!config["ClutchParams"].HasMember("AccuracyMode")) return false; if (!config["ClutchParams"].HasMember("EstimateIterations")) return false; clutchParams.accuracyMode = static_cast<PxVehicleClutchAccuracyMode::Enum>(config["ClutchParams"]["AccuracyMode"].GetInt()); clutchParams.estimateIterations = config["ClutchParams"]["EstimateIterations"].GetInt(); return true; } bool writeClutchParams(const PxVehicleClutchParams& clutchParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("ClutchParams"); writer.StartObject(); writer.Key("AccuracyMode"); writer.Int(static_cast<PxU32>(clutchParams.accuracyMode)); writer.Key("EstimateIterations"); writer.Int(clutchParams.estimateIterations); writer.EndObject(); return true; } bool readEngineDrivetrainParamsFromJsonFile(const char* directory, const char* filename, EngineDrivetrainParams& engineDrivetrainParams) { rapidjson::Document config; if (!openDocument(directory, filename, config)) return false; if(!readAutoboxParams(config, engineDrivetrainParams.autoboxParams)) return false; if(!readClutchCommandResponseParams(config, engineDrivetrainParams.clutchCommandResponseParams)) return false; if (!readEngineParams(config, engineDrivetrainParams.engineParams)) return false; if (!readGearboxParams(config, engineDrivetrainParams.gearBoxParams)) return false; if (!readMultiWheelDifferentialParams(config, engineDrivetrainParams.multiWheelDifferentialParams)) return false; if (!readFourWheelDifferentialParams(config, engineDrivetrainParams.fourWheelDifferentialParams)) return false; if (!readTankDifferentialParams(config, engineDrivetrainParams.tankDifferentialParams)) return false; if (!reaClutchParams(config, engineDrivetrainParams.clutchParams)) return false; return true; } bool writeEngineDrivetrainParamsToJsonFile(const char* directory, const char* filename, const EngineDrivetrainParams& engineDrivetrainParams) { rapidjson::StringBuffer strbuf; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf); writer.StartObject(); writeAutoboxParams(engineDrivetrainParams.autoboxParams, writer); writeClutchCommandResponseParams(engineDrivetrainParams.clutchCommandResponseParams, writer); writeEngineParams(engineDrivetrainParams.engineParams, writer); writeGearboxParams(engineDrivetrainParams.gearBoxParams, writer); writeMultiWheelDifferentialParams(engineDrivetrainParams.multiWheelDifferentialParams, writer); writeFourWheelDifferentialParams(engineDrivetrainParams.fourWheelDifferentialParams, writer); writeTankDifferentialParams(engineDrivetrainParams.tankDifferentialParams, writer); writeClutchParams(engineDrivetrainParams.clutchParams, writer); writer.EndObject(); std::ofstream myfile; myfile.open(std::string(directory) + "/" + filename); myfile << strbuf.GetString() << std::endl; myfile.close(); return true; } }//namespace snippetvehicle2
19,734
C++
34.687161
173
0.782102
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/EngineDrivetrainSerialization.h
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../enginedrivetrain/EngineDrivetrain.h" #if PX_SWITCH #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #elif PX_OSX #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #elif PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #if (PX_LINUX && PX_CLANG) || PX_SWITCH #pragma clang diagnostic pop #endif namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; bool readAutoboxParams(const rapidjson::Document& config, PxVehicleAutoboxParams& autoboxParams); bool writeAutoboxParams(const PxVehicleAutoboxParams& autoboxParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readClutchCommandResponseParams(const rapidjson::Document& config, PxVehicleClutchCommandResponseParams& clutchCommandResponseParams); bool writeClutchCommandResponseParams(const PxVehicleClutchCommandResponseParams& clutchCommandResponseParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readEngineParams(const rapidjson::Document& config, PxVehicleEngineParams& engineParams); bool writeEngineParams(const PxVehicleEngineParams& engineParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readGearboxParams(const rapidjson::Document& config, PxVehicleGearboxParams& gearboxParams); bool writeGearboxParams(const PxVehicleGearboxParams& gearboxParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readFourWheelDifferentialParams(const rapidjson::Document& config, PxVehicleFourWheelDriveDifferentialParams& fourWheelDifferentialParams); bool writeFourWheelDifferentialParams(const PxVehicleFourWheelDriveDifferentialParams& fourWheelDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readMultiWheelDifferentialParams(const rapidjson::Document& config, PxVehicleMultiWheelDriveDifferentialParams& multiWheelDifferentialParams); bool writeMultiWheelDifferentialParams(const PxVehicleMultiWheelDriveDifferentialParams& multiWheelDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readTankDifferentialParams(const rapidjson::Document& config, PxVehicleTankDriveDifferentialParams& tankDifferentialParams); bool writeTankDifferentialParams(const PxVehicleTankDriveDifferentialParams& tankDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool reaClutchParams(const rapidjson::Document& config, PxVehicleClutchParams& clutchParams); bool writeClutchParams(const PxVehicleClutchParams& clutchParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readEngineDrivetrainParamsFromJsonFile(const char* directory, const char* filename, EngineDrivetrainParams&); bool writeEngineDrivetrainParamsToJsonFile(const char* directory, const char* filename, const EngineDrivetrainParams&); }//namespace snippetvehicle2
4,869
C
53.719101
177
0.822756
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/BaseSerialization.cpp
// 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-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "BaseSerialization.h" #include "SerializationCommon.h" #include <fstream> #include <sstream> namespace snippetvehicle2 { bool readAxleDescription(const rapidjson::Document& config, PxVehicleAxleDescription& axleDesc) { if (!config.HasMember("AxleDescription")) return false; const PxU32 nbAxles = config["AxleDescription"].Size(); if (nbAxles > PxVehicleLimits::eMAX_NB_AXLES) return false; axleDesc.setToDefault(); //Read each axle in turn. for (PxU32 i = 0; i < nbAxles; i++) { const rapidjson::Value& axle = config["AxleDescription"][i]; if (!axle.HasMember("WheelIds")) return false; const rapidjson::Value& wheelIds = axle["WheelIds"]; const PxU32 nbWheelIds = wheelIds.Size(); if(nbWheelIds > PxVehicleLimits::eMAX_NB_WHEELS) return false; PxU32 axleWheelIds[PxVehicleLimits::eMAX_NB_WHEELS]; for (PxU32 j = 0; j < nbWheelIds; j++) { axleWheelIds[j]= wheelIds[j].GetInt(); } axleDesc.addAxle(nbWheelIds, axleWheelIds); } return true; } bool writeAxleDescription(const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("AxleDescription"); writer.StartArray(); for(PxU32 i = 0; i < axleDesc.getNbAxles(); i++) { writer.StartObject(); writer.Key("WheelIds"); writer.StartArray(); for(PxU32 j = 0; j < axleDesc.getNbWheelsOnAxle(i); j++) { writer.Int(axleDesc.getWheelOnAxle(j, i)); } writer.EndArray(); writer.EndObject(); } writer.EndArray(); return true; } bool readFrame(const rapidjson::Document& config, PxVehicleFrame& frame) { if (!config.HasMember("Frame")) return false; if (!config["Frame"].HasMember("LngAxis")) return false; if (!config["Frame"].HasMember("LatAxis")) return false; if (!config["Frame"].HasMember("VrtAxis")) return false; const PxU32 lngAxis = config["Frame"]["LngAxis"].GetInt(); const PxU32 latAxis = config["Frame"]["LatAxis"].GetInt(); const PxU32 vrtAxis = config["Frame"]["VrtAxis"].GetInt(); if ((lngAxis == latAxis) || (lngAxis == vrtAxis) || (latAxis == vrtAxis)) { return false; } frame.lngAxis = static_cast<PxVehicleAxes::Enum>(lngAxis); frame.latAxis = static_cast<PxVehicleAxes::Enum>(latAxis); frame.vrtAxis = static_cast<PxVehicleAxes::Enum>(vrtAxis); return true; } bool writeFrame(const PxVehicleFrame& frame, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("Frame"); writer.StartObject(); writer.Key("LngAxis"); writer.Int(static_cast<PxU32>(frame.lngAxis)); writer.Key("LatAxis"); writer.Int(static_cast<PxU32>(frame.latAxis)); writer.Key("VrtAxis"); writer.Int(static_cast<PxU32>(frame.vrtAxis)); writer.EndObject(); return true; } bool readScale(const rapidjson::Document& config, PxVehicleScale& scale) { if (!config.HasMember("Scale")) return false; if (!config["Scale"].HasMember("Scale")) return false; scale.scale = static_cast<PxReal>(config["Scale"]["Scale"].GetDouble()); return true; } bool writeScale(const PxVehicleScale& scale, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("Scale"); writer.StartObject(); writer.Key("Scale"); writer.Double(static_cast<double>(scale.scale)); writer.EndObject(); return true; } bool readBrakeResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleBrakeCommandResponseParams& brakeResponseParams) { if (!config.HasMember("BrakeCommandResponseParams")) return false; if (!readCommandResponseParams(config["BrakeCommandResponseParams"], axleDesc, brakeResponseParams)) return false; return true; } bool writeBrakeResponseParams (const PxVehicleBrakeCommandResponseParams& brakeResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("BrakeCommandResponseParams"); writer.StartObject(); writeCommandResponseParams(brakeResponseParams, axleDesc, writer); writer.EndObject(); return true; } bool readHandbrakeResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleBrakeCommandResponseParams& handbrakeResponseParams) { if (!config.HasMember("HandbrakeCommandResponseParams")) return false; if (!readCommandResponseParams(config["HandbrakeCommandResponseParams"], axleDesc, handbrakeResponseParams)) return false; return true; } bool writeHandbrakeResponseParams (const PxVehicleBrakeCommandResponseParams& handrakeResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("HandbrakeCommandResponseParams"); writer.StartObject(); writeCommandResponseParams(handrakeResponseParams, axleDesc, writer); writer.EndObject(); return true; } bool readSteerResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSteerCommandResponseParams& steerResponseParams) { if (!config.HasMember("SteerCommandResponseParams")) return false; if (!readCommandResponseParams(config["SteerCommandResponseParams"], axleDesc, steerResponseParams)) return false; return true; } bool writeSteerResponseParams (const PxVehicleSteerCommandResponseParams& steerResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SteerCommandResponseParams"); writer.StartObject(); writeCommandResponseParams(steerResponseParams, axleDesc, writer); writer.EndObject(); return true; } bool readAckermannParams(const rapidjson::Document& config, PxVehicleAckermannParams& ackermannParams) { if (!config.HasMember("AckermannParams")) return false; const rapidjson::Value& corrections = config["AckermannParams"]; if (!corrections.HasMember("WheelBase")) return false; if (!corrections.HasMember("TrackWidth")) return false; if (!corrections.HasMember("Strength")) return false; ackermannParams.wheelBase = static_cast<PxReal>(corrections["WheelBase"].GetDouble()); ackermannParams.trackWidth = static_cast<PxReal>(corrections["TrackWidth"].GetDouble()); ackermannParams.strength = static_cast<PxReal>(corrections["Strength"].GetDouble()); if (!corrections.HasMember("WheelIds")) return false; const rapidjson::Value& wheelIds = corrections["WheelIds"]; const PxU32 nbWheelIds = wheelIds.Size(); if (nbWheelIds != 2) return false; for (PxU32 j = 0; j < 2; j++) { ackermannParams.wheelIds[j] = wheelIds[j].GetInt(); } return true; } bool writeAckermannParams(const PxVehicleAckermannParams& ackermannParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("AckermannParams"); writer.StartObject(); writer.Key("WheelIds"); writer.StartArray(); writer.Int(ackermannParams.wheelIds[0]); writer.Int(ackermannParams.wheelIds[1]); writer.EndArray(); writer.Key("WheelBase"); writer.Double(static_cast<double>(ackermannParams.wheelBase)); writer.Key("TrackWidth"); writer.Double(static_cast<double>(ackermannParams.trackWidth)); writer.Key("Strength"); writer.Double(static_cast<double>(ackermannParams.strength)); writer.EndObject(); return true; } bool readRigidBodyParams (const rapidjson::Document& config, PxVehicleRigidBodyParams& rigidBodyParams) { if (!config.HasMember("RigidBodyParams")) return false; if (!config["RigidBodyParams"].HasMember("Mass")) return false; if (!config["RigidBodyParams"].HasMember("MOI")) return false; rigidBodyParams.mass = static_cast<PxReal>(config["RigidBodyParams"]["Mass"].GetDouble()); if (!readVec3(config["RigidBodyParams"]["MOI"], rigidBodyParams.moi)) return false; return true; } bool writeRigidBodyParams (const PxVehicleRigidBodyParams& rigidBodyParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("RigidBodyParams"); writer.StartObject(); writer.Key("Mass"); writer.Double(static_cast<double>(rigidBodyParams.mass)); writer.Key("MOI"); writeVec3(rigidBodyParams.moi, writer); writer.EndObject(); return true; } bool readSuspensionParams(const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionParams* suspParams) { if (!config.HasMember("SuspensionParams")) return false; const rapidjson::Value& suspensions = config["SuspensionParams"]; const PxU32 nbSuspensions = suspensions.Size(); if (nbSuspensions != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbSuspensions; i++) { if(!suspensions[i].HasMember("WheelId")) return false; if (!suspensions[i].HasMember("SuspensionAttachment")) return false; if (!suspensions[i].HasMember("SuspensionTravelDir")) return false; if (!suspensions[i].HasMember("SuspensionTravelDist")) return false; if (!suspensions[i].HasMember("WheelAttachment")) return false; const PxU32 wheelId = suspensions[i]["WheelId"].GetInt(); PxVehicleSuspensionParams& sp = suspParams[wheelId]; if (!readTransform(suspensions[i]["SuspensionAttachment"], sp.suspensionAttachment)) return false; if (!readVec3(suspensions[i]["SuspensionTravelDir"], sp.suspensionTravelDir)) return false; sp.suspensionTravelDist = static_cast<PxReal>(suspensions[i]["SuspensionTravelDist"].GetDouble()); if (!readTransform(suspensions[i]["WheelAttachment"], sp.wheelAttachment)) return false; } return true; } bool writeSuspensionParams(const PxVehicleSuspensionParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SuspensionParams"); writer.StartArray(); for(PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("SuspensionAttachment"); writeTransform(suspParams[wheelId].suspensionAttachment, writer); writer.Key("SuspensionTravelDir"); writeVec3(suspParams[wheelId].suspensionTravelDir, writer); writer.Key("SuspensionTravelDist"); writer.Double(static_cast<double>(suspParams[wheelId].suspensionTravelDist)); writer.Key("WheelAttachment"); writeTransform(suspParams[wheelId].wheelAttachment, writer); writer.EndObject(); } writer.EndArray(); return true; } static const char* kLimitSuspensionExpansionVelocity = "LimitSuspensionExpansionVelocity"; bool readSuspensionStateCalculationParams(const rapidjson::Document& config, PxVehicleSuspensionStateCalculationParams& suspParams) { if (!config.HasMember("SuspensionStateCalculationParams")) return false; const rapidjson::Value& suspCalcParams = config["SuspensionStateCalculationParams"]; if (!suspCalcParams.HasMember("JounceCalculationType")) return false; if (!suspCalcParams.HasMember(kLimitSuspensionExpansionVelocity)) return false; suspParams.suspensionJounceCalculationType = static_cast<PxVehicleSuspensionJounceCalculationType::Enum>(suspCalcParams["JounceCalculationType"].GetInt()); suspParams.limitSuspensionExpansionVelocity = suspCalcParams[kLimitSuspensionExpansionVelocity].GetBool(); return true; } bool writeSuspensionStateCalculationParams (const PxVehicleSuspensionStateCalculationParams& suspParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SuspensionStateCalculationParams"); writer.StartObject(); writer.Key("JounceCalculationType"); writer.Int(static_cast<PxU32>(suspParams.suspensionJounceCalculationType)); writer.Key(kLimitSuspensionExpansionVelocity); writer.Bool(suspParams.limitSuspensionExpansionVelocity); writer.EndObject(); return true; } bool readSuspensionComplianceParams(const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionComplianceParams* suspCompParams) { if (!config.HasMember("SuspensionComplianceParams")) return false; const rapidjson::Value& suspensions = config["SuspensionComplianceParams"]; const PxU32 nbSuspensions = suspensions.Size(); if (nbSuspensions != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbSuspensions; i++) { if (!suspensions[i].HasMember("WheelId")) return false; if (!suspensions[i].HasMember("WheelToeAngle")) return false; if (!suspensions[i].HasMember("WheelCamberAngle")) return false; if (!suspensions[i].HasMember("SuspForceAppPoint")) return false; if (!suspensions[i].HasMember("SuspForceAppPoint")) return false; const PxU32 wheelId = suspensions[i]["WheelId"].GetInt(); if (!readFloatLookupTable(suspensions[i]["WheelToeAngle"], suspCompParams[wheelId].wheelToeAngle)) return false; if (!readFloatLookupTable(suspensions[i]["WheelCamberAngle"], suspCompParams[wheelId].wheelCamberAngle)) return false; if (!readVec3LookupTable(suspensions[i]["SuspForceAppPoint"], suspCompParams[wheelId].suspForceAppPoint)) return false; if (!readVec3LookupTable(suspensions[i]["TireForceAppPoint"], suspCompParams[wheelId].tireForceAppPoint)) return false; } return true; } bool writeSuspensionComplianceParams (const PxVehicleSuspensionComplianceParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SuspensionComplianceParams"); writer.StartArray(); for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("WheelToeAngle"); writeFloatLookupTable(suspParams[wheelId].wheelToeAngle, writer); writer.Key("WheelCamberAngle"); writeFloatLookupTable(suspParams[wheelId].wheelCamberAngle, writer); writer.Key("SuspForceAppPoint"); writeVec3LookupTable(suspParams[wheelId].suspForceAppPoint, writer); writer.Key("TireForceAppPoint"); writeVec3LookupTable(suspParams[wheelId].tireForceAppPoint, writer); writer.EndObject(); } writer.EndArray(); return true; } bool readSuspensionForceParams(const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionForceParams* suspParams) { if (!config.HasMember("SuspensionForceParams")) return false; const rapidjson::Value& suspensions = config["SuspensionForceParams"]; const PxU32 nbSuspensions = suspensions.Size(); if (nbSuspensions != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbSuspensions; i++) { if (!suspensions[i].HasMember("WheelId")) return false; if (!suspensions[i].HasMember("Damping")) return false; if (!suspensions[i].HasMember("Stiffness")) return false; if (!suspensions[i].HasMember("SprungMass")) return false; const PxU32 wheelId = suspensions[i]["WheelId"].GetInt(); suspParams[wheelId].damping = static_cast<PxReal>(suspensions[i]["Damping"].GetDouble()); suspParams[wheelId].stiffness = static_cast<PxReal>(suspensions[i]["Stiffness"].GetDouble()); suspParams[wheelId].sprungMass = static_cast<PxReal>(suspensions[i]["SprungMass"].GetDouble()); } return true; } bool writeSuspensionForceParams (const PxVehicleSuspensionForceParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SuspensionForceParams"); writer.StartArray(); for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("Damping"); writer.Double(double(suspParams[wheelId].damping)); writer.Key("Stiffness"); writer.Double(double(suspParams[wheelId].stiffness)); writer.Key("SprungMass"); writer.Double(double(suspParams[wheelId].sprungMass)); writer.EndObject(); } writer.EndArray(); return true; } bool readTireForceParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleTireForceParams* tireParams) { if (!config.HasMember("TireForceParams")) return false; const rapidjson::Value& tires = config["TireForceParams"]; const PxU32 nbTires = tires.Size(); if (nbTires != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbTires; i++) { if (!tires[i].HasMember("WheelId")) return false; if (!tires[i].HasMember("LongitudinalStiffness")) return false; if (!tires[i].HasMember("LateralStiffnessX")) return false; if (!tires[i].HasMember("LateralStiffnessY")) return false; if (!tires[i].HasMember("CamberStiffness")) return false; if (!tires[i].HasMember("RestLoad")) return false; if (!tires[i].HasMember("FrictionVsSlip")) return false; if (!tires[i].HasMember("TireLoadFilter")) return false; const PxU32 wheelId = tires[i]["WheelId"].GetInt(); tireParams[wheelId].longStiff = static_cast<PxReal>(tires[i]["LongitudinalStiffness"].GetDouble()); tireParams[wheelId].latStiffX = static_cast<PxReal>(tires[i]["LateralStiffnessX"].GetDouble()); tireParams[wheelId].latStiffY = static_cast<PxReal>(tires[i]["LateralStiffnessY"].GetDouble()); tireParams[wheelId].camberStiff = static_cast<PxReal>(tires[i]["CamberStiffness"].GetDouble()); tireParams[wheelId].restLoad = static_cast<PxReal>(tires[i]["RestLoad"].GetDouble()); const rapidjson::Value& frictionVsSlip = tires[i]["FrictionVsSlip"]; if (frictionVsSlip.Size() != 3) return false; for (PxU32 j = 0; j < 3; j++) { const rapidjson::Value& element = tires[i]["FrictionVsSlip"][j]; if (element.Size() != 2) return false; tireParams[wheelId].frictionVsSlip[j][0] = static_cast<PxReal>(element[0].GetDouble()); tireParams[wheelId].frictionVsSlip[j][1] = static_cast<PxReal>(element[1].GetDouble()); } const rapidjson::Value& tireLoadFilter = tires[i]["TireLoadFilter"]; if (tireLoadFilter.Size() != 2) return false; for (PxU32 j = 0; j < 2; j++) { const rapidjson::Value& element = tires[i]["TireLoadFilter"][j]; if (element.Size() != 2) return false; tireParams[wheelId].loadFilter[j][0] = static_cast<PxReal>(element[0].GetDouble()); tireParams[wheelId].loadFilter[j][1] = static_cast<PxReal>(element[1].GetDouble()); } } return true; } bool writeTireForceParams (const PxVehicleTireForceParams* tireParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("TireForceParams"); writer.StartArray(); for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("LongitudinalStiffness"); writer.Double(static_cast<double>(tireParams[wheelId].longStiff)); writer.Key("LateralStiffnessX"); writer.Double(static_cast<double>(tireParams[wheelId].latStiffX)); writer.Key("LateralStiffnessY"); writer.Double(static_cast<double>(tireParams[wheelId].latStiffY)); writer.Key("CamberStiffness"); writer.Double(static_cast<double>(tireParams[wheelId].camberStiff)); writer.Key("RestLoad"); writer.Double(static_cast<double>(tireParams[wheelId].restLoad)); writer.Key("FrictionVsSlip"); writer.StartArray(); for(PxU32 k = 0; k < 3; k++) { writer.StartArray(); writer.Double(static_cast<double>(tireParams[wheelId].frictionVsSlip[k][0])); writer.Double(static_cast<double>(tireParams[wheelId].frictionVsSlip[k][1])); writer.EndArray(); } writer.EndArray(); writer.Key("TireLoadFilter"); writer.StartArray(); for (PxU32 k = 0; k < 2; k++) { writer.StartArray(); writer.Double(static_cast<double>(tireParams[wheelId].loadFilter[k][0])); writer.Double(static_cast<double>(tireParams[wheelId].loadFilter[k][1])); writer.EndArray(); } writer.EndArray(); writer.EndObject(); } writer.EndArray(); return true; } bool readWheelParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleWheelParams* wheelParams) { if (!config.HasMember("WheelParams")) return false; const rapidjson::Value& wheels = config["WheelParams"]; const PxU32 nbWheels = wheels.Size(); if (nbWheels != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbWheels; i++) { if (!wheels[i].HasMember("WheelId")) return false; if (!wheels[i].HasMember("HalfWidth")) return false; if (!wheels[i].HasMember("Radius")) return false; if (!wheels[i].HasMember("Mass")) return false; if (!wheels[i].HasMember("MOI")) return false; if (!wheels[i].HasMember("DampingRate")) return false; const PxU32 wheelId = wheels[i]["WheelId"].GetInt(); wheelParams[wheelId].halfWidth = static_cast<PxReal>(wheels[i]["HalfWidth"].GetDouble()); wheelParams[wheelId].radius = static_cast<PxReal>(wheels[i]["Radius"].GetDouble()); wheelParams[wheelId].mass = static_cast<PxReal>(wheels[i]["Mass"].GetDouble()); wheelParams[wheelId].moi = static_cast<PxReal>(wheels[i]["MOI"].GetDouble()); wheelParams[wheelId].dampingRate = static_cast<PxReal>(wheels[i]["DampingRate"].GetDouble()); } return true; } bool writeWheelParams (const PxVehicleWheelParams* wheelParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("WheelParams"); writer.StartArray(); for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("HalfWidth"); writer.Double(static_cast<double>(wheelParams[wheelId].halfWidth)); writer.Key("Radius"); writer.Double(static_cast<double>(wheelParams[wheelId].radius)); writer.Key("Mass"); writer.Double(static_cast<double>(wheelParams[wheelId].mass)); writer.Key("MOI"); writer.Double(static_cast<double>(wheelParams[wheelId].moi)); writer.Key("DampingRate"); writer.Double(static_cast<double>(wheelParams[wheelId].dampingRate)); writer.EndObject(); } writer.EndArray(); return true; } bool readBaseParamsFromJsonFile(const char* directory, const char* filename, BaseVehicleParams& baseParams) { rapidjson::Document config; if (!openDocument(directory, filename, config)) return false; ////////////////////////////// //Read the high level params ////////////////////////////// PxMemSet(&baseParams.axleDescription, 0xff, sizeof(baseParams.axleDescription)); if (!readAxleDescription(config, baseParams.axleDescription)) return false; PxMemSet(&baseParams.frame, 0xff, sizeof(baseParams.frame)); if (!readFrame(config, baseParams.frame)) return false; PxMemSet(&baseParams.scale, 0xff, sizeof(baseParams.scale)); if (!readScale(config, baseParams.scale)) return false; ////////////////////////////// //Read the rigid body params ///////////////////////////// PxMemSet(&baseParams.rigidBodyParams, 0xff, sizeof(baseParams.rigidBodyParams)); if (!readRigidBodyParams(config, baseParams.rigidBodyParams)) return false; ////////////////////////////// //Read the suspension state calculation params. ////////////////////////////// PxMemSet(&baseParams.suspensionStateCalculationParams, 0xff, sizeof(baseParams.suspensionStateCalculationParams)); if (!readSuspensionStateCalculationParams(config, baseParams.suspensionStateCalculationParams)) return false; /////////////////////////////// //Read the command responses /////////////////////////////// PxMemSet(&baseParams.brakeResponseParams[0], 0xff, sizeof(baseParams.brakeResponseParams[0])); if (!readBrakeResponseParams(config, baseParams.axleDescription, baseParams.brakeResponseParams[0])) return false; PxMemSet(&baseParams.brakeResponseParams[1], 0xff, sizeof(baseParams.brakeResponseParams[1])); if (!readHandbrakeResponseParams(config, baseParams.axleDescription, baseParams.brakeResponseParams[1])) return false; PxMemSet(&baseParams.steerResponseParams, 0xff, sizeof(baseParams.steerResponseParams)); if (!readSteerResponseParams(config, baseParams.axleDescription, baseParams.steerResponseParams)) return false; PxMemSet(&baseParams.ackermannParams, 0xff, sizeof(baseParams.ackermannParams)); if (!readAckermannParams(config, baseParams.ackermannParams[0])) return false; /////////////////////////////////// //Read the suspension params /////////////////////////////////// PxMemSet(baseParams.suspensionParams, 0xff, sizeof(baseParams.suspensionParams)); if (!readSuspensionParams(config, baseParams.axleDescription, baseParams.suspensionParams)) return false; PxMemSet(baseParams.suspensionComplianceParams, 0x00, sizeof(baseParams.suspensionComplianceParams)); if (!readSuspensionComplianceParams(config, baseParams.axleDescription, baseParams.suspensionComplianceParams)) return false; PxMemSet(baseParams.suspensionForceParams, 0xff, sizeof(baseParams.suspensionForceParams)); if (!readSuspensionForceParams(config, baseParams.axleDescription, baseParams.suspensionForceParams)) return false; /////////////////////////////////// //Read the tire params /////////////////////////////////// PxMemSet(baseParams.tireForceParams, 0xff, sizeof(baseParams.tireForceParams)); if (!readTireForceParams(config, baseParams.axleDescription, baseParams.tireForceParams)) return false; ////////////////////////// //Read the wheel params ////////////////////////// PxMemSet(baseParams.wheelParams, 0xff, sizeof(baseParams.wheelParams)); if (!readWheelParams(config, baseParams.axleDescription, baseParams.wheelParams)) return false; return true; } bool writeBaseParamsToJsonFile(const char* directory, const char* filename, const BaseVehicleParams& baseParams) { rapidjson::StringBuffer strbuf; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf); writer.StartObject(); ////////////////////////////// //Write the high level params ////////////////////////////// writeAxleDescription(baseParams.axleDescription, writer); writeFrame(baseParams.frame, writer); writeScale(baseParams.scale, writer); ////////////////////////////// //Write the rigid body params ///////////////////////////// writeRigidBodyParams(baseParams.rigidBodyParams, writer); ////////////////////////////// //Write the suspension state calculation params ////////////////////////////// writeSuspensionStateCalculationParams(baseParams.suspensionStateCalculationParams, writer); /////////////////////////////// //Write the command responses /////////////////////////////// writeBrakeResponseParams(baseParams.brakeResponseParams[0], baseParams.axleDescription, writer); writeHandbrakeResponseParams(baseParams.brakeResponseParams[1], baseParams.axleDescription, writer); writeSteerResponseParams(baseParams.steerResponseParams, baseParams.axleDescription, writer); writeAckermannParams(baseParams.ackermannParams[0], writer); /////////////////////////////////// //Write the suspension params /////////////////////////////////// writeSuspensionParams(baseParams.suspensionParams, baseParams.axleDescription, writer); writeSuspensionComplianceParams(baseParams.suspensionComplianceParams, baseParams.axleDescription, writer); writeSuspensionForceParams(baseParams.suspensionForceParams, baseParams.axleDescription, writer); /////////////////////////////////// //Write the tire params /////////////////////////////////// writeTireForceParams(baseParams.tireForceParams, baseParams.axleDescription, writer); ////////////////////////// //Write the wheel params ////////////////////////// writeWheelParams(baseParams.wheelParams, baseParams.axleDescription, writer); writer.EndObject(); std::ofstream myfile; myfile.open(std::string(directory) + "/" + filename); myfile << strbuf.GetString() << std::endl; myfile.close(); return true; } }//namespace snippetvehicle2
29,295
C++
31.052516
165
0.735006
NVIDIA-Omniverse/PhysX/physx/snippets/snippetarticulationrc/SnippetArticulation.cpp
// 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-2023 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 demonstrates the use of Reduced Coordinates articulations. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxArticulationReducedCoordinate* gArticulation = NULL; static PxArticulationJointReducedCoordinate* gDriveJoint = NULL; static PxFilterFlags scissorFilter( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(attributes1); PX_UNUSED(constantBlock); PX_UNUSED(constantBlockSize); if (filterData0.word2 != 0 && filterData0.word2 == filterData1.word2) return PxFilterFlag::eKILL; pairFlags |= PxPairFlag::eCONTACT_DEFAULT; return PxFilterFlag::eDEFAULT; } static void createScissorLift() { const PxReal runnerLength = 2.f; const PxReal placementDistance = 1.8f; const PxReal cosAng = (placementDistance) / (runnerLength); const PxReal angle = PxAcos(cosAng); const PxReal sinAng = PxSin(angle); const PxQuat leftRot(-angle, PxVec3(1.f, 0.f, 0.f)); const PxQuat rightRot(angle, PxVec3(1.f, 0.f, 0.f)); //(1) Create base... PxArticulationLink* base = gArticulation->createLink(NULL, PxTransform(PxVec3(0.f, 0.25f, 0.f))); PxRigidActorExt::createExclusiveShape(*base, PxBoxGeometry(0.5f, 0.25f, 1.5f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*base, 3.f); //Now create the slider and fixed joints... gArticulation->setSolverIterationCounts(32); PxArticulationLink* leftRoot = gArticulation->createLink(base, PxTransform(PxVec3(0.f, 0.55f, -0.9f))); PxRigidActorExt::createExclusiveShape(*leftRoot, PxBoxGeometry(0.5f, 0.05f, 0.05f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftRoot, 1.f); PxArticulationLink* rightRoot = gArticulation->createLink(base, PxTransform(PxVec3(0.f, 0.55f, 0.9f))); PxRigidActorExt::createExclusiveShape(*rightRoot, PxBoxGeometry(0.5f, 0.05f, 0.05f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightRoot, 1.f); PxArticulationJointReducedCoordinate* joint = static_cast<PxArticulationJointReducedCoordinate*>(leftRoot->getInboundJoint()); joint->setJointType(PxArticulationJointType::eFIX); joint->setParentPose(PxTransform(PxVec3(0.f, 0.25f, -0.9f))); joint->setChildPose(PxTransform(PxVec3(0.f, -0.05f, 0.f))); //Set up the drive joint... gDriveJoint = static_cast<PxArticulationJointReducedCoordinate*>(rightRoot->getInboundJoint()); gDriveJoint->setJointType(PxArticulationJointType::ePRISMATIC); gDriveJoint->setMotion(PxArticulationAxis::eZ, PxArticulationMotion::eLIMITED); gDriveJoint->setLimitParams(PxArticulationAxis::eZ, PxArticulationLimit(-1.4f, 0.2f)); gDriveJoint->setDriveParams(PxArticulationAxis::eZ, PxArticulationDrive(100000.f, 0.f, PX_MAX_F32)); gDriveJoint->setParentPose(PxTransform(PxVec3(0.f, 0.25f, 0.9f))); gDriveJoint->setChildPose(PxTransform(PxVec3(0.f, -0.05f, 0.f))); const PxU32 linkHeight = 3; PxArticulationLink* currLeft = leftRoot, *currRight = rightRoot; PxQuat rightParentRot(PxIdentity); PxQuat leftParentRot(PxIdentity); for (PxU32 i = 0; i < linkHeight; ++i) { const PxVec3 pos(0.5f, 0.55f + 0.1f*(1 + i), 0.f); PxArticulationLink* leftLink = gArticulation->createLink(currLeft, PxTransform(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), leftRot)); PxRigidActorExt::createExclusiveShape(*leftLink, PxBoxGeometry(0.05f, 0.05f, 1.f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftLink, 1.f); const PxVec3 leftAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), -0.9f); joint = static_cast<PxArticulationJointReducedCoordinate*>(leftLink->getInboundJoint()); joint->setParentPose(PxTransform(currLeft->getGlobalPose().transformInv(leftAnchorLocation), leftParentRot)); joint->setChildPose(PxTransform(PxVec3(0.f, 0.f, -1.f), rightRot)); joint->setJointType(PxArticulationJointType::eREVOLUTE); leftParentRot = leftRot; joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eLIMITED); joint->setLimitParams(PxArticulationAxis::eTWIST, PxArticulationLimit(-PxPi, angle)); PxArticulationLink* rightLink = gArticulation->createLink(currRight, PxTransform(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), rightRot)); PxRigidActorExt::createExclusiveShape(*rightLink, PxBoxGeometry(0.05f, 0.05f, 1.f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightLink, 1.f); const PxVec3 rightAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), 0.9f); joint = static_cast<PxArticulationJointReducedCoordinate*>(rightLink->getInboundJoint()); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setParentPose(PxTransform(currRight->getGlobalPose().transformInv(rightAnchorLocation), rightParentRot)); joint->setChildPose(PxTransform(PxVec3(0.f, 0.f, 1.f), leftRot)); joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eLIMITED); joint->setLimitParams(PxArticulationAxis::eTWIST, PxArticulationLimit(-angle, PxPi)); rightParentRot = rightRot; PxD6Joint* d6joint = PxD6JointCreate(*gPhysics, leftLink, PxTransform(PxIdentity), rightLink, PxTransform(PxIdentity)); d6joint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); currLeft = rightLink; currRight = leftLink; } PxArticulationLink* leftTop = gArticulation->createLink(currLeft, currLeft->getGlobalPose().transform(PxTransform(PxVec3(-0.5f, 0.f, -1.0f), leftParentRot))); PxRigidActorExt::createExclusiveShape(*leftTop, PxBoxGeometry(0.5f, 0.05f, 0.05f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftTop, 1.f); PxArticulationLink* rightTop = gArticulation->createLink(currRight, currRight->getGlobalPose().transform(PxTransform(PxVec3(-0.5f, 0.f, 1.0f), rightParentRot))); PxRigidActorExt::createExclusiveShape(*rightTop, PxCapsuleGeometry(0.05f, 0.8f), *gMaterial); //PxRigidActorExt::createExclusiveShape(*rightTop, PxBoxGeometry(0.5f, 0.05f, 0.05f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightTop, 1.f); joint = static_cast<PxArticulationJointReducedCoordinate*>(leftTop->getInboundJoint()); joint->setParentPose(PxTransform(PxVec3(0.f, 0.f, -1.f), currLeft->getGlobalPose().q.getConjugate())); joint->setChildPose(PxTransform(PxVec3(0.5f, 0.f, 0.f), leftTop->getGlobalPose().q.getConjugate())); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eFREE); joint = static_cast<PxArticulationJointReducedCoordinate*>(rightTop->getInboundJoint()); joint->setParentPose(PxTransform(PxVec3(0.f, 0.f, 1.f), currRight->getGlobalPose().q.getConjugate())); joint->setChildPose(PxTransform(PxVec3(0.5f, 0.f, 0.f), rightTop->getGlobalPose().q.getConjugate())); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eFREE); currLeft = leftRoot; currRight = rightRoot; rightParentRot = PxQuat(PxIdentity); leftParentRot = PxQuat(PxIdentity); for (PxU32 i = 0; i < linkHeight; ++i) { const PxVec3 pos(-0.5f, 0.55f + 0.1f*(1 + i), 0.f); PxArticulationLink* leftLink = gArticulation->createLink(currLeft, PxTransform(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), leftRot)); PxRigidActorExt::createExclusiveShape(*leftLink, PxBoxGeometry(0.05f, 0.05f, 1.f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftLink, 1.f); const PxVec3 leftAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), -0.9f); joint = static_cast<PxArticulationJointReducedCoordinate*>(leftLink->getInboundJoint()); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setParentPose(PxTransform(currLeft->getGlobalPose().transformInv(leftAnchorLocation), leftParentRot)); joint->setChildPose(PxTransform(PxVec3(0.f, 0.f, -1.f), rightRot)); leftParentRot = leftRot; joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eLIMITED); joint->setLimitParams(PxArticulationAxis::eTWIST, PxArticulationLimit(-PxPi, angle)); PxArticulationLink* rightLink = gArticulation->createLink(currRight, PxTransform(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), rightRot)); PxRigidActorExt::createExclusiveShape(*rightLink, PxBoxGeometry(0.05f, 0.05f, 1.f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightLink, 1.f); const PxVec3 rightAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), 0.9f); /*joint = PxD6JointCreate(getPhysics(), currRight, PxTransform(currRight->getGlobalPose().transformInv(rightAnchorLocation)), rightLink, PxTransform(PxVec3(0.f, 0.f, 1.f)));*/ joint = static_cast<PxArticulationJointReducedCoordinate*>(rightLink->getInboundJoint()); joint->setParentPose(PxTransform(currRight->getGlobalPose().transformInv(rightAnchorLocation), rightParentRot)); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setChildPose(PxTransform(PxVec3(0.f, 0.f, 1.f), leftRot)); joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eLIMITED); joint->setLimitParams(PxArticulationAxis::eTWIST, PxArticulationLimit(-angle, PxPi)); rightParentRot = rightRot; PxD6Joint* d6joint = PxD6JointCreate(*gPhysics, leftLink, PxTransform(PxIdentity), rightLink, PxTransform(PxIdentity)); d6joint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); currLeft = rightLink; currRight = leftLink; } PxD6Joint* d6joint = PxD6JointCreate(*gPhysics, currLeft, PxTransform(PxVec3(0.f, 0.f, -1.f)), leftTop, PxTransform(PxVec3(-0.5f, 0.f, 0.f))); d6joint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); d6joint = PxD6JointCreate(*gPhysics, currRight, PxTransform(PxVec3(0.f, 0.f, 1.f)), rightTop, PxTransform(PxVec3(-0.5f, 0.f, 0.f))); d6joint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); const PxTransform topPose(PxVec3(0.f, leftTop->getGlobalPose().p.y + 0.15f, 0.f)); PxArticulationLink* top = gArticulation->createLink(leftTop, topPose); PxRigidActorExt::createExclusiveShape(*top, PxBoxGeometry(0.5f, 0.1f, 1.5f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*top, 1.f); joint = static_cast<PxArticulationJointReducedCoordinate*>(top->getInboundJoint()); joint->setJointType(PxArticulationJointType::eFIX); joint->setParentPose(PxTransform(PxVec3(0.f, 0.0f, 0.f))); joint->setChildPose(PxTransform(PxVec3(0.f, -0.15f, -0.9f))); gScene->addArticulation(*gArticulation); for (PxU32 i = 0; i < gArticulation->getNbLinks(); ++i) { PxArticulationLink* link; gArticulation->getLinks(&link, 1, i); link->setLinearDamping(0.2f); link->setAngularDamping(0.2f); link->setMaxAngularVelocity(20.f); link->setMaxLinearVelocity(100.f); if (link != top) { for (PxU32 b = 0; b < link->getNbShapes(); ++b) { PxShape* shape; link->getShapes(&shape, 1, b); shape->setSimulationFilterData(PxFilterData(0, 0, 1, 0)); } } } const PxVec3 halfExt(0.25f); const PxReal density(0.5f); PxRigidDynamic* box0 = gPhysics->createRigidDynamic(PxTransform(PxVec3(-0.25f, 5.f, 0.5f))); PxShape* shape0 = PxRigidActorExt::createExclusiveShape(*box0, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box0, density); gScene->addActor(*box0); PxRigidDynamic* box1 = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.25f, 5.f, 0.5f))); PxShape* shape1 = PxRigidActorExt::createExclusiveShape(*box1, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box1, density); gScene->addActor(*box1); PxRigidDynamic* box2 = gPhysics->createRigidDynamic(PxTransform(PxVec3(-0.25f, 4.5f, 0.5f))); PxShape* shape2 = PxRigidActorExt::createExclusiveShape(*box2, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box2, density); gScene->addActor(*box2); PxRigidDynamic* box3 = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.25f, 4.5f, 0.5f))); PxShape* shape3 = PxRigidActorExt::createExclusiveShape(*box3, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box3, density); gScene->addActor(*box3); PxRigidDynamic* box4 = gPhysics->createRigidDynamic(PxTransform(PxVec3(-0.25f, 5.f, 0.f))); PxShape* shape4 = PxRigidActorExt::createExclusiveShape(*box4, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box4, density); gScene->addActor(*box4); PxRigidDynamic* box5 = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.25f, 5.f, 0.f))); PxShape* shape5 = PxRigidActorExt::createExclusiveShape(*box5, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box5, density); gScene->addActor(*box5); PxRigidDynamic* box6 = gPhysics->createRigidDynamic(PxTransform(PxVec3(-0.25f, 4.5f, 0.f))); PxShape* shape6 = PxRigidActorExt::createExclusiveShape(*box6, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box6, density); gScene->addActor(*box6); PxRigidDynamic* box7 = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.25f, 4.5f, 0.f))); PxShape* shape7 = PxRigidActorExt::createExclusiveShape(*box7, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box7, density); gScene->addActor(*box7); const float contactOffset = 0.2f; shape0->setContactOffset(contactOffset); shape1->setContactOffset(contactOffset); shape2->setContactOffset(contactOffset); shape3->setContactOffset(contactOffset); shape4->setContactOffset(contactOffset); shape5->setContactOffset(contactOffset); shape6->setContactOffset(contactOffset); shape7->setContactOffset(contactOffset); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.solverType = PxSolverType::eTGS; sceneDesc.filterShader = scissorFilter; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); gArticulation = gPhysics->createArticulationReducedCoordinate(); createScissorLift(); } static bool gClosing = true; void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; PxReal driveValue = gDriveJoint->getDriveTarget(PxArticulationAxis::eZ); if (gClosing && driveValue < -1.2f) gClosing = false; else if (!gClosing && driveValue > 0.f) gClosing = true; if (gClosing) driveValue -= dt*0.25f; else driveValue += dt*0.25f; gDriveJoint->setDriveTarget(PxArticulationAxis::eZ, driveValue); gScene->simulate(dt); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { gArticulation->release(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); PX_RELEASE(gPvd); PX_RELEASE(transport); PxCloseExtensions(); PX_RELEASE(gFoundation); printf("SnippetArticulation done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
18,854
C++
42.344827
162
0.752413