def main(): rc = getInput_TrimmingObjects() if rc is None: return ( rhObjs_Splitters, bScanForNakedEdges, bEcho, bDebug, ) = rc #print len(rc) if not rhObjs_Splitters: # Get all Normal objects now so before any layer, etc., changes occur during next input. rhObjs_Splitters = getAllNormalObjs(bScanForNakedEdges) if not rhObjs_Splitters: print "No splitters." return while True: sc.escape_test() rc = getInput_Face() if rc is None: return ( objref_Face, bScanForNakedEdges, bPickPtForKeepNotRemove, bOnlyUseCrvsOnFace, bSplitToCrvSegs, fTolerance, bTryOtherTolsOnFail, bExtract, bEcho, bDebug, ) = rc #print len(rc) sc.doc.Objects.UnselectAll() Rhino.RhinoApp.SetCommandPrompt("Working ...") if not bDebug: sc.doc.Views.RedrawEnabled = False gBs_fromTrim = processBrepObject( objref_Face, rhObjs_Splitters, bPickPtForKeepNotRemove=bPickPtForKeepNotRemove, bOnlyUseCrvsOnFace=bOnlyUseCrvsOnFace, bSplitToCrvSegs=bSplitToCrvSegs, fTolerance=fTolerance, bTryOtherTolsOnFail=bTryOtherTolsOnFail, bExtract=bExtract, bEcho=bEcho, ) sc.doc.Views.RedrawEnabled = True
def getNurbsSrfFaces(rgFaceA, rgNurbsSurfaceA=None, idx_rgFaces_Filter=None, fTolerance=1e-9, bDebug=False): if rgNurbsSurfaceA is None: rgSrfA = rgFaceA.UnderlyingSurface() if not isinstance(rgSrfA, rg.NurbsSurface): rgSrfA.Dispose() return nsA = rgSrfA else: nsA = rgNurbsSurfaceA idx_rgFaceA = rgFaceA.FaceIndex # Find matching shapes of adjacent faces. idxFaces_Pass = [idx_rgFaceA] idxFaces_Fail = [] idxFaces_LastAdded = [idx_rgFaceA] rgBrep0 = rgFaceA.Brep for idxFace_LastAdded in idxFaces_LastAdded: sc.escape_test() for idx_Face_Adj in rgBrep0.Faces[idxFace_LastAdded].AdjacentFaces(): if idx_rgFaces_Filter and idx_Face_Adj not in idx_rgFaces_Filter: continue elif idx_Face_Adj in idxFaces_Pass: continue elif idx_Face_Adj in idxFaces_Fail: continue rgFaceB = rgBrep0.Faces[idx_Face_Adj] srfB = rgFaceB.UnderlyingSurface() if not isinstance(srfB, rg.NurbsSurface): continue nsB = srfB if not nsA.EpsilonEquals(other=nsB, epsilon=fTolerance): idxFaces_Fail.append(idx_Face_Adj) continue # Main parameters of NurbsSurface are equal, so now check all ControlPoints. if nsA.Points.CountU != nsB.Points.CountU: idxFaces_Fail.append(idx_Face_Adj) continue if nsA.Points.CountV != nsB.Points.CountV: idxFaces_Fail.append(idx_Face_Adj) continue for ptA, ptB in zip(nsA.Points, nsB.Points): if not ptA.EpsilonEquals(other=ptB, epsilon=fTolerance): idxFaces_Fail.append(idx_Face_Adj) break else: if bDebug: print "NurbsSurfaces are EpsilonEqual." idxFaces_Pass.append(idx_Face_Adj) idxFaces_LastAdded.append(idx_Face_Adj) return idxFaces_Pass
def do_capture(name, is_first, cfg): Rhino.RhinoApp.Wait() if (sc.escape_test(False)): raise Exception('Esc key caught pre-render in do_capture()') if DO_CAPTURE_VIEW: do_view_capture(name, is_first, cfg) Rhino.RhinoApp.Wait() if (sc.escape_test(False)): raise Exception('Esc key caught post-render in do_capture()')
def sortFacesByIslands(rgBrep, idxF_Start): """ Returns: list(int(Index of start face and islands)) list(int(Index of remaining faces)) """ rgB = rgBrep if 1 <= rgB.Faces.Count <= 2: return [idxF_Start], [0 if idxF_Start else 1] idxFs_Keep = [] idxFs_Skip = [] idxFs_toAddToSkip = [] idxFs_Adj_toNewSkip = [idxF_Start] while True: sc.escape_test() # Add to keep. idxFs_toAddToKeep = [] for idxF in idxFs_Adj_toNewSkip: if idxF not in idxFs_Keep and idxF not in idxFs_Skip: idxFs_toAddToKeep.append(idxF) if not idxFs_toAddToKeep: # All faces have been tested. return idxFs_Keep, idxFs_Skip idxFs_Keep.extend(idxFs_toAddToKeep) idxFs_Adj_toNewKeep = [] for idxF in idxFs_toAddToKeep: idxFs_Adj_toNewKeep.extend(rgB.Faces[idxF].AdjacentFaces()) idxFs_Adj_toNewKeep = list(set(idxFs_Adj_toNewKeep)) idxFs_toAddToSkip = [] for idxF in idxFs_Adj_toNewKeep: if idxF not in idxFs_Skip and idxF not in idxFs_Keep: idxFs_toAddToSkip.append(idxF) if not idxFs_toAddToSkip: # All faces have been tested. return idxFs_Keep, idxFs_Skip idxFs_Skip.extend(idxFs_toAddToSkip) idxFs_Adj_toNewSkip = [] for idxF in idxFs_toAddToSkip: idxFs_Adj_toNewSkip.extend(rgB.Faces[idxF].AdjacentFaces()) idxFs_Adj_toNewSkip = list(set(idxFs_Adj_toNewSkip))
def throwNode(nodes,speed,stickRange,passParams,resizeThreshold): boundRadius = passParams[0] bGeom = passParams[1] #sFactor = passParams[2] #print passParams[2] #assumes time steps of 1 startPos = getBoundaryPos(boundRadius); endPos = getBoundaryPos(boundRadius); direction = rs.VectorSubtract(endPos,startPos) direction = rs.VectorUnitize(direction) vel = rs.VectorScale(direction,speed); currentPos = rs.VectorAdd(startPos,vel) previewGeom = [] isTravelling = True while(isTravelling): scriptcontext.escape_test() #hit escape to quit NOT WORKING time.sleep(0.01*10**-7) for o in previewGeom: rs.DeleteObjects(o) dist = rs.VectorLength(currentPos) #distance to origin #check if particle went out of bounds if(dist>boundRadius): isTravelling = False else: previewGeom.append(drawPos(currentPos,stickRange)) for i in range(len(nodes)): n = nodes[i] if(inStickRange(currentPos,n,stickRange)): #GOT STUCK! add a new node at that position newNode = node(currentPos,i,.08) #parent is idx of node stuck too newNode.increaseRadius(.01, nodes) nodes.append(newNode) #rNodes.append(rs.AddPoint(currentPos)) if(math.fabs(boundRadius-dist) <= resizeThreshold): #print "boundRadius should resize" rs.DeleteObjects(bGeom) boundRadius += resizeThreshold/2 #arbitrary bGeom = rs.AddCircle([0,0,0],boundRadius) passParams[0] = boundRadius passParams[1] = bGeom isTravelling = False for o in previewGeom: rs.DeleteObjects(o) break currentPos = rs.VectorAdd(currentPos,vel) Rhino.RhinoApp.Wait() return passParams
def getBrepIdAndTrimIdx(): disposeUs = [] # Load sticky. stickyKeys = ['bSmooth({})'.format(__file__)] stickyValues = [True] for i, stickyKey in enumerate(stickyKeys): if sc.sticky.has_key(stickyKey): stickyValues[i] = sc.sticky[stickyKey] bSmooth, = stickyValues # Get untrimmed brep edge with optional input. go = ri.Custom.GetObject() disposeUs.append(go) go.SetCommandPrompt("Select untrimmed edge to extend") go.GeometryFilter = rd.ObjectType.EdgeFilter # SurfaceBoundaryEdge doesn't include seams. go.GeometryAttributeFilter = ( ri.Custom.GeometryAttributeFilter.SurfaceBoundaryEdge) def is1FaceBrep(rdBrep, rgTrim, compIdx): return rdBrep.BrepGeometry.Faces.Count == 1 go.SetCustomGeometryFilter(is1FaceBrep) optT_Smooth = ri.Custom.OptionToggle(bSmooth, 'RuledExtension', 'Smooth') go.AddOptionToggle('Type', optT_Smooth) while go.Get() != ri.GetResult.Object: sc.escape_test() if go.CommandResult() != Rhino.Commands.Result.Success: # Canceled. dispose(disposeUs) return objref = go.Object(0) disposeUs.append(objref) idBrep = objref.ObjectId compIdx = objref.GeometryComponentIndex.Index bSmooth = optT_Smooth.CurrentValue # Save sticky. stickyValues = bSmooth, for i, stickyKey in enumerate(stickyKeys): sc.sticky[stickyKey] = stickyValues[i] dispose(disposeUs) return idBrep, compIdx, bSmooth
def GetObjectsToNest(self): '''Select Objects To Nest''' geometryFilter = Rhino.DocObjects.ObjectType.Annotation | \ Rhino.DocObjects.ObjectType.TextDot | \ Rhino.DocObjects.ObjectType.Point | \ Rhino.DocObjects.ObjectType.Curve | \ Rhino.DocObjects.ObjectType.Surface | \ Rhino.DocObjects.ObjectType.PolysrfFilter | \ Rhino.DocObjects.ObjectType.Mesh go = Rhino.Input.Custom.GetObject() go.SetCommandPrompt("OpenNest: Select objects for nesting") go.GeometryFilter = geometryFilter go.GroupSelect = False go.SubObjectSelect = False go.EnableClearObjectsOnEntry(True) go.EnableUnselectObjectsOnExit(True) go.DeselectAllBeforePostSelect = False bHavePreselectedObjects = False while True: if scriptcontext.escape_test(False): return res = go.GetMultiple(1, 0) if res == Rhino.Input.GetResult.Option: go.EnablePreSelect(False, True) continue elif res != Rhino.Input.GetResult.Object: return if go.ObjectsWerePreselected: bHavePreselectedObjects = True go.EnablePreSelect(False, True) continue break if (bHavePreselectedObjects): for i in xrange(go.ObjectCount): rhinoObject = go.Object(i).Object() if not rhinoObject is None: rhinoObject.Select(False) scriptcontext.doc.Views.Redraw() guids = List[System.Guid]() for i in xrange(go.ObjectCount): guids.Add(go.Object(i).ObjectId) # Tuple<Brep[], Dictionary<int, List<Guid>>> data = OpenNestLib.OpenNestUtil.SortGuidsByPlanarCurves(guids, self.cp) #print type(data) print "OpenNest: Selected object count = {0}".format(go.ObjectCount) self.n = data.Item1.Length scriptcontext.doc.Views.Redraw() return data
def main(): cfg = setup(PARENT_LAYER, VIEW_COUNT, IMG_SIZE, DEBUG, DO_CAPTURE_Z_BUFFER) # MAIN LOOP print("plottting {} layers taken from {} views across {} xforms.".format( len(cfg['layer_info']['children']), len(cfg['view_locs']), len(cfg['xforms']))) print("{} images will result.".format( len(cfg['layer_info']['children']) * len(cfg['view_locs']) * len(cfg['xforms']))) try: for l, layer in enumerate(cfg['layer_info']['children']): isolate_layer(cfg['layer_info'], l) for x, xf in enumerate(cfg['xforms']): print("##### xform {} of {}".format(x + 1, len(cfg['xforms']))) apply_xf_to_all_objects(xf) # apply transformation for c, cam in enumerate(cfg['view_locs']): do_capture(cam, "{}_{:04}_{:02}".format(layer.Name, c, x), cfg) # capture view apply_xf_to_all_objects( rs.XformInverse(xf)) # restore transformation Rhino.RhinoApp.Wait() if (sc.escape_test(False)): raise Exception('Esc key caught in main()') except Exception as e: print e finally: teardown(cfg)
def main(): skNum = (datetime.date.today()-datetime.date(2020, 03, 28)).days + 201 if int(skNum) > int(os.path.splitext(os.path.basename(__file__))[0]): print "!!!!SAVE THE SKETCH WITH A NEW NAME!!!!" rs.UnselectAllObjects() init_time = time.time() version = 'a' anim = mp4.Animation(os.path.splitext(os.path.basename(__file__))[0] + version) numFrames = 200 numPasses = 200 anim.fps = 30 td = TempDisplay() display = HUD(os.path.splitext(os.path.basename(__file__))[0], numFrames) s = Scene() ################################ #SETUP ballSystem = System() ################################ for i in range(numFrames): start_time = time.time() print "Frame {}".format(i) if sc.escape_test(False): anim.Cleanup(); return ################################ #MAIN LOOP ballSystem.Update() ################################ #HUD #display.UpdateParam1('x: ' + str(ball.pos.X)) #display.UpdateParam2('y: ' + str(ball.pos.Y)) #display.UpdateParam3('z: ' + str(ball.pos.Z)) display.UpdateScaleBar() ################################ sc.doc.Views.Redraw() display.Update(i) anim.AddFrame(numberOfPasses = numPasses) #if result: # break ################################ #Framerate frameTime = time.time() - start_time timeLeft = (numFrames - i) * frameTime timeLeftStr = str(datetime.timedelta(seconds=timeLeft)) print "Time remaining: {}".format(timeLeftStr) frameTime = time.time() - init_time timeLeftStr = str(datetime.timedelta(seconds=frameTime)) print "Total Time: {}".format(timeLeftStr) if os.path.isdir(r"D:\Files\Work\LIBRARY\06_RHINO\10_Python\300 DAYS\anim"): anim.Create(r"D:\Files\Work\LIBRARY\06_RHINO\10_Python\300 DAYS\anim", frames2Keep = [i/2, i-1]) else: anim.Create(r"C:\Tim\300 Days\anim", frames2Keep = [i/2, i-1])
def main(): startDate = None init_time = time.time() version = 'a' anim = mp4.Animation( os.path.splitext(os.path.basename(__file__))[0] + version) numFrames = 150 numPasses = 200 anim.fps = 30 td = TempDisplay() display = HUD(os.path.splitext(os.path.basename(__file__))[0], numFrames) s = Scene() ################################ #SETUP ball = Ball() ################################ for i in range(numFrames): start_time = time.time() print "Frame {}".format(i) if sc.escape_test(False): anim.Cleanup() return ################################ #MAIN LOOP ball.Update() ################################ #HUD display.UpdateParam1('x: ' + str(ball.pos.X)) display.UpdateParam2('y: ' + str(ball.pos.Y)) display.UpdateParam3('z: ' + str(ball.pos.Z)) display.UpdateScaleBar() ################################ sc.doc.Views.Redraw() display.Update(i) anim.AddFrame(numberOfPasses=numPasses) #if result: # break ################################ #Framerate frameTime = time.time() - start_time timeLeft = (numFrames - i) * frameTime timeLeftStr = str(datetime.timedelta(seconds=timeLeft)) print "Time remaining: {}".format(timeLeftStr) frameTime = time.time() - init_time timeLeftStr = str(datetime.timedelta(seconds=frameTime)) print "Total Time: {}".format(timeLeftStr) if os.path.isdir( r"D:\Files\Work\LIBRARY\06_RHINO\10_Python\300 DAYS\anim"): anim.Create(r"D:\Files\Work\LIBRARY\06_RHINO\10_Python\300 DAYS\anim", frames2Keep=[i / 2, i - 1]) else: anim.Create(r"C:\Tim\300 Days\anim", frames2Keep=[i / 2, i - 1])
def Update(self): xform = rg.Transform.Rotation(math.radians(2.4 * 3), rg.Vector3d(1, 0, 0), rg.Point3d(50, 50, 50)) for eachGeo in self.geos: eachGeo.Transform(xform) for ball in self.system.particles: if sc.escape_test(True): return None newGeos = [] deadGeos = [] for geo in self.geos: if geo is None: print "A geo was None" deadGeos.append(geo) if ball.box is None: print "A ball.box was None" continue resultBrep = rg.Brep.CreateBooleanDifference( geo, ball.box, sc.doc.ModelAbsoluteTolerance) if resultBrep: if len(resultBrep) != 0: ball.hit = True #ball.alive = False newGeos += resultBrep deadGeos.append(geo) else: deadGeos.append(geo) for deadGeo in deadGeos: if deadGeo in self.geos: self.geos.remove(deadGeo) for newGeo in newGeos: if newGeo not in self.geos: if newGeo: self.geos.append(newGeo) largestMass = None largestVol = None for geo in self.geos: v = rg.VolumeMassProperties.Compute(geo) if v > largestVol or largestVol is None: largestVol = v largestMass = geo self.geo = largestMass #Update Display for id in self.ids: sc.doc.Objects.Delete(id, True) for geo in self.geos: self.ids.append(sc.doc.Objects.AddBrep(geo, self.attr))
def loop(self): self.Enabled = True self.loopFlg = True while(self.loopFlg): if scriptcontext.escape_test(False): self.loopFlg = False self.bake() self.update() scriptcontext.doc.ActiveDoc.Views.ActiveView.Redraw() self.saveImage(self.frameCnt) self.frameCnt += 1 self.Enabled = False
def do_capture(loc, name, cfg): #print("view {} of {}".format(m+1,len(locs))) set_camera(cfg, loc) """ contour_crv_ids = [] if contour_curve_dist: contour_crv_ids = contour_all_meshes(loc, contour_curve_dist) """ light_id = light_from_upper_left(light_intensity, light_color) Rhino.RhinoApp.Wait() if (sc.escape_test(False)): raise Exception('Esc key caught pre-render in do_capture()') do_view_capture(cfg, name) do_render(cfg, name) Rhino.RhinoApp.Wait() if (sc.escape_test(False)): raise Exception('Esc key caught post-render in do_capture()') delete_light_by_id(light_id)
def tryGetPlane(rgSrf0, fTolerance=1e-9, bDebug=False): """ Updated in May of 2019. Returns a tuple: On success: (rg.Plane instance), (float: tolerance actually used to obtain shape) On fail: None, None """ if fTolerance <= 0.0: return None, None elif fTolerance < 1e-12: fTolerance = 1e-12 if isinstance(rgSrf0, rg.BrepFace): rgSrf0 = rgSrf0.UnderlyingSurface() if isinstance(rgSrf0, rg.NurbsSurface): rgNurbsSrf1 = rgSrf0.Duplicate() else: rgNurbsSrf1 = rgSrf0.ToNurbsSurface() # Start tolerance to use at a low value and iterate up to input tolerance. fTol_Attempting = fTolerance if fTolerance < 1e-9 else 1e-9 while fTol_Attempting <= fTolerance: sc.escape_test() b, plane = rgNurbsSrf1.TryGetPlane(fTol_Attempting) if b: rgNurbsSrf1.Dispose() return plane, fTol_Attempting if fTol_Attempting == fTolerance: break fTol_Attempting *= 10.0 if fTol_Attempting > fTolerance: fTol_Attempting = fTolerance return None, None
def Update(self): changed = False for ball in self.system.particles: if sc.escape_test(True): return None newGeos = [] deadGeos = [] for geo in self.geos: if geo is None: print "A geo was None" deadGeos.append(geo) if ball.union is None: print "A ball.union was None" continue resultBrep = rg.Brep.CreateBooleanDifference( geo, ball.union, sc.doc.ModelAbsoluteTolerance) if resultBrep: if len(resultBrep) != 0: ball.hit = True #ball.alive = False changed = True newGeos += resultBrep deadGeos.append(geo) else: deadGeos.append(geo) for deadGeo in deadGeos: if deadGeo in self.geos: self.geos.remove(deadGeo) for newGeo in newGeos: if newGeo not in self.geos: if newGeo: self.geos.append(newGeo) largestMass = None largestVol = None for geo in self.geos: v = rg.VolumeMassProperties.Compute(geo) if v > largestVol or largestVol is None: largestVol = v largestMass = geo self.geo = largestMass #Update Display if changed: for id in self.ids: sc.doc.Objects.Delete(id, True) for geo in self.geos: self.ids.append(sc.doc.Objects.AddBrep(geo, self.attr))
def drawTime(): FPS = 30 last_time = time.time() global t t = 0 curves = [] # whatever the loop is... while True: # draw animation t += 1 # pause so that the animation runs at 30 fps new_time = time.time() # see how many milliseconds we have to sleep for # then divide by 1000.0 since time.sleep() uses seconds sleep_time = ((1000.0 / FPS) - (new_time - last_time)) / 1000.0 if sleep_time > 0: time.sleep(sleep_time) last_time = new_time run() print t if t > 108: for k in pts: curves.append(rs.AddCurve(k.ptList)) rs.EnableRedraw(False) for crv in curves: rs.AddPipe(crv, [0,0.5,1], [4,1,4], cap=2) for ln in lns: rs.AddPipe(ln, 0, 1, cap=2) rs.EnableRedraw(True) break escape_test()
def Min3DBoundingBox(objs, init_plane, count, rel_stop, im_rep): #for non-planar or non-coplanar object(s) #get initial fast bb in init plane (World XY), plus volume to compare curr_bb = BoundingBoxPlane(objs, init_plane, False) curr_vol = curr_bb.Volume tot_ang = math.pi * 0.5 #90 degrees for intial octant factor = 0.1 #angle reduction factor for each successive refinement pass max_passes = 20 #safety factor prec = sc.doc.ModelDistanceDisplayPrecision us = rs.UnitSystemName(abbreviate=True) #run intitial bb calculation xyz_planes = GenerateOctantPlanes(count) best_plane, curr_bb, curr_vol = MinBBPlane(objs, init_plane, xyz_planes, curr_bb, curr_vol) #report results of intial rough calculation if im_rep: print "Initial pass 0, volume: {} {}3".format(round(curr_vol, prec), us) #refine with smaller angles around best fit plane, loop until... for i in range(max_passes): prev_vol = curr_vol #reduce angle by factor, use refinement planes to generate array tot_ang *= factor ref_planes = RotatePlaneArray3D(best_plane, tot_ang, count) best_plane, curr_bb, curr_vol = MinBBPlane(objs, best_plane, ref_planes, curr_bb, curr_vol) vol_diff = prev_vol - curr_vol #vol. diff. over last pass, should be positive or 0 #print "Volume difference from last pass: {}".format(vol_diff) #debug #check if difference is less than minimum "significant" #rel_stop==True: relative stop value <.01% difference from previous if rel_stop: if vol_diff < 0.0001 * prev_vol: break else: if vol_diff < sc.doc.ModelAbsoluteTolerance: break Rhino.RhinoApp.Wait() if im_rep: print "Refine pass {}, volume: {} {}3".format( i + 1, round(curr_vol, prec), us) #get out of loop if escape is pressed if sc.escape_test(False): print "Refinement aborted after {} passes.".format(i + 1) break return curr_bb, curr_vol, i + 1
def GetNestingSettings(self): # Parameters go = Rhino.Input.Custom.GetOption() go.SetCommandPrompt("OpenNest: Set nesting settings") optIterations = Rhino.Input.Custom.OptionInteger(1, 1, 100) #optSpacing = Rhino.Input.Custom.OptionDouble(0.01, 0.001, 1E10) optSpacing = Rhino.Input.Custom.OptionDouble(1.0, True, 0.001) optPlacement = Rhino.Input.Custom.OptionInteger(1, 0, 4) optTolerance = Rhino.Input.Custom.OptionDouble(0.1, 0.01, 10) optRotations = Rhino.Input.Custom.OptionInteger(4, 1, 360) optSeed = Rhino.Input.Custom.OptionInteger(0, 0, 100) optClosestObjects = Rhino.Input.Custom.OptionDouble(0.05, 0, 100) go.AddOptionInteger("Iterations", optIterations) go.AddOptionDouble("Spacing", optSpacing, "Spacing between sheets if only one is selected") go.AddOptionInteger("Placement", optPlacement, "Placement side to start nesting from") go.AddOptionDouble("Tolerance", optTolerance, "Gap size between nested parts") go.AddOptionInteger("Rotations", optRotations, "Number of rotation steps, use 1 for no rotation") go.AddOptionInteger("Seed", optSeed, "Random seed") go.AddOptionDouble("ClosestObjects", optClosestObjects) while True: if scriptcontext.escape_test(False): return False get_rc = go.Get() if go.CommandResult() != Rhino.Commands.Result.Success: break self.iterations = optIterations.CurrentValue self.spacing = optSpacing.CurrentValue self.placementType = optPlacement.CurrentValue self.tolerance = optTolerance.CurrentValue self.rotations = optRotations.CurrentValue self.seed = optSeed.CurrentValue #self.spacing *= (1 / tolerance) self.cp = optClosestObjects.CurrentValue print "optSpacing.CurrentValue = ", self.spacing return True
def RunCommand( is_interactive ): if sc.escape_test(False): print "script cancelled" #do something print "Selecting all blocks of same definition..." #******* Get blocks ***************** #************************************ objectIds = rs.GetObjects("Pick some blocks", 4096, preselect=True) if not objectIds: print "No objects" return False #pause viewport redraw rs.EnableRedraw(False) #******* Sort blocks by Name ******** #************************************ blockNames = [] for id in objectIds: blockName = rs.BlockInstanceName(id) if blockName not in blockNames: blockNames.append(blockName) #******* Get block instances by name ******** #******************************************** selIds = [] for name in blockNames: blockIds = rs.BlockInstances(name) selIds.extend(blockIds) #******* Select blocks ************** #************************************ rs.SelectObjects(selIds) rs.EnableRedraw(True) print "...aaand its done." #End RunCommand() #end sane return 0
def RunCommand(is_interactive): if sc.escape_test(False): print "script cancelled" #do something print "Selecting all blocks of same definition..." #******* Get blocks ***************** #************************************ objectIds = rs.GetObjects("Pick some blocks", 4096, preselect=True) if not objectIds: print "No objects" return False #pause viewport redraw rs.EnableRedraw(False) #******* Sort blocks by Name ******** #************************************ blockNames = [] for id in objectIds: blockName = rs.BlockInstanceName(id) if blockName not in blockNames: blockNames.append(blockName) #******* Get block instances by name ******** #******************************************** selIds = [] for name in blockNames: blockIds = rs.BlockInstances(name) selIds.extend(blockIds) #******* Select blocks ************** #************************************ rs.SelectObjects(selIds) rs.EnableRedraw(True) print "...aaand its done." #End RunCommand() #end sane return 0
def main(): #collect base points pointGUIDs = rs.GetObjects('select points to make agents', rs.filter.point) attractorGUIDs = rs.GetObjects('select points to make attractors', rs.filter.point) #define pipe length pipelength = rs.GetInteger('set the length of the pipe', 15) #set up the agent vec = [1, 1, 1] agentPopulation = [] for pointGUID in pointGUIDs: coord = rs.PointCoordinates(pointGUID) agentPopulation.append( Agent(coord, pointGUID, vec, pipelength)) #get the poins which draw lines #set up attractor magnitude = 10 attractorPopulation = [] for attractorGUID in attractorGUIDs: coord = rs.PointCoordinates(attractorGUID) attractorPopulation.append( Attractor(coord, attractorGUID, magnitude)) #get the list of attractor points #agentPopulation[0].test() #set up looped call while not sc.escape_test(): for agent in agentPopulation: agent.update(attractorPopulation) #continue the line
def Update(self): changed = False for ball in self.system.balls: if sc.escape_test(True): return None newGeos = [] deadGeos = [] for geo in self.geos: if geo is None: print "A geo was None" deadGeos.append(geo) if ball.union is None: print "A ball.union was None" continue resultBrep = rg.Brep.CreateBooleanDifference(geo, ball.union, sc.doc.ModelAbsoluteTolerance) if resultBrep: if len(resultBrep) != 0: changed = True newGeos += resultBrep deadGeos.append(geo) else: deadGeos.append(geo) for deadGeo in deadGeos: if deadGeo in self.geos: self.geos.remove(deadGeo) for newGeo in newGeos: if newGeo not in self.geos: if newGeo: self.geos.append(newGeo) #Update Display if changed: for id in self.ids: sc.doc.Objects.Delete(id, True) for geo in self.geos: self.ids.append(sc.doc.Objects.AddBrep(geo, self.attr))
def viewCapture(fileName, directory, viewNames, image_width, image_height, keepAspectRatio, saveAlpha): fullPathList = [] if saveAlpha == None: saveAlpha = False for viewName in viewNames: if viewName in rs.ViewNames(): rs.CurrentView(viewName, True) else: # change to RhinoDoc to get access to NamedViews sc.doc = rc.RhinoDoc.ActiveDoc namedViews = rs.NamedViews() if viewName in namedViews: viewName = rs.RestoreNamedView(viewName) else: viewName = None # change back to Grasshopper sc.doc = ghdoc viewName = rs.CurrentView(viewName, True) rs.CurrentView(viewName) sc.doc.Views.Find(viewName, False) viewtoCapture = sc.doc.Views.ActiveView try: dispMode = rc.Display.DisplayModeDescription.FindByName( dispModeStr) sc.doc.Views.ActiveView.ActiveViewport.DisplayMode = dispMode except: pass if image_height == None: image_h = viewtoCapture.ActiveViewport.Size.Height else: image_h = image_height if image_width == None: image_w = viewtoCapture.ActiveViewport.Size.Width else: image_w = image_width # aspectRatio if keepAspectRatio: if image_height == None and image_width != None: image_h = image_h * (image_w / viewtoCapture.ActiveViewport.Size.Width) elif image_height != None and image_width == None: image_w = image_w * (image_h / viewtoCapture.ActiveViewport.Size.Height) fullPath = os.path.join(directory, fileName + '_' + viewName + '.png') fullPathList.append(fullPath) # Set the image size rc.RhinoDoc.ActiveDoc.RenderSettings.UseViewportSize = False viewSize = System.Drawing.Size(int(image_w), int(image_h)) rc.RhinoDoc.ActiveDoc.RenderSettings.ImageSize = viewSize try: VRayForRhinoNETInterface.VRayInterface.SetRenderOutputSize( int(image_w), int(image_h)) except: pass print "Image dimensions set to (" + str(int(image_w)) + "x" + str( int(image_h)) + ")" # Render the image and save it. try: # V-Ray is the renderer. VRayForRhinoNETInterface.VRayInterface.HasRenderFinished() rs.Command("!_Render", echo=False) print "Rendering " + viewName + "..." while not VRayForRhinoNETInterface.VRayInterface.HasRenderFinished( ): if sc.escape_test(False): print("Rendering cancelled") rs.Command("_CloseRenderWindow", echo=False) rs.GetPlugInObject("V-Ray for Rhino").SetBatchRenderOn( True) vray.CancelRender() rs.GetPlugInObject("V-Ray for Rhino").SetBatchRenderOn( False) esc = True break rs.Sleep(10) rs.Command("_-SaveRenderWindowAs \"" + directory + "\\" + fileName + '_' + viewName + ".png\"") rs.Command( "_-CloseRenderWindow" ) #close the rendered window when in saving mode to avoid stacking a series of renderWindows when running on Rhino renderer. if saveAlpha == False: try: alphaPath = os.path.join( directory, fileName + '_' + viewName + '.Alpha.png') os.remove(alphaPath) except: pass except: if renderTime_ != None: # V-Ray is probably the renderer. start = time.clock() rs.Command("!_Render", echo=False) print "Rendering " + viewName + "..." while float(time.clock() - start) < renderTime_: rs.Sleep(10) rs.Command("_-SaveRenderWindowAs \"" + directory + "\\" + fileName + '_' + viewName + ".jpeg\"") rs.Command( "_-CloseRenderWindow" ) #close the rendered window when in saving mode to avoid stacking a series of renderWindows when running on Rhino renderer. if saveAlpha == False: try: alphaPath = os.path.join( directory, fileName + '_' + viewName + '.Alpha.jpeg') os.remove(alphaPath) except: pass else: # Hopefully Rhino is the renderer. print "Rendering " + viewName + "..." rs.Command("!_render") rs.Command("_-SaveRenderWindowAs \"" + directory + "\\" + fileName + '_' + viewName + ".png\"") rs.Command( "_-CloseRenderWindow" ) #close the rendered window when in saving mode to avoid stacking a series of renderWindows when running on Rhino renderer. return fullPathList
def RunCommand( is_interactive ): if sc.escape_test(False): print "script cancelled" #do something print "Resetting..." #******* Get blocks ***********''**** #************************************ objectIds = rs.GetObjects("Pick some blocks", 4096, preselect=True) if not objectIds: print "No objects" return False rs.EnableRedraw(False) #******* Ref Geometry *************** #************************************ points = [ G.Point3d(0,0,0), G.Point3d(1,0,0), G.Point3d(0,1,0), G.Point3d(0,0,1) ] #gather all new objects when done finalObjs = [] for id in objectIds: #Get the block transformation matrix and name blockXForm = rs.BlockInstanceXform(id) blockName = rs.BlockInstanceName(id) #Add reference geometry pts = G.Polyline(points) #Apply block transformation matrix to ref geometry pts.Transform(blockXForm) #create final plane finalOrigin = pts[1] finalXaxis = rs.VectorSubtract( pts[1], pts[0] ) finalYaxis = rs.VectorSubtract( pts[2], pts[0] ) finalPlane = G.Plane(finalOrigin, finalXaxis, finalYaxis) #create scaling factors xFac = 1 / rs.Distance(pts[1],pts[0]) yFac = 1 / rs.Distance(pts[2],pts[0]) zFac = 1 / rs.Distance(pts[3],pts[0]) #Scale block newXForm = G.Transform.Scale(finalPlane, xFac, yFac, zFac) rs.TransformObject(id,newXForm) #Select all new objects rs.SelectObjects(objectIds) rs.EnableRedraw(True) print "...aaand its done." #End RunCommand() #end sane return 0
def getMatches(objref_toMatch, **kwargs): """ """ def setOpt(key, value=None): if key in kwargs: return kwargs[key] elif key in Opts.riOpts: return Opts.riOpts[key].InitialValue else: return value sAttr = setOpt('sAttr') fFloatTol = setOpt('fFloatTol') bEcho = setOpt('bEcho') bDebug = setOpt('bDebug') objref0 = objref_toMatch bToMatch_IsExtrusion = bool(objref0.Surface()) if sAttr == "Colour": rdRhObj0 = objref0.Object() if rdRhObj0.Attributes.ColorSource == rd.ObjectColorSource.ColorFromMaterial: print "Colour from material not supported yet." return elif rdRhObj0.Attributes.ColorSource == rd.ObjectColorSource.ColorFromObject: colorRhObj0 = rdRhObj0.Attributes.ObjectColor else: if rdRhObj0.Attributes.ColorSource == rd.ObjectColorSource.ColorFromLayer: pass else: # Color from parent. # Use layer color unless object is within a block definition. pass li = rdRhObj0.Attributes.LayerIndex layer = sc.doc.Layers.FindIndex(li) colorRhObj0 = layer.Color elif sAttr == 'Volume': rgBrep0 = objref0.Brep( ) # Brep is also returned when objref0 contains an Extrusion. if not rgBrep0.IsValid: print "Reference {} {} is invalid. Repair it then rerun this script.".format( "Extrusion" if bToMatch_IsExtrusion else "Brep", objref0.ObjectId) rgBrep0.Dispose() return if not rgBrep0.IsSolid: print "Reference {} {} is open. Its 'Volume' will not be matched.".format( "Extrusion" if bToMatch_IsExtrusion else "Brep", objref0.ObjectId) rgBrep0.Dispose() return fVol0 = rgBrep0.GetVolume() if not fVol0: print "Volume can not be calculated. Repair {} {}.".format( "Extrusion" if bToMatch_IsExtrusion else "Brep", objref0.ObjectId) rgBrep0.Dispose() return iToMatch_FaceCt = rgBrep0.Faces.Count rgBrep0.Dispose() gBreps_ToSearch = [] rgBreps_ToSearch = [] iCts_Faces_ToSearch = [] fEdgeLens_ToSearch = [] iter = rd.ObjectEnumeratorSettings() iter.NormalObjects = True iter.LockedObjects = False iter.IncludeLights = False iter.IncludeGrips = False iter.ObjectTypeFilter = rd.ObjectType.Brep | rd.ObjectType.Extrusion gBreps_MatchesFound = [] # Also can include Extrusions. iBrepExtrCt = 0 for rdObj in sc.doc.Objects.GetObjectList(iter): iBrepExtrCt += 1 iOpenBrepCt = 0 idxs_AtTenths = [int(round(0.1 * i * iBrepExtrCt, 0)) for i in range(10)] for i, rdRhObjX in enumerate(sc.doc.Objects.GetObjectList(iter)): if sc.escape_test(throw_exception=False): print "*** Analysis interrupted by user." \ " Selected breps/extrusions are of partial results." return gBreps_MatchesFound if rdRhObjX.Id == objref0.ObjectId: continue if iBrepExtrCt > 10: if i in idxs_AtTenths: Rhino.RhinoApp.SetCommandPrompt( "Analysis at {:d}% of {} breps/extrusions ...".format( int(100.0 * (i + 1) / iBrepExtrCt), iBrepExtrCt)) elif iBrepExtrCt > 1: Rhino.RhinoApp.SetCommandPrompt( "Analysis at {} of {} breps/extrusions".format( i + 1, iBrepExtrCt)) else: Rhino.RhinoApp.SetCommandPrompt( "Analyzing other brep/extrusion ...") if sAttr == 'Colour': if rdRhObjX.Attributes.ColorSource == rd.ObjectColorSource.ColorFromObject: colorRhObjX = rdRhObjX.Attributes.ObjectColor elif rdRhObjX.Attributes.ColorSource == rd.ObjectColorSource.ColorFromMaterial: print "Colour from material not supported yet." return else: if rdRhObjX.Attributes.ColorSource == rd.ObjectColorSource.ColorFromLayer: pass else: # Color from parent. # Use layer color unless object is within a block definition. pass li = rdRhObjX.Attributes.LayerIndex layer = sc.doc.Layers.FindIndex(li) colorRhObjX = layer.Color if colorRhObjX == colorRhObj0: gBreps_MatchesFound.append(rdRhObjX.Id) elif sAttr == 'Name': if rdRhObjX.Attributes.Name == objref0.Object().Attributes.Name: gBreps_MatchesFound.append(rdRhObjX.Id) elif sAttr == 'Layer': if rdRhObjX.Attributes.LayerIndex == objref0.Object( ).Attributes.LayerIndex: gBreps_MatchesFound.append(rdRhObjX.Id) elif sAttr == 'Volume': bToCheck_IsExtrusion = isinstance(rdRhObjX, rd.ExtrusionObject) rgGeomX = rdRhObjX.Geometry if not rgGeomX.IsValid: print "{} {} is invalid. Fix first.".format( rdRhObjX.GetType().Name, rdRhObjX.Id) rgGeomX.Dispose() continue if bToCheck_IsExtrusion: rgBrepX = rgGeomX.ToBrep(splitKinkyFaces=True) rgGeomX.Dispose() else: rgBrepX = rgGeomX if not rgBrepX.IsSolid: iOpenBrepCt += 1 rgBrepX.Dispose() continue ## This significantly speeds up the analysis. #if rdRhObjX.ObjectType == rd.ObjectType.Brep: # if rgBrepX.Faces.Count != iToMatch_FaceCt: # rgBrepX.Dispose() # continue fVol = rgBrepX.GetVolume( ) # GetVolume may be faster than VolumeMassProperties.Compute. if not fVol: print "Volume can not be calculated. Repair {} {}.".format( rdRhObjX.GetType().Name, rdRhObjX.Id) rgBrepX.Dispose() continue rgBrepX.Dispose() fVolDiff = abs(fVol - fVol0) if bDebug: print "Volume:", fVol0, fVolDiff if fVolDiff > fFloatTol: continue gBreps_MatchesFound.append(rdRhObjX.Id) if sAttr == 'Volume': if iOpenBrepCt: print "{} open breps skipped for volume matching.".format( iOpenBrepCt) else: print "No open breps are present." return gBreps_MatchesFound
def viewCapture(fileName, directory, viewNames, image_width, image_height, keepAspectRatio, saveAlpha): fullPathList = [] if saveAlpha == None: saveAlpha = False for viewName in viewNames: if viewName in rs.ViewNames(): rs.CurrentView(viewName, True) else: # change to RhinoDoc to get access to NamedViews sc.doc = rc.RhinoDoc.ActiveDoc namedViews = rs.NamedViews() if viewName in namedViews: viewName = rs.RestoreNamedView(viewName) else: viewName = None # change back to Grasshopper sc.doc = ghdoc viewName = rs.CurrentView(viewName, True) rs.CurrentView(viewName) sc.doc.Views.Find(viewName, False) viewtoCapture = sc.doc.Views.ActiveView try: dispMode = rc.Display.DisplayModeDescription.FindByName(dispModeStr) sc.doc.Views.ActiveView.ActiveViewport.DisplayMode = dispMode except: pass if image_height == None: image_h = viewtoCapture.ActiveViewport.Size.Height else: image_h = image_height if image_width == None: image_w = viewtoCapture.ActiveViewport.Size.Width else: image_w = image_width # aspectRatio if keepAspectRatio: if image_height == None and image_width != None: image_h = image_h * (image_w/viewtoCapture.ActiveViewport.Size.Width) elif image_height != None and image_width == None: image_w = image_w * (image_h/viewtoCapture.ActiveViewport.Size.Height) fullPath = os.path.join(directory, fileName +'_'+ viewName + '.png') fullPathList.append(fullPath) # Set the image size rc.RhinoDoc.ActiveDoc.RenderSettings.UseViewportSize = False viewSize = System.Drawing.Size(int(image_w), int(image_h)) rc.RhinoDoc.ActiveDoc.RenderSettings.ImageSize = viewSize try: VRayForRhinoNETInterface.VRayInterface.SetRenderOutputSize(int(image_w), int(image_h)) except: pass print "Image dimensions set to (" + str(int(image_w)) + "x" + str(int(image_h)) + ")" # Render the image and save it. try: # V-Ray is the renderer. VRayForRhinoNETInterface.VRayInterface.HasRenderFinished() rs.Command("!_Render", echo=False) print "Rendering " + viewName + "..." while not VRayForRhinoNETInterface.VRayInterface.HasRenderFinished(): if sc.escape_test(False): print ("Rendering cancelled") rs.Command("_CloseRenderWindow", echo=False) rs.GetPlugInObject("V-Ray for Rhino").SetBatchRenderOn(True) vray.CancelRender() rs.GetPlugInObject("V-Ray for Rhino").SetBatchRenderOn(False) esc = True break rs.Sleep(10) rs.Command("_-SaveRenderWindowAs \"" + directory + "\\" + fileName +'_'+ viewName + ".png\"") rs.Command ("_-CloseRenderWindow") #close the rendered window when in saving mode to avoid stacking a series of renderWindows when running on Rhino renderer. if saveAlpha == False: try: alphaPath = os.path.join(directory, fileName +'_'+ viewName + '.Alpha.png') os.remove(alphaPath) except: pass except: # Rhino is the renderer. print "Rendering " + viewName + "..." rs.Command("!_render") rs.Command("_-SaveRenderWindowAs \"" + directory + "\\" + fileName +'_'+ viewName + ".png\"") rs.Command ("_-CloseRenderWindow") #close the rendered window when in saving mode to avoid stacking a series of renderWindows when running on Rhino renderer. return fullPathList
def RunCommand(is_interactive): if sc.escape_test(False): print "script cancelled" #do something print "Making unique..." #******* Get blocks ***************** #************************************ objectIds = rs.GetObjects("Pick some blocks", 4096, preselect=True) if not objectIds: print "No objects" return False #pause viewport redraw rs.EnableRedraw(False) #******* Sort blocks by type ******** #************************************ blockTypes = {} for id in objectIds: blockName = rs.BlockInstanceName(id) if blockName not in blockTypes: blockTypes[blockName] = [] blockTypes[blockName].append(id) #***** Define new block and add ***** #************************************ #Get block names blockNames = rs.BlockNames() #gather all new objects when done finalObjs = [] for blockType in blockTypes: for id in blockTypes[blockType]: #Get the block transformation matrix and name blockXForm = rs.BlockInstanceXform(id) blockName = rs.BlockInstanceName(id) #Insert new block in 0,0,0 newBlock = rs.InsertBlock(blockName, [0, 0, 0]) #Explode the block exObjs = rs.ExplodeBlockInstance(newBlock) #create new block name # if the string ends in digits m will be a Match object, or None otherwise. strippedName = re.sub(r'#[0-9]+$', '', blockName) #test if block name exist and add to the end number if true. x = 0 tryAgain = True while tryAgain: x += 1 newerBlockName = strippedName + "#" + str(x) if newerBlockName not in blockNames: tryAgain = False break #insert exObjs as new block rs.AddBlock(exObjs, [0, 0, 0], newerBlockName, delete_input=True) newerBlock = rs.InsertBlock(newerBlockName, [0, 0, 0]) #match properties from original rs.MatchObjectAttributes(newerBlock, id) #transform new block rs.TransformObject(newerBlock, blockXForm) #append for final selection finalObjs.append(newerBlock) #add name to list of used blocknames. blockNames.append(newerBlockName) #Delete original block rs.DeleteObjects(objectIds) #Select all new objects rs.SelectObjects(finalObjs) rs.EnableRedraw(True) print "...aaand its done." #End RunCommand() #end sane return 0
def AStarPathFinder(self): """ paramters: start (node): end (node): returns: Bool (success or failure) list (nodes visited) (use the .pos to get the rhino point) """ openSet = [self.start] closedSet = [] path = [] searching = True while searching: if sc.escape_test(True): return if len(openSet) > 0: #Choose tile with lowest f score lowestTile = openSet[0] for tile in openSet: if tile is lowestTile: continue if tile.f < lowestTile.f or lowestTile is None: lowestTile = tile current = lowestTile path = [] temp = current path.append(temp) while temp.previous: path.append(temp.previous) temp = temp.previous #Check if at the end if current is self.end: searching = False break #Move current tile from open to closed set openSet.remove(current) closedSet.append(current) #Check all the neighbors for neighbor in current.neighbors: #if neighbor.type == 0: continue #Use this if nodes are blocked if neighbor not in closedSet: tempG = current.g + rs.Distance(current.pos, neighbor.pos) #Is this a better path? if neighbor not in openSet: openSet.append(neighbor) elif tempG >= neighbor.g: #It is not a better path continue neighbor.previous = current neighbor.g = tempG neighbor.h = rs.Distance(current.pos, self.end.pos) neighbor.f = neighbor.g + neighbor.h else: #print "No Solution" return False, None return True, path
def main(): cfg = setup() rs.CurrentView(cfg['view'].ActiveViewportID) # MAIN LOOP msg0 = "{} views at {} zoom levels across {} xforms of {} objects.".format( cfg['view_count'], len(cfg['obj_bbox_pads']), cfg['xform_count'], len(cfg['groups_info'])) msg1 = "{} images will result.".format(cfg['total_image_count']) print(msg0) print(msg1) if rs.MessageBox( "This script will plot {}\n{}\nThe folder {} has been created for this purpose.\nShall we proceed?" .format(msg0, msg1, cfg['pth_save']), 4, "Ready to plot {} images?".format(cfg['total_image_count'])) != 6: teardown(cfg) exit() cfg['tmp_obj_ids'] = False cfg['rot_group'] = False cfg['tot_rot'] = False try: #raise Exception("nope") for g, group_info in enumerate(cfg['groups_info']): print("##### {} ({} of {})".format(group_info['name'].lower(), g + 1, len(cfg['groups_info']))) #print("{} objects in this group".format(len(group_info['obj_ids']))) #set_camera(group_info['bbox'], cfg) isolate_group(g, cfg) deg = 360.0 / cfg['view_count'] rxf = rs.XformRotation2(deg, (0, 0, 1), group_info['bbox'].Center) cfg['rot_group'] = group_info cfg['tot_rot'] = 0 for r in range(cfg['view_count']): for x, xf in enumerate( xforms_to_apply(group_info['bbox'], cfg, DEBUG)): all_layers_on(cfg) cfg['tmp_obj_ids'] = apply_xf( xf, group_info['obj_ids']) # apply this transformation rs.RemoveObjectsFromGroup(cfg['tmp_obj_ids'], group_info['name']) rs.HideGroup(group_info['name']) for p, pad in enumerate(cfg['obj_bbox_pads']): xbbox = bbox_of_objects(cfg['tmp_obj_ids']) set_camera(xbbox, pad, cfg) name = "{}_r{:03}_x{:02}_p{:02}_{}".format( group_info['name'].lower(), r, x, p, cfg['layer_info']['parent'].Name.lower()) is_first = (r == 0 and x == 0) do_capture(name, is_first, cfg) # capture view isolate_group(g, cfg) all_layers_on(cfg) rs.DeleteObjects(cfg['tmp_obj_ids']) cfg['tmp_obj_ids'] = False Rhino.RhinoApp.Wait() if (sc.escape_test(False)): raise Exception('Esc key caught in main()') rs.TransformObjects(group_info['obj_ids'], rxf) cfg['tot_rot'] += deg cfg['rot_group'] = False cfg['tot_rot'] = 0 except Exception as e: print("!!!! SCRIPT STOPPED !!!!") print e exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) finally: teardown(cfg)
def main(): skNum = (datetime.date.today() - datetime.date(2020, 03, 29)).days + 201 if int(skNum) > int(os.path.splitext(os.path.basename(__file__))[0]): print "!!!!SAVE THE SKETCH WITH A NEW NAME!!!!" rs.UnselectAllObjects() init_time = time.time() version = 'a' anim = mp4.Animation( os.path.splitext(os.path.basename(__file__))[0] + version) numFrames = 150 numPasses = 100 anim.fps = 30 td = TempDisplay() display = HUD(os.path.splitext(os.path.basename(__file__))[0], numFrames) s = Scene() ################################ #SETUP targets = [] vSystems = [] for i in range(5): targets.append(geo.Particle(geo.RandomPoint(), geo.RandomVector3d(5))) targets[-1].radius = 5 for i in range(5): print(i * .05) + .3 vSystems.append(VoxelSystem(targets, i * .05 + .3)) ################################ for i in range(numFrames): start_time = time.time() print "Frame {}".format(i) if sc.escape_test(False): anim.Cleanup() return ################################ #MAIN LOOP for target in targets: target.Update() for vSystem in vSystems: vSystem.Update() vSystem.UpdateDisplay() ################################ #HUD #display.UpdateParam1('boxes: ' + str(len(bSystem.boxes))) #display.UpdateParam2('links: ' + str(len(bSystem.links))) #display.UpdateParam3('z: ' + str(ball.pos.Z)) display.UpdateScaleBar() ################################ sc.doc.Views.Redraw() display.Update(i) anim.AddFrame(numberOfPasses=numPasses) rs.Sleep(500) ################################ #Framerate frameTime = time.time() - start_time timeLeft = (numFrames - i) * frameTime timeLeftStr = str(datetime.timedelta(seconds=timeLeft)) print "Time remaining: {}".format(timeLeftStr) frameTime = time.time() - init_time timeLeftStr = str(datetime.timedelta(seconds=frameTime)) print "Total Time: {}".format(timeLeftStr) if int(skNum) > int(os.path.splitext(os.path.basename(__file__))[0]): print "!!!!SAVE THE SKETCH WITH A NEW NAME!!!!" if os.path.isdir( r"D:\Files\Work\LIBRARY\06_RHINO\10_Python\300 DAYS\anim"): anim.Create(r"D:\Files\Work\LIBRARY\06_RHINO\10_Python\300 DAYS\anim", frames2Keep=[i / 2, i - 1]) else: anim.Create(r"C:\Tim\300 Days\anim", frames2Keep=[i / 2, i - 1])
def main(): skNum = (datetime.date.today() - datetime.date(2020, 03, 29)).days + 201 if int(skNum) > int(os.path.splitext(os.path.basename(__file__))[0]): print "!!!!SAVE THE SKETCH WITH A NEW NAME!!!!" rs.UnselectAllObjects() init_time = time.time() version = 'a' anim = mp4.Animation( os.path.splitext(os.path.basename(__file__))[0] + version) numFrames = 150 numPasses = 100 anim.fps = 30 td = TempDisplay() display = HUD(os.path.splitext(os.path.basename(__file__))[0], numFrames) s = Scene() ################################ #SETUP pt = rg.Point3d(10, 50, 70) vec = rg.Vector3d(0, -10, 10) plane = rg.Plane(pt, vec) xint = rg.Interval(0, 80) yint = rg.Interval(0, 80) zint = rg.Interval(0, 40) xcount = 50 ycount = 50 zcount = 20 box = rg.Box(plane, xint, yint, zint) #m = rg.Mesh.CreateFromBox(box, xcount, ycount, zcount) m = rg.Mesh.CreateFromPlane(plane, xint, yint, xcount, ycount) mObj = vSystem(m) ################################ for i in range(numFrames): start_time = time.time() print "Frame {}".format(i) if sc.escape_test(False): anim.Cleanup() return ################################ #MAIN LOOP if i % 5 == 0: mObj.Update() mObj.UpdateDisplay() ################################ #HUD #display.UpdateParam1('boxes: ' + str(len(bSystem.boxes))) #display.UpdateParam2('links: ' + str(len(bSystem.links))) #display.UpdateParam3('z: ' + str(ball.pos.Z)) display.UpdateScaleBar() ################################ sc.doc.Views.Redraw() display.Update(i) anim.AddFrame(numberOfPasses=numPasses) rs.Sleep(500) ################################ #Framerate frameTime = time.time() - start_time timeLeft = (numFrames - i) * frameTime timeLeftStr = str(datetime.timedelta(seconds=timeLeft)) print "Time remaining: {}".format(timeLeftStr) frameTime = time.time() - init_time timeLeftStr = str(datetime.timedelta(seconds=frameTime)) print "Total Time: {}".format(timeLeftStr) if int(skNum) > int(os.path.splitext(os.path.basename(__file__))[0]): print "!!!!SAVE THE SKETCH WITH A NEW NAME!!!!" if os.path.isdir( r"D:\Files\Work\LIBRARY\06_RHINO\10_Python\300 DAYS\anim"): anim.Create(r"D:\Files\Work\LIBRARY\06_RHINO\10_Python\300 DAYS\anim", frames2Keep=[i / 2, i - 1]) else: anim.Create(r"C:\Tim\300 Days\anim", frames2Keep=[i / 2, i - 1])
def meshDLA_MAIN(): """GET MESH""" filter = Rhino.DocObjects.ObjectType.Mesh rc, objRef = Rhino.Input.RhinoGet.GetOneObject("select seedMesh", False, filter) if not objRef or rc != Rhino.Commands.Result.Success: return rc mesh = objRef.Mesh() if not mesh: return mesh.Compact() """GET POLYSRF BOX filter = Rhino.DocObjects.ObjectType.PolysrfFilter rc, boxRef = Rhino.Input.RhinoGet.GetOneObject("select boundingBox (polySrf)",False,filter) if not boxRef or rc!=Rhino.Commands.Result.Success: return rc #scriptcontext.doc.Objects.Hide(boxRef,True) """ areaMassProps = Rhino.Geometry.AreaMassProperties.Compute(mesh) centroid = areaMassProps.Centroid centroid.Z += 2.3 rs.ViewTarget(view=None, target=centroid) showParticles = True showWorld = False debugTime = False saveLineage = False spin = False pRadius = 0.5 stepRatio = 0.5 speed = pRadius * stepRatio # relate to pRadius and some other len?? nParticles = 50 if debugTime: timeSteps = 50 else: timeSteps = 1000 ratioMaxMinEdgeLen = 0.33 thresMult = 5 alpha = 2 beta = 6 gravFactor = 1 peakInclination = gravFactor * math.pi gStepSize = 0.01 maxGrowLen = 0.25 minGrowLen = 0.001 cutoffDist = 1 nSave = 10 tsSave = timeSteps / nSave threshDist = pRadius * thresMult """INITIALIZE WORLD, CORAL""" world = World(mesh) if not showWorld: world.hide() coral = Coral(objRef, mesh, ratioMaxMinEdgeLen) world.resize(coral, threshDist) world.getSpawnPlane() world.reDraw() """save param string""" paramStr = ( "\nPARAMS_______________" + "\npRadius: %1.2fin." % pRadius + "\nstepRatio: %1.2f" % stepRatio + "\nnParticles: %d" % nParticles + "\ntimeSteps: %d" % timeSteps + "\nmaxEdgeLen: %1.2f" % coral.maxEdgeLength + "\nminEdgeLen: %1.2f" % coral.minEdgeLen + " (max/minEdgeLen: %.2f)" % ratioMaxMinEdgeLen + "\nthreshMult: %1.1f" % thresMult + "\nmaxGrowLen: %.2fin." % maxGrowLen + "\nminGrowLen: %.2fin." % minGrowLen + "\ncutoffDist: %1.1fin." % cutoffDist + "\nused TrianglularDist" + "\ngravFactor: %.2f" % gravFactor + "\nnSave: %d" % nSave ) # "\nbetaDist: a=%d, b=%d" %(alpha,beta) +\ print "INPUT PARAMS________________________" print "pRadius = %1.2fin." % pRadius print "nParticles = " + str(nParticles) peakIncDeg = peakInclination * 180.0 / math.pi print "peakInclination = %1.1fdeg" % peakIncDeg print "timeSteps(ts) = " + str(timeSteps) print "speed = %0.2f in./ts" % speed print " maxGrowLen = %1.2fin." % maxGrowLen print " minGrowLen = %1.2fin." % minGrowLen print " cutoffDist = %1.2fin." % cutoffDist print "maxEdgeLength(Avg) = %0.2f in." % coral.maxEdgeLength print "minEdgeLen = %0.2f in." % coral.minEdgeLen print "thresMult = " + str(thresMult) print "____________________________________" gKernel = GKernel(gStepSize, maxGrowLen, minGrowLen, cutoffDist) # gKernel.plot() particles = [] growVerts = set() prevHighestPoint = 0 highestPoint = 0 """INITIALIZE PARTICLES""" for i in range(nParticles): p = Particle(pRadius) p.setToSpawnLoc(world) if showParticles: p.drawParticle(i) particles.append(p) """RUN SIMIULATION""" ts = 0 for t in range(timeSteps): if spin: rs.RotateView(angle=1.0) ts += 1 if ts >= tsSave: # print "time:%d"%timeSteps if saveLineage: coral.saveToLineage(t) ts = 0 # time.sleep(0.3) Rhino.RhinoApp.Wait() scriptcontext.escape_test() """MOVE PARTICLES""" for i in range(len(particles)): p = particles[i] # boundChecks occur within moveParticle() p.moveParticle(speed, alpha, beta, peakInclination, world) if showParticles: p.clearParticle(), p.drawParticle(i) """SEARCH FOR INTERSECTIONS""" centerVerts = coral.verticesThatAte(world, particles) """GROW REGIONS AROUND CENTERVERTS""" growVerts = coral.getGrowData(gKernel, centerVerts) coral.grow(growVerts) """SUBDIVIDE LONG EDGES""" coral.subdivideLongEdges() """COLLAPSE SHORT EDGES""" didCollapse = coral.collapseShortEdges() """UPDATE MESH""" coral.updateNormals() coral.mesh.Weld(math.pi) coral.setNakedVerts() """UPDATE CORAL AND WORLD """ coral.reDraw() # coral.colorVerts(growVerts,gKernel) world.resize(coral, threshDist) world.getSpawnPlane() if showWorld: world.reDraw() # displayGrowNormals(mesh,growLength) if saveLineage: coral.packLineage(paramStr) if not rs.SetUserText(coral.objRef.ObjectId, "params", paramStr, True): print "SetUserText failed"
def tryGetRoundPrimitive(rgSrf0, bCylinder=True, bCone=True, bSphere=True, bTorus=True, fTolerance=1e-9, bDebug=False): """ Updated in May of 2019. Returns a tuple: On success: (rg.Cone, Cylinder, Sphere, or Torus instance), (float: tolerance actually used to obtain shape) On fail: None, None Tolerance up to fTolerance parameter is first tested for a Cylinder Then the other 3 shapes are tested together each tolerance trial at a time. """ if fTolerance <= 0.0: return None, None elif fTolerance < 1e-12: fTolerance = 1e-12 if isinstance(rgSrf0, rg.BrepFace): rgSrf0 = rgSrf0.UnderlyingSurface() if isinstance(rgSrf0, rg.NurbsSurface): rgNurbsSrf1 = rgSrf0.Duplicate() else: rgNurbsSrf1 = rgSrf0.ToNurbsSurface() bConeSkipped = False bSphereSkipped = False bTorusSkipped = False # Start tolerance to use at a low value and iterate up to input tolerance. fTol_Attempting = fTolerance if fTolerance < 1e-9 else 1e-9 # Cylinder has preference, so all tolerances will be iterated, trying for that shape. if bCylinder: while fTol_Attempting <= fTolerance: sc.escape_test() b, cylinder = rgNurbsSrf1.TryGetCylinder(fTol_Attempting) if b: if Cylinder.isSizeAcceptable(cylinder, bDebug=bDebug): rgNurbsSrf1.Dispose() return cylinder, fTol_Attempting else: break if fTol_Attempting == fTolerance: break fTol_Attempting *= 10.0 if fTol_Attempting > fTolerance: fTol_Attempting = fTolerance fTol_Attempting = fTolerance if fTolerance < 1e-9 else 1e-9 while fTol_Attempting <= fTolerance: sc.escape_test() if not bConeSkipped: if bCone: b, cone = rgNurbsSrf1.TryGetCone(fTol_Attempting) if b: for pt in (rgNurbsSrf1.PointAt( rgNurbsSrf1.Domain(0).T0, rgNurbsSrf1.Domain(1).T0), rgNurbsSrf1.PointAt( rgNurbsSrf1.Domain(0).T1, rgNurbsSrf1.Domain(1).T1)): rc = Cone.isSizeAcceptableAtPoint(cone, point=pt, bDebug=bDebug) if rc is None: continue elif rc is False: bConeSkipped = True break else: # Size is acceptable. rgNurbsSrf1.Dispose() return cone, fTol_Attempting if not bSphereSkipped: if bSphere: b, sphere = rgNurbsSrf1.TryGetSphere(fTol_Attempting) if b: if Sphere.isSizeAcceptable(sphere, bDebug=bDebug): rgNurbsSrf1.Dispose() return sphere, fTol_Attempting else: bSphereSkipped = True if not bTorusSkipped: if bTorus: b, torus = rgNurbsSrf1.TryGetTorus(fTol_Attempting) if b: if Torus.isSizeAcceptable(torus, bDebug=bDebug): rgNurbsSrf1.Dispose() return torus, fTol_Attempting else: bTorusSkipped = True if fTol_Attempting == fTolerance: rgNurbsSrf1.Dispose() return None, None fTol_Attempting *= 10.0 if fTol_Attempting > fTolerance: fTol_Attempting = fTolerance
def getPrimitiveShapedFaces(rgFaceA, rgPrimitiveShapeA=None, idx_rgFaces_Filter=None, fTolerance=1e-9, bDebug=False): rgBrep0 = rgFaceA.Brep idx_rgFaceA = rgFaceA.FaceIndex if rgPrimitiveShapeA is None: rc = xPrimitiveShape.BrepFace.tryGetPrimitiveShape( rgFace0=rgFaceA, fTolerance=fTolerance, bDebug=bDebug) if rc[0] is None: return rgPrimitiveShapeA = rc[0][0] bPlane = bCylinder = bCone = bSphere = bTorus = False if isinstance(rgPrimitiveShapeA, rg.Plane): bPlane = True elif isinstance(rgPrimitiveShapeA, rg.Cylinder): bCylinder = True elif isinstance(rgPrimitiveShapeA, rg.Cone): bCone = True elif isinstance(rgPrimitiveShapeA, rg.Sphere): bSphere = True elif isinstance(rgPrimitiveShapeA, rg.Torus): bTorus = True idxFaces_Pass = [idx_rgFaceA] # Find matching shapes of adjacent faces. idxFaces_Pass = [idx_rgFaceA] idxFaces_Fail = [] idxFaces_LastAdded = [idx_rgFaceA] for idxFace_LastAdded in idxFaces_LastAdded: sc.escape_test() for idx_Face_Adj in rgBrep0.Faces[idxFace_LastAdded].AdjacentFaces(): if idx_rgFaces_Filter and idx_Face_Adj not in idx_rgFaces_Filter: continue elif idx_Face_Adj in idxFaces_Pass: continue elif idx_Face_Adj in idxFaces_Fail: continue rgFaceB = rgBrep0.Faces[idx_Face_Adj] rc = xPrimitiveShape.BrepFace.tryGetPrimitiveShape( rgFace0=rgFaceB, bPlane=bPlane, bCylinder=bCylinder, bCone=bCone, bSphere=bSphere, bTorus=bTorus, fTolerance=fTolerance, bDebug=bDebug) if rc[0] is None: idxFaces_Fail.append(idx_Face_Adj) continue shapeB = rc[0][0] if xPrimitiveShape.AnyShape.areEqual( [rgPrimitiveShapeA, shapeB], epsilon=fTolerance, bDebug=bDebug ): idxFaces_Pass.append(idx_Face_Adj) idxFaces_LastAdded.append(idx_Face_Adj) else: idxFaces_Fail.append(idx_Face_Adj) return idxFaces_Pass