def AutolabelPoints(): text_height = 10 font_name = 'Arial' if (sc.sticky.has_key("NumPrefix")): prefix = sc.sticky["NumPrefix"] else: prefix = "" if (sc.sticky.has_key("NumSuffix")): suffix = sc.sticky["NumSuffix"] else: suffix = "" ids = rs.GetObjects('Select points to label', 1) if not ids: return start = rs.GetInteger("Start index", 0) if not start: start = 0 prefix = rs.StringBox('Numbering prefix (Cancel for none)', default_value=prefix, title="Number prefix") if not prefix: prefix = '' sc.sticky["NumPrefix"] = prefix suffix = rs.StringBox('Numbering suffix (Cancel for none)', default_value=suffix, title="Number suffix") if not suffix: suffix = '' sc.sticky["NumSuffix"] = suffix count = start + len(ids) padding = len(str(count)) pad_str = '{}'.format(':0{}d'.format(padding)) pad_str = '{' + pad_str + '}' dot_ids = [] for i, id in enumerate(ids): num_str = pad_str.format(start + i) text_str = '{}{}{}'.format(prefix, num_str, suffix) pt = id dot_id = rs.AddTextDot(text_str, pt) #rs.TextDotFont(dot_id, font_name) #rs.TextDotHeight(dot_id, text_height) dot_ids.append(dot_id) rs.AddObjectsToGroup(dot_ids, rs.AddGroup())
def MakeBlockUniqueButton(): try: block = rs.GetObject("Select block to make unique", rs.filter.instance, preselect=True) if block is None: return defaultName = utils.UpdateString(rs.BlockInstanceName(block)) looping = True while looping: newName = rs.StringBox("Enter new block name", default_value=defaultName, title='MakeUnique') if newName is None: return if rs.IsBlock(newName): print "Block name already exists" elif len(newName) == 0: print "Must specify a name" else: looping = False if newName is None: return rs.EnableRedraw(False) newBlock = MakeBlockUnique(block, newName) rs.EnableRedraw(True) rs.SelectObject(newBlock) return True except: return False
def RenameBlockButton(): try: block = rs.GetObject("Select block to rename", filter=4096, preselect=True) #Default Name try: number = int(rs.BlockInstanceName(block).split('_')[-1]) number += 1 if len(str(number)) < 2: numString = '0' + str(number) else: numString = str(number) except: numString = '01A' defaultName = GetDatePrefix() + "_OPTION_" + numString looping = True while looping: newName = rs.StringBox("Enter new block name", default_value=defaultName, title='Rename Block') if newName is None: return if rs.IsBlock(newName): print "Block name already exists" elif len(newName) == 0: print "Must specify a name" pass else: looping = False return rs.RenameBlock(rs.BlockInstanceName(block), newName) except: return None
def offsetext(): def RepresentsInt(s): try: int(s) return True except ValueError: return False viste = rs.ViewNames() for viewport in viste: rs.ViewDisplayMode(viewport,"Shaded") diametro = rs.StringBox("dimensione della punta","10","scontornatura") if RepresentsInt(diametro): diametro = int(diametro) else: diametro = 10 brep = rs.GetObjects("dammi un solido",16) brepexp = rs.ExplodePolysurfaces(brep) get_val = rs.GetEdgeCurves("dammi le curve") surf_edge = [] for i in get_val: surf_edge.append(i[0]) surf_edge = rs.coerceguidlist(surf_edge) if len(surf_edge)>1: surf_edge = rs.JoinCurves(surf_edge,True) surface = rs.GetObjects("conferma la selezione",8,False,True,1,1) print surf_edge uv= [] temp_edge = rs.ExplodeCurves(surf_edge,False) new_surface = rs.CopyObject(surface,(0,0,0)) list_evpt =[] for i in temp_edge: evpt =rs.CurveMidPoint(i) print evpt list_evpt.append(evpt) for i in list_evpt: bord= rs.SurfaceClosestPoint(new_surface,i) uv.append(bord) for i in uv: rs.ExtendSurface(new_surface,i,diametro*10) edge = rs.OffsetCurveOnSurface(surf_edge,new_surface,-diametro) print edge if rs.CurveLength(edge)<rs.CurveLength(surf_edge): rs.DeleteObject(edge) edge = rs.OffsetCurveOnSurface(surf_edge,new_surface,diametro) surf_edge = rs.ExplodeCurves(surf_edge,True) print edge rs.ObjectColor(edge,(0,0,255)) for i in brepexp: rs.DeleteObject(i) for i in temp_edge: rs.DeleteObject(i) for i in surf_edge: rs.DeleteObject(i) rs.DeleteObjects([new_surface,surface])
def PostViewToTumblr(email, password): size = rs.ViewSize() path = '\\mypic.png' rs.Command('-_ViewCaptureToFile ' + path + ' Width=' + str(size[0]) + ' Height=' + str(size[1]) + ' DrawGrid=Yes DrawWorldAxes=Yes DrawCPlaneAxes=Yes _Enter', 0) print 'Post ' + rs.CurrentView() + ' view to tumblr' comment = rs.StringBox (title='Add a caption to your post') url = 'http://www.tumblr.com/api/write' img=open(path, 'rb').read() values = { 'type': 'photo', 'email': email, 'password': password, 'data': img, 'send-to-twitter': 'auto', 'caption' : comment} data = urlencode(values,'utf-8') req = Request(url, data) try: response = urlopen(req) page = response.read() print 'Upload successful' except HTTPError, e: print 'Upload failed ' + e.code
def new_settings_button(self,sender,e,edit=False): while True: name = rs.StringBox (message=TXT["name"], default_value=None, title=TXT["nueva"]) if name != "" and name not in self.machining_settings: break if name: machining_settings = {name:{}} for compensation in [key for key in INPUT_VALUES]: machining_settings[name][compensation] = {} if self.user_data["selected_preset"]: list_settings = rs.PropertyListBox([i for i in INPUT_VALUES[compensation]],[str(self.machining_settings[self.user_data["selected_preset"]][compensation][i]) for i in VARIABLE_NAMES[compensation]],compensation, "Configuracion de corte") else: list_settings = rs.PropertyListBox([i for i in INPUT_VALUES[compensation]],[0 for i in INPUT_VALUES[compensation]],compensation, "Configuracion de corte") if list_settings: for i in range(0,len(list_settings)): machining_settings[name][compensation][VARIABLE_NAMES[compensation][i]] = self.validate_data(list_settings[i], VARIABLE_NAMES[compensation][i]) else: return persistant = rs.MessageBox(TXT["save_pers"], 4 | 256 | 64,TXT["database"]) if persistant == 6: machining_settings[name]["persistant"] = False else: machining_settings[name]["persistant"] = True self.user_data["selected_preset"] = name w = self.form.panel.Controls.Find("preset", True)[0] w.Text = name self.machining_settings.update(machining_settings)
def meshfunction_xy(): zfunc, domain, resolution = loadfunctiondata() zfunc = rs.StringBox( zfunc, "Specify a function f(x,y[,D,A])", "Mesh function") if not zfunc: return while True: prompt = "Function domain x{%f,%f} y{%f,%f} @%d" % (domain[0], domain[1], domain[2], domain[3], resolution) result = rs.GetString(prompt, "Insert", ("xMin","xMax","yMin","yMax","Resolution","Insert")) if not result: return result = result.upper() if result=="XMIN": f = rs.GetReal("X-Domain start", domain[0]) if f is not None: domain[0]=f elif result=="XMAX": f = rs.GetReal("X-Domain end", domain[1]) if f is not None: domain[1]=f elif result=="YMIN": f = rs.GetReal("Y-Domain start", domain[2]) if f is not None: domain[2]=f elif result=="YMAX": f = rs.GetReal("Y-Domain end", domain[3]) if f is not None: domain[3]=f elif result=="RESOLUTION": f = rs.GetInteger("Resolution of the graph", resolution) if f is not None: resolution=f elif result=="INSERT": break verts = createmeshvertices(zfunc, domain, resolution) faces = createmeshfaces(resolution) rs.AddMesh(verts, faces)
def label_consecutive_lines(): """Prompts for label text and a point triple (or a line segment + 3rd point) to identify line segments. Draws scalene lpoint triples, which have no reflections. """ offset = 0.1 def get_points(): """Prompts for a point triple. Returns a list of the points: [<iter>, ...] """ points = rs.GetPoints(draw_lines=False, in_plane=False, message1='Select first tail', message2='Select heads', max_points=None, base_point=None) return points def draw_lpoint_triple(text, tail, head): """Receives label text and a list of point triples: str [<iter>, ...] Draws text dots with <text>-a, -b, -c """ line_vector = rs.PointSubtract(head, tail) offset_vector = line_vector * offset offset_tail = rs.VectorAdd(tail, offset_vector) offset_head = rs.VectorSubtract(head, offset_vector) axis = [0, 0, 1] angle = 90 rotated_offset_vector = rs.VectorRotate(offset_vector, angle, axis) offset_side = rs.VectorAdd(offset_tail, rotated_offset_vector) rs.AddTextDot(('%s-a' % text), offset_tail) rs.AddTextDot(('%s-b' % text), offset_head) rs.AddTextDot(('%s-c' % text), offset_side) def side_is_same_as_rule(point): """Receives a point (i.e., a list): [num, num, num] Returns whether the point is on the same side as the side label in the rule """ return False points = get_points() text = rs.StringBox('Enter label text') for i in range(len(points) - 1): # for point in points: tail = points[i] head = points[i + 1] draw_lpoint_triple(text, tail, head)
def CreateDesignOption(): objs = rs.GetObjects("Select objects to create design option with", preselect=True) if objs is None: return None try: date = utils.GetDatePrefix() origName = date + '_OPTION_00' defaultName = origName for i in range(100): defaultName = utils.UpdateString(defaultName) if origName == defaultName: break if rs.IsBlock(defaultName) == False: break looping = True while looping: designOptionName = rs.StringBox("Design Option Name", defaultName, "Create Design Option") if designOptionName is None: return None if rs.IsBlock(designOptionName): print "Block name already exists" elif len(designOptionName) == 0: print "Must specify a name" else: looping = False block = rs.AddBlock(objs, (0, 0, 0), designOptionName, True) blockInstance = rs.InsertBlock(designOptionName, (0, 0, 0)) #Add user text rs.SetUserText(blockInstance, 'Design Option History', designOptionName) #Ensure 3_DESIGN OPTIONS already exists layers.AddLayerByNumber(3000, False) #Create new layer parentLayer = layers.GetLayerNameByNumber(3000) designOptionLayer = rs.AddLayer(parentLayer + "::" + designOptionName, color=utils.GetRandomColor()) rs.ObjectLayer(blockInstance, designOptionLayer) utils.SaveFunctionData('Blocks-Create Design Option', [__version__, designOptionName]) return True except: print "Failed to create design option" utils.SaveFunctionData('Blocks-Create Design Option', [__version__, '', 'Failed']) return None
def main(): path = rs.BrowseForFolder() if path is None: return newFolderName = rs.StringBox(default_value='180710_TEST_01') newFolder = os.path.join(path,newFolderName) if not os.path.exists(newFolder): os.mkdir(newFolder) objs = rs.VisibleObjects() #ExportEachLayerAsSat(objs, newFolder, newFolderName) #ExportEachLayerAs3DS(objs, newFolder, newFolderName) #ExportEachLayerAsDAE(objs, newFolder, newFolderName) #ExportEachLayerAsIGES(objs, newFolder, newFolderName) #ExportEachLayerAsOBJ(objs, newFolder, newFolderName) ExportAsSKP(objs, newFolder, newFolderName)
def ReplicateBlock(blockObj): #Copy block copiedBlock = rs.CopyObject(blockObj) #Get new block name origName = rs.BlockInstanceName(blockObj) defaultName = origName for i in range(100): defaultName = utils.UpdateString(defaultName) if origName == defaultName: break if rs.IsBlock(defaultName) == False: break looping = True while looping: newBlockName = rs.StringBox("Enter new block name", default_value=defaultName, title='Iterate Design Option') if newBlockName is None: rs.DeleteObject(copiedBlock) return if rs.IsBlock(newBlockName): print "Block name already exists" elif len(newBlockName) == 0: print "Must specify a name" else: looping = False if newBlockName is None: rs.DeleteObject(copiedBlock) return #Get previous base point xform = rs.BlockInstanceXform(copiedBlock) basePoint = rs.BlockInstanceInsertPoint(copiedBlock) #Explode block objsInside = rs.ExplodeBlockInstance(copiedBlock) rs.AddBlock(objsInside, basePoint, newBlockName, True) #Create new block instance = rs.InsertBlock2(newBlockName, xform) return instance
import os import rhinoscriptsyntax as rs import Rhino #FolderLocation mydir = rs.StringBox("Insert folder path") def getRhinoFile(dir): pathList = [] for file in os.listdir(dir): if file.endswith(".3dm"): path = dir + "\\" + file pathList.append(path) print (path) return (pathList) test = getRhinoFile(mydir) def insertFile(fList): for item in fList: origin = 0,0,0 origin = str(origin) item = '"' + item + '"' #Defining Rhino command iCommand = "-insert F L L {} B 0 1 0 -Enter _Hide".format(item) rs.Command("%s" %iCommand) insertFile(test) #Show result after imported rs.Command("_Show")
import scriptcontext as sc import Rhino as rh def RepresentsInt(s): try: int(s) return True except ValueError: return False viste = rs.ViewNames() for viewport in viste: rs.ViewDisplayMode(viewport, "Shaded") diametro = rs.StringBox("dimensione della punta", "10", "scontornatura") if RepresentsInt(diametro): diametro = int(diametro) else: diametro = 10 brep = rs.GetObjects("dammi un solido", 16) brepexp = rs.ExplodePolysurfaces(brep) get_val = rs.GetEdgeCurves("dammi le curve") surf_edge = [] for i in get_val: surf_edge.append(i[0]) surface = rs.SelectObject(i[1]) surf_edge = rs.coerceguidlist(surf_edge) surf_edge = rs.JoinCurves(surf_edge, True) surf_edge = surf_edge[0]
import rhinoscriptsyntax as rs import sys sys.path.append(r'X:\05_RHINO STANDARDS\05 SCRIPTS\PYTHON\PCPA\PCPA\libs') from geopy.geocoders import Nominatim geolocator = Nominatim() address = rs.StringBox("Enter Address") #address = r'310 12th st, ny' location = geolocator.geocode(address) print(location.address) print((location.latitude, location.longitude)) #print location.address['city'] #print(location.raw)
def OnSaveAsPressed(self, sender, e): print "Save As" path = rs.StringBox('Version Name', GetDatePrefix() + "_Version_01", 'Save new version') self.SaveToYaml(path)
# rename layer names def renameLayers(_originalLayersList, _newLayersList): if _originalLayersList and _newLayersList: for i in range(len(_originalLayersList)): new_name = rs.RenameLayer(_originalLayersList[i], _newLayersList[i]) print "Done" return else: print "Something went wrong with re.sub() function. Function terminated" return # function inputs find = rs.StringBox("Which part of your Layer's name do you want to replace?", None, "Find") replace = rs.StringBox("Replace with?", None, "Replace") if find and replace: # comment out line 126 if you want to remove the Message box layersLevelInfo = rs.MessageBox( "At what level do you want to replace your layer names?\n \n- Choose some of the following numbers:\nparent layers level: 0\nsub-layers level: 1\nsub-sub-layers level: 2\n \n- Combinations (always from lower level to higher):\nreplace layer names at all levels: 210\nreplace only at parent level: 0\nreplace only at sub-sub and parent: 20\nreplace at sub-sub and sub: 21\netc.", 64) layersLevelInput = int( rs.StringBox("Enter the level code (210 will cover all levels):", "210", "Layers level code")) if layersLevelInput: originalLayersList = layersList(layersLevelInput) find2 = cleaningUp(find, replace)[0] replace2 = cleaningUp(find, replace)[1] newLayersList = [] for layer2 in originalLayersList: