Example #1
0
def test():
	
	opt_KeepLayer = Rhino.Input.Custom.OptionToggle("KeepLayer","No","Yes")
	
	go = Rhino.Input.Custom.GetObject()
	go.GeometryFilter = Rhino.DocObjects.ObjectType.Brep

	go.SetCommandPrompt("Select Breps")
	go.AddOptionToggle("KeepLayer",opt_KeepLayer)
	
#	go.GroupSelect = True
#	go.SubObjectSelect = False
#	go.AcceptEnterWhenDone(True)
#	go.AcceptNothing(True)
#	go.EnableClearObjectsOnEntry(False)
#	go.GroupSelect = True
#	go.SubObjectSelect = False
#	go.DeselectAllBeforePostSelect = False
	
	go.GroupSelect = True
	go.SubObjectSelect = False
	go.AcceptEnterWhenDone(True)
	go.AcceptNothing(True)
	go.EnableClearObjectsOnEntry(False)
	go.EnableUnselectObjectsOnExit(False)
	go.GroupSelect = True
	go.SubObjectSelect = False
	go.DeselectAllBeforePostSelect = False
	
	res = None
	bHavePreselectedObjects = True
	while True:
		res = go.GetMultiple(1,0)
		if res == Rhino.Input.GetResult.Option:
			go.EnablePreSelect(False, True)
			continue
		elif res != Rhino.Input.GetResult.Object:
			rs.Redraw()
			print "No Breps Selected!"
			return Rhino.Commands.Result.Cancel
		if go.ObjectsWerePreselected:
			rs.Redraw()
			bHavePreselectedObjects = True
			go.EnablePreSelect(False, True)
			continue
		break
	
	print "testing..."
	return None
Example #2
0
def divide_curve():
    # get user input
    res, obj_refs = RhinoGet.GetMultipleObjects("Curves to divide",
        False, ObjectType.EdgeFilter | ObjectType.Curve)
    if res <> Result.Success: return res
    curves = [obj_ref.Curve() for obj_ref in obj_refs]

    distance_between_divisions = rs.GetReal(
      message = "Distance between divisions",
      number = 5.0, minimum = 1.0)
    if distance_between_divisions == None: return

    # generate the points
    points = []
    for curve in curves:
      t0 = curve.Domain.Min
      points.append(curve.PointAt(t0))

      sphere_center = curve.PointAt(t0)
      t = t0
      rest_of_curve = curve
      while True:
        sphere = Sphere(sphere_center, distance_between_divisions)
        b, overlapCurves, intersectPoints = Intersection.CurveBrep(
                               rest_of_curve, sphere.ToBrep(), 0.0)
        if b == False or (overlapCurves.Length == 0 and intersectPoints.Length == 0):
          break
        t, point = nextIntersectParamAndPoint(
          overlapCurves, intersectPoints, rest_of_curve)
        points.append(point)
        sphere_center = point
        rest_of_curve = curve.Split(t)[1]

    rs.AddPoints(points)
    rs.Redraw()
def SampleSynchronizeRenderColors():

    objects = rs.AllObjects()
    if objects is None: return

    for obj in objects:

        color = rs.ObjectColor(obj)
        source = rs.ObjectColorSource(obj)
        material = -1

        if source == 0:
            layer = rs.ObjectLayer(obj)
            material = rs.LayerMaterialIndex(layer)
            if material < 0:
                material = rs.AddMaterialToLayer(layer)

        elif source == 1:
            material = rs.ObjectMaterialIndex(obj)
            if material < 0:
                material = rs.AddMaterialToObject(obj)

        if material >= 0:
            if color != rs.MaterialColor(material):
                rs.MaterialColor(material, color)

    rs.Redraw()
Example #4
0
def RunCommand(is_interactive):
    setGlobals()
    crvs = get_input()
    if isinstance(crvs, list):
        rc_get_tags(crvs)
    rs.EnableRedraw(True)
    rs.Redraw()
    return 0
def SampleTextDot():
    gp = SampleGetTextDotPoint();
    gp.Get()
    if (gp.CommandResult() == Rhino.Commands.Result.Success):
        point = gp.Point()
        str = gp.FormatPointString(point)
        rs.AddTextDot(str, point)
        rs.Redraw()
 def jumps(self, magnitude):
     a = rs.GetPoint("Enter start point")
     p = rs.AddPoint(a)
     sphere = rs.AddSphere(p, 4)
     print self.direction
     prevPos = rs.PointCoordinates(self.point)
     for d in range(1, 50):
         nn = rs.Redraw()
         for i in range(1, 50):
             rs.MoveObject(sphere, (1, 1, 20 / i))
         for i in range(1, 50):
             rs.MoveObject(sphere, (1, 1, -1 * i / 40))
def main():

    max_flrs = 9999  # maximum number of folders to open
    max_fils = 9999  # maximum number of files to open in each folder

    folder_tic = time.clock()
    fdr_cnt = 0
    for root, dirs, files in walklevel(src_path):

        print("{}\t {}".format(fdr_cnt, root))
        #if (root == src_path): continue

        fil_cnt = 0
        for full_filename in files:
            filename, file_extension = os.path.splitext(full_filename)
            if file_extension != ".3dm": continue

            file_tic = time.clock()
            filepath = os.path.join(root, full_filename)
            rs.DocumentModified(False)
            rs.Command('_-Open {} _Enter'.format('"' + filepath + '"'))

            pln = rs.PlaneFromPoints((100, 0, 0), (0, 100, 0), (100, 100, 0))
            rs.AddRectangle(pln, 100, 100)

            set_active_view("Origin_SW_ISO")
            view = rs.CurrentView()
            set_disp_mode(disp_mode)
            rs.Redraw()
            """
            rs.ViewProjection(view,2)
            rs.ViewCameraTarget(view,cam_pos,tar_pos)
            
            rs.ViewCameraLens(view,lens_len)
            rs.ZoomExtents(view)
            #rs.ViewCameraLens(view,25)
            """
            capture_view_antialias(
                os.path.join(tar_path, "{}.png".format(filename)), image_size)

            t = round(time.clock() - file_tic)
            print(filename + "\ttime:\t" + str(t))

            fil_cnt += 1
            if fil_cnt > max_fils: break

        fdr_cnt += 1
        if fdr_cnt > max_flrs: break

    t = round(time.clock() - folder_tic)
    print("TOTAL\ttime:\t" + str(t))
Example #8
0
 def __init__(self, color=None):
     self.point = rs.GetPoint()
     self.radius = .2
     self.color = color
     self.block = Block()
     self.circle = None
     self.id = uuid.uuid4()
     self.hatch = None
     self.group_name = None
     self.center = None
     self.group_list = []
     self.add_count()
     self.set_color(color)
     rs.Redraw()
Example #9
0
    def redraw(self, timeout=None):
        """Redraw the Rhino view.

        Parameters
        ----------
        timeout : float, optional
            The amount of time the artist waits before updating the Rhino view.
            The time should be specified in seconds.
            Default is ``None``.

        """
        if timeout:
            time.sleep(timeout)
        rs.EnableRedraw(True)
        rs.Redraw()
Example #10
0
def draw_mesh_as_faces(mesh,
                       layer=None,
                       clear_layer=False,
                       facecolor=None,
                       redraw=True):

    guids = compas_rhino.get_objects(
        name='{0}.*'.format(mesh.attributes['name']))
    compas_rhino.delete_objects(guids)

    if clear_layer:
        if not layer:
            compas_rhino.clear_current_layer()
        else:
            compas_rhino.clear_layer(layer)

    facecolor = facecolor or {}

    meshes = []

    for fkey in mesh.faces():
        vertices = mesh.face_coordinates(fkey)
        faces = [range(len(vertices))]
        color = facecolor.get(fkey, (255, 255, 255))
        guid = compas_rhino.xdraw_mesh(vertices,
                                       faces,
                                       None,
                                       '{0}.face.{1}'.format(
                                           mesh.attributes['name'], fkey),
                                       layer=layer,
                                       clear=False,
                                       redraw=False)
        compas_rhino.set_mesh_vertex_colors(
            guid, [color for i in range(len(vertices))])
        meshes.append(guid)

    if layer:
        previous = rs.CurrentLayer(layer)

    guid = rs.JoinMeshes(meshes, delete_input=True)

    if layer:
        rs.CurrentLayer(previous)

    rs.ObjectName(guid, '{0}'.format(mesh.attributes['name']))

    rs.EnableRedraw()
    rs.Redraw()
def guessHorizontalShift():
    """
    This script will correct the horizontal distortion and set it in the V-Ray Camera.
    It levels the camera for this correction to work well and resets
    lens shift (vertical shift) to 0
    Works with V-Ray 5.1
        
    version 0.4
        
    www.studiogijs.nl
    """
    viewport = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport
    if viewport.IsParallelProjection:
        print "Stupid, you should select a perspective view"
        return
    view = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport
    #set camera location to target height
    pt = view.CameraLocation
    pt[2] = view.CameraTarget.Z
    dir = rs.VectorSubtract(view.CameraTarget, pt)
    view.SetCameraLocation(pt, False)
    view.SetCameraDirection(dir, False)

    #calculate camera direction angle relative to WorldXY plane
    cam = view.CameraZ
    vec = Rhino.Geometry.Vector3d(1, 0, 0)
    plane = Rhino.Geometry.Plane.WorldXY
    angle = Rhino.Geometry.Vector3d.VectorAngle(cam, vec, plane)

    #calculate the correction factor
    for i in range(3):
        if angle > math.pi / 2:
            angle -= math.pi / 2
        else:
            break

    if 0 <= angle < math.pi / 4:
        factor = math.tan(angle)

    if math.pi / 4 <= angle < math.pi / 2:
        factor = -math.tan(math.pi / 2 - angle)

    rv = rs.GetPlugInObject("V-Ray for Rhino").Scene().Plugin(
        "/CameraPhysical")
    rv.Param("horizontal_shift").Value = factor
    print "Horizontal shift factor set to %r." % factor
    rv.Param("lens_shift").Value = 0
    rs.Redraw()
Example #12
0
def cloudrestore(id):
    """Retrieve settings document from a couchdb database and
    update the current application settings by these values
    Parameters:
        id: name of the document store in the database
    """
    f = urllib.urlopen(couchdb_url + "/" + id)
    data = json.load(f)
    f.close()
    if data.has_key("error"): return data

    states = {}
    states[
        "AppearanceSettings"] = Rhino.ApplicationSettings.AppearanceSettings.GetDefaultState(
        )
    states[
        "EdgeAnalysisSettings"] = Rhino.ApplicationSettings.EdgeAnalysisSettings.GetDefaultState(
        )
    states[
        "ModelAidSettings"] = Rhino.ApplicationSettings.ModelAidSettings.GetDefaultState(
        )

    def restoresetting(state, name, setting):
        try:
            s = "state." + name
            if name.endswith("Color"):
                s += "=System.Drawing.ColorTranslator.FromHtml(\"" + setting + "\")"
            else:
                if type(setting) is str: s += "='" + setting + "'"
                else: s += "=" + str(setting)
            exec(s)
        except:
            print sys.exc_info()

    for setting, val in data.items():
        if type(val) is dict and states.has_key(setting):
            state = states[setting]
            for k, v in val.items():
                restoresetting(state, k, v)
    Rhino.ApplicationSettings.AppearanceSettings.UpdateFromState(
        states["AppearanceSettings"])
    Rhino.ApplicationSettings.EdgeAnalysisSettings.UpdateFromState(
        states["EdgeAnalysisSettings"])
    Rhino.ApplicationSettings.ModelAidSettings.UpdateFromState(
        states["ModelAidSettings"])
    rs.Redraw()
Example #13
0
def cloudrestore(id):
    """Retrieve settings from database and update the
    the current application settings by these values
    Parameters:
      id: name of the settings scheme in the database
    """
    f = urllib.urlopen(appengine_url + '/' + id)
    received_data = f.read()
    f.close()
    if not received_data:
        return
    data = json.loads(received_data)

    color = data["ViewportBackgroundColor"]
    color = System.Drawing.ColorTranslator.FromHtml(color)
    Rhino.ApplicationSettings.AppearanceSettings.ViewportBackgroundColor = color
    rs.Redraw()
Example #14
0
 def on_selected(sender, event):
     try:
         rs.UnselectAllObjects()
         key = event.Item.Values[0]
         guid2key = getattr(sceneNode.artist, guid_field)
         key2guid = {str(guid2key[guid]): guid for guid in guid2key}
         if key in key2guid:
             find_object(key2guid[key]).Select(True)
         elif children_guid_field:
             if key == '':
                 key = event.Item.Values[1]
             guid2key = getattr(sceneNode.artist, children_guid_field)
             key2guid = {str(guid2key[guid]): guid for guid in guid2key}
             find_object(key2guid[key]).Select(True)
         print('selected', key, key2guid[key])
         rs.Redraw()
     except Exception as e:
         print(e)
def draw_light(mesh, temp=True):

    pts = []
    faces = []
    count = 0
    for u, v in mesh.edges():
        pts.append(mesh.vertex_coordinates(u))
        pts.append(mesh.vertex_coordinates(v))
        pts.append(
            (mesh.vertex[u]['x2'], mesh.vertex[u]['y2'], mesh.vertex[u]['z2']))
        pts.append(
            (mesh.vertex[v]['x2'], mesh.vertex[v]['y2'], mesh.vertex[v]['z2']))
        faces.append([count, count + 1, count + 3, count + 2])
        count += 4

    guid = rs.AddMesh(pts, faces)
    if temp:
        Rhino.RhinoApp.Wait()
        rs.Redraw()
        #         rs.EnableRedraw(True)
        #         rs.EnableRedraw(False)
        rs.DeleteObject(guid)
    return guid
Example #16
0
        def on_selected(sender, event):
            try:
                rs.UnselectAllObjects()
                key = event.Item.Values[1]
                guid2key = getattr(sceneNode, guid_field)
                key2guid = {str(guid2key[guid]): guid for guid in guid2key}
                if key in key2guid:
                    find_object(key2guid[key]).Select(True)

                if dual:
                    force_edge_index = int(event.Item.Values[0])
                    force_edge_key2index = dual.diagram.edge_index(
                        dual.diagram.dual)
                    force_edge_index2key = {
                        force_edge_key2index[key]: key
                        for key in force_edge_key2index
                    }
                    force_edge_key = force_edge_index2key[force_edge_index]

                    guid2key = getattr(dual, guid_field)
                    key2guid = {guid2key[guid]: guid for guid in guid2key}
                    key2guid.update({(v, u): key2guid[(u, v)]
                                     for u, v in key2guid})
                    if force_edge_key in key2guid:
                        find_object(key2guid[force_edge_key]).Select(True)

                # elif children_guid_field:
                #     if key == '':
                #         key = event.Item.Values[1]
                #     guid2key = getattr(sceneNode.artist, children_guid_field)
                #     key2guid = {str(guid2key[guid]): guid for guid in guid2key}
                #     find_object(key2guid[key]).Select(True)

                # print('selected', key, key2guid[key])
                rs.Redraw()
            except Exception as e:
                print(e)
Example #17
0
 def redraw(self):
     """Redraw the Rhino view."""
     rs.EnableRedraw(True)
     rs.Redraw()
Example #18
0
def rc_collapse_box():

    go = Rhino.Input.Custom.GetObject()
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Brep

    default_KeepLayer = sc.sticky["KeepLayer"] if sc.sticky.has_key(
        "KeepLayer") else False
    default_IgnoreOpen = sc.sticky["IgnoreOpen"] if sc.sticky.has_key(
        "IgnoreOpen") else False
    opt_KeepLayer = Rhino.Input.Custom.OptionToggle(default_KeepLayer, "No",
                                                    "Yes")
    opt_IgnoreOpen = Rhino.Input.Custom.OptionToggle(default_IgnoreOpen, "No",
                                                     "Yes")

    go.SetCommandPrompt("Select Breps")
    go.AddOptionToggle("KeepLayer", opt_KeepLayer)
    go.AddOptionToggle("IgnoreOpenBreps", opt_IgnoreOpen)

    go.GroupSelect = True
    go.SubObjectSelect = False
    go.AcceptEnterWhenDone(True)
    go.AcceptNothing(True)
    go.EnableClearObjectsOnEntry(False)
    go.EnableUnselectObjectsOnExit(False)
    go.GroupSelect = True
    go.SubObjectSelect = False
    go.DeselectAllBeforePostSelect = False

    res = None
    bHavePreselectedObjects = True

    while True:
        res = go.GetMultiple(1, 0)
        if res == Rhino.Input.GetResult.Option:
            go.EnablePreSelect(False, True)
            continue
        #If not correct
        elif res != Rhino.Input.GetResult.Object:
            rs.Redraw()
            print "No breps were selected!"
            return Rhino.Commands.Result.Cancel
        if go.ObjectsWerePreselected:
            rs.Redraw()
            bHavePreselectedObjects = True
            go.EnablePreSelect(False, True)
            continue
        break

    OPT_IGNORE_OPEN = opt_IgnoreOpen.CurrentValue
    OPT_KEEP_LAYER = opt_KeepLayer.CurrentValue
    sticky["IgnoreOpen"] = OPT_IGNORE_OPEN
    sticky["KeepLayer"] = OPT_KEEP_LAYER

    rs.EnableRedraw(False)

    input_breps = []
    for i in xrange(go.ObjectCount):
        b_obj = go.Object(i).Object()
        input_breps.append(b_obj.Id)

    current_cplane = sc.doc.Views.ActiveView.ActiveViewport.GetConstructionPlane(
    )
    temp_cplane = current_cplane.Plane
    current_cplane.Plane = rs.WorldXYPlane()

    solid_brep_count = 0
    for brep in input_breps:

        if not rs.IsObjectSolid(brep):
            solid_brep_count += 1
            if OPT_IGNORE_OPEN: continue

        if OPT_KEEP_LAYER: brep_layer = rs.ObjectLayer(rs.coerceguid(brep))

        exploded = rs.ExplodePolysurfaces(brep, True)
        remaining_srfs = []
        for srf in exploded:
            norm = rs.SurfaceNormal(srf, [0.5, 0.5])
            if 10 > rs.VectorAngle(norm, [0, 0, 1]) or 10 > rs.VectorAngle(
                    norm, [0, 0, -1]):
                rs.DeleteObject(srf)
            else:
                remaining_srfs.append(srf)
        areas = [rs.SurfaceArea(s) for s in remaining_srfs]
        areas = [x[0] for x in areas]
        srfs, areas = zip(
            *sorted(zip(remaining_srfs, areas), key=lambda x: x[1]))
        pt1, _ = rs.SurfaceAreaCentroid(srfs[-1])
        pt2, _ = rs.SurfaceAreaCentroid(srfs[-2])
        vect = rs.VectorCreate(pt2, pt1)
        vect = rs.VectorDivide(vect, 2)
        rs.MoveObject(srfs[-1], vect)

        if OPT_KEEP_LAYER: rs.ObjectLayer(srfs[-1], brep_layer)
        rs.SelectObjects(srfs[-1])
        rs.DeleteObjects(srfs[:-1])

    rs.EnableRedraw(True)
    rs.Redraw()

    current_cplane.Plane = temp_cplane
    if solid_brep_count > 0:
        outcome = " and were not collapsed." if OPT_IGNORE_OPEN else " and may have been flattened incorrectly. Check input geometry."
        report = str(solid_brep_count) + " brep(s) were not closed" + outcome
        print report
Example #19
0
def rc_Bridge():
    #get stickies
    default_bridge_size = sticky["defaultSize"] if sticky.has_key(
        "defaultSize") else 2
    default_bridge_border = sticky["defaultBorder"] if sticky.has_key(
        "defaultBorder") else 2
    default_bynum_bool = sticky["defaultByNum"] if sticky.has_key(
        "defaultByNum") else True

    go = Rhino.Input.Custom.GetObject()
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve
    go.GeometryAttributeFilter = Rhino.Input.Custom.GeometryAttributeFilter.ClosedCurve

    opt_bridge_size = Rhino.Input.Custom.OptionDouble(default_bridge_size, 0.2,
                                                      1000)
    opt_bridge_border = Rhino.Input.Custom.OptionDouble(
        default_bridge_border, 0.2, 1000)
    opt_by_num = Rhino.Input.Custom.OptionToggle(default_bynum_bool,
                                                 "ByLength", "ByNumber")

    go.SetCommandPrompt("Select Curves for Bridging")
    go.AddOptionDouble("BridgeSize", opt_bridge_size)
    go.AddOptionDouble("BridgeBorder", opt_bridge_border)
    out_mode = go.AddOptionToggle("Mode", opt_by_num)

    go.GroupSelect = True
    go.SubObjectSelect = False
    go.AcceptEnterWhenDone(True)
    go.AcceptNothing(True)
    go.EnableClearObjectsOnEntry(False)
    go.EnableUnselectObjectsOnExit(False)
    go.GroupSelect = True
    go.SubObjectSelect = False
    go.DeselectAllBeforePostSelect = False

    res = None
    bHavePreselectedObjects = False

    while True:
        res = go.GetMultiple(1, 0)

        #If new option entered, redraw a possible result
        if res == Rhino.Input.GetResult.Option:
            # print res
            go.EnablePreSelect(False, True)
            continue

        #If not correct
        elif res != Rhino.Input.GetResult.Object:
            return Rhino.Commands.Result.Cancel

        if go.ObjectsWerePreselected:
            bHavePreselectedObjects = True
            go.EnablePreSelect(False, True)
            continue

        break

    CUT_LENGTH = opt_bridge_size.CurrentValue
    CUT_TOL = opt_bridge_border.CurrentValue
    BY_NUM = opt_by_num.CurrentValue

    #get properties of objects
    crv_max_length = 0
    crv_obj_list = []
    for i in xrange(go.ObjectCount):
        c_obj = go.Object(i).Object()
        crv_obj_list.append(c_obj)
        if i == 0:
            crv_max_length = c_obj.CurveGeometry.Domain.Mid
        else:
            crv_max_length = min(crv_max_length,
                                 c_obj.CurveGeometry.Domain.Mid)

    #add bridges by length or by number.
    if BY_NUM == True:
        default_segmentCount = sticky["defaultSegmentCount"] if sticky.has_key(
            "defaultSegmentCount") else 2

        rc, segment_count = Rhino.Input.RhinoGet.GetInteger(
            "Divide curves into how many segments?", True,
            default_segmentCount, 2, 500)
        if rc != Rhino.Commands.Result.Success:
            return rc
        m_addBridges(crv_obj_list, segment_count)
        sticky["defaultSegmentCount"] = segment_count
    else:
        default_segmentLength = sticky["defaultSegLength"] if (
            sticky.has_key("defaultSegLength")
            and sticky["defaultSegLength"] < crv_max_length
        ) else crv_max_length / 2
        s = "What approximate length would you like to target? The maximum for these curves is {0:.2f}".format(
            crv_max_length)
        rc, segment_length = Rhino.Input.RhinoGet.GetNumber(
            s, False, default_segmentLength, 0, crv_max_length)
        if rc != Rhino.Commands.Result.Success:
            return rc
        m_addBridges(crv_obj_list, segment_length, False)
        sticky["defaultSegLen"] = segment_length

    #display the bridges and request options.
    go = Rhino.Input.Custom.GetOption()
    opt_bridge_size = Rhino.Input.Custom.OptionDouble(CUT_LENGTH, 0.2, 1000)
    opt_bridge_border = Rhino.Input.Custom.OptionDouble(CUT_TOL, 0.2, 1000)

    go.SetCommandPrompt("Adjust Options. Enter to Continue.")
    go.AddOptionDouble("BridgeSize", opt_bridge_size)
    go.AddOptionDouble("BridgeBorder", opt_bridge_border)
    go.AcceptEnterWhenDone(True)
    go.AcceptNothing(True)

    #draw the preview.
    buffer_distance = CUT_LENGTH + CUT_TOL
    m_manage_discons(crv_obj_list, buffer_distance)
    preview_layers = m_showBridges(crv_obj_list, CUT_LENGTH, CUT_TOL)
    rs.Redraw()
    while True:
        res = go.Get()

        #If new option entered, redraw a possible result
        if res == Rhino.Input.GetResult.Option:
            for layer_ind in preview_layers:
                Rhino.DocObjects.Tables.LayerTable.Purge(
                    doc.ActiveDoc.Layers, layer_ind, True)
            CUT_LENGTH = opt_bridge_size.CurrentValue
            CUT_TOL = opt_bridge_border.CurrentValue
            buffer_distance = CUT_LENGTH + CUT_TOL
            m_manage_discons(crv_obj_list, buffer_distance)
            preview_layers = m_showBridges(crv_obj_list, CUT_LENGTH, CUT_TOL)
            rs.Redraw()
            continue

        #If not correct
        elif res == Rhino.Input.GetResult.Nothing:
            for layer_ind in preview_layers:
                doc.ActiveDoc.Layers
                Rhino.DocObjects.Tables.LayerTable.Purge(
                    doc.ActiveDoc.Layers, layer_ind, True)
            break

        for layer_ind in preview_layers:
            doc.ActiveDoc.Layers
            Rhino.DocObjects.Tables.LayerTable.Purge(doc.ActiveDoc.Layers,
                                                     layer_ind, True)
        return Rhino.Commands.Result.Failure

        break

    CUT_LENGTH = opt_bridge_size.CurrentValue
    CUT_TOL = opt_bridge_border.CurrentValue

    #Request output options.
    m_makeBridgeLines(crv_obj_list, CUT_LENGTH)

    sticky["defaultSize"] = CUT_LENGTH
    sticky["defaultBorder"] = CUT_TOL
    sticky["defaultByNum"] = BY_NUM
    return Rhino.Commands.Result.Success
Example #20
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 rc_unroll_ortho():
	
	go = Rhino.Input.Custom.GetObject()
	go.GeometryFilter = Rhino.DocObjects.ObjectType.Brep
	
	default_thickness = sticky["thickness"] if sticky.has_key("thickness") else 5.5
	default_lid = sticky["lid"] if sticky.has_key("lid") else False
	
	opt_thickness = Rhino.Input.Custom.OptionDouble(default_thickness,0.2,1000)
	opt_lid = Rhino.Input.Custom.OptionToggle(default_lid,"No","Yes")

	go.SetCommandPrompt("Select breps to unroll. Breps must be orthogonal (faces at 90 degree angles)")
	go.AddOptionDouble("Thickness", opt_thickness)
	go.AddOptionToggle("Lids", opt_lid)

	go.GroupSelect = True
	go.SubObjectSelect = False
	go.AcceptEnterWhenDone(True)
	go.AcceptNothing(True)
	go.EnableClearObjectsOnEntry(False)
	go.EnableUnselectObjectsOnExit(False)
	go.GroupSelect = True
	go.SubObjectSelect = False
	go.DeselectAllBeforePostSelect = False

	res = None
	bHavePreselectedObjects = False

	while True:
		res = go.GetMultiple(1,0)

		#If new option entered, redraw a possible result
		if res == Rhino.Input.GetResult.Option:
			#print res
			go.EnablePreSelect(False, True)
			continue

		#If not correct
		elif res != Rhino.Input.GetResult.Object:
			return Rhino.Commands.Result.Cancel

		if go.ObjectsWerePreselected:
			bHavePreselectedObjects = True
			go.EnablePreSelect(False, True)
			continue

		break

	rs.EnableRedraw(False)

	LID = opt_lid.CurrentValue
	global LCUT_INDICES, THICKNESS
	THICKNESS = opt_thickness.CurrentValue
	LCUT_INDICES = wla.get_lcut_layers()

	#Get geometry and object lists
	brep_obj_list = []
	brep_geo_list = []
	brep_ids_list = []
	for i in xrange(go.ObjectCount):
		b_obj = go.Object(i).Object()
		brep_obj_list.append(b_obj)
	
	#use world cplane
	current_cplane = sc.doc.Views.ActiveView.ActiveViewport.GetConstructionPlane()
	temp_cplane = current_cplane.Plane
	current_cplane.Plane = rs.WorldXYPlane()
	
	#get information for each piece to be output.
	#future implementation should use bounding dims and curves rather than dimension-based system.
	unrolled_brep_info = []
	lid_info = []
	
	SELECT_GUIDS = []
	
	#convert to breps
	input_brep_geo = []
	for i,obj in enumerate(brep_obj_list):
		#geometry prep: convert extrusions to breps
		if str(obj.ObjectType) != "Brep":
			new_brep = wru.extrusion_to_brep(obj.Geometry)
		else:
			new_brep = obj.Geometry
		input_brep_geo.append(new_brep)
	
	for geo in input_brep_geo:
		unroll_brep_with_thickness(geo)
	
	
	sticky["thickness"] = THICKNESS
	sticky["lid"] = LID
	
	current_cplane.Plane = temp_cplane
	rs.UnselectAllObjects()
	rs.SelectObjects(SELECT_GUIDS)
	rs.Redraw()
	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()
Example #23
0
def draw_mesh(
    mesh,
    layer=None,
    clear_layer=False,
    show_faces=True,
    show_vertices=False,
    show_edges=False,
    show_wireframe=False,
    vertexcolor=None,
    edgecolor=None,
    wireframecolor=None,
    facecolor=None,
):
    """
    Draw a mesh object in Rhino.

    Parameters:
        mesh (compas.datastructures.mesh.Mesh): The mesh object.
        layer (str): Optional. The layer to draw in. Default is ``None``.
        clear_layer (bool): Optional. Clear the drawing layer. Default is ``True``.
        show_faces (bool): Optional. Show the faces. Default is ``True``.
        show_vertices (bool): Optional. Show the vertices. Default is ``True``.
        show_edges (bool): Optional. Show the edges. Default is ``True``.
        vertexcolor (str, tuple, list, dict): Optional. The vertex color specification. Default is ``None``.
        edgecolor (str, tuple, list, dict): Optional. The edge color specification. Default is ``None``.
        facecolor (str, tuple, list, dict): Optional. The face color specification. Default is ``None``.
        redraw (bool): Optional. Redraw instructions. Default is ``True``.

    Note:
        Colors can be specifiedin different ways:

        * str: A hexadecimal color that will be applied to all elements subject to the specification.
        * tuple, list: RGB color that will be applied to all elements subject to the specification.
        * dict: RGB or hex color dict with a specification for some or all of the related elements.

    Important:
        RGB colors should specify color values between 0 and 255.

    """

    vertexcolor = color_to_colordict(vertexcolor,
                                     mesh.vertices(),
                                     default=mesh.attributes['color.vertex'],
                                     colorformat='rgb',
                                     normalize=False)

    edgecolor = color_to_colordict(edgecolor,
                                   mesh.edges(),
                                   default=mesh.attributes['color.edge'],
                                   colorformat='rgb',
                                   normalize=False)

    # facecolor = color_to_colordict(facecolor,
    #                                mesh.faces(),
    #                                default=mesh.attributes['color.face'],
    #                                colorformat='rgb',
    #                                normalize=False)

    guids = compas_rhino.get_objects(
        name='{0}.*'.format(mesh.attributes['name']))
    compas_rhino.delete_objects(guids)

    if clear_layer:
        if not layer:
            compas_rhino.clear_current_layer()
        else:
            compas_rhino.clear_layer(layer)

    if show_faces:
        key_index = {key: index for index, key in enumerate(mesh.vertices())}
        xyz = [mesh.vertex_coordinates(key) for key in mesh.vertices()]
        faces = []
        color = mesh.attributes['color.face']

        for fkey in mesh.face:
            face = mesh.face_vertices(fkey, ordered=True)
            v = len(face)

            if v < 3:
                print('Degenerate face: {0} => {1}'.format(fkey, face))
            elif v == 3:
                faces.append([key_index[k] for k in face + [face[-1]]])
            elif v == 4:
                faces.append([key_index[k] for k in face])
            else:
                c = len(xyz)
                xyz.append(mesh.face_center(fkey))
                for i in range(-1, len(face) - 1):
                    key = face[i]
                    nbr = face[i + 1]
                    vertices = [
                        c, key_index[key], key_index[nbr], key_index[nbr]
                    ]
                    faces.append(vertices)

        compas_rhino.xdraw_mesh(xyz,
                                faces,
                                color,
                                '{0}.mesh'.format(mesh.attributes['name']),
                                layer=layer,
                                clear=False,
                                redraw=False)

    if show_edges:
        lines = []
        color = mesh.attributes['color.edge']
        for u, v in mesh.edges():
            lines.append({
                'start':
                mesh.vertex_coordinates(u),
                'end':
                mesh.vertex_coordinates(v),
                'name':
                '{0}.edge.{1}-{2}'.format(mesh.attributes['name'], repr(u),
                                          repr(v)),
                'color':
                edgecolor.get((u, v), color),
            })
        compas_rhino.xdraw_lines(lines, layer=layer, clear=False, redraw=False)

    if show_wireframe:
        lines = []
        color = mesh.attributes['color.edge']
        for u, v in mesh.wireframe():
            lines.append({
                'start':
                mesh.vertex_coordinates(u),
                'end':
                mesh.vertex_coordinates(v),
                'name':
                '{0}.edge.{1}-{2}'.format(mesh.attributes['name'], repr(u),
                                          repr(v)),
                'color':
                edgecolor.get((u, v), color),
            })
        compas_rhino.xdraw_lines(lines, layer=layer, clear=False, redraw=False)

    if show_vertices:
        points = []
        color = mesh.attributes['color.vertex']
        for key in mesh.vertices():
            points.append({
                'pos':
                mesh.vertex_coordinates(key),
                'name':
                '{0}.vertex.{1}'.format(mesh.attributes['name'], repr(key)),
                'color':
                vertexcolor.get(key, color),
            })
        compas_rhino.xdraw_points(points,
                                  layer=layer,
                                  clear=False,
                                  redraw=False)

    rs.EnableRedraw()
    rs.Redraw()
Example #24
0
def rc_plot_volumes(use_epsilon):
    #get sticky
    default_thickness = sticky["defaultThickness"] if sticky.has_key(
        "defaultThickness") else 5.5

    go = Rhino.Input.Custom.GetObject()
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Brep

    opt_thickness = Rhino.Input.Custom.OptionDouble(default_thickness, 0.2,
                                                    1000)
    opt_sections = Rhino.Input.Custom.OptionToggle(False, "No", "Yes")
    opt_inplace = Rhino.Input.Custom.OptionToggle(False, "No", "Yes")
    opt_heights = Rhino.Input.Custom.OptionToggle(False, "No", "Yes")

    go.SetCommandPrompt("Select breps to extract plan cuts")
    go.AddOptionDouble("Thickness", opt_thickness)

    go.GroupSelect = True
    go.SubObjectSelect = False
    go.AcceptEnterWhenDone(True)
    go.AcceptNothing(True)
    go.EnableClearObjectsOnEntry(False)
    go.EnableUnselectObjectsOnExit(False)
    go.GroupSelect = True
    go.SubObjectSelect = False
    go.DeselectAllBeforePostSelect = False

    res = None
    bHavePreselectedObjects = False

    while True:
        res = go.GetMultiple(1, 0)
        #If new option entered, redraw a possible result
        if res == Rhino.Input.GetResult.Option:
            # print res
            go.EnablePreSelect(False, True)
            continue
        #If not correct
        elif res != Rhino.Input.GetResult.Object:
            return Rhino.Commands.Result.Cancel
        if go.ObjectsWerePreselected:
            bHavePreselectedObjects = True
            go.EnablePreSelect(False, True)
            continue
        break

    rs.EnableRedraw(False)

    global THICKNESS
    THICKNESS = opt_thickness.CurrentValue

    global LCUT_INDICES
    LCUT_INDICES = wla.get_lcut_layers()

    #Get brep representations of objects
    brep_geo_list = []
    for i in xrange(go.ObjectCount):
        b_obj = go.Object(i).Object()
        brep_geo_list.append(b_obj.Geometry)

    #...brep conversion may be necessary
    new_brep_list = []
    for i, geo in enumerate(brep_geo_list):
        if geo.GetType() != Rhino.Geometry.Brep:
            new_brep_list.append(wru.extrusion_to_brep(geo))
        else:
            new_brep_list.append(geo)

    #set base for output.
    xbase = 0
    ybase = 0
    #set the amount to move up from the bottom of the brep for cutting the lower outline.
    #this should be replaced by a projection of the bottom face of the brep.
    epsilon = D_TOL * 2

    select_items = []
    for i, brep in enumerate(new_brep_list):

        #get label prefix and bounding dims for this brep
        bdims = wge.get_bounding_dims(brep)
        baseplane = rs.MovePlane(rs.WorldXYPlane(), [xbase, ybase, 0])
        label_letter = wut.number_to_letter(i)
        label_prefix = label_letter + "-"

        #prepare heights and labels for each section cut
        num_sections = 1
        remaining_thickness = 0
        cuts_at = [epsilon] if use_epsilon else [0]
        brep_label = label_letter
        section_labels = [label_letter]

        num_sections, remaining_thickness, cuts_at = get_section_division(
            bdims.Z, THICKNESS)
        if use_epsilon: cuts_at[0] = epsilon
        brep_label = label_letter + " r: " + str(round(remaining_thickness, 2))
        section_labels = [label_prefix + str(i) for i in xrange(len(cuts_at))]

        #get section information for each cut
        section_planes = get_brep_section_planes(brep, cuts_at)

        #get lowest curve info
        section_curves, section_dims = [[], []]
        for i, plane in enumerate(section_planes):
            curve, dims = [0, 0]
            if (not use_epsilon) and (i == 0):
                curve, dims = get_lowest_curve_info(brep, D_TOL * 2)
            else:
                curve, dims = get_section_curve_info_multi_no_ortho(
                    brep, plane)
            section_curves.append(curve)
            section_dims.append(dims)

        ##DO WORK HERE##
        drawing_planes = get_drawing_planes(section_dims, baseplane, GAP_SIZE)

        #place curves in drawing location
        for sp, dp, sc in zip(section_planes, drawing_planes, section_curves):
            t = Rhino.Geometry.Transform.ChangeBasis(dp, sp)
            for c in sc:
                c.Transform(t)

        #THIS IS STILL A MESS: LABEL ADDING
        #draw curves and add text dots
        top_label_pt = get_brep_label_pt(brep)
        brep_textdot = rs.AddTextDot(brep_label, top_label_pt)
        rs.ObjectLayer(brep_textdot, "XXX_LCUT_00-GUIDES")

        label_pts = []
        for sc, label in zip(section_curves, section_labels):
            temp_area = 0
            for i, c in enumerate(sc):
                crv = wru.add_curve_to_layer(c, LCUT_INDICES[1])
                select_items.append(crv)
                if i == 0:
                    label_pts.append(rs.CurveAreaCentroid(crv)[0])
                    temp_area = rs.CurveArea(crv)
                else:
                    if rs.CurveArea(crv) > temp_area:
                        label_pts[-1] = rs.CurveAreaCentroid(crv)[0]
                        temp_area = rs.CurveArea(crv)

        fab_tags = wfa.add_fab_tags(label_pts, section_labels, TEXTSIZE)
        for tag in fab_tags:
            rs.ObjectLayer(tag, "XXX_LCUT_02-SCORE")
            group_name = rs.AddGroup()
            rs.AddObjectsToGroup(tag, group_name)

        ybase += max([s.Y for s in section_dims]) + GAP_SIZE * 1

        for tag in fab_tags:
            select_items.extend(tag)
        #THIS IS STILL A MESS: LABEL ADDING

    sticky["defaultThickness"] = THICKNESS

    rs.UnselectAllObjects()
    rs.SelectObjects(select_items)
    rs.Redraw()
    rs.EnableRedraw(True)
Example #25
0
def TurbofanNacelle(EngineSection,
                    Chord,
                    CentreLocation=[0, 0, 0],
                    ScarfAngle=3,
                    HighlightRadius=1.45,
                    MeanNacelleLength=5.67):
    # The defaults yield a nacelle similar to that of an RR Trent 1000 / GEnx

    HighlightDepth = 0.12 * MeanNacelleLength
    SectionNo = 100

    # Draw the nacelle with the centre of the intake highlight circle in 0,0,0
    rs.EnableRedraw(False)
    Highlight = rs.AddCircle3Pt((0, 0, HighlightRadius),
                                (0, -HighlightRadius, 0),
                                (0, 0, -HighlightRadius))
    HighlightCutterCircle = rs.AddCircle3Pt((0, 0, HighlightRadius * 1.5),
                                            (0, -HighlightRadius * 1.5, 0),
                                            (0, 0, -HighlightRadius * 1.5))

    # Fan disk for CFD boundary conditions
    FanCircle = rs.CopyObject(Highlight, (MeanNacelleLength * 0.25, 0, 0))
    FanDisk = rs.AddPlanarSrf(FanCircle)
    # Aft outflow for CFD boundary conditions
    BypassCircle = rs.CopyObject(Highlight, (MeanNacelleLength * 0.85, 0, 0))
    BypassDisk = rs.AddPlanarSrf(BypassCircle)
    rs.DeleteObjects([FanCircle, BypassCircle])

    # Outflow cone
    TailConeBasePoint = [MeanNacelleLength * 0.84, 0, 0]
    TailConeApex = [MeanNacelleLength * 1.35, 0, 0]
    TailConeRadius = HighlightRadius * 0.782
    TailCone = rs.AddCone(TailConeBasePoint, TailConeApex, TailConeRadius)
    # Spinner cone
    SpinnerConeBasePoint = [MeanNacelleLength * 0.26, 0, 0]
    SpinnerConeApex = [MeanNacelleLength * 0.08, 0, 0]
    SpinnerConeRadius = MeanNacelleLength * 0.09
    Spinner = rs.AddCone(SpinnerConeBasePoint, SpinnerConeApex,
                         SpinnerConeRadius)

    # Tilt the intake
    RotVec = rs.VectorCreate((0, 0, 0), (0, 1, 0))
    Highlight = rs.RotateObject(Highlight, (0, 0, 0), ScarfAngle, axis=RotVec)

    # Set up the disk for separating the intake lip later
    HighlightCutterCircle = rs.RotateObject(HighlightCutterCircle, (0, 0, 0),
                                            ScarfAngle,
                                            axis=RotVec)
    HighlightCutterDisk = rs.AddPlanarSrf(HighlightCutterCircle)
    rs.DeleteObject(HighlightCutterCircle)
    rs.MoveObject(HighlightCutterDisk, (HighlightDepth, 0, 0))

    # Build the actual airfoil sections to define the nacelle
    HighlightPointVector = rs.DivideCurve(Highlight, SectionNo)

    Sections = []
    TailPoints = []
    Rotation = 0
    Twist = 0
    AirfoilSeligName = 'goe613'
    SmoothingPasses = 1

    for HighlightPoint in HighlightPointVector:
        ChordLength = MeanNacelleLength - HighlightPoint.X
        Af = primitives.Airfoil(HighlightPoint, ChordLength, Rotation, Twist,
                                airconics_setup.SeligPath)
        AfCurve, Chrd = primitives.Airfoil.AddAirfoilFromSeligFile(
            Af, AirfoilSeligName, SmoothingPasses)
        rs.DeleteObject(Chrd)
        P = rs.CurveEndPoint(AfCurve)
        list.append(TailPoints, P)
        AfCurve = act.AddTEtoOpenAirfoil(AfCurve)
        list.append(Sections, AfCurve)
        Rotation = Rotation + 360.0 / SectionNo

    list.append(TailPoints, TailPoints[0])

    # Build the actual nacelle OML surface
    EndCircle = rs.AddInterpCurve(TailPoints)
    Nacelle = rs.AddSweep2([Highlight, EndCircle], Sections, closed=True)
    # Separate the lip
    Cowling, HighlightSection = rs.SplitBrep(Nacelle, HighlightCutterDisk,
                                             True)

    # Now build the pylon between the engine and the specified chord on the wing
    CP1 = [
        MeanNacelleLength * 0.26 + CentreLocation[0], CentreLocation[1],
        CentreLocation[2] + HighlightRadius * 0.1
    ]
    CP2 = [
        MeanNacelleLength * 0.4 + CentreLocation[0], CentreLocation[1],
        HighlightRadius * 1.45 + CentreLocation[2]
    ]
    CP3 = rs.CurveEndPoint(Chord)
    rs.ReverseCurve(Chord)
    CP4 = rs.CurveEndPoint(Chord)

    # Move the engine into its actual place on the wing
    rs.MoveObjects(
        [HighlightSection, Cowling, FanDisk, BypassDisk, TailCone, Spinner],
        CentreLocation)

    # Pylon wireframe
    PylonTop = rs.AddInterpCurve([CP1, CP2, CP3, CP4])
    PylonAf = primitives.Airfoil(CP1, MeanNacelleLength * 1.35, 90, 0,
                                 airconics_setup.SeligPath)
    PylonAfCurve, PylonChord = primitives.Airfoil.AddNACA4(
        PylonAf, 0, 0, 12, 3)
    LowerTE = rs.CurveEndPoint(PylonChord)
    PylonTE = rs.AddLine(LowerTE, CP4)

    # Create the actual pylon surface
    PylonLeft = rs.AddNetworkSrf([PylonTop, PylonAfCurve, PylonTE])
    rs.MoveObject(PylonLeft, (0, -CentreLocation[1], 0))
    PylonRight = act.MirrorObjectXZ(PylonLeft)
    rs.MoveObject(PylonLeft, (0, CentreLocation[1], 0))
    rs.MoveObject(PylonRight, (0, CentreLocation[1], 0))
    PylonAfCurve = act.AddTEtoOpenAirfoil(PylonAfCurve)
    PylonAfSrf = rs.AddPlanarSrf(PylonAfCurve)

    # Assigning basic surface properties
    act.AssignMaterial(Cowling, "ShinyBABlueMetal")
    act.AssignMaterial(HighlightSection, "UnpaintedMetal")
    act.AssignMaterial(TailCone, "UnpaintedMetal")
    act.AssignMaterial(FanDisk, "FanDisk")
    act.AssignMaterial(Spinner, "ShinyBlack")
    act.AssignMaterial(BypassDisk, "FanDisk")
    act.AssignMaterial(PylonLeft, "White_composite_external")
    act.AssignMaterial(PylonRight, "White_composite_external")

    # Clean-up
    rs.DeleteObject(HighlightCutterDisk)
    rs.DeleteObjects(Sections)
    rs.DeleteObject(EndCircle)
    rs.DeleteObject(Highlight)
    rs.DeleteObjects([PylonTop, PylonAfCurve, PylonChord, PylonTE])

    rs.Redraw()

    TFEngine = [
        Cowling, HighlightSection, TailCone, FanDisk, Spinner, BypassDisk
    ]
    TFPylon = [PylonLeft, PylonRight, PylonAfSrf]

    return TFEngine, TFPylon
#Python Workshop Lesson:06
#http://designalyze.com/int2pythonscripting06_nestedloops-functions
#Nested For Loops
#color points
import rhinoscriptsyntax as rs


def createColoredPoint(x, y, z, r, g, b):
    currentColor = [r, g, b]
    pt = rs.AddPoint(x, y, z)
    rs.ObjectColor(pt, currentColor)


rs.EnableRedraw(False)
step = 10

for x in range(0, 256, step):
    for y in range(0, 256, step):
        for z in range(0, 256, step):
            createColoredPoint(x, y, z, x, y, z)
rs.Redraw()
Example #27
0
def rc_unroll_ortho():

    go = Rhino.Input.Custom.GetObject()
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Brep

    default_thickness = sticky["thickness"] if sticky.has_key(
        "thickness") else 5.5
    default_lid = sticky["lid"] if sticky.has_key("lid") else False

    opt_thickness = Rhino.Input.Custom.OptionDouble(default_thickness, 0.2,
                                                    1000)
    opt_lid = Rhino.Input.Custom.OptionToggle(default_lid, "No", "Yes")

    go.SetCommandPrompt(
        "Select breps to unroll. Breps must be orthogonal (faces at 90 degree angles)"
    )
    go.AddOptionDouble("Thickness", opt_thickness)
    go.AddOptionToggle("Lids", opt_lid)

    go.GroupSelect = True
    go.SubObjectSelect = False
    go.AcceptEnterWhenDone(True)
    go.AcceptNothing(True)
    go.EnableClearObjectsOnEntry(False)
    go.EnableUnselectObjectsOnExit(False)
    go.GroupSelect = True
    go.SubObjectSelect = False
    go.DeselectAllBeforePostSelect = False

    res = None
    bHavePreselectedObjects = False

    while True:
        res = go.GetMultiple(1, 0)

        #If new option entered, redraw a possible result
        if res == Rhino.Input.GetResult.Option:
            #print res
            go.EnablePreSelect(False, True)
            continue

        #If not correct
        elif res != Rhino.Input.GetResult.Object:
            return Rhino.Commands.Result.Cancel

        if go.ObjectsWerePreselected:
            bHavePreselectedObjects = True
            go.EnablePreSelect(False, True)
            continue

        break

    rs.EnableRedraw(False)

    LID = opt_lid.CurrentValue
    THICKNESS = opt_thickness.CurrentValue
    global LCUT_INDICES
    LCUT_INDICES = wla.get_lcut_layers()

    #Get geometry and object lists
    brep_obj_list = []
    brep_geo_list = []
    brep_ids_list = []
    for i in xrange(go.ObjectCount):
        b_obj = go.Object(i).Object()
        brep_obj_list.append(b_obj)
        #For Debug and reference...
        #brep_geo_list.append(b_obj.Geometry)
        #brep_ids_list.append(b_obj.Id)

    #get information for each piece to be output.
    #future implementation should use bounding dims and curves rather than dimension-based system.
    unrolled_brep_info = []
    lid_info = []

    SELECT_GUIDS = []
    for i, obj in enumerate(brep_obj_list):
        #geometry prep: convert extrusions to breps
        if str(obj.ObjectType) != "Brep":
            new_brep = wru.extrusion_to_brep(obj.Geometry)
        else:
            new_brep = obj.Geometry

        #pull the brep sides info for this solid
        this_brep_side_info = get_brep_sides_info(new_brep, THICKNESS)
        unrolled_brep_info.append(this_brep_side_info)
        num_sides = len(this_brep_side_info.dims)

        #pull the lid info for this solid
        if LID == True:
            this_brep_lid_info = get_brep_lid_info(new_brep, num_sides,
                                                   THICKNESS)
            lid_info.append(this_brep_lid_info)

    #get dims needed to place this solid's outline curves
    brep_output_bounding_heights = []
    for i, brep_side_info in enumerate(unrolled_brep_info):
        if LID == True:
            brep_output_bounding_heights.append(
                max(brep_side_info.boundingDims.y, lid_info[i].dims.y)
            )  #lid info needs to become a named tuple as well.
        else:
            brep_output_bounding_heights.append(brep_side_info.boundingDims.y)

    ybase = 0
    #each solid
    for i, brep_side_info in enumerate(unrolled_brep_info):
        top_label_text = wut.number_to_letter(i)
        prefix = top_label_text + "-"
        xbase = 0
        #each piece
        for j, piecedims in enumerate(brep_side_info.dims):
            face_label = prefix + str(brep_side_info.labelNums[j])
            rect = rs.AddRectangle([xbase, ybase, 0], piecedims.x, piecedims.y)
            dot = rs.AddTextDot(face_label, rs.CurveAreaCentroid(rect)[0])

            rs.ObjectLayer(dot, "XXX_LCUT_00-GUIDES")
            rs.ObjectLayer(rect, "XXX_LCUT_01-CUT")
            SELECT_GUIDS.extend([rect, dot])
            xbase += piecedims[0] + GAP_SIZE

        #add the lids
        if LID == True:

            #transform the lid curve to the basepoint
            lid_curve = lid_info[i].outline
            p1 = rs.WorldXYPlane()
            p2 = rs.PlaneFromNormal([xbase, ybase, 0], [0, 0, 1], [1, 0, 0])
            orient = Rhino.Geometry.Transform.ChangeBasis(
                rs.coerceplane(p2), rs.coerceplane(p1))
            lid_curve.Transform(orient)

            #add the curve to the document
            crv_1 = wru.add_curve_to_layer(lid_curve, LCUT_INDICES[1])
            crv_2 = rs.CopyObject(
                crv_1, [lid_info[i].dims.x + GAP_SIZE, 0, 0
                        ])  #change this to use a transform; it's nasty.

            #add text dot
            face_label_1 = prefix + str(len(brep_side_info.dims))
            face_label_2 = prefix + str(len(brep_side_info.dims) + 1)
            dot_1 = rs.AddTextDot(face_label_1, rs.CurveAreaCentroid(crv_1)[0])
            dot_2 = rs.AddTextDot(face_label_2, rs.CurveAreaCentroid(crv_2)[0])
            rs.ObjectLayer([dot_1, dot_2], "XXX_LCUT_00-GUIDES")

            SELECT_GUIDS.extend([crv_1, crv_2, dot_1, dot_2])

        top_label = rs.AddTextDot(top_label_text, brep_side_info.topLabelPt)
        rs.ObjectLayer(top_label, "XXX_LCUT_00-GUIDES")
        ybase += brep_output_bounding_heights[i] + GAP_SIZE * 4

    sticky["thickness"] = THICKNESS
    sticky["lid"] = LID

    rs.UnselectAllObjects()
    rs.SelectObjects(SELECT_GUIDS)
    rs.Redraw()
    rs.EnableRedraw(True)
Example #28
0
def redraw():
    rs.EnableRedraw(True)
    rs.Redraw()
Example #29
0
 def redraw(self, timeout=None):
     """Redraw the Rhino view."""
     if timeout:
         time.sleep(timeout)
     rs.EnableRedraw(True)
     rs.Redraw()
Example #30
0
def rc_plot_volumes(use_epsilon):

    go = Rhino.Input.Custom.GetObject()
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Brep

    default_inplaceBool = sticky["inplaceBool"] if sticky.has_key(
        "inplaceBool") else False
    default_heightsBool = sticky["heightsBool"] if sticky.has_key(
        "heightsBool") else False

    opt_inplace = Rhino.Input.Custom.OptionToggle(default_inplaceBool, "No",
                                                  "Yes")
    opt_heights = Rhino.Input.Custom.OptionToggle(default_heightsBool, "No",
                                                  "Yes")

    go.SetCommandPrompt("Select breps to extract plan cuts")
    go.AddOptionToggle("InPlace", opt_inplace)
    go.AddOptionToggle("PrintPieceHeights", opt_heights)

    go.GroupSelect = True
    go.SubObjectSelect = False
    go.AcceptEnterWhenDone(True)
    go.AcceptNothing(True)
    go.EnableClearObjectsOnEntry(False)
    go.EnableUnselectObjectsOnExit(False)
    go.GroupSelect = True
    go.SubObjectSelect = False
    go.DeselectAllBeforePostSelect = False

    res = None
    bHavePreselectedObjects = False

    while True:
        res = go.GetMultiple(1, 0)
        #If new option entered, redraw a possible result
        if res == Rhino.Input.GetResult.Option:
            # print res
            go.EnablePreSelect(False, True)
            continue
        #If not correct
        elif res != Rhino.Input.GetResult.Object:
            return Rhino.Commands.Result.Cancel
        if go.ObjectsWerePreselected:
            bHavePreselectedObjects = True
            go.EnablePreSelect(False, True)
            continue
        break

    rs.EnableRedraw(False)

    DIRPT1 = rs.coerce3dpoint([0, 0, 0])
    DIRPT2 = rs.coerce3dpoint([1, 0.001, 0])
    global BOOL_HEIGHTS
    global LCUT_INDICES
    global SORTDIR
    BOOL_HEIGHTS = opt_heights.CurrentValue
    LCUT_INDICES = wla.get_lcut_layers()
    SORTDIR = DIRPT2 - DIRPT1

    #Get boolean for "inplace"
    INPLACE = opt_inplace.CurrentValue

    #Get brep representations of objects
    brep_geo_list = []
    for i in xrange(go.ObjectCount):
        b_obj = go.Object(i).Object()
        brep_geo_list.append(b_obj.Geometry)

    #...brep conversion may be necessary
    new_brep_list = []
    for i, geo in enumerate(brep_geo_list):
        if geo.GetType() != Rhino.Geometry.Brep:
            new_brep_list.append(wru.extrusion_to_brep(geo))
        else:
            new_brep_list.append(geo)

    #set base for output.
    xbase = 0
    ybase = 0
    #set the amount to move up from the bottom of the brep for cutting the lower outline.
    #this should be replaced by a projection of the bottom face of the brep.
    epsilon = D_TOL * 2

    select_items = []

    centroids = [
        c.GetBoundingBox(rs.WorldXYPlane()).Center for c in new_brep_list
    ]
    brep_collection = zip(centroids, new_brep_list)
    brep_collection = sorted(brep_collection, sortcompare)
    _, new_brep_list = zip(*brep_collection)

    for i, brep in enumerate(new_brep_list):
        #get lowest curve info

        #get label prefix and bounding dims for this brep
        bdims = wge.get_bounding_dims(brep)
        baseplane = rs.MovePlane(rs.WorldXYPlane(), [xbase, ybase, 0])
        label_letter = wut.number_to_letter(i)

        #prepare heights and labels for each section cut
        num_sections = 1
        remaining_thickness = 0
        cuts_at = [epsilon] if use_epsilon else [0]
        brep_label = label_letter
        section_labels = [label_letter]

        if BOOL_HEIGHTS == True:
            section_labels = [
                label + "\n" + str(round(bdims.Z, 1))
                for label in section_labels
            ]

        #get section information for each cut
        section_planes = get_brep_section_planes(brep, cuts_at)

        section_curves, section_dims = [[], []]
        for i, plane in enumerate(section_planes):
            curve, dims = [0, 0]
            if (not use_epsilon) and (i == 0):
                curve, dims = get_lowest_curve_info(brep, D_TOL * 2)
            else:
                curve, dims = get_section_curve_info_multi_no_ortho(
                    brep, plane)
            section_curves.append(curve)
            section_dims.append(dims)

        ##DO WORK HERE##
        drawing_planes = get_drawing_planes(section_dims, baseplane, GAP_SIZE)

        #place curves in drawing location
        for sp, dp, sc in zip(section_planes, drawing_planes, section_curves):
            if INPLACE == True:
                t = Rhino.Geometry.Transform.Translation(0, 0, 0)
            else:
                t = Rhino.Geometry.Transform.ChangeBasis(dp, sp)
            for c in sc:
                c.Transform(t)

        #THIS IS STILL A MESS: LABEL ADDING
        #draw curves and add text dots
        top_label_pt = get_brep_label_pt(brep)
        brep_textdot = rs.AddTextDot(brep_label, top_label_pt)
        rs.ObjectLayer(brep_textdot, "XXX_LCUT_00-GUIDES")

        label_pts = []
        for sc, label in zip(section_curves, section_labels):
            for i, c in enumerate(sc):
                crv = wru.add_curve_to_layer(c, LCUT_INDICES[1])
                select_items.append(crv)
                if i == 0:
                    label_pts.append(rs.CurveAreaCentroid(crv)[0])

        fab_tags = wfa.add_fab_tags(label_pts, section_labels, TEXTSIZE)
        for tag in fab_tags:
            rs.ObjectLayer(tag, "XXX_LCUT_02-SCORE")
            group_name = rs.AddGroup()
            rs.AddObjectsToGroup(tag, group_name)
        ybase += max([s.Y for s in section_dims]) + GAP_SIZE * 1

        for tag in fab_tags:
            select_items.extend(tag)

    sticky["inplaceBool"] = INPLACE
    sticky["heightsBool"] = BOOL_HEIGHTS

    rs.UnselectAllObjects()
    rs.SelectObjects(select_items)
    rs.Redraw()
    rs.EnableRedraw(True)