Exemplo n.º 1
0
def add_labels(product, lr, st):

    if product.links:
        for link in product.links:

            if link.product.doc_id != product.doc_id:

                if not link.product.label_reference:

                    lr_2 = TDF_LabelSequence()
                    si = StepImporter(link.product.doc_path)
                    shape_tool = si.shape_tool
                    shape_tool.GetFreeShapes(lr_2)
                    add_labels(link.product, lr_2.Value(1), shape_tool)
                    link.product.label_reference = lr_2.Value(1)
                    # FIXME: free memory
                    del si
                    gc.collect()
                for d in range(link.quantity):
                    transformation = gp_Trsf()
                    loc = link.locations[d]
                    transformation.SetValues(loc.x1, loc.x2, loc.x3, loc.x4,
                                             loc.y1, loc.y2, loc.y3, loc.y4,
                                             loc.z1, loc.z2, loc.z3, loc.z4, 1,
                                             1)

                    new_label = st.AddComponent(
                        lr, link.product.label_reference,
                        TopLoc_Location(transformation))
                    set_label_name(new_label, link.names[d])
Exemplo n.º 2
0
def composer(temp_file_name):
    """
    :param temp_file_name: path of a  :class:`.tempfile` **.arb** that contains the information to generate a :class:`.Product` relative to the arborescense of a **.stp** file


    For every node of the :class:`.Product`  the attribute **doc_file_path** indicates where is store the file **.stp** that represents the node

    """
    output = open(temp_file_name.encode(), "r")
    product = Product.from_list(json.loads(output.read()))
    output.close()
    output = open(temp_file_name.encode(), "w+")  # erase old data
    output.close()

    WS = XSControl_WorkSession()
    my_step_importer = StepImporter(product.doc_path)

    st = my_step_importer.shape_tool
    lr = TDF_LabelSequence()
    st.GetFreeShapes(lr)

    add_labels(product, lr.Value(1), st)
    writer = STEPCAFControl_Writer(WS.GetHandle(), False)
    for i in range(lr.Length()):
        writer.Transfer(lr.Value(i + 1), STEPControl_AsIs)

    writer.Write(temp_file_name)
Exemplo n.º 3
0
def read_step_file_shapes(filename):
    _shapes = []

    # create an handle to a document
    h_doc = Handle_TDocStd_Document()

    # Create the application
    app = XCAFApp_Application.GetApplication().GetObject()
    app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc)

    # Get root assembly
    doc = h_doc.GetObject()
    h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main())

    step_reader = STEPCAFControl_Reader()
    step_reader.SetNameMode(True)

    status = step_reader.ReadFile(filename)
    if status == IFSelect_RetDone:
        step_reader.Transfer(doc.GetHandle())

    labels = TDF_LabelSequence()
    shape_tool = h_shape_tool.GetObject()
    h_shape_tool.GetObject().GetFreeShapes(labels)

    print("Number of shapes at root :%i" % labels.Length())
    for i in range(labels.Length()):
        label = labels.Value(i + 1)
        a_shape = h_shape_tool.GetObject().GetShape(label)
        _shapes.append(a_shape)
    return _shapes
Exemplo n.º 4
0
def getShapes():
    labels = TDF_LabelSequence()
    h_shape_tool.GetObject().GetFreeShapes(labels)
    global cnt
    cnt += 1

    print()
    print("Number of shapes at root :", labels.Length())
    print()
    root = labels.Value(1)

    getSubShapes(root, None)
Exemplo n.º 5
0
    def test_read_step_file(self):
        ''' Reads the previous step file '''
        # create an handle to a document
        h_doc = Handle_TDocStd_Document()
        # Create the application
        app = XCAFApp_Application.GetApplication().GetObject()
        app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc)
        # Get root assembly
        doc = h_doc.GetObject()
        h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main())
        l_colors = XCAFDoc_DocumentTool_ColorTool(doc.Main())
        step_reader = STEPCAFControl_Reader()
        step_reader.SetColorMode(True)
        step_reader.SetLayerMode(True)
        step_reader.SetNameMode(True)
        step_reader.SetMatMode(True)
        status = step_reader.ReadFile("./test_io/test_ocaf.stp")
        if status == IFSelect_RetDone:
            step_reader.Transfer(doc.GetHandle())

        labels = TDF_LabelSequence()
        color_labels = TDF_LabelSequence()

        shape_tool = h_shape_tool.GetObject()
        h_shape_tool.GetObject().GetFreeShapes(labels)

        assert (labels.Length() == 1)
        sub_shapes_labels = TDF_LabelSequence()
        assert (not shape_tool.IsAssembly(labels.Value(1)))
        shape_tool.GetSubShapes(labels.Value(1), sub_shapes_labels)
        assert (sub_shapes_labels.Length() == 0)

        l_colors.GetObject().GetColors(color_labels)
        assert (color_labels.Length() == 1)

        label_shp = labels.Value(1)
        a_shape = h_shape_tool.GetObject().GetShape(label_shp)
        assert (not a_shape.IsNull())
Exemplo n.º 6
0
    def generate_product_arbre(self):
        """

        Generates a :class:`.Product` relative to the assemblies of the file **.stp**, for every node of the :class:`.Product` it includes a label (:class:`.OCC.TDF.TDF_Label`) that represents and identifies the node , openPLM can only work whit a single root **.stp** files

        """

        roots = TDF_LabelSequence()
        self.shape_tool.GetFreeShapes(roots)
        if roots.Length() != 1:
            raise MultiRootError

        deep = 0
        product_id = [1]
        root = roots.Value(1)
        name = get_label_name(root)
        self.main_product = Product(name, deep, root, self.id, product_id[0],
                                    self.file)
        product_id[0] += 1
        expand_product(self.shape_tool, self.main_product, self.shapes_simples,
                       deep + 1, self.id, self.main_product, product_id,
                       self.file)

        return self.main_product
step_reader.SetMatMode(True)

status = step_reader.ReadFile(filename)
if status == IFSelect_RetDone:
    step_reader.Transfer(doc.GetHandle())

labels = TDF_LabelSequence()
color_labels = TDF_LabelSequence()

shape_tool = h_shape_tool.GetObject()
h_shape_tool.GetObject().GetFreeShapes(labels)

print("Number of shapes at root :%i" % labels.Length())
for i in range(labels.Length()):
    sub_shapes_labels = TDF_LabelSequence()
    print("Is Assembly :", shape_tool.IsAssembly(labels.Value(i+1)))
    sub_shapes = shape_tool.GetSubShapes(labels.Value(i+1), sub_shapes_labels)
    print("Number of subshapes in the assemly :%i" % sub_shapes_labels.Length())
l_colors.GetObject().GetColors(color_labels)

print("Number of colors=%i" % color_labels.Length())
for i in range(color_labels.Length()):
    color = color_labels.Value(i+1)
    print(color.DumpToString())

for i in range(labels.Length()):
    label = labels.Value(i+1)
    a_shape = h_shape_tool.GetObject().GetShape(label)
    m = l_layers.GetObject().GetLayers(a_shape)
    _shapes.append(a_shape)
Exemplo n.º 8
0
def getSubShapes(lab, loc):
    global cnt, lvl
    cnt += 1
    print("\n[%d] level %d, handling LABEL %s\n" %
          (cnt, lvl, get_label_name(lab)))
    print()
    print(lab.DumpToString())
    print()
    print("Is Assembly    :", shape_tool.IsAssembly(lab))
    print("Is Free        :", shape_tool.IsFree(lab))
    print("Is Shape       :", shape_tool.IsShape(lab))
    print("Is Compound    :", shape_tool.IsCompound(lab))
    print("Is Component   :", shape_tool.IsComponent(lab))
    print("Is SimpleShape :", shape_tool.IsSimpleShape(lab))
    print("Is Reference   :", shape_tool.IsReference(lab))

    users = TDF_LabelSequence()
    users_cnt = shape_tool.GetUsers(lab, users)
    print("Nr Users       :", users_cnt)

    l_subss = TDF_LabelSequence()
    shape_tool.GetSubShapes(lab, l_subss)
    print("Nb subshapes   :", l_subss.Length())
    l_comps = TDF_LabelSequence()
    shape_tool.GetComponents(lab, l_comps)
    print("Nb components  :", l_comps.Length())
    print()

    if shape_tool.IsAssembly(lab):
        l_c = TDF_LabelSequence()
        shape_tool.GetComponents(lab, l_c)
        for i in range(l_c.Length()):
            label = l_c.Value(i + 1)
            if shape_tool.IsReference(label):
                print("\n########  reference label :", label)
                label_reference = TDF_Label()
                shape_tool.GetReferredShape(label, label_reference)
                loc = shape_tool.GetLocation(label)
                print("    loc          :", loc)
                trans = loc.Transformation()
                print("    tran form    :", trans.Form())
                rot = trans.GetRotation()
                print("    rotation     :", rot)
                print("    X            :", rot.X())
                print("    Y            :", rot.Y())
                print("    Z            :", rot.Z())
                print("    W            :", rot.W())
                tran = trans.TranslationPart()
                print("    translation  :", tran)
                print("    X            :", tran.X())
                print("    Y            :", tran.Y())
                print("    Z            :", tran.Z())

                locs.append(loc)
                print(">>>>")
                lvl += 1
                getSubShapes(label_reference, loc)
                lvl -= 1
                print("<<<<")
                locs.pop()

    elif shape_tool.IsSimpleShape(lab):
        print("\n########  simpleshape label :", lab)
        shape = shape_tool.GetShape(lab)
        print("    all ass locs   :", locs)

        loc = TopLoc_Location()
        for i in range(len(locs)):
            print("    take loc       :", locs[i])
            loc = loc.Multiplied(locs[i])

        trans = loc.Transformation()
        print("    FINAL loc    :")
        print("    tran form    :", trans.Form())
        rot = trans.GetRotation()
        print("    rotation     :", rot)
        print("    X            :", rot.X())
        print("    Y            :", rot.Y())
        print("    Z            :", rot.Z())
        print("    W            :", rot.W())
        tran = trans.TranslationPart()
        print("    translation  :", tran)
        print("    X            :", tran.X())
        print("    Y            :", tran.Y())
        print("    Z            :", tran.Z())
        shape = BRepBuilderAPI_Transform(shape, loc.Transformation()).Shape()

        c = Quantity_Color()
        colorSet = False
        if (color_tool.GetInstanceColor(shape, 0, c)
                or color_tool.GetInstanceColor(shape, 1, c)
                or color_tool.GetInstanceColor(shape, 2, c)):
            for i in (0, 1, 2):
                color_tool.SetInstanceColor(shape, i, c)
            colorSet = True
            n = c.Name(c.Red(), c.Green(), c.Blue())
            print('    instance color Name & RGB: ', c, n, c.Red(), c.Green(),
                  c.Blue())

        if not colorSet:
            if (color_tool.GetColor(lab, 0, c)
                    or color_tool.GetColor(lab, 1, c)
                    or color_tool.GetColor(lab, 2, c)):
                for i in (0, 1, 2):
                    color_tool.SetInstanceColor(shape, i, c)

                n = c.Name(c.Red(), c.Green(), c.Blue())
                print('    shape color Name & RGB: ', c, n, c.Red(), c.Green(),
                      c.Blue())

        # n = c.Name(c.Red(), c.Green(), c.Blue())
        # print('    color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue())
        # Display shape
        display.DisplayColoredShape(shape, c)

        for i in range(l_subss.Length()):
            lab = l_subss.Value(i + 1)
            print("\n########  simpleshape subshape label :", lab)
            shape = shape_tool.GetShape(lab)

            c = Quantity_Color()
            colorSet = False
            if (color_tool.GetInstanceColor(shape, 0, c)
                    or color_tool.GetInstanceColor(shape, 1, c)
                    or color_tool.GetInstanceColor(shape, 2, c)):
                for i in (0, 1, 2):
                    color_tool.SetInstanceColor(shape, i, c)
                colorSet = True
                n = c.Name(c.Red(), c.Green(), c.Blue())
                print('    instance color Name & RGB: ', c, n, c.Red(),
                      c.Green(), c.Blue())

            if not colorSet:
                if (color_tool.GetColor(lab, 0, c)
                        or color_tool.GetColor(lab, 1, c)
                        or color_tool.GetColor(lab, 2, c)):
                    for i in (0, 1, 2):
                        color_tool.SetInstanceColor(shape, i, c)

                    n = c.Name(c.Red(), c.Green(), c.Blue())
                    print('    shape color Name & RGB: ', c, n, c.Red(),
                          c.Green(), c.Blue())

            # n = c.Name(c.Red(), c.Green(), c.Blue())
            # print('    color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue())
            # Display shape
            display.DisplayColoredShape(shape, c)
Exemplo n.º 9
0
    def __init__(self, file_path, id=None):

        self.file = file_path.encode("utf-8")
        self.id = id
        self.shapes_simples = []
        self.main_product = None
        basename = os.path.basename(self.file)
        self.fileName = os.path.splitext(basename)[0]

        self.STEPReader = STEPCAFControl_Reader()

        if self.STEPReader.ReadFile(self.file) != 1:
            raise OCCReadingStepError

        self.h_doc = TDocStd.Handle_TDocStd_Document()
        self.app = XCAFApp.GetApplication().GetObject()
        self.app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"),
                             self.h_doc)

        self.STEPReader.Transfer(self.h_doc)

        self.doc = self.h_doc.GetObject()
        self.h_shape_tool = XCAFDoc.XCAFDoc_DocumentTool_ShapeTool(
            self.doc.Main())
        self.h_colors_tool = XCAFDoc.XCAFDoc_DocumentTool_ColorTool(
            self.doc.Main())
        self.shape_tool = self.h_shape_tool.GetObject()
        self.color_tool = self.h_colors_tool.GetObject()

        self.shapes = TDF_LabelSequence()
        self.shape_tool.GetShapes(self.shapes)
        for i in range(self.shapes.Length()):
            shape = self.shapes.Value(i + 1)
            if self.shape_tool.IsSimpleShape(shape):
                compShape = self.shape_tool.GetShape(shape)
                t = Topo(compShape)
                if t.number_of_vertices() > 0:
                    label = get_label_name(shape)
                    color = find_color(shape, self.color_tool, self.shape_tool)
                    self.shapes_simples.append(
                        SimpleShape(label, compShape, color))

        roots = TDF_LabelSequence()
        self.shape_tool.GetFreeShapes(roots)
        self.thumbnail_valid = False
        if roots.Length() == 1:
            shape = self.shape_tool.GetShape(roots.Value(1))
            t = Topo(shape)
            if t.number_of_vertices() > 0:
                bbox = Bnd_Box()
                gap = 0
                bbox.SetGap(gap)

                BRepMesh_Mesh(shape, get_mesh_precision(shape, 1))
                faces_iterator = Topo(shape).faces()
                for F in faces_iterator:
                    face_location = TopLoc_Location()
                    BRep_Tool_Triangulation(F, face_location)
                BRepBndLib_Add(shape, bbox)
                x_min, y_min, z_min, x_max, y_max, z_max = bbox.Get()
                diagonal = max(x_max - x_min, y_max - y_min, z_max - z_min)
                if diagonal > 0:
                    self.scale = 200. / diagonal
                    self.trans = ((x_max - x_min) / 2. - x_max,
                                  (y_max - y_min) / 2. - y_max,
                                  (z_max - z_min) / 2. - z_max)
                    self.thumbnail_valid = True

        ws = self.STEPReader.Reader().WS().GetObject()
        model = ws.Model().GetObject()
        model.Clear()
Exemplo n.º 10
0
class StepImporter(object):
    """

    :param file_path: Path of the file **.stp** to analyzing
    :param id: For the generation of the :class:`.Product`, **id** is assigned like product.doc_id for every node of :class:`.Product`. For the generation of the files of geometry **.geo**, **id** , together with an index generated by the class, are used to identify the content of every file



    Generates from a path of :class:`~django.core.files.File` **.stp**:


    -A set of files **.geo** that represents the geometry of the different simple products that are useful to realize the visualization 3D across the web browser.

    -A structure of information that represents the arborescencse of the different assemblies,represented in a  :class:`.Product` . (Including his spatial location and orientation and his label of reference (:class:`.OCC.TDF.TDF_Label`))


    This class is invoked from three different subprocesses related to the functionality of pythonOCC(generate3D.py , generateComposition.py , generateDecomposition.py).

   """
    def __init__(self, file_path, id=None):

        self.file = file_path.encode("utf-8")
        self.id = id
        self.shapes_simples = []
        self.main_product = None
        basename = os.path.basename(self.file)
        self.fileName = os.path.splitext(basename)[0]

        self.STEPReader = STEPCAFControl_Reader()

        if self.STEPReader.ReadFile(self.file) != 1:
            raise OCCReadingStepError

        self.h_doc = TDocStd.Handle_TDocStd_Document()
        self.app = XCAFApp.GetApplication().GetObject()
        self.app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"),
                             self.h_doc)

        self.STEPReader.Transfer(self.h_doc)

        self.doc = self.h_doc.GetObject()
        self.h_shape_tool = XCAFDoc.XCAFDoc_DocumentTool_ShapeTool(
            self.doc.Main())
        self.h_colors_tool = XCAFDoc.XCAFDoc_DocumentTool_ColorTool(
            self.doc.Main())
        self.shape_tool = self.h_shape_tool.GetObject()
        self.color_tool = self.h_colors_tool.GetObject()

        self.shapes = TDF_LabelSequence()
        self.shape_tool.GetShapes(self.shapes)
        for i in range(self.shapes.Length()):
            shape = self.shapes.Value(i + 1)
            if self.shape_tool.IsSimpleShape(shape):
                compShape = self.shape_tool.GetShape(shape)
                t = Topo(compShape)
                if t.number_of_vertices() > 0:
                    label = get_label_name(shape)
                    color = find_color(shape, self.color_tool, self.shape_tool)
                    self.shapes_simples.append(
                        SimpleShape(label, compShape, color))

        roots = TDF_LabelSequence()
        self.shape_tool.GetFreeShapes(roots)
        self.thumbnail_valid = False
        if roots.Length() == 1:
            shape = self.shape_tool.GetShape(roots.Value(1))
            t = Topo(shape)
            if t.number_of_vertices() > 0:
                bbox = Bnd_Box()
                gap = 0
                bbox.SetGap(gap)

                BRepMesh_Mesh(shape, get_mesh_precision(shape, 1))
                faces_iterator = Topo(shape).faces()
                for F in faces_iterator:
                    face_location = TopLoc_Location()
                    BRep_Tool_Triangulation(F, face_location)
                BRepBndLib_Add(shape, bbox)
                x_min, y_min, z_min, x_max, y_max, z_max = bbox.Get()
                diagonal = max(x_max - x_min, y_max - y_min, z_max - z_min)
                if diagonal > 0:
                    self.scale = 200. / diagonal
                    self.trans = ((x_max - x_min) / 2. - x_max,
                                  (y_max - y_min) / 2. - y_max,
                                  (z_max - z_min) / 2. - z_max)
                    self.thumbnail_valid = True

        ws = self.STEPReader.Reader().WS().GetObject()
        model = ws.Model().GetObject()
        model.Clear()

    def compute_geometries(self, root_path, pov_dir):
        """

        :param root_path: Path where to store the files **.geo** generated

        When we generate a new :class:`.StepImporter` we will refill a list(**shapes_simples**) whit the :class:`.SimpleShape` contained in the file **.stp**

        For each :class:`.SimpleShape` in the list **shapes_simples**:

            We call the method :func:`.write_geometries` to generate a file **.geo** representative of its geometry,the content of the file is identified by the index+1 (>0) of the position of the :class:`.SimpleShape` in the list of **SimpleShapes**  and by the attribue id of :class:`.StepImporter`

        Returns the list of the path of the generated **.geo** files

        """
        files_index = ""
        self.povs = []

        for index, shape in enumerate(self.shapes_simples):
            name = get_available_name(root_path, self.fileName + ".geo")
            path = os.path.join(root_path, name)
            identifier = "_" + str(index + 1) + "_" + str(self.id)
            writer = GeometryWriter(shape, 0.3)
            pov_filename = os.path.join(pov_dir,
                                        os.path.basename(path + ".inc"))
            writer.write_geometries(identifier, path, pov_filename)
            files_index += "GEO:" + name + " , " + str(index + 1) + "\n"
            if writer.triangle_count:
                self.povs.append((os.path.basename(name + ".inc"), identifier))

        return files_index

    def generate_product_arbre(self):
        """

        Generates a :class:`.Product` relative to the assemblies of the file **.stp**, for every node of the :class:`.Product` it includes a label (:class:`.OCC.TDF.TDF_Label`) that represents and identifies the node , openPLM can only work whit a single root **.stp** files

        """

        roots = TDF_LabelSequence()
        self.shape_tool.GetFreeShapes(roots)
        if roots.Length() != 1:
            raise MultiRootError

        deep = 0
        product_id = [1]
        root = roots.Value(1)
        name = get_label_name(root)
        self.main_product = Product(name, deep, root, self.id, product_id[0],
                                    self.file)
        product_id[0] += 1
        expand_product(self.shape_tool, self.main_product, self.shapes_simples,
                       deep + 1, self.id, self.main_product, product_id,
                       self.file)

        return self.main_product
Exemplo n.º 11
0
def expand_product(shape_tool, product, shapes_simples, deep, doc_id,
                   product_root, product_id, file_path):
    """
    :param shape_tool: :class:`.OCC.XCAFDoc.XCAFDoc_ShapeTool`
    :param product: :class:`.Product` that will be expanded
    :param shapes_simples: list of :class:`.SimpleShape`
    :param deep: Depth of the node that we explore
    :param doc_id: id that references a :class:`.DocumentFile` of which we are generating the :class:`.Product`
    :param product_root: :class:`.Product` root of the arborescense


    We are going to expand a :class:`.Product` (**product**) from the :class:`.OCC.TDF.TDF_Label` who identifies it (**product**.label_reference)


    If the **product** is an assembly:

        * We generate the **list** of the :class:`.OCC.TDF.TDF_Label` that define it

        * for each :class:`.OCC.TDF.TDF_Label` in **list**:

            - We generate a new :class:`.document3D.classes.Link`  or if two or more :class:`.OCC.TDF.TDF_Label` of the list are partner, add an occurrence extra to the :class:`.document3D.classes.Link` that already was generated

            - The :class:`.document3D.classes.Link` is going to point at a new :class:`.Product` or, if the :class:`.Product` is already present in **product_root**, at the already definite product

            - If the :class:`.document3D.classes.Link` pointed at a new :class:`.Product` we need to expand it

                * The atribute **label_reference** of the new :class:`.Product` should be the :class:`.OCC.TDF.TDF_Label`

                * We expand the :class:`.Product` in a recursive call of method


    Else the **product** is a simple shape:

       * We look in the list of **shapes_simples** for his partner

       * We set the attribute **product**.geometry like the index+1 (>0) of the position of his partner in the list of **SimpleShape**

    """
    if shape_tool.IsAssembly(product.label_reference):
        l_c = TDF_LabelSequence()
        shape_tool.GetComponents(product.label_reference, l_c)
        for i in range(l_c.Length()):
            label = l_c.Value(i + 1)
            if shape_tool.IsReference(label):
                label_reference = TDF_Label()
                shape_tool.GetReferredShape(label, label_reference)
                reference_found = False
                matrix = TransformationMatrix(
                    get_matrix(shape_tool.GetLocation(label).Transformation()))
                shape = shape_tool.GetShape(label_reference)
                for link in product.links:
                    if shape_tool.GetShape(
                            link.product.label_reference).IsPartner(shape):
                        link.add_occurrence(get_label_name(label), matrix)
                        reference_found = True
                        break

                if not reference_found:
                    new_product = Product(get_label_name(label_reference),
                                          deep, label_reference, doc_id,
                                          product_id[0], file_path)
                    product_assembly = search_assembly(new_product,
                                                       product_root)
                    if product_assembly:
                        product.links.append(Link(product_assembly))
                    else:
                        product.links.append(Link(new_product))
                        product_id[0] += 1
                        expand_product(shape_tool, new_product, shapes_simples,
                                       deep + 1, doc_id, product_root,
                                       product_id, file_path)

                    product.links[-1].add_occurrence(get_label_name(label),
                                                     matrix)
    else:
        compShape = shape_tool.GetShape(product.label_reference)
        for index in range(len(shapes_simples)):
            if compShape.IsPartner(shapes_simples[index].shape):
                product.set_geometry(index + 1)  #to avoid index==0
Exemplo n.º 12
0
    def loadShape(self, shape_list):
        """
        Method for loading one or more shapes and displaying to Output Viewer.

        This method uses libraries of iges caf control for fetching sub-shape names within .igs files. This method
        is used when adding a case in the main routine.

        @param shape_list [list] First index contains the path of shape, second index contains a list of display
        exceptions, e.g: [[igs_2d_shape_path, ["HUB", "SHROUD"], [igs_3d_shape_path, ["STREAM"]]
        @return First return contains list of ais_shapes handles and second return contains a list of sub-shape names
        in strings
        """
        loaded_ais_shape = []
        loaded_h_ais_shape = []
        loaded_subshape_names = []
        default_displaying_h_ais_shape = []

        for shape_case in shape_list:

            loaded_shape_filename = os.path.basename(shape_case[0])
            exception_list = shape_case[1]
            exception_list = list(
                filter(None, exception_list)
            )  # Mistake-prevention of user filling of exception list

            # creates a handle for TdocStd documents
            h_doc = Handle_TDocStd_Document()

            # create the application
            app = _XCAFApp.XCAFApp_Application_GetApplication().GetObject()
            app.NewDocument(TCollection_ExtendedString(""), h_doc)

            # get root assembly
            doc = h_doc.GetObject()
            h_shape_tool = XCAFDoc_DocumentTool().ShapeTool(doc.Main())

            # creates a reader responsible for reading an IGS file
            reader = IGESCAFControl_Reader()
            reader.ReadFile(shape_case[0])

            #  Translates currently loaded IGES file into the document
            reader.Transfer(doc.GetHandle())

            # labels for the shapes. Every IGS file contains a name for each individual shape
            labels = TDF_LabelSequence()

            shape_tool = h_shape_tool.GetObject()
            shape_tool.GetShapes(labels)

            # gets the number of individual shapes contained in the igs file
            nb = reader.NbShapes()

            # for each individual shape gets the label nad creates a AIS_Shape for data contained in reader.Shape()
            for i in range(1, nb + 1):
                label = labels.Value(i)

                h_name = Handle_TDataStd_Name()
                label.FindAttribute(TDataStd_Name_GetID(), h_name)
                str_dump = h_name.GetObject().DumpToString()
                name_subshape = str_dump.split('|')[-2]
                name = "%s - %s" % (loaded_shape_filename, name_subshape)

                loaded_subshape_names.append(name)

                shape = AIS_ColoredShape(reader.Shape(i))
                loaded_ais_shape.append(shape)
                loaded_h_ais_shape.append(shape.GetHandle())

                if not any(iterator in name_subshape
                           for iterator in exception_list):
                    default_displaying_h_ais_shape.append(shape.GetHandle())

                self.op_viewer.master_shape_list.append(shape.GetHandle())

            # number of cases is a variable used to make the loaded shape color different from the previous one
            number_of_cases = self.op_viewer.model.rowCount(
                self.op_viewer.ui_case_treeview.rootIndex())

            # sets the default attributes for ais shapes handles
            for h_ais_shape in loaded_h_ais_shape:
                self.op_viewer.display.Context.SetDeviationCoefficient(
                    h_ais_shape,
                    self.op_viewer.DC / self.op_viewer.default_shape_factor)
                self.op_viewer.display.Context.SetHLRDeviationCoefficient(
                    h_ais_shape, self.op_viewer.DC_HLR /
                    self.op_viewer.default_shape_factor)
                self.op_viewer.display.Context.SetColor(
                    h_ais_shape, shape_colordictionary[shape_colorlist[
                        (self.op_viewer.default_shape_color + number_of_cases)
                        % len(shape_colorlist)]])

                self.op_viewer.display.Context.SetTransparency(
                    h_ais_shape, self.op_viewer.default_shape_transparency)

        # displays the handles of the ais_shapes in the viewer3d context.
        for h_ais_shape in default_displaying_h_ais_shape:
            self.op_viewer.display.Context.Display(h_ais_shape)

        return loaded_h_ais_shape, loaded_subshape_names