def __init__(self,generalSettings,machiningSettings,userData): # Make a new form (dialog) self.rhino_objects = None self.sorted_objects = None self.time = 0 self.code_thread = False self.login_thread = False self.terminal_lines = ["","",""] self.spkmodel_objects = None self.general_settings = {"sec_plane":6,"feed_rapid":3000,"cut_diam":6} if not generalSettings else generalSettings self.machining_settings = {} if not machiningSettings else machiningSettings self.user_data = {"technical_name":False,"save_file":False,"spkcam_session_token":False,"material_info":False,"sort_closest":False,"user_data":False,"sorting":True,"name_url":False,"autocluster":True,"index_pause":False,"user_mail":False,"save_path":rs.DocumentPath().replace(".3dm","_gcode.txt") if rs.DocumentPath() else False,"selected_preset":False} if not userData else userData if not self.user_data["technical_name"]: self.user_data["technical_name"]= rs.DocumentName().replace(".3dm","_gcode") if not self.user_data["name_url"]:self.user_data["name_url"] = rs.DocumentName().replace(".3dm","") try: token = um.get_login_token() self.user_data["spkcam_session_token"] = token self.user_data["user_mail"] = um.get_user() except: self.user_data["spkcam_session_token"] = False self.user_data["user_mail"] = False self.form = Meier_UI_Utility.UIForm("SPKCAM:.") self.addControls() self.form.layoutControls() self.print_initial_state()
def AddAreaTag(): objs = rs.GetObjects("Select curves, hatches, or surfaces to add area tag", 65548, preselect = True) if objs is None: return decPlaces = rs.GetInteger("Number of decimal places", 0, maximum = 8) if decPlaces is None: return #Load Anno style if it doesnt exist already if sc.doc.DimStyles.FindName('PCPA_12') is None: standards.LoadStyles() rs.EnableRedraw(False) total = 0 for obj in objs: try: currentArea,result, tag = AreaTag(obj, decPlaces) utils.SaveFunctionData('Drawing-Add Area Tag', [rs.DocumentName(), rs.ObjectLayer(obj), rs.ObjectDescription(obj), rs.CurrentDimStyle(), currentArea, decPlaces, result]) total += currentArea rs.SetUserText(tag, 'hostGUID', str(obj)) except: pass print 'Cumulative Area = ' + str(total) rs.EnableRedraw(True)
def __init__(self, objects_to_render): self.objects_to_render = objects_to_render dirname = os.path.dirname self.script_path = dirname(os.path.realpath(__file__)) + "\\" filepath = rs.DocumentPath() if not filepath: self.filepath = self.script_path else: self.filepath = str(os.path.splitext(str(filepath))[0]) doc_name = rs.DocumentName() if not doc_name: doc_name = "Render_" else: doc_name = os.path.splitext(doc_name)[0] self.render_name = doc_name + "_" + date.today().strftime( "%y%m%d") + "_" + time.strftime("%Hh%Mm%Ss") #print "Filepath: " + self.filepath #print "Rendername: " + self.render_name self.camera_data = None #Default Material self.materials = [] default_material_index = sc.doc.Materials.Add() default_material = sc.doc.Materials[default_material_index] default_material.Name = "Default" default_material.Shine = 0 default_material.CommitChanges() self.materials.append(default_material_index)
def unIsolateLayers(): """Unisolate layers by unhiding layers.""" file_name = rs.DocumentName() file_path = rs.DocumentPath() if file_name is None: temp_file_name = "IsolateLayers_temp.json" else: temp_file_name = file_path + 'IsolateLayers_temp_' + file_name.strip( '.3dm') + '.json' if not os.path.isfile(temp_file_name): print("Temp File does not exist!") return with open(temp_file_name, "r") as f: layers_data = json.load(f) layers_data = {rs.LayerName(k): v for k, v in layers_data.items()} sorted_layers_data = sorted(layers_data.iteritems()) for layer_name, layer_visibility in sorted_layers_data: rs.LayerVisible(layer_name, layer_visibility) # remove TEMP FILE os.remove(temp_file_name)
def exportAllPlansToCAD(): if rs.IsLayer("6_DRAWINGS"): children = rs.LayerChildren("6_DRAWINGS") items = [] for child in children: items.append(rs.LayerName(child, False)) #level = rs.ComboListBox(items) print rs.DocumentPath() pathParts = rs.DocumentPath().split("\\") if pathParts[0] == "P:": defaultPath = pathParts[0] + "\\" + pathParts[ 1] + "\\" + pathParts[2] + "\\" + pathParts[3] folder = rs.BrowseForFolder( folder=defaultPath, message="Select Folder to export plans.", title="Export Plans") else: folder = rs.BrowseForFolder() RhinoFile = rs.DocumentName() rhinoName = RhinoFile.split(".")[0] + "_P_" for item in items: levelNum = item.split("_")[-1] fileName = "\\" + rhinoName + levelNum + ".dwg" savePath = folder + fileName #savePath = rs.SaveFileName("Save", "Autocad (*.dwg)|*.dwg||") if savePath is not None: exportPlanToCAD(item, savePath) else: print "No plans currently cut. Use CutPlans." return
def CreateShortcut(): """ Create a shortcut to the current document NOTE!! This function only runs on Windows """ if (not rs.IsRunningOnWindows()): rs.MessageBox("CreateShortcut.py only runs on Windows", 48, "Script Error") return # Get the document name and path name = rs.DocumentName() path = rs.DocumentPath() # Get the Windows Scripting Host's Shell object objShell = System.Activator.CreateInstance( System.Type.GetTypeFromProgID("WScript.Shell")) # Get the desktop folder desktop = objShell.SpecialFolders("Desktop") # Make a new shortcut ShellLink = objShell.CreateShortcut(desktop + "\\" + name + ".lnk") ShellLink.TargetPath = Path.Combine(path, name) ShellLink.WindowStyle = 1 ShellLink.IconLocation = rs.ExeFolder() + "Rhino4.exe, 0" ShellLink.Description = "Shortcut to " + name ShellLink.WorkingDirectory = path ShellLink.Save()
def write_file(file_name, content): path = rs.DocumentPath() name = rs.DocumentName() # save to public path = path + "/../../../../public/data/geo/" + file_name f = open(path, "w") f.write(content) f.close()
def get_document_basename(): """Get the name of the Rhino document (including the extension). Returns ------- str or None The name of the document or None if the document is still "Untitled". """ return rs.DocumentName()
def CurrentModelInfo(): "Get the current document name and path" name = rs.DocumentName() path = rs.DocumentPath() fileexists = False if (path and name): filespec = Path.Combine(path, name) fileexists = File.Exists(filespec) if fileexists: __PrintFileInformation(filespec) else: print "Current model not found. Make sure the model has been saved to disk."
def get_output_path(): """Returns output path as 'system.dat' in the directory of the Rhino model (Windows + Mac OS).""" path = rs.DocumentPath() name = rs.DocumentName() if gc.operating_system == "mac": path = path[:-len(name)] + "_system.dat" elif gc.operating_system == "win": i = path.rfind("\\") path = path[:i] + "/_system.dat" return path
def IsolateLayers(): """Isolate layers by hiding layers.""" file_name = rs.DocumentName() file_path = rs.DocumentPath() # Select objects input_obj = rs.SelectedObjects() if not input_obj: input_obj = rs.GetObjects("Select objects on layers to isolate") if not input_obj: return # Get all layers names proj_layers = rs.LayerNames() layers_history = {rs.LayerId(l): rs.LayerVisible(l) for l in proj_layers} # Save temp if file_name is None: temp_file_name = "IsolateLayers_temp.json" else: temp_file_name = file_path + 'IsolateLayers_temp_' + file_name.strip( '.3dm') + '.json' with open(temp_file_name, "w+") as f: f.write(json.dumps(layers_history, sort_keys=True, indent=4)) # Get objects layers obj_layers = [rs.ObjectLayer(o) for o in input_obj] layers = [] for l in obj_layers: s = l.split('::') a = 0 while len(s) > a: layers.append("::".join(s[:a + 1])) a += 1 # Set current layer rs.CurrentLayer(layers[0]) # Hide layers layers_to_hide = list(set(proj_layers) - set(layers)) for l in layers_to_hide: rs.LayerVisible(l, False)
def ExportSTLWithSettings(objs): rs.SelectObjects(objs) strCurrDP = rs.DocumentPath() strCurrDN = rs.DocumentName() filt = "STL Files (*.stl)|*stl||" if strCurrDN: strSaveDN = strCurrDN[:-3] + "stl" strFileName = rs.SaveFileName("Export STL", filt, strCurrDP, strSaveDN) else: strFileName = rs.SaveFileName("Export STL", filt) strSett = STLSettings() if not strSett: print("Unable to get export settings") print("exporting" + strFileName) rs.Command("-_Export" + " \"" + strFileName + "\"" + " " + strSett, True)
def export(cls): ## cf import deriv """Writes the grammar's dat string to a file, proposing the Rhino document name as the file name. Returns: dat_string str. The dat string, if successful. None, otherwise """ initial_shapes, rules = cls._get_element_layers() if (initial_shapes == [] or rules == []): (error_message) = (' '.join([ "The grammar must have at least", "one initial shape and one rule" ])) print(error_message) return_value = None else: (suggested_file_name, dat_string) = (rs.DocumentName(), gd.GuidsToDat.get_dat_string( initial_shapes, rules)) dat_string_out = cls._write_to_file(suggested_file_name, dat_string) return_value = dat_string_out return return_value
def SaveCopy(): """Save a copy of the current Rhino file.""" date_time = datetime.now().strftime("%Y%m%d_%H%M%S") while rs.DocumentPath() is None: rs.Command("'_Save") file_name = rs.DocumentName() file_dir = rs.DocumentPath() file_path = file_dir + file_name copy_name = "_".join([date_time, file_name]) copy_path = rs.DocumentPath() + copy_name try: os.mkdir(copy_dir) rs.Command("'-Save " + file_path) copyfile(file_path, copy_path) except: rs.Command("'-Save " + file_path) copyfile(file_path, copy_path)
def ExportNamedViews(): ''' Extract view coordinates and write to JSON Example: * Open original .3dm file * RunPythonScript `ExportNamedViews()` * Create a New .3dm file * RunPythonScript `ImportNamedViews()` ''' log = open('./views.json', 'a') fname = rs.DocumentPath() + rs.DocumentName() data = {} data[fname] = {} for view in rs.NamedViews(): rs.RestoreNamedView(view) data[fname][view] = (list(rs.ViewCamera()), list(rs.ViewTarget())) log.write(json.dumps(data, indent=2) + '\n') log.close() return data
def dimensionPline_Button(): objects = rs.GetObjects("Select Curves to Dimension", filter = 4, preselect = True) if objects is None:return if 'dimPline-dist' in sc.sticky: distDefault = sc.sticky['dimPline-dist'] else: distDefault = 60 offsetDist = rs.GetInteger('Dimension offset distance (in.)', distDefault) if offsetDist is None: return sc.sticky['dimPline-dist'] = offsetDist #Load Anno style if it doesnt exist already if sc.doc.DimStyles.FindName('PCPA_12') is None: standards.LoadStyles() try: layers.AddLayerByNumber(8101) layerName = layers.GetLayerNameByNumber(8101) rs.CurrentLayer(layerName) except: pass rs.EnableRedraw(False) for obj in objects: if rs.IsCurve(obj): try: group, rc = dimensionPline(obj, offsetDist) utils.SaveFunctionData('Drawing-Dim Pline', [rs.DocumentPath(), rs.DocumentName(), rs.ObjectLayer(obj), rs.CurrentDimStyle(), offsetDist, rc]) except: print "Unknown Error" else: print "Not a polyline" rs.EnableRedraw(True)
def get_document_name(): return rs.DocumentName()
(T1 M6) (change tool) S16000 M3 (start spindle at full speed) """ def insertSafetyStop(): print >>f, "\nM5 (stop spindle)" def getLayerOrder(layerName): return rs.LayerOrder(layerName) if __name__=="__main__": filename = (rs.DocumentName().split("."))[0] + ".gcode" print "Generating gcode:", filename f = open(filename, 'w') insertHeader() toolpaths = sorted(rs.LayerChildren("Toolpaths"), key=getLayerOrder) for toolpath in toolpaths: print toolpath generateToolpath(toolpath) insertSafetyStop()
import sys import os import re import rhinoscriptsyntax as rs def SaveAsFBX(filename): folder = "C:/Temp/" path = os.path.abspath(folder + filename+".fbx") cmd = "_-SaveAs " + '\"' + path + '\"' + " _-Enter" + " _-Enter" rs.Command(cmd, True) return #save a file as .fbx filename=rs.DocumentName() fileName=re.sub('\.3dm$', '', filename) SaveAsFBX(fileName) rs.Exit()
import rhinoscriptsyntax as rs import System import time import Rhino GH = Rhino.RhinoApp.GetPlugInObject("Grasshopper") dateandtimenow = time.strftime("%Y%m%d") save_date = dateandtimenow[2:] desktop_path = "D:\\David Kay\\Dropbox\\Desktop\\" current_name = rs.DocumentName() if ('_') in current_name: current_name = current_name.split('_', 1)[1] rhino_save_file_name = chr( 34) + desktop_path + save_date + '_' + current_name + chr(34) cmd = '-_SaveAs ' + rhino_save_file_name rs.Command(cmd, True) if GH.IsEditorLoaded(): import clr clr.AddReference('Grasshopper') import Grasshopper
def file_name_button(self,sender,e): save_path = rs.SaveFileName(TXT["save_file"],None, rs.DocumentPath() if not self.user_data["save_path"] else self.user_data["save_path"] ,"%s_gcode" % rs.DocumentName().replace(".3dm",""), ".txt") if save_path: self.add_line(save_path) else: pass
#Export All plans if rs.IsLayer("6_DRAWINGS"): children = rs.LayerChildren("6_DRAWINGS") items = [] for child in children: items.append(rs.LayerName(child, False)) level = rs.ComboListBox(items) print rs.DocumentPath() pathParts = rs.DocumentPath().split("\\") if pathParts[0] == "P:": defaultPath = pathParts[0] + "\\" + pathParts[ 1] + "\\" + pathParts[2] + "\\" + pathParts[3] folder = rs.BrowseForFolder( folder=defaultPath, message="Select Folder to export plan.", title="Export Plan") else: folder = rs.BrowseForFolder() RhinoFile = rs.DocumentName() rhinoName = RhinoFile.split(".")[0] + "_P_" levelNum = level.split("_")[-1] fileName = "\\" + rhinoName + levelNum + ".dwg" savePath = folder + fileName #savePath = rs.SaveFileName("Save", "Autocad (*.dwg)|*.dwg||") if savePath is not None: exportPlanToCAD(level, savePath) else: print "No plans currently cut. Use CutPlans." elif (type == 3): exportAllPlansToCAD()