コード例 #1
0
ファイル: groups.py プロジェクト: zaphodbe/FreeCAD
def get_group_names(doc=None):
    """Return a list of names of existing groups in the document.

    Parameters
    ----------
    doc: App::Document, optional
        It defaults to `None`.
        A document on which to search group names.
        It if is `None` it will search the current document.

    Returns
    -------
    list of str
        A list of names of objects that are "groups".
        These are objects derived from `App::DocumentObjectGroup`
        or which are of types `'Floor'`, `'Building'`, or `'Site'`
        from the Arch Workbench.

        Otherwise, return an empty list.
    """
    if not doc:
        found, doc = utils.find_doc(App.activeDocument())

    if not found:
        _err(_tr("No active document. Aborting."))
        return []

    glist = []

    for obj in doc.Objects:
        if (obj.isDerivedFrom("App::DocumentObjectGroup")
                or utils.get_type(obj) in ("Floor", "Building", "Site")):
            glist.append(obj.Name)

    return glist
コード例 #2
0
def get_group_names(doc=None):
    """Return a list of names of existing groups in the document.

    Parameters
    ----------
    doc: App::Document, optional
        It defaults to `None`.
        A document on which to search group names.
        It if is `None` it will search the current document.

    Returns
    -------
    list of str
        A list of names of objects that are considered groups.
        See the is_group function.

        Otherwise returns an empty list.
    """
    if not doc:
        found, doc = utils.find_doc(App.activeDocument())

    if not found:
        _err(_tr("No active document. Aborting."))
        return []

    glist = []

    for obj in doc.Objects:
        if is_group(obj):
            glist.append(obj.Name)

    return glist
コード例 #3
0
ファイル: make_layer.py プロジェクト: zaphodbe/FreeCAD
def get_layer_container():
    """Return a group object to put layers in.

    Returns
    -------
    App::DocumentObjectGroupPython
        The existing group object named `'LayerContainer'`
        of type `LayerContainer`.
        If it doesn't exist it will create it with this default Name.
    """
    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(translate("draft", "No active document. Aborting."))
        return None

    for obj in doc.Objects:
        if obj.Name == "LayerContainer":
            return obj

    new_obj = doc.addObject("App::DocumentObjectGroupPython", "LayerContainer")
    new_obj.Label = translate("draft", "Layers")

    LayerContainer(new_obj)

    if App.GuiUp:
        ViewProviderLayerContainer(new_obj.ViewObject)

    return new_obj
コード例 #4
0
ファイル: make_text.py プロジェクト: zyqcome/FreeCAD
def convert_draft_texts(textslist=None):
    """Convert the given Annotation to a Draft text.

    In the past, the `Draft Text` object didn't exist; text objects
    were of type `App::Annotation`. This function was introduced
    to convert those older objects to a `Draft Text` scripted object.

    This function was already present at splitting time during v0.19.

    Parameters
    ----------
    textslist: list of objects, optional
        It defaults to `None`.
        A list containing `App::Annotation` objects or a single of these
        objects.
        If it is `None` it will convert all objects in the current document.
    """
    _name = "convert_draft_texts"
    utils.print_header(_name, "Convert Draft texts")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    if not textslist:
        textslist = list()
        for obj in doc.Objects:
            if obj.TypeId == "App::Annotation":
                textslist.append(obj)

    if not isinstance(textslist, list):
        textslist = [textslist]

    to_delete = []

    for obj in textslist:
        label = obj.Label
        obj.Label = label + ".old"

        # Create a new Draft Text object
        new_obj = make_text(obj.LabelText, placement=obj.Position)
        new_obj.Label = label
        to_delete.append(obj)

        # Move the new object to the group which contained the old object
        for in_obj in obj.InList:
            if in_obj.isDerivedFrom("App::DocumentObjectGroup"):
                if obj in in_obj.Group:
                    group = in_obj.Group
                    group.append(new_obj)
                    in_obj.Group = group

    for obj in to_delete:
        doc.removeObject(obj.Name)
コード例 #5
0
ファイル: gui_utils.py プロジェクト: zqsgdnq/FreeCAD
def get_bbox(obj, debug=False):
    """Return a BoundBox from any object that has a Coin RootNode.

    Normally the bounding box of an object can be taken
    from its `Part::TopoShape`.
    ::
        >>> print(obj.Shape.BoundBox)

    However, for objects without a `Shape`, such as those
    derived from `App::FeaturePython` like `Draft Text` and `Draft Dimension`,
    the bounding box can be calculated from the `RootNode` of the viewprovider.

    Parameters
    ----------
    obj: App::DocumentObject
        Any object that has a `ViewObject.RootNode`.

    Returns
    -------
    Base::BoundBox
        It returns a `BoundBox` object which has information like
        minimum and maximum values of X, Y, and Z, as well as bounding box
        center.

    None
        If there is a problem it will return `None`.
    """
    _name = "get_bbox"
    utils.print_header(_name, "Bounding box", debug=debug)

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    if isinstance(obj, str):
        obj_str = obj

    found, obj = utils.find_object(obj, doc)
    if not found:
        _msg("obj: {}".format(obj_str))
        _err(_tr("Wrong input: object not in document."))
        return None

    if debug:
        _msg("obj: {}".format(obj.Label))

    if (not hasattr(obj, "ViewObject")
            or not obj.ViewObject
            or not hasattr(obj.ViewObject, "RootNode")):
        _err(_tr("Does not have 'ViewObject.RootNode'."))

    # For Draft Dimensions
    # node = obj.ViewObject.Proxy.node
    node = obj.ViewObject.RootNode

    view = Gui.ActiveDocument.ActiveView
    region = view.getViewer().getSoRenderManager().getViewportRegion()
    action = coin.SoGetBoundingBoxAction(region)

    node.getBoundingBox(action)
    bb = action.getBoundingBox()

    # xlength, ylength, zlength = bb.getSize().getValue()
    xmin, ymin, zmin = bb.getMin().getValue()
    xmax, ymax, zmax = bb.getMax().getValue()

    return App.BoundBox(xmin, ymin, zmin, xmax, ymax, zmax)
コード例 #6
0
ファイル: make_dimension.py プロジェクト: zikpuppy/FreeCAD
def make_angular_dimension(center=App.Vector(0, 0, 0),
                           angles=[0, 90],
                           dim_line=App.Vector(10, 10, 0),
                           normal=None):
    """Create an angular dimension from the given center and angles.

    Parameters
    ----------
    center: Base::Vector3, optional
        It defaults to the origin `Vector(0, 0, 0)`.
        Center of the dimension line, which is a circular arc.

    angles: list of two floats, optional
        It defaults to `[0, 90]`.
        It is a list of two angles, given in degrees, that determine
        the aperture of the dimension line, that is, of the circular arc.
        It is drawn counter-clockwise.
        ::
            angles = [0 90]
            angles = [330 60]  # the arc crosses the X axis
            angles = [-30 60]  # same angle

    dim_line: Base::Vector3, optional
        It defaults to `Vector(10, 10, 0)`.
        This is a point through which the extension of the dimension line
        will pass. This defines the radius of the dimension line,
        the circular arc.

    normal: Base::Vector3, optional
        It defaults to `None`, in which case the `normal` is taken
        from the currently active `App.DraftWorkingPlane.axis`.

        If the working plane is not available, then the `normal`
        defaults to +Z or `Vector(0, 0, 1)`.

    Returns
    -------
    App::FeaturePython
        A scripted object of type `'AngularDimension'`.
        This object does not have a `Shape` attribute, as the text and lines
        are created on screen by Coin (pivy).

    None
        If there is a problem it will return `None`.
    """
    _name = "make_angular_dimension"
    utils.print_header(_name, "Angular dimension")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    _msg("center: {}".format(center))
    try:
        utils.type_check([(center, App.Vector)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a vector."))
        return None

    _msg("angles: {}".format(angles))
    try:
        utils.type_check([(angles, (tuple, list))], name=_name)

        if len(angles) != 2:
            _err(_tr("Wrong input: must be a list with two angles."))
            return None

        ang1, ang2 = angles
        utils.type_check([(ang1, (int, float)), (ang2, (int, float))],
                         name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a list with two angles."))
        return None

    # If the angle is larger than 360 degrees, make sure
    # it is smaller than 360
    for n in range(len(angles)):
        if angles[n] > 360:
            angles[n] = angles[n] - 360

    _msg("dim_line: {}".format(dim_line))
    try:
        utils.type_check([(dim_line, App.Vector)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a vector."))
        return None

    _msg("normal: {}".format(normal))
    if normal:
        try:
            utils.type_check([(dim_line, App.Vector)], name=_name)
        except TypeError:
            _err(_tr("Wrong input: must be a vector."))
            return None

    if not normal:
        if hasattr(App, "DraftWorkingPlane"):
            normal = App.DraftWorkingPlane.axis
        else:
            normal = App.Vector(0, 0, 1)

    new_obj = App.ActiveDocument.addObject("App::FeaturePython", "Dimension")
    AngularDimension(new_obj)

    new_obj.Center = center
    new_obj.FirstAngle = angles[0]
    new_obj.LastAngle = angles[1]
    new_obj.Dimline = dim_line

    if App.GuiUp:
        ViewProviderAngularDimension(new_obj.ViewObject)

        # Invert the normal if we are viewing it from the back.
        # This is determined by the angle between the current
        # 3D view and the provided normal being below 90 degrees
        vnorm = gui_utils.get3DView().getViewDirection()
        if vnorm.getAngle(normal) < math.pi / 2:
            normal = normal.negative()

    new_obj.Normal = normal

    if App.GuiUp:
        gui_utils.format_object(new_obj)
        gui_utils.select(new_obj)

    return new_obj
コード例 #7
0
ファイル: make_dimension.py プロジェクト: zikpuppy/FreeCAD
def make_radial_dimension_obj(edge_object,
                              index=1,
                              mode="radius",
                              dim_line=None):
    """Create a radial or diameter dimension from an arc object.

    Parameters
    ----------
    edge_object: Part::Feature
        The object which has a circular edge which will be measured.
        It must have a `Part::TopoShape`, and at least one element
        must be a circular edge in `Shape.Edges` to be able to measure
        its radius.

    index: int, optional
        It defaults to `1`.
        It is the index of the edge in `edge_object` which is going to
        be measured.
        The minimum value should be `1`, which will be interpreted
        as `'Edge1'`. If the value is below `1`, it will be set to `1`.

    mode: str, optional
        It defaults to `'radius'`; the other option is `'diameter'`.
        It determines whether the dimension will be shown as a radius
        or as a diameter.

    dim_line: Base::Vector3, optional
        It defaults to `None`.
        This is a point through which the extension of the dimension line
        will pass. The dimension line will be a radius or diameter
        of the measured arc, extending from the center to the arc itself.

        If it is `None`, this point will be set to one unit to the right
        of the center of the arc, which will create a dimension line that is
        horizontal, that is, parallel to the +X axis.

    Returns
    -------
    App::FeaturePython
        A scripted object of type `'LinearDimension'`.
        This object does not have a `Shape` attribute, as the text and lines
        are created on screen by Coin (pivy).

    None
        If there is a problem it will return `None`.
    """
    _name = "make_radial_dimension_obj"
    utils.print_header(_name, "Radial dimension")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    if isinstance(edge_object, str):
        edge_object_str = edge_object

    found, edge_object = utils.find_object(edge_object, doc)
    if not found:
        _msg("edge_object: {}".format(edge_object_str))
        _err(_tr("Wrong input: object not in document."))
        return None

    _msg("edge_object: {}".format(edge_object.Label))
    if not hasattr(edge_object, "Shape"):
        _err(_tr("Wrong input: object doesn't have a 'Shape' to measure."))
        return None
    if (not hasattr(edge_object.Shape, "Edges")
            or len(edge_object.Shape.Edges) < 1):
        _err(
            _tr("Wrong input: object doesn't have at least one element "
                "in 'Edges' to use for measuring."))
        return None

    _msg("index: {}".format(index))
    try:
        utils.type_check([(index, int)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be an integer."))
        return None

    if index < 1:
        index = 1
        _wrn(_tr("index: values below 1 are not allowed; will be set to 1."))

    edge = edge_object.getSubObject("Edge" + str(index))
    if not edge:
        _err(
            _tr("Wrong input: index doesn't correspond to an edge "
                "in the object."))
        return None

    if not hasattr(edge, "Curve") or edge.Curve.TypeId != 'Part::GeomCircle':
        _err(_tr("Wrong input: index doesn't correspond to a circular edge."))
        return None

    _msg("mode: {}".format(mode))
    try:
        utils.type_check([(mode, str)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a string, 'radius' or 'diameter'."))
        return None

    if mode not in ("radius", "diameter"):
        _err(_tr("Wrong input: must be a string, 'radius' or 'diameter'."))
        return None

    _msg("dim_line: {}".format(dim_line))
    if dim_line:
        try:
            utils.type_check([(dim_line, App.Vector)], name=_name)
        except TypeError:
            _err(_tr("Wrong input: must be a vector."))
            return None
    else:
        center = edge_object.Shape.Edges[index - 1].Curve.Center
        dim_line = center + App.Vector(1, 0, 0)

    # TODO: the internal function expects an index starting with 0
    # so we need to decrease the value here.
    # This should be changed in the future in the internal function.
    index -= 1

    new_obj = make_dimension(edge_object, index, mode, dim_line)

    return new_obj
コード例 #8
0
ファイル: make_dimension.py プロジェクト: zikpuppy/FreeCAD
def make_linear_dimension_obj(edge_object, i1=1, i2=2, dim_line=None):
    """Create a linear dimension from an object.

    Parameters
    ----------
    edge_object: Part::Feature
        The object which has an edge which will be measured.
        It must have a `Part::TopoShape`, and at least one element
        in `Shape.Vertexes`, to be able to measure a distance.

    i1: int, optional
        It defaults to `1`.
        It is the index of the first vertex in `edge_object` from which
        the measurement will be taken.
        The minimum value should be `1`, which will be interpreted
        as `'Vertex1'`.

        If the value is below `1`, it will be set to `1`.

    i2: int, optional
        It defaults to `2`, which will be converted to `'Vertex2'`.
        It is the index of the second vertex in `edge_object` that determines
        the endpoint of the measurement.

        If it is the same value as `i1`, the resulting measurement will be
        made from the origin `(0, 0, 0)` to the vertex indicated by `i1`.

        If the value is below `1`, it will be set to the last vertex
        in `edge_object`.

        Then to measure the first and last, this could be used
        ::
            make_linear_dimension_obj(edge_object, i1=1, i2=-1)

    dim_line: Base::Vector3
        It defaults to `None`.
        This is a point through which the extension of the dimension line
        will pass.
        This point controls how close or how far the dimension line is
        positioned from the measured segment in `edge_object`.

        If it is `None`, this point will be calculated from the intermediate
        distance betwwen the vertices defined by `i1` and `i2`.

    Returns
    -------
    App::FeaturePython
        A scripted object of type `'LinearDimension'`.
        This object does not have a `Shape` attribute, as the text and lines
        are created on screen by Coin (pivy).

    None
        If there is a problem it will return `None`.
    """
    _name = "make_linear_dimension_obj"
    utils.print_header(_name, "Linear dimension")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    if isinstance(edge_object, str):
        edge_object_str = edge_object

    if isinstance(edge_object, (list, tuple)):
        _msg("edge_object: {}".format(edge_object))
        _err(_tr("Wrong input: object must not be a list."))
        return None

    found, edge_object = utils.find_object(edge_object, doc)
    if not found:
        _msg("edge_object: {}".format(edge_object_str))
        _err(_tr("Wrong input: object not in document."))
        return None

    _msg("edge_object: {}".format(edge_object.Label))
    if not hasattr(edge_object, "Shape"):
        _err(_tr("Wrong input: object doesn't have a 'Shape' to measure."))
        return None
    if (not hasattr(edge_object.Shape, "Vertexes")
            or len(edge_object.Shape.Vertexes) < 1):
        _err(
            _tr("Wrong input: object doesn't have at least one element "
                "in 'Vertexes' to use for measuring."))
        return None

    _msg("i1: {}".format(i1))
    try:
        utils.type_check([(i1, int)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be an integer."))
        return None

    if i1 < 1:
        i1 = 1
        _wrn(_tr("i1: values below 1 are not allowed; will be set to 1."))

    vx1 = edge_object.getSubObject("Vertex" + str(i1))
    if not vx1:
        _err(_tr("Wrong input: vertex not in object."))
        return None

    _msg("i2: {}".format(i2))
    try:
        utils.type_check([(i2, int)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a vector."))
        return None

    if i2 < 1:
        i2 = len(edge_object.Shape.Vertexes)
        _wrn(
            _tr("i2: values below 1 are not allowed; "
                "will be set to the last vertex in the object."))

    vx2 = edge_object.getSubObject("Vertex" + str(i2))
    if not vx2:
        _err(_tr("Wrong input: vertex not in object."))
        return None

    _msg("dim_line: {}".format(dim_line))
    if dim_line:
        try:
            utils.type_check([(dim_line, App.Vector)], name=_name)
        except TypeError:
            _err(_tr("Wrong input: must be a vector."))
            return None
    else:
        diff = vx2.Point.sub(vx1.Point)
        diff.multiply(0.5)
        dim_line = vx1.Point.add(diff)

    # TODO: the internal function expects an index starting with 0
    # so we need to decrease the value here.
    # This should be changed in the future in the internal function.
    i1 -= 1
    i2 -= 1

    new_obj = make_dimension(edge_object, i1, i2, dim_line)

    return new_obj
コード例 #9
0
ファイル: make_dimension.py プロジェクト: zikpuppy/FreeCAD
def make_linear_dimension(p1, p2, dim_line=None):
    """Create a free linear dimension from two main points.

    Parameters
    ----------
    p1: Base::Vector3
        First point of the measurement.

    p2: Base::Vector3
        Second point of the measurement.

    dim_line: Base::Vector3, optional
        It defaults to `None`.
        This is a point through which the extension of the dimension line
        will pass.
        This point controls how close or how far the dimension line is
        positioned from the measured segment that goes from `p1` to `p2`.

        If it is `None`, this point will be calculated from the intermediate
        distance betwwen `p1` and `p2`.

    Returns
    -------
    App::FeaturePython
        A scripted object of type `'LinearDimension'`.
        This object does not have a `Shape` attribute, as the text and lines
        are created on screen by Coin (pivy).

    None
        If there is a problem it will return `None`.
    """
    _name = "make_linear_dimension"
    utils.print_header(_name, "Linear dimension")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    _msg("p1: {}".format(p1))
    try:
        utils.type_check([(p1, App.Vector)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a vector."))
        return None

    _msg("p2: {}".format(p2))
    try:
        utils.type_check([(p2, App.Vector)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a vector."))
        return None

    _msg("dim_line: {}".format(dim_line))
    if dim_line:
        try:
            utils.type_check([(dim_line, App.Vector)], name=_name)
        except TypeError:
            _err(_tr("Wrong input: must be a vector."))
            return None
    else:
        diff = p2.sub(p1)
        diff.multiply(0.5)
        dim_line = p1.add(diff)

    new_obj = make_dimension(p1, p2, dim_line)

    return new_obj
コード例 #10
0
def make_array(base_object,
               arg1,
               arg2,
               arg3,
               arg4=None,
               arg5=None,
               arg6=None,
               use_link=True):
    """Create a Draft Array of the given object.

    Rectangular array
    -----------------
    make_array(object,xvector,yvector,xnum,ynum,[name])
    makeArray(object,xvector,yvector,zvector,xnum,ynum,znum,[name])

    xnum of iterations in the x direction
    at xvector distance between iterations, same for y direction
    with yvector and ynum, same for z direction with zvector and znum.

    Polar array
    -----------
    makeArray(object,center,totalangle,totalnum,[name]) for polar array, or

    center is a vector, totalangle is the angle to cover (in degrees)
    and totalnum is the number of objects, including the original.

    Circular array
    --------------
    makeArray(object,rdistance,tdistance,axis,center,ncircles,symmetry,[name])

    In case of a circular array, rdistance is the distance of the
    circles, tdistance is the distance within circles, axis the rotation-axis,
    center the center of rotation, ncircles the number of circles
    and symmetry the number of symmetry-axis of the distribution.

    To Do
    -----
    The `Array` class currently handles three types of arrays,
    orthogonal, polar, and circular. In the future, probably they should be
    split in separate classes so that they are easier to manage.
    """
    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    if use_link:
        # The Array class must be called in this special way
        # to make it a LinkArray
        new_obj = doc.addObject("Part::FeaturePython", "Array", Array(None),
                                None, True)
    else:
        new_obj = doc.addObject("Part::FeaturePython", "Array")
        Array(new_obj)

    new_obj.Base = base_object
    if arg6:
        if isinstance(arg1, (int, float, App.Units.Quantity)):
            new_obj.ArrayType = "circular"
            new_obj.RadialDistance = arg1
            new_obj.TangentialDistance = arg2
            new_obj.Axis = arg3
            new_obj.Center = arg4
            new_obj.NumberCircles = arg5
            new_obj.Symmetry = arg6
        else:
            new_obj.ArrayType = "ortho"
            new_obj.IntervalX = arg1
            new_obj.IntervalY = arg2
            new_obj.IntervalZ = arg3
            new_obj.NumberX = arg4
            new_obj.NumberY = arg5
            new_obj.NumberZ = arg6
    elif arg4:
        new_obj.ArrayType = "ortho"
        new_obj.IntervalX = arg1
        new_obj.IntervalY = arg2
        new_obj.NumberX = arg3
        new_obj.NumberY = arg4
    else:
        new_obj.ArrayType = "polar"
        new_obj.Center = arg1
        new_obj.Angle = arg2
        new_obj.NumberPolar = arg3

    if App.GuiUp:
        if use_link:
            ViewProviderDraftLink(new_obj.ViewObject)
        else:
            ViewProviderDraftArray(new_obj.ViewObject)
            gui_utils.format_object(new_obj, new_obj.Base)

            if hasattr(new_obj.Base.ViewObject, "DiffuseColor"):
                if len(new_obj.Base.ViewObject.DiffuseColor) > 1:
                    new_obj.ViewObject.Proxy.resetColors(new_obj.ViewObject)

        new_obj.Base.ViewObject.hide()
        gui_utils.select(new_obj)

    return new_obj
コード例 #11
0
ファイル: make_patharray.py プロジェクト: zyqcome/FreeCAD
def make_path_array(base_object,
                    path_object,
                    count=4,
                    extra=App.Vector(0, 0, 0),
                    subelements=None,
                    align=False,
                    align_mode="Original",
                    tan_vector=App.Vector(1, 0, 0),
                    force_vertical=False,
                    vertical_vector=App.Vector(0, 0, 1),
                    use_link=True):
    """Make a Draft PathArray object.

    Distribute copies of a `base_object` along `path_object`
    or `subelements` from `path_object`.

    Parameters
    ----------
    base_object: Part::Feature or str
        Any of object that has a `Part::TopoShape` that can be duplicated.
        This means most 2D and 3D objects produced with any workbench.
        If it is a string, it must be the `Label` of that object.
        Since a label is not guaranteed to be unique in a document,
        it will use the first object found with this label.

    path_object: Part::Feature or str
        Path object like a polyline, B-Spline, or bezier curve that should
        contain edges.
        Just like `base_object` it can also be `Label`.

    count: int, float, optional
        It defaults to 4.
        Number of copies to create along the `path_object`.
        It must be at least 2.
        If a `float` is provided, it will be truncated by `int(count)`.

    extra: Base.Vector3, optional
        It defaults to `App.Vector(0, 0, 0)`.
        It translates each copy by the value of `extra`.
        This is useful to adjust for the difference between shape centre
        and shape reference point.

    subelements: list or tuple of str, optional
        It defaults to `None`.
        It should be a list of names of edges that must exist in `path_object`.
        Then the path array will be created along these edges only,
        and not the entire `path_object`.
        ::
            subelements = ['Edge1', 'Edge2']

        The edges must be contiguous, meaning that it is not allowed to
        input `'Edge1'` and `'Edge3'` if they do not touch each other.

        A single string value is also allowed.
        ::
            subelements = 'Edge1'

    align: bool, optional
        It defaults to `False`.
        If it is `True` it will align `base_object` to tangent, normal,
        or binormal to the `path_object`, depending on the value
        of `tan_vector`.

    align_mode: str, optional
        It defaults to `'Original'` which is the traditional alignment.
        It can also be `'Frenet'` or `'Tangent'`.

        - Original. It does not calculate curve normal.
          `X` is curve tangent, `Y` is normal parameter, Z is the cross
          product `X` x `Y`.
        - Frenet. It defines a local coordinate system along the path.
          `X` is tangent to curve, `Y` is curve normal, `Z` is curve binormal.
          If normal cannot be computed, for example, in a straight path,
          a default is used.
        - Tangent. It is similar to `'Original'` but includes a pre-rotation
          to align the base object's `X` to the value of `tan_vector`,
          then `X` follows curve tangent.

    tan_vector: Base::Vector3, optional
        It defaults to `App.Vector(1, 0, 0)` or the +X axis.
        It aligns the tangent of the path to this local unit vector
        of the object.

    force_vertical: Base::Vector3, optional
        It defaults to `False`.
        If it is `True`, the value of `vertical_vector`
        will be used when `align_mode` is `'Original'` or `'Tangent'`.

    vertical_vector: Base::Vector3, optional
        It defaults to `App.Vector(0, 0, 1)` or the +Z axis.
        It will force this vector to be the vertical direction
        when `force_vertical` is `True`.

    use_link: bool, optional
        It defaults to `True`, in which case the copies are `App::Link`
        elements. Otherwise, the copies are shape copies which makes
        the resulting array heavier.

    Returns
    -------
    Part::FeaturePython
        The scripted object of type `'PathArray'`.
        Its `Shape` is a compound of the copies of the original object.

    None
        If there is a problem it will return `None`.
    """
    _name = "make_path_array"
    utils.print_header(_name, "Path array")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    if isinstance(base_object, str):
        base_object_str = base_object

    found, base_object = utils.find_object(base_object, doc)
    if not found:
        _msg("base_object: {}".format(base_object_str))
        _err(_tr("Wrong input: object not in document."))
        return None

    _msg("base_object: {}".format(base_object.Label))

    if isinstance(path_object, str):
        path_object_str = path_object

    found, path_object = utils.find_object(path_object, doc)
    if not found:
        _msg("path_object: {}".format(path_object_str))
        _err(_tr("Wrong input: object not in document."))
        return None

    _msg("path_object: {}".format(path_object.Label))

    _msg("count: {}".format(count))
    try:
        utils.type_check([(count, (int, float))], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a number."))
        return None
    count = int(count)

    _msg("extra: {}".format(extra))
    try:
        utils.type_check([(extra, App.Vector)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a vector."))
        return None

    _msg("subelements: {}".format(subelements))
    if subelements:
        try:
            # Make a list
            if isinstance(subelements, str):
                subelements = [subelements]

            utils.type_check([(subelements, (list, tuple, str))], name=_name)
        except TypeError:
            _err(
                _tr("Wrong input: must be a list or tuple of strings. "
                    "Or a single string."))
            return None

        # The subelements list is used to build a special list
        # called a LinkSubList, which includes the path_object.
        # Old style: [(path_object, "Edge1"), (path_object, "Edge2")]
        # New style: [(path_object, ("Edge1", "Edge2"))]
        #
        # If a simple list is given ["a", "b"], this will create an old-style
        # SubList.
        # If a nested list is given [["a", "b"]], this will create a new-style
        # SubList.
        # In any case, the property of the object accepts both styles.
        #
        # If the old style is deprecated then this code should be updated
        # to create new style lists exclusively.
        sub_list = list()
        for sub in subelements:
            sub_list.append((path_object, sub))
    else:
        sub_list = None

    align = bool(align)
    _msg("align: {}".format(align))

    _msg("align_mode: {}".format(align_mode))
    try:
        utils.type_check([(align_mode, str)], name=_name)

        if align_mode not in ("Original", "Frenet", "Tangent"):
            raise TypeError
    except TypeError:
        _err(_tr("Wrong input: must be "
                 "'Original', 'Frenet', or 'Tangent'."))
        return None

    _msg("tan_vector: {}".format(tan_vector))
    try:
        utils.type_check([(tan_vector, App.Vector)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a vector."))
        return None

    force_vertical = bool(force_vertical)
    _msg("force_vertical: {}".format(force_vertical))

    _msg("vertical_vector: {}".format(vertical_vector))
    try:
        utils.type_check([(vertical_vector, App.Vector)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a vector."))
        return None

    use_link = bool(use_link)
    _msg("use_link: {}".format(use_link))

    if use_link:
        # The PathArray class must be called in this special way
        # to make it a PathLinkArray
        new_obj = doc.addObject("Part::FeaturePython", "PathArray",
                                PathArray(None), None, True)
    else:
        new_obj = doc.addObject("Part::FeaturePython", "PathArray")
        PathArray(new_obj)

    new_obj.Base = base_object
    new_obj.PathObject = path_object
    new_obj.Count = count
    new_obj.ExtraTranslation = extra
    new_obj.PathSubelements = sub_list
    new_obj.Align = align
    new_obj.AlignMode = align_mode
    new_obj.TangentVector = tan_vector
    new_obj.ForceVertical = force_vertical
    new_obj.VerticalVector = vertical_vector

    if App.GuiUp:
        if use_link:
            ViewProviderDraftLink(new_obj.ViewObject)
        else:
            ViewProviderDraftArray(new_obj.ViewObject)
            gui_utils.formatObject(new_obj, new_obj.Base)

            if hasattr(new_obj.Base.ViewObject, "DiffuseColor"):
                if len(new_obj.Base.ViewObject.DiffuseColor) > 1:
                    new_obj.ViewObject.Proxy.resetColors(new_obj.ViewObject)

        new_obj.Base.ViewObject.hide()
        gui_utils.select(new_obj)

    return new_obj
コード例 #12
0
ファイル: make_patharray.py プロジェクト: zyqcome/FreeCAD
def make_path_twisted_array(base_object,
                            path_object,
                            count=15,
                            rot_factor=0.25,
                            use_link=True):
    """Create a Path twisted array."""
    _name = "make_path_twisted_array"
    utils.print_header(_name, "Path twisted array")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    if isinstance(base_object, str):
        base_object_str = base_object

    found, base_object = utils.find_object(base_object, doc)
    if not found:
        _msg("base_object: {}".format(base_object_str))
        _err(_tr("Wrong input: object not in document."))
        return None

    _msg("base_object: {}".format(base_object.Label))

    if isinstance(path_object, str):
        path_object_str = path_object

    found, path_object = utils.find_object(path_object, doc)
    if not found:
        _msg("path_object: {}".format(path_object_str))
        _err(_tr("Wrong input: object not in document."))
        return None

    _msg("path_object: {}".format(path_object.Label))

    _msg("count: {}".format(count))
    try:
        utils.type_check([(count, (int, float))], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a number."))
        return None
    count = int(count)

    use_link = bool(use_link)
    _msg("use_link: {}".format(use_link))

    if use_link:
        # The PathTwistedArray class must be called in this special way
        # to make it a PathTwistLinkArray
        new_obj = doc.addObject("Part::FeaturePython", "PathTwistedArray",
                                PathTwistedArray(None), None, True)
    else:
        new_obj = doc.addObject("Part::FeaturePython", "PathTwistedArray")
        PathTwistedArray(new_obj)

    new_obj.Base = base_object
    new_obj.PathObject = path_object
    new_obj.Count = count
    new_obj.RotationFactor = rot_factor

    if App.GuiUp:
        if use_link:
            ViewProviderDraftLink(new_obj.ViewObject)
        else:
            ViewProviderDraftArray(new_obj.ViewObject)
            gui_utils.formatObject(new_obj, new_obj.Base)

        if hasattr(new_obj.Base.ViewObject, "DiffuseColor"):
            if len(new_obj.Base.ViewObject.DiffuseColor) > 1:
                new_obj.ViewObject.Proxy.resetColors(new_obj.ViewObject)

        new_obj.Base.ViewObject.hide()
        gui_utils.select(new_obj)

    return new_obj
コード例 #13
0
ファイル: make_pointarray.py プロジェクト: zikpuppy/FreeCAD
def make_point_array(base_object, point_object, extra=None):
    """Make a Draft PointArray object.

    Distribute copies of a `base_object` in the points
    defined by `point_object`.

    Parameters
    ----------
    base_object: Part::Feature or str
        Any of object that has a `Part::TopoShape` that can be duplicated.
        This means most 2D and 3D objects produced with any workbench.
        If it is a string, it must be the `Label` of that object.
        Since a label is not guaranteed to be unique in a document,
        it will use the first object found with this label.

    point_object: Part::Feature or str
        An object that is a type of container for holding points.
        This object must have one of the following properties `Geometry`,
        `Links`, or `Components`, which themselves must contain objects
        with `X`, `Y`, and `Z` properties.

        This object could be:

        - A `Sketcher::SketchObject`, as it has a `Geometry` property.
          The sketch can contain different elements but it must contain
          at least one `Part::GeomPoint`.

        - A `Part::Compound`, as it has a `Links` property. The compound
          can contain different elements but it must contain at least
          one object that has `X`, `Y`, and `Z` properties,
          like a `Draft Point` or a `Part::Vertex`.

        - A `Draft Block`, as it has a `Components` property. This `Block`
          behaves essentially the same as a `Part::Compound`. It must
          contain at least a point or vertex object.

    extra: Base::Placement, Base::Vector3, or Base::Rotation, optional
        It defaults to `None`.
        If it is provided, it is an additional placement that is applied
        to each copy of the array.
        The input could be a full placement, just a vector indicating
        the additional translation, or just a rotation.

    Returns
    -------
    Part::FeaturePython
        A scripted object of type `'PointArray'`.
        Its `Shape` is a compound of the copies of the original object.

    None
        If there is a problem it will return `None`.
    """
    _name = "make_point_array"
    utils.print_header(_name, "Point array")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    if isinstance(base_object, str):
        base_object_str = base_object

    found, base_object = utils.find_object(base_object, doc)
    if not found:
        _msg("base_object: {}".format(base_object_str))
        _err(_tr("Wrong input: object not in document."))
        return None

    _msg("base_object: {}".format(base_object.Label))

    if isinstance(point_object, str):
        point_object_str = point_object

    found, point_object = utils.find_object(point_object, doc)
    if not found:
        _msg("point_object: {}".format(point_object_str))
        _err(_tr("Wrong input: object not in document."))
        return None

    _msg("point_object: {}".format(point_object.Label))
    if (not hasattr(point_object, "Geometry")
            and not hasattr(point_object, "Links")
            and not hasattr(point_object, "Components")):
        _err(
            _tr("Wrong input: point object doesn't have "
                "'Geometry', 'Links', or 'Components'."))
        return None

    _msg("extra: {}".format(extra))
    if not extra:
        extra = App.Placement()
    try:
        utils.type_check([(extra, (App.Placement, App.Vector, App.Rotation))],
                         name=_name)
    except TypeError:
        _err(
            _tr("Wrong input: must be a placement, a vector, "
                "or a rotation."))
        return None

    # Convert the vector or rotation to a full placement
    if isinstance(extra, App.Vector):
        extra = App.Placement(extra, App.Rotation())
    elif isinstance(extra, App.Rotation):
        extra = App.Placement(App.Vector(), extra)

    new_obj = doc.addObject("Part::FeaturePython", "PointArray")
    PointArray(new_obj)
    new_obj.Base = base_object
    new_obj.PointObject = point_object
    new_obj.ExtraPlacement = extra

    if App.GuiUp:
        ViewProviderDraftArray(new_obj.ViewObject)
        gui_utils.formatObject(new_obj, new_obj.Base)

        if hasattr(new_obj.Base.ViewObject, "DiffuseColor"):
            if len(new_obj.Base.ViewObject.DiffuseColor) > 1:
                new_obj.ViewObject.Proxy.resetColors(new_obj.ViewObject)

        new_obj.Base.ViewObject.hide()
        gui_utils.select(new_obj)

    return new_obj
コード例 #14
0
def make_text(string, placement=None, screen=False):
    """Create a Text object containing the given list of strings.

    The current color and text height and font specified in preferences
    are used.

    Parameters
    ----------
    string: str, or list of str
        String to display on screen.

        If it is a list, each element in the list should be a string.
        In this case each element will be printed in its own line, that is,
        a newline will be added at the end of each string.

        If an empty string is passed `''` this won't cause an error
        but the text `'Label'` will be displayed in the 3D view.

    placement: Base::Placement, Base::Vector3, or Base::Rotation, optional
        It defaults to `None`.
        If it is provided, it is the placement of the new text.
        The input could be a full placement, just a vector indicating
        the translation, or just a rotation.

    screen: bool, optional
        It defaults to `False`, in which case the text is placed in 3D space
        oriented like any other object, on top of a given plane,
        by the default the XY plane.
        If it is `True`, the text will always face perpendicularly
        to the camera direction, that is, it will be flat on the screen.

    Returns
    -------
    App::FeaturePython
        A scripted object of type `'Text'`.
        This object does not have a `Shape` attribute, as the text is created
        on screen by Coin (pivy).

    None
        If there is a problem it will return `None`.
    """
    _name = "make_text"
    utils.print_header(_name, "Text")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    _msg("string: {}".format(string))
    try:
        utils.type_check([(string, (str, list))])
    except TypeError:
        _err(
            _tr("Wrong input: must be a list of strings "
                "or a single string."))
        return None

    if not all(isinstance(element, str) for element in string):
        _err(
            _tr("Wrong input: must be a list of strings "
                "or a single string."))
        return None

    if isinstance(string, str):
        string = [string]

    _msg("placement: {}".format(placement))
    if not placement:
        placement = App.Placement()
    try:
        utils.type_check([(placement,
                           (App.Placement, App.Vector, App.Rotation))],
                         name=_name)
    except TypeError:
        _err(
            _tr("Wrong input: must be a placement, a vector, "
                "or a rotation."))
        return None

    # Convert the vector or rotation to a full placement
    if isinstance(placement, App.Vector):
        placement = App.Placement(placement, App.Rotation())
    elif isinstance(placement, App.Rotation):
        placement = App.Placement(App.Vector(), placement)

    new_obj = doc.addObject("App::FeaturePython", "Text")
    Text(new_obj)
    new_obj.Text = string
    new_obj.Placement = placement

    if App.GuiUp:
        ViewProviderText(new_obj.ViewObject)

        h = utils.get_param("textheight", 0.20)

        if screen:
            _msg("screen: {}".format(screen))
            new_obj.ViewObject.DisplayMode = "3D text"
            h = h * 10

        new_obj.ViewObject.FontSize = h
        new_obj.ViewObject.FontName = utils.get_param("textfont", "")
        new_obj.ViewObject.LineSpacing = 1

        gui_utils.format_object(new_obj)
        gui_utils.select(new_obj)

    return new_obj
コード例 #15
0
ファイル: make_label.py プロジェクト: zikpuppy/FreeCAD
def make_label(target_point=App.Vector(0, 0, 0),
               placement=App.Vector(30, 30, 0),
               target_object=None, subelements=None,
               label_type="Custom", custom_text="Label",
               direction="Horizontal", distance=-10,
               points=None):
    """Create a Label object containing different types of information.

    The current color and text height and font specified in preferences
    are used.

    Parameters
    ----------
    target_point: Base::Vector3, optional
        It defaults to the origin `App.Vector(0, 0, 0)`.
        This is the point which is pointed to by the label's leader line.
        This point can be adorned with a marker like an arrow or circle.

    placement: Base::Placement, Base::Vector3, or Base::Rotation, optional
        It defaults to `App.Vector(30, 30, 0)`.
        If it is provided, it defines the base point of the textual
        label.
        The input could be a full placement, just a vector indicating
        the translation, or just a rotation.

    target_object: Part::Feature or str, optional
        It defaults to `None`.
        If it exists it should be an object which will be used to provide
        information to the label, as long as `label_type` is different
        from `'Custom'`.

        If it is a string, it must be the `Label` of that object.
        Since a `Label` is not guaranteed to be unique in a document,
        it will use the first object found with this `Label`.

    subelements: str, optional
        It defaults to `None`.
        If `subelements` is provided, `target_object` should be provided
        as well, otherwise it is ignored.

        It should be a string indicating a subelement name, either
        `'VertexN'`, `'EdgeN'`, or `'FaceN'` which should exist
        within `target_object`.
        In this case `'N'` is an integer that indicates the specific number
        of vertex, edge, or face in `target_object`.

        Both `target_object` and `subelements` are used to link the label
        to a particular object, or to the particular vertex, edge, or face,
        and get information from them.
        ::
            make_label(..., target_object=App.ActiveDocument.Box)
            make_label(..., target_object="My box", subelements="Face3")

        These two parameters can be can be obtained from the `Gui::Selection`
        module.
        ::
            sel_object = Gui.Selection.getSelectionEx()[0]
            target_object = sel_object.Object
            subelements = sel_object.SubElementNames[0]

    label_type: str, optional
        It defaults to `'Custom'`.
        It can be `'Custom'`, `'Name'`, `'Label'`, `'Position'`,
        `'Length'`, `'Area'`, `'Volume'`, `'Tag'`, or `'Material'`.
        It indicates the type of information that will be shown in the label.

        Only `'Custom'` allows you to manually set the text
        by defining `custom_text`. The other types take their information
        from the object included in `target`.

        - `'Position'` will show the base position of the target object,
          or of the indicated `'VertexN'` in `target`.
        - `'Length'` will show the `Length` of the target object's `Shape`,
          or of the indicated `'EdgeN'` in `target`.
        - `'Area'` will show the `Area` of the target object's `Shape`,
          or of the indicated `'FaceN'` in `target`.

    custom_text: str, optional
        It defaults to `'Label'`.
        It is the text that will be displayed by the label when
        `label_type` is `'Custom'`.

    direction: str, optional
        It defaults to `'Horizontal'`.
        It can be `'Horizontal'`, `'Vertical'`, or `'Custom'`.
        It indicates the direction of the straight segment of the leader line
        that ends up next to the textual label.

        If `'Custom'` is selected, the leader line can be manually drawn
        by specifying the value of `points`.
        Normally, the leader line has only three points, but with `'Custom'`
        you can specify as many points as needed.

    distance: int, float, Base::Quantity, optional
        It defaults to -10.
        It indicates the length of the horizontal or vertical segment
        of the leader line.

        The leader line is composed of two segments, the first segment is
        inclined, while the second segment is either horizontal or vertical
        depending on the value of `direction`.
        ::
            T
            |
            |
            o------- L text

        The `oL` segment's length is defined by `distance`
        while the `oT` segment is automatically calculated depending
        on the values of `placement` (L) and `distance` (o).

        This `distance` is oriented, meaning that if it is positive
        the segment will be to the right and above of the textual
        label, depending on if `direction` is `'Horizontal'` or `'Vertical'`,
        respectively.
        If it is negative, the segment will be to the left
        and below of the text.

    points: list of Base::Vector3, optional
        It defaults to `None`.
        It is a list of vectors defining the shape of the leader line;
        the list must have at least two points.
        This argument must be used together with `direction='Custom'`
        to display this custom leader.

        However, notice that if the Label's `StraightDirection` property
        is later changed to `'Horizontal'` or `'Vertical'`,
        the custom point list will be overwritten with a new,
        automatically calculated three-point list.

        For the object to use custom points, `StraightDirection`
        must remain `'Custom'`, and then the `Points` property
        can be overwritten by a suitable list of points.

    Returns
    -------
    App::FeaturePython
        A scripted object of type `'Label'`.
        This object does not have a `Shape` attribute, as the text and lines
        are created on screen by Coin (pivy).

    None
        If there is a problem it will return `None`.
    """
    _name = "make_label"
    utils.print_header(_name, "Label")

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(_tr("No active document. Aborting."))
        return None

    _msg("target_point: {}".format(target_point))
    if not target_point:
        target_point = App.Vector(0, 0, 0)
    try:
        utils.type_check([(target_point, App.Vector)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a vector."))
        return None

    _msg("placement: {}".format(placement))
    if not placement:
        placement = App.Placement()
    try:
        utils.type_check([(placement, (App.Placement,
                                       App.Vector,
                                       App.Rotation))], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a placement, a vector, "
                 "or a rotation."))
        return None

    # Convert the vector or rotation to a full placement
    if isinstance(placement, App.Vector):
        placement = App.Placement(placement, App.Rotation())
    elif isinstance(placement, App.Rotation):
        placement = App.Placement(App.Vector(), placement)

    if isinstance(target_object, str):
        target_object_str = target_object

    if target_object:
        if isinstance(target_object, (list, tuple)):
            _msg("target_object: {}".format(target_object))
            _err(_tr("Wrong input: object must not be a list."))
            return None

        found, target_object = utils.find_object(target_object, doc)
        if not found:
            _msg("target_object: {}".format(target_object_str))
            _err(_tr("Wrong input: object not in document."))
            return None

        _msg("target_object: {}".format(target_object.Label))

    if target_object and subelements:
        _msg("subelements: {}".format(subelements))
        try:
            # Make a list
            if isinstance(subelements, str):
                subelements = [subelements]

            utils.type_check([(subelements, (list, tuple, str))],
                             name=_name)
        except TypeError:
            _err(_tr("Wrong input: must be a list or tuple of strings. "
                     "Or a single string."))
            return None

        # The subelements list is used to build a special list
        # called a LinkSub, which includes the target_object
        # and the subelements.
        # Single: (target_object, "Edge1")
        # Multiple: (target_object, ("Edge1", "Edge2"))
        for sub in subelements:
            _sub = target_object.getSubObject(sub)
            if not _sub:
                _err("subelement: {}".format(sub))
                _err(_tr("Wrong input: subelement not in object."))
                return None

    _msg("label_type: {}".format(label_type))
    if not label_type:
        label_type = "Custom"
    try:
        utils.type_check([(label_type, str)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a string, "
                 "'Custom', 'Name', 'Label', 'Position', "
                 "'Length', 'Area', 'Volume', 'Tag', or 'Material'."))
        return None

    if label_type not in ("Custom", "Name", "Label", "Position",
                          "Length", "Area", "Volume", "Tag", "Material"):
        _err(_tr("Wrong input: must be a string, "
                 "'Custom', 'Name', 'Label', 'Position', "
                 "'Length', 'Area', 'Volume', 'Tag', or 'Material'."))
        return None

    _msg("custom_text: {}".format(custom_text))
    if not custom_text:
        custom_text = "Label"
    try:
        utils.type_check([(custom_text, str)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a string."))
        return None

    _msg("direction: {}".format(direction))
    if not direction:
        direction = "Horizontal"
    try:
        utils.type_check([(direction, str)], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a string, "
                 "'Horizontal', 'Vertical', or 'Custom'."))
        return None

    if direction not in ("Horizontal", "Vertical", "Custom"):
        _err(_tr("Wrong input: must be a string, "
                 "'Horizontal', 'Vertical', or 'Custom'."))
        return None

    _msg("distance: {}".format(distance))
    if not distance:
        distance = 1
    try:
        utils.type_check([(distance, (int, float))], name=_name)
    except TypeError:
        _err(_tr("Wrong input: must be a number."))
        return None

    if points:
        _msg("points: {}".format(points))

        _err_msg = _tr("Wrong input: must be a list of at least two vectors.")
        try:
            utils.type_check([(points, (tuple, list))], name=_name)
        except TypeError:
            _err(_err_msg)
            return None

        if len(points) < 2:
            _err(_err_msg)
            return None

        if not all(isinstance(p, App.Vector) for p in points):
            _err(_err_msg)
            return None

    new_obj = doc.addObject("App::FeaturePython",
                            "dLabel")
    Label(new_obj)

    new_obj.TargetPoint = target_point
    new_obj.Placement = placement
    if target_object:
        if subelements:
            new_obj.Target = [target_object, subelements]
        else:
            new_obj.Target = [target_object, []]

    new_obj.LabelType = label_type
    new_obj.CustomText = custom_text

    new_obj.StraightDirection = direction
    new_obj.StraightDistance = distance
    if points:
        if direction != "Custom":
            _wrn(_tr("Direction is not 'Custom'; "
                     "points won't be used."))
        new_obj.Points = points

    if App.GuiUp:
        ViewProviderLabel(new_obj.ViewObject)
        h = utils.get_param("textheight", 0.20)
        new_obj.ViewObject.TextSize = h

        gui_utils.format_object(new_obj)
        gui_utils.select(new_obj)

    return new_obj
コード例 #16
0
ファイル: make_layer.py プロジェクト: zaphodbe/FreeCAD
def make_layer(name=None,
               line_color=None,
               shape_color=None,
               line_width=2.0,
               draw_style="Solid",
               transparency=0):
    """Create a Layer object in the active document.

    If a layer container named `'LayerContainer'` does not exist,
    it is created with this name.

    A layer controls the view properties of the objects inside the layer,
    so all parameters except for `name` only apply if the graphical interface
    is up.

    Parameters
    ----------
    name: str, optional
        It is used to set the layer's `Label` (user editable).
        It defaults to `None`, in which case the `Label`
        is set to `'Layer'` or to its translation in the current language.

    line_color: tuple, optional
        It defaults to `None`, in which case it uses the value of the parameter
        `User parameter:BaseApp/Preferences/View/DefaultShapeLineColor`.
        If it is given, it should be a tuple of three
        floating point values from 0.0 to 1.0.

    shape_color: tuple, optional
        It defaults to `None`, in which case it uses the value of the parameter
        `User parameter:BaseApp/Preferences/View/DefaultShapeColor`.
        If it is given, it should be a tuple of three
        floating point values from 0.0 to 1.0.

    line_width: float, optional
        It defaults to 2.0.
        It determines the width of the edges of the objects contained
        in the layer.

    draw_style: str, optional
        It defaults to `'Solid'`.
        It determines the style of the edges of the objects contained
        in the layer.
        If it is given, it should be 'Solid', 'Dashed', 'Dotted',
        or 'Dashdot'.

    transparency: int, optional
        It defaults to 0.
        It should be an integer value from 0 (completely opaque)
        to 100 (completely transparent).

    Return
    ------
    App::FeaturePython
        A scripted object of type `'Layer'`.
        This object does not have a `Shape` attribute.
        Modifying the view properties of this object will affect the objects
        inside of it.

    None
        If there is a problem it will return `None`.
    """
    _name = "make_layer"
    utils.print_header(_name, translate("draft", "Layer"))

    found, doc = utils.find_doc(App.activeDocument())
    if not found:
        _err(translate("draft", "No active document. Aborting."))
        return None

    if name:
        _msg("name: {}".format(name))
        try:
            utils.type_check([(name, str)], name=_name)
        except TypeError:
            _err(translate("draft", "Wrong input: it must be a string."))
            return None
    else:
        name = translate("draft", "Layer")

    if line_color:
        _msg("line_color: {}".format(line_color))
        try:
            utils.type_check([(line_color, tuple)], name=_name)
        except TypeError:
            _err(
                translate(
                    "draft",
                    "Wrong input: must be a tuple of three floats 0.0 to 1.0.")
            )
            return None

        if not all(isinstance(color, (int, float)) for color in line_color):
            _err(
                translate(
                    "draft",
                    "Wrong input: must be a tuple of three floats 0.0 to 1.0.")
            )
            return None
    else:
        c = view_group.GetUnsigned("DefaultShapeLineColor", 255)
        line_color = (((c >> 24) & 0xFF) / 255, ((c >> 16) & 0xFF) / 255,
                      ((c >> 8) & 0xFF) / 255)

    if shape_color:
        _msg("shape_color: {}".format(shape_color))
        try:
            utils.type_check([(shape_color, tuple)], name=_name)
        except TypeError:
            _err(
                translate(
                    "draft",
                    "Wrong input: must be a tuple of three floats 0.0 to 1.0.")
            )
            return None

        if not all(isinstance(color, (int, float)) for color in shape_color):
            _err(
                translate(
                    "draft",
                    "Wrong input: must be a tuple of three floats 0.0 to 1.0.")
            )
            return None
    else:
        c = view_group.GetUnsigned("DefaultShapeColor", 4294967295)
        shape_color = (((c >> 24) & 0xFF) / 255, ((c >> 16) & 0xFF) / 255,
                       ((c >> 8) & 0xFF) / 255)

    _msg("line_width: {}".format(line_width))
    try:
        utils.type_check([(line_width, (int, float))], name=_name)
        line_width = float(abs(line_width))
    except TypeError:
        _err(translate("draft", "Wrong input: must be a number."))
        return None

    _msg("draw_style: {}".format(draw_style))
    try:
        utils.type_check([(draw_style, str)], name=_name)
    except TypeError:
        _err(
            translate(
                "draft",
                "Wrong input: must be 'Solid', 'Dashed', 'Dotted', or 'Dashdot'."
            ))
        return None

    if draw_style not in ('Solid', 'Dashed', 'Dotted', 'Dashdot'):
        _err(
            translate(
                "draft",
                "Wrong input: must be 'Solid', 'Dashed', 'Dotted', or 'Dashdot'."
            ))
        return None

    _msg("transparency: {}".format(transparency))
    try:
        utils.type_check([(transparency, (int, float))], name=_name)
        transparency = int(abs(transparency))
    except TypeError:
        _err(
            translate("draft",
                      "Wrong input: must be a number between 0 and 100."))
        return None

    new_obj = doc.addObject("App::FeaturePython", "Layer")
    Layer(new_obj)

    new_obj.Label = name

    if App.GuiUp:
        ViewProviderLayer(new_obj.ViewObject)

        new_obj.ViewObject.LineColor = line_color
        new_obj.ViewObject.ShapeColor = shape_color
        new_obj.ViewObject.LineWidth = line_width
        new_obj.ViewObject.DrawStyle = draw_style
        new_obj.ViewObject.Transparency = transparency

    container = get_layer_container()
    container.addObject(new_obj)

    return new_obj