def Orthographic_Cplane():
    cpln_current = rs.ViewCPlane()
    Bool_Osnap = rs.Osnap()
    point = cpln_current.Origin
    if Bool_Osnap:
        rs.Osnap(False)
    
    rs.Command("_Circle 0,0,0 ")
    
    #
    rs.EnableRedraw(False)
    #
    Circle = rs.LastCreatedObjects()
    if Bool_Osnap:
        rs.Osnap(True)
        
        
    if Circle is None:
            #
        rs.EnableRedraw(True)
    #
        return
            
    if not rs.IsObject(Circle):
        rs.EnableRedraw(True)
        return
    
        
    rs.Command("_Point 0,0,1 ")
    pt_pos = rs.LastCreatedObjects()
    rs.Command("_Point 0,0,-1 ") 
    pt_neg = rs.LastCreatedObjects()
    
    pt_cam = rs.ViewCamera()
    
    dist_pos = rs.Distance(pt_cam,pt_pos)
    dist_neg = rs.Distance(pt_cam,pt_neg)
    
    print pt_cam
    
    Disk = rs.AddPlanarSrf(Circle)
    rs.UnselectAllObjects()
    rs.SelectObjects(Disk)
    
    if dist_pos>dist_neg:
        rs.Command("OrientCameraToSrf _f 0,0,0 _pause")
    else:
        rs.Command("OrientCameraToSrf 0,0,0 _pause")
        
        
    rs.DeleteObjects((pt_pos,pt_neg,Circle,Disk))
    
    rs.ViewProjection(None,1)
Exemple #2
0
def calculateWidth(files):

    global box_width

    for filename in files:
        join_string = str(input_directory + filename)
        combined_string = '!_Import ' + '"' + join_string + '"'
        rs.Command(combined_string)

        objs = rs.LastCreatedObjects(select=False)[0]

        bounding_pts = rs.BoundingBox([objs], view_or_plane=rs.WorldXYPlane())

        maxX = 0
        minX = 0
        minY = 0
        minZ = 0
        for pt in bounding_pts:
            if pt[0] < minX:
                minX = pt[0]
            if pt[0] > maxX:
                maxX = pt[0]
            if pt[1] < minY:
                minY = pt[1]
            if pt[2] < minZ:
                minZ = pt[2]

        if abs(maxX - minX) > box_width:
            box_width = abs(maxX - minX)

        rs.DeleteObject(objs)
Exemple #3
0
def GetFracture ():
    dx = rs.GetReal("Enter x-axis direction:")
    if not dx:
        dx = 0.0
    print "x-axis direction: ", dx
    objs = rs.ObjectsByType(8,False)
    cir_objs = rs.ObjectsByType(4)
    
    #delete all circles
    for cur_obj in cir_objs:
        if rs.IsCircle(cur_obj):
            rs.DeleteObject(cur_obj)
    occor = []
    radius = []
    center = []
    
    #for all surface
    for obj in objs:
        rs.UnselectAllObjects()
        rs.SelectObject(obj)
        rs.Command ("_Silhouette")
        created_objs = rs.LastCreatedObjects()
        #not a circle
        if len(created_objs) !=1:
            rs.DeleteObjects(created_objs)
            print "unvailded surface"
            continue
        created_objs = created_objs[0]
        #not a circle
        if not rs.IsCircle(created_objs):
            rs.DeleteObject(created_objs)
            print "unvailded surface, not circle"
            continue
        point = rs.CircleCenterPoint(created_objs)
        center.append(point)
        r = rs.CircleRadius(created_objs)
        radius.append(r)
        normal = rs.SurfaceNormal(obj,[0,0])
        occor.append(GetDirDip(normal,dx))
        rs.DeleteObject(created_objs)
    print center
    print occor
    print radius
    path = rs.DocumentPath()
    path_l = path.split("\\")
    path_l[len(path_l)-1] = "fracture.dat"
    file = open("\\".join(path_l),"w")
    file.write(str(len(occor)))
    file.write('\n')
    for i in range (len(occor)):
        file.write("%.15f " % center[i][0])
        file.write("%.15f " % center[i][1])
        file.write("%.15f " % center[i][2])
        file.write ("%.15f " % occor[i][0])
        file.write ("%.15f " % occor[i][1])
        file.write ("%.15f " % radius[i])
        file.write ("0.0001 0.1 30\n")
    file.close ()
def srfExtrude(srfs):
    rs.EnableRedraw(False)
    # for srf in srfs:
    rs.SelectObjects(srfs)
    rs.Command('_ExtrudeSrf _Pause')
    objs = rs.LastCreatedObjects()
    map(trp.copySourceLayer, objs, srfs)
    map(trp.copySourceData, objs, srfs)
    rs.EnableRedraw(True)
def box_from_dims(w, l, h):
    cmd = "_Box "
    cmd += "0,0,0 "
    cmd += (str(w) + " ")
    cmd += (str(l) + " ")
    cmd += (str(h) + " ")
    rs.Command(cmd)
    box = rs.LastCreatedObjects()
    return box
Exemple #6
0
def thicken(surf, h=1):
    s = rh.OffsetSurface(surf.realize()._ref, h, None, True, True)
    if not s:
        rh.UnselectAllObjects()
        rh.SelectObjects(surf.refs())
        rh.Command("OffsetSrf BothSides=Yes Solid=Yes {0} _Enter".format(h))
        s = single_ref_or_union(rh.LastCreatedObjects())
    surf.delete()
    return s
def placeSlits(data, width, height):
    for i in range(0, len(data)):
        rect = rs.AddRectangle(rs.WorldXYPlane(), height, width)
        rs.MoveObject(rect, [data[i][0], data[i][2], 0])

    rs.LastCreatedObjects(select=True)
    # export_string = '!_Export ' + '"' + str(output_directory + 'placements') + '"'
    # rs.Command(export_string)
    filename = 'placements.ai'
    rs.Command("_-Export " + output_directory + filename +
               " _Enter _Color=RGB _Enter")
Exemple #8
0
def hatch_srf():
    # select surfaces
    objs = rs.GetObjects("Select surfaces to hatch",
                         rs.filter.surface,
                         select=True)
    # outline shapes
    rs.Command("_MeshOutline ")
    outlines = rs.LastCreatedObjects()

    # select hatch to use
    for line in outlines:
        rs.AddHatch(line, hatch_pattern="SOLID")
def importComponent(path):
    imported=rs.Command("-Insert "+path+' Objects Enter 0,0,0 1 0')
    if imported:
        components=rs.LastCreatedObjects()
        polys=[]
        breps=[]
        for comp in components:
            if rs.IsCurve(comp):polys.append(comp)
            if rs.IsBrep(comp):breps.append(comp)
        print ('polys \n',polys)
        print ('breps \n',breps)
        return [breps,polys]
Exemple #10
0
def importComponent(path):
    if path is None: return None
    imported = rs.Command("-Insert " + path + ' Objects Enter 0,0,0 1 0')
    outComponent = AttrDict()

    if imported:
        components = rs.LastCreatedObjects()
        outComponent.polys = []
        outComponent.breps = []
        for comp in components:
            if rs.IsCurve(comp): outComponent.polys.append(comp)
            if rs.IsBrep(comp): outComponent.breps.append(comp)
        return outComponent
def modify_input(filename):

    # Import object from file
    join_string = str(input_directory + filename)
    combined_string = '!_Import ' + '"' + join_string + '"'
    rs.Command(combined_string)

    # Get all objects imported
    objs = rs.LastCreatedObjects(select=False)[0]

    # Close curve
    closed_curve = rs.CloseCurve(objs, 0.5)
    rs.DeleteObject(objs)

    # Rebuild curve to create smoother shape
    rs.RebuildCurve(closed_curve, 3, 100)

    # Pipe figure with radius of 0.25
    piped = rs.AddPipe(closed_curve, 0, 0.4)[0]

    rs.MoveObject(piped, [0, 0, 0])

    bounding_pts = rs.BoundingBox([piped], view_or_plane=rs.WorldXYPlane())

    maxX = 0
    minX = 0
    minY = 0
    minZ = 0
    for pt in bounding_pts:
        if pt[0] < minX:
            minX = pt[0]
        if pt[0] > maxX:
            maxX = pt[0]
        if pt[1] < minY:
            minY = pt[1]
        if pt[2] < minZ:
            minZ = pt[2]

    rect = rs.AddRectangle(rs.WorldXYPlane(), abs(maxX - minX), 3.0)
    # Move rect up 1/2 of diameter of circle used to pipe
    # Potentially use solid but smaller in height rect
    # Select function in rhino module could allow us to select objects so that the export works.
    rs.MoveObject(rect, [minX, minY - 3.0, minZ + 0.4])
    piped_rect = rs.AddPipe(rect, 0, 0.4)
    rs.DeleteObject(closed_curve)
    rs.DeleteObject(rect)
    rs.SelectObjects([piped, piped_rect])

    rs.Command("_-Export " + output_directory + filename + '.stl' +
               " _Enter _Tolerance=.001  _Enter")
Exemple #12
0
def CrossPlatformExtrudeSurface(SurfaceId, CurveId, Capped=True):
    # rs.ExtrudeSurface not implemented in Rhino for OS X

    if airconics_setup.RhinoVersion == 1:
        SolidId = rs.ExtrudeSurface(SurfaceId, CurveId, Capped)
    else:
        rs.SelectObject(CurveId)
        rs.Command("_SelNone")
        rs.SelectObject(SurfaceId)
        rs.Command("_ExtrudeSrfAlongCrv _SelPrev")
        SolidId = rs.LastCreatedObjects()
        rs.Command("_SelNone")

    return SolidId
def intersect_surfaces(guids):
    """Intersects all surfaces in model. Uses python cmd line, not api."""
    sc.doc.Views.Redraw()
    rs.UnselectAllObjects()
    layer('INTS_BOX')
    rs.SelectObjects(guids.boxes)
    rs.Command('_Intersect', echo=False)
    rs.UnselectAllObjects()
    layer('INTS')
    rs.SelectObjects(guids.fractures)
    rs.Command('_Intersect', echo=False)
    frac_isect_ids = rs.LastCreatedObjects()
    rs.UnselectAllObjects()
    if frac_isect_ids:
        for intid in frac_isect_ids:
            if rs.IsCurve(intid):
                rs.AddPoint(rs.CurveStartPoint(intid))
                rs.AddPoint(rs.CurveEndPoint(intid))
        if len(frac_isect_ids) > 1:
            rs.SelectObjects(frac_isect_ids)
            rs.Command('_Intersect', echo=False)
    if rs.IsLayer('INTS_BOX_INT'):
        layer('INTS_BOX_INT')
        rs.UnselectAllObjects()
        rs.SelectObjects(guids.boxes_int)
        rs.SelectObjects(guids.fractures)
        rs.Command('_Intersect', echo=False)
        frac_isect_ids = rs.LastCreatedObjects()
        rs.UnselectAllObjects()
        if frac_isect_ids:
            for intid in frac_isect_ids:
                if rs.IsCurve(intid):
                    rs.AddPoint(rs.CurveStartPoint(intid))
                    rs.AddPoint(rs.CurveEndPoint(intid))
            if len(frac_isect_ids) > 1:
                rs.SelectObjects(frac_isect_ids)
                rs.Command('_Intersect', echo=False)
def output_frame (filename):

    join_string = str(input_directory + filename)
    combined_string = '!_Import ' + '"' + join_string + '"'
    rs.Command(combined_string)

    # Get all objects imported 
    objs = rs.LastCreatedObjects(select=False)[0]
    
    # Close curve
    closed_curve = rs.CloseCurve(objs, 0.5)
    rs.DeleteObject(objs)
    
    # Rebuild curve to create smoother shape
    rs.RebuildCurve(closed_curve, 3, 100)

    # Pipe figure with radius of 0.25
    piped = rs.AddPipe(closed_curve,0,pipe_diameter)[0]

    rs.MoveObject(piped, [0,0,0])

    bounding_pts = rs.BoundingBox([piped], view_or_plane=rs.WorldXYPlane())

    maxX = 0
    minX = 0
    minY = 0
    minZ = 0
    for pt in bounding_pts:
        if pt[0] < minX:
            minX = pt[0]
        if pt[0] > maxX:
            maxX = pt[0]
        if pt[1] < minY:
            minY = pt[1]
        if pt[2] < minZ:
            minZ = pt[2]
    
    epsilon = 0.5
    center = 0
    one = [center - (box_width / 2),minY-epsilon,-1 * pipe_diameter]
    two = [center - (box_width / 2),minY-epsilon,pipe_diameter]
    three = [center + (box_width / 2),minY-epsilon,pipe_diameter]
    four = [center + (box_width / 2),minY-epsilon,-1 * pipe_diameter]
    five = [center - (box_width / 2),minY+epsilon,-1 * pipe_diameter]
    six = [center - (box_width / 2),minY+epsilon,pipe_diameter]
    seven = [center + (box_width / 2),minY+epsilon,pipe_diameter]
    eight = [center + (box_width / 2),minY+epsilon,-1 * pipe_diameter]
    
    bowx = rs.AddBox([two, three, four, one, six, seven, eight, five])
Exemple #15
0
def convertTextToPolylines2(obj):

    # get object properties
    text = rs.TextObjectText(obj)
    pt = rs.TextObjectPoint(obj)
    origin = rs.coerce3dpoint([0, 0, 0])
    ht = rs.TextObjectHeight(obj)
    object_layer = rs.ObjectLayer(obj)
    plane = rs.TextObjectPlane(obj)

    diff = rs.coerce3dpoint([pt.X, pt.Y, pt.Z])

    p1 = rs.WorldXYPlane()
    #restore view cplane
    rs.ViewCPlane(None, p1)

    matrix = rs.XformRotation4(p1.XAxis, p1.YAxis, p1.ZAxis, plane.XAxis,
                               plane.YAxis, plane.ZAxis)

    rs.DeleteObject(obj)

    # split text at enters
    text = text.split('\r\n')
    opts = 'GroupOutput=No FontName="' + EXPORT_FONT + '" Italic=No Bold=No Height=' + str(
        ht)
    opts += " Output=Curves AllowOpenCurves=Yes LowerCaseAsSmallCaps=No AddSpacing=No "

    n_lines = len(text)

    origin.Y += 1.6 * ht * (len(text) - 1)

    polylines = []
    for item in text:
        rs.Command(
            "_-TextObject " + opts + '"' + item + '"' + " " + str(origin),
            False)
        polylines += rs.LastCreatedObjects()
        origin.Y -= ht * 1.6

    rs.ObjectLayer(polylines, object_layer)

    polylines = rs.ScaleObjects(polylines, (0, 0, 0), (0.7, 1, 1), True)

    # transform to old position
    rs.TransformObjects(polylines, matrix, copy=False)
    rs.MoveObjects(polylines, diff)

    return polylines
Exemple #16
0
def AgiImport(dirpath, file):
    """
    Create new rhino file, import mesh, split, then save.
    """
    objPath = dirpath + '\\' + file
    if os.path.exists(objPath) == False:
        print objPath
        return

    ## Open new template file ##
    template = rs.TemplateFile()
    cmd = "-_New "
    cmd += template + " "
    rs.Command(cmd)

    cmd = "-_Import "
    cmd += '"' + os.path.abspath(objPath) + '"' + " "
    cmd += "IgnoreTextures=No "
    cmd += "MapOBJToRhinoZ=Yes "
    cmd += "_Enter "
    rs.Command(cmd)

    rs.Command("SplitDisjointMesh ")

    meshes = rs.LastCreatedObjects()
    max = 0
    keep = None
    for guid in meshes:
        mesh = rs.coercemesh(guid)
        count = mesh.Faces.Count
        if count > max:
            keep = guid
            max = count

    if keep:
        meshes.remove(keep)
    rs.DeleteObjects(meshes)

    rs.ZoomExtents(all=True)

    cmd = "-_SaveAs "
    cmd += "SaveTextures=Yes "
    cmd += '"' + os.path.abspath(objPath).replace(".obj", ".3dm") + '"' + " "
    cmd += "_Enter "
    rs.Command(cmd)
    rs.DocumentModified(False)
    Rhino.RhinoApp.Wait()
Exemple #17
0
    def explode(objs, li):
        for obj in objs:
            if rs.IsBlockInstance(obj):

                # DIRTY FIX FOR RHINO 5-SR14 522.8390 (5-22-2017)
                # temp_objs = rs.ExplodeBlockInstance(obj)

                rs.UnselectAllObjects()
                rs.SelectObject(obj)
                rs.Command("Explode" , False)
                temp_objs = rs.LastCreatedObjects()

                explode(temp_objs, li)
            else:
                li.append(obj)

        return li
Exemple #18
0
def modify_input(filename):

    # Import object from file
    join_string = str(input_directory + filename)
    combined_string = '!_Import ' + '"' + join_string + '"'
    rs.Command(combined_string)

    # Get all objects imported
    objs = rs.LastCreatedObjects(select=False)[0]

    # Close curve
    closed_curve = rs.CloseCurve(objs, 0.5)
    rs.DeleteObject(objs)

    # Rebuild curve to create smoother shape
    rs.RebuildCurve(closed_curve, 3, 100)

    # Pipe figure with radius of 0.25
    piped = rs.AddPipe(closed_curve, 0, 0.4)[0]

    rs.MoveObject(piped, [0, 0, 0])

    bounding_pts = rs.BoundingBox([piped], view_or_plane=rs.WorldXYPlane())

    maxX = 0
    minX = 0
    minY = 0
    minZ = 0
    for pt in bounding_pts:
        if pt[0] < minX:
            minX = pt[0]
        if pt[0] > maxX:
            maxX = pt[0]
        if pt[1] < minY:
            minY = pt[1]
        if pt[2] < minZ:
            minZ = pt[2]

    rect = rs.AddRectangle(rs.WorldXYPlane(), abs(maxX - minX), 3.0)
    rs.MoveObject(rect, [minX, minY - 3.0, minZ])
    rs.AddPipe(rect, 0, 0.4)
    rs.DeleteObject(closed_curve)
    rs.DeleteObject(rect)

    export_string = '!_Export ' + '"' + str(output_directory + filename) + '"'
    rs.Command(export_string)
Exemple #19
0
def intersections():
    """Intersects all surfaces in model. Uses python cmd line, not api."""
    sc.doc.Views.Redraw()
    layer('INTERSECTIONS')
    objs = rs.AllObjects()
    rs.SelectObjects(objs)
    rs.Command('_Intersect', echo=False)
    frac_isect_ids = rs.LastCreatedObjects()
    rs.UnselectAllObjects()
    if frac_isect_ids:
        for intid in frac_isect_ids:
            if rs.IsCurve(intid):
                rs.AddPoint(rs.CurveStartPoint(intid))
                rs.AddPoint(rs.CurveEndPoint(intid))
        if len(frac_isect_ids) > 1:
            rs.SelectObjects(frac_isect_ids)
            rs.Command('_Intersect', echo=False)
Exemple #20
0
def AddTEtoOpenAirfoil(AirfoilCurve):
    # If the airfoil curve given as an argument is open at the trailing edge, it adds
    # a line between the ends of the curve and joins this with the rest of the curve.
    if rs.IsCurveClosed(AirfoilCurve) == False:
        EP1 = rs.CurveEndPoint(AirfoilCurve)
        rs.ReverseCurve(AirfoilCurve)
        EP2 = rs.CurveEndPoint(AirfoilCurve)
        rs.ReverseCurve(AirfoilCurve)
        Closure = rs.AddLine(EP1, EP2)
        rs.UnselectAllObjects()
        rs.SelectObject(Closure)
        rs.SelectObject(AirfoilCurve)
        rs.Command("_Join ")
        LO = rs.LastCreatedObjects()
        AirfoilCurve = LO[0]
        rs.UnselectAllObjects()

    return AirfoilCurve
Exemple #21
0
def DrapeOne():
    # drape options
    a = "AutoSpacing=No"
    b = "U"
    c = "8"
    d = "V"
    e = "8"
    #f = "AutoDetectMaxDepth=No"
    # 3d points
    #pt0 = Rhino.Geometry.Point3d(-60,-60,0)
    #pt1 = Rhino.Geometry.Point3d(50,50,0)
    # command
    cmd = "_Drape {0} {1} {2} {3} {4}".format(a,b,c,d,e)
    result = rs.Command(cmd, True)
    if result:
        drape_srf = rs.LastCreatedObjects(select=True)[0]
    else:
        print "No result"
Exemple #22
0
def add_logo_offcenter(pt_base, W, H):
    """deprecated"""
    proportion = 0.25
    scale_factor = W * (proportion) / 40
    if scale_factor * 14 * 1.05 > H:
        scale_factor = H * 0.5 / 40

    margin = max(W, H) * 0.05 + T_OBOX

    str_file = r"O:\SHL\ModelshopCopenhagen\05_scripting\Resources\logo\shl_logo_40x13_hatch_block_centered"
    str_pt = str(pt_base.X + margin) + "," + str(pt_base.Y + margin) + ",0"
    str_scale = str(scale_factor)
    #rs.Command("_-Insert _File=_Yes " + str_file + " _Block " + str_pt + " _Enter _Enter", 0)
    rs.Command(
        "_-Insert _File=_Yes " + str_file + " _Block " + str_pt + " " +
        str_scale + " _Enter ", 0)
    logo = rs.LastCreatedObjects()
    rs.ObjectLayer(logo, LCUT_NAMES[4])
def import_group(filename):

    global group_count
    global groups

    # Import object from file
    join_string = str(input_directory + filename)
    combined_string = '!_Import ' + '"' + join_string + '"'
    rs.Command(combined_string)

    # Get all objects imported
    objs = rs.LastCreatedObjects(select=False)
    name = rs.AddGroup(str(group_count))
    if (name == None):
        raise ValueError("Creation of group failed")
    else:
        rs.AddObjectsToGroup(objs, name)
        group_count += 1
        groups.append(name)
        return name
Exemple #24
0
def add_logo(pt_base, W, H):

    #determine size based on the boxdim. try to do 80mm.
    hatchdims = (40, 14)  #WxH
    if W > hatchdims[0] * 2.2 and H > hatchdims[1] * 2.2:
        scale_factor = 2
    else:
        proportion = 0.5
        scale_factor = W * (proportion) / 40
        if scale_factor * 14 * 1.05 > H:
            scale_factor = H * 0.5 / 40

    str_file = r"O:\SHL\ModelshopCopenhagen\05_scripting\Resources\logo\shl_logo_40x13_hatch_centered"
    str_pt = str(pt_base.X) + "," + str(pt_base.Y) + ",0"
    str_scale = str(scale_factor)
    rs.Command(
        "_-Insert _File=_Yes " + str_file + " _Block " + str_pt + " " +
        str_scale + " _Enter ", 0)
    logo = rs.LastCreatedObjects()
    rs.ObjectLayer(logo, LCUT_NAMES[4])
    SELECT_GUIDS.extend(logo)
def draw_model_paperspace():
    #go to paperspace, then go to view and enter its modelspace
    view = rs.CurrentView()  #rs.CurrentDetail()
    detail = rs.CurrentDetail(view)

    type = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.ViewportType
    if type != Rhino.Display.ViewportType.DetailViewport:
        print "Please enter detail modelspace"
        return
    print type

    #get model
    objs = rs.GetObjects("Select objects to draw", rs.filter.polysurface)
    rs.SelectObjects(objs)

    #make 2d, as current view
    rs.Command("!-_Make2D DrawingLayout=CurrentView _enter _enter")
    dwg_crvs = rs.LastCreatedObjects()

    #cut and paste into view window (paperspace)
    origin = [0, 0, 0]
    rs.AddBlock(dwg_crvs, origin, name=view, delete_input=True)

    #leave detail view and insert block
    rs.CurrentDetail(view, detail=view)
    insert_pt = [17, 11, 0]
    obj = rs.InsertBlock(view, insert_pt)

    #orient 2pt with 3d scaling enabled
    r1 = rs.GetPoint("Pick reference corner 1")
    r2 = rs.GetPoint("Pick reference corner 2")
    t1 = rs.GetPoint("Pick target corner 1")
    t2 = rs.GetPoint("Pick target corner 2")
    ref_pts = [r1, r2]
    target_pts = [t1, t2]
    rs.OrientObject(obj, ref_pts, target_pts, flags=2)

    print "Script Finished"
    return
Exemple #26
0
def main(threeDeeShapes):
    if (not threeDeeShapes) or (_threeDeeShapes[0] == None):
        threeDeeShapes_allClosedPolysrf_objs = None
        validInput = False
        printMsg = "Input closed 3d objects into \"_threeDeeShapes\" input to boolean union them."
        return threeDeeShapes_allClosedPolysrf_objs, validInput, printMsg

    if (_runIt == False):
        threeDeeShapes_allClosedPolysrf_objs = None
        validInput = False
        printMsg = "Set the \"_runIt\" input to \"True\" in order to run the component."
        return threeDeeShapes_allClosedPolysrf_objs, validInput, printMsg

    # perform boolean union of the 3d buildings, and make them all "closed polysurfaces"

    rs.EnableRedraw(False)

    errorMsg = "Something went wrong. Open a new topic at:\nhttps://www.grasshopper3d.com/group/gismo/forum\n and attach your .gh file."

    threeDeeShapes_unboolean_rhino_ids = []

    sc.doc = Rhino.RhinoDoc.ActiveDoc
    # add all breps to Rhino document
    for i, threeDeeShape in enumerate(_threeDeeShapes):
        rhino_ids = Rhino.RhinoDoc.ActiveDoc.Objects.AddBrep(threeDeeShape)
        threeDeeShapes_unboolean_rhino_ids.append(rhino_ids)

    # perform Rhino BooleanUnion
    selIds = ""
    for rhino_id in threeDeeShapes_unboolean_rhino_ids:
        selIds += "_SelId %s " % rhino_id

    commandString1 = "_-BooleanUnion " + selIds + "_Enter "

    echo1 = False
    success1 = rs.Command(commandString1, echo1)
    if (success1 == False):
        print errorMsg

    # explode and rejoin the shape in case it is not a "closed solid"
    if closedSolid_:
        ######################
        if (rs.ContextIsGrasshopper() == True):
            # document is set to sc.doc = ghdoc (for some reason. For example the component was copy pasted from one definition to another)
            sc.doc = Rhino.RhinoDoc.ActiveDoc
        ######################

        threeDeeShapes_someOpenPolysrf_rhino_ids = rs.LastCreatedObjects(
            select=True)
        rs.UnselectAllObjects()

        global threeDeeShapes_allClosedPolysrf_rhino_ids
        threeDeeShapes_allClosedPolysrf_rhino_ids = []
        for rhino_id2 in threeDeeShapes_someOpenPolysrf_rhino_ids:
            threeDeeShapes_someOpenPolysrf = rs.coercegeometry(rhino_id2)
            if (
                    type(threeDeeShapes_someOpenPolysrf) == Rhino.Geometry.Brep
            ):  # do not include the textDot's which can be created in Rhino 6 once the "_BooleanUnion" command fails
                if (threeDeeShapes_someOpenPolysrf.IsSolid == False
                    ):  # explode only "open polysurfaces" fron Rhino
                    """
                    # method 1: use grasshopper's Rhino.Gemometry.JoinBreps()  - not working!!!
                    tol = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance
                    threeDeeShapes_closedPolysrf = Rhino.Geometry.Brep.JoinBreps( [rs.coercegeometry(rhino_id2)], tol)[0]
                    threeDeeShapes_closedPolysrf_rhino_id = Rhino.RhinoDoc.ActiveDoc.Objects.AddBrep(threeDeeShapes_closedPolysrf)
                    threeDeeShapes_allClosedPolysrf_rhino_ids.append( threeDeeShapes_closedPolysrf_rhino_id )
                    """

                    # method 2: use Rhino's "_Explode, _Join" commands
                    commandString2 = "_-SelId %s _Explode _Join _Enter" % rhino_id2
                    echo2 = False
                    success2 = rs.Command(commandString2, echo2)
                    threeDeeShapes_joined_rhino_ids = rs.LastCreatedObjects(
                        select=False)
                    threeDeeShapes_allClosedPolysrf_rhino_ids.extend(
                        threeDeeShapes_joined_rhino_ids)
                    rs.UnselectAllObjects()

                    if (success2 == False):
                        print errorMsg
                elif (threeDeeShapes_someOpenPolysrf.IsSolid == True
                      ):  # no need to explode it. It is "closed polysurface"
                    threeDeeShapes_allClosedPolysrf_rhino_ids.append(rhino_id2)

    # delete all objects from rhino working space
    threeDeeShapes_allClosedPolysrf_objs = [
        rs.coercegeometry(id)
        for id in threeDeeShapes_allClosedPolysrf_rhino_ids
    ]
    print "threeDeeShapes_allClosedPolysrf_rhino_ids: ", threeDeeShapes_allClosedPolysrf_rhino_ids
    print "-------------------------------------------"
    print "-------------------"
    #rs.SelectObjects(threeDeeShapes_allClosedPolysrf_rhino_ids)
    for rhino_id3 in threeDeeShapes_allClosedPolysrf_rhino_ids:
        try:
            rs.DeleteObject(rhino_id3)
        except:
            # for some reason the "Parameter must be a Guid or string representing a Guid" error is thrown
            Rhino.RhinoDoc.ActiveDoc.Objects.Delete(rhino_id3, quiet=False)

    sc.doc = ghdoc

    if bakeIt_:
        for rhino_id4 in threeDeeShapes_allClosedPolysrf_objs:
            final_id = Rhino.RhinoDoc.ActiveDoc.Objects.AddBrep(rhino_id4)

    rs.EnableRedraw(True)

    validInput = True
    printMsg = "ok"
    return threeDeeShapes_allClosedPolysrf_objs, validInput, printMsg
Exemple #27
0
def main(shapesDataTree, keys, valuesDataTree, OSM3DrenderMesh, defaultColor,
         textureImageName, textureImage_filePath):

    meshParam = Rhino.Geometry.MeshingParameters()
    meshParam.SimplePlanes = True

    if (OSM3DrenderMesh == True):
        # initial values
        buildingColor_keyIndex = None
        roofColor_keyIndex = None
        treeColor_keyIndex = None
        grassColor_keyIndex = None
        for keyIndex, key in enumerate(keys):
            if (key == "building:colour"):  # short name: "building_c"
                buildingColor_keyIndex = keyIndex
            elif (key == "roof:colour"):  # short name: "roof_colou"
                roofColor_keyIndex = keyIndex
            elif (key == "natural"):
                treeColor_keyIndex = keyIndex
            elif (key == "leisure"):
                grassColor_keyIndex = keyIndex

        allMeshesSeparated = []
        if (buildingColor_keyIndex != None
            ) or (roofColor_keyIndex != None) or (
                treeColor_keyIndex != None) or (grassColor_keyIndex != None):
            shapesLL = shapesDataTree.Branches
            valuesLL = valuesDataTree.Branches

            # initial values
            valueBuildingColor = ""
            valueRoofColor = ""
            valueTree = ""
            valueGrass = ""
            for branchIndex, shapesL in enumerate(shapesLL):
                shapes2L = []
                roofsL = []
                shapesLColor = None  # initial value
                roofColor = None  # initial value
                if (
                        len(shapesL) != 0
                ):  # some shape may have been removed with the "OSM ids" component
                    if (buildingColor_keyIndex != None):
                        valueBuildingColor = valuesLL[branchIndex][
                            buildingColor_keyIndex]
                    if (roofColor_keyIndex != None):
                        valueRoofColor = valuesLL[branchIndex][
                            roofColor_keyIndex]
                    if (treeColor_keyIndex != None):
                        valueTree = valuesLL[branchIndex][treeColor_keyIndex]
                    if (grassColor_keyIndex != None):
                        valueGrass = valuesLL[branchIndex][grassColor_keyIndex]

                    if (valueBuildingColor != ""):
                        valueBuildingColor_corrected = US_vs_UK_englishNames(
                            valueBuildingColor)
                        shapesLColor = System.Drawing.ColorTranslator.FromHtml(
                            valueBuildingColor_corrected
                        )  # if building:color is in Hexadecimal format, convert it to RGB
                    elif (valueTree == "tree"):
                        randomGreenColor = random.randint(75, 140)
                        shapesLColor = System.Drawing.Color.FromArgb(
                            0, randomGreenColor, 0)
                    elif (valueGrass == "park") or (valueGrass == "garden"):
                        randomGreenColor = random.randint(100, 190)
                        shapesLColor = System.Drawing.Color.FromArgb(
                            0, randomGreenColor, 0)
                    else:
                        # this is for buildings only, not trees, parks and gardens
                        shapesLColor = defaultColor

                    if (valueRoofColor != ""):
                        valueRoofColor_corrected = US_vs_UK_englishNames(
                            valueRoofColor)
                        roofColor = System.Drawing.ColorTranslator.FromHtml(
                            valueRoofColor_corrected
                        )  # if roof:color is in Hexadecimal format, convert it to RGB
                    elif (valueRoofColor == "") and (valueBuildingColor != ""):
                        # if there is no valid "roof:colour", but there is "building:colour", then use the "building:colour" value as "roof:colour" value
                        roofColor = shapesLColor

                    # mesh the shapesL (building with roof included, or tree, or grass)
                    meshes = Rhino.Geometry.Mesh.CreateFromBrep(
                        shapesL[0], meshParam)
                    joinedMesh = Rhino.Geometry.Mesh()
                    for mesh in meshes:
                        joinedMesh.Append(mesh)
                    shapes2L = [joinedMesh]

                    # color the mesh (colorTheShapesL = True)
                    shapes2L[0].VertexColors.Clear()
                    mesh_verticesCount = shapes2L[0].Vertices.Count
                    for i in xrange(mesh_verticesCount):
                        shapes2L[0].VertexColors.Add(shapesLColor)

                    if (roofColor != None):
                        # roof
                        upperShapesLfaceBrep = shapesL[0].Faces[
                            0].DuplicateFace(False)
                        upperShapesLfaceBrep.Flip(
                        )  # if it isn't fliped the upperShapesLface_extruded is invalid

                        nakedOnly = False
                        shapesL_randomCrvs = upperShapesLfaceBrep.DuplicateEdgeCurves(
                            nakedOnly)
                        shapesL_startPt = shapesL_randomCrvs[0].PointAtStart
                        extrusionVec = Rhino.Geometry.Vector3d(0, 0, 0.01)
                        extrudeCrv = Rhino.Geometry.Line(
                            shapesL_startPt,
                            shapesL_startPt + extrusionVec).ToNurbsCurve()
                        cap = True
                        upperShapesLface_extruded = Rhino.Geometry.BrepFace.CreateExtrusion(
                            upperShapesLfaceBrep.Faces[0], extrudeCrv, cap)

                        # mesh the roof
                        meshes = Rhino.Geometry.Mesh.CreateFromBrep(
                            upperShapesLface_extruded, meshParam)
                        joinedMesh = Rhino.Geometry.Mesh()
                        for mesh in meshes:
                            joinedMesh.Append(mesh)
                        roofsL = [joinedMesh]

                        roofsL[0].VertexColors.Clear()
                        mesh_verticesCount = roofsL[0].Vertices.Count
                        for i in xrange(mesh_verticesCount):
                            roofsL[0].VertexColors.Add(roofColor)

                elif (len(shapesL) == 0):
                    # some shape may have been removed with the "OSM ids" component
                    pass

                if len(shapes2L) != 0:
                    allMeshesSeparated.extend(shapes2L)
                if len(roofsL) != 0:
                    allMeshesSeparated.extend(roofsL)

        else:
            renderedJoinedMesh = None
            printMsg = "The list of supplied _keys does not contain neither \"building:color\" nor \"roof:color\" keys.\n" + \
                       "These keys are essential so that component could color the inputted shapes."
            level = Grasshopper.Kernel.GH_RuntimeMessageLevel.Warning
            ghenv.Component.AddRuntimeMessage(level, printMsg)
            print printMsg
            return renderedJoinedMesh

        # join the "allMeshesSeparated" to "joinedMesh"
        rs.EnableRedraw(False)
        allMeshesSeparated_ids = []
        for mesh in allMeshesSeparated:
            meshId = Rhino.RhinoDoc.ActiveDoc.Objects.AddMesh(mesh)
            allMeshesSeparated_ids.append(meshId)

        sc.doc = Rhino.RhinoDoc.ActiveDoc
        numOfSelectedObjs = rs.SelectObjects(allMeshesSeparated_ids)

        echo = False
        sucess = rs.Command("NoEcho _-Join _Enter", echo)

        select = True
        joinedMesh_id = rs.LastCreatedObjects(select)[0]
        joinedMesh = Rhino.RhinoDoc.ActiveDoc.Objects.Find(
            joinedMesh_id).Geometry

        quiet = True
        deleteSuccess = Rhino.RhinoDoc.ActiveDoc.Objects.Delete(
            joinedMesh_id, quiet)
        rs.EnableRedraw(True)
        sc.doc = ghdoc

    elif (OSM3DrenderMesh == False):
        allMeshesSeparated = Rhino.Geometry.Mesh(
        )  # dummy variable, due to need to delete
        allMeshesSeparated_ids = Rhino.Geometry.Mesh(
        )  # dummy variable, due to need to delete
        joinedMesh = shapesDataTree.Branches[0][0]

    # create render mesh and imageTexture
    renderedJoinedMesh = gismo_createGeometry.createRenderMesh(
        joinedMesh, textureImage_filePath)

    if bakeIt_:

        layerName = "defaultColor=" + "(%s,%s,%s)" % (
            defaultColor.R, defaultColor.G,
            defaultColor.B) + "_textureImageName=" + textureImageName
        layParentName = "GISMO"
        laySubName = "OSM"
        layerCategoryName = "RENDER_MESH"
        newLayerCategory = False
        laySubName_color = System.Drawing.Color.FromArgb(100, 191, 70)  # green
        layerColor = System.Drawing.Color.FromArgb(0, 0, 0)  # black

        layerIndex, layerName_dummy = gismo_preparation.createLayer(
            layParentName, laySubName, layerCategoryName, newLayerCategory,
            layerName, laySubName_color, layerColor)

        geometryIds = gismo_preparation.bakeGeometry([renderedJoinedMesh],
                                                     layerIndex)

        # grouping
        groupIndex = gismo_preparation.groupGeometry(
            "OSM_RENDER_MESH" + "_" + layerName, geometryIds)
        del geometryIds

    # deleting
    del joinedMesh
    del allMeshesSeparated
    del allMeshesSeparated_ids
    gc.collect()

    return renderedJoinedMesh
Exemple #28
0
def outline_region():
	
	
	go = Rhino.Input.Custom.GetObject()
	go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve
	
	default_length = sc.sticky["length"] if sc.sticky.has_key("length") else 100
	default_delete = sc.sticky["delete"] if sc.sticky.has_key("delete") else True
	
	opt_delete = Rhino.Input.Custom.OptionToggle(default_delete,"No","Yes")
	go.SetCommandPrompt("Select Curves")
	go.AddOptionToggle("DeleteInput", opt_delete)

	go.GroupSelect = True
	go.SubObjectSelect = False
	go.AcceptEnterWhenDone(True)
	go.AcceptNothing(True)
	go.EnableClearObjectsOnEntry(False)
	go.GroupSelect = True
	go.SubObjectSelect = False
	go.DeselectAllBeforePostSelect = False
	
	res = None
	bHavePreselectedObjects = False
	while True:
		res = go.GetMultiple(1,0)
		if res == Rhino.Input.GetResult.Option:
			#print res
			go.EnablePreSelect(False, True)
			continue
		#If not correct
		elif res != Rhino.Input.GetResult.Object:
			print "No curves selected!"
			return Rhino.Commands.Result.Cancel
		if go.ObjectsWerePreselected:
			bHavePreselectedObjects = True
			go.EnablePreSelect(False, True)
			continue
		break
	
	input_curves = []
	for i in xrange(go.ObjectCount):
		b_obj = go.Object(i).Object()
		input_curves.append(b_obj.Id)
	
	#Get length
	extension_length = rs.GetInteger(message="Enter Extension Length",number=default_length)
	if not extension_length:
		rs.EnableRedraw(True)
		print "No Extension Length entered."
		return False

	arr_preview_geom = get_preview_geometry(input_curves)
	for indCrv in arr_preview_geom:
		rs.ExtendCurveLength(indCrv,0,2,extension_length)
	
	rs.EnableRedraw(False)
	#Get curveboolean and display it
	region_was_created = True
	rs.UnselectAllObjects()
	rs.SelectObjects(arr_preview_geom)
	
	rs.Command("_-CurveBoolean _AllRegions _Enter")
	
	pcurve_outline = rs.LastCreatedObjects()
	
	if isinstance(pcurve_outline,list):
		preview_srf = rs.AddPlanarSrf(pcurve_outline)
		rs.LockObjects(arr_preview_geom)
		rs.LockObjects(preview_srf)
	else:
		region_was_created = False
		rs.LockObjects(arr_preview_geom)
		preview_srf = []

	rs.EnableRedraw(True)
	rs.Redraw()

	#Set up input object
	go = Rhino.Input.Custom.GetOption()
	optint = Rhino.Input.Custom.OptionDouble(extension_length)

	prompt = "Press Enter to accept"
	warning = "Insufficient overlap length. "
	s = prompt if region_was_created else warning+prompt
	go.SetCommandPrompt(s)
	go.AddOptionDouble("ExtensionLength", optint)
	go.AddOptionToggle("DeleteInput", opt_delete)
	go.AcceptEnterWhenDone(True)
	go.AcceptNothing(True)

	#control flow: can distinguish between inserting an option, cancelling, and pressing enter
	res = None
	while True:
		res = go.Get()
		rs.EnableRedraw(False)
		region_was_created = True
		
		#If new option entered, redraw a possible result
		if res == Rhino.Input.GetResult.Option:
			#Delete old preview
			rs.UnlockObjects(preview_srf+arr_preview_geom)
			rs.DeleteObjects(preview_srf+arr_preview_geom)
			if isinstance(pcurve_outline,list):
				rs.DeleteObjects(pcurve_outline)
			rs.SelectObjects(input_curves)
			
			#Draw new preview
			arr_preview_geom = get_preview_geometry(input_curves)
			if not extension_length: return False
			
			for indCrv in arr_preview_geom:
				rs.ExtendCurveLength(indCrv,0,2,optint.CurrentValue)
			
			rs.UnselectAllObjects()
			rs.SelectObjects(arr_preview_geom)
			rs.Command("_-CurveBoolean _AllRegions _Enter")
			pcurve_outline = rs.LastCreatedObjects()
			
			if isinstance(pcurve_outline,list):
				preview_srf = rs.AddPlanarSrf(pcurve_outline)
				rs.LockObjects(arr_preview_geom)
				rs.LockObjects(preview_srf)
			else:
				rs.LockObjects(arr_preview_geom)
				preview_srf = []
				region_was_created = False
			rs.EnableRedraw(True)
			
			s = prompt if region_was_created else warning+prompt
			go.SetCommandPrompt(s)
			
			continue

		#If accepted, leave loop
		elif res == Rhino.Input.GetResult.Nothing:
			break
		
		#If cancelled, delete working geometry
		elif res != Rhino.Input.GetResult.Option:
			rs.UnlockObjects(preview_srf)
			rs.UnlockObjects(arr_preview_geom)
			rs.DeleteObjects(preview_srf)
			rs.DeleteObjects(arr_preview_geom)
			rs.DeleteObjects(pcurve_outline)
			rs.EnableRedraw(True)
			return Rhino.Commands.Result.Cancel
	

	#Clean up if successful
	if opt_delete.CurrentValue == True: rs.DeleteObjects(input_curves)
	rs.UnlockObjects(preview_srf)
	rs.UnlockObjects(arr_preview_geom)
	rs.DeleteObjects(preview_srf)
	rs.DeleteObjects(arr_preview_geom)
	if isinstance(pcurve_outline,list):
		rs.SelectObjects(pcurve_outline)
	
	sc.sticky["length"] = optint.CurrentValue
	sc.sticky["delete"] = opt_delete.CurrentValue
	
	rs.EnableRedraw(True)
def transonic_airliner(
    Propulsion=1,  # 1 - twin, 2 - quad 
    EngineDia=2.9,  # Diameter of engine intake highlight 
    FuselageScaling=[55.902, 55.902, 55.902],  # [x,y,z] scale factors
    NoseLengthRatio=0.182,  # Proportion of forward tapering section of the fuselage 
    TailLengthRatio=0.293,  # Proportion of aft tapering section of the fuselage
    WingScaleFactor=44.56,
    WingChordFactor=1.0,
    Topology=1,  # Topology = 2 will yield a box wing airliner - use with caution, this is just for demo purposes.
    SpanStation1=0.31,  # Inboard engine at this span station
    SpanStation2=0.625,  # Outboard engine at this span station (ignored if Propulsion=1)
    EngineCtrBelowLE=0.3558,  # Engine below leading edge, normalised by the length of the nacelle - range: [0.35,0.5]
    EngineCtrFwdOfLE=0.9837,  # Engine forward of leading edge, normalised by the length of the nacelle - range: [0.85,1.5]
    Scarf_deg=3):  # Engine scarf angle

    # Build fuselage geometry
    rs.EnableRedraw(False)
    try:
        FuselageOMLSurf, SternPoint = fuselage_oml.FuselageOML(
            NoseLengthRatio,
            TailLengthRatio,
            Scaling=FuselageScaling,
            NoseCoordinates=[0, 0, 0],
            CylindricalMidSection=False,
            SimplificationReqd=False)
    except:
        print "Fuselage fitting failed - stopping."
        return

    FuselageHeight = FuselageScaling[2] * 0.105
    FuselageLength = FuselageScaling[0]
    FuselageWidth = FuselageScaling[1] * 0.106
    rs.Redraw()

    if FuselageOMLSurf is None:
        print "Failed to fit fuselage surface, stopping."
        return

    FSurf = rs.CopyObject(FuselageOMLSurf)

    # Position of the apex of the wing
    if FuselageHeight < 8.0:
        WingApex = [0.1748 * FuselageLength, 0,
                    -0.0523 * FuselageHeight]  #787:[9.77,0,-0.307]
    else:
        WingApex = [0.1748 * FuselageLength, 0,
                    -0.1 * FuselageHeight]  #787:[9.77,0,-0.307]

    # Set up the wing object, including the list of user-defined functions that
    # describe the spanwise variations of sweep, dihedral, etc.
    LooseSurf = 1
    if Topology == 1:
        SegmentNo = 10
        Wing = liftingsurface.LiftingSurface(WingApex,
                                             ta.mySweepAngleFunctionAirliner,
                                             ta.myDihedralFunctionAirliner,
                                             ta.myTwistFunctionAirliner,
                                             ta.myChordFunctionAirliner,
                                             ta.myAirfoilFunctionAirliner,
                                             LooseSurf,
                                             SegmentNo,
                                             TipRequired=True)
    elif Topology == 2:
        SegmentNo = 101
        Wing = liftingsurface.LiftingSurface(WingApex,
                                             ta.mySweepAngleFunctionAirliner,
                                             bw.myDihedralFunctionBoxWing,
                                             ta.myTwistFunctionAirliner,
                                             ta.myChordFunctionAirliner,
                                             ta.myAirfoilFunctionAirliner,
                                             LooseSurf,
                                             SegmentNo,
                                             TipRequired=True)

    # Instantiate the wing object and add it to the document
    rs.EnableRedraw(False)
    WingSurf, ActualSemiSpan, LSP_area, RootChord, AR, WingTip = Wing.GenerateLiftingSurface(
        WingChordFactor, WingScaleFactor)
    rs.Redraw()

    if Topology == 1:
        # Add wing to body fairing
        WTBFXCentre = WingApex[
            0] + RootChord / 2.0 + RootChord * 0.1297  # 787: 23.8
        if FuselageHeight < 8.0:
            WTBFZ = RootChord * 0.009  #787: 0.2
            WTBFheight = 0.1212 * RootChord  #787:2.7
            WTBFwidth = 1.08 * FuselageWidth
        else:
            WTBFZ = WingApex[2] + 0.005 * RootChord
            WTBFheight = 0.09 * RootChord
            WTBFwidth = 1.15 * FuselageWidth

        WTBFlength = 1.167 * RootChord  #787:26

        WTBFXStern = WTBFXCentre + WTBFlength / 2.0

        CommS = "_Ellipsoid %3.2f,0,%3.2f %3.2f,0,%3.2f %3.2f,%3.2f,%3.2f %3.2f,0,%3.2f " % (
            WTBFXCentre, WTBFZ, WTBFXStern, WTBFZ, 0.5 *
            (WTBFXCentre + WTBFXStern), 0.5 * WTBFwidth, WTBFZ, 0.5 *
            (WTBFXCentre + WTBFXStern), WTBFheight)

        rs.EnableRedraw(False)

        rs.CurrentView("Perspective")
        rs.Command(CommS)
        LO = rs.LastCreatedObjects()
        WTBF = LO[0]
        rs.Redraw()

        # Trim wing inboard section
        CutCirc = rs.AddCircle3Pt((0, WTBFwidth / 4, -45),
                                  (0, WTBFwidth / 4, 45),
                                  (90, WTBFwidth / 4, 0))
        CutCircDisk = rs.AddPlanarSrf(CutCirc)
        CutDisk = CutCircDisk[0]
        rs.ReverseSurface(CutDisk, 1)
        rs.TrimBrep(WingSurf, CutDisk)
    elif Topology == 2:
        # Overlapping wing tips
        CutCirc = rs.AddCircle3Pt((0, 0, -45), (0, 0, 45), (90, 0, 0))
        CutCircDisk = rs.AddPlanarSrf(CutCirc)
        CutDisk = CutCircDisk[0]
        rs.ReverseSurface(CutDisk, 1)
        rs.TrimBrep(WingSurf, CutDisk)

    # Engine installation (nacelle and pylon)

    if Propulsion == 1:
        # Twin, wing mounted
        SpanStation = SpanStation1
        NacelleLength = 1.95 * EngineDia
        rs.EnableRedraw(False)
        EngineSection, Chord = act.CutSect(WingSurf, SpanStation)
        CEP = rs.CurveEndPoint(Chord)
        EngineStbd, PylonStbd = engine.TurbofanNacelle(
            EngineSection,
            Chord,
            CentreLocation=[
                CEP.X - EngineCtrFwdOfLE * NacelleLength, CEP.Y,
                CEP.Z - EngineCtrBelowLE * NacelleLength
            ],
            ScarfAngle=Scarf_deg,
            HighlightRadius=EngineDia / 2.0,
            MeanNacelleLength=NacelleLength)
        rs.Redraw()
    elif Propulsion == 2:
        # Quad, wing-mounted
        NacelleLength = 1.95 * EngineDia

        rs.EnableRedraw(False)
        EngineSection, Chord = act.CutSect(WingSurf, SpanStation1)
        CEP = rs.CurveEndPoint(Chord)

        EngineStbd1, PylonStbd1 = engine.TurbofanNacelle(
            EngineSection,
            Chord,
            CentreLocation=[
                CEP.X - EngineCtrFwdOfLE * NacelleLength, CEP.Y,
                CEP.Z - EngineCtrBelowLE * NacelleLength
            ],
            ScarfAngle=Scarf_deg,
            HighlightRadius=EngineDia / 2.0,
            MeanNacelleLength=NacelleLength)

        rs.DeleteObjects([EngineSection, Chord])

        EngineSection, Chord = act.CutSect(WingSurf, SpanStation2)
        CEP = rs.CurveEndPoint(Chord)

        EngineStbd2, PylonStbd2 = engine.TurbofanNacelle(
            EngineSection,
            Chord,
            CentreLocation=[
                CEP.X - EngineCtrFwdOfLE * NacelleLength, CEP.Y,
                CEP.Z - EngineCtrBelowLE * NacelleLength
            ],
            ScarfAngle=Scarf_deg,
            HighlightRadius=EngineDia / 2.0,
            MeanNacelleLength=NacelleLength)
        rs.Redraw()

    # Script for generating and positioning the fin
    rs.EnableRedraw(False)
    # Position of the apex of the fin
    P = [0.6524 * FuselageLength, 0.003, FuselageHeight * 0.384]
    #P = [36.47,0.003,2.254]55.902
    RotVec = rs.VectorCreate([1, 0, 0], [0, 0, 0])
    LooseSurf = 1
    SegmentNo = 200
    Fin = liftingsurface.LiftingSurface(P, tail.mySweepAngleFunctionFin,
                                        tail.myDihedralFunctionFin,
                                        tail.myTwistFunctionFin,
                                        tail.myChordFunctionFin,
                                        tail.myAirfoilFunctionFin, LooseSurf,
                                        SegmentNo)
    ChordFactor = 1.01  #787:1.01
    if Topology == 1:
        ScaleFactor = WingScaleFactor / 2.032  #787:21.93
    elif Topology == 2:
        ScaleFactor = WingScaleFactor / 3.5
    FinSurf, FinActualSemiSpan, FinArea, FinRootChord, FinAR, FinTip = Fin.GenerateLiftingSurface(
        ChordFactor, ScaleFactor)
    FinSurf = rs.RotateObject(FinSurf, P, 90, axis=RotVec)
    FinTip = rs.RotateObject(FinTip, P, 90, axis=RotVec)

    if Topology == 1:
        # Tailplane
        P = [0.7692 * FuselageLength, 0.000, FuselageHeight * 0.29]
        RotVec = rs.VectorCreate([1, 0, 0], [0, 0, 0])
        LooseSurf = 1
        SegmentNo = 100
        TP = liftingsurface.LiftingSurface(P, tail.mySweepAngleFunctionTP,
                                           tail.myDihedralFunctionTP,
                                           tail.myTwistFunctionTP,
                                           tail.myChordFunctionTP,
                                           tail.myAirfoilFunctionTP, LooseSurf,
                                           SegmentNo)
        ChordFactor = 1.01
        ScaleFactor = 0.388 * WingScaleFactor  #787:17.3
        TPSurf, TPActualSemiSpan, TPArea, TPRootChord, TPAR, TPTip = TP.GenerateLiftingSurface(
            ChordFactor, ScaleFactor)

    rs.EnableRedraw(True)

    rs.DeleteObjects([EngineSection, Chord])
    try:
        rs.DeleteObjects([CutCirc])
    except:
        pass

    try:
        rs.DeleteObjects([CutCircDisk])
    except:
        pass

    # Windows

    # Cockpit windows:
    rs.EnableRedraw(False)

    CockpitWindowTop = 0.305 * FuselageHeight

    CWC1s, CWC2s, CWC3s, CWC4s = fuselage_oml.CockpitWindowContours(
        Height=CockpitWindowTop, Depth=6)

    FuselageOMLSurf, Win1 = rs.SplitBrep(FuselageOMLSurf,
                                         CWC1s,
                                         delete_input=True)
    FuselageOMLSurf, Win2 = rs.SplitBrep(FuselageOMLSurf,
                                         CWC2s,
                                         delete_input=True)
    FuselageOMLSurf, Win3 = rs.SplitBrep(FuselageOMLSurf,
                                         CWC3s,
                                         delete_input=True)
    FuselageOMLSurf, Win4 = rs.SplitBrep(FuselageOMLSurf,
                                         CWC4s,
                                         delete_input=True)

    rs.DeleteObjects([CWC1s, CWC2s, CWC3s, CWC4s])

    (Xmin, Ymin, Zmin, Xmax, Ymax,
     Zmax) = act.ObjectsExtents([Win1, Win2, Win3, Win4])
    CockpitBulkheadX = Xmax

    CockpitWallPlane = rs.PlaneFromPoints([CockpitBulkheadX, -15, -15],
                                          [CockpitBulkheadX, 15, -15],
                                          [CockpitBulkheadX, -15, 15])

    CockpitWall = rs.AddPlaneSurface(CockpitWallPlane, 30, 30)

    if 'WTBF' in locals():
        rs.TrimBrep(WTBF, CockpitWall)

    rs.DeleteObject(CockpitWall)

    # Window lines
    WIN = [1]
    NOWIN = [0]

    # A typical window pattern (including emergency exit windows)
    WinVec = WIN + 2 * NOWIN + 9 * WIN + 3 * NOWIN + WIN + NOWIN + 24 * WIN + 2 * NOWIN + WIN + NOWIN + 14 * WIN + 2 * NOWIN + WIN + 20 * WIN + 2 * NOWIN + WIN + NOWIN + 20 * WIN

    if FuselageHeight < 8.0:
        # Single deck
        WindowLineHeight = 0.3555 * FuselageHeight
        WinX = 0.1157 * FuselageLength
        WindowPitch = 0.609
        WinInd = -1
        while WinX < 0.75 * FuselageLength:
            WinInd = WinInd + 1
            if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX:
                WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow(
                    FuselageOMLSurf, WinX, WindowLineHeight)
                act.AssignMaterial(WinStbd, "Plexiglass")
                act.AssignMaterial(WinPort, "Plexiglass")
            WinX = WinX + WindowPitch
    else:
        # Fuselage big enough to accommodate two decks
        # Lower deck
        WindowLineHeight = 0.17 * FuselageHeight  #0.166
        WinX = 0.1 * FuselageLength  #0.112
        WindowPitch = 0.609
        WinInd = 0
        while WinX < 0.757 * FuselageLength:
            WinInd = WinInd + 1
            if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX:
                WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow(
                    FuselageOMLSurf, WinX, WindowLineHeight)
                act.AssignMaterial(WinStbd, "Plexiglass")
                act.AssignMaterial(WinPort, "Plexiglass")
            WinX = WinX + WindowPitch
        # Upper deck
        WindowLineHeight = 0.49 * FuselageHeight
        WinX = 0.174 * FuselageLength  #0.184
        WinInd = 0
        while WinX < 0.757 * FuselageLength:
            WinInd = WinInd + 1
            if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX:
                WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow(
                    FuselageOMLSurf, WinX, WindowLineHeight)
                act.AssignMaterial(WinStbd, "Plexiglass")
                act.AssignMaterial(WinPort, "Plexiglass")
            WinX = WinX + WindowPitch

    rs.Redraw()

    act.AssignMaterial(FuselageOMLSurf, "White_composite_external")
    act.AssignMaterial(WingSurf, "White_composite_external")
    try:
        act.AssignMaterial(TPSurf, "ShinyBARedMetal")
    except:
        pass
    act.AssignMaterial(FinSurf, "ShinyBARedMetal")
    act.AssignMaterial(Win1, "Plexiglass")
    act.AssignMaterial(Win2, "Plexiglass")
    act.AssignMaterial(Win3, "Plexiglass")
    act.AssignMaterial(Win4, "Plexiglass")

    # Mirror the geometry as required
    act.MirrorObjectXZ(WingSurf)
    act.MirrorObjectXZ(WingTip)
    try:
        act.MirrorObjectXZ(TPSurf)
        act.MirrorObjectXZ(TPTip)
    except:
        pass
    if Propulsion == 1:
        for ObjId in EngineStbd:
            act.MirrorObjectXZ(ObjId)
        act.MirrorObjectXZ(PylonStbd)
    elif Propulsion == 2:
        for ObjId in EngineStbd1:
            act.MirrorObjectXZ(ObjId)
        act.MirrorObjectXZ(PylonStbd1)
        for ObjId in EngineStbd2:
            act.MirrorObjectXZ(ObjId)
        act.MirrorObjectXZ(PylonStbd2)

    rs.DeleteObject(FSurf)
    rs.Redraw()
import rhinoscriptsyntax as rs
import Rhino
import Rhino.Geometry as rg
doc = Rhino.RhinoDoc.ActiveDoc


###insert clipboard object at point
cmd = "'_Paste"
rs.Command(cmd, False)
objs = rs.LastCreatedObjects(select=True)
destination = rs.GetPoint("Choose a point to place object")

#calculate initial point and placement point
pt = rs.CurveStartPoint(objs[0])
dx = destination[0] - pt[0]
dy = destination[1] - pt[1]
dz = destination[2] - pt[2]
translation = [dx, dy, dz]
rs.MoveObjects(objs, translation)