def SaveNClean(defject, vertices, i, content): #save all there is to run from current iteration and clean up proper rs.Command("_SelNone") rs.Command("_SelPolysrf") index = i if index < 10: j = "0" + str(index) if index >= 10: j = index #Quite probably there is a purely scripted way of writing the export now #It would be through the Rhino and scriptcontext rs.Command("_-Export C:\R3\OffCenter\Walk\Temp\proto2o" + j + ".igs ENTER") rs.DeleteObject(defject) for vrtx in vertices: rs.AddPolyline(vrtx) #Again rs.Command("-saveas C:\\R3\OffCenter\Walk\Temp\sth" + j + ".3dm") objects = rs.AllObjects() rs.DeleteObjects(objects) #need a place to write our polies to!!! History.WritePolies(tempfolder + "\polies" + j + ".txt", content)
def iterate(flow_func, iterations, gif_path=None, *args, **kwargs): """Performs the given number of iterations of an arbitrary flow function, passing specific arguments to that function (those may include the curve/mesh id). Useful for animated flow rendering in RhinoPython. """ can_generate_gif = gif_path is not None if can_generate_gif: # Generate a temporary folder to store frames captured during each iteration. temp_dir = tempfile.mkdtemp() # Iterate the flow function. If the user wants to generate the gif animation, # capture each frame into a file in the temporary folder. obj_id = None for i in range(iterations): if can_generate_gif: rs.Command("-ViewCaptureToFile %s _Enter" % os.path.join(temp_dir, "%08i.png" % i)) obj_id = flow_func(obj_id, *args, **kwargs) if can_generate_gif: # Don't forget to capture the last frame. rs.Command("-ViewCaptureToFile %s _Enter" % os.path.join(temp_dir, "%08i.png" % i)) # NOTE(mikhaildubov): The Pillow (PIL) package should be installed to generate gif animation. # NOTE(mikhaildubov): We make a system call to the python interpreter to launch the gif # compilation script here. That's because Rhinoceros 5 uses its own # IronPython interpreter, and it may be rather difficult to make # third-party libraries available to it. script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "create_gif.py") os.system('python "%s" "%s" "%s"' % (script, gif_path, temp_dir)) # Delete the temporary folder with all the frames inside it. shutil.rmtree(temp_dir) return obj_id
def render_view(str): rh.RenderResolution([render_width(), render_height()]) rh.Command("_-Render", False) rh.Command( '_-SaveRenderWindowAs "{0}"'.format(ensure_dir(render_pathname(str))), False) rh.Command("_-CloseRenderWindow", False)
def main(): print "Checking model" #Check model units if rs.UnitSystem() != 8: rs.MessageBox("Your model is not in inches.", 16) print "Unit warning" #Check bad objects rs.Command('-_SelBadObjects ') objs = rs.SelectedObjects() if len(objs) > 0: message = "You have {} bad objects. Use SelBadObjects to delete them.".format( len(objs)) rs.MessageBox(message, 16) rs.UnselectAllObjects() #SelDup rs.Command('-_SelDup ') objs = rs.SelectedObjects() if len(objs) > 0: message = "You have {} duplicate objects. Use SelDup to delete them.".format( len(objs)) rs.MessageBox(message, 16) rs.UnselectAllObjects() #SelSmall rs.Command('-_SelSmall .01 ') objs = rs.SelectedObjects() if len(objs) > 0: message = "You have {} tiny objects. Use SelSmall to delete them.".format( len(objs)) rs.MessageBox(message, 16) rs.UnselectAllObjects()
def CockpitWindowContours(Height=1.620, Depth=5): P1 = [0.000, 0.076, Height - 1.620 + 2.194] P2 = [0.000, 0.852, Height - 1.620 + 2.290] P3 = [0.000, 0.904, Height + 0.037] P4 = [0.000, 0.076, Height] CWC1 = rs.AddPolyline([P1, P2, P3, P4, P1]) rs.SelectObject(CWC1) rs.Command("_FilletCorners 0.08 ") P1 = [0.000, 0.951, Height - 1.620 + 2.289] P2 = [0.000, 1.343, Height - 1.620 + 2.224] P3 = [0.000, 1.634, Height - 1.620 + 1.773] P4 = [0.000, 1.557, Height - 1.620 + 1.588] P5 = [0.000, 1.027, Height - 1.620 + 1.671] CWC2 = rs.AddPolyline([P1, P2, P3, P4, P5, P1]) rs.SelectObject(CWC2) rs.Command("_FilletCorners 0.08 ") CWC3 = act.MirrorObjectXZ(CWC1) CWC4 = act.MirrorObjectXZ(CWC2) ExtPathId = rs.AddLine([0, 0, 0], [Depth, 0, 0]) CWC1s = rs.ExtrudeCurve(CWC1, ExtPathId) CWC2s = rs.ExtrudeCurve(CWC2, ExtPathId) CWC3s = rs.ExtrudeCurve(CWC3, ExtPathId) CWC4s = rs.ExtrudeCurve(CWC4, ExtPathId) rs.DeleteObjects([CWC1, CWC2, CWC3, CWC4, ExtPathId]) return CWC1s, CWC2s, CWC3s, CWC4s
def export(ids, file_path, file_name, file_type, doc): """ Exports Rhino geometry to a file. :param ids: Geometry ID :param file_path: File directory :param file_name: File name :param file_type: File extension :param doc: Grasshopper document :return: True on success. """ sel_ids = "" for i in range(len(ids)): sel_ids += "_SelId %s " % ids[i] file_name_and_type = file_name + file_type final_path = chr(34) + file_path + '\\' + file_name_and_type + chr(34) command_string = "_-Export " + sel_ids + "_Enter " + final_path + \ " _Enter _Enter _Enter" echo = False done = rs.Command(command_string, echo) sc.doc = rc.RhinoDoc.ActiveDoc rs.SelectObject(ids) rs.Command("_Delete", True) sc.doc = doc if done: return True else: return False
def import_file(self, relPath=None): if relPath == None: rs.Command("_import ") return abs_path = self.directory + relPath command = self.prefix + abs_path + self.suffix did_work = rs.Command(command) assert did_work, "unable to import {}!".format(abs_path)
def do_view_capture(cfg, fname): #rs.Command("_-ViewCaptureToFile LockAspectRatio=No width={w} height={h} {pth}\{fname}_line.jpg".format(w=cfg['size'],h=cfg['size'],pth=cfg['pth_save'],fname=fname)) bmp = cfg['view'].CaptureToBitmap( System.Drawing.Size(cfg['size'], cfg['size'])) bmp.Save(os.path.join(cfg['pth_save_line'], "{}.jpg".format(fname))) if cfg['do_capture_z_buffer']: rs.Command("ShowZBuffer") bmp = cfg['view'].CaptureToBitmap( System.Drawing.Size(cfg['size'], cfg['size'])) bmp.Save(os.path.join(cfg['pth_save_depth'], "{}.jpg".format(fname))) rs.Command("ShowZBuffer")
def __historyImage(self, p): self.design_history = self.design_history + 1 self.outpath = str(config.outpath_design_history + str(self.design_history) + ".jpg") # set view and render image to target folder rs.CurrentView("Perspective") rs.Command("_-Render", False) rs.Command("_-SaveRenderWindowAs \n\"" + self.outpath + "\"\n", False) rs.Command("_-CloseRenderWindow", False) p.Controls.Find("history_image", True)[0].Load(self.outpath) p.Controls.Find("design_history_outpath", True)[0].Text = self.drawn_emotion
def Orthographic_Cplane(): cpln_current = rs.ViewCPlane() Bool_Osnap = rs.Osnap() point = cpln_current.Origin if Bool_Osnap: rs.Osnap(False) rs.Command("_Circle 0,0,0 ") # rs.EnableRedraw(False) # Circle = rs.LastCreatedObjects() if Bool_Osnap: rs.Osnap(True) if Circle is None: # rs.EnableRedraw(True) # return if not rs.IsObject(Circle): rs.EnableRedraw(True) return rs.Command("_Point 0,0,1 ") pt_pos = rs.LastCreatedObjects() rs.Command("_Point 0,0,-1 ") pt_neg = rs.LastCreatedObjects() pt_cam = rs.ViewCamera() dist_pos = rs.Distance(pt_cam,pt_pos) dist_neg = rs.Distance(pt_cam,pt_neg) print pt_cam Disk = rs.AddPlanarSrf(Circle) rs.UnselectAllObjects() rs.SelectObjects(Disk) if dist_pos>dist_neg: rs.Command("OrientCameraToSrf _f 0,0,0 _pause") else: rs.Command("OrientCameraToSrf 0,0,0 _pause") rs.DeleteObjects((pt_pos,pt_neg,Circle,Disk)) rs.ViewProjection(None,1)
def render_emotion_object(object_id, emotion_id): outpath = config.outpath_render + object_id + "_" + emotion_id if not os.path.exists(outpath): os.makedirs(outpath) # set render view to perspective view rs.CurrentView("Perspective") # set animation turntable properties rs.Command( "-SetTurntableAnimation 30 Clockwise png RenderFull Perspective " + emotion_id + " -Enter") # record animation to target folder rs.Command("-RecordAnimation _TargetFolder " + outpath + " -Enter")
def switch_on_new_emotion(object_id, emotion_id=None): if not emotion_id: emotion_id = get_emotion_type(object_id) drawable = draw_emotion_object(object_id, emotion_id) # Perform next action: either new emotion, add, modify, render, save, or new object next_action = get_next_action() if next_action == "e": # new emotion switch_on_new_emotion(object_id) elif next_action == "a": # add emotion added_emotion = get_added_emotions() emotion_id += "."+added_emotion draw_emotion_object(object_id, emotion_id) switch_on_new_emotion(object_id, emotion_id) elif next_action == "m": # modify emotion drawable = draw_emotion_object(object_id, emotion_id) emotion_object = drawable.get_emotion() direct_or_proportional = get_modify_directly_or_proportionally(emotion_object, emotion_id) emotion_breakdown = {} if direct_or_proportional == "c": emotion_breakdown = get_modified_emotion_breakdown_directly(emotion_object) elif direct_or_proportional == "p": # no other options emotion_breakdown = get_modified_emotion_breakdown_proportionally(emotion_object) modify_user_dictionary(object_id, emotion_id, emotion_breakdown) draw_emotion_object(object_id, emotion_id) switch_on_new_emotion(object_id, emotion_id) elif next_action == "r": # render outpath = config.outpath_render + emotion_id if not os.path.exists(outpath): os.makedirs(outpath) # set render view to perspective view rs.CurrentView("Perspective") # set animation turntable properties rs.Command("-SetTurntableAnimation 30 Clockwise png RenderFull Perspective " + emotion_id + " -Enter") # record animation to target folder rs.Command("-RecordAnimation _TargetFolder " + outpath + " -Enter") switch_on_new_emotion(object_id, emotion_id) elif next_action == "s": # save outpath = config.outpath_save + emotion_id rs.Command("-Save " + outpath + " -Enter") switch_on_new_emotion(object_id, emotion_id) elif next_action == "n": # new object switch_on_new_object() elif next_action in config.exit_commands: exit_script()
def main(): objs = rs.VisibleObjects() cutLevel = 12 rs.EnableRedraw(False) objsCopy = rs.CopyObjects(objs) splitModel(objsCopy, cutLevel) makePlan() rs.DeleteObjects(rs.ObjectsByGroup("Above")) rs.DeleteObjects(rs.ObjectsByGroup("Below")) cutAtPlan(cutLevel, False) rs.Command('_SelDupAll _delete') cutAtPlan(cutLevel, True) rs.Command('_SelDup _delete') rs.EnableRedraw(True)
def Render(folder, View, State): """ Defines the Rendering action Saves the render to the browsed folder Adds the name of the view and the name of the layer state to the naming of the view """ FileName = '"' + folder + '\\' + View + '_' + State + '"' FileName = str(FileName) rs.Command("!_-Render") rs.Command("_-SaveRenderWindowAs " + FileName) rs.Command("_-CloseRenderWindow") return 1
def modify_input(filename): # Import object from file join_string = str(input_directory + filename) combined_string = '!_Import ' + '"' + join_string + '"' rs.Command(combined_string) # Get all objects imported objs = rs.LastCreatedObjects(select=False)[0] # Close curve closed_curve = rs.CloseCurve(objs, 0.5) rs.DeleteObject(objs) # Rebuild curve to create smoother shape rs.RebuildCurve(closed_curve, 3, 100) # Pipe figure with radius of 0.25 piped = rs.AddPipe(closed_curve, 0, 0.4)[0] rs.MoveObject(piped, [0, 0, 0]) bounding_pts = rs.BoundingBox([piped], view_or_plane=rs.WorldXYPlane()) maxX = 0 minX = 0 minY = 0 minZ = 0 for pt in bounding_pts: if pt[0] < minX: minX = pt[0] if pt[0] > maxX: maxX = pt[0] if pt[1] < minY: minY = pt[1] if pt[2] < minZ: minZ = pt[2] rect = rs.AddRectangle(rs.WorldXYPlane(), abs(maxX - minX), 3.0) # Move rect up 1/2 of diameter of circle used to pipe # Potentially use solid but smaller in height rect # Select function in rhino module could allow us to select objects so that the export works. rs.MoveObject(rect, [minX, minY - 3.0, minZ + 0.4]) piped_rect = rs.AddPipe(rect, 0, 0.4) rs.DeleteObject(closed_curve) rs.DeleteObject(rect) rs.SelectObjects([piped, piped_rect]) rs.Command("_-Export " + output_directory + filename + '.stl' + " _Enter _Tolerance=.001 _Enter")
def CrossPlatformExtrudeSurface(SurfaceId, CurveId, Capped=True): # rs.ExtrudeSurface not implemented in Rhino for OS X if airconics_setup.RhinoVersion == 1: SolidId = rs.ExtrudeSurface(SurfaceId, CurveId, Capped) else: rs.SelectObject(CurveId) rs.Command("_SelNone") rs.SelectObject(SurfaceId) rs.Command("_ExtrudeSrfAlongCrv _SelPrev") SolidId = rs.LastCreatedObjects() rs.Command("_SelNone") return SolidId
def saveSelectionToFile(self, name, fileType): settings = self.settingsList["Get" + fileType.upper() + "Settings"]() command = '-_Export "{}{}{}" {}'.format(self.filePath, self.fileName, "." + fileType.lower(), settings) rs.Command(command, True)
def new(units="Meter"): # create new file successNew = rs.Command("-_New None") # change units successProp = rs.Command("-_DocumentProperties Units UnitSystem " + units + " No Enter Enter") # delete all but one layer layerCt = rs.LayerCount() for i in range(layerCt - 1): layer = rs.CurrentLayer() rs.DeleteLayer(layer) return successNew and successProp
def main(): msg = "Select polysurface objects to export data" objs = rs.GetObjects(msg, 16, preselect=True) if not objs: return extrusions = [] rs.UnselectAllObjects() for obj in objs: if rs.ObjectType(obj) == 1073741824: extrusions.append(obj) if len(extrusions) > 0: rs.SelectObjects(extrusions) resp = rs.MessageBox( "Selected objects will be converted to polysurfaces.\n Press OK to continue, Cancel to abort", 1) if resp == 1: rs.Command("ConvertExtrusion _Enter") rs.UnselectAllObjects() else: return keys = [i.name for i in ATTRS if i.isEditable] makeDetail(keys, objs) details = [] spec = dict([]) ids = dict([]) for obj in objs: detail = Detail(obj) details.append(detail) spec = Specification([], details) dialog = SpecDialog() dialog.setData(spec) rs.UnselectAllObjects() Rhino.UI.EtoExtensions.ShowSemiModal(dialog, Rhino.RhinoDoc.ActiveDoc, Rhino.UI.RhinoEtoApp.MainWindow)
def main(): print("script_start") objs = rs.GetObjects("select objects to export", 0, True, True) if not objs: print "abort" return # check curves for deviation from c-plane result = checkCurvePosition(objs) # if ok, start export if result: #make curve direction all the same setCurveDir(objs) rs.UnselectAllObjects() # move to origin objs = copyToOrigin(objs) # export rs.SelectObjects(objs) rs.Command("Export") rs.DeleteObjects(objs) else: print "abort" return
def RunCommand(is_interactive): if not rs.IsLayer("Dim"): util.initCaadLayer("Dim") oldLayer = rs.CurrentLayer("Dim") rs.Command("_DimAligned") rs.CurrentLayer(oldLayer)
def setNormalVec(self): #set normal vector from selected base surface #if selected base surface isn't planar, return False self.baseSurface = rs.GetSurfaceObject( "Select surface to be addded object") if self.baseSurface == None: return False rs.SelectObject(self.baseSurface[0]) if not rs.IsSurfacePlanar(self.baseSurface[0]): print( "Selected Surface is not planar\nPlease select planar surface") return False print("Confirm direction to add object") rs.Command("Dir") self.normalVec = rs.SurfaceNormal(self.baseSurface[0], [0, 0]) rs.UnselectAllObjects() self.setAngleOfBaseSurface() return True
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 ImportObject(self, file): rs.Command("_-Insert _File=_Yes " + self.root + file + ".3dm B 0,0,0 1 0 _Enter") object = rs.SelectedObjects()[0] rs.UnselectAllObjects() object = rs.ExplodeBlockInstance(object)[0] return object
def AutoExport(objs): appData = os.getenv('APPDATA') targetFolder = appData + r"\PCPA\temp.dwg" rs.SelectObjects(objs) rs.Command( '-_Export ' + '"' + targetFolder + '"' + ' s "2007 Natural" Enter ', True)
def AddFrame(self, numberOfPasses=500): """ Parameters: Returns: path of the saved frame Example: fileName = xxxxx Format = 190723_xxxxx_003 """ year = int(datetime.datetime.today().strftime('%Y')) - 2000 md = datetime.datetime.today().strftime('%m%d') date = str(year) + str(md) frameNumberStr = self.frameNumber frameNumberStr = str(frameNumberStr).zfill(4) self.frameNumber += 1 fileName = date + "_" + self.videoName + "_" + frameNumberStr + ".jpg" file_path = os.path.join(self.sourceFolder, fileName) self.frameFilePaths.append(file_path) rs.Command( '-_viewCaptureToFile w=' + str(self.width) + ' N=' + str(numberOfPasses) + ' h=' + str(self.height) + ' s=1 TransparentBackground=No "' + str(file_path) + '" Enter', False) return file_path
def addComponent(): libPath = 'C:\\Users\\Tim\\Desktop\\temp\\library' rhinoFiles = [] items = os.listdir(libPath) if items is None: print "Library is empty or path is wrong" return for item in items: parts = item.split(".") if len(parts) == 2: if parts[1] == "3dm": rhinoFiles.append(parts[0]) choice = rs.ComboListBox(rhinoFiles, "Select Components to add", "add Component") if choice is None: return choiceFile = choice + ".3dm" rs.EnableRedraw(False) rs.Command('-_NoEcho _-Import ' + libPath + "\\" + choiceFile + ' Objects Enter -_SelLast Enter') importedGeo = rs.GetObjects(preselect=True) rs.ObjectLayer(importedGeo, rs.CurrentLayer()) rs.SelectObjects(importedGeo) rs.EnableRedraw(True)
def calculateWidth(files): global box_width for filename in files: join_string = str(input_directory + filename) combined_string = '!_Import ' + '"' + join_string + '"' rs.Command(combined_string) objs = rs.LastCreatedObjects(select=False)[0] bounding_pts = rs.BoundingBox([objs], view_or_plane=rs.WorldXYPlane()) maxX = 0 minX = 0 minY = 0 minZ = 0 for pt in bounding_pts: if pt[0] < minX: minX = pt[0] if pt[0] > maxX: maxX = pt[0] if pt[1] < minY: minY = pt[1] if pt[2] < minZ: minZ = pt[2] if abs(maxX - minX) > box_width: box_width = abs(maxX - minX) rs.DeleteObject(objs)
def Render(folder, count): """ Defines the Rendering action Saves the render to the browsed folder Adds the name of the view and the name of the layer state to the naming of the view """ FileName = '"'+folder+'/img_'+str(count)+'"' FileName = str(FileName) rs.Command ("!_-Render") rs.Command ("_-SaveRenderWindowAs "+FileName) rs.Sleep(2000) rs.Command ("_-CloseRenderWindow") rs.Sleep(1000) return 1
def LoadAcadSchemes(filepath): if os.path.isdir(filepath) is False: print "FAIL-----ACAD Scheme folder not found" return None else: allFilesRaw = os.listdir(filepath) allFiles = [] for file in allFilesRaw: if file.endswith(".ini"): allFiles.append(file) if len(allFiles) == 0: print "\tACAD Schemes not updated. No ACAD Schemes in standards folder" return for file in allFiles: fullFilePath = '"' + filepath + '\\' + file + '"' shortName = file.split('.')[0] rs.Command('-_AcadSchemes i ' + fullFilePath + ' Enter c ' + shortName + ' Enter ', echo=False) if len(allFiles) == 1: print "\t{} ACAD Scheme updated".format(len(allFiles)) else: print "\t{} ACAD Schemes updated".format(len(allFiles))