def CreateFromDocument (xml_text, default_namespace=None, location_base=None):
def CreateFromDOM (node, default_namespace=None):
def _BuildAutomaton ():
def _BuildAutomaton_ ():
def _BuildAutomaton_2 ():
def _BuildAutomaton_3 ():
def _BuildAutomaton_4 ():
def _BuildAutomaton_5 ():
def _BuildAutomaton_6 ():
def _BuildAutomaton_7 ():
def _BuildAutomaton_8 ():
def _BuildAutomaton_9 ():
def _BuildAutomaton_10 ():
def _BuildAutomaton_11 ():
def _BuildAutomaton_12 ():
def _BuildAutomaton_13 ():
def _BuildAutomaton_14 ():
def _BuildAutomaton_15 ():
def _BuildAutomaton_16 ():
def _BuildAutomaton_17 ():
def _BuildAutomaton_18 ():
def _BuildAutomaton_19 ():
def _BuildAutomaton_20 ():
def _BuildAutomaton_21 ():
def _BuildAutomaton_22 ():
def _BuildAutomaton_23 ():
class vector3 (pyxb.binding.datatypes.string):
class CTD_ANON (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_ (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_2 (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_3 (pyxb.binding.basis.complexTypeDefinition):
class BodySet (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_4 (pyxb.binding.basis.complexTypeDefinition):
class Body (pyxb.binding.basis.complexTypeDefinition):
class WrapObjectSet (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_5 (pyxb.binding.basis.complexTypeDefinition):
class Millard2012EquilibriumMuscle (pyxb.binding.basis.complexTypeDefinition):
class Millard2012AccelerationMuscle (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_6 (pyxb.binding.basis.complexTypeDefinition):
class Thelen2003Muscle (pyxb.binding.basis.complexTypeDefinition):
class RigidTendonMuscle (pyxb.binding.basis.complexTypeDefinition):
class MyoroboticsMuscle (pyxb.binding.basis.complexTypeDefinition):
class WrapCylinder (pyxb.binding.basis.complexTypeDefinition):
class WrapSphere (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_7 (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_8 (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_9 (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_10 (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_11 (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_12 (pyxb.binding.basis.complexTypeDefinition):
class CTD_ANON_13 (pyxb.binding.basis.complexTypeDefinition): class RDOperator(bpy.types.Operator):
    """
    Base class for the :term:`operators<operator>` in the RobotDesigner.

    :term:`Blender operators<operator>` are defined as :term:`class objects` derived from :class:`bpy.types.Operator`.
    A plugin must *register* these classes by calling :func:`bpy.utils.register_class` which causes blender to
    create a callable function *out of a method* (:meth:`bpy.types.Operator.execute`) that accepts
    :term:`keyword arguments <keyword argument>` that are bound to the class' attributes -- if they are
    subclasses
    of :class:`bpy.types.Property`. Note that the static method has not the same arguments and operates on its
    attributes.
    Finally, the operator is addressed to by its ID. For example:

    .. code-block:: python

        class NewOp(bpy.types.Operator):
            bl_label = "Description" # Obligatory
            bl_idname = "plugin_name.newop" # obligatory

            test = StringProperty() # A property. It's value is passed when calling the operator.

            def execute(self, context):
                self.report({INFO}, self.text)
                return {'FINISHED'}

        # ...

        bpy.utils.register(NewOp)

        # ...

        bpy.ops.plugin_name.newop(test="Hello World)


    This example show an operator that opens a window containing the message *"Hello World"*. While this is feasible
    for smaller plugins, what happens, if you have a lot of operators written, and you want to have code completion.
    What happens if you want to refactor the names of of the identifier or class attributes. While for the latter there
    is no simple solution available, the :mod:`robot_designer_plugin.core` provides this wrapper class with
    an additional ``run(**kwargs)`` method (that can---and should---be overridden to provide keyword completion).
    Furthermore, it provides decorators for automatically setting preconditions (that define the
    :meth:`bpy.types.Operator.poll` method) for automatic condition checking, logging functionality and post condition
    checking. Together with the :meth:`.pluginmanager.PluginManager.register` method, this makes developing faster (
    code completion,
    code navigation, less verbosity, ...) and safer.

    An examplary :term:`operator` looks like this:

    .. literalinclude:: ../../../resources/templates/operator.py
        :emphasize-lines: 7-11,16-18, 31-33, 60-62
        :lines: 50-111
        :linenos:

    A template is located in ``<RobotDesignerDirectory>/resources/templates/operator.py`` (where you should insert
    the path to the repository) that can be used to quickly write new operators.
    """

    _pre_conditions = {}
    """Dictionary set by the :meth:`PreConditions` decorator. Stores the :class:`.conditions.Condition` that are
    checked for each :class:`RDOperator` -based operator"""

    logger = logger
    """For convenience, every the operators share a logging instance."""

    @classmethod
    def poll(cls, context):
        """
        The :meth:`bpy.types.Operator.poll` class method is called every time, an operator is to be executed, but
        also when it is placed in a guy (it becomes greyed out). This method is defined in this base class and
        the checks are defined by a list of :class:`.conditions.Condition` derived classes that are given by
        the :meth:`Preconditions` decorator. Derived classes do not need to override this method and should
        call the parent's method otherwise.

        :param context: The actual Blender :term:`context`.
        :type context: :class:`bpy.types.Context`
        :return:
        """
        if cls in cls._pre_conditions:
            check, messages = Condition.check_conditions(*cls._pre_conditions[cls])
            if not check:
                cls.logger.debug("Unmet preconditions: \n{}".format(messages))
            return check
        return True

    @staticmethod
    def pass_keywords():
        """
        Helper function that extracts the arguments of the callee (must be a (class) method) and returns them.

        Credits to `Kelly Yancey <http://kbyanc.blogspot.de/2007/07/python-aggregating-function-arguments.html>`_
        """

        args, _, _, locals = inspect.getargvalues(inspect.stack()[1][0])
        args.pop(0)
        kwargs = {i: j for i, j in locals.items() if i in args}
        return kwargs

    @classmethod
    def run(cls, **kwargs):
        """
        Enables to run an :ref:`operator` by calling its class object.
        Child classes *should* override this method with keywords. Then your :term:`IDE` will be able to assist you
        The :meth:`pass_keywords` function makes
        overriding very convenient (just copy the method's body):

        .. code: python

            class NewOp(RDOperator):
                model_name = StringProperty(name="Enter model name:")
                base_segment_name = StringProperty(name="Enter root segment name:", default="")

                @classmethod
                def run(cls, model_name, base_segment_name):
                    return super().run(**cls.pass_keywords())

        .. warning:

            :term: `refactoring<Refactoring>` class attributes (i.e., the keywords) requires you modify both the
            overridden run function *and* your attributes.

        In addition, this method also does extensive error and exception handling writing everything to the log file
        (see :mod:`.logfile`).

        :param kwargs: The keyword arguments passed to the :ref:`Operator` (**must** match the names of the class's
            attributes (only of type :class:`bpy.types.Property).
        :return: The return values of :meth:`bpy.types.Operator.execute`.
        """
        try:
            # cls.logger.debug('get registered operator')
            return get_registered_operator(cls)(**kwargs)


        except TypeError as e:
            bad_kwargs = []
            for kwarg in kwargs.keys():
                if kwarg not in dir(cls):
                    bad_kwargs.append(kwarg)

            cls.logger.error('Exception when running operator {} ({}):'
                             '\n\tkeywords:\t%s\n\tBad keywords:\t{}'
                             '\n\tException:\t%s\n\tMessages:\n\t\t{}'.format(
                             cls.bl_idname, cls.__name__,
                             kwargs,
                             ', '.join(bad_kwargs), type(e).__name__,
                             '\n\t\t'.join(e.__str__().split('\n'))))
            InfoBox.global_messages.append(e.__str__())
            raise e

            # todo check for keyword arguments without default value

        except RuntimeError as e:
            cls.logger.error('Exception when running operator {} ({}):'
                             '\n\tException:\t{}\n\t{}\n'.format(cls.bl_idname, cls.__name__,
                             type(e).__name__, '\n\t'.join(e.__str__().split('\n'))))
            check, messages = Condition.check_conditions(*cls._pre_conditions[cls])
            cls.logger.info("Conditions set for this operator: {}\n\t{}\n\t{}".format(cls._pre_conditions[cls], check,
                            messages))
            InfoBox.global_messages.append(e.__str__())
            raise e
        except Exception as e:
            cls.logger.error('THIS CODE SHOULD NEVER BE EXECUTED: {}\n{}\n'.format(e, log_callstack(back_trace=True)))
            InfoBox.global_messages.append(e.__str__())
            raise e

    @classmethod
    def place_button(cls, layout, text=None, infoBox=None, **kwargs):
        """
        This is a convenience method that let's the developer create a button executing the operator from the gui.
        The results of the :meth:`poll` method (i.e., checking it's conditions) can be optionally passed to an
        :class:`.gui.InfoBox` instance such that a report for a group of operators can be displayed (i.e., why
        it is not executable)

        :param layout: the gui element to place the button (see :meth:`bpy.types.Panel.draw`)
        :param text: Optionally override the text in the ``bl_label`` attribute.
        :param infoBox: Optional instance of :class:`.gui.InfoBox`
        :param kwargs: Additional keyword arguments to :meth:`bpy.types.UILayout.operator`)
        :return: The operator instance (this can be used to set one of the class's attributes)
        """
        if infoBox and cls in cls._pre_conditions:
            # if not isinstance(infoBox, InfoBox):
            #    raise TypeError("Argument: infobox must be of type %s (not %s)" % (InfoBox.__name__, type(infoBox)))

            check, messages = Condition.check_conditions(*cls._pre_conditions[cls])
            if not check:
                infoBox.add_message(messages)

        # Checkconditions
        # todo check KWargs
        if not text:
            text = cls.bl_label
        return layout.operator(cls.bl_idname, text=text, **kwargs)

    @staticmethod
    def OperatorLogger(func):
        """
        Decorator for the `bpy.types.Operator.execute` method (only for sub classes of :class:`RDOperator`).

        Performs logging and exception handling.
        """

        def op_logger(self, context):

            # `callargs['self']` parameter refers to the operator instance
            # This is done in order to avoid positional arguments.
            # That way, the decorator can be used as @OperationLogger instead of
            # @OperationLogger
            # callargs = inspect.getcallargs(func,*args)

            class_name = self.__class__.__name__
            id = self.__class__.bl_idname

            # Execute the Operator
            try:
                # self.logger.debug("Entering {}() from {}({}):\n{}".format(
                #                    func.__name__, id, class_name,
                #                    log_callstack()))

                result = func(self, context)
                # self.logger.debug("Leaving {}() {}({})".format(id, class_name, result))

                return result

            except Exception as e:
                InfoBox.global_messages.append(
                    "%s: %s (%s)" % (type(e).__name__, e.__str__(), log_callstack_last(back_trace=True)))
                message = "Operator %s (%s) threw an exception:%s\n\t%s" % (id, class_name,
                                                                            type(e).__name__, e)
                self.logger.error("Operator {} ({}) threw an exception:\n {} {} {} {}".format(EXCEPTION_MESSAGE,
                                  id, class_name, type(e).__name__, e, log_callstack(), log_callstack(back_trace=True)))
                if isinstance(self, RDOperator):
                    self.report({'ERROR'}, message)
                    return {'FINISHED'}
                else:
                    # Menu has no report and must return None
                    return

        return op_logger

    @staticmethod
    def Preconditions(*conditions):
        """
        :term:`Class decorator<class decorator>` for :term:`operators<operator>`.

        Registers the conditions (of type :class:`.conditions.Condition`) for its subclasses. They will be
        checked within the :meth:`poll` and :meth:`place_button` methods.

        :param conditions: a number of subclasses of :class:`.conditions.Condition`.
        """

        def decorator(cls: RDOperator):  # Todo check why this check fails some times
            if not issubclass(cls, RDOperator):
                raise TypeError("Preconditions: Can only decorate sub classes of RDOperator.i \n%s \n%s \n%s\n%s" % (
                    cls.__name__,
                    cls.mro(), type(cls), conditions))

            cls._pre_conditions[cls] = conditions

            cls.__doc__ += "\n    **Preconditions**:\n\n%s" % "".join(
                '    * :class:`%s.%s`\n' % (i.__module__, i.__name__) for i in conditions)

            # RDOperator.logger.debug("Decorating {}, \nArgs: {}\n {}, {}, {}".format(cls, args, issubclass(cls, RDOperator),
            #                        issubclass(cls, bpy.types.Operator), [RDOperator is i for i in cls.mro()]))
            # for i in cls.mro():
            #    print(i)
            return cls

        # RDOperator.logger.debug("Precondition:\nArgs: {}".format(args))
        if len(conditions) == 1 and issubclass(conditions[0], RDOperator):
            raise TypeError('Decorator Preconditions must be called with arguments of subclasses of Condition')
        else:
            if any([issubclass(i, RDOperator) for i in conditions]):
                raise TypeError('Decorator Preconditions must be called with arguments of subclasses of Condition '
                            '%s', conditions)

            return decorator


    @staticmethod
    def Postconditions(*conditions):
        """
        Method decorator for the :meth:`bpy.types.Operator.execute` method. Works only with :term:`operators<operator>`
        derived :class:`RDOperator`.

        Checks whether post conditions are met after calling the operator. Reports an error message to the log file
        (see :mod:`.logfile`)

        :param conditions: a number of subclasses of :class:`.conditions.Condition`.
        """

        def decorator(func):
            def func_wrapper(self, context):
                result = func(self, context)
                check, messages = Condition.check_conditions(*conditions)
                if not check:
                    self.report({'ERROR'}, messages)
                    logger.error('Postcondition not met: %s\\n%s\n%s', messages, log_callstack(), log_callstack(True))
                    InfoBox.global_messages.append(messages)
                return result

            doc = "\n    **Postconditions**:\n\n%s" % "".join(
                '    * :class:`%s.%s`\n' % (i.__module__, i.__name__) for i in conditions)
            func.__doc__ = func.__doc__ + doc if func.__doc__ else doc
            return func_wrapper

        return decorator def LogFunction(func):
    def func_logger(self, context):
def log_callstack(back_trace=False):
def log_callstack_last(back_trace=False): class RDSelectedObjects(PropertyGroupHandlerBase):
class RDGlobals(PropertyGroupHandlerBase):
    def __init__(self):
    def debug_level_callback(self, context):
    def updateGlobals(self, context):
    def updateBoneName(self, context):
    def display_physics(self, context):
    def attach_world(self, context):
    def updateMuscleName(self, context):
    def update_geometry_name(self, context):
    def update_wrapping_name(self, context):
    def display_geometries(self, context):
    def display_wrapping_geometries(self, context):
    def display_muscles(self, context):
    def display_sensors(self, context):
    def name_update(self, context):
    def muscle_dim_update(self, context):
    def __init__(self): class CreateNewMuscle(RDOperator):
    """
    :term:`Operator <operator>` for creating new robot segments and add it to the current model.
    If a segment is already selected, the new segment is added as a child segment. A call :class:`SelectSegment`
    before might be necessary.
    """

    bl_idname = config.OPERATOR_PREFIX + "create_muscle"
    bl_label = "Create New Muscle"

    muscle_name: StringProperty(name="Enter new muscle name:")

    @classmethod
    def run(cls, muscle_name):  # , parent_name=""):
        return super().run(**cls.pass_keywords())

    @RDOperator.OperatorLogger
    @RDOperator.Postconditions(ModelSelected, SingleSegmentSelected)
    def execute(self, context):
        global_properties.active_muscle.set(bpy.context.scene, self.muscle_name)

        # basic muscle visualization data
        muscleVis = bpy.data.curves.new(name=self.muscle_name, type="CURVE")
        muscleVis.dimensions = "3D"
        muscleVis.fill_mode = "FULL"
        muscleVis.bevel_depth = global_properties.muscle_dim.get(context.scene)
        # create muscle object with visualization data
        muscle = bpy.data.objects.new(self.muscle_name, muscleVis)
        bpy.context.scene.collection.objects.link(muscle)
        muscle.location = (0.0, 0.0, 0.0)
        # setup a material
        lmat = bpy.data.materials.new(self.muscle_name + "_vis")
        lmat.diffuse_color = (0.0, 0.0, 1.0, 1.0)
        # lmat.use_shadeless = True
        muscle.data.materials.append(lmat)
        muscleData = muscle.RobotDesigner.muscles
        muscleData.name = self.muscle_name
        muscleData.muscleType = "THELEN"
        muscleData.robotName = global_properties.model_name.get(context.scene)
        return {"FINISHED"}

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self) class CreateNewPathpoint(RDOperator):
    """
    :term:`Operator <operator> for creating a new pathpoint as a spline point on the muscle object
    """

    bl_idname = config.OPERATOR_PREFIX + "create_muscle_pathpoint"
    bl_label = "Add Current Cursor Location as Pathpoint"

    bl_description = (
        "Add the current cursor location as a new pathpoint \n\n"
        + "Select a cursor location with 'Shift' + RightClick"
    )

    @classmethod
    def run(cls):  # , parent_name=""):
        return super().run(**cls.pass_keywords())

    @RDOperator.OperatorLogger
    @RDOperator.Postconditions(ModelSelected, SingleSegmentSelected)
    def execute(self, context):

        active_muscle = bpy.data.objects[
            global_properties.active_muscle.get(bpy.context.scene)
        ]

        flag = 0
        if len(active_muscle.data.splines) == 0:
            active_muscle.data.splines.new("POLY")
            flag = 1

        if flag == 0:
            active_muscle.data.splines[0].points.add(1)
        cursor = bpy.context.scene.cursor.location

        nr = len(active_muscle.data.splines[0].points)
        active_muscle.data.splines[0].points[nr - 1].co = [
            cursor.x,
            cursor.y,
            cursor.z,
            1,
        ]

        active_muscle.RobotDesigner.muscles.pathPoints.add()

        # add new hok modifier for pathpoint
        active_muscle.modifiers.new(
            name=global_properties.active_muscle.get(bpy.context.scene)
            + "_"
            + str(nr - 1),
            type="HOOK",
        )

        return {"FINISHED"}

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self) class SelectSegment(RDOperator):
    """
    :term:`Operator<operator>` for selecting a segment. If :attr:`segment_name` is empty,
    all segments will be deselected
    """

    bl_idname = config.OPERATOR_PREFIX + "select_segment"
    bl_label = "Select Segment"

    segment_name: StringProperty()

    @RDOperator.OperatorLogger
    def execute(self, context):
        if not (
            context.active_object.type == "ARMATURE"
        ):  # or context.active_object.type == 'MESH'
            raise Exception("BoneSelectionException")

        model = bpy.context.active_object

        for b in model.data.bones:
            b.select = False

        # Alternative to do this:
        # mode = context.mode
        # bpy.ops.object.mode_set(mode='EDIT')
        # bpy.ops.armature.select_all(action='DESELECT')
        # bpy.ops.object.mode_set(mode=mode)

        # Second alternative:
        # mode = context.mode
        # bpy.ops.object.mode_set(mode='EDIT')
        # for b in context.selected_bones:
        #     b.select = False
        # bpy.ops.object.mode_set(mode=mode)

        if self.segment_name:
            model.data.bones.active = model.data.bones[self.segment_name]
            model.data.bones.active.select = True
        else:
            model.data.bones.active = None

        return {"FINISHED"}

    @classmethod
    def run(cls, segment_name=""):
        return super().run(**cls.pass_keywords()) class SelectModel(RDOperator):
    """
    :ref:`operator` for ...

    **Preconditions:**

    **RDOperator.Postconditions:**
    """

    bl_idname = config.OPERATOR_PREFIX + "selectarmature"
    bl_label = "Select Model"

    model_name: StringProperty()

    @classmethod
    def run(cls, model_name=""):
        return super().run(**cls.pass_keywords())

    @RDOperator.OperatorLogger
    @RDOperator.Postconditions(ModelSelected)
    def execute(self, context):
        from . import segments

        for obj in context.scene.objects:
            obj.select_set(False)

        context.view_layer.objects.active = bpy.data.objects[self.model_name]
        context.active_object.select_set(True)
        global_properties.model_name.set(context.scene, self.model_name)
        global_properties.old_name.set(context.scene, self.model_name)
        # not so sure if this is needed at all

        if len(context.active_object.data.bones) > 0:
            baseBoneName = context.active_object.data.bones[0].name
            segments.SelectSegment.run(segment_name=baseBoneName)
        return {"FINISHED"} class SelectGeometry(RDOperator):
    """
    :ref:`Operator <operator>` for selecting a geometry (:class:`bpy.types.Object` with `bpy.types.Mesh` data)
    second to the selected model (Blender object with :class:`bpy.types.Armature` data)
    """

    bl_idname = config.OPERATOR_PREFIX + "select_geometry"
    bl_label = "Select Geometry"

    geometry_name: StringProperty()

    @classmethod
    def run(cls, geometry_name=""):
        return super().run(**cls.pass_keywords())

    @RDOperator.OperatorLogger
    @RDOperator.Postconditions(ModelSelected, SingleMeshSelected)
    def execute(self, context):
        mesh = bpy.data.objects[self.geometry_name]

        if mesh.type != "MESH":
            self.report({"ERROR"}, "Object is no geometry (Mesh). Is %s" % mesh.type)
            global_properties.mesh_name.set(context.scene, "Search")
            return {"FINISHED"}

        # Has the side effect of de-selecting all other objects except for the armature and our mesh.
        global_properties.mesh_name.set(context.scene, self.geometry_name)

        #    context.region.tag_redraw()
        #    context.area.tag_redraw()
        return {"FINISHED"} class AttachWrappingObject(RDOperator):
    """
    :ref:`operator` for assigning a geometry to a segment.
    """

    bl_idname = config.OPERATOR_PREFIX + "attach_wrapping_object"
    bl_label = "Attach Wrapping Object to Active Segment"

    @RDOperator.OperatorLogger
    @RDOperator.Postconditions(ModelSelected, SingleMeshSelected, SingleSegmentSelected)
    def execute(self, context):
        # Set parenting relation. There are two ways to attach geometry to a bone:
        # This way, which sets the parent_bone variable of the object. Or by using vertex weights,
        # in which case parent_bone should be left empty.
        # See also https://blender.stackexchange.com/questions/9200/make-object-a-a-parent-of-object-b-via-python
        # At this point bpy.context.scene.objects.active should point to the armature which will be the parent.
        bpy.ops.object.parent_set(type="BONE", keep_transform=False)

        return {"FINISHED"}

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self, width=400) def string_to_list(s):
    """
    Converts a XML string representing a float vector to python list of float.

    :param s: the XML string
    :return: the python list
    """
    # todo move to helper module one level above (and create it)
    v = [float(i) for i in re.findall("[-+]?\d*\.?\d+[eE]?[-+]?\d*", s)]
    return v
import pyxb
import os.path
import bpy
from mathutils import Matrix, Euler, Vector
from ..osim import osim_dom  # xsd bindings
from ...core import RDOperator
from ...core.logfile import export_logger
from ...properties.globals import global_properties
from ...operators.muscles import CreateNewMuscle, CreateNewPathpoint
from ...operators.segments import SelectSegment
from ...operators.model import SelectModel
from ...operators.rigid_bodies import SelectGeometry
from ...operators.mesh_generation import AttachWrappingObject
from ..sdf.generic.helpers import string_to_list
        while True:
            try:
                # current pathpoint
                pathpoint = muscle.GeometryPath.PathPointSet.objects.PathPoint[p]

                # get pathpoint parent world pose
                model = bpy.data.objects[
                    global_properties.model_name.get(bpy.context.scene)
                ]
                pose_bone = model.pose.bones[pathpoint.body]
                segment_world = model.matrix_world @ pose_bone.matrix

                # calculate pathpoint world pose
                location_local = [float(x) for x in pathpoint.location.split()]
                location_global = segment_world @ Matrix.Translation(
                    (location_local[0], location_local[1], location_local[2], 1)
                )

                # create new pathpoint and set parameters of RD pathpoint object
                CreateNewPathpoint.run()
                location_global = location_global.to_translation()
                RDmuscle.data.splines[0].points[p].co = (
                    location_global[0],
                    location_global[1],
                    location_global[2],
                    1,
                )

                #  hook pathpoints to segments
                RDmuscle.RobotDesigner.muscles.pathPoints[p].coordFrame = pathpoint.body
                bpy.ops.RobotDesigner.select_segment_muscle(
                    segment_name=pathpoint.body, pathpoint_nr=p + 1
                )

                p += 1

            except:
                break

    def import_wrapping_sphere(self, body, wrapping):
        """
        Create wrapping sphere from osim file
        :param body: parent segment
        :param wrapping: .osim pyxb wrapping object instance
        :return:
        """
        radius = wrapping.radius
        bpy.ops.mesh.primitive_uv_sphere_add(
            radius=1.0, calc_uvs=True, enter_editmode=False, location=(0, 0, 0)
        )
        sphere = bpy.context.active_object
        sphere.name = wrapping.name

        lmat = bpy.data.materials.new(sphere.name)
        lmat.diffuse_color = (0.0, 0.135, 0.0, 1.0)
        # lmat.use_shadeless = True
        sphere.data.materials.append(lmat)

        sphere.RobotDesigner.tag = "WRAPPING"
        sphere.RobotDesigner.wrap.WrappingType = "WRAPPING_SPHERE"

        model = bpy.data.objects[global_properties.model_name.get(bpy.context.scene)]
        pose_bone = model.pose.bones[body.name]
        segment_world = model.matrix_world @ pose_bone.matrix

        model_posexyz = string_to_list(wrapping.translation[:])[0:3]
        model_poserpy = [0, 0, 0]
        trafo = (
            Matrix.Translation(Vector(model_posexyz))
            @ Euler(model_poserpy, "XYZ").to_matrix().to_4x4()
        )

        bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
        bpy.context.active_object.matrix_world = (
            segment_world @ trafo @ bpy.context.active_object.matrix_world
        )

        assigned_name = bpy.context.active_object.name

        bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
        SelectModel.run(model_name=model.name)
        SelectSegment.run(segment_name=body.name)
        SelectGeometry.run(geometry_name=assigned_name)

        bpy.data.objects[sphere.name].RobotDesigner.wrap_scaling.scale_all = radius
        # Model has to be selected and active in order to update scale
        # Geometry has to be selected, else the update function itself will take a different object
        bpy.data.objects[sphere.name].RobotDesigner.wrap_scaling.scale_all_update(
            bpy.context
        )

        AttachWrappingObject.run()

    def import_wrapping_cylinder(self, body, wrapping):
        """
        Create wrapping cylinder from osim file
        :param body: parent segment
        :param wrapping: .osim pyxb wrapping object instance
        :return:
        """
        radius = wrapping.radius
        depth = wrapping.length
        bpy.ops.mesh.primitive_cylinder_add(
            radius=1.0, depth=1.0, enter_editmode=False, location=(0, 0, 0)
        )
        cylinder = bpy.context.active_object
        cylinder.name = wrapping.name

        lmat = bpy.data.materials.new(cylinder.name)
        lmat.diffuse_color = (0.0, 0.135, 0.0, 1.0)
        # lmat.use_shadeless = True
        cylinder.data.materials.append(lmat)

        cylinder.RobotDesigner.tag = "WRAPPING"
        cylinder.RobotDesigner.wrap.WrappingType = "WRAPPING_CYLINDER"

        model = bpy.data.objects[global_properties.model_name.get(bpy.context.scene)]
        pose_bone = model.pose.bones[body.name]
        segment_world = model.matrix_world @ pose_bone.matrix


        model_posexyz = string_to_list(wrapping.translation[:])