Esempio n. 1
0
 def print_epochs(self, indent = '', **kwargs):
     indent = indent
     Primitive.print_epochs(self, indent = indent, **kwargs)
     print('')
     for element in self.elements:
         element.print_epochs(indent = ' '*len(indent) + '- ', **kwargs)
         print('')
Esempio n. 2
0
    def report(self, indent = '', **kwargs):
        w = 14 # this should be the same as that from Primitive.report
        indent = indent
        if 'primitives' in kwargs.keys():
            primitives = kwargs['primitives']
        else:
            frame_locals = inspect.currentframe().f_back.f_locals
            primitives = filter_by_class(frame_locals, Primitive, option = 'inclusive')


        Primitive.report(self, indent = indent, primitives = primitives)
        if self.elements == []:
            print(indent + ' '*2),
            print(str('{0:<' + str(w) + '}').format('no elements'))
            return
        elif len(self.elements) == 1:
            print(indent + ' '*2),
            print(str('{0:<' + str(w) + '}').format('1 element') + ':'),
        else:
            print(indent + ' '*2),
            print(str('{0:<' + str(w) + '}').format(str(len(self.elements)) + ' elements') + ':'),
        element = self.elements[0]
        print(' '*3 + '- '),
        print("\bid: %s"%id(element)),
        print(' '*2),
        print('{0:<14}'.format('(' + find_name(element, primitives) + ')'))
        
        for element in self.elements[1:]:
            print(indent + ' '*(w+8) + '- '),
            print("\bid: %s"%id(element)),
            print(' '*2),
            print('{0:<14}'.format('(' + find_name(element, primitives) + ')'))
Esempio n. 3
0
 def print_report(self, indent='', **kwargs):
     w = 14  # should be same as Primitive.print_report
     indent = indent
     Primitive.print_report(self, indent=indent, **kwargs)
     print(indent + ' ' * 2),
     print(str('{0:<' + str(w) + '}').format('stage') + ':'),
     print(' ' * 2),
     print('{0:<14}'.format(self.stage))
Esempio n. 4
0
 def __init__(self, file_name):
     Primitive.__init__(self)
     self.anchor = ORIGIN
     self.cardinals, self.elements = get_svg_elements(file_name)
     for element in self.elements:
         element.masters.append(self)
     self.external_call = False
     self.update_epochs()
Esempio n. 5
0
    def __init__(self, *args, **kwargs):
        Primitive.__init__(self, *args, **kwargs)

        datas = (('Width', float, 'width'), ('Depth', float, 'depth'),
                 ('Height', float, 'height'), ('Origin', pm.Point3, 'origin'))
        for data in datas:
            self.AddAttributes(NPOAttr(*data, pyTagName=TAG_PRIMITIVE_OBJECT),
                               parent='Box')
Esempio n. 6
0
 def __init__(self,
              stage='intro',
              pace='smooth',
              duration=DEFAULT_EFFECT_DURATION):
     Primitive.__init__(self)
     self.stage = stage
     self.epochs = initialize_epochs(stage, duration)
     self.pace = pace
Esempio n. 7
0
    def __init__(self, *args, **kwargs):
        Primitive.__init__(self, *args, **kwargs)

        datas = (('Radius', float, 'radius'), ('Height', float, 'height'),
                 ('NumSegs', int, 'numSegs'), ('Degrees', int, 'degrees'),
                 ('Axis', pm.Vec3, 'axis'), ('Origin', pm.Point3, 'origin'))
        for data in datas:
            self.AddAttributes(NPOAttr(*data, pyTagName=TAG_PRIMITIVE_OBJECT),
                               parent='Cone')
Esempio n. 8
0
    def __init__(self, *args, **kwargs):
        Primitive.__init__(self, *args, **kwargs)

        datas = (
            ("Width", float, "width"),
            ("Depth", float, "depth"),
            ("Height", float, "height"),
            ("Origin", pm.Point3, "origin"),
        )
        for data in datas:
            self.AddAttributes(NPOAttr(*data, pyTagName=TAG_PRIMITIVE_OBJECT), parent="Box")
Esempio n. 9
0
 def __init__( self, *args, **kwargs ):
     Primitive.__init__( self, *args, **kwargs )
     
     datas = (
         ('Width', float, 'width'),
         ('Depth', float, 'depth'),
         ('Height', float, 'height'),
         ('Origin', pm.Point3, 'origin')
     )
     for data in datas:
         self.AddAttributes( NPOAttr( *data, pyTagName=TAG_PRIMITIVE_OBJECT ), parent='Box' )
Esempio n. 10
0
 def __init__( self, *args, **kwargs ):
     Primitive.__init__( self, *args, **kwargs )
     
     datas = (
         ('Radius', float, 'radius'),
         ('NumSegs', int, 'numSegs'),
         ('Degrees', int, 'degrees'),
         ('Axis', pm.Vec3, 'axis'),
         ('Origin', pm.Point3, 'origin')
     )
     for data in datas:
         self.AddAttributes( NPOAttr( *data, pyTagName=TAG_PRIMITIVE_OBJECT ), parent='Sphere' )
Esempio n. 11
0
def type_1(factory_object, primitives, kwargs):
    # Args
    x0 = kwargs['x0']
    x1 = kwargs['x1']
    y0 = kwargs['y0']
    y1 = kwargs['y1']
    z0 = kwargs['z0']
    z1 = kwargs['z1']
    lc = kwargs['lc']
    tx = kwargs['tx']
    ty = kwargs['ty']
    tz = kwargs['tz']
    pn = kwargs['pn']
    sns = kwargs['sns']
    factory_str = kwargs['factory']
    primitives.append(
        Primitive(factory_str, [
            [x1, y1, z0, lc],
            [x0, y1, z0, lc],
            [x0, y0, z0, lc],
            [x1, y0, z0, lc],
            [x1, y1, z1, lc],
            [x0, y1, z1, lc],
            [x0, y0, z1, lc],
            [x1, y0, z1, lc],
        ], [0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [[], [], [], [], [], [], [], [], [], [], [], []],
                  [tx, ty, tz],
                  0,
                  physical_name=pn,
                  surfaces_names=sns))
Esempio n. 12
0
def type_11(factory_object, primitives, kwargs):
    # Args
    """
    Arcs: X Y NX NY
    :param factory_object:
    :param primitives:
    :param kwargs:
    """
    factory = kwargs['factory']
    transform_data = kwargs['transform_data']
    args = kwargs['args']
    string_args = kwargs['string_args']
    array_args = kwargs['array_args']
    lx = args[0]
    ly = args[1]
    lz = args[2]
    lc = args[3]
    tt = args[4]
    r = args[5]
    tx = array_args[0]
    ty = array_args[1]
    tz = array_args[2]
    physical_name = string_args[0]
    # Init
    hlx = lx / 2
    hly = ly / 2
    hlz = lz / 2
    p = Primitive(factory=factory,
                  point_data=[
                      [hlx, hly, -hlz, lc],
                      [-hlx, hly, -hlz, lc],
                      [-hlx, -hly, -hlz, lc],
                      [hlx, -hly, -hlz, lc],
                      [hlx, hly, hlz, lc],
                      [-hlx, hly, hlz, lc],
                      [-hlx, -hly, hlz, lc],
                      [hlx, -hly, hlz, lc],
                  ],
                  transform_data=transform_data,
                  curve_types=[0, 3, 3, 0, 0, 0, 3, 3, 0, 0, 0, 0],
                  curve_data=[[], [[0, hly, hlz + r]], [[0, -hly, hlz + r]],
                              [], [], [], [[-hlx, 0, hlz + r]],
                              [[hlx, 0, hlz + r]], [], [], [], []],
                  transfinite_data=[tx, ty, tz],
                  transfinite_type=tt,
                  physical_name=physical_name)
    primitives.append(p)
Esempio n. 13
0
 def __init__(self, factory, inputs, physical_names, reader, reader_kwargs,
              coordinates_transform, mesh_size_coefficients):
     if factory == 'occ':
         factory_object = gmsh.model.occ
     else:
         factory_object = gmsh.model.geo
     primitives = list()
     for i, path in enumerate(inputs):
         result = check_file(path)
         reader_kwargs["path"] = result['path']
         points, polygons = readers[reader](**reader_kwargs)
         print('Transform coordinates')
         points = transform_coordinates(points, coordinates_transform)
         print('last point: {}'.format(points[-1]))
         print('Evaluate groups')
         groups_points, groups_polygons = evaluate_groups(points, polygons)
         print('Number of groups points: {}\nNumber of groups polygons: {}'.
               format([len(x) for x in groups_points],
                      [len(x) for x in groups_polygons]))
         print('Groups: {}'.format(len(groups_points)))
         print('Check closed volumes')
         result = check_closed_volume(polygons, groups_polygons)
         print('Closed volumes {}'.format(sum(result)))
         print(result)
         # Leave only closed volumes
         closed_groups_points = list(
             itertools.compress(groups_points, result))
         closed_groups_polygons = list(
             itertools.compress(groups_polygons, result))
         print('Evaluate sizes')
         sizes = evaluate_groups_points_mesh_sizes(points, polygons,
                                                   closed_groups_polygons)
         print(sizes)
         print('Correct sizes by coefficient')
         k = mesh_size_coefficients[i]
         print('Coefficient: {}'.format(k))
         sizes = [k * x for x in sizes]
         print(sizes)
         print('Create closed volumes only')
         vs = create_volumes(factory_object, points, polygons,
                             closed_groups_points, closed_groups_polygons,
                             sizes)
         name = physical_names[i]
         p = Primitive(factory, physical_name=name, inner_volumes=vs)
         primitives.append(p)
     Complex.__init__(self, factory, primitives)
Esempio n. 14
0
 def shift_to_begin_at(self, begin_time_or_object, **kwargs):
     with PostponeTimeUpdatingToEnd(self):
         begin_time = Primitive.shift_to_begin_at(self,
                                                  begin_time_or_object,
                                                  **kwargs)
     return begin_time
Esempio n. 15
0
 def shift_to_end_at(self, end_time_or_object, **kwargs):
     with PostponeTimeUpdatingToEnd(self):
         end_time = Primitive.shift_to_end_at(self, end_time_or_object,
                                              **kwargs)
     return end_time
Esempio n. 16
0
 def delay(self, delay):
     with PostponeCurveTimeUpdatingToEnd(self):
         for curve in get_subelements_by_class(self.elements, [], Curve):
             delay = Primitive.delay(curve, delay)                
     return delay
Esempio n. 17
0
 def print_epochs(self, indent='', **kwargs):
     indent = indent
     Primitive.print_epochs(self, indent=indent, **kwargs)
     print('')
     for effect in self.effects:
         effect.print_epochs(indent=' ' * len(indent) + '> ', **kwargs)
Esempio n. 18
0
        print("[INFO] Displaying Matching Results on staff", i + 1)
        for box in sharp_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "sharp"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7,
                                       thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color,
                        text, (x, y),
                        font,
                        fontScale=0.7,
                        color=red,
                        thickness=1)
            sharp = Primitive("sharp", 0, box)
            staff_primitives.append(sharp)

        print("[INFO] Matching flat accidental template...")
        flat_boxes = locate_templates(staff_img, flat_imgs, flat_lower,
                                      flat_upper, flat_thresh)
        flat_boxes = merge_boxes([j for i in flat_boxes for j in i], 0.5)

        print("[INFO] Displaying Matching Results on staff", i + 1)
        for box in flat_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "flat"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7,
                                       thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
Esempio n. 19
0
    (-2, -1.5),
    (+1, -2.5),
    (-2, +1.5),
    (+2, -1.5),
    (-1, +2.5),
    (+2, +1.5),
    (+1, +2.5),
]
eye_pupil = [
    (-1, -1),
    (-1, +1),
    (+1, -1),
    (+1, +1),
]
eye_left = Shape([
    Primitive(eye_white, Color.white).offset(+2, +1.5),
    Primitive(eye_pupil, Color.black).offset(+1, +2)
])
eye_right = Shape([
    Primitive(eye_white, Color.white).offset(-4, +1.5),
    Primitive(eye_pupil, Color.black).offset(-5, +2)
])

ghost_body1 = [
    (-7, -7),  # 0
    (-7.0, 0.0),  # 1
    (-5, -5),  # 22
    (-6.7, 2.0),  # 2
    (-3, -7),  # 21
    (-5.9, 3.8),  # 3
    (-1, -7),  # 20
Esempio n. 20
0
 def set_duration(self, duration, **kwargs):
     with PostponeTimeUpdatingToEnd(self):
         duration = Primitive.set_duration(self, duration, **kwargs)
     return duration
Esempio n. 21
0
 def __init__(self, factory, radii, heights, layers_lcs, transform_data,
              layers_physical_names, transfinite_r_data, transfinite_h_data,
              transfinite_phi_data, straight_boundary=None,
              layers_surfaces_names=None, surfaces_names=None,
              volumes_names=None):
     """
     Multilayer cylinder
     Used for axisymmetric objects
     Layers structure:
     h - height
     c - radius
     hM_r1 hM_r2 ... hM_rN
     ...   ...   ... ...
     h2_r1 h2_r2 ... h2_rN
     h1_r1 h1_r2 ... h1_rN
     Bottom center of h1_r1 layer is an origin of the cylinder
     :param str factory: see Primitive
     :param list of float radii: layers outer radii [r1, r2, ..., rN]
     :param list of float heights: layers heights [h1, h2, ..., hM]
     :param list of list of float layers_lcs: characteristic lengths
     of layers
     [[h1_r1, h1_r2, ..., h1_rN], [h2_r1, h2_r2, ..., h2_rN], ...,
     [hM_r1, hM_r2, ..., hM_rN]]
     :param list of float transform_data: relative to cylinder bottom
     (see Primitive)
     :param list of list of str layers_physical_names: physical names
     of layers
     [[h1_r1, h1_r2, ..., h1_rN], [h2_r1, h2_r2, ..., h2_rN], ...,
     [hM_r1, hM_r2, ..., hM_rN]]
     :param list of list of float transfinite_r_data: see Primitive
     [[number of r1 nodes, type, coefficient], [number of r2 nodes, type,
     coefficient], ...]
     :param list of list of float transfinite_h_data: see Primitive
     [[number of h1 nodes, type, coefficient], [number of h2 nodes, type,
     coefficient], ...]
     :param list of float transfinite_phi_data: see Primitive
     [number of circumferential nodes, type, coefficient]
     :param list of int straight_boundary: radii layers form of curves:
     0 - ||
     1 - |)
     2 - )|
     3 - ))
     :param list of list of int layers_surfaces_names:
     :param list of list of str surfaces_names:
     :param list of str volumes_names:
     :return None
     """
     primitives = []
     k = 1 / 3.0  # inner quadrangle part of the first layer radius
     transfinite_types = [0, 0, 0, 1, 3]
     h_cnt = 0.0  # height counter
     if layers_lcs is None:
         layers_lcs = [[1 for _ in radii] for _ in heights]
     if surfaces_names is None:
         surfaces_names = [['NX', 'X', 'NY', 'Y', 'NZ', 'Z']]
     if layers_surfaces_names is None:
         layers_surfaces_names = [[0 for _ in radii] for _ in heights]
     if volumes_names is not None:
         new_layers_physical_names = [[volumes_names[x] for x in y]
                                      for y in layers_physical_names]
         layers_physical_names = new_layers_physical_names
     for i, h in enumerate(heights):
         c = radii[0] / math.sqrt(2.0)
         kc = k * radii[0] / math.sqrt(2.0)
         bottom_h = h_cnt  # primitive bottom h
         top_h = h_cnt + h  # primitive top h
         h_cnt += h
         if straight_boundary is None:
             # Core center
             primitives.append(Primitive(
                 factory,
                 [
                     [kc, kc, bottom_h, layers_lcs[i][0]],
                     [-kc, kc, bottom_h, layers_lcs[i][0]],
                     [-kc, -kc, bottom_h, layers_lcs[i][0]],
                     [kc, -kc, bottom_h, layers_lcs[i][0]],
                     [kc, kc, top_h, layers_lcs[i][0]],
                     [-kc, kc, top_h, layers_lcs[i][0]],
                     [-kc, -kc, top_h, layers_lcs[i][0]],
                     [kc, -kc, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                 [[], [], [], [], [], [], [], [], [], [], [], []],
                 [
                     transfinite_phi_data,
                     transfinite_phi_data,
                     transfinite_h_data[i]
                 ],
                 transfinite_types[0],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[layers_surfaces_names[i][0]]
             ))
             # Core X
             primitives.append(Primitive(
                 factory,
                 [
                     [c, c, bottom_h, layers_lcs[i][0]],
                     [kc, kc, bottom_h, layers_lcs[i][0]],
                     [kc, -kc, bottom_h, layers_lcs[i][0]],
                     [c, -c, bottom_h, layers_lcs[i][0]],
                     [c, c, top_h, layers_lcs[i][0]],
                     [kc, kc, top_h, layers_lcs[i][0]],
                     [kc, -kc, top_h, layers_lcs[i][0]],
                     [c, -c, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
                 [
                     [], [], [], [],
                     [[0, 0, bottom_h, 1]], [], [], [[0, 0, top_h, 1]],
                     [], [], [], []
                 ],
                 [
                     transfinite_r_data[0],
                     transfinite_phi_data,
                     transfinite_h_data[i]
                 ],
                 transfinite_types[1],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[layers_surfaces_names[i][0]]
             ))
             # Core Y
             primitives.append(Primitive(
                 factory,
                 [
                     [c, c, bottom_h, layers_lcs[i][0]],
                     [-c, c, bottom_h, layers_lcs[i][0]],
                     [-kc, kc, bottom_h, layers_lcs[i][0]],
                     [kc, kc, bottom_h, layers_lcs[i][0]],
                     [c, c, top_h, layers_lcs[i][0]],
                     [-c, c, top_h, layers_lcs[i][0]],
                     [-kc, kc, top_h, layers_lcs[i][0]],
                     [kc, kc, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                 [
                     [[0, 0, bottom_h, 1]], [[0, 0, top_h, 1]], [], [],
                     [], [], [], [],
                     [], [], [], []
                 ],
                 [
                     transfinite_phi_data,
                     transfinite_r_data[0],
                     transfinite_h_data[i],
                 ],
                 transfinite_types[2],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[layers_surfaces_names[i][0]]
             ))
             # Core NX
             if transfinite_r_data[0][
                 1] == 0:  # If type is Progression then reverse coefficient
                 rc = 1.0 / transfinite_r_data[0][2]
             else:
                 rc = transfinite_r_data[0][2]
             primitives.append(Primitive(
                 factory,
                 [
                     [-kc, kc, bottom_h, layers_lcs[i][0]],
                     [-c, c, bottom_h, layers_lcs[i][0]],
                     [-c, -c, bottom_h, layers_lcs[i][0]],
                     [-kc, -kc, bottom_h, layers_lcs[i][0]],
                     [-kc, kc, top_h, layers_lcs[i][0]],
                     [-c, c, top_h, layers_lcs[i][0]],
                     [-c, -c, top_h, layers_lcs[i][0]],
                     [-kc, -kc, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
                 [
                     [], [], [], [],
                     [], [[0, 0, bottom_h, 1]], [[0, 0, top_h, 1]], [],
                     [], [], [], []
                 ],
                 [
                     [transfinite_r_data[0][0], transfinite_r_data[0][1],
                      rc],
                     transfinite_phi_data,
                     transfinite_h_data[i]
                 ],
                 transfinite_types[3],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[layers_surfaces_names[i][0]]
             ))
             # Core NY
             if transfinite_r_data[0][
                 1] == 0:  # If type is Progression then reverse coefficient
                 rc = 1.0 / transfinite_r_data[0][2]
             else:
                 rc = transfinite_r_data[0][2]
             primitives.append(Primitive(
                 factory,
                 [
                     [kc, -kc, bottom_h, layers_lcs[i][0]],
                     [-kc, -kc, bottom_h, layers_lcs[i][0]],
                     [-c, -c, bottom_h, layers_lcs[i][0]],
                     [c, -c, bottom_h, layers_lcs[i][0]],
                     [kc, -kc, top_h, layers_lcs[i][0]],
                     [-kc, -kc, top_h, layers_lcs[i][0]],
                     [-c, -c, top_h, layers_lcs[i][0]],
                     [c, -c, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                 [
                     [], [], [[0, 0, top_h, 1]], [[0, 0, bottom_h, 1]],
                     [], [], [], [],
                     [], [], [], []
                 ],
                 [
                     transfinite_phi_data,
                     [transfinite_r_data[0][0], transfinite_r_data[0][1],
                      rc],
                     transfinite_h_data[i],
                 ],
                 transfinite_types[4],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[layers_surfaces_names[i][0]]
             ))
             # Layers
             for j in range(1, len(radii)):
                 c1 = radii[j - 1] / math.sqrt(2.0)
                 c2 = radii[j] / math.sqrt(2.0)
                 # Layer X
                 primitives.append(Primitive(
                     factory,
                     [
                         [c2, c2, bottom_h, layers_lcs[i][j]],
                         [c1, c1, bottom_h, layers_lcs[i][j]],
                         [c1, -c1, bottom_h, layers_lcs[i][j]],
                         [c2, -c2, bottom_h, layers_lcs[i][j]],
                         [c2, c2, top_h, layers_lcs[i][j]],
                         [c1, c1, top_h, layers_lcs[i][j]],
                         [c1, -c1, top_h, layers_lcs[i][j]],
                         [c2, -c2, top_h, layers_lcs[i][j]]
                     ],
                     transform_data,
                     [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
                     [
                         [], [], [], [],
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, top_h, 1]],
                         [], [], [], []
                     ],
                     [
                         transfinite_r_data[j],
                         transfinite_phi_data,
                         transfinite_h_data[i]
                     ],
                     transfinite_types[1],
                     layers_physical_names[i][j],
                     surfaces_names=surfaces_names[
                         layers_surfaces_names[i][j]]
                 ))
                 # Layer Y
                 primitives.append(Primitive(
                     factory,
                     [
                         [c2, c2, bottom_h, layers_lcs[i][j]],
                         [-c2, c2, bottom_h, layers_lcs[i][j]],
                         [-c1, c1, bottom_h, layers_lcs[i][j]],
                         [c1, c1, bottom_h, layers_lcs[i][j]],
                         [c2, c2, top_h, layers_lcs[i][j]],
                         [-c2, c2, top_h, layers_lcs[i][j]],
                         [-c1, c1, top_h, layers_lcs[i][j]],
                         [c1, c1, top_h, layers_lcs[i][j]]
                     ],
                     transform_data,
                     [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                     [
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, bottom_h, 1]],
                         [], [], [], [],
                         [], [], [], []
                     ],
                     [
                         transfinite_phi_data,
                         transfinite_r_data[j],
                         transfinite_h_data[i]
                     ],
                     transfinite_types[2],
                     layers_physical_names[i][j],
                     surfaces_names=surfaces_names[
                         layers_surfaces_names[i][j]]
                 ))
                 # Layer NX
                 if transfinite_r_data[j][
                     1] == 0:  # If type is Progression then reverse coefficient
                     rc = 1.0 / transfinite_r_data[j][2]
                 else:
                     rc = transfinite_r_data[j][2]
                 primitives.append(Primitive(
                     factory,
                     [
                         [-c1, c1, bottom_h, layers_lcs[i][j]],
                         [-c2, c2, bottom_h, layers_lcs[i][j]],
                         [-c2, -c2, bottom_h, layers_lcs[i][j]],
                         [-c1, -c1, bottom_h, layers_lcs[i][j]],
                         [-c1, c1, top_h, layers_lcs[i][j]],
                         [-c2, c2, top_h, layers_lcs[i][j]],
                         [-c2, -c2, top_h, layers_lcs[i][j]],
                         [-c1, -c1, top_h, layers_lcs[i][j]]
                     ],
                     transform_data,
                     [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
                     [
                         [], [], [], [],
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, top_h, 1]],
                         [], [], [], []
                     ],
                     [
                         [transfinite_r_data[j][0], transfinite_r_data[j][1],
                          rc],
                         transfinite_phi_data,
                         transfinite_h_data[i]
                     ],
                     transfinite_types[3],
                     layers_physical_names[i][j],
                     surfaces_names=surfaces_names[
                         layers_surfaces_names[i][j]]
                 ))
                 # Layer NY
                 if transfinite_r_data[j][
                     1] == 0:  # If type is Progression then reverse coefficient
                     rc = 1.0 / transfinite_r_data[j][2]
                 else:
                     rc = transfinite_r_data[j][2]
                 primitives.append(Primitive(
                     factory,
                     [
                         [c1, -c1, bottom_h, layers_lcs[i][j]],
                         [-c1, -c1, bottom_h, layers_lcs[i][j]],
                         [-c2, -c2, bottom_h, layers_lcs[i][j]],
                         [c2, -c2, bottom_h, layers_lcs[i][j]],
                         [c1, -c1, top_h, layers_lcs[i][j]],
                         [-c1, -c1, top_h, layers_lcs[i][j]],
                         [-c2, -c2, top_h, layers_lcs[i][j]],
                         [c2, -c2, top_h, layers_lcs[i][j]]
                     ],
                     transform_data,
                     [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                     [
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, bottom_h, 1]],
                         [], [], [], [],
                         [], [], [], []
                     ],
                     [
                         transfinite_phi_data,
                         [transfinite_r_data[j][0], transfinite_r_data[j][1],
                          rc],
                         transfinite_h_data[i]
                     ],
                     transfinite_types[4],
                     layers_physical_names[i][j],
                     surfaces_names=surfaces_names[
                         layers_surfaces_names[i][j]]
                 ))
         else:
             if straight_boundary[0] == 0:
                 curve_types = {
                     'C': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     'X': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     'Y': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     'NX': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     'NY': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                 }
             elif straight_boundary[0] == 1:
                 curve_types = {
                     'C': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     'X': [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
                     'Y': [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     'NX': [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
                     'NY': [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
                 }
             elif straight_boundary[0] == 2:
                 curve_types = {
                     'C': [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
                     'X': [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
                     'Y': [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                     'NX': [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
                     'NY': [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                 }
             else:
                 curve_types = {
                     'C': [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
                     'X': [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
                     'Y': [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                     'NX': [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
                     'NY': [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
                 }
             # Core center
             primitives.append(Primitive(
                 factory,
                 [
                     [kc, kc, bottom_h, layers_lcs[i][0]],
                     [-kc, kc, bottom_h, layers_lcs[i][0]],
                     [-kc, -kc, bottom_h, layers_lcs[i][0]],
                     [kc, -kc, bottom_h, layers_lcs[i][0]],
                     [kc, kc, top_h, layers_lcs[i][0]],
                     [-kc, kc, top_h, layers_lcs[i][0]],
                     [-kc, -kc, top_h, layers_lcs[i][0]],
                     [kc, -kc, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 curve_types['C'],
                 [
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, top_h, 1]],
                     [[0, 0, top_h, 1]],
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, top_h, 1]],
                     [[0, 0, top_h, 1]],
                     [], [], [], []],
                 [
                     transfinite_phi_data,
                     transfinite_phi_data,
                     transfinite_h_data[i]
                 ],
                 transfinite_types[0],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[layers_surfaces_names[i][0]]
             ))
             # Core X
             primitives.append(Primitive(
                 factory,
                 [
                     [c, c, bottom_h, layers_lcs[i][0]],
                     [kc, kc, bottom_h, layers_lcs[i][0]],
                     [kc, -kc, bottom_h, layers_lcs[i][0]],
                     [c, -c, bottom_h, layers_lcs[i][0]],
                     [c, c, top_h, layers_lcs[i][0]],
                     [kc, kc, top_h, layers_lcs[i][0]],
                     [kc, -kc, top_h, layers_lcs[i][0]],
                     [c, -c, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 curve_types['X'],
                 [
                     [], [], [], [],
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, top_h, 1]],
                     [[0, 0, top_h, 1]],
                     [], [], [], []
                 ],
                 [
                     transfinite_r_data[0],
                     transfinite_phi_data,
                     transfinite_h_data[i]
                 ],
                 transfinite_types[1],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[
                     layers_surfaces_names[i][0]]
             ))
             # Core Y
             primitives.append(Primitive(
                 factory,
                 [
                     [c, c, bottom_h, layers_lcs[i][0]],
                     [-c, c, bottom_h, layers_lcs[i][0]],
                     [-kc, kc, bottom_h, layers_lcs[i][0]],
                     [kc, kc, bottom_h, layers_lcs[i][0]],
                     [c, c, top_h, layers_lcs[i][0]],
                     [-c, c, top_h, layers_lcs[i][0]],
                     [-kc, kc, top_h, layers_lcs[i][0]],
                     [kc, kc, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 curve_types['Y'],
                 [
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, top_h, 1]],
                     [[0, 0, top_h, 1]],
                     [[0, 0, bottom_h, 1]],
                     [], [], [], [],
                     [], [], [], []
                 ],
                 [
                     transfinite_phi_data,
                     transfinite_r_data[0],
                     transfinite_h_data[i],
                 ],
                 transfinite_types[2],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[layers_surfaces_names[i][0]]
             ))
             # Core NX
             if transfinite_r_data[0][
                 1] == 0:  # If type is Progression then reverse coefficient
                 rc = 1.0 / transfinite_r_data[0][2]
             else:
                 rc = transfinite_r_data[0][2]
             primitives.append(Primitive(
                 factory,
                 [
                     [-kc, kc, bottom_h, layers_lcs[i][0]],
                     [-c, c, bottom_h, layers_lcs[i][0]],
                     [-c, -c, bottom_h, layers_lcs[i][0]],
                     [-kc, -kc, bottom_h, layers_lcs[i][0]],
                     [-kc, kc, top_h, layers_lcs[i][0]],
                     [-c, c, top_h, layers_lcs[i][0]],
                     [-c, -c, top_h, layers_lcs[i][0]],
                     [-kc, -kc, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 curve_types['NX'],
                 [
                     [], [], [], [],
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, top_h, 1]],
                     [[0, 0, top_h, 1]],
                     [], [], [], []
                 ],
                 [
                     [transfinite_r_data[0][0], transfinite_r_data[0][1],
                      rc],
                     transfinite_phi_data,
                     transfinite_h_data[i]
                 ],
                 transfinite_types[3],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[layers_surfaces_names[i][0]]
             ))
             # Core NY
             if transfinite_r_data[0][
                 1] == 0:  # If type is Progression then reverse coefficient
                 rc = 1.0 / transfinite_r_data[0][2]
             else:
                 rc = transfinite_r_data[0][2]
             primitives.append(Primitive(
                 factory,
                 [
                     [kc, -kc, bottom_h, layers_lcs[i][0]],
                     [-kc, -kc, bottom_h, layers_lcs[i][0]],
                     [-c, -c, bottom_h, layers_lcs[i][0]],
                     [c, -c, bottom_h, layers_lcs[i][0]],
                     [kc, -kc, top_h, layers_lcs[i][0]],
                     [-kc, -kc, top_h, layers_lcs[i][0]],
                     [-c, -c, top_h, layers_lcs[i][0]],
                     [c, -c, top_h, layers_lcs[i][0]]
                 ],
                 transform_data,
                 curve_types['NY'],
                 [
                     [[0, 0, bottom_h, 1]],
                     [[0, 0, top_h, 1]],
                     [[0, 0, top_h, 1]],
                     [[0, 0, bottom_h, 1]],
                     [], [], [], [],
                     [], [], [], []
                 ],
                 [
                     transfinite_phi_data,
                     [transfinite_r_data[0][0], transfinite_r_data[0][1],
                      rc],
                     transfinite_h_data[i],
                 ],
                 transfinite_types[4],
                 layers_physical_names[i][0],
                 surfaces_names=surfaces_names[layers_surfaces_names[i][0]]
             ))
             # Layers
             for j in range(1, len(radii)):
                 if straight_boundary[j] == 0:
                     curve_types = {
                         'X': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                         'Y': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                         'NX': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                         'NY': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                     }
                 elif straight_boundary[j] == 1:
                     curve_types = {
                         'X': [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
                         'Y': [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                         'NX': [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
                         'NY': [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
                     }
                 elif straight_boundary[j] == 2:
                     curve_types = {
                         'X': [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
                         'Y': [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                         'NX': [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
                         'NY': [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                     }
                 else:
                     curve_types = {
                         'X': [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
                         'Y': [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                         'NX': [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
                         'NY': [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
                     }
                 c1 = radii[j - 1] / math.sqrt(2.0)
                 c2 = radii[j] / math.sqrt(2.0)
                 # Layer X
                 primitives.append(Primitive(
                     factory,
                     [
                         [c2, c2, bottom_h, layers_lcs[i][j]],
                         [c1, c1, bottom_h, layers_lcs[i][j]],
                         [c1, -c1, bottom_h, layers_lcs[i][j]],
                         [c2, -c2, bottom_h, layers_lcs[i][j]],
                         [c2, c2, top_h, layers_lcs[i][j]],
                         [c1, c1, top_h, layers_lcs[i][j]],
                         [c1, -c1, top_h, layers_lcs[i][j]],
                         [c2, -c2, top_h, layers_lcs[i][j]]
                     ],
                     transform_data,
                     curve_types['X'],
                     [
                         [], [], [], [],
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, top_h, 1]],
                         [], [], [], []
                     ],
                     [
                         transfinite_r_data[j],
                         transfinite_phi_data,
                         transfinite_h_data[i]
                     ],
                     transfinite_types[1],
                     layers_physical_names[i][j],
                     surfaces_names=surfaces_names[
                         layers_surfaces_names[i][j]]
                 ))
                 # Layer Y
                 primitives.append(Primitive(
                     factory,
                     [
                         [c2, c2, bottom_h, layers_lcs[i][j]],
                         [-c2, c2, bottom_h, layers_lcs[i][j]],
                         [-c1, c1, bottom_h, layers_lcs[i][j]],
                         [c1, c1, bottom_h, layers_lcs[i][j]],
                         [c2, c2, top_h, layers_lcs[i][j]],
                         [-c2, c2, top_h, layers_lcs[i][j]],
                         [-c1, c1, top_h, layers_lcs[i][j]],
                         [c1, c1, top_h, layers_lcs[i][j]]
                     ],
                     transform_data,
                     curve_types['Y'],
                     [
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, bottom_h, 1]],
                         [], [], [], [],
                         [], [], [], []
                     ],
                     [
                         transfinite_phi_data,
                         transfinite_r_data[j],
                         transfinite_h_data[i]
                     ],
                     transfinite_types[2],
                     layers_physical_names[i][j],
                     surfaces_names=surfaces_names[
                         layers_surfaces_names[i][j]]
                 ))
                 # Layer NX
                 if transfinite_r_data[j][
                     1] == 0:  # If type is Progression then reverse coefficient
                     rc = 1.0 / transfinite_r_data[j][2]
                 else:
                     rc = transfinite_r_data[j][2]
                 primitives.append(Primitive(
                     factory,
                     [
                         [-c1, c1, bottom_h, layers_lcs[i][j]],
                         [-c2, c2, bottom_h, layers_lcs[i][j]],
                         [-c2, -c2, bottom_h, layers_lcs[i][j]],
                         [-c1, -c1, bottom_h, layers_lcs[i][j]],
                         [-c1, c1, top_h, layers_lcs[i][j]],
                         [-c2, c2, top_h, layers_lcs[i][j]],
                         [-c2, -c2, top_h, layers_lcs[i][j]],
                         [-c1, -c1, top_h, layers_lcs[i][j]]
                     ],
                     transform_data,
                     curve_types['NX'],
                     [
                         [], [], [], [],
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, top_h, 1]],
                         [], [], [], []
                     ],
                     [
                         [transfinite_r_data[j][0],
                          transfinite_r_data[j][1], rc],
                         transfinite_phi_data,
                         transfinite_h_data[i]
                     ],
                     transfinite_types[3],
                     layers_physical_names[i][j],
                     surfaces_names=surfaces_names[
                         layers_surfaces_names[i][j]]
                 ))
                 # Layer NY
                 if transfinite_r_data[j][
                     1] == 0:  # If type is Progression then reverse coefficient
                     rc = 1.0 / transfinite_r_data[j][2]
                 else:
                     rc = transfinite_r_data[j][2]
                 primitives.append(Primitive(
                     factory,
                     [
                         [c1, -c1, bottom_h, layers_lcs[i][j]],
                         [-c1, -c1, bottom_h, layers_lcs[i][j]],
                         [-c2, -c2, bottom_h, layers_lcs[i][j]],
                         [c2, -c2, bottom_h, layers_lcs[i][j]],
                         [c1, -c1, top_h, layers_lcs[i][j]],
                         [-c1, -c1, top_h, layers_lcs[i][j]],
                         [-c2, -c2, top_h, layers_lcs[i][j]],
                         [c2, -c2, top_h, layers_lcs[i][j]]
                     ],
                     transform_data,
                     curve_types['NY'],
                     [
                         [[0, 0, bottom_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, top_h, 1]],
                         [[0, 0, bottom_h, 1]],
                         [], [], [], [],
                         [], [], [], []
                     ],
                     [
                         transfinite_phi_data,
                         [transfinite_r_data[j][0],
                          transfinite_r_data[j][1], rc],
                         transfinite_h_data[i]
                     ],
                     transfinite_types[4],
                     layers_physical_names[i][j],
                     surfaces_names=surfaces_names[
                         layers_surfaces_names[i][j]]
                 ))
     Complex.__init__(self, factory, primitives)
Esempio n. 22
0
File: room.py Progetto: msarch/py
 def make_shape(self):
     primitive = Primitive(self.make_verts(), roomColor)
     self.shape = Shape([primitive])
Esempio n. 23
0
 def __init__(self,
              factory,
              divide_data,
              point_data,
              transform_data=None,
              curve_types=None,
              curve_data=None,
              transfinite_data=None,
              transfinite_type=None,
              physical_name=None,
              inner_volumes=None,
              surfaces_names=None):
     """
     Primitive object divided into parts for boolean accuracy.
     :param str factory: see Primitive
     :param list of int divide_data: [n_parts_x, n_parts_y, n_parts_z]
     :param list point_data: see Primitive
     :param list of float transform_data: see Primitive
     :param list of int curve_types: see Primitive
     :param list curve_data: see Primitive
     :param list of list of float transfinite_data: see Primitive
     :param int transfinite_type: see Primitive
     :param str physical_name: see Primitive
     :param list of int inner_volumes: see Primitive
     :param list of str surfaces_names: see Primitive
     """
     primitives = list()
     if len(point_data) == 3:
         half_lx = point_data[0] / 2.0
         half_ly = point_data[1] / 2.0
         half_lz = point_data[2] / 2.0
         primitive_lc = None
         new_point_data = [[half_lx, half_ly, -half_lz],
                           [-half_lx, half_ly, -half_lz],
                           [-half_lx, -half_ly, -half_lz],
                           [half_lx, -half_ly, -half_lz],
                           [half_lx, half_ly, half_lz],
                           [-half_lx, half_ly, half_lz],
                           [-half_lx, -half_ly, half_lz],
                           [half_lx, -half_ly, half_lz]]
     elif len(point_data) == 4:
         half_lx = point_data[0] / 2.0
         half_ly = point_data[1] / 2.0
         half_lz = point_data[2] / 2.0
         primitive_lc = point_data[3]
         new_point_data = [[half_lx, half_ly, -half_lz],
                           [-half_lx, half_ly, -half_lz],
                           [-half_lx, -half_ly, -half_lz],
                           [half_lx, -half_ly, -half_lz],
                           [half_lx, half_ly, half_lz],
                           [-half_lx, half_ly, half_lz],
                           [-half_lx, -half_ly, half_lz],
                           [half_lx, -half_ly, half_lz]]
     else:
         primitive_lc = None
         new_point_data = [x[:3] for x in point_data]  # slice lc if exist
     if curve_data is None:
         curve_data = [[]] * 12
     if physical_name is None:
         physical_name = ComplexPrimitive.__name__
     ps_base_points, ps_curves_points = divide_primitive(
         divide_data, new_point_data, curve_data)
     for i, bps in enumerate(ps_base_points):
         if primitive_lc is not None:
             new_point_data = [
                 x + [primitive_lc] for x in ps_base_points[i]
             ]
         else:
             new_point_data = ps_base_points[i]
         new_curve_data = list()
         for cps in ps_curves_points[i]:
             if primitive_lc is not None:
                 new_curve_data.append([x + [primitive_lc] for x in cps])
             else:
                 new_curve_data.append(cps)
         primitives.append(
             Primitive(factory, new_point_data, transform_data, curve_types,
                       new_curve_data, transfinite_data, transfinite_type,
                       physical_name, inner_volumes, surfaces_names))
     Complex.__init__(self, factory, primitives)
Esempio n. 24
0
 def set_times(self, times_or_object, **kwargs):
     with PostponeTimeUpdatingToEnd(self):
         times = Primitive.set_times(self, times_or_object, **kwargs)
     return times
Esempio n. 25
0
    (-1, -7),  # 20
    (-4.6, 5.3),  # 4
    (-1, -5),  # 19
    (-2.9, 6.4),  # 5
    (1, -5),  # 18
    (-1.0, 6.9),  # 6
    (3, -7),  # 16
    (1.0, 6.9),  # 7
    (5, -5),  # 15
    (2.9, 6.4),  # 8
    (7, -7),  # 14
    (4.6, 5.3),  # 9
    (7.0, 0.0),  # 13
    (4.6, 5.3),  # 10
    (6.7, 2.0),  # 12
    (5.9, 3.8),  # 11
]

sh = Shape([
    Primitive(ghost, Color.black).offset(+200, +105),
    Primitive(ghost, Color.orange).offset(+300, +200),
    Rect(100, 100, 120, 200, Color.red).offset(100, 200),
    Rect(100, 100, 120, 200, Color.red).rotate(10).offset(200, 600)
])
act1 = Actor()
act1.shape = sh
act1.tick = tick1

#--> FIXME
#--> position?
Esempio n. 26
0
 def SetupNodePath( self ):
     Primitive.SetupNodePath( self )
     
     self.data.setName( 'cylinder' )
     self.data.setTag( game.nodes.TAG_NODE_TYPE, TAG_CYLINDER )
     CylinderNPO( self.data )
Esempio n. 27
0
 def delay(self, delay):
     with PostponeTimeUpdatingToEnd(self):
         delay = Primitive.delay(self, delay)
     return delay
    def __init__(self, w, h, char, parent=None, sizer_borders=(0, 0, 0, 0)):

        Primitive.__init__(self, (w, h), sizer_borders)

        self.char = char
        self.parent = parent
Esempio n. 29
0
def main(filepath):

    #-------------------------------------------------------------------------------
    # Image Preprocessing (Blurring, Noise Removal, Binarization, Deskewing)
    #-------------------------------------------------------------------------------

    # Noise Removal: https://docs.opencv.org/3.3.1/d5/d69/tutorial_py_non_local_means.html
    # Deskewing: https://www.pyimagesearch.com/2017/02/20/text-skew-correction-opencv-python/
    # Binarization + Blurring (Otsu): https://docs.opencv.org/3.3.1/d7/d4d/tutorial_py_thresholding.html

    # ============ Read Image ============
    #img_file = sys.argv[1:][0]
    #img_file = path + r'\test\mary.jpg'
    img = cv2.imread(filepath, 0)

    # ============ Noise Removal ============

    img = cv2.fastNlMeansDenoising(img, None, 10, 7, 21)

    # ============ Binarization ============

    # Global Thresholding
    # retval, img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)

    # Otsu's Thresholding
    retval, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    #cv2.imwrite(path + r'\output\binarized.jpg', img)

    # ============ Deskewing ============

    # angle, img = deskew(img)
    # print("[INFO] Deskew Angle: {:.3f}".format(angle))
    # cv2.imshow("Input", img)
    # cv2.waitKey(0)

    # ============ Reference Lengths ============
    # Reference lengths staff line thickness (staffline_height)
    # and vertical line distance within the same staff (staffspace_height)
    # computed, providing the basic scale for relative size comparisons

    # Use run-length encoding on columns to estimate staffline height and staffspace height

    line_width, line_spacing = get_ref_lengths(img)

    #-------------------------------------------------------------------------------
    # Staff Line Detection
    #-------------------------------------------------------------------------------

    # In practice, several horizontal projections on images with slightly different
    # rotation angles are computed to deal with not completely horizontal staff lines.
    # The projection with the highest local maxima is then chosen.

    # ============ Find Staff Line Rows ============

    all_staffline_vertical_indices = find_staffline_rows(img, line_width, line_spacing)

    # ============ Find Staff Line Columns ============

    # Find column with largest index that has no black pixels

    all_staffline_horizontal_indices = find_staffline_columns(img, all_staffline_vertical_indices, line_width, line_spacing)

    # ============ Show Detected Staffs ============
    staffs = []
    half_dist_between_staffs = (all_staffline_vertical_indices[1][0][0] - all_staffline_vertical_indices[0][4][line_width - 1])//2

    for i in range(len(all_staffline_vertical_indices)):
        # Create Bounding Box
        x = all_staffline_horizontal_indices[i][0]
        y = all_staffline_vertical_indices[i][0][0]
        width = all_staffline_horizontal_indices[i][1] - x
        height = all_staffline_vertical_indices[i][4][line_width - 1] - y
        staff_box = BoundingBox(x, y, width, height)

        # Create Cropped Staff Image
        staff_img = img[max(0, y - half_dist_between_staffs): min(y+ height + half_dist_between_staffs, img.shape[0] - 1), x:x+width]

        # Normalize Staff line Numbers to Cropped Image
        pixel = half_dist_between_staffs
        normalized_staff_line_vertical_indices = []

        for j in range(5):
            line = []
            for k in range(line_width):
                line.append(pixel)
                pixel += 1
            normalized_staff_line_vertical_indices.append(line)
            pixel += line_spacing + 1

        staff = Staff(normalized_staff_line_vertical_indices, staff_box, line_width, line_spacing, staff_img)
        staffs.append(staff)

    staff_boxes_img = img.copy()
    staff_boxes_img = cv2.cvtColor(staff_boxes_img, cv2.COLOR_GRAY2RGB)
    red = (0, 0, 255)
    box_thickness = 2
    for staff in staffs:
        box = staff.getBox()
        box.draw(staff_boxes_img, red, box_thickness)
        x = int(box.getCorner()[0] + (box.getWidth() // 2))
        y = int(box.getCorner()[1] + box.getHeight() + 35)
        cv2.putText(staff_boxes_img, "Staff", (x, y), cv2.FONT_HERSHEY_DUPLEX, 0.9 , red)

    #cv2.imwrite(path + r'\output\detected_staffs.jpg', staff_boxes_img)
    # open_file('output/detected_staffs.jpg')

    #-------------------------------------------------------------------------------
    # Symbol Segmentation, Object Recognition, and Semantic Reconstruction
    #-------------------------------------------------------------------------------

    # The score is then divided into regions of interest to localize and isolate the musical primitives.
    # Music score is analyzed and split by staves
    # Primitive symbols extracted

    # Find all primitives on each stave first
    # then move from left to right and create structure

    # ============ Determine Clef, Time Signature ============

    staff_imgs_color = []

    for i in range(len(staffs)):
        red = (0, 0, 255)
        box_thickness = 2
        staff_img = staffs[i].getImage()
        staff_img_color = staff_img.copy()
        staff_img_color = cv2.cvtColor(staff_img_color, cv2.COLOR_GRAY2RGB)

        # ------- Clef -------
        for clef in clef_imgs:
            clef_boxes = locate_templates(staff_img, clef_imgs[clef], clef_lower, clef_upper, clef_thresh)
            clef_boxes = merge_boxes([j for i in clef_boxes for j in i], 0.5)

            if (len(clef_boxes) == 1):
                staffs[i].setClef(clef)

                clef_boxes_img = staffs[i].getImage()
                clef_boxes_img = clef_boxes_img.copy()

                for boxes in clef_boxes:
                    boxes.draw(staff_img_color, red, box_thickness)
                    x = int(boxes.getCorner()[0] + (boxes.getWidth() // 2))
                    y = int(boxes.getCorner()[1] + boxes.getHeight() + 10)
                    cv2.putText(staff_img_color, "{} clef".format(clef), (x, y), cv2.FONT_HERSHEY_DUPLEX, 0.9, red)
                break

        # # ------- Time -------
        for time in time_imgs:
            time_boxes = locate_templates(staff_img, time_imgs[time], time_lower, time_upper, time_thresh)
            time_boxes = merge_boxes([j for i in time_boxes for j in i], 0.5)

            if (len(time_boxes) == 1):
                staffs[i].setTimeSignature(time)

                for boxes in time_boxes:
                    boxes.draw(staff_img_color, red, box_thickness)
                    x = int(boxes.getCorner()[0] - (boxes.getWidth() // 2))
                    y = int(boxes.getCorner()[1] + boxes.getHeight() + 20)
                    cv2.putText(staff_img_color, "{} time".format(time), (x, y), cv2.FONT_HERSHEY_DUPLEX, 0.9, red)
                break

            elif (len(time_boxes) == 0 and i > 0):
                # Take time signature of previous staff
                previousTime = staffs[i-1].getTimeSignature()
                staffs[i].setTimeSignature(previousTime)
                #print("[INFO] No time signature found on staff", i + 1, ". Using time signature from previous staff line: ", previousTime)
                break

        staff_imgs_color.append(staff_img_color)


    # ============ Find Primitives ============

    # always assert that notes in a bar equal duration dictated by time signature
    for i in range(len(staffs)):
        staff_primitives = []
        staff_img = staffs[i].getImage()
        staff_img_color = staff_imgs_color[i]
        red = (0, 0, 255)
        box_thickness = 2

        # ------- Find primitives on staff -------
        sharp_boxes = locate_templates(staff_img, sharp_imgs, sharp_lower, sharp_upper, sharp_thresh)
        sharp_boxes = merge_boxes([j for i in sharp_boxes for j in i], 0.5)

        for box in sharp_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "sharp"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            sharp = Primitive("sharp", 0, box)
            staff_primitives.append(sharp)

        flat_boxes = locate_templates(staff_img, flat_imgs, flat_lower, flat_upper, flat_thresh)
        flat_boxes = merge_boxes([j for i in flat_boxes for j in i], 0.5)

        for box in flat_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "flat"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            flat = Primitive("flat", 0, box)
            staff_primitives.append(flat)

        quarter_boxes = locate_templates(staff_img, quarter_note_imgs, quarter_note_lower, quarter_note_upper, quarter_note_thresh)
        quarter_boxes = merge_boxes([j for i in quarter_boxes for j in i], 0.5)

        for box in quarter_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "1/4 note"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            pitch = staffs[i].getPitch(round(box.getCenter()[1]))
            quarter = Primitive("note", 1, box, pitch)
            staff_primitives.append(quarter)

        half_boxes = locate_templates(staff_img, half_note_imgs, half_note_lower, half_note_upper, half_note_thresh)
        half_boxes = merge_boxes([j for i in half_boxes for j in i], 0.5)

        for box in half_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "1/2 note"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            pitch = staffs[i].getPitch(round(box.getCenter()[1]))
            half = Primitive("note", 2, box, pitch)
            staff_primitives.append(half)

        whole_boxes = locate_templates(staff_img, whole_note_imgs, whole_note_lower, whole_note_upper, whole_note_thresh)
        whole_boxes = merge_boxes([j for i in whole_boxes for j in i], 0.5)

        for box in whole_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "1 note"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            pitch = staffs[i].getPitch(round(box.getCenter()[1]))
            whole = Primitive("note", 4, box, pitch)
            staff_primitives.append(whole)

        eighth_boxes = locate_templates(staff_img, eighth_rest_imgs, eighth_rest_lower, eighth_rest_upper, eighth_rest_thresh)
        eighth_boxes = merge_boxes([j for i in eighth_boxes for j in i], 0.5)

        for box in eighth_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "1/8 rest"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            eighth = Primitive("rest", 0.5, box)
            staff_primitives.append(eighth)

        quarter_boxes = locate_templates(staff_img, quarter_rest_imgs, quarter_rest_lower, quarter_rest_upper, quarter_rest_thresh)
        quarter_boxes = merge_boxes([j for i in quarter_boxes for j in i], 0.5)

        for box in quarter_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "1/4 rest"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            quarter = Primitive("rest", 1, box)
            staff_primitives.append(quarter)

        half_boxes = locate_templates(staff_img, half_rest_imgs, half_rest_lower, half_rest_upper, half_rest_thresh)
        half_boxes = merge_boxes([j for i in half_boxes for j in i], 0.5)

        for box in half_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "1/2 rest"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            half = Primitive("rest", 2, box)
            staff_primitives.append(half)

        whole_boxes = locate_templates(staff_img, whole_rest_imgs, whole_rest_lower, whole_rest_upper, whole_rest_thresh)
        whole_boxes = merge_boxes([j for i in whole_boxes for j in i], 0.5)

        for box in whole_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "1 rest"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            whole = Primitive("rest", 4, box)
            staff_primitives.append(whole)

        flag_boxes = locate_templates(staff_img, eighth_flag_imgs, eighth_flag_lower, eighth_flag_upper, eighth_flag_thresh)
        flag_boxes = merge_boxes([j for i in flag_boxes for j in i], 0.5)


        for box in flag_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "1/8 flag"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            flag = Primitive("eighth_flag", 0, box)
            staff_primitives.append(flag)

        bar_boxes = locate_templates(staff_img, bar_imgs, bar_lower, bar_upper, bar_thresh)
        bar_boxes = merge_boxes([j for i in bar_boxes for j in i], 0.5)

        for box in bar_boxes:
            box.draw(staff_img_color, red, box_thickness)
            text = "line"
            font = cv2.FONT_HERSHEY_DUPLEX
            textsize = cv2.getTextSize(text, font, fontScale=0.7, thickness=1)[0]
            x = int(box.getCorner()[0] - (textsize[0] // 2))
            y = int(box.getCorner()[1] + box.getHeight() + 20)
            cv2.putText(staff_img_color, text, (x, y), font, fontScale=0.7, color=red, thickness=1)
            line = Primitive("line", 0, box)
            staff_primitives.append(line)

        #cv2.imwrite(path + r'\output\staff_{}_primitives.jpg'.format(i+1), staff_img_color)
        # open_file("output/staff_{}_primitives.jpg".format(i+1))

        # ------- Sort primitives on staff from left to right -------

        staff_primitives.sort(key=lambda primitive: primitive.getBox().getCenter())

        eighth_flag_indices = []
        for j in range(len(staff_primitives)):

            if (staff_primitives[j].getPrimitive() == "eighth_flag"):
                # Find all eighth flags
                eighth_flag_indices.append(j)

        # ------- Correct for eighth notes -------
        # Sort out eighth flags
        # Assign to closest note
        for j in eighth_flag_indices:

            distances = []
            distance = staff_primitives[j].getBox().distance(staff_primitives[j-1].getBox())
            distances.append(distance)
            if (j + 1 < len(staff_primitives)):
                distance = staff_primitives[j].getBox().distance(staff_primitives[j+1].getBox())
                distances.append(distance)

            if (distances[1] and distances[0] > distances[1]):
                staff_primitives[j+1].setDuration(0.5)
            else:
                staff_primitives[j-1].setDuration(0.5)

            del staff_primitives[j]

        # Correct for beamed eighth notes
        # If number of pixels in center row of two notes
        # greater than 5 * line_width, then notes are
        # beamed
        for j in range(len(staff_primitives)):
            if (j+1 < len(staff_primitives)
                and staff_primitives[j].getPrimitive() == "note"
                and staff_primitives[j+1].getPrimitive() == "note"
                and (staff_primitives[j].getDuration() == 1 or staff_primitives[j].getDuration() == 0.5)
                and staff_primitives[j+1].getDuration() == 1):

                # Notes of interest
                note_1_center_x = staff_primitives[j].getBox().getCenter()[0]
                note_2_center_x = staff_primitives[j+1].getBox().getCenter()[0]

                # Regular number of black pixels in staff column
                num_black_pixels = 5 * staffs[i].getLineWidth()

                # Actual number of black pixels in mid column
                center_column = (note_2_center_x - note_1_center_x) // 2
                mid_col = staff_img[:, int(note_1_center_x + center_column)]
                num_black_pixels_mid = len(np.where(mid_col == 0)[0])

                if (num_black_pixels_mid > num_black_pixels):
                    # Notes beamed
                    # Make eighth note length
                    staff_primitives[j].setDuration(0.5)
                    staff_primitives[j+1].setDuration(0.5)

        # ------- Account for Key Signature -------
        num_sharps = 0
        num_flats = 0
        j = 0
        while (staff_primitives[j].getDuration() == 0):
            accidental = staff_primitives[j].getPrimitive()
            if (accidental == "sharp"):
                num_sharps += 1
                j += 1

            elif (accidental == "flat"):
                num_flats += 1
                j += 1

        # Check if last accidental belongs to note

        if (j != 0):
            # Determine if accidental coupled with first note
            # Center of accidental should be within a note width from note
            max_accidental_offset_x = staff_primitives[j].getBox().getCenter()[0] - staff_primitives[j].getBox().getWidth()
            accidental_center_x = staff_primitives[j-1].getBox().getCenter()[0]
            accidental_type = staff_primitives[j-1].getPrimitive()

            if (accidental_center_x > max_accidental_offset_x):
                num_sharps = num_sharps - 1 if accidental_type == "sharp" else num_sharps
                num_flats = num_flats - 1 if accidental_type == "flat" else num_flats

            # Modify notes in staff
            notes_to_modify = []
            if (accidental_type == "sharp"):
                notes_to_modify = key_signature_changes[accidental_type][num_sharps]
                # Remove accidentals from primitive list
                staff_primitives = staff_primitives[num_sharps:]
            else:
                notes_to_modify = key_signature_changes[accidental_type][num_flats]
                # Remove accidentals from primitive list
                staff_primitives = staff_primitives[num_flats:]

            for primitive in staff_primitives:
                type = primitive.getPrimitive()
                note = primitive.getPitch()
                if (type == "note" and note[0] in notes_to_modify):
                    new_note = MIDI_to_pitch[pitch_to_MIDI[note] + 1] if accidental_type == "sharp" else MIDI_to_pitch[pitch_to_MIDI[note] - 1]
                    primitive.setPitch(new_note)

        # ------- Apply Sharps and Flats -------
        primitive_indices_to_remove = []
        for j in range(len(staff_primitives)):
            accidental_type = staff_primitives[j].getPrimitive()

            if (accidental_type == "flat" or accidental_type == "sharp"):
                max_accidental_offset_x = staff_primitives[j+1].getBox().getCenter()[0] - staff_primitives[j+1].getBox().getWidth()
                accidental_center_x = staff_primitives[j].getBox().getCenter()[0]
                primitive_type = staff_primitives[j+1].getPrimitive()

                if (accidental_center_x > max_accidental_offset_x and primitive_type == "note"):
                    note = staff_primitives[j+1].getPitch()
                    new_note = MIDI_to_pitch[pitch_to_MIDI[note] + 1] if accidental_type == "sharp" else MIDI_to_pitch[pitch_to_MIDI[note] - 1]
                    staff_primitives[j+1].setPitch(new_note)
                    primitive_indices_to_remove.append(i)

        # Removed actioned accidentals
        for j in primitive_indices_to_remove:
            del staff_primitives[j]

        # ------- Assemble Staff -------

        bar = Bar()
        while (len(staff_primitives) > 0):
            primitive = staff_primitives.pop(0)

            if (primitive.getPrimitive() != "line"):
                bar.addPrimitive(primitive)
            else:
                staffs[i].addBar(bar)
                bar = Bar()
        # Add final bar in staff
        staffs[i].addBar(bar)

    # -------------------------------------------------------------------------------
    # Output MusicXml
    # -------------------------------------------------------------------------------
    score = Score()
    part = Part("Piano")
    score.append(part)

    measures = []

    time = int(staffs[0].getTimeSignature())
    clef = staffs[0].getClef()
    
    key_signature = "C"
    
    if(num_sharps!=0):
        key_signature = key[num_sharps - 1]

    if(num_flats!=0):
        key_signature = key[len(key) - num_flats]

    for i in range(len(staffs)):
        bars = staffs[i].getBars()
        for j in range(len(bars)):
            m = Measure(clef=clef, time_signature=(time//10, time%10) if i == 0 else None)
            primitives = bars[j].getPrimitives()
            for k in range(len(primitives)):
                duration = primitives[k].getDuration()
                if (primitives[k].getPrimitive() == "note"):
                    pitch = primitives[k].getPitch()
                    m.append(Note(pitch, duration))
                elif(primitives[k].getPrimitive() == "rest"):
                    m.append(Rest(duration))
            measures.append(m)

    part.extend(measures)

    # ------- Write to disk -------
    print("[INFO] Writing MusicXml to disk")
    #outputpath = path + '\\output\\' + key_signature + 'major.xml'
    output_path = "/sdcard/Documents/" + key_signature + "sheet.xml"
    score.export_to_file(output_path)

    return output_path
Esempio n. 30
0
    def SetupNodePath(self):
        Primitive.SetupNodePath(self)

        self.data.setName('box')
        self.data.setTag(game.nodes.TAG_NODE_TYPE, TAG_BOX)
        BoxNPO(self.data)
Esempio n. 31
0
 def __init__(self, anchor=ORIGIN, cardinals=DEFAULT_CARDINALS):
     Primitive.__init__(self)
     self.external_call = False
     self.anchor = anchor
     self.cardinals = cardinals
Esempio n. 32
0
    def SetupNodePath(self):
        Primitive.SetupNodePath(self)

        self.data.setName('cone')
        self.data.setTag(game.nodes.TAG_NODE_TYPE, TAG_CONE)
        ConeNPO(self.data)
Esempio n. 33
0
 def print_epochs(self, indent='', **kwargs):
     indent = indent
     Primitive.print_epochs(self, indent=indent, **kwargs)
     print('')