==================
Exchange-Parasolid
==================

Designed to facilitate CAD conversion and geometric modeling in a single interface, the Exchange-Parasolid Sprocket is useful for developers who wish to load files using HOOPS Exchange and then interact with the geometry in the scene using the Parasolid modeling kernel.

The Exchange-Parasolid Sprocket is available on Windows, Linux, and MacOS platforms, and you must have a license for both Exchange and Parasolid in order to use the sprocket.

|HPSNOW|, Exchange, and Parasolid interact with each other in the following manner:

#. |HPSNOW| displays the model on screen, builds a Component structure, provides the user access to Parasolid and Exchange data, and keeps the Parasolid data, Exchange data, Component structure, and visual rendition synchronized.
#. Exchange loads and translates the model and manages Views, PMI, and the assembly structure.
#. Parasolid tessellates the model and performs modeling operations.

Throughout this guide, we sometimes refer to "PRC" -- this refers to the intermediate CAD data format used by Exchange during file conversion. In |HPSNOW|, PRC also forms the basis of the Component structure used in the Exchange-Parasolid Sprocket. For more information on PRC, see the `HOOPS Exchange documentation <https://docs.techsoft3d.com/exchange/latest>`_ or the `PRC specification <https://docs.techsoft3d.com/exchange/latest/SC2N570-PRC-WD.pdf>`_ itself.


Prerequisites
=============

To satisfy the prerequisites, users should complete the prerequisite steps for both the :doc:`Exchange <0906_exchange_integration>` and :doc:`Parasolid <0907_parasolid>` sprockets.


File Loading and Translation
============================

When using the Exchange-Parasolid Sprocket, the contents of each Exchange Representation Item is translated to Parasolid. The 
translation process takes place automatically as part of the import and is configurable by the user. Since the geometry being inserted 
into the scene will be tessellated by Parasolid, Parasolid tessellation settings also need to be provided.

Since |HPSNOW|'s Parasolid integration supports convergent modeling, even files without B-rep can be loaded and translated to Parasolid, if the format is supported by Exchange.

This is a basic example of loading and translating a file with default options:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_default_load.cpp
		   :start-after: //! [import_default_options]
		   :end-before: //! [import_default_options]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_default_load.cs
		   :start-after: //! [import_default_options]
		   :end-before: //! [import_default_options]
		   
The usual caveats described in the other Sprocket guides still apply here:

* The user can call ``HPS::IONotifier::Wait()`` on the notifier to wait until after the import has completed. The import happens on a separate thread, and it is not guaranteed to be completed until after ``HPS::IONotifier::Wait()`` returns or until the ``HPS::IONotifier::Status()`` call returns something other than ``HPS::Event::Status::InProgress``.
* The import can be canceled by calling ``HPS::IONotifier::Cancel()`` on the notifier.
* The import status can be queried while the import is in progress.


Options for File Loading
------------------------

The :ref:`Options for file loading <prog_guide/0906_exchange_integration:Options for File Loading>` section in the Exchange Sprocket Programming Guide also applies to the Exchange-Parasolid Sprocket. As the sample above shows there are several options kit which need to be passed to the ``HPS::ExchangeParasolid::File::Import()`` function call:

#. An ``HPS::Exchange::ImportOptionsKit``. This kit determines how the file is read by Exchange. The options specified in the Exchange Sprocket sections still apply (for example, calling ``HPS::Exchange::ImportOptionsKit::SetPMI()`` on this kit will result in PMIs not being imported).
	
#. An ``HPS::Exchange::TranslationOptionsKit``. This kit determines how the file is translated into Parasolid, and optionally performs some functions such as sewing and healing. It's worth noting that one of the options allows users to use multiple processes to translate the data, speeding up the process. See the function ``HPS::Exchange::TranslationOptionsKit::SetMultiProcessCount`` for more information.
	
#. A ``HPS::Parasolid::FacetTessellationKit`` and a ``HPS::Parasolid::LineTessellationKit``. These kits determine how Parasolid will tessellate facets and lines respectively. The description of these kits is the same as the one found in the :ref:`Import options <prog_guide/0907_parasolid:Import options>` section of the Parasolid programming guide. It is worth noting that if you don't need to fine tune all the tessellation options, you can just call the ``HPS::Parasolid::FacetTessellationKit::SetTessellationLevel()`` function from the ``HPS::Parasolid::FacetTessellationKit``, and use the default ``HPS::Parasolid::LineTessellationKit``. This way the two are guaranteed to be compatible. (When these kits are not compatible, it can result in lines that do not exactly lie on faces or lines that are tessellated more coarsely than the faces they belong to.)


Importing Multiple Models
=========================

Multiple models can be imported into the same scene using the same functionality described in :ref:`Importing multiple models <prog_guide/0906_exchange_integration:Importing multiple models>` in the Exchange Programming Guide.

**Note:** When importing multiple models, the Parasolid entities from all models in the same scene are placed in the 
same Parasolid partition.


Component Structure of Exchange-Parasolid Files
-----------------------------------------------

* The top of the component structure for Exchange-Parasolid files will be an ``HPS::Exchange::CADModel``.
	
* From there the component structure will continue as expected for an Exchange file: the CADModel will contain Product Occurrence components, which will in turn contain either other Product Occurrence components or a Part Definition component. Part Definition components will contain Representation Item components.
	
* When importing a model through Exchange-Parasolid, components under the Representation Item level will all be Parasolid components. For example, Representation Item components will contain Parasolid Topological Body components. 
	
* The component structure will still contain Views and Filters if the original CAD file contained them.


Sample Component Structure of an Exchange-Parasolid File
--------------------------------------------------------

The following graphic demonstrates a hypothetical Component structure for an Exchange-Parasolid file:

.. image:: images/exchange_parasolid_component_structure.png

*A sample of a Component structure in a hypothetical CAD model imported into the Exchange-Parasolid Sprocket.*

The most important aspect of this structure is that the Exchange representation item will always contain a single Parasolid topological body (and not a Parasolid assembly or other data). In the next section, we'll look at a sample that shows how to use the function ``HPS::Component::GetSubcomponents()`` to retrieve these elements.


.. _para_exch:

Accessing Parasolid and Exchange Data
=====================================

By using the the |HPSNOW| Component structure, it's possible to gain access to Exchange or Parasolid entities directly. You can then 
operate on these entities using the native Exchange and Parasolid APIs.

The first step in this process is to find the component we are interested in. Each component can query its parent and children component 
through its ``HPS::Component::GetOwners()`` and ``HPS::Component::GetSubcomponents()`` functions. It can also query all its descendants of a particular type by calling ``HPS::Component::GetAllSubcomponents()``.

The type of a component can be found using the ``HPS::Component::GetComponentType()`` function, and the result can be checked against the ``HPS::Component::ComponentType`` enumeration. The ``HPS::Component`` class also contains the ``HPS::Component::HasComponentType()`` function, which allows us to check against a bitmask. For example, the function can be used to determine whether a component is an Exchange or a Parasolid component, or whether the component represents any of the topological items supported by Exchange or Parasolid.

Once an interesting component has been located, we can access its underlying data. For Exchange components, we create an 
``HPS::Exchange::Component`` from the Component object, and call ``HPS::Exchange::Component::GetExchangeEntity()``. For Parasolid components, we create an ``HPS::Parasolid::Component`` from the component object, and call ``HPS::Parasolid::Component::GetParasolidEntity()``.

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_query_model.cpp
		   :start-after: //! [query_cad_model]
		   :end-before: //! [query_cad_model]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_query_model.cs
		   :start-after: //! [query_cad_model]
		   :end-before: //! [query_cad_model]
		   

.. _para_update:

Updating the Model after Parasolid Modeling Operations
======================================================

After a modelling operation takes place in Parasolid, |HPSNOW| will have to be notified about which Parasolid bodies have changed, 
so that they can be retessellated and have their component structure updated to reflect their new status.

This can be done through the ``HPS::ExchangeParasolid::File::Tessellate()`` function or the ``HPS::Parasolid::Component::Tessellate()`` function.

**Note:** Currently the ``HPS::Parasolid::Component::Tessellate()`` and ``HPS::ExchangeParasolid::File::Tessellate()`` functions update |HPSNOW| to reflect the changes made in Parasolid. This function does NOT however update the PRC representation of the model held by Exchange. Therefore, after calling either of these Tessellate functions, in order to export an accurate representation of the model, use the Parasolid API (e.g., ``PK_PART_transmit``) and reload the model into |HPSNOW| from disk.

The following code sample demonstrates how to add a fillet to an edge of a model and retessellate it using the native Parasolid API:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_fillet_retessellate.cpp
		   :start-after: //! [fillet_retessellate]
		   :end-before: //! [fillet_retessellate]
		   
	.. group-tab:: C#
	
		.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_fillet_retessellate.cs
		   :start-after: //! [fillet_retessellate]
		   :end-before: //! [fillet_retessellate]

Here is the output when applying this code to a simple cube; the edge on the left is where the fillet has been applied:

.. image:: images/cube_tessellate.png

*A sample of a Component structure in a hypothetical CAD model imported into the Exchange-Parasolid Sprocket.*


.. _create_geometry:

Creating Geometry in Memory Using Parasolid and Adding It to the Scene
======================================================================

**Note:** This is the Exchange-Parasolid equivalent of the :ref:`Entity Creation <prog_guide/0907_parasolid:Entity creation>` section of the Parasolid Programming Guide.

Sometimes you may want to create a model from scratch instead of loading one, or other times you may want to create some geometry from scratch and then add it to an existing model you've already loaded. In either case, you'll need a way to take what you've created in memory using Parasolid and add it to the scene.

The ``HPS::ExchangeParasolid::File::AddEntity()`` function allows you to not only update the |HPSNOW| component structure but also to create new PRC data to update the Exchange structure. (Please see the ``HPS::ExchangeParasolid::File::AddEntity()`` for details about the limitations of the ``HPS::ExchangeParasolid::File::AddEntity()`` function.)

Below is a sample of how to add a new Parasolid body to the model *PartWithPMI.CATPart*, located in the *samples/data* directory. Here's the model before adding the new body:

.. image:: images/cad_model_before.png

*Model before addition of new Parasolid body.*

This code snippet demonstrates loading a model via Exchange, creating a Parasolid body in memory (a red cube), and using the ``HPS::ExchangeParasolid::File::AddEntity()`` function to add the Parasolid body to the Exchange CAD model:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_add_body.cpp
		   :start-after: //! [parasolid_add_body]
		   :end-before: //! [parasolid_add_body]
		   
	.. group-tab:: C#
	
		.. code-block:: c#

			.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_add_body.cs
			   :start-after: //! [parasolid_add_body]
			   :end-before: //! [parasolid_add_body]

And here's the final output, with the red cube inserted into the CAD model:

.. image:: images/cad_model_after.png

*Model after addition of new Parasolid body (in red).*


Limitations
===========

* When importing files that do not contain B-rep information, colors will not be imported.
    
* Currently the ``HPS::Parasolid::Component::Tessellate()`` and ``HPS::ExchangeParasolid::File::Tessellate()`` functions update |HPSNOW| to reflect the changes made in Parasolid. This function does NOT however update the PRC representation of the model held by Exchange. Therefore, after calling either of these Tessellate functions, in order to export an accurate representation of the model, use the Parasolid API (e.g., ``PK_PART_transmit11``) and reload the model into |HPSNOW| from disk.
    

Miscellaneous
=============

* The `HOOPS Parasolid Demo Viewer <https://developer.techsoft3d.com/hoops/demos/>`_ uses Exchange-Parasolid and can be used to sample basic modeling operations.
    

.. _cheat_sheet:

Synchronizing |HPSNOW| and the Native Parasolid API
===================================================

This chart shows which |HPSNOW| functions must be called after a specific native Parasolid operation:

.. csv-table::
	:header: "Native Parasolid operation", "Related |HPSNOW| call", "Updates PRC?"

	"Adds new Body to the Parasolid partition", "``HPS::ExchangeParasolid::File::AddEntity()``", "YES"
	"Modifies existing body", "``HPS::ExchangeParasolid::File::Tessellate()``", "NO"
	"Deletes Body", "``HPS::CADModel::Delete()``", "YES"


.. _boolean_operations:

Boolean Operations
==================

|HPSNOW| supports the subtraction boolean operation via the native Parasolid API. To perform a subtraction in a scene, we'll load two CAD models into a scene, defining one of them as a target (the 3D model we'll be subtracting from) and the other as a tool (the 3D shape that will define the bounds of the subtraction operation). In this example, we'll load an engine model as our target and then load a cylinder to serve as the tool for the subtraction.
 
Please note, this is a very basic sample boolean subtraction operator, merely a starting point from which to build a more robust boolean operator leveraging Parasolid. Specifically, this operator implementation does not address the case in which a boolean operation would result in multiple bodies (although the comments in the :ref:`operator code <boolean_full_source>` explain how to address that eventuality).

.. image:: images/engine_target.png

*CAD model of an engine that will be used as the target for a boolean operation*

.. image:: images/cylinder_tool.png

*CAD model of a cylinder that will be used as the tool for a boolean operation*

The full code for importing two CAD models into a scene is :ref:`here <prog_guide/0907_exchange_parasolid:Scene setup and operator instantiation>`, and, for the most part, we're just using a standard approach for importing files in |HPSNOW|. However, please note that we're using a ``HPS::Exchange::ImportOptionsKit::SetLocation()`` to import our second model (the tool) into the same Component tree as the first file.

In addition, please note that in terms of positioning, our models have been designed to overlap each other in World Space to facilitate the subtraction operation. If you want to use two models that weren't necessarily designed for this purpose, there are a variety of approaches for positioning them on top of each other to perform the boolean operation. For example, using the :ref:`Handles Operator <prog_guide/0601_standard_operators:HandlesOperator>` is an easy way to manually super-impose one model on top of another.

Once loaded, our two CAD models will look like this, with the cylinder piercing the engine model on the left:

.. image:: images/target_and_tool.png

*Two intersecting CAD models loaded via the Exchange sprocket*


Defining a Custom Operator
--------------------------

Perhaps the simplest method for implementing a boolean operation in |HPSNOW| is to define a custom operator that handles a series of mouse clicks for defining the target and tool. The full source code for the class is available at the :ref:`bottom of the page <boolean_full_source>`, but for now we'll just focus on the ``OnMouseUp`` method, since that's where the bulk of the logic is contained. (More info about custom operators is available in :doc:`this section <0602_custom_operators>`.)

We'll call our custom operator class ``TestBooleanOperator``, and like all custom operators, it inherits the ``HPS::Operator`` class. In this example, we'll overload the ``HPS::Operator::OnMouseUp`` method, and in the overloaded method we'll place the logic for selecting the target and tool for the boolean subtraction operation:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_boolean.cpp
		   :start-after: //! [00760_exchange_parasolid_boolean_selection_logic]
		   :end-before: //! [00760_exchange_parasolid_boolean_selection_logic]
		   
	.. group-tab:: C#
	
		.. code-block:: c#

			.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_boolean.cs
			   :start-after: //! [00760_exchange_parasolid_boolean_selection_logic]
			   :end-before: //! [00760_exchange_parasolid_boolean_selection_logic]

The Parasolid Body upon which the user clicks first will be selected as the target, and the second body selected by the user will be the tool for the 
boolean operation:

.. image:: images/target_selected.png

*The target is selected and highlighted in green*

.. image:: images/tool_selected.png
    
*The tool is selected and highlighted in orange*


Instantiating the Custom Operator
---------------------------------

With our custom operator class defined, in our application code (provided in full :ref:`below <boolean_setup>`) we can now instantiate our custom operator and push it onto the operator stack in the ``HPS::Operator::Priority::Default`` priority queue:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_boolean.cpp
		   :start-after: //! [00760_exchange_parasolid_boolean_instantiate]
		   :end-before: //! [00760_exchange_parasolid_boolean_instantiate]
		   
	.. group-tab:: C#
	
		.. code-block:: c#

			.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_boolean.cs
			   :start-after: //! [00760_exchange_parasolid_boolean_instantiate]
			   :end-before: //! [00760_exchange_parasolid_boolean_instantiate]
		   
This instance of ``TestBooleanOperator`` is now available in the operator stack, and we'll learn how to retrieve it in the next section. (For more details about the operator stack, please see :doc:`this section <0601_standard_operators>`.)

Once our ``TestBooleanOperator`` instance has been pushed to the operator stack, |HPSNOW| takes ownership of its memory, so do not call ``delete`` on this instance, as it will be automatically freed by |HPSNOW|.


Retrieving the Operator From the Stack
--------------------------------------

Suppose that after we've pushed our original instance of ``TestBooleanOperator`` onto the operator stack, we want to access its member methods &ndash; in this case, specifically the ``ApplyBoolean()`` method.

In order to retrieve our custom operator from the ``Default`` priority operator stack, we can use the following approach:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_boolean.cpp
		   :start-after: //! [00760_exchange_parasolid_boolean_retrieve]
		   :end-before: //! [00760_exchange_parasolid_boolean_retrieve]
		   
	.. group-tab:: C#
	
		.. code-block:: c#

			.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_boolean.cs
			   :start-after: //! [00760_exchange_parasolid_boolean_retrieve]
			   :end-before: //! [00760_exchange_parasolid_boolean_retrieve]
		   
We can retrieve a pointer to the operator by calling ``HPS::OperatorControl::ShowTop``, passing a newly instantiated ``HPS::OperatorPtr`` as an out parameter to be populated by the function.

At this point, however, in order to gain access to the methods in our derived ``TestBooleanOperator`` class we'll need to create a new pointer to our derived type and use a ``static_pointer_cast`` to transform our ``HPS::OperatorPtr`` to a shared pointer of ``TestBooleanOperator`` type.

Now that we have a ``TestBooleanOperator`` pointer, we can access its methods and call the ``ApplyBoolean()`` function, which will call Parasolid's boolean subtraction function, removing from the target any overlapping volume, as seen in the image below:

.. image:: images/engine_with_hole.png

*Final result of our boolean subtraction operation*

After the data has been changed in Parasolid, |HPSNOW| needs to be updated. This update can be accomplished by using the three functions: ``HPS::Parasolid::Component::Tessellate`` (for geometry that was modified, like the target), ``HPS::Component::Delete`` (for geometry that was deleted, like the tool), and ``ExchangeParasolid::File::AddEntity`` (for geometry that was created, which would happen in the case where a boolean operation splits an entity in two, for example).

The source code :ref`below <boolean_full_source` demonstrates ``HPS::Parasolid::Component::Tessellate`` and ``HPS::Component::Delete``, and :ref:`this section <prog_guide/0907_exchange_parasolid:Creating geometry in memory using Parasolid and adding it to the scene>` demonstrates how to use the ``HPS::ExchangeParasolid::File::AddEntity`` function.


.. _boolean_full_source:

Full Source for Custom Boolean Operator
=======================================

TestBooleanOperator derived class
---------------------------------

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_boolean.cpp
		   :start-after: //! [00760_exchange_parasolid_boolean_operator_class]
		   :end-before: //! [00760_exchange_parasolid_boolean_operator_class]
		   
	.. group-tab:: C#
	
		.. code-block:: c#

			.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_boolean.cs
			   :start-after: //! [00760_exchange_parasolid_boolean_operator_class]
			   :end-before: //! [00760_exchange_parasolid_boolean_operator_class]
		   
		   
.. _boolean_setup:

Scene Setup and Operator Instantiation
======================================

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_boolean.cpp
		   :start-after: //! [00760_exchange_parasolid_boolean_setup]
		   :end-before: //! [00760_exchange_parasolid_boolean_setup]
		   
	.. group-tab:: C#
	
		.. code-block:: c#

			.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_boolean.cs
			   :start-after: //! [00760_exchange_parasolid_boolean_setup]
			   :end-before: //! [00760_exchange_parasolid_boolean_setup]
		   
		   
.. _boolean_execute:

Operator Retrieval and Boolean Operation Execution
==================================================

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00760_exchange_parasolid_boolean.cpp
		   :start-after: //! [00760_exchange_parasolid_boolean_execute]
		   :end-before: //! [00760_exchange_parasolid_boolean_execute]
		   
	.. group-tab:: C#
	
		.. code-block:: c#

			.. literalinclude:: ../../../internals/tests/docs/source/cs/00760_exchange_parasolid_boolean.cs
			   :start-after: //! [00760_exchange_parasolid_boolean_execute]
			   :end-before: //! [00760_exchange_parasolid_boolean_execute]
			   