def layerSet(text, color): #deletes existing information regarding this layer if rs.LayerId(text): rs.DeleteObjects(rs.ObjectsByLayer(text)) rs.PurgeLayer(text) #recomputes layer as new layer rs.AddLayer(text, color)
def set_layer(obj, name, r, g, b, visible=True): if not rs.IsLayer(name): layer = rs.AddLayer(name, [r, g, b], visible, locked=False, parent=None) else: layer = rs.LayerId(name) # オブジェクトをライヤーに割り当て rs.ObjectLayer(obj, layer)
def CollapseRootLayers(roots): rs.EnableRedraw(False) for root in roots: try: rootLay = sc.doc.Layers.FindId(rs.coerceguid(rs.LayerId(root))) rootLay.IsExpanded = False except: pass rs.EnableRedraw(True)
def layerChangeEvent(sender, e): toolpaths = rs.LayerChildren("Toolpaths") layerId = "" for toolpath in toolpaths: layerId = rs.LayerId(toolpath) for textDotId in rs.ObjectsByType(8192): toolpathName = rs.TextDotText(textDotId) if rs.GetUserText(textDotId, "LayerId") == layerId: newToolpathName = toolpath.split("::")[1] print "Renaming ", toolpathName, " to ", newToolpathName rs.TextDotText(textDotId, newToolpathName)
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 ExportEachLayerAsOBJ(objs, newFolder, newFolderName): try: allLayers = [] for obj in objs: layer = rs.ObjectLayer(obj) if layer not in allLayers: allLayers.append(layer) for eachLayer in allLayers: try: #FindByLayer doesnt work with full layer names id = rs.LayerId(eachLayer) shortName = rs.LayerName(id, False) filepath = os.path.join(newFolder,newFolderName+ '_' + shortName + '.obj') rhobjs = sc.doc.Objects.FindByLayer(shortName) rs.SelectObjects(rhobjs) rs.Command('-_Export ' + '"' + filepath + '"' + ' Enter Enter ') rs.UnselectAllObjects() except: pass except: print 'ExportEachLayerAsSat failed'
def prepareToolpaths(toolpathName, objects, mode, totalDepth, passDepth, toolDiameter): objectNr = 1 pathSegmentNr = 1 lastPoint = [] for id in objects: plane = rs.CurvePlane(id) # place point inside or outside the object (it is needed for the offset) if mode == "Inside": point = rs.CurveAreaCentroid(id)[0] else: point = rs.XformCPlaneToWorld([10000, 10000, 0], plane) tempCurve = rs.OffsetCurve(id, point, toolDiameter / 2.0, plane.ZAxis) if not tempCurve: print "Tool cannot do this toolpath" return False passPoint = rs.CurveStartPoint(tempCurve) if objectNr > 1: objId = rs.AddLine(lastPoint, [passPoint.X, passPoint.Y, safetyHeight]) setSegmentId(objId, pathSegmentNr) pathSegmentNr = pathSegmentNr + 1 setFeedrate(objId, feedrateMove) objId = rs.AddLine([passPoint.X, passPoint.Y, safetyHeight], [passPoint.X, passPoint.Y, 0]) setSegmentId(objId, pathSegmentNr) pathSegmentNr = pathSegmentNr + 1 setFeedrate(objId, feedratePlunge) if objectNr == 1: labelId = rs.AddTextDot(toolpathName, [passPoint.X, passPoint.Y, safetyHeight]) rs.SetUserText(labelId, "LayerId", rs.LayerId("Toolpaths::" + pathLayerName)) lastPass = False passNr = 1 prevDepth = 0 while True: depth = passNr * passDepth # if the depth is lower, set it to max and mark for last pass if depth >= totalDepth: depth = totalDepth lastPass = True objId = rs.AddLine([passPoint.X, passPoint.Y, -prevDepth], [passPoint.X, passPoint.Y, -depth]) setSegmentId(objId, pathSegmentNr) setFeedrate(objId, feedratePlunge) pathSegmentNr = pathSegmentNr + 1 prevDepth = depth # add the toolpath and move it to current depth toolpathCurve = rs.CopyObject(tempCurve) rs.MoveObject(toolpathCurve, [0, 0, -depth]) setSegmentId(toolpathCurve, pathSegmentNr) setFeedrate(toolpathCurve, feedrateCutting) passNr = passNr + 1 pathSegmentNr = pathSegmentNr + 1 if lastPass == True: break # add the exit move lastPoint = [passPoint.X, passPoint.Y, safetyHeight] objId = rs.AddLine([passPoint.X, passPoint.Y, -depth], lastPoint) setSegmentId(objId, pathSegmentNr) setFeedrate(objId, feedrateRetract) pathSegmentNr = pathSegmentNr + 1 # remove the helper curve rs.DeleteObject(tempCurve) objectNr = objectNr + 1 return True
def importCAD(filePath, scaleDWG = False): explodeBlockBoo = True #setup the layers importLayerNumber = 6000 importLayerObj = layers.AddLayerByNumber(importLayerNumber, False) importLayerName = layers.GetLayerNameByNumber(importLayerNumber) #Shorten cad file name fileNameExt = os.path.basename(filePath) fileName = os.path.splitext(fileNameExt)[0] #create layer name time = utils.GetDatePrefix() iter = "01" layerName = time+"_"+fileName+"_"+iter #Check if this layer already exists while rs.IsLayer(importLayerName + "::" + time + "_" + fileName + "_" + iter): iterInt = int(iter)+1 if len(str(iterInt))<2: iter = "0" + str(iterInt) else: iter = str(iterInt) elementLayerName = importLayerName + "::" + time + "_" + fileName + "_" + iter elementLayer = rs.AddLayer(elementLayerName) rs.CurrentLayer(elementLayer) #get intial list of all layers in the file currentLayers = rs.LayerNames() rs.Command('_-Import "' + filePath + '" _IgnoreThickness=Yes _ModelUnits=Inches _Enter', False) #get new layers added endLayersNames = rs.LayerNames() newLayers = diff(endLayersNames, currentLayers) for layer in newLayers: rs.ParentLayer(layer, elementLayer) objects = rs.ObjectsByLayer(layer) if rs.IsLayerEmpty(layer): rs.DeleteLayer(layer) else: for obj in objects: if rs.IsDimension(obj): rs.DeleteObject(obj) elif rs.IsHatch(obj): rs.DeleteObject(obj) #Get all the imported geometry allObjects = [] finalLayers = rs.LayerChildren(rs.CurrentLayer()) blockNames = [] for finalLayer in finalLayers: layerObjects = rs.ObjectsByLayer(finalLayer) for layerObject in layerObjects: if rs.IsBlockInstance(layerObject): blockNames.append(rs.BlockInstanceName(layerObject)) allObjects.append(rs.ExplodeBlockInstance(layerObject, True)) else: allObjects.append(layerObject) finalAllObjects = list(flatten(allObjects)) for eachBlock in blockNames: try: rs.DeleteBlock(eachBlock) except: pass #Scale objects if scaleDWG: rs.ScaleObjects(finalAllObjects, [0,0,0], [.001, .001, .001]) #Collapse layers try: rootLay = sc.doc.Layers.FindId(rs.coerceguid(rs.LayerId(elementLayerName))) rootLay.IsExpanded = False except: pass print "Import Successful" return finalAllObjects
import rhinoscriptsyntax as rs #must have default layer and "Source Points" initialized for this to work source_pts = rs.ObjectsByLayer("Source Points", True) point = rs.GetObject("select the point on default layer") l_id = rs.LayerId("Source Points") rs.ObjectLayer(point, l_id)
def add_rivet(rivet): # *********************************************** # ******** ADDING THE RIVET TO THE SCENE ********* # *********************************************** old_osnap_state = ModelAidSettings.OsnapModes #record Osnap state to reset later rivets = 0 rs.OsnapMode(32 + 134217728) while True: Rhino.UI.MouseCursor.SetToolTip("select surface or face") # this function ask the user to select a point on a surface to insert the bolt on # Surface to orient on gs = Rhino.Input.Custom.GetObject() gs.SetCommandPrompt("Surface to orient on") gs.GeometryFilter = Rhino.DocObjects.ObjectType.Surface gs.Get() if gs.CommandResult() != Rhino.Commands.Result.Success: ModelAidSettings.OsnapModes = old_osnap_state #reset to previous Osnap state print str(rivets) + " " + rivet.__repr__( ) + " rivet(s) added to the document" Rhino.UI.MouseCursor.SetToolTip("") return objref = gs.Object(0) # get selected surface object obj = objref.Object() if not obj: ModelAidSettings.OsnapModes = old_osnap_state #reset to previous Osnap state print str(rivets) + " " + rivet.__repr__( ) + " bolt(s) added to the document" return # get selected surface (face) global surface surface = objref.Surface() if not surface: return Rhino.Commands.Result.Failure # Unselect surface obj.Select(False) # Point on surface to orient to / activate center Osnap gp = Rhino.Input.Custom.GetPoint() gp.SetCommandPrompt("Point on surface to orient to") gp.Constrain(surface, False) #display the geometry to be created gp.DynamicDraw += drawbreps gp.Get() if gp.CommandResult() != Rhino.Commands.Result.Success: ModelAidSettings.OsnapModes = old_osnap_state #reset to previous Osnap state print str(rivets) + " " + rivet.__repr__( ) + " bolt(s) added to the document" return getrc, u, v = surface.ClosestPoint(gp.Point()) if getrc: getrc, target_plane = surface.FrameAt(u, v) if getrc: # Build transformation source_plane = Rhino.Geometry.Plane.WorldXY xform = Rhino.Geometry.Transform.PlaneToPlane( source_plane, target_plane) #check if layer Block_Definitions exist, else create it if not rs.IsLayer("Block_Definitions"): rs.AddLayer("Block_Definitions") #check if layer with block name exists, else create it if not rs.IsLayer("Block_Definitions::" + rivet.name): block_layer = rs.AddLayer("Block_Definitions::" + rivet.name, color=(120, 210, 210)) block_layer = "Block_Definitions::" + rivet.name layer_id = rs.LayerId(block_layer) layer_index = sc.doc.Layers.Find(layer_id, True) # Do the transformation rs.EnableRedraw(False) temp_layer = rs.CurrentLayer() rs.CurrentLayer(block_layer) objs = rivet.breps rhobj = [] for brep in objs: attribs = Rhino.DocObjects.ObjectAttributes() attribs.WireDensity = -1 attribs.LayerIndex = layer_index rhobj.append(sc.doc.Objects.AddBrep(brep, attribs)) rs.AddBlock(rhobj, [0, 0, 0], rivet.name, True) newrivet = rs.InsertBlock2(rivet.name, xform) rs.CurrentLayer(temp_layer) rs.EnableRedraw(True) rivets += 1