def viewCapture(fileName, directory, viewNames, image_width, image_height, dispModeStr, keepAspectRatio): 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) viewSize = System.Drawing.Size(int(image_w), int(image_h)) pic = rc.Display.RhinoView.CaptureToBitmap(viewtoCapture , viewSize) fullPath = os.path.join(directory, fileName +'_'+ viewName + '.png') try: System.Drawing.Bitmap.Save(pic , fullPath) except: try: fullPath = os.path.join(directory, fileName +'_'+ viewName + '_1.png') System.Drawing.Bitmap.Save(pic , fullPath) except: print "Failed!" return pass return fullPath
def capture_image_size_w_all_option(self, file_name, ww, hh): ### Change Viewport rs.CurrentView("Top") rs.ViewDisplayMode("Top", 'Rendered') ### Capture query = "-ViewCaptureToFile W={} H={} S=1 D=_No R=_No A=_No T=_Yes {}" \ .format(ww, hh, file_name) rs.Command(query) ### Delete ALL self.delete_all() ### Change Viewport rs.CurrentView("Perspective")
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 create_capture(self, view, file): command = self.get_command(file) if self.zoom_extents: rs.ZoomExtents(view, False) rs.CurrentView(view) rs.Command(command, False)
def set_mesh_objects(self): sys.path.append(self.pluginPath) object_ids = rs.ObjectsByType(32 | 16, True) objects_visible = True view = rs.CurrentView() for obj in object_ids: rs.HideObjects(obj)
def __init__(self): self.view = rs.CurrentView() self.detail = rs.CurrentDetail(self.view) self.is_in_detail = None self.polysrfs = None self.drawing = None self.dwg_crvs = None self.paper_dwg = None self.block_name = None
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 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 main(): max_flrs = 9999 # maximum number of folders to open max_fils = 9999 # maximum number of files to open in each folder folder_tic = time.clock() fdr_cnt = 0 for root, dirs, files in walklevel(src_path): print("{}\t {}".format(fdr_cnt, root)) #if (root == src_path): continue fil_cnt = 0 for full_filename in files: filename, file_extension = os.path.splitext(full_filename) if file_extension != ".3dm": continue file_tic = time.clock() filepath = os.path.join(root, full_filename) rs.DocumentModified(False) rs.Command('_-Open {} _Enter'.format('"' + filepath + '"')) pln = rs.PlaneFromPoints((100, 0, 0), (0, 100, 0), (100, 100, 0)) rs.AddRectangle(pln, 100, 100) set_active_view("Origin_SW_ISO") view = rs.CurrentView() set_disp_mode(disp_mode) rs.Redraw() """ rs.ViewProjection(view,2) rs.ViewCameraTarget(view,cam_pos,tar_pos) rs.ViewCameraLens(view,lens_len) rs.ZoomExtents(view) #rs.ViewCameraLens(view,25) """ capture_view_antialias( os.path.join(tar_path, "{}.png".format(filename)), image_size) t = round(time.clock() - file_tic) print(filename + "\ttime:\t" + str(t)) fil_cnt += 1 if fil_cnt > max_fils: break fdr_cnt += 1 if fdr_cnt > max_flrs: break t = round(time.clock() - folder_tic) print("TOTAL\ttime:\t" + str(t))
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 view(camera=False, target=False, lens=False): if camera and target and lens: if not rh.IsViewMaximized("Perspective"): rh.MaximizeRestoreView("Perspective") rh.ViewProjection("Perspective", 2) rh.ViewCameraLens("Perspective", lens) rh.ViewCameraTarget("Perspective", Pt(camera), Pt(target)) rh.ViewDisplayMode("Perspective", "Shaded") vs.Redraw() return (camera, target, lens) else: rh.CurrentView("Perspective") camera, target, lens = rh.ViewCamera(), rh.ViewTarget( ), rh.ViewCameraLens() return (fromPt(camera), fromPt(target), lens)
def extr_bld_flr(): # Extrude all buildings according to NUM_FLOORS attribute multiplied by FLOOR_HEIGHT constant # get all objects in building layer building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"]) for building_obj in building_objs: if rs.IsCurve(building_obj) and rs.IsCurveClosed( building_obj ) and rs.CurveArea(building_obj)[0] > MIN_BUILDING_AREA_SQM: crv = rs.coercecurve(building_obj) num_of_floors = rs.GetUserText(building_obj, "NUM_FLOORS") building_height = FLOOR_HEIGHT_M * int(num_of_floors) srf = rs.ExtrudeCurveStraight(crv, (0, 0, 0), (0, 0, building_height)) rs.CapPlanarHoles(srf) rs.ViewDisplayMode(rs.CurrentView(), "Shaded")
def GetMap(): socket.setdefaulttimeout(10) filename = 'c:\\map.jpg' # you migth hve to change this path street = rs.GetString('Street') city = rs.GetString('City') country = rs.GetString('Country') zoom = rs.GetInteger('Zoom', 17, 1, 19) rs.UnitSystem(4, True) url = 'http://nominatim.openstreetmap.org/search?q=' + street + ',' + city + ',' + country + '&format=xml' rs.CurrentView('Top') try: xml = urllib.urlopen(url).read() except: print 'http://nominatim.openstreetmap.org produced an error' return temp = xml[xml.find("lat=") + 5:-1] lat = temp[0:temp.find("'")] temp = xml[xml.find("lon=") + 5:-1] lng = temp[0:temp.find("'")] print 'Latitude, Longitude: ' + lat + ", " + lng picture_page = 'http://osm-tah-cache.firefishy.com/MapOf/?lat=' + lat + '&long=' + lng + '&z=' + str( zoom) + '&w=1000&h=1000&format=jpeg' opener1 = urllib2.build_opener() try: page1 = opener1.open(picture_page) my_picture = page1.read() except: print 'http://osm-tah-cache.firefishy.com produced an error' return try: fout = open(filename, 'wb') fout.write(my_picture) fout.close() except: print 'writing of ' + path + ' produced an error' return res = 40075017 * math.cos( float(lat) / 180 * math.pi) / (256 * 2**zoom) * 1000 rs.Command('_-BackgroundBitmap Remove _Enter', False) rs.Command( '_-BackgroundBitmap ' + filename + ' ' + str(-res / 2) + ',' + str(-res / 2) + ',0 ' + str(res / 2) + ',' + str(res / 2) + ',0 _Enter', True) rs.Command('_-BackgroundBitmap Grayscale=No _Enter', False) rs.Command( '_-EarthAnchorPoint Latitude ' + lat + ' Longitude ' + lng + ' _Enter _Enter _Enter _Enter _Enter', False)
def ringSizes(): fingerSizes = {} fingerChoice = [] startSize = 72 endSize = 91 start = 14.5 h_incr = 0.2 for x in range(startSize, endSize): start += h_incr fingerSizes[str(chr(x))] = round(start, 2) start += h_incr fingerSizes[str(chr(x)) + chr(189)] = round(start, 2) fingerChoice.append(chr(x)) fingerChoice.append(chr(x) + chr(189)) #debug #print(fingerSizes) #listbox if fingerChoice: try: result = rd.ListBox(sorted(fingerChoice), "Select FingerSize", "Finger Size", "N") if result: myLayer = "Finger Size: " + result rs.AddLayer(myLayer, col.Brown) rs.CurrentLayer(myLayer) rs.CurrentView("front") rs.Command("_Circle 0 " + str(fingerSizes.get(result))) rs.CurrentLayer("Default") rs.LayerLocked(myLayer, True) rs.ClearCommandHistory() if rs.IsLayer(myLayer): print("\nFinger rail added!") else: print("\nOperation Aborted") except: print "Aborted by user"
def draw_model_paperspace(): #go to paperspace, then go to view and enter its modelspace view = rs.CurrentView() #rs.CurrentDetail() detail = rs.CurrentDetail(view) type = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.ViewportType if type != Rhino.Display.ViewportType.DetailViewport: print "Please enter detail modelspace" return print type #get model objs = rs.GetObjects("Select objects to draw", rs.filter.polysurface) rs.SelectObjects(objs) #make 2d, as current view rs.Command("!-_Make2D DrawingLayout=CurrentView _enter _enter") dwg_crvs = rs.LastCreatedObjects() #cut and paste into view window (paperspace) origin = [0, 0, 0] rs.AddBlock(dwg_crvs, origin, name=view, delete_input=True) #leave detail view and insert block rs.CurrentDetail(view, detail=view) insert_pt = [17, 11, 0] obj = rs.InsertBlock(view, insert_pt) #orient 2pt with 3d scaling enabled r1 = rs.GetPoint("Pick reference corner 1") r2 = rs.GetPoint("Pick reference corner 2") t1 = rs.GetPoint("Pick target corner 1") t2 = rs.GetPoint("Pick target corner 2") ref_pts = [r1, r2] target_pts = [t1, t2] rs.OrientObject(obj, ref_pts, target_pts, flags=2) print "Script Finished" return
MIN_BUILDING_AREA_SQM): crv = rs.coercecurve(building_obj) if rs.PointInPlanarClosedCurve(related_building_pnt, crv): xy_found = True for attr_label, attr_val in zip(attribute_labels_list, attributes_row): rs.SetUserText(building_obj, attr_label, attr_val) if not xy_found: rs.SelectObject(building_obj) print(x_val, y_val, z_val) print(out_loop_counter) ########################################################################################################################################## # Extrude all buildings according to NUM_FLOORS attribute multiplied by FLOOR_HEIGHT constant # get all objects in building layer building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"]) for building_obj in building_objs: if rs.IsCurve(building_obj) and rs.IsCurveClosed( building_obj ) and rs.CurveArea(building_obj)[0] > MIN_BUILDING_AREA_SQM: crv = rs.coercecurve(building_obj) num_of_floors = rs.GetUserText(building_obj, "NUM_FLOORS") if num_of_floors == None: pass # building_height = FLOOR_HEIGHT_M * num_of_floors srf = rs.ExtrudeCurveStraight(crv, (0, 0, 0), (0, 0, 20)) rs.CapPlanarHoles(srf) rs.ViewDisplayMode(rs.CurrentView(), "Shaded")
rs.ZoomExtents() create_view_image( conf['part_img_right'] % (stepnumeral, partkind), w_l, h_l) # rs.HideObject(part) for partkind, vvv in vv.items(): rs.ShowObject(vvv) rs.LayerVisible(step, False) # utils.show_children(subsystem) utils.show_step_children(subsystem) utils.show_blocks() utils.show_subsystems() rs.ZoomExtents() clear_img_dir() # get CAD file structure structure = utils.get_structure() utils.structure_to_file(structure) # set up view rs.CurrentView(rs.ViewNames()[-1]) # typ "Perspective" on 4th tab view_to_restore = rs.CurrentView() size = rs.ViewSize() view_aspect = size[0] / float(size[1]) # generate images generate_step_images(structure) generate_part_images(structure) # restore view rs.CurrentView(view_to_restore)
import rhinoscriptsyntax as rs layername = rs.CurrentLayer() viewname = rs.CurrentView() folder = 'E:\\2015\\2015053.00\\5-Model\\ISOPLAN' layername = layername.replace(" ", "_") layername = layername.replace(":", "_") layername = layername.replace("/", "-") viewname = viewname.replace(" ", "_") filepath = folder + '\\' + layername + "-" + viewname + ".png\" " imagewidth = str(4000) imageheight = str(int(4000*0.6)) rscommand = ("-ViewCaptureToFile "+ ' "' + filepath + " Width=" + imagewidth + " Height=" + imageheight + " d=yes r=no a=no enter") print(rscommand) rs.Command(rscommand)
def do_render(fname, cfg): rs.CurrentView(cfg['view'].ActiveViewportID) rs.Command("_-Render") rs.Command('_-SaveRenderWindowAs "{}"'.format( os.path.join(cfg['pth_save_rndr'], "{}.png".format(fname)))) rs.Command("_-CloseRenderWindow")
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 viewCapture(fileName, directory, viewNames, image_width, image_height, dispModeStr, keepAspectRatio, transparent): fullPaths = [] 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) viewSize = System.Drawing.Size(int(image_w), int(image_h)) pic = rc.Display.RhinoView.CaptureToBitmap(viewtoCapture, viewSize) if transparent == True: if sc.doc.Views.ActiveView.ActiveViewport.DisplayMode.EnglishName == 'Rendered': rhBackColor = sc.doc.Views.Document.RenderSettings.BackgroundColorTop else: rhBackColor = rc.ApplicationSettings.AppearanceSettings.ViewportBackgroundColor pic.MakeTransparent(rhBackColor) fullPath = os.path.join(directory, fileName + '_' + viewName + '.png') try: System.Drawing.Bitmap.Save(pic, fullPath) except: try: fullPath = os.path.join(directory, fileName + '_' + viewName + '_1.png') System.Drawing.Bitmap.Save(pic, fullPath) except: print "Failed!" return pass fullPaths.append(fullPath) return fullPaths
def wangqiao(): l = 8000 f = 2000 m = 5 n = 12 # circle center and radius xn = l / (2 * m) r = (f**2 + (l / 2)**2) / (2 * f) ctrs = [] rads = [] # from top circle to devide circle for i in range(m): x = xn * (i + 1) z = math.sqrt(r**2 - x**2) - (r - f) ctrs.append([0, 0, z]) rads.append(x) # create guide circle pts = [] ptss = [] rs.CurrentView("top") rs.AddLayer("guide") rs.CurrentLayer("guide") for i in range(m): cir = rs.AddCircle(ctrs[i], rads[i]) pts = rs.DivideCurve(cir, n) ptss.append(pts) # vertical direction rs.AddLayer("hdir", (0, 255, 0)) rs.CurrentLayer("hdir") toppt = [0, 0, f] for i in range(n): rs.AddLine(toppt, ptss[0][i]) for i in range(m - 1): for j in range(n): rs.AddLine(ptss[i][j], ptss[i + 1][j]) # horizonal direction rs.AddLayer("vdir", (0, 0, 255)) rs.CurrentLayer("vdir") for i in range(m): for j in range(n - 1): rs.AddLine(ptss[i][j], ptss[i][j + 1]) rs.AddLine(ptss[i][n - 1], ptss[i][0]) # add shell rs.AddLayer("plane", (255, 0, 0)) rs.CurrentLayer("plane") for i in range(n - 1): rs.AddSrfPt([(ptss[0][i]), (ptss[0][i + 1]), (0, 0, f)]) rs.AddSrfPt([(ptss[0][n - 1]), (ptss[0][0]), (0, 0, f)]) for i in range(m - 1): for j in range(n - 1): rs.AddSrfPt([(ptss[i][j]), (ptss[i + 1][j]), (ptss[i + 1][j + 1]), (ptss[i][j + 1])]) rs.AddSrfPt([(ptss[i][n - 1]), (ptss[i + 1][n - 1]), (ptss[i + 1][0]), (ptss[i][0])]) # delete guide layer rs.PurgeLayer("guide")
def __init__(self, outputUnits, dynamicSHDGroup_1, dynamicSHDGroup_2, RhinoViewsName, adaptiveZone, dgp_imageSize, onlyRunGlareAnalysis): if len(outputUnits) != 0 and outputUnits[0] != None: self.outputUnits = outputUnits else: self.outputUnits = [2] self.onlyAnnualGlare = onlyRunGlareAnalysis self.runAnnualGlare = False validViews = [] if RhinoViewsName != []: for viewName in RhinoViewsName: # check viewes if viewName in rs.ViewNames(): validViews.append(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: validViews.append(rs.RestoreNamedView(viewName)) else: warning = viewName + " is not a valid Rhino view name in this document." ghenv.Component.AddRuntimeMessage( gh.GH_RuntimeMessageLevel.Warning, warning) # change back to Grasshopper sc.doc = ghdoc viewName = rs.CurrentView(viewName, True) self.RhinoViewsName = validViews if self.RhinoViewsName != []: self.runAnnualGlare = True if adaptiveZone == None: adaptiveZone = False self.adaptiveZone = adaptiveZone if not dgp_imageSize: dgp_imageSize = 250 self.dgp_imageSize = dgp_imageSize if dynamicSHDGroup_1 == None and dynamicSHDGroup_2 == None: class dynamicSHDRecipe(object): def __init__(self, type=1, name="no_blind"): self.type = type self.name = name self.DShdR = [dynamicSHDRecipe(type=1, name="no_blind")] else: self.DShdR = [] shadingGroupNames = [] if dynamicSHDGroup_1 != None: self.DShdR.append(dynamicSHDGroup_1) shadingGroupNames.append(dynamicSHDGroup_1.name) if dynamicSHDGroup_2 != None: self.DShdR.append(dynamicSHDGroup_2) shadingGroupNames.append(dynamicSHDGroup_2.name) if len(shadingGroupNames ) == 2 and shadingGroupNames[0] == shadingGroupNames[1]: msg = "Shading group names cannot be the same. Change the names and try again." # Number of ill files self.numOfIll = 1 for shadingRecipe in self.DShdR: if shadingRecipe.name == "no_blind": pass elif shadingRecipe.name == "conceptual_dynamic_shading": self.numOfIll += 1 else: # advanced dynamic shading self.numOfIll += len(shadingRecipe.shadingStates) - 1 print "number of ill files = " + str(self.numOfIll)
def transonic_airliner( Propulsion=1, # 1 - twin, 2 - quad EngineDia=2.9, # Diameter of engine intake highlight FuselageScaling=[55.902, 55.902, 55.902], # [x,y,z] scale factors NoseLengthRatio=0.182, # Proportion of forward tapering section of the fuselage TailLengthRatio=0.293, # Proportion of aft tapering section of the fuselage WingScaleFactor=44.56, WingChordFactor=1.0, Topology=1, # Topology = 2 will yield a box wing airliner - use with caution, this is just for demo purposes. SpanStation1=0.31, # Inboard engine at this span station SpanStation2=0.625, # Outboard engine at this span station (ignored if Propulsion=1) EngineCtrBelowLE=0.3558, # Engine below leading edge, normalised by the length of the nacelle - range: [0.35,0.5] EngineCtrFwdOfLE=0.9837, # Engine forward of leading edge, normalised by the length of the nacelle - range: [0.85,1.5] Scarf_deg=3): # Engine scarf angle # Build fuselage geometry rs.EnableRedraw(False) try: FuselageOMLSurf, SternPoint = fuselage_oml.FuselageOML( NoseLengthRatio, TailLengthRatio, Scaling=FuselageScaling, NoseCoordinates=[0, 0, 0], CylindricalMidSection=False, SimplificationReqd=False) except: print "Fuselage fitting failed - stopping." return FuselageHeight = FuselageScaling[2] * 0.105 FuselageLength = FuselageScaling[0] FuselageWidth = FuselageScaling[1] * 0.106 rs.Redraw() if FuselageOMLSurf is None: print "Failed to fit fuselage surface, stopping." return FSurf = rs.CopyObject(FuselageOMLSurf) # Position of the apex of the wing if FuselageHeight < 8.0: WingApex = [0.1748 * FuselageLength, 0, -0.0523 * FuselageHeight] #787:[9.77,0,-0.307] else: WingApex = [0.1748 * FuselageLength, 0, -0.1 * FuselageHeight] #787:[9.77,0,-0.307] # Set up the wing object, including the list of user-defined functions that # describe the spanwise variations of sweep, dihedral, etc. LooseSurf = 1 if Topology == 1: SegmentNo = 10 Wing = liftingsurface.LiftingSurface(WingApex, ta.mySweepAngleFunctionAirliner, ta.myDihedralFunctionAirliner, ta.myTwistFunctionAirliner, ta.myChordFunctionAirliner, ta.myAirfoilFunctionAirliner, LooseSurf, SegmentNo, TipRequired=True) elif Topology == 2: SegmentNo = 101 Wing = liftingsurface.LiftingSurface(WingApex, ta.mySweepAngleFunctionAirliner, bw.myDihedralFunctionBoxWing, ta.myTwistFunctionAirliner, ta.myChordFunctionAirliner, ta.myAirfoilFunctionAirliner, LooseSurf, SegmentNo, TipRequired=True) # Instantiate the wing object and add it to the document rs.EnableRedraw(False) WingSurf, ActualSemiSpan, LSP_area, RootChord, AR, WingTip = Wing.GenerateLiftingSurface( WingChordFactor, WingScaleFactor) rs.Redraw() if Topology == 1: # Add wing to body fairing WTBFXCentre = WingApex[ 0] + RootChord / 2.0 + RootChord * 0.1297 # 787: 23.8 if FuselageHeight < 8.0: WTBFZ = RootChord * 0.009 #787: 0.2 WTBFheight = 0.1212 * RootChord #787:2.7 WTBFwidth = 1.08 * FuselageWidth else: WTBFZ = WingApex[2] + 0.005 * RootChord WTBFheight = 0.09 * RootChord WTBFwidth = 1.15 * FuselageWidth WTBFlength = 1.167 * RootChord #787:26 WTBFXStern = WTBFXCentre + WTBFlength / 2.0 CommS = "_Ellipsoid %3.2f,0,%3.2f %3.2f,0,%3.2f %3.2f,%3.2f,%3.2f %3.2f,0,%3.2f " % ( WTBFXCentre, WTBFZ, WTBFXStern, WTBFZ, 0.5 * (WTBFXCentre + WTBFXStern), 0.5 * WTBFwidth, WTBFZ, 0.5 * (WTBFXCentre + WTBFXStern), WTBFheight) rs.EnableRedraw(False) rs.CurrentView("Perspective") rs.Command(CommS) LO = rs.LastCreatedObjects() WTBF = LO[0] rs.Redraw() # Trim wing inboard section CutCirc = rs.AddCircle3Pt((0, WTBFwidth / 4, -45), (0, WTBFwidth / 4, 45), (90, WTBFwidth / 4, 0)) CutCircDisk = rs.AddPlanarSrf(CutCirc) CutDisk = CutCircDisk[0] rs.ReverseSurface(CutDisk, 1) rs.TrimBrep(WingSurf, CutDisk) elif Topology == 2: # Overlapping wing tips CutCirc = rs.AddCircle3Pt((0, 0, -45), (0, 0, 45), (90, 0, 0)) CutCircDisk = rs.AddPlanarSrf(CutCirc) CutDisk = CutCircDisk[0] rs.ReverseSurface(CutDisk, 1) rs.TrimBrep(WingSurf, CutDisk) # Engine installation (nacelle and pylon) if Propulsion == 1: # Twin, wing mounted SpanStation = SpanStation1 NacelleLength = 1.95 * EngineDia rs.EnableRedraw(False) EngineSection, Chord = act.CutSect(WingSurf, SpanStation) CEP = rs.CurveEndPoint(Chord) EngineStbd, PylonStbd = engine.TurbofanNacelle( EngineSection, Chord, CentreLocation=[ CEP.X - EngineCtrFwdOfLE * NacelleLength, CEP.Y, CEP.Z - EngineCtrBelowLE * NacelleLength ], ScarfAngle=Scarf_deg, HighlightRadius=EngineDia / 2.0, MeanNacelleLength=NacelleLength) rs.Redraw() elif Propulsion == 2: # Quad, wing-mounted NacelleLength = 1.95 * EngineDia rs.EnableRedraw(False) EngineSection, Chord = act.CutSect(WingSurf, SpanStation1) CEP = rs.CurveEndPoint(Chord) EngineStbd1, PylonStbd1 = engine.TurbofanNacelle( EngineSection, Chord, CentreLocation=[ CEP.X - EngineCtrFwdOfLE * NacelleLength, CEP.Y, CEP.Z - EngineCtrBelowLE * NacelleLength ], ScarfAngle=Scarf_deg, HighlightRadius=EngineDia / 2.0, MeanNacelleLength=NacelleLength) rs.DeleteObjects([EngineSection, Chord]) EngineSection, Chord = act.CutSect(WingSurf, SpanStation2) CEP = rs.CurveEndPoint(Chord) EngineStbd2, PylonStbd2 = engine.TurbofanNacelle( EngineSection, Chord, CentreLocation=[ CEP.X - EngineCtrFwdOfLE * NacelleLength, CEP.Y, CEP.Z - EngineCtrBelowLE * NacelleLength ], ScarfAngle=Scarf_deg, HighlightRadius=EngineDia / 2.0, MeanNacelleLength=NacelleLength) rs.Redraw() # Script for generating and positioning the fin rs.EnableRedraw(False) # Position of the apex of the fin P = [0.6524 * FuselageLength, 0.003, FuselageHeight * 0.384] #P = [36.47,0.003,2.254]55.902 RotVec = rs.VectorCreate([1, 0, 0], [0, 0, 0]) LooseSurf = 1 SegmentNo = 200 Fin = liftingsurface.LiftingSurface(P, tail.mySweepAngleFunctionFin, tail.myDihedralFunctionFin, tail.myTwistFunctionFin, tail.myChordFunctionFin, tail.myAirfoilFunctionFin, LooseSurf, SegmentNo) ChordFactor = 1.01 #787:1.01 if Topology == 1: ScaleFactor = WingScaleFactor / 2.032 #787:21.93 elif Topology == 2: ScaleFactor = WingScaleFactor / 3.5 FinSurf, FinActualSemiSpan, FinArea, FinRootChord, FinAR, FinTip = Fin.GenerateLiftingSurface( ChordFactor, ScaleFactor) FinSurf = rs.RotateObject(FinSurf, P, 90, axis=RotVec) FinTip = rs.RotateObject(FinTip, P, 90, axis=RotVec) if Topology == 1: # Tailplane P = [0.7692 * FuselageLength, 0.000, FuselageHeight * 0.29] RotVec = rs.VectorCreate([1, 0, 0], [0, 0, 0]) LooseSurf = 1 SegmentNo = 100 TP = liftingsurface.LiftingSurface(P, tail.mySweepAngleFunctionTP, tail.myDihedralFunctionTP, tail.myTwistFunctionTP, tail.myChordFunctionTP, tail.myAirfoilFunctionTP, LooseSurf, SegmentNo) ChordFactor = 1.01 ScaleFactor = 0.388 * WingScaleFactor #787:17.3 TPSurf, TPActualSemiSpan, TPArea, TPRootChord, TPAR, TPTip = TP.GenerateLiftingSurface( ChordFactor, ScaleFactor) rs.EnableRedraw(True) rs.DeleteObjects([EngineSection, Chord]) try: rs.DeleteObjects([CutCirc]) except: pass try: rs.DeleteObjects([CutCircDisk]) except: pass # Windows # Cockpit windows: rs.EnableRedraw(False) CockpitWindowTop = 0.305 * FuselageHeight CWC1s, CWC2s, CWC3s, CWC4s = fuselage_oml.CockpitWindowContours( Height=CockpitWindowTop, Depth=6) FuselageOMLSurf, Win1 = rs.SplitBrep(FuselageOMLSurf, CWC1s, delete_input=True) FuselageOMLSurf, Win2 = rs.SplitBrep(FuselageOMLSurf, CWC2s, delete_input=True) FuselageOMLSurf, Win3 = rs.SplitBrep(FuselageOMLSurf, CWC3s, delete_input=True) FuselageOMLSurf, Win4 = rs.SplitBrep(FuselageOMLSurf, CWC4s, delete_input=True) rs.DeleteObjects([CWC1s, CWC2s, CWC3s, CWC4s]) (Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) = act.ObjectsExtents([Win1, Win2, Win3, Win4]) CockpitBulkheadX = Xmax CockpitWallPlane = rs.PlaneFromPoints([CockpitBulkheadX, -15, -15], [CockpitBulkheadX, 15, -15], [CockpitBulkheadX, -15, 15]) CockpitWall = rs.AddPlaneSurface(CockpitWallPlane, 30, 30) if 'WTBF' in locals(): rs.TrimBrep(WTBF, CockpitWall) rs.DeleteObject(CockpitWall) # Window lines WIN = [1] NOWIN = [0] # A typical window pattern (including emergency exit windows) WinVec = WIN + 2 * NOWIN + 9 * WIN + 3 * NOWIN + WIN + NOWIN + 24 * WIN + 2 * NOWIN + WIN + NOWIN + 14 * WIN + 2 * NOWIN + WIN + 20 * WIN + 2 * NOWIN + WIN + NOWIN + 20 * WIN if FuselageHeight < 8.0: # Single deck WindowLineHeight = 0.3555 * FuselageHeight WinX = 0.1157 * FuselageLength WindowPitch = 0.609 WinInd = -1 while WinX < 0.75 * FuselageLength: WinInd = WinInd + 1 if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX: WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow( FuselageOMLSurf, WinX, WindowLineHeight) act.AssignMaterial(WinStbd, "Plexiglass") act.AssignMaterial(WinPort, "Plexiglass") WinX = WinX + WindowPitch else: # Fuselage big enough to accommodate two decks # Lower deck WindowLineHeight = 0.17 * FuselageHeight #0.166 WinX = 0.1 * FuselageLength #0.112 WindowPitch = 0.609 WinInd = 0 while WinX < 0.757 * FuselageLength: WinInd = WinInd + 1 if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX: WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow( FuselageOMLSurf, WinX, WindowLineHeight) act.AssignMaterial(WinStbd, "Plexiglass") act.AssignMaterial(WinPort, "Plexiglass") WinX = WinX + WindowPitch # Upper deck WindowLineHeight = 0.49 * FuselageHeight WinX = 0.174 * FuselageLength #0.184 WinInd = 0 while WinX < 0.757 * FuselageLength: WinInd = WinInd + 1 if WinVec[WinInd] == 1 and WinX > CockpitBulkheadX: WinStbd, WinPort, FuselageOMLSurf = fuselage_oml.MakeWindow( FuselageOMLSurf, WinX, WindowLineHeight) act.AssignMaterial(WinStbd, "Plexiglass") act.AssignMaterial(WinPort, "Plexiglass") WinX = WinX + WindowPitch rs.Redraw() act.AssignMaterial(FuselageOMLSurf, "White_composite_external") act.AssignMaterial(WingSurf, "White_composite_external") try: act.AssignMaterial(TPSurf, "ShinyBARedMetal") except: pass act.AssignMaterial(FinSurf, "ShinyBARedMetal") act.AssignMaterial(Win1, "Plexiglass") act.AssignMaterial(Win2, "Plexiglass") act.AssignMaterial(Win3, "Plexiglass") act.AssignMaterial(Win4, "Plexiglass") # Mirror the geometry as required act.MirrorObjectXZ(WingSurf) act.MirrorObjectXZ(WingTip) try: act.MirrorObjectXZ(TPSurf) act.MirrorObjectXZ(TPTip) except: pass if Propulsion == 1: for ObjId in EngineStbd: act.MirrorObjectXZ(ObjId) act.MirrorObjectXZ(PylonStbd) elif Propulsion == 2: for ObjId in EngineStbd1: act.MirrorObjectXZ(ObjId) act.MirrorObjectXZ(PylonStbd1) for ObjId in EngineStbd2: act.MirrorObjectXZ(ObjId) act.MirrorObjectXZ(PylonStbd2) rs.DeleteObject(FSurf) rs.Redraw()
def distFromCamera(target): camPos = rs.ViewCamera(rs.CurrentView()) dist = rs.Distance(camPos, target) print "Distance from camera is " + str(dist)
# Project points to bottom surface btm_surface = [bottom_surface] # Create a list with one single element bottom_pts = rs.ProjectPointToSurface(rndm_cull_points, btm_surface, (0,0,-1)) # Project points to top surface top_surface = [top_surface] # Create a list with one single element top_pts = rs.ProjectPointToSurface(rndm_cull_points, top_surface, (0,0,1)) # Planes on the bottom bottom_planes = [] for i in bottom_pts: view = rs.CurrentView() planes = rs.CreatePlane(i, (1,0,0), (0,1,0)) bottom_planes.append(planes) # Rotate planes on ZAxis rotated_planes = [] for i in bottom_planes: plane = rs.ViewCPlane() rndm_angle = random.randrange(-5, 5) rotated_z = rs.RotatePlane(i, rndm_angle, planes.ZAxis) # Tilt control tilt = random.randrange(-5, 5) * max_tilt rotated_x = rs.RotatePlane(rotated_z, tilt, planes.XAxis) rotated_planes.append(rotated_x)
number=10, minimum=2, maximum=100) #vis_res = 5 vis_ste = obj_dep / vis_res #Calculate the starting point for the clipping plane pla_org = -crd_o pla_org[1] = pla_org[1] + (vis_ste / 2) pla_pos = pla_org #Transform the width of the object into a 3D point pnt_ste = (-obj_wid, 0, 0) #Prepare the view for the axonometric view captures rs.CurrentView(view='Perspective') rs.ObjectsByGroup('obj_all', select=True) rs.ZoomSelected() rs.UnselectAllObjects() for i in range(img_zoo): rs.Command('Zoom Out') #Main loop taking the axonometry shots on each iteration for i in range(vis_res + 2): #Clipping plane pla_obj = rs.AddClippingPlane(rs.WorldZXPlane(), obj_wid, obj_hei, views='Perspective') rs.ObjectLayer(pla_obj, 'lay_axo_pla')
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 lengqiuta(): # (x/a)**2-(z - zz[3] / b)**2=1 a = 46000 b = 110269 # no.4 is the neck, that is [3] # z space z = [26212, 21259, 17815, 15649, 13900, 12725, 11911, 11386, 11103, 11040, 11192, 11572] # segment n = 32 # get z coordinate zz = [] for i in range(len(z)): zz.append(sum(z[i:len(z)])) zz.append(0) # get x coordinate x = [] for i in range(len(zz)): x1 = a * math.sqrt(1 + ((zz[i] - zz[3]) / b) **2) x.append(x1) rs.CurrentView("top") # add guide circle and points rs.AddLayer("guide") rs.CurrentLayer("guide") epts = [] opts = [] ptss = [] for i in range(len(zz)): if (i % 2) == 1: # even number circle: 0 2 4 6 8 10 12 cir = rs.AddCircle([0, 0, zz[i]], x[i]) epts = rs.DivideCurve(cir, 2 * n) for j in range(len(epts)): if (j % 2) == 0: ptss.append(list(epts[j])) elif (i % 2) == 0: # odd number circle: 1 3 5 7 9 11 cir = rs.AddCircle([0, 0, zz[i]], x[i]) opts = rs.DivideCurve(cir, 2 * n) for j in range(len(opts)): if (j % 2) == 1: ptss.append(list(opts[j])) # vertical members rs.AddLayer("hbar", (0, 255 ,0)) rs.CurrentLayer("hbar") i = 0 while (i < (len(zz) * n)): if i in range((n - 1), len(zz) * n, n): rs.AddLine(ptss[i], ptss[i - n + 1]) else: rs.AddLine(ptss[i], ptss[i + 1]) i = i + 1 # vertical members rs.AddLayer("vbar", (0, 0, 255)) rs.CurrentLayer("vbar") for i in range(n): for j in range(0, (len(zz) - 1), 2): #0, 2, 4, 6, 8, 10, 12 t = n * j + i rs.AddLine(ptss[t], ptss [t + n]) if t == (n * (j + 1) - 1): rs.AddLine(ptss[t], ptss[t + 1]) else: rs.AddLine(ptss[t], ptss[t + n + 1]) for i in range(n): for j in range(1, (len(zz)), 2): #1, 3, 5, 7, 9, 11 t = n * j + i rs.AddLine(ptss[t], ptss[t + n]) if t == n * j: rs.AddLine(ptss[t], ptss[t + 2 * n - 1]) else: rs.AddLine(ptss[t], ptss[t + n - 1]) # add plane rs.AddLayer("plane", (255, 0, 0)) rs.CurrentLayer("plane") for j in range(0, len(zz) - 1, 2): for i in range(j * n, j * n + n - 1, 1): rs.AddSrfPt([(ptss[i + 1]), (ptss[i]), (ptss[n + i + 1])]) rs.AddSrfPt([(ptss[j * n]), (ptss[j * n + n - 1]), (ptss[j * n + n])]) for j in range(0, len(zz) - 1, 2): for i in range(j * n + n, j * n + 2 * n - 1, 1): rs.AddSrfPt([(ptss[i]), (ptss[i + 1]), (ptss[i - n])]) rs.AddSrfPt([(ptss[j * n + 2 * n - 1]), (ptss[j * n + n]), (ptss[j * n + n - 1])]) for j in range(0, len(zz) - 1, 2): for i in range(j * n + 2 * n, j * n + 3 * n -1, 1): rs.AddSrfPt([(ptss[i]), (ptss[i + 1]), (ptss[i - n + 1])]) rs.AddSrfPt([(ptss[j * n + 3 * n -1]), (ptss[j * n + 2 * n]), (ptss[j * n + n])]) for j in range(0, len(zz) - 1, 2): for i in range(j * n + n, j * n + 2 * n - 1, 1): rs.AddSrfPt([(ptss[i + 1]), (ptss[i]), (ptss[i + n])]) rs.AddSrfPt([(ptss[j * n + n]), (ptss[j * n + 2 * n -1]), (ptss[j * n + 3 * n - 1])]) # delete guide layer rs.PurgeLayer("guide")